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
3af31179a23314712f67e45c79f928cad4c29ce6
2,205
hxx
C++
include/rtkMultiplyByVectorImageFilter.hxx
vlibertiaux/RTK
0965dfe680e7993141898af13425ae2afb98d319
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
include/rtkMultiplyByVectorImageFilter.hxx
vlibertiaux/RTK
0965dfe680e7993141898af13425ae2afb98d319
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
include/rtkMultiplyByVectorImageFilter.hxx
vlibertiaux/RTK
0965dfe680e7993141898af13425ae2afb98d319
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef rtkMultiplyByVectorImageFilter_hxx #define rtkMultiplyByVectorImageFilter_hxx #include "rtkMultiplyByVectorImageFilter.h" #include "itkImageRegionIterator.h" namespace rtk { // // Constructor // template <class TInputImage> MultiplyByVectorImageFilter<TInputImage>::MultiplyByVectorImageFilter() {} template <class TInputImage> void MultiplyByVectorImageFilter<TInputImage>::SetVector(std::vector<float> vect) { m_Vector = vect; this->Modified(); } template <class TInputImage> void MultiplyByVectorImageFilter<TInputImage>::DynamicThreadedGenerateData( const typename TInputImage::RegionType & outputRegionForThread) { int Dimension = this->GetInput()->GetImageDimension(); for (unsigned int i = outputRegionForThread.GetIndex()[Dimension - 1]; i < outputRegionForThread.GetSize()[Dimension - 1] + outputRegionForThread.GetIndex()[Dimension - 1]; i++) { typename TInputImage::RegionType SubRegion; SubRegion = outputRegionForThread; SubRegion.SetSize(Dimension - 1, 1); SubRegion.SetIndex(Dimension - 1, i); itk::ImageRegionIterator<TInputImage> outputIterator(this->GetOutput(), SubRegion); itk::ImageRegionConstIterator<TInputImage> inputIterator(this->GetInput(), SubRegion); while (!inputIterator.IsAtEnd()) { outputIterator.Set(inputIterator.Get() * m_Vector[i]); ++outputIterator; ++inputIterator; } } } } // namespace rtk #endif
30.205479
108
0.687075
[ "vector" ]
3af401e47fbaef78b414cf83f0da2df09f0c989e
2,843
cpp
C++
SigkSens/src/sensors/bmp280/bmp280.cpp
ba58smith/SigkSens
4105f5ff4e26b3ccd426e7d236a1c3b50318c265
[ "Apache-2.0" ]
42
2018-01-20T21:48:17.000Z
2021-11-23T22:59:48.000Z
SigkSens/src/sensors/bmp280/bmp280.cpp
ba58smith/SigkSens
4105f5ff4e26b3ccd426e7d236a1c3b50318c265
[ "Apache-2.0" ]
58
2018-02-18T19:02:47.000Z
2021-05-12T12:20:43.000Z
SigkSens/src/sensors/bmp280/bmp280.cpp
ba58smith/SigkSens
4105f5ff4e26b3ccd426e7d236a1c3b50318c265
[ "Apache-2.0" ]
13
2018-01-21T20:52:04.000Z
2021-02-20T21:54:06.000Z
#ifdef ESP8266 extern "C" { #include "user_interface.h" } #endif #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BMP280.h> #include "../../../config.h" #include "bmp280.h" BMP280SensorInfo::BMP280SensorInfo(String addr) { strcpy(address, addr.c_str()); signalKPath[0] = ""; signalKPath[1] = ""; attrName[0] = "tempK"; attrName[1] = "Pa"; type = SensorType::bmp280; valueJson[0] = "null"; valueJson[1] = "null"; offset[0] = 0; offset[1] = 0; scale[0] = 1; scale[1] = 1; isUpdated = false; } BMP280SensorInfo::BMP280SensorInfo( String addr, String path1, String path2, float offset0, float offset1, float scale0, float scale1) { strcpy(address, addr.c_str()); signalKPath[0] = path1; signalKPath[1] = path2; attrName[0] = "tempK"; attrName[1] = "Pa"; type = SensorType::bmp280; valueJson[0] = "null"; valueJson[1] = "null"; offset[0] = offset0; offset[1] = offset1; scale[0] = scale0; scale[1] = scale1; isUpdated = false; } BMP280SensorInfo *BMP280SensorInfo::fromJson(JsonObject &jsonSens) { return new BMP280SensorInfo( jsonSens["address"], jsonSens["attrs"][0]["signalKPath"], jsonSens["attrs"][1]["signalKPath"], jsonSens["attrs"][0]["offset"], jsonSens["attrs"][1]["offset"], jsonSens["attrs"][0]["scale"], jsonSens["attrs"][1]["scale"] ); } void BMP280SensorInfo::toJson(JsonObject &jsonSens) { jsonSens["address"] = address; jsonSens["type"] = (int)SensorType::bmp280; JsonArray& jsonAttrs = jsonSens.createNestedArray("attrs"); for (int x=0 ; x < MAX_SENSOR_ATTRIBUTES ; x++) { if (strcmp(attrName[x].c_str(), "") == 0 ) { break; //no more attributes } JsonObject& attr = jsonAttrs.createNestedObject(); attr["name"] = attrName[x]; attr["signalKPath"] = signalKPath[x]; attr["offset"] = offset[x]; attr["scale"] = scale[x]; attr["value"] = valueJson[x]; } } // sensor object Adafruit_BMP280 bmp; //Running values. (running value to reduce noise with exponential filter) float valueTempK = 0; float valuePa = 0; uint16_t readBMPDelay = 25; // forward declarations void readBMP280(); void updateBMP280(); void setupBMP280() { // this calls Wire.begin() again, but that shouldn't // do any harm. Hopefully. bmp.begin(); app.onRepeat(SLOW_LOOP_DELAY, readBMP280); } void readBMP280() { float Pa; float tempK; Pa = bmp.readPressure(); tempK = bmp.readTemperature() + 273.15; valueTempK = ((0.2*tempK) + (0.8*valueTempK)); valuePa = ((0.05*Pa) + (0.95*valuePa)); updateBMP280(); } void updateBMP280() { sensorStorage[(int)SensorType::bmp280].forEach([&](SensorInfo* si) { si->valueJson[0] = (valueTempK * si->scale[0] ) + si->offset[0]; si->valueJson[1] = (valuePa * si->scale[1] ) + si->offset[1]; si->isUpdated = true; }); }
23.691667
104
0.641576
[ "object" ]
3af5f4ebbc9b3bb384d03e438c3b4fab80ded9a6
12,453
cc
C++
test/graph_test.cc
olivermichel/plexum
618acfc05aa2db447f3eafc5c43b5298a58c81f5
[ "MIT" ]
2
2018-11-19T13:46:23.000Z
2019-12-09T09:38:10.000Z
test/graph_test.cc
olivermichel/plexum
618acfc05aa2db447f3eafc5c43b5298a58c81f5
[ "MIT" ]
null
null
null
test/graph_test.cc
olivermichel/plexum
618acfc05aa2db447f3eafc5c43b5298a58c81f5
[ "MIT" ]
null
null
null
#include <catch.h> #include <plexum/graph.h> class V { public: V() = delete; V(unsigned long i) : i(i) { } unsigned long i; }; class E { public: E() = delete; E(unsigned long i, double weight) : i(i), weight(weight) { } unsigned long i; double weight; }; TEST_CASE("graph vertices and edges", "[Graph]") { plexum::Graph<int, int> g1; REQUIRE(typeid(g1) == typeid(plexum::Graph<int,int>)); SECTION("graphs are empty upon construction") { REQUIRE(g1.vertices.count() == 0); REQUIRE(g1.edges.count() == 0); } SECTION("vertices can be added") { g1.vertices.add(1); g1.vertices.add(2); REQUIRE(g1.vertices.has_index(0)); REQUIRE(g1.vertices.has_index(1)); REQUIRE(!(g1.vertices.has_index(2))); REQUIRE(g1.vertices.count() == 2); } SECTION("vertices can be connected through edges") { g1.vertices.add(1); g1.vertices.add(2); g1.edges.add(g1.vertices[0], g1.vertices[1], 1); REQUIRE(g1.edges.count() == 1); } SECTION("edge iterators hold iterators to connected vertices") { auto a = g1.vertices.add(1); auto b = g1.vertices.add(2); auto e = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); REQUIRE(e.from() == a); REQUIRE(e.to() == b); REQUIRE(e.from().id() == 0); REQUIRE(e.to().id() == 1); } SECTION("vertices and edges can be accessed through sequential indices") { g1.vertices.add(1); g1.vertices.add(2); g1.vertices.add(3); REQUIRE_NOTHROW(g1.vertices[2]); REQUIRE_THROWS(g1.vertices[3]); REQUIRE_THROWS(g1.vertices[42]); g1.edges.add(g1.vertices[0], g1.vertices[1], 1); g1.edges.add(g1.vertices[1], g1.vertices[2], 2); REQUIRE_NOTHROW(g1.edges[0]); REQUIRE_NOTHROW(g1.edges[1]); REQUIRE_THROWS(g1.edges[42]); REQUIRE_THROWS(g1.edges[2]); } SECTION("edges can be accessed through a vertex pair") { g1.vertices.add(1); g1.vertices.add(2); g1.vertices.add(3); g1.edges.add(g1.vertices[0], g1.vertices[1], 1); g1.edges.add(g1.vertices[1], g1.vertices[2], 2); REQUIRE(*(g1.edges.between(g1.vertices[0], g1.vertices[1])) == 1); REQUIRE(*(g1.edges.between(g1.vertices[1], g1.vertices[2])) == 2); REQUIRE(*(g1.edges.between(g1.vertices[1], g1.vertices[0])) == 1); REQUIRE(*(g1.edges.between(g1.vertices[2], g1.vertices[1])) == 2); REQUIRE_THROWS(g1.edges.between(g1.vertices[2], g1.vertices[0])); REQUIRE_THROWS(g1.edges.between(g1.vertices[0], g1.vertices[2])); } SECTION("vertex.neighbors() returns iterators to neighbor vertices") { auto v1 = g1.vertices.add(1); auto v2 = g1.vertices.add(2); auto v3 = g1.vertices.add(3); auto e1 = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); auto e2= g1.edges.add(g1.vertices[1], g1.vertices[2], 2); REQUIRE(v1.neighbors().size() == 1); REQUIRE(v2.neighbors().size() == 2); REQUIRE(v3.neighbors().size() == 1); REQUIRE(*(v1.neighbors()[0]) == *v2); REQUIRE(*(v2.neighbors()[0]) == *v1); REQUIRE(*(v2.neighbors()[1]) == *v3); REQUIRE(*(v3.neighbors()[0]) == *v2); } SECTION("vertex.edges() returns iterators to edges connected to respective vertex") { auto v1 = g1.vertices.add(1); auto v2 = g1.vertices.add(2); auto v3 = g1.vertices.add(3); auto e1 = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); auto e2 = g1.edges.add(g1.vertices[1], g1.vertices[0], 2); REQUIRE(v1.edges().size() == 2); REQUIRE(v2.edges().size() == 2); REQUIRE(v3.edges().size() == 0); REQUIRE(v1.edges()[0] == e1); REQUIRE(v1.edges()[1] == e2); REQUIRE(v2.edges()[0] == e1); REQUIRE(v2.edges()[1] == e2); } SECTION("vertices can be removed") { auto v1 = g1.vertices.add(1); auto v2 = g1.vertices.add(2); auto v3 = g1.vertices.add(3); auto e1 = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); auto e2= g1.edges.add(g1.vertices[1], g1.vertices[2], 2); REQUIRE_THROWS(g1.vertices.remove(v1)); g1.edges.remove(e1); REQUIRE_NOTHROW(g1.vertices.remove(v1)); REQUIRE_NOTHROW(g1.vertices.remove_with_edges(v2)); REQUIRE(g1.vertices.count() == 1); REQUIRE(g1.edges.count() == 0); } SECTION("edges can be removed") { auto v1 = g1.vertices.add(1); auto v2 = g1.vertices.add(2); auto e1 = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); REQUIRE(g1.edges.count() == 1); REQUIRE_NOTHROW(g1.edges.remove(g1.edges.between(v2, v1))); REQUIRE_THROWS(g1.edges.remove(g1.edges.between(v2, v1))); REQUIRE(g1.edges.count() == 0); } } TEST_CASE("internal id management", "[Graph]") { plexum::Graph<int, int> g; auto a = g.vertices.add(1); auto b = g.vertices.add(2); auto c = g.vertices.add(3); auto d = g.edges.add(a, b, 1); auto e = g.edges.add(b, c, 2); SECTION("vertices have monotonously increasing indices") { auto i = g.vertices.begin(); REQUIRE(i.id() == 0); i++; REQUIRE(i.id() == 1); i++; REQUIRE(i.id() == 2); i++; REQUIRE(i == g.vertices.end()); } SECTION("edges have monotonously increasing indices") { auto i = g.edges.begin(); REQUIRE(i.id() == 0); i++; REQUIRE(i.id() == 1); i++; REQUIRE(i == g.edges.end()); } SECTION("vertex indices remain consistent when removing vertices") { g.edges.remove(d); g.edges.remove(e); g.vertices.remove(b); auto i = g.vertices.begin(); REQUIRE(i.id() == 0); i++; REQUIRE(i.id() == 2); i++; REQUIRE(i == g.vertices.end()); } SECTION("vertex indices remain consistent when removing vertices") { g.edges.remove(d); auto i = g.edges.begin(); REQUIRE(i.id() == 1); i++; REQUIRE(i == g.edges.end()); } SECTION("when adding a new vertex the new index is MAX_INDEX + 1") { auto f = g.vertices.add(4); REQUIRE(f.id() == 3); } SECTION("when adding a new edge the new index is MAX_INDEX + 1") { auto f = g.edges.add(a, b, 3); REQUIRE(f.id() == 2); } } TEST_CASE("sub and super graphs", "[Graph]") { plexum::Graph<int, int> g1; plexum::Graph<int, int> g2; plexum::Graph<int, int> g3; SECTION("graph objects can be mapped onto each other") { REQUIRE(typeid(g1) == typeid(plexum::Graph<int,int>)); REQUIRE(typeid(g2) == typeid(plexum::Graph<int,int>)); REQUIRE(!g1.has_subgraphs()); REQUIRE(!g2.supergraph()); g1.map(&g2); REQUIRE(g1.has_subgraphs()); REQUIRE(g1.has_subgraph(&g2)); REQUIRE(g2.supergraph()); } SECTION("unmapping a not mapped graph throws an exception") { g1.map(&g3); REQUIRE_THROWS(g1.unmap(&g2)); REQUIRE_NOTHROW(g1.unmap(&g3)); } SECTION("unmapping a not mapped vertex throws an exception") { auto a = g1.vertices.add(1); auto b = g2.vertices.add(1); auto c = g3.vertices.add(1); g1.vertices[0].map(b); REQUIRE_THROWS(g1.vertices[0].unmap(c)); REQUIRE_NOTHROW(g1.vertices[0].unmap(b)); } SECTION("unmapping a not mapped edge throws an exception") { g1.vertices.add(1); g2.vertices.add(1); g3.vertices.add(1); g1.vertices.add(2); g2.vertices.add(2); g3.vertices.add(2); auto a = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); auto b = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); auto c = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); g1.edges[0].map_link(b); REQUIRE_THROWS(g1.edges[0].unmap(c)); REQUIRE_NOTHROW(g1.edges[0].unmap(b)); } SECTION("map and unmap graph vertices") { auto a = g1.vertices.add(1); auto b = g2.vertices.add(1); REQUIRE(!g1.vertices[0].has_subvertices()); REQUIRE(!g1.vertices[0].has_supervertex()); REQUIRE(!g2.vertices[0].has_subvertices()); REQUIRE(!g2.vertices[0].has_supervertex()); REQUIRE(g1.vertices[0].sub_vertices().empty()); REQUIRE(g1.vertices[0].super_vertex() == nullptr); REQUIRE(g2.vertices[0].sub_vertices().empty()); REQUIRE(g2.vertices[0].super_vertex() == nullptr); g1.vertices[0].map(g2.vertices[0]); REQUIRE(g1.vertices[0].has_subvertices()); REQUIRE(!g1.vertices[0].has_supervertex()); REQUIRE(g2.vertices[0].has_supervertex()); REQUIRE(!g2.vertices[0].has_subvertices()); REQUIRE(g1.vertices[0].sub_vertices()[0] == b._ptr()); REQUIRE(g1.vertices[0].super_vertex() == nullptr); REQUIRE(g2.vertices[0].sub_vertices().empty()); REQUIRE(g2.vertices[0].super_vertex() == a._ptr()); g1.vertices[0].unmap(g2.vertices[0]); REQUIRE(!g1.vertices[0].has_subvertices()); REQUIRE(!g1.vertices[0].has_supervertex()); REQUIRE(!g2.vertices[0].has_subvertices()); REQUIRE(!g2.vertices[0].has_supervertex()); REQUIRE(g1.vertices[0].sub_vertices().empty()); REQUIRE(g1.vertices[0].super_vertex() == nullptr); REQUIRE(g2.vertices[0].sub_vertices().empty()); REQUIRE(g2.vertices[0].super_vertex() == nullptr); g1.vertices[0].map(g2.vertices[0]); g2.vertices[0].unmap_from_super_vertex(); REQUIRE(!g1.vertices[0].has_subvertices()); REQUIRE(!g1.vertices[0].has_supervertex()); REQUIRE(!g2.vertices[0].has_subvertices()); REQUIRE(!g2.vertices[0].has_supervertex()); REQUIRE(g1.vertices[0].sub_vertices().empty()); REQUIRE(g1.vertices[0].super_vertex() == nullptr); REQUIRE(g2.vertices[0].sub_vertices().empty()); REQUIRE(g2.vertices[0].super_vertex() == nullptr); } SECTION("map and unmap graph edges") { g1.vertices.add(1); g1.vertices.add(2); g2.vertices.add(1); g2.vertices.add(2); auto a = g1.edges.add(g1.vertices[0], g1.vertices[1], 1); auto b = g2.edges.add(g2.vertices[0], g2.vertices[1], 1); REQUIRE(!g1.edges[0].has_subedges()); REQUIRE(!g1.edges[0].has_superedge()); REQUIRE(!g2.edges[0].has_subedges()); REQUIRE(!g2.edges[0].has_superedge()); REQUIRE(g1.edges[0].sub_edges().empty()); REQUIRE(g1.edges[0].super_edge().empty()); REQUIRE(g2.edges[0].sub_edges().empty()); REQUIRE(g2.edges[0].super_edge().empty()); g1.edges[0].map_link(g2.edges[0]); REQUIRE(g1.edges[0].has_subedges()); REQUIRE(!g1.edges[0].has_superedge()); REQUIRE(g2.edges[0].has_superedge()); REQUIRE(!g2.edges[0].has_subedges()); REQUIRE(g1.edges[0].sub_edges()[0] == b._ptr()); REQUIRE(g1.edges[0].super_edge().empty()); REQUIRE(g2.edges[0].sub_edges().empty()); REQUIRE(g2.edges[0].super_edge()[0] == a._ptr()); g1.edges[0].unmap(g2.edges[0]); REQUIRE(!g1.edges[0].has_subedges()); REQUIRE(!g1.edges[0].has_superedge()); REQUIRE(!g2.edges[0].has_subedges()); REQUIRE(!g2.edges[0].has_superedge()); REQUIRE(g1.edges[0].sub_edges().empty()); REQUIRE(g1.edges[0].super_edge().empty()); REQUIRE(g2.edges[0].sub_edges().empty()); REQUIRE(g2.edges[0].super_edge().empty()); g1.edges[0].map_link(g2.edges[0]); g2.edges[0].unmap_from_super_edge(); REQUIRE(!g1.edges[0].has_subedges()); REQUIRE(!g1.edges[0].has_superedge()); REQUIRE(!g2.edges[0].has_subedges()); REQUIRE(!g2.edges[0].has_superedge()); REQUIRE(g1.edges[0].sub_edges().empty()); REQUIRE(g1.edges[0].super_edge().empty()); REQUIRE(g2.edges[0].sub_edges().empty()); REQUIRE(g2.edges[0].super_edge().empty()); } } TEST_CASE("bfs", "[Graph]") { plexum::Graph<V, E> g; REQUIRE(typeid(g) == typeid(plexum::Graph<V,E>)); auto v1 = g.vertices.add(0); auto v2 = g.vertices.add(1); auto v3 = g.vertices.add(2); auto v4 = g.vertices.add(4); auto e1 = g.edges.add(v1, v2, {0, 1}); auto e2 = g.edges.add(v2, v3, {1, 2}); auto e3 = g.edges.add(v3, v1, {2, 2}); REQUIRE(g.vertices.count() == 4); REQUIRE(g.edges.count() == 3); SECTION("find an unconstrained BFS path") { std::vector<plexum::Graph<V, E>::edge_proxy::iterator> path; REQUIRE_NOTHROW(path = g.find_path(v1, v2)); REQUIRE(path.size() == 1); REQUIRE(path[0].from() == v1); REQUIRE(path[0].to() == v2); } SECTION("throw an exception if there is no unconstrained path") { std::vector<plexum::Graph<V, E>::edge_proxy::iterator> path; REQUIRE_THROWS(path = g.find_path(v1, v4)); } SECTION("finds a constrained BFS path") { std::vector<plexum::Graph<V, E>::edge_proxy::iterator> path; REQUIRE_NOTHROW(path = g.find_path(v1, v2, [](E* e) { return e->weight >= 1; })); REQUIRE(path.size() == 1); REQUIRE(path[0].from() == v1); REQUIRE(path[0].to() == v2); } SECTION("finds a constrained BFS path") { std::vector<plexum::Graph<V, E>::edge_proxy::iterator> path; REQUIRE_NOTHROW(path = g.find_path(v1, v2, [](E* e) { return e->weight >= 2; })); REQUIRE(path.size() == 2); REQUIRE(path[0].from() == v3); REQUIRE(path[0].to() == v1); REQUIRE(path[1].from() == v2); REQUIRE(path[1].to() == v3); } SECTION("throws an exception if there is no constrained path") { std::vector<plexum::Graph<V, E>::edge_proxy::iterator> path; REQUIRE_THROWS(path = g.find_path(v1, v3, [](E* e) { return e->weight >= 10; })); } }
26.838362
84
0.644985
[ "vector" ]
3afa8a82667b6d27b9f6975fed19fdc04a0897ce
15,592
cpp
C++
diffsim_torch3d/arcsim/src/mesh.cpp
priyasundaresan/kaolin
ddae34ba5f09bffc4368c29bc50491c5ece797d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
diffsim_torch3d/arcsim/src/mesh.cpp
priyasundaresan/kaolin
ddae34ba5f09bffc4368c29bc50491c5ece797d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
diffsim_torch3d/arcsim/src/mesh.cpp
priyasundaresan/kaolin
ddae34ba5f09bffc4368c29bc50491c5ece797d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* Copyright ©2013 The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial licensing opportunities. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include "mesh.hpp" #include "geometry.hpp" #include "util.hpp" #include <assert.h> #include <cstdlib> using namespace std; using torch::Tensor; template <typename T1, typename T2> void check (const T1 *p1, const T2 *p2, const vector<T2*> &v2) { if (p2 && find((T2*)p2, v2) == -1) { cout << p1 << "'s adjacent " << p2 << " is not accounted for" << endl; abort(); } } template <typename T1, typename T2> void not_null (const T1 *p1, const T2 *p2) { if (!p2) { cout << "adjacent to " << p1 << " is null " << p2 << endl; abort(); } } template <typename T1, typename T2> void not_any_null (const T1 *p1, T2 *const*p2, int n) { bool any_null = false; for (int i = 0; i < n; i++) if (!p2[i]) any_null = true; if (any_null) { cout << "adjacent to " << p1 << " one of these is null" << endl; for (int i = 0; i < n; i++) cout << p2[i] << endl; abort(); } } template <typename T1, typename T2> void not_all_null (const T1 *p1, T2 *const*p2, int n) { bool all_null = true; for (int i = 0; i < n; i++) if (p2[i]) all_null = false; if (all_null) { cout << "adjacent to " << p1 << " all of these are null" << endl; for (int i = 0; i < n; i++) cout << p2[i] << endl; abort(); } } bool check_that_pointers_are_sane (const Mesh &mesh) { for (int v = 0; v < mesh.verts.size(); v++) { const Vert *vert = mesh.verts[v]; not_null(vert, vert->node); check(vert, vert->node, mesh.nodes); if (find((Vert*)vert, vert->node->verts) == -1) { cout << "vert " << vert << "'s node " << vert->node << " doesn't contain it" << endl; abort(); } for (int i = 0; i < vert->adjf.size(); i++) check(vert, vert->adjf[i], mesh.faces); } for (int n = 0; n < mesh.nodes.size(); n++) { const Node *node = mesh.nodes[n]; for (int i = 0; i < node->verts.size(); i++) check(node, node->verts[i], mesh.verts); for (int i = 0; i < 2; i++) check(node, node->adje[i], mesh.edges); } for (int e = 0; e < mesh.edges.size(); e++) { const Edge *edge = mesh.edges[e]; for (int i = 0; i < 2; i++) check(edge, edge->n[i], mesh.nodes); not_any_null(edge, edge->n, 2); for (int i = 0; i < 2; i++) check(edge, edge->adjf[i], mesh.faces); not_all_null(edge, edge->adjf, 2); } for (int f = 0; f < mesh.faces.size(); f++) { const Face *face = mesh.faces[f]; for (int i = 0; i < 3; i++) check(face, face->v[i], mesh.verts); not_any_null(face, face->v, 3); for (int i = 0; i < 3; i++) check(face, face->adje[i], mesh.edges); not_any_null(face, face->adje, 3); } return true; } bool check_that_contents_are_sane (const Mesh &mesh) { // // TODO // for (int v = 0; v < mesh.verts.size(); v++) { // const Vert *vert = mesh.verts[v]; // if (!isfinite(norm2(vert->x + vert->v + vert->n) + vert->a)) { // cout << "Vertex " << name(vert) << " is " << vert->x << " " // << vert->v << " " << vert->n << " " << vert->a << endl; // return false; // } // } // for (int f = 0; f < mesh.faces.size(); f++) { // const Face *face = mesh.faces[f]; // if (!isfinite(norm2(face->n) + face->a)) { // cout << "Face " << name(face) << " is " << face->n << " " // << face->a << endl; // return false; // } // } return true; } // Material space data void compute_ms_data (Face* face) { face->Dm = torch::stack({face->v[1]->u - face->v[0]->u, face->v[2]->u - face->v[0]->u},1); face->a = det(face->Dm)/2; if ((face->a == ZERO).item<int>()) face->invDm = torch::zeros({2,2},TNOPT); else face->invDm = face->Dm.inverse(); } void compute_ms_data (Edge* edge) { edge->l = ZERO; for (int s = 0; s < 2; s++) if (edge->adjf[s]) edge->l = edge->l + norm(edge_vert(edge,s,0)->u - edge_vert(edge,s,1)->u); if (edge->adjf[0] && edge->adjf[1]) edge->l = edge->l / 2; if (!edge->adjf[0] || !edge->adjf[1]) return; edge->ldaa = edge->l/(edge->adjf[0]->a + edge->adjf[1]->a); Tensor du0 = edge_vert(edge, 0, 1)->u - edge_vert(edge, 0, 0)->u; Tensor du1 = edge_vert(edge, 1, 1)->u - edge_vert(edge, 1, 0)->u; edge->bias_angle = torch::stack({atan2(du0[1], du0[0]), atan2(du1[1], du1[0])})*(4/M_PI)-1; } void compute_ms_data (Vert* vert) { vert->a = ZERO; const vector<Face*> &adjfs = vert->adjf; for (int i = 0; i < adjfs.size(); i++) { Face const* face = adjfs[i]; vert->a = vert->a + face->a/3; } } void compute_ms_data (Node* node) { node->a = ZERO; for (int v = 0; v < node->verts.size(); v++) node->a = node->a + node->verts[v]->a; } void compute_ms_data (Mesh &mesh) { for (int f = 0; f < mesh.faces.size(); f++) compute_ms_data(mesh.faces[f]); for (int e = 0; e < mesh.edges.size(); e++) compute_ms_data(mesh.edges[e]); for (int v = 0; v < mesh.verts.size(); v++) compute_ms_data(mesh.verts[v]); for (int n = 0; n < mesh.nodes.size(); n++) compute_ms_data(mesh.nodes[n]); // now we need to recompute world-space data compute_ws_data(mesh); } // World-space data void compute_ws_data (Face* face) { const Tensor &x0 = face->v[0]->node->x, &x1 = face->v[1]->node->x, &x2 = face->v[2]->node->x; face->n = normalize(cross(x1-x0, x2-x0)); // Mat3x2 F = derivative(x0, x1, x2, face); // SVD<3,2> svd = singular_value_decomposition(F); // Mat3x2 Vt_ = 0; // for (int i = 0; i < 2; i++) // for (int j = 0; j < 2; j++) // Vt_(i,j) = svd.Vt(i,j); // face->R = svd.U*Vt_; // face->F = svd.Vt.t()*diag(svd.s)*svd.Vt; } void compute_ws_data (Edge *edge) { edge->theta = dihedral_angle<WS>(edge); } void compute_ws_data (Node* node) { node->n = ZERO3; for (int v = 0; v < node->verts.size(); v++) { const Vert *vert = node->verts[v]; const vector<Face*> &adjfs = vert->adjf; for (int i = 0; i < adjfs.size(); i++) { Face const* face = adjfs[i]; int j = find(vert, face->v), j1 = (j+1)%3, j2 = (j+2)%3; Tensor e1 = face->v[j1]->node->x - node->x, e2 = face->v[j2]->node->x - node->x; node->n = node->n + cross(e1,e2)/(2*norm2(e1)*norm2(e2));//face->n;// } } node->n = normalize(node->n); } void compute_ws_data (Mesh &mesh) { for (int f = 0; f < mesh.faces.size(); f++) compute_ws_data(mesh.faces[f]); if (mesh.isCloth) for (int e = 0; e < mesh.edges.size(); e++) compute_ws_data(mesh.edges[e]); for (int n = 0; n < mesh.nodes.size(); n++) compute_ws_data(mesh.nodes[n]); } // Mesh operations template <> const vector<Vert*> &get (const Mesh &mesh) {return mesh.verts;} template <> const vector<Node*> &get (const Mesh &mesh) {return mesh.nodes;} template <> const vector<Edge*> &get (const Mesh &mesh) {return mesh.edges;} template <> const vector<Face*> &get (const Mesh &mesh) {return mesh.faces;} Edge *get_edge (const Node *n0, const Node *n1) { for (int e = 0; e < n0->adje.size(); e++) { Edge *edge = n0->adje[e]; if (edge->n[0] == n1 || edge->n[1] == n1) return edge; } return NULL; } Vert *edge_vert (const Edge *edge, int side, int i) { Face *face = (Face*)edge->adjf[side]; if (!face) return NULL; for (int j = 0; j < 3; j++) if (face->v[j]->node == edge->n[i]) return face->v[j]; return NULL; } Vert *edge_opp_vert (const Edge *edge, int side) { Face *face = (Face*)edge->adjf[side]; if (!face) return NULL; for (int j = 0; j < 3; j++) if (face->v[j]->node == edge->n[side]) return face->v[PREV(j)]; return NULL; } void connect (Vert *vert, Node *node) { vert->node = node; include(vert, node->verts); } void Mesh::add (Vert *vert) { verts.push_back(vert); vert->node = NULL; vert->adjf.clear(); vert->index = verts.size()-1; } void Mesh::remove (Vert* vert) { if (!vert->adjf.empty()) { cout << "Error: can't delete vert " << vert << " as it still has " << vert->adjf.size() << " faces attached to it." << endl; return; } exclude(vert, verts); } void Mesh::add (Node *node) { nodes.push_back(node); node->preserve = false; node->index = nodes.size()-1; node->adje.clear(); for (int v = 0; v < node->verts.size(); v++) node->verts[v]->node = node; } void Mesh::remove (Node* node) { if (!node->adje.empty()) { cout << "Error: can't delete node " << node << " as it still has " << node->adje.size() << " edges attached to it." << endl; return; } exclude(node, nodes); } void Mesh::add (Edge *edge) { edges.push_back(edge); edge->adjf[0] = edge->adjf[1] = NULL; edge->index = edges.size()-1; include(edge, edge->n[0]->adje); include(edge, edge->n[1]->adje); } void Mesh::remove (Edge *edge) { if (edge->adjf[0] || edge->adjf[1]) { cout << "Error: can't delete edge " << edge << " as it still has a face attached to it." << endl; return; } exclude(edge, edges); exclude(edge, edge->n[0]->adje); exclude(edge, edge->n[1]->adje); } void add_edges_if_needed (Mesh &mesh, const Face *face) { for (int i = 0; i < 3; i++) { Node *n0 = face->v[i]->node, *n1 = face->v[NEXT(i)]->node; if (get_edge(n0, n1) == NULL) mesh.add(new Edge(n0, n1)); } } void Mesh::add (Face *face) { faces.push_back(face); face->index = faces.size()-1; // adjacency add_edges_if_needed(*this, face); for (int i = 0; i < 3; i++) { Vert *v0 = face->v[NEXT(i)], *v1 = face->v[PREV(i)]; include(face, v0->adjf); Edge *e = get_edge(v0->node, v1->node); face->adje[i] = e; int side = e->n[0]==v0->node ? 0 : 1; e->adjf[side] = face; } } void Mesh::remove (Face* face) { exclude(face, faces); // adjacency for (int i = 0; i < 3; i++) { Vert *v0 = face->v[NEXT(i)]; exclude(face, v0->adjf); Edge *e = face->adje[i]; int side = e->n[0]==v0->node ? 0 : 1; e->adjf[side] = NULL; } } void update_indices (Mesh &mesh) { for (int v = 0; v < mesh.verts.size(); v++) mesh.verts[v]->index = v; for (int f = 0; f < mesh.faces.size(); f++) mesh.faces[f]->index = f; for (int n = 0; n < mesh.nodes.size(); n++) mesh.nodes[n]->index = n; for (int e = 0; e < mesh.edges.size(); e++) mesh.edges[e]->index = e; } void mark_nodes_to_preserve (Mesh &mesh) { for (int n = 0; n < mesh.nodes.size(); n++) { Node *node = mesh.nodes[n]; if (is_seam_or_boundary(node) || node->label) node->preserve = true; } for (int e = 0; e < mesh.edges.size(); e++) { Edge *edge = mesh.edges[e]; if (edge->label) { edge->n[0]->preserve = true; edge->n[1]->preserve = true; } } } void apply_transformation_onto (const Mesh &start_state, Mesh &onto, const Transformation &tr) { for (int n = 0; n < onto.nodes.size(); n++) onto.nodes[n]->x = tr.apply(start_state.nodes[n]->x); compute_ws_data(onto); } void opt_apply_transformation_onto (const Mesh &start_state, Mesh &onto, const Transformation &tr) { for (int n = 0; n < onto.nodes.size(); n++) onto.nodes[n]->x = tr.apply(start_state.nodes[n]->x); } void apply_transformation (Mesh& mesh, const Transformation& tr) { apply_transformation_onto(mesh, mesh, tr); } void update_x0 (Mesh &mesh) { for (int n = 0; n < mesh.nodes.size(); n++) mesh.nodes[n]->x0 = mesh.nodes[n]->x; } Mesh deep_copy (const Mesh &mesh0) { Mesh mesh1; mesh1.isCloth = mesh0.isCloth; if (mesh0.dummy_node) { const Node *node0 = mesh0.dummy_node; mesh1.dummy_node = new Node(node0->x, node0->v, node0->label); } for (int v = 0; v < mesh0.verts.size(); v++) { const Vert *vert0 = mesh0.verts[v]; Vert *vert1 = new Vert(vert0->u, vert0->label); mesh1.add(vert1); } for (int n = 0; n < mesh0.nodes.size(); n++) { const Node *node0 = mesh0.nodes[n]; Node *node1 = new Node(node0->x, node0->v, node0->label); node1->preserve = node0->preserve; node1->verts.resize(node0->verts.size()); for (int v = 0; v < node0->verts.size(); v++) node1->verts[v] = mesh1.verts[node0->verts[v]->index]; mesh1.add(node1); } for (int e = 0; e < mesh0.edges.size(); e++) { const Edge *edge0 = mesh0.edges[e]; Edge *edge1 = new Edge(mesh1.nodes[edge0->n[0]->index], mesh1.nodes[edge0->n[1]->index], edge0->label); mesh1.add(edge1); } for (int f = 0; f < mesh0.faces.size(); f++) { const Face *face0 = mesh0.faces[f]; Face *face1 = new Face(mesh1.verts[face0->v[0]->index], mesh1.verts[face0->v[1]->index], mesh1.verts[face0->v[2]->index], face0->label); mesh1.add(face1); } compute_ms_data(mesh1); return mesh1; } void delete_mesh (Mesh &mesh) { for (int v = 0; v < mesh.verts.size(); v++) delete mesh.verts[v]; for (int n = 0; n < mesh.nodes.size(); n++) delete mesh.nodes[n]; for (int e = 0; e < mesh.edges.size(); e++) delete mesh.edges[e]; for (int f = 0; f < mesh.faces.size(); f++) delete mesh.faces[f]; if (mesh.dummy_node) delete mesh.dummy_node; mesh.verts.clear(); mesh.nodes.clear(); mesh.edges.clear(); mesh.faces.clear(); }
33.316239
95
0.532773
[ "mesh", "geometry", "vector" ]
3afd963b46f864a3f861784acb0861400246f5cf
1,495
cc
C++
cpp/hackranker/h25.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/hackranker/h25.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/hackranker/h25.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
/* * https://www.hackerrank.com/challenges/matrix-rotation-algo/problem */ #include <iostream> #include <vector> #include <string> #include <algorithm> #include <iomanip> #include <cstdlib> #include <cstdio> #include <map> #include <set> #include <deque> #include <queue> using namespace std; void matrixRotation(vector<vector<int>> matrix, int r) { int left = 0, right = matrix[0].size() -1, top = 0, bottom = matrix.size() -1 ; while (bottom > top && left < right) { int k = r % ( 2 * ((bottom - top) + (right - left))); queue<int> que; for (int c = left; c <= right; c++) { que.push(matrix[top][c]); } for (int row = top + 1; row <= bottom; row++) { que.push(matrix[row][right]); } for (int c = right - 1; c >= left; c--) { que.push(matrix[bottom][c]); } for (int row = bottom - 1; row > top; row--) { que.push(matrix[row][left]); } while (k) { que.push(que.front()); que.pop(); k--; } for (int c = left; c <= right; c++) { matrix[top][c] = que.front(); que.pop(); } for (int row = top + 1; row <= bottom; row++) { matrix[row][right] = que.front(); que.pop(); } for (int c = right - 1; c >= left; c--) { matrix[bottom][c] = que.front(); que.pop(); } for (int row = bottom - 1; row > top; row--) { matrix[row][left] = que.front(); que.pop(); } left += 1; right -= 1; bottom -= 1; top += 1; } for (auto vec : matrix) { for (auto k : vec) { cout << k << " "; } cout << endl; } }
21.056338
80
0.541806
[ "vector" ]
d700f80c2d765117d08f5c40b4cd817a10a7e502
1,491
hpp
C++
framework/renderer.hpp
Sabbelz/programmiersprachen-raytracer
7662ab6cbd389e90908db722a6aad418b7cc820b
[ "MIT" ]
null
null
null
framework/renderer.hpp
Sabbelz/programmiersprachen-raytracer
7662ab6cbd389e90908db722a6aad418b7cc820b
[ "MIT" ]
null
null
null
framework/renderer.hpp
Sabbelz/programmiersprachen-raytracer
7662ab6cbd389e90908db722a6aad418b7cc820b
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------- // Copyright : (C) 2014-2017 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #ifndef BUW_RENDERER_HPP #define BUW_RENDERER_HPP #include "scene.hpp" #include "color.hpp" #include "pixel.hpp" #include "ppmwriter.hpp" #include <string> #include <glm/glm.hpp> class Renderer { public: Renderer(unsigned w, unsigned h, std::string const& file, Scene const& scene); void render(); void write(Pixel const& p); Color calculate_light(hitpoint const& hit, std::shared_ptr<Light> light); Color calculate_color(hitpoint const& hit, int counter); Color calculate_ambiente(hitpoint const& hit); Color calculate_diffuse(hitpoint const& hit); Color calculate_specular(hitpoint const& hit); Color calculate_reflection(hitpoint const& hit, int max_depth); Color calculate_refraction(hitpoint const& hit, std::string prev_medium); Color tonemapping(Color const& clr); inline std::vector<Color> const& color_buffer() const { return color_buffer_; } private: Scene scene_; unsigned width_; unsigned height_; std::vector<Color> color_buffer_; std::string filename_; PpmWriter ppm_; }; Ray transformRay(Ray const& ray, glm::mat4 m); #endif // #ifndef BUW_RENDERER_HPP
28.132075
80
0.657948
[ "render", "vector" ]
d704594dc92b596dba1c823d6fb8b63b6a49e69d
1,036
cpp
C++
Public/Src/Sandbox/MacOs/Interop/Sandbox/Data/SandboxedPip.cpp
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
448
2018-11-07T21:00:58.000Z
2019-05-06T17:29:34.000Z
Public/Src/Sandbox/MacOs/Interop/Sandbox/Data/SandboxedPip.cpp
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
496
2019-05-06T21:38:22.000Z
2022-03-14T18:17:14.000Z
Public/Src/Sandbox/MacOs/Interop/Sandbox/Data/SandboxedPip.cpp
miniksa/BuildXL
4dc257a82a6126fe7516f15fa6f505c14c122ffb
[ "MIT" ]
88
2019-05-08T08:28:45.000Z
2022-03-24T23:43:21.000Z
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "SandboxedPip.hpp" #include "BuildXLException.hpp" #pragma mark SandboxedPip Implementation SandboxedPip::SandboxedPip(pid_t pid, const char *payload, size_t length) { log_debug("Initializing with pid (%d) from: %{public}s", pid, __FUNCTION__); payload_ = (char *) malloc(length); if (payload == NULL) { throw BuildXLException("Could not allocate memory for FAM payload storage!"); } memcpy(payload_, payload, length); fam_.init((BYTE*)payload_, length); if (fam_.HasErrors()) { std::string error= "FileAccessManifest parsing exception, error: "; throw BuildXLException(error.append(fam_.Error())); } processId_ = pid; processTreeCount_ = 1; } SandboxedPip::~SandboxedPip() { log_debug("Releasing pip object (%#llX) - freed from %{public}s", GetPipId(), __FUNCTION__); free(payload_); }
28
101
0.686293
[ "object" ]
d70601aaa7096e32fe8de1c6bc0e3799b2cf68ef
2,607
cc
C++
stapl_release/test/views/test_stl_view.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/test/views/test_stl_view.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/test/views/test_stl_view.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #include <iostream> #include <vector> #include <list> #include <stapl/algorithms/algorithm.hpp> #include <stapl/containers/array/array.hpp> #include <stapl/views/array_view.hpp> #include <stapl/views/list_view.hpp> #include <stapl/utility/do_once.hpp> #include "../test_report.hpp" using namespace stapl; struct equal_one { typedef size_t result_type; template<typename Ref> size_t operator()(Ref r) { return r == 1; } }; struct nested_mr { typedef size_t result_type; template<typename VectorRef> size_t operator()(VectorRef& vec_ref) { return map_reduce<skeletons::tags::no_coarsening>( equal_one(), stapl::plus<size_t>(), make_array_view(vec_ref)); } }; stapl::exit_code stapl_main(int argc, char* argv[]) { // Testing view over std:vector typedef std::vector<size_t> pa_t; typedef array_view<pa_t> view_t; typedef view_t::domain_type dom_t; pa_t pa1(100,1); view_t view1(pa1); size_t res = count(view1,size_t(1)); STAPL_TEST_REPORT(res == 100,"Testing std::vector [0..99]"); view_t view4(pa1,dom_t(10,89)); res = count(view4,size_t(1)); STAPL_TEST_REPORT(res == 80,"Testing std::vector [10..89]"); // Testing view over std:list typedef std::list<size_t> pb_t; typedef list_view<pb_t, dom1D<pb_t::iterator, seqDom<pb_t::iterator> > > viewb_t; typedef viewb_t::domain_type domb_t; pb_t pb1(100,1); viewb_t view1b(pb1, domb_t(pb1.begin(), --pb1.end())); res = count(view1b,size_t(1)); STAPL_TEST_REPORT(res == 100,"Testing std::list [0..99]"); pb_t::iterator low = pb1.begin(); pb_t::iterator upr = pb1.begin(); // pb_t::iterator is not a random iterator for (size_t i=0;i<10;++i) ++low; for (size_t i=0;i<60;++i) ++upr; viewb_t view4b(pb1,domb_t(low,upr)); res = count(view4b,size_t(1)); STAPL_TEST_REPORT(res == 51,"Testing std::list [10..60]"); // Testing view<proxy<vector<T>, A>> (non coarsened). array<pa_t> ct(10, pa_t(10, 1)); res = map_reduce<skeletons::tags::no_coarsening>( nested_mr(), stapl::plus<size_t>(), make_array_view(ct)); STAPL_TEST_REPORT(res == 100, "Testing view<proxy<vector<T>, A>> (non coarsened)"); return EXIT_SUCCESS; }
23.276786
74
0.677407
[ "vector" ]
d706c9defd602d7c04cec2c4d797b90df49635f6
1,819
cpp
C++
GameEntity.cpp
danielHPeters/fight-dude
812c65c093cff31e66b0c17c956bc9cbaf620ede
[ "MIT" ]
null
null
null
GameEntity.cpp
danielHPeters/fight-dude
812c65c093cff31e66b0c17c956bc9cbaf620ede
[ "MIT" ]
null
null
null
GameEntity.cpp
danielHPeters/fight-dude
812c65c093cff31e66b0c17c956bc9cbaf620ede
[ "MIT" ]
null
null
null
#include <utility> #include "GameEntity.h" namespace fightdude { /** * Constructor. * * @param id Entity id * @param createdAt Create timestamp * @param updatedAt Update timestamp * @param fileName Sprite filename */ GameEntity::GameEntity(std::string id, std::string fileName) : Entity(std::move(id)), fileName(std::move(fileName)), loaded(false) {} /** * Destructor. */ GameEntity::~GameEntity() = default; /** * Load the sprite of this game entity. */ void GameEntity::load() { loaded = texture.loadFromFile(fileName); if (loaded) { sprite.setTexture(texture); } } /** * Render method of the game entity. * * @param window Game window to render the game entity on */ void GameEntity::render(sf::RenderWindow &window) { if (loaded) { window.draw(sprite); } } /** * Update internal data like position, size etc. of this game entity. * * @param elapsedTime Time since last update */ void GameEntity::update(double elapsedTime) {} /** * Getter for the vector position of this game entity. * * @return Position of the entity or an empty vector if the sprite did not load */ sf::Vector2f GameEntity::getPosition() const { return loaded ? sprite.getPosition() : sf::Vector2f(); } /** * Getter for the sprite of the game entity. * * @return Sprite of the game entity */ sf::Sprite &GameEntity::getSprite() { return sprite; } /** * Checks if sprite asset has been loaded. * * @return True if the sprite has been successfully loaded. */ bool GameEntity::isLoaded() const { return loaded; } /** * Set position of the internal sprite. * Does nothing if sprite loading failed. * * @param position New position */ void GameEntity::setPosition(sf::Vector2f position) { if (loaded) { sprite.setPosition(position); } } } //namespace fightdude
20.438202
79
0.681693
[ "render", "vector" ]
d707d56088249de9832d9583b38f15fc4449b5dd
1,413
cpp
C++
Code/2_Arrange_Domain/peakDetail2D_pairFrag.cpp
Lan-lab/Chrom-Lasso-
3b1c7797bfdf0f7d3330339ace0929e8e2225a40
[ "MIT" ]
null
null
null
Code/2_Arrange_Domain/peakDetail2D_pairFrag.cpp
Lan-lab/Chrom-Lasso-
3b1c7797bfdf0f7d3330339ace0929e8e2225a40
[ "MIT" ]
null
null
null
Code/2_Arrange_Domain/peakDetail2D_pairFrag.cpp
Lan-lab/Chrom-Lasso-
3b1c7797bfdf0f7d3330339ace0929e8e2225a40
[ "MIT" ]
3
2020-10-15T09:15:46.000Z
2021-05-07T02:16:27.000Z
#ifndef PEAKDETAILPAIRFRAG2D_CPP #define PEAKDETAILPAIRFRAG2D_CPP #include "peakDetail2D_pairFrag.hpp" int peakDetail_pairFrag_2D::getSumLogProb(const map<int, double>& ranDisMap_local, map<int, map< int, vector<fragInfo_bothEndsMapped_withCuttingSite> > >& cuttingSiteFragMap_local, const double minProb_local, const double aveSiteFrag_local, const int binSize_local) { vector<fragInfo_bothEndsMapped_withCuttingSite>::const_iterator fragIt = frag_info.begin(), fragIt_end = frag_info.end(); for ( ; fragIt != fragIt_end; ++fragIt ) { map< int, vector<fragInfo_bothEndsMapped_withCuttingSite> >::const_iterator end1Site = cuttingSiteFragMap_local[fragIt->end1_chr].find(fragIt->end1_cuttingSite); double correctionCoeff = (end1Site->second.size()) * 1.0 / aveSiteFrag_local; double minProb_corrected = minProb_local * correctionCoeff; double logMinProb = log(minProb_corrected); if (fragIt->end1_chr == fragIt->end2_chr) { int dis = abs(fragIt->end2_cuttingSite - fragIt->end1_cuttingSite); int binIndex = dis / binSize_local; map<int, double>::const_iterator disProbIt = ranDisMap_local.find(binIndex); if (disProbIt != ranDisMap_local.end()) { sumLogProb += log((disProbIt->second)*correctionCoeff); } else { sumLogProb += logMinProb; } } else { sumLogProb += logMinProb; } } return 0; } #endif
32.113636
266
0.726822
[ "vector" ]
d70ead7c70defb5bfd09ef01959b7cda7518d45f
800
cpp
C++
src/modules/osg/generated_code/vector_less__float__greater_.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osg/generated_code/vector_less__float__greater_.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osg/generated_code/vector_less__float__greater_.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #include "boost/python.hpp" #include "indexing_suite/container_suite.hpp" #include "indexing_suite/vector.hpp" #include "wrap_osg.h" #include "vector_less__float__greater_.pypp.hpp" namespace bp = boost::python; void register_vector_less__float__greater__class(){ { //::std::vector< float > typedef bp::class_< std::vector< float > > vector_less__float__greater__exposer_t; vector_less__float__greater__exposer_t vector_less__float__greater__exposer = vector_less__float__greater__exposer_t( "vector_less__float__greater_" ); bp::scope vector_less__float__greater__scope( vector_less__float__greater__exposer ); vector_less__float__greater__exposer.def( bp::indexing::vector_suite< std::vector< float > >() ); } }
38.095238
159
0.7725
[ "vector" ]
d71049e218e1c76b2921d8a6b2707557c9ee929c
5,014
cpp
C++
src/SampleLoader.cpp
Zebreus/webmusictracker
c2e5f93d86017ef8556c494a538892018d50a4f6
[ "MIT" ]
null
null
null
src/SampleLoader.cpp
Zebreus/webmusictracker
c2e5f93d86017ef8556c494a538892018d50a4f6
[ "MIT" ]
null
null
null
src/SampleLoader.cpp
Zebreus/webmusictracker
c2e5f93d86017ef8556c494a538892018d50a4f6
[ "MIT" ]
null
null
null
#include "SampleLoader.hpp" SampleLoader::SampleLoader(){ EM_ASM( FS.mkdir('/samples'); FS.mount(IDBFS, {}, '/samples'); FS.syncfs(true, function (err) { // onerror }); ); std::thread t([this](){ std::cout << "thread function\n"; std::this_thread::sleep_for(1s); std::cout << "thread function\n"; this->loadAvailableSamples(); }); t.detach(); } void SampleLoader::drawWindow(){ ImGui::Begin("Sample Manager"); ImGui::Text("The sample manager manages and loads samples"); if (ImGui::Button("Load samples")){ loadSamples(); } if (ImGui::Button("Update available samples")){ loadAvailableSamples(); } ImGui::Text("Available samples"); ImGui::Columns(1, "mycolumns3", false); // 3-ways, no border ImGui::Separator(); for(const filesystem::path& sampleFile: availableSamples){ bool selected = sampleFile == *selectedSample; if (ImGui::Selectable(sampleFile.stem().c_str(), selected, ImGuiSelectableFlags_SpanAllColumns)) { if(selectedSample != nullptr){ delete selectedSample; } selectedSample = new filesystem::path(sampleFile); } ImGui::NextColumn(); } ImGui::Columns(1); ImGui::Separator(); if (ImGui::Button("Load sample")){ if(selectedSample != nullptr){ loadAvailableSample(*selectedSample); } } ImGui::End(); } void SampleLoader::loadSamples(){ EM_ASM( var input = document.createElement("input"); input.setAttribute("type", "file"); input.setAttribute("accept", "audio/*"); input.setAttribute("style", "display:none"); input.setAttribute("multiple", "true"); document.body.appendChild(input); input.click(); input.onchange = function(evt) { var files = evt.target.files; console.log(files); var audioCtx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 96000, }); //TODO better solution to close the audio context setTimeout(function(){ audioCtx.close(); }, 30000); for(file of files ){ var reader = new FileReader(); reader.onload = function() { console.log(file.name); console.log(reader.result); var filename = '/samples/' + file.name; audioCtx.decodeAudioData(reader.result, function(buffer){ //~ const source = audioCtx.createBufferSource(); //~ source.buffer = buffer; //~ source.connect(audioCtx.destination); //~ source.start(); var myAudioBuffer = buffer.getChannelData(0); var byteAudioBuffer = new Uint8Array(myAudioBuffer.buffer); console.log(filename); console.log(myAudioBuffer); console.log(byteAudioBuffer); //TODO decode audio FS.writeFile(filename, byteAudioBuffer); FS.syncfs(false, function (err) { // onerror }); }, function(e){ console.log("ERROR decoding audio"); } ); //TODO find a way to remove input after last file //input.parentNode.removeChild(input); }; reader.readAsArrayBuffer(file); } } //TODO find a way to remove input, when not used //input.parentNode.removeChild(input); ); } vector<filesystem::path> SampleLoader::getAvailableSamples(){ return availableSamples; } void SampleLoader::loadAvailableSamples(){ std::string path = "/samples"; vector<filesystem::path> ret; for (const auto & entry : filesystem::directory_iterator(path)){ ret.push_back(entry.path()); } availableSamples = ret; } vector<float> SampleLoader::loadAvailableSample(filesystem::path samplePath){ vector<float> sampleData; ifstream sampleFile( samplePath, ios::in | ios::binary); while( sampleFile.is_open() && !sampleFile.eof()){ float f; sampleFile.read((char*)&f, sizeof(f)); sampleData.push_back(f); } for(int i = 0; i<100;i++){ cout << sampleData[i] << endl; } return sampleData; }
35.062937
106
0.499801
[ "vector" ]
d7157478c3cfcd587b2dc0d46e60209644b78d4f
3,003
cpp
C++
labs/lab3/gradeStats.cpp
ToyVo/DataStucturesStout
285daddff31d44315b53816d67d92754ed341682
[ "MIT" ]
null
null
null
labs/lab3/gradeStats.cpp
ToyVo/DataStucturesStout
285daddff31d44315b53816d67d92754ed341682
[ "MIT" ]
null
null
null
labs/lab3/gradeStats.cpp
ToyVo/DataStucturesStout
285daddff31d44315b53816d67d92754ed341682
[ "MIT" ]
null
null
null
//Problem 2 //Collin Diekvoss #include <iostream> #include <fstream> #include <string> #include <vector> #include <cmath> using namespace std; void getData(ifstream& inputFile, vector<string>& roster, vector<double>& list); double findMean(vector<double> list); double findStdDev(vector<double> list); double maxScore(vector<double> list); void printSummary(vector<string> st, vector<double> list, double mean, double std, double max); int main() { // (1) two vectors: a vector of string named as students for storing students' names // a vector of double named as grades for storing students' scores vector<string> students; vector<double> grades; // (2) create ifstream object infile and use it to open a data file ifstream infile; infile.open("data.txt"); if(!infile) { cout<<"file not found"<<endl; return 1; } // (3) call function getData() // this function reads a data file and store the information into two vectors. getData(infile, students, grades); // (4) call three functions for statistics: // findMean(), findStdDev(), maxScore() double mean, std, max; mean = findMean(grades); std = findStdDev(grades); max = maxScore(grades); // (5) call function printSummary() printSummary(students, grades, mean, std, max); // (6) close the file infile.close(); return 0; } // implement each of the following functions: // getData(), findMean(), findStdDev(), maxScore(), printSummary() void getData(ifstream& inputFile, vector<string>& roster, vector<double>& list) { //variables to store the values read in string name; double grade; //read and push values while(inputFile >> name) { roster.push_back(name); inputFile >> grade; list.push_back(grade); } } //calculate average double findMean(vector<double> list) { double total = 0; for(int i = 0; i < list.size(); i++) { total += list[i]; } total = total / list.size(); return total; } //calculate std variation by adding up all values minus the average, square that //and then divide everything by n, and finally square root everything double findStdDev(vector<double> list) { double mean = findMean(list); double std = 0; for(int i = 0; i < list.size(); i++) { std += (list[i]-mean)*(list[i]-mean); } std = std / list.size(); std = sqrt(std); } //find the top score double maxScore(vector<double> list) { double max = 0; for(int i = 0; i < list.size(); i++) { if(list[i]>max) { max = list[i]; } } return max; } //print everything void printSummary(vector<string> st, vector<double> list, double mean, double std, double max) { cout << "Class Mean: " << mean << endl; cout << "Class Standard Deviation: " << std << endl; cout << "Highest Score: " << max << endl; cout << "Students with scores above mean: " << endl; for(int i = 0; i < list.size(); i++) { if(list[i] > mean) cout << st[i] << endl; } cout << "Student(s) with highest score: " << endl;; for(int i = 0; i < list.size(); i++) { if(list[i] == max) cout << st[i] << endl; } }
23.1
95
0.664669
[ "object", "vector" ]
d719a44f3767c2294956d460c87d6a151bfe86da
32,700
cpp
C++
libraries/model/test/src/CompilerTest.cpp
dashesy/ELL
b4a2b852fc0479d8f0854b1133ee324e14c66bf8
[ "MIT" ]
null
null
null
libraries/model/test/src/CompilerTest.cpp
dashesy/ELL
b4a2b852fc0479d8f0854b1133ee324e14c66bf8
[ "MIT" ]
null
null
null
libraries/model/test/src/CompilerTest.cpp
dashesy/ELL
b4a2b852fc0479d8f0854b1133ee324e14c66bf8
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: CompilerTest.cpp (compile_test) // Authors: Umesh Madan, Chuck Jacobs // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "CompilerTest.h" #include <model_testing/include/ModelTestUtilities.h> #include <model/include/CompilableNode.h> #include <model/include/InputNode.h> #include <model/include/IRCompiledMap.h> #include <model/include/IRMapCompiler.h> #include <model/include/Map.h> #include <model/include/Model.h> #include <nodes/include/AccumulatorNode.h> #include <nodes/include/ClockNode.h> #include <nodes/include/ConstantNode.h> #include <nodes/include/DelayNode.h> #include <nodes/include/DotProductNode.h> #include <nodes/include/ForestPredictorNode.h> #include <nodes/include/L2NormSquaredNode.h> #include <nodes/include/LinearPredictorNode.h> #include <nodes/include/MatrixVectorProductNode.h> #include <nodes/include/ProtoNNPredictorNode.h> #include <nodes/include/SinkNode.h> #include <nodes/include/SourceNode.h> #include <nodes/include/SquaredEuclideanDistanceNode.h> #include <nodes/include/SumNode.h> #include <emitters/include/EmitterException.h> #include <emitters/include/EmitterTypes.h> #include <emitters/include/IREmitter.h> #include <emitters/include/IRFunctionEmitter.h> #include <emitters/include/IRModuleEmitter.h> #include <emitters/include/ScalarVariable.h> #include <emitters/include/VectorVariable.h> #include <predictors/include/LinearPredictor.h> #include <predictors/include/ProtoNNPredictor.h> #include <utilities/include/Logger.h> #include <testing/include/testing.h> #include <algorithm> #include <iostream> #include <ostream> #include <string> #include <vector> using namespace ell; using namespace ell::logging; std::string outputBasePath = ""; void SetOutputPathBase(std::string path) { outputBasePath = path; } std::string OutputPath(std::string relPath) { return outputBasePath + relPath; } // // Helper functions for constructing example models/maps // model::Map MakeSimpleMap() { // make a model model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(3); const auto& sum = nodes::Sum(inputNode->output); return model::Map{ model, { { "input", inputNode } }, { { "output", sum } } }; } model::Map MakeForestMap() { // define some abbreviations using SplitAction = predictors::SimpleForestPredictor::SplitAction; using SplitRule = predictors::SingleElementThresholdPredictor; using EdgePredictorVector = std::vector<predictors::ConstantPredictor>; // build a forest predictors::SimpleForestPredictor forest; auto root = forest.Split(SplitAction{ forest.GetNewRootId(), SplitRule{ 0, 0.3 }, EdgePredictorVector{ -1.0, 1.0 } }); auto child1 = forest.Split(SplitAction{ forest.GetChildId(root, 0), SplitRule{ 1, 0.6 }, EdgePredictorVector{ -2.0, 2.0 } }); forest.Split(SplitAction{ forest.GetChildId(child1, 0), SplitRule{ 1, 0.4 }, EdgePredictorVector{ -2.1, 2.1 } }); forest.Split(SplitAction{ forest.GetChildId(child1, 1), SplitRule{ 1, 0.7 }, EdgePredictorVector{ -2.2, 2.2 } }); forest.Split(SplitAction{ forest.GetChildId(root, 1), SplitRule{ 2, 0.9 }, EdgePredictorVector{ -4.0, 4.0 } }); auto root2 = forest.Split(SplitAction{ forest.GetNewRootId(), SplitRule{ 0, 0.2 }, EdgePredictorVector{ -3.0, 3.0 } }); forest.Split(SplitAction{ forest.GetChildId(root2, 0), SplitRule{ 1, 0.21 }, EdgePredictorVector{ -3.1, 3.1 } }); forest.Split(SplitAction{ forest.GetChildId(root2, 1), SplitRule{ 1, 0.22 }, EdgePredictorVector{ -3.2, 3.2 } }); // build the model model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(3); auto forestNode = model.AddNode<nodes::SimpleForestPredictorNode>(inputNode->output, forest); return { model, { { "input", inputNode } }, { { "output", forestNode->output } } }; } // // Tests // void TestNodeMetadata() { model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(10); inputNode->GetMetadata().SetEntry("window_size", std::string("80")); auto outputNode = model.AddNode<model::OutputNode<double>>(inputNode->output); auto map = model::Map(model, { { "input", inputNode } }, { { "output", outputNode->output } }); model::MapCompilerOptions settings; settings.moduleName = "Model"; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); auto compiledMap = compiler.Compile(map); auto compiledFunction = compiledMap.GetJitter().GetFunction<char*(const char*)>("Model_GetMetadata"); char* result = compiledFunction("window_size"); testing::ProcessTest("Test compiled node metadata", testing::IsEqual(std::string(result), std::string("80"))); } void TestSimpleMap(bool optimize) { model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(3); // auto bufferNode = model.AddNode<model::OutputNode<double>>(inputNode->output); auto accumNode = model.AddNode<nodes::AccumulatorNode<double>>(inputNode->output); auto accumNode2 = model.AddNode<nodes::AccumulatorNode<double>>(accumNode->output); // auto outputNode = model.AddNode<model::OutputNode<double>>(accumNode->output); auto map = model::Map(model, { { "input", inputNode } }, { { "output", accumNode2->output } }); model::MapCompilerOptions settings; settings.compilerSettings.optimize = optimize; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); auto compiledMap = compiler.Compile(map); testing::ProcessTest("Testing IsValid of original map", testing::IsEqual(compiledMap.IsValid(), true)); // compare output std::vector<std::vector<double>> signal = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 3, 4, 5 }, { 2, 3, 2 }, { 1, 5, 3 }, { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 7, 4, 2 }, { 5, 2, 1 } }; VerifyCompiledOutput(map, compiledMap, signal, " map"); } void TestSqEuclideanDistanceMap() { model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(3); math::RowMatrix<double> m{ { 1.2, 1.1, 0.8 }, { 0.6, 0.9, 1.3 }, { 0.3, 1.0, 0.4 }, { -.4, 0.2, -.7 } }; auto sqEuclidDistNode = model.AddNode<nodes::SquaredEuclideanDistanceNode<double, math::MatrixLayout::rowMajor>>(inputNode->output, m); auto map = model::Map{ model, { { "input", inputNode } }, { { "output", sqEuclidDistNode->output } } }; model::MapCompilerOptions settings; settings.compilerSettings.optimize = true; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); auto compiledMap = compiler.Compile(map); testing::ProcessTest("Testing IsValid of original map", testing::IsEqual(compiledMap.IsValid(), true)); // compare output std::vector<std::vector<double>> signal = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 3, 4, 5 }, { 2, 3, 2 }, { 1, 5, 3 }, { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 7, 4, 2 }, { 5, 2, 1 } }; VerifyCompiledOutput(map, compiledMap, signal, " map"); } void TestProtoNNPredictorMap() { // the values of dim, gamma, and matrices come from the result of running protoNNTrainer with the following command line // protoNNTrainer -v --inputDataFilename Train-28x28_sparse.txt -dd 784 -sw 0.29 -sb 0.8 -sz 0.8 -pd 15 -l 10 -mp 5 --outputModelFilename mnist-94.model --evaluationFrequency 1 -plf L4 -ds 0.003921568627451 size_t dim = 784, projectedDim = 15, numPrototypes = 50, numLabels = 10; double gamma = 0.0733256; predictors::ProtoNNPredictor protonnPredictor(dim, projectedDim, numPrototypes, numLabels, gamma); // projectedDim * dim auto W = protonnPredictor.GetProjectionMatrix() = { #include "TestProtoNNPredictorMap_Projection.inc" }; // projectedDim * numPrototypes auto B = protonnPredictor.GetPrototypes() = { #include "TestProtoNNPredictorMap_Prototypes.inc" }; // numLabels * numPrototypes auto Z = protonnPredictor.GetLabelEmbeddings() = { #include "TestProtoNNPredictorMap_LabelEmbeddings.inc" }; // MNIST training data features std::vector<std::vector<double>> features = { #include "TestProtoNNPredictorMap_features.inc" }; std::vector<std::vector<int>> labels{ { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 } }; testing::IsEqual(protonnPredictor.GetProjectedDimension(), projectedDim); testing::IsEqual(protonnPredictor.GetNumPrototypes(), numPrototypes); testing::IsEqual(protonnPredictor.GetNumLabels(), numLabels); model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(dim); auto protonnPredictorNode = model.AddNode<nodes::ProtoNNPredictorNode>(inputNode->output, protonnPredictor); auto outputNode = model.AddNode<model::OutputNode<double>>(protonnPredictorNode->output); auto map = model::Map{ model, { { "input", inputNode } }, { { "output", outputNode->output } } }; model::MapCompilerOptions settings; settings.compilerSettings.optimize = false; settings.compilerSettings.includeDiagnosticInfo = true; settings.compilerSettings.inlineOperators = false; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); auto compiledMap = compiler.Compile(map); testing::ProcessTest("Testing IsValid of original map", testing::IsEqual(compiledMap.IsValid(), true)); for (unsigned i = 0; i < features.size(); ++i) { auto& input = features[i]; std::transform(input.begin(), input.end(), input.begin(), [](double d) { return d / 255; }); const auto& label = labels[i]; IsEqual(input.size(), dim); inputNode->SetInput(input); auto computeOutput = model.ComputeOutput(outputNode->output); testing::ProcessTest("ProtoNN: one hot indices are incorrect for computed and actual label", IsEqual(std::max_element(label.begin(), label.end()) - label.begin(), std::max_element(computeOutput.begin(), computeOutput.end()) - computeOutput.begin())); map.SetInputValue(0, input); auto refinedOutput = map.ComputeOutput<double>(0); testing::ProcessTest("ProtoNN: computed and refined output vectors don't match", IsEqual(computeOutput, refinedOutput, 1e-5)); compiledMap.SetInputValue(0, input); auto compiledOutput = compiledMap.ComputeOutput<double>(0); testing::ProcessTest("ProtoNN: refined and compiled output vectors don't match", IsEqual(refinedOutput, compiledOutput, 1e-5)); } } void TestCombineOutputMap() { model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(3); auto accumNode = model.AddNode<nodes::AccumulatorNode<double>>(inputNode->output); // combine inputNode and accumNode as a bigger vector of size 6 and output that. auto outputNode = model.AddNode<model::OutputNode<double>>(model::PortElements<double>{ inputNode->output, accumNode->output }); auto map = model::Map(model, { { "input", inputNode } }, { { "output", outputNode->output } }); model::MapCompilerOptions settings; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); auto compiledMap = compiler.Compile(map); testing::ProcessTest("Testing TestCombineOutputMap IsValid", testing::IsEqual(compiledMap.IsValid(), true)); std::vector<std::vector<double>> signal = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 3, 4, 5 }, { 2, 3, 2 }, { 1, 5, 3 }, { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 7, 4, 2 }, { 5, 2, 1 } }; std::vector<double> expected = { 5, 2, 1, 42, 48, 49 }; std::vector<double> result = VerifyCompiledOutput<double, double>(map, compiledMap, signal, "TestCombineOutputMap"); // compare final output double epsilon = 1e-5; bool ok = IsEqual(result, expected, epsilon); if (IsVerbose() || !ok) { std::cout << "result versus expected: " << std::endl; std::cout << " result: " << result << std::endl; std::cout << " expected: " << expected << std::endl; std::cout << " Largest difference: " << LargestDifference(result, expected) << std::endl; } testing::ProcessTest("TestCombineOutputMap matches expected result", ok); } void TestMultiOutputMap() { // Map with 2 OutputNodes model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(3); auto sumNode = model.AddNode<nodes::SumNode<double>>(inputNode->output); auto dotNode = model.AddNode<nodes::DotProductNode<double>>(inputNode->output, inputNode->output); auto outputNode = model.AddNode<model::OutputNode<double>>(model::PortElements<double>{ sumNode->output }); auto outputNode2 = model.AddNode<model::OutputNode<double>>(model::PortElements<double>{ dotNode->output }); auto map = model::Map(model, { { "input", inputNode } }, { { "output", outputNode->output }, { "output2", outputNode2->output } }); // can't compile multiple maps with outputs yet... //model::IRMapCompiler compiler; //auto compiledMap = compiler.Compile(map); //PrintIR(compiledMap); //// compare output //std::vector<std::vector<double>> signal = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 3, 4, 5 }, { 2, 3, 2 }, { 1, 5, 3 }, { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 7, 4, 2 }, { 5, 2, 1 } }; //auto result = VerifyCompiledOutput<double, double>(map, compiledMap, signal, "TestMultiOutputMap"); testing::ProcessTest("Testing TestMultiOutputMap clone and prune", map.GetModel().Size() == 5); } void TestCompiledMapMove() { model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(3); auto accumNode = model.AddNode<nodes::AccumulatorNode<double>>(inputNode->output); auto map = model::Map(model, { { "input", inputNode } }, { { "output", accumNode->output } }); model::IRMapCompiler compiler1; auto compiledMap1 = compiler1.Compile(map); PrintIR(compiledMap1); testing::ProcessTest("Testing IsValid of original map", testing::IsEqual(compiledMap1.IsValid(), true)); // compare output std::vector<std::vector<double>> signal = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 3, 4, 5 }, { 2, 3, 2 }, { 1, 5, 3 }, { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 7, 4, 2 }, { 5, 2, 1 } }; VerifyCompiledOutput(map, compiledMap1, signal, " original compiled map"); auto compiledMap2 = std::move(compiledMap1); testing::ProcessTest("Testing IsValid of moved-from map", testing::IsEqual(compiledMap1.IsValid(), false)); testing::ProcessTest("Testing IsValid of moved-to map", testing::IsEqual(compiledMap2.IsValid(), true)); // compare output VerifyCompiledOutput(map, compiledMap2, signal, " moved compiled map"); } typedef void (*MapPredictFunction)(void* context, double*, double*); void TestBinaryVector(bool expanded, bool runJit) { std::vector<double> data = { 5, 10, 15, 20 }; std::vector<double> data2 = { 4, 4, 4, 4 }; const int c_InputSize = data.size(); const std::string modelFunctionName = "TestBinaryVector"; model::Model model; auto inputNode1 = model.AddNode<model::InputNode<double>>(c_InputSize); const auto& c1 = nodes::Constant(model, data); const auto& c2 = nodes::Constant(model, data2); const auto& sum = nodes::Add(c1, inputNode1->output); const auto& product = nodes::Multiply(sum, c2); model::MapCompilerOptions settings; settings.compilerSettings.unrollLoops = expanded; settings.mapFunctionName = modelFunctionName; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); model::Map map{ model, { { "input", inputNode1 } }, { { "output", product } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); std::vector<double> testInput = { 1, 1, 1, 1 }; std::vector<double> testOutput(testInput.size()); PrintIR(compiledMap); PrintDiagnostics(compiledMap.GetModule().GetDiagnosticHandler()); if (runJit) { auto& jitter = compiledMap.GetJitter(); auto predict = reinterpret_cast<MapPredictFunction>(jitter.ResolveFunctionAddress(modelFunctionName)); predict(nullptr, &testInput[0], testOutput.data()); } else { auto mainFunction = compiledMap.GetModule().BeginMainDebugFunction(); emitters::IRFunctionCallArguments args(mainFunction); auto& emitter = compiledMap.GetModule().GetIREmitter(); args.Append(emitter.NullPointer(emitter.GetIRBuilder().getInt8Ty()->getPointerTo())); args.Append(compiledMap.GetModule().ConstantArray("c_data", testInput)); auto* pResult = args.AppendOutput(emitters::VariableType::Double, testInput.size()); mainFunction.Call(modelFunctionName, args); mainFunction.PrintForEach("%f,", pResult, testInput.size()); mainFunction.Return(); compiledMap.GetModule().EndFunction(); compiledMap.GetModule().WriteToFile(OutputPath(expanded ? "BinaryVector_E.asm" : "BinaryVector.asm")); } } void TestBinaryScalar() { std::vector<double> data = { 5 }; model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(1); const auto& c1 = nodes::Constant(model, data); const auto& sum = nodes::Add(c1, inputNode->output); model::MapCompilerOptions settings; settings.compilerSettings.optimize = true; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); model::Map map{ model, { { "input", inputNode } }, { { "output", sum } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); } void TestDotProduct(model::MapCompilerOptions& settings) { std::vector<double> data = { 5, 10, 15, 20 }; model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(4); const auto& c1 = nodes::Constant(model, data); const auto& dotProduct = nodes::DotProduct(c1, inputNode->output); model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); model::Map map{ model, { { "input", inputNode } }, { { "output", dotProduct } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); } void TestDotProduct() { model::MapCompilerOptions settings; settings.compilerSettings.unrollLoops = false; settings.compilerSettings.inlineOperators = true; TestDotProduct(settings); settings.compilerSettings.unrollLoops = true; settings.compilerSettings.inlineOperators = true; TestDotProduct(settings); settings.compilerSettings.unrollLoops = false; settings.compilerSettings.inlineOperators = false; TestDotProduct(settings); } void TestSimpleSum(bool expanded, bool optimized) { std::vector<double> data = { 5, 10, 15, 20 }; model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(4); const auto& sum = nodes::Sum(inputNode->output); model::MapCompilerOptions settings; settings.compilerSettings.unrollLoops = expanded; settings.compilerSettings.optimize = optimized; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); model::Map map{ model, { { "input", inputNode } }, { { "output", sum } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); PrintDiagnostics(compiledMap.GetModule().GetDiagnosticHandler()); } void TestSum(bool expanded, bool optimized) { std::vector<double> data = { 5, 10, 15, 20 }; model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(4); const auto& c1 = nodes::Constant(model, data); const auto& product = nodes::Multiply(c1, inputNode->output); const auto& sum = nodes::Sum(product); model::MapCompilerOptions settings; settings.compilerSettings.unrollLoops = expanded; settings.compilerSettings.optimize = optimized; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); model::Map map{ model, { { "input", inputNode } }, { { "output", sum } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); // Print out any diagnostic messages PrintDiagnostics(compiledMap.GetModule().GetDiagnosticHandler()); } void TestAccumulator(bool expanded) { std::vector<double> data = { 5, 10, 15, 20 }; model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(4); const auto& c1 = nodes::Constant(model, data); const auto& product = nodes::Multiply(c1, inputNode->output); const auto& accumulate = nodes::Accumulate(product); model::MapCompilerOptions settings; settings.compilerSettings.unrollLoops = expanded; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); model::Map map{ model, { { "input", inputNode } }, { { "output", accumulate } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); } void TestDelay() { model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(4); const auto& delay = nodes::Delay(inputNode->output, 3); model::IRMapCompiler compiler; model::Map map{ model, { { "input", inputNode } }, { { "output", delay } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); } void TestSqrt() { model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(1); const auto& sqrt = nodes::Sqrt(inputNode->output); model::IRMapCompiler compiler; model::Map map{ model, { { "input", inputNode } }, { { "output", sqrt } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); } void TestBinaryPredicate(bool expanded) { std::vector<double> data = { 5 }; model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(data.size()); const auto& c1 = nodes::Constant(model, data); const auto& eq = nodes::Equal(inputNode->output, c1); model::IRMapCompiler compiler; model::Map map{ model, { { "input", inputNode } }, { { "output", eq } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); } void TestMultiplexer() { std::vector<double> data = { 5, 10 }; model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(data.size()); const auto& c1 = nodes::Constant(model, true); const auto& selectedOutput = nodes::Multiplexer(inputNode->output, c1); model::IRMapCompiler compiler; model::Map map{ model, { { "input", inputNode } }, { { "output", selectedOutput } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); PrintIR(compiledMap); } void TestSlidingAverage() { model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(4); const auto& dim = nodes::Constant(model, (double)4.0); const auto& delay = nodes::Delay(inputNode->output, 2); const auto& sum = nodes::Sum(delay); const auto& avg = nodes::Divide(sum, dim); model::MapCompilerOptions settings; settings.mapFunctionName = "TestSlidingAverage"; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); model::Map map{ model, { { "input", inputNode } }, { { "output", avg } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); auto& module = compiledMap.GetModule(); module.DeclarePrintf(); auto mainFunction = module.BeginMainFunction(); std::vector<double> data = { 5, 10, 15, 20 }; auto& emitter = compiledMap.GetModule().GetIREmitter(); emitters::LLVMValue pContext = emitter.NullPointer(emitter.GetIRBuilder().getInt8Ty()->getPointerTo()); emitters::LLVMValue pData = module.ConstantArray("c_data", data); emitters::LLVMValue pResult = mainFunction.Variable(emitters::VariableType::Double, 1); mainFunction.Call("TestSlidingAverage", { pContext, mainFunction.PointerOffset(pData, 0), mainFunction.PointerOffset(pResult, 0) }); mainFunction.PrintForEach("%f\n", pResult, 1); mainFunction.Call("TestSlidingAverage", { pContext, mainFunction.PointerOffset(pData, 0), mainFunction.PointerOffset(pResult, 0) }); mainFunction.PrintForEach("%f\n", pResult, 1); mainFunction.Call("TestSlidingAverage", { pContext, mainFunction.PointerOffset(pData, 0), mainFunction.PointerOffset(pResult, 0) }); mainFunction.PrintForEach("%f\n", pResult, 1); mainFunction.Return(); module.EndFunction(); PrintIR(module); } void TestDotProductOutput() { model::MapCompilerOptions settings; settings.compilerSettings.inlineOperators = false; settings.mapFunctionName = "TestDotProduct"; std::vector<double> data = { 5, 10, 15, 20 }; model::Model model; auto inputNode = model.AddNode<model::InputNode<double>>(4); const auto& c1 = nodes::Constant(model, data); const auto& dotProduct = nodes::DotProduct(c1, inputNode->output); model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); model::Map map{ model, { { "input", inputNode } }, { { "output", dotProduct } } }; model::IRCompiledMap compiledMap = compiler.Compile(map); auto mainFunction = compiledMap.GetModule().BeginMainDebugFunction(); emitters::IRFunctionCallArguments args(mainFunction); auto& emitter = compiledMap.GetModule().GetIREmitter(); args.Append(emitter.NullPointer(emitter.GetIRBuilder().getInt8Ty()->getPointerTo())); args.Append(compiledMap.GetModule().ConstantArray("c_data", data)); auto pResult = args.AppendOutput(emitters::VariableType::Double, 1); mainFunction.Call("TestDotProduct", args); mainFunction.PrintForEach("%f\n", pResult, 1); mainFunction.Return(); compiledMap.GetModule().EndFunction(); PrintIR(compiledMap); } void TestForest() { auto map = MakeForestMap(); std::vector<double> data = { 0.2, 0.5, 0.0 }; model::MapCompilerOptions settings; settings.compilerSettings.optimize = true; settings.compilerSettings.includeDiagnosticInfo = false; settings.mapFunctionName = "TestForest"; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); auto compiledMap = compiler.Compile(map); auto& module = compiledMap.GetModule(); module.DeclarePrintf(); auto mainFunction = module.BeginMainFunction(); emitters::LLVMValue pData = module.ConstantArray("c_data", data); emitters::LLVMValue pResult = nullptr; auto args = module.GetFunction("TestForest")->args(); emitters::IRValueList callArgs; callArgs.push_back(mainFunction.PointerOffset(pData, 0)); size_t i = 0; for (auto& arg : args) { (void)arg; // stifle compiler warning if (i > 0) { emitters::LLVMValue pArg = nullptr; if (pResult == nullptr) { pArg = mainFunction.Variable(emitters::VariableType::Double, 1); pResult = pArg; } else { pArg = mainFunction.Variable(emitters::VariableType::Int32, 1); } callArgs.push_back(mainFunction.PointerOffset(pArg, 0)); } ++i; } //mainFunction.Call("TestForest", { mainFunction.PointerOffset(pData, 0), mainFunction.PointerOffset(pResult, 0) }); mainFunction.Print("Calling TestForest\n"); mainFunction.Call("TestForest", callArgs); mainFunction.Print("Done Calling TestForest\n"); mainFunction.PrintForEach("%f\n", pResult, 1); mainFunction.Return(); mainFunction.Verify(); PrintIR(compiledMap); compiledMap.GetModule().WriteToFile(OutputPath("forest_map.ll")); } extern "C" { // Callbacks used by compiled map bool TestMulti_DataCallback1(void* context, double* input) { Log() << "Data callback 1" << EOL; const std::vector<double> input1{ 1, 3, 5, 7, 9, 11, 13 }; std::copy(input1.begin(), input1.end(), input); return true; } bool TestMulti_DataCallback2(void* context, double* input) { Log() << "Data callback 2" << EOL; const std::vector<double> input2{ 42 }; std::copy(input2.begin(), input2.end(), input); return true; } void TestMulti_ResultsCallback_Scalar(void* context, double result) { Log() << "Results callback (scalar): " << result << EOL; } void TestMulti_ResultsCallback_Vector(void* context, double* result) { Log() << "Results callback (vector): " << result[0] << EOL; } void TestMulti_LagNotificationCallback(void* context, double lag) { Log() << "Lag callback:" << lag << EOL; } } // Ensure that LLVM jit can find these symbols TESTING_FORCE_DEFINE_SYMBOL(TestMulti_DataCallback1, bool, void*, double*); TESTING_FORCE_DEFINE_SYMBOL(TestMulti_DataCallback2, bool, void*, double*); TESTING_FORCE_DEFINE_SYMBOL(TestMulti_ResultsCallback_Scalar, void, void*, double); TESTING_FORCE_DEFINE_SYMBOL(TestMulti_ResultsCallback_Vector, void, void*, double*); TESTING_FORCE_DEFINE_SYMBOL(TestMulti_LagNotificationCallback, void, void*, double); void TestMultiSourceSinkMap(bool expanded, bool optimized) { // Create the map constexpr nodes::TimeTickType lagThreshold = 200; constexpr nodes::TimeTickType interval = 40; model::Model model; auto inputNode = model.AddNode<model::InputNode<nodes::TimeTickType>>(1 /*currentTime*/); auto clockNode = model.AddNode<nodes::ClockNode>(inputNode->output, interval, lagThreshold, "LagNotificationCallback"); auto sourceNode1 = model.AddNode<nodes::SourceNode<double>>(clockNode->output, 7, "DataCallback1", [](auto& v) { return TestMulti_DataCallback1(nullptr, &v[0]); }); auto sourceNode2 = model.AddNode<nodes::SourceNode<double>>(clockNode->output, 1, "DataCallback2", [](auto& v) { return TestMulti_DataCallback2(nullptr, &v[0]); }); auto sumNode = model.AddNode<nodes::SumNode<double>>(sourceNode1->output); auto minusNode = model.AddNode<nodes::BinaryOperationNode<double>>(sumNode->output, sourceNode2->output, nodes::BinaryOperationType::subtract); auto conditionNode = model.AddNode<nodes::ConstantNode<bool>>(true); auto sinkNode1 = model.AddNode<nodes::SinkNode<double>>(sumNode->output, conditionNode->output, "ResultsCallback_Scalar"); auto sinkNode2 = model.AddNode<nodes::SinkNode<double>>(model::PortElements<double>{ minusNode->output, sumNode->output }, conditionNode->output, "ResultsCallback_Vector"); // compiled maps require a single output, so we concatenate the ports for the sink nodes auto outputNode = model.AddNode<model::OutputNode<double>>(model::PortElements<double>{ sinkNode1->output, sinkNode2->output }); auto map = model::Map(model, { { "time", inputNode } }, { { "output", outputNode->output } }); // Compile the map model::MapCompilerOptions settings; settings.moduleName = "TestMulti"; settings.compilerSettings.optimize = optimized; settings.compilerSettings.unrollLoops = expanded; model::ModelOptimizerOptions optimizerOptions; model::IRMapCompiler compiler(settings, optimizerOptions); auto compiledMap = compiler.Compile(map); // Compare output std::vector<std::vector<nodes::TimeTickType>> signal = { { 0 }, { interval * 1 + lagThreshold / 2 }, // within threshold { interval * 2 }, // on time { interval * 3 + lagThreshold }, // late { interval * 4 + lagThreshold * 20 }, // really late { interval * 5 } // on time }; VerifyCompiledOutput(map, compiledMap, signal, " multi-sink and source map"); } void TestMultiSourceSinkMap() { TestMultiSourceSinkMap(true, true); TestMultiSourceSinkMap(true, false); TestMultiSourceSinkMap(false, true); TestMultiSourceSinkMap(false, false); }
41.709184
210
0.675199
[ "vector", "model", "transform" ]
d71e3e21bc49a9f40a44a5a4ae5bd1b97f637f9d
22,404
cpp
C++
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/meta/metabitmaprt.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
5,937
2018-12-04T16:32:50.000Z
2022-03-31T09:48:37.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/meta/metabitmaprt.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
4,151
2018-12-04T16:38:19.000Z
2022-03-31T18:41:14.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/meta/metabitmaprt.cpp
Mu-L/wpf
a539c26bb4c099acaf902077e03f787775b082fd
[ "MIT" ]
1,084
2018-12-04T16:24:21.000Z
2022-03-30T13:52:03.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+----------------------------------------------------------------------------- // // // $TAG ENGR // $Module: win_mil_graphics_targets // $Keywords: // // $Description: // CMetaBitmapRenderTarget implementation // // This is a multiple or meta Render Target for rendering on multiple // offscreen surfaces. This is also a meta Bitmap Source that holds // references to IWGXBitmapSources specific to the sub Render Targets. // // $ENDTAG // //------------------------------------------------------------------------------ #include "precomp.hpp" MtDefine(CMetaBitmapRenderTarget, MILRender, "CMetaBitmapRenderTarget"); //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::operator new // // Synopsis: // Allocate memory for one rendertarget, plus additional memory for each // sub-render target // //------------------------------------------------------------------------------ void * __cdecl CMetaBitmapRenderTarget::operator new( size_t cb, // bytes of memory to allocate for render target size_t cRTs // number of sub-render targets ) { HRESULT hr = S_OK; void *pBuffer = NULL; size_t cbBufferSize = 0; IFC(SizeTMult(cRTs, sizeof(MetaData), &cbBufferSize)); IFC(SizeTAdd(cbBufferSize, cb, &cbBufferSize)); pBuffer = WPFAlloc( ProcessHeap, Mt(CMetaBitmapRenderTarget), cbBufferSize ); Cleanup: return pBuffer; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::Create // // Synopsis: // Create a CMetaBitmapRenderTarget // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::Create( UINT uWidth, // Width of render targets UINT uHeight, // Height of render targets UINT cRTs, // Count of render targets __in_ecount(cRTs) MetaData *pMetaData, // Array of render target data __in_ecount(1) CDisplaySet const *pDisplaySet, IntermediateRTUsage usageInfo, MilRTInitialization::Flags dwFlags, __deref_out_ecount(1) CMetaBitmapRenderTarget **ppMetaRT // Location to return object pointer ) { HRESULT hr = S_OK; *ppMetaRT = NULL; // // Create the CMetaBitmapRenderTarget // *ppMetaRT = new(cRTs) CMetaBitmapRenderTarget(cRTs, pDisplaySet); IFCOOM(*ppMetaRT); (*ppMetaRT)->AddRef(); // CMetaBitmapRenderTarget::ctor sets ref count == 0 // // Call Init // IFC((*ppMetaRT)->Init( uWidth, uHeight, usageInfo, dwFlags, pMetaData )); Cleanup: if (FAILED(hr)) { ReleaseInterface(*ppMetaRT); } RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::CMetaBitmapRenderTarget // // Synopsis: // ctor // //------------------------------------------------------------------------------ #pragma warning( push ) #pragma warning( disable : 4355 ) CMetaBitmapRenderTarget::CMetaBitmapRenderTarget( UINT cMaxRTs, __inout_ecount(1) CDisplaySet const *pDisplaySet ) : CMetaRenderTarget( reinterpret_cast<MetaData *>(reinterpret_cast<BYTE *>(this) + sizeof(*this)), cMaxRTs, pDisplaySet ) { } #pragma warning( pop ) //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::~CMetaBitmapRenderTarget // // Synopsis: // dtor // //------------------------------------------------------------------------------ CMetaBitmapRenderTarget::~CMetaBitmapRenderTarget() { for (UINT i = 0; i < m_cRT; i++) { ReleaseInterface(m_rgMetaData[i].pIRTBitmap); } } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::HrFindInterface // // Synopsis: // HrFindInterface implementation // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::HrFindInterface( __in_ecount(1) REFIID riid, __deref_out void **ppvObject ) { HRESULT hr = E_INVALIDARG; if (ppvObject) { if (riid == IID_IMILRenderTargetBitmap) { *ppvObject = static_cast<IMILRenderTargetBitmap*>(this); hr = S_OK; } else if (riid == IID_IWGXBitmapSource) { *ppvObject = static_cast<IWGXBitmapSource*>(this); hr = S_OK; } else if (riid == IID_CMetaBitmapRenderTarget) { *ppvObject = this; hr = S_OK; } else { hr = CMetaRenderTarget::HrFindInterface(riid, ppvObject); } } return hr; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::Init // // Synopsis: // Inits the meta render target and allocates the required resources // //------------------------------------------------------------------------------ HRESULT CMetaBitmapRenderTarget::Init( UINT uWidth, UINT uHeight, IntermediateRTUsage usageInfo, MilRTInitialization::Flags dwFlags, __in_xcount(m_cRTs) MetaData const *pMetaData ) { HRESULT hr = S_OK; // // Intialize basic members // m_uWidth = uWidth; m_uHeight = uHeight; // // Create bitmap RTs for each RT and remember // their source bitmaps. // Assert(m_cRT*sizeof(m_rgMetaData[0]) == RtlCompareMemoryUlong(m_rgMetaData, m_cRT*sizeof(m_rgMetaData[0]), 0)); // The width and height are converted to floats when clipping, // make sure we don't expect values TOO big as input. if (uWidth > SURFACE_RECT_MAX || uHeight > SURFACE_RECT_MAX) { IFC(WGXERR_UNSUPPORTEDTEXTURESIZE); } for (UINT i=0; i < m_cRT && SUCCEEDED(hr); i++) { // // Initialize the cache index to invalid. We only want the meta data // object which has a non-null pIRTBitmap to have a valid cache index. // m_rgMetaData[i].cacheIndex = CMILResourceCache::InvalidToken; #if DBG m_rgMetaData[i].uIndexOfRealRTBitmap = UINT_MAX; #endif if (pMetaData[i].fEnable) { ULONG curCacheIndex = pMetaData[i].pInternalRT->GetRealizationCacheIndex(); if (curCacheIndex == CMILResourceCache::InvalidToken) { curCacheIndex = CMILResourceCache::SwRealizationCacheIndex; } // Initialize the index 'pointer' to itself. m_rgMetaData[i].uIndexOfRealRTBitmap = i; // Future Consideration: We may want to revisit this sharing code. If it is cheap to share // textures (i.e. they have the same underlying video card and we have 9EX // devices) we may want to enable that. Currently this is only used in software // mode. // // Search for bitmap RTs created for other displays that we could // share. We allow sharing of RTs when the displays share a device. // [We use the cache index to differentiate devices.] We also allow // sharing of software bitmap render targets- we don't bother to // create hardware render targets when we already have a software // render target avaliable for use. // for (UINT j = 0; j < i; j++) { if ( m_rgMetaData[j].cacheIndex == curCacheIndex || m_rgMetaData[j].cacheIndex == CMILResourceCache::SwRealizationCacheIndex ) { // // Found a match. There is no need to create two identical // render targets so we will 'point' back to the matching // one. // m_rgMetaData[i].uIndexOfRealRTBitmap = j; break; } } if (m_rgMetaData[i].uIndexOfRealRTBitmap != i) { m_rgMetaData[i].cacheIndex = CMILResourceCache::InvalidToken; Assert(m_rgMetaData[i].fEnable == FALSE); } else { MIL_THR(pMetaData[i].pInternalRT->CreateRenderTargetBitmap( uWidth, uHeight, usageInfo, dwFlags, &m_rgMetaData[i].pIRTBitmap )); if (SUCCEEDED(hr)) { #if DBG if (pMetaData[i].pInternalRT->GetRealizationCacheIndex() == CMILResourceCache::InvalidToken) { // // Assert that CreateRenderTargetBitmap created a // software RT. This justifies setting curCacheIndex to // CMILResourceCache::SwRealizationCacheIndex above // Assert(curCacheIndex == CMILResourceCache::SwRealizationCacheIndex); // The DYNCAST does the assert DYNCAST(CSwRenderTargetBitmap, m_rgMetaData[i].pIRTBitmap); } #endif hr = THR(m_rgMetaData[i].pIRTBitmap->QueryInterface( IID_IRenderTargetInternal, (void **)&(m_rgMetaData[i].pInternalRT) )); } if (SUCCEEDED(hr)) { // // Enable rendering to the new RT upon success // m_rgMetaData[i].fEnable = TRUE; // // Set the cache index to the cache index of the newly // created bitmap render target. It is important not to use // the cache index of the original render target, as // hardware render targets are allowed to create software // render targets. // m_rgMetaData[i].cacheIndex = m_rgMetaData[i].pInternalRT->GetRealizationCacheIndex(); // Set the bounds either way Assert(m_rgMetaData[i].rcLocalDeviceRenderBounds.left == 0); Assert(m_rgMetaData[i].rcLocalDeviceRenderBounds.top == 0); m_rgMetaData[i].rcLocalDeviceRenderBounds.right = static_cast<LONG>(uWidth); m_rgMetaData[i].rcLocalDeviceRenderBounds.bottom = static_cast<LONG>(uHeight); m_rgMetaData[i].rcLocalDevicePresentBounds = m_rgMetaData[i].rcLocalDeviceRenderBounds; } } } } Cleanup: RRETURN(hr); } //+======================================================================== // IMILRenderTarget methods //========================================================================= //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetBounds // // Synopsis: // Return accumulated bounds of all render targets // //------------------------------------------------------------------------------ STDMETHODIMP_(VOID) CMetaBitmapRenderTarget::GetBounds( __out_ecount(1) MilRectF * const pBounds ) { CMilRectF rcAcc; rcAcc.SetEmpty(); for (UINT idx = 0; idx < m_cRT; idx++) { // Acuumulate bounds of all RTs as long as there is an RT if (m_rgMetaData[idx].pInternalRT) { m_rgMetaData[idx].pInternalRT->GetBounds(pBounds); rcAcc.Union(*pBounds); } } *pBounds = rcAcc; return; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::Clear // // Synopsis: // Clear the surface to a given color. // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::Clear( __in_ecount_opt(1) const MilColorF *pColor, __in_ecount_opt(1) const CAliasedClip *pAliasedClip ) { return CMetaRenderTarget::Clear(pColor, pAliasedClip); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::Begin3D, End3D // // Synopsis: // Assert state then delegate to base class // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::Begin3D( __in_ecount(1) MilRectF const &rcBounds, MilAntiAliasMode::Enum AntiAliasMode, bool fUseZBuffer, FLOAT rZ ) { return CMetaRenderTarget::Begin3D(rcBounds, AntiAliasMode, fUseZBuffer, rZ); } STDMETHODIMP CMetaBitmapRenderTarget::End3D( ) { return CMetaRenderTarget::End3D(); } //+======================================================================== // IMILRenderTargetBitmap methods //========================================================================= //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetBitmapSource // // Synopsis: // Return a bitmap source interface to the internal meta bitmap that holds // separate RT specific bitmaps // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetBitmapSource( __deref_out_ecount(1) IWGXBitmapSource ** const ppIBitmapSource ) { Assert(m_rgMetaData); *ppIBitmapSource = this; (*ppIBitmapSource)->AddRef(); return S_OK; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetCacheableBitmapSource // // Synopsis: // Return a bitmap source interface to the internal meta bitmap that holds // separate RT specific bitmaps // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetCacheableBitmapSource( __deref_out_ecount(1) IWGXBitmapSource ** const ppIBitmapSource ) { // To implement GetCacheableBitmapSource, we would need to go into each // surface bitmap & ensure those bitmaps are cacheable. This functionality // isn't currently supported because CMetaBitmapRenderTarget is not used // by any callers of GetCacheableBitmapSource. *ppIBitmapSource = NULL; RIP("CMetaBitmapRenderTarget::GetCacheableBitmapSource isn't implemented"); RRETURN(E_NOTIMPL); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetBitmap // // Synopsis: // Not implemented // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetBitmap( __deref_out_ecount(1) IWGXBitmap ** const ppIBitmap ) { RRETURN(WGXERR_NOTIMPLEMENTED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetNumQueuedPresents // // Synopsis: // Forwards call to the CMetaRenderTarget member. // //------------------------------------------------------------------------------ HRESULT CMetaBitmapRenderTarget::GetNumQueuedPresents( __out_ecount(1) UINT *puNumQueuedPresents ) { RRETURN(CMetaRenderTarget::GetNumQueuedPresents(puNumQueuedPresents)); } //+======================================================================== // IWGXBitmapSource methods //========================================================================= //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetSize // // Synopsis: // Get pixel dimensions of bitmap // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetSize( __out_ecount(1) UINT *puWidth, __out_ecount(1) UINT *puHeight ) { *puWidth = m_uWidth; *puHeight = m_uHeight; return S_OK; } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetPixelFormat // // Synopsis: // Get pixel format of bitmap // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetPixelFormat( __out_ecount(1) MilPixelFormat::Enum *pPixelFormat ) { RRETURN(E_ACCESSDENIED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetResolution // // Synopsis: // Not implemented // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::GetResolution( __out_ecount(1) double *pDpiX, __out_ecount(1) double *pDpiY ) { RRETURN(E_ACCESSDENIED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::CopyPalette // // Synopsis: // Not implemented // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::CopyPalette( __inout_ecount(1) IWICPalette *pIPalette ) { RRETURN(E_ACCESSDENIED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::CopyPixels // // Synopsis: // Access via CopyPixels method is not supported // //------------------------------------------------------------------------------ STDMETHODIMP CMetaBitmapRenderTarget::CopyPixels( __in_ecount_opt(1) const MILRect *prc, UINT cbStride, UINT cbBufferSize, __out_ecount(cbBufferSize) BYTE *pvPixels ) { RRETURN(E_ACCESSDENIED); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetSubRenderTargetNoRef // // Synopsis: // Walks the internal render targets, finding the one that matches the // cache index and display id. // // The display id is optional, but if it exists it overrides the cache // index as a lookup mechanism. // // Returns an error if no rendertarget was found. // HRESULT CMetaBitmapRenderTarget::GetCompatibleSubRenderTargetNoRef( IMILResourceCache::ValidIndex uOptimalRealizationCacheIndex, DisplayId targetDestination, __deref_out_ecount(1) IMILRenderTargetBitmap **ppIRenderTargetNoRef ) { HRESULT hr = S_OK; IMILRenderTargetBitmap *pIRenderTargetNoRef = GetCompatibleSubRenderTargetNoRefInternal( uOptimalRealizationCacheIndex, targetDestination ); if (pIRenderTargetNoRef == NULL) { RIPW(L"No internal intermediate render target found matching realization cache index!"); MIL_THR(WGXERR_INTERNALERROR); } *ppIRenderTargetNoRef = pIRenderTargetNoRef; RRETURN(hr); } //+----------------------------------------------------------------------------- // // Member: // CMetaBitmapRenderTarget::GetCompatibleSubRenderTargetNoRefInternal // // Synopsis: // Walks the internal render targets, finding the one that matches the // cache index and display id. // // The display id is optional, but if it exists it overrides the cache // index as a lookup mechanism. // __out_ecount_opt(1) IMILRenderTargetBitmap * CMetaBitmapRenderTarget::GetCompatibleSubRenderTargetNoRefInternal( IMILResourceCache::ValidIndex uOptimalRealizationCacheIndex, DisplayId targetDestination ) { // PREfast should catch violations, but doesn't seem to today - so assert Assert(uOptimalRealizationCacheIndex != CMILResourceCache::InvalidToken); IMILRenderTargetBitmap *pIRenderTargetNoRef = NULL; if (targetDestination.IsNone()) { IMILResourceCache::ValidIndex uRealizationCacheIndexToLookFor = uOptimalRealizationCacheIndex; LookAgain: for (UINT i = 0; i < m_cRT; i++) { if (m_rgMetaData[i].fEnable) { UINT uRTRealizationIndex = m_rgMetaData[i].pInternalRT->GetRealizationCacheIndex(); // Meta bitmap RT should never be created with sub RT that has an // invalid cache index. Assert(uRTRealizationIndex != CMILResourceCache::InvalidToken); if (uRTRealizationIndex == uRealizationCacheIndexToLookFor) { pIRenderTargetNoRef = m_rgMetaData[i].pIRTBitmap; } } } if ( pIRenderTargetNoRef == NULL && uRealizationCacheIndexToLookFor != CMILResourceCache::SwRealizationCacheIndex ) { // // We were hoping to find a hardware intermediate, but no such // intermediate exists. Look for a software intermediate instead. // uRealizationCacheIndexToLookFor = CMILResourceCache::SwRealizationCacheIndex; goto LookAgain; } } else { UINT idx; Verify(SUCCEEDED(m_pDisplaySet->GetDisplayIndexFromDisplayId( targetDestination, OUT idx ))); idx = m_rgMetaData[idx].uIndexOfRealRTBitmap; Assert(idx < m_cRT); Assert(m_rgMetaData[idx].fEnable); Assert(m_rgMetaData[idx].pIRTBitmap); pIRenderTargetNoRef = m_rgMetaData[idx].pIRTBitmap; } return pIRenderTargetNoRef; }
29.401575
112
0.512766
[ "render", "object" ]
d723033484aca57b5e25a32ab36e7aee1443a2a1
4,037
cpp
C++
Core/GDCore/Events/Parsers/VariableParser.cpp
mohajain/GDevelop
8e8d96dd3a5957221fb3d0ec28a694620149d835
[ "MIT" ]
4
2021-03-18T22:26:31.000Z
2021-07-16T00:12:15.000Z
Core/GDCore/Events/Parsers/VariableParser.cpp
mohajain/GDevelop
8e8d96dd3a5957221fb3d0ec28a694620149d835
[ "MIT" ]
9
2020-04-04T19:26:47.000Z
2022-03-25T18:41:20.000Z
Core/GDCore/Events/Parsers/VariableParser.cpp
mohajain/GDevelop
8e8d96dd3a5957221fb3d0ec28a694620149d835
[ "MIT" ]
2
2020-03-02T05:20:41.000Z
2021-05-10T03:59:05.000Z
/* * GDevelop Core * Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights * reserved. This project is released under the MIT License. */ #include "GDCore/Events/Parsers/VariableParser.h" #include <vector> #include "GDCore/String.h" namespace gd { class Layout; } namespace gd { class Project; } namespace gd { class Platform; } #include "GDCore/Tools/Localization.h" namespace gd { VariableParser::~VariableParser() {} bool VariableParser::Parse(VariableParserCallbacks& callbacks_) { callbacks = &callbacks_; rootVariableParsed = false; firstErrorStr.clear(); firstErrorPos = 0; currentPositionIt = expression.begin(); currentTokenType = TS_INVALID; currentToken.clear(); S(); return firstErrorStr == ""; } void VariableParser::ReadToken() { currentTokenType = TS_INVALID; currentToken.clear(); while (currentPositionIt != expression.end()) { char32_t currentChar = *currentPositionIt; if (currentChar == U'[' || currentChar == U']' || currentChar == U'.') { if (currentTokenType == TS_VARNAME) return; // We've parsed a variable name. } if (currentChar == U'[') { currentTokenType = TS_OPENING_BRACKET; currentToken.clear(); ++currentPositionIt; return; } else if (currentChar == U']') { currentTokenType = TS_CLOSING_BRACKET; currentToken.clear(); ++currentPositionIt; return; } else if (currentChar == U'.') { currentTokenType = TS_PERIOD; currentToken.clear(); ++currentPositionIt; return; } currentTokenType = TS_VARNAME; // We're parsing a variable name. currentToken.push_back(currentChar); ++currentPositionIt; } // Can be reached if we are at the end of the expression. In this case, // currentTokenType will be either TS_VARNAME or TS_INVALID. } void VariableParser::S() { ReadToken(); if (currentTokenType != TS_VARNAME) { firstErrorStr = _("Expecting a variable name."); firstErrorPos = std::distance<gd::String::const_iterator>( expression.begin(), currentPositionIt); return; } if (!rootVariableParsed) { rootVariableParsed = true; if (callbacks) callbacks->OnRootVariable(currentToken); } else if (callbacks) callbacks->OnChildVariable(currentToken); X(); } void VariableParser::X() { ReadToken(); if (currentTokenType == TS_INVALID) return; // Ended parsing. else if (currentTokenType == TS_PERIOD) S(); else if (currentTokenType == TS_OPENING_BRACKET) { gd::String strExpr = SkipStringExpression(); ReadToken(); if (currentTokenType != TS_CLOSING_BRACKET) { firstErrorStr = _("Expecting ]"); firstErrorPos = std::distance<gd::String::const_iterator>( expression.begin(), currentPositionIt); return; } if (callbacks) callbacks->OnChildSubscript(strExpr); X(); } } gd::String VariableParser::SkipStringExpression() { gd::String stringExpression; bool insideStringLiteral = false; bool lastCharacterWasBackslash = false; unsigned int nestedBracket = 0; while (currentPositionIt != expression.end()) { char32_t currentChar = *currentPositionIt; if (currentChar == U'\"') { if (!insideStringLiteral) insideStringLiteral = true; else if (!lastCharacterWasBackslash) insideStringLiteral = false; } else if (currentChar == U'[' && !insideStringLiteral) { nestedBracket++; } else if (currentChar == U']' && !insideStringLiteral) { if (nestedBracket == 0) return stringExpression; // Found the end of the string litteral. nestedBracket--; } lastCharacterWasBackslash = currentChar == U'\\'; stringExpression.push_back(currentChar); ++currentPositionIt; } // End of the expression reached (so expression is invalid by the way) return stringExpression; } } // namespace gd
28.429577
77
0.651474
[ "vector" ]
d7248889112f7fb90c3749adb1ee38d026f3b9c7
18,842
cpp
C++
dev/Code/Sandbox/Editor/ShortcutDispatcher.cpp
yuriy0/lumberyard
18ab07fd38492d88c34df2a3e061739d96747e13
[ "AML" ]
null
null
null
dev/Code/Sandbox/Editor/ShortcutDispatcher.cpp
yuriy0/lumberyard
18ab07fd38492d88c34df2a3e061739d96747e13
[ "AML" ]
null
null
null
dev/Code/Sandbox/Editor/ShortcutDispatcher.cpp
yuriy0/lumberyard
18ab07fd38492d88c34df2a3e061739d96747e13
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "StdAfx.h" #include "ActionManager.h" #include "ShortcutDispatcher.h" #include "QtViewPaneManager.h" #include <QScopedValueRollback> #include <QApplication> #include <QMainWindow> #include <QEvent> #include <QWidget> #include <QAction> #include <QKeyEvent> #include <QShortcutEvent> #include <QShortcut> #include <QList> #include <QDockWidget> #include <QDebug> #include <QMenuBar> #include <QSet> #include <QPointer> #include <QLabel> #include <assert.h> #include <LyMetricsProducer/LyMetricsAPI.h> #include <AzToolsFramework/Metrics/LyEditorMetricsBus.h> #include <AzQtComponents/Buses/ShortcutDispatch.h> const char* FOCUSED_VIEW_PANE_EVENT_NAME = "FocusedViewPaneEvent"; //Sent when view panes are focused const char* FOCUSED_VIEW_PANE_ATTRIBUTE_NAME = "FocusedViewPaneName"; //Name of the current focused view pane // WAF sets _DEBUG when we're in debug mode; define SHOW_ACTION_INFO_IN_DEBUGGER so that when stepping through the debugger, // we can see what the actions are and what their keyboard shortcuts are #define SHOW_ACTION_INFO_IN_DEBUGGER _DEBUG static QPointer<QWidget> s_lastFocus; #if AZ_TRAIT_OS_PLATFORM_APPLE class MacNativeShortcutFilter : public QObject { /* mac's native toolbar doesn't generate shortcut events, it calls the action directly. * It doesn't even honour shortcut contexts. * * To remedy this, we catch the QMetaCallEvent that triggers the menu item activation * and suppress it if it was triggered via key combination, and send a QShortcutEvent. * * The tricky part is to find out if the menu item was triggered via mouse or shortcut. * If the previous event was a ShortcutOverride then it means key press. */ public: explicit MacNativeShortcutFilter(QObject* parent) : QObject(parent) , m_lastShortcutOverride(QEvent::KeyPress, 0, Qt::NoModifier) // dummy init { qApp->installEventFilter(this); } bool eventFilter(QObject* watched, QEvent* event) override { switch (event->type()) { case QEvent::ShortcutOverride: { auto ke = static_cast<QKeyEvent*>(event); m_lastEventWasShortcutOverride = true; m_lastShortcutOverride = QKeyEvent(*ke); break; } case QEvent::MetaCall: { if (m_lastEventWasShortcutOverride) { m_lastEventWasShortcutOverride = false; const QMetaObject* mo = watched->metaObject(); const bool isMenuItem = mo && qstrcmp(mo->className(), "QPlatformMenuItem") == 0; if (isMenuItem) { QWidget* focusWidget = ShortcutDispatcher::focusWidget(); if (focusWidget) { QShortcutEvent se(QKeySequence(m_lastShortcutOverride.key() + m_lastShortcutOverride.modifiers()), /*ambiguous=*/false); se.setAccepted(false); QApplication::sendEvent(focusWidget, &se); return se.isAccepted(); } } } break; } case QEvent::MouseButtonDblClick: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::KeyPress: case QEvent::KeyRelease: m_lastEventWasShortcutOverride = false; break; default: break; } return false; } bool m_lastEventWasShortcutOverride = false; QKeyEvent m_lastShortcutOverride; }; #endif // Returns either a top-level or a dock widget (regardless of floating) // This way when docking a main window Qt::WindowShortcut still works QWidget* ShortcutDispatcher::FindParentScopeRoot(QWidget* widget) { QWidget* w = widget; // if the current scope root is a QDockWidget, we want to bubble out // so we move to the parent immediately if (qobject_cast<QDockWidget*>(w) != nullptr || qobject_cast<QMainWindow*>(w) != nullptr) { w = w->parentWidget(); } QWidget* newScopeRoot = w; while (newScopeRoot && newScopeRoot->parent() && !qobject_cast<QDockWidget*>(newScopeRoot) && !qobject_cast<QMainWindow*>(newScopeRoot)) { newScopeRoot = newScopeRoot->parentWidget(); } // This method should always return a parent scope root; if it can't find one // it returns null if (newScopeRoot == widget) { newScopeRoot = nullptr; if (w != nullptr) { // we couldn't find a valid parent; broadcast a message to see if something else wants to tell us about one AzQtComponents::ShortcutDispatchBus::EventResult(newScopeRoot, w, &AzQtComponents::ShortcutDispatchBus::Events::GetShortcutDispatchScopeRoot, w); } } return newScopeRoot; } // Returns true if a widget is ancestor of another widget bool ShortcutDispatcher::IsAContainerForB(QWidget* a, QWidget* b) { if (!a || !b) { return false; } while (b && (a != b)) { b = b->parentWidget(); } return (a == b); } // Returns the list of QActions which have this specific key shortcut // Only QActions under scopeRoot are considered. QList<QAction*> ShortcutDispatcher::FindCandidateActions(QObject* scopeRoot, const QKeySequence& sequence, QSet<QObject*>& previouslyVisited, bool checkVisibility) { QList<QAction*> actions; if (!scopeRoot) { return actions; } if (previouslyVisited.contains(scopeRoot)) { return actions; } previouslyVisited.insert(scopeRoot); QWidget* scopeRootWidget = qobject_cast<QWidget*>(scopeRoot); if (scopeRootWidget && ((checkVisibility && !scopeRootWidget->isVisible()) || !scopeRootWidget->isEnabled())) { return actions; } #ifdef SHOW_ACTION_INFO_IN_DEBUGGER QString matchingAgainst = sequence.toString(); (void) matchingAgainst; // avoid an unused variable warning; want this for debugging #endif // Don't just call scopeRoot->actions()! It doesn't always return the proper list, especially with the dock widgets for (QAction* action : scopeRoot->findChildren<QAction*>(QString(), Qt::FindDirectChildrenOnly)) // Width first { #ifdef SHOW_ACTION_INFO_IN_DEBUGGER QString actionName = action->text(); (void)actionName; // avoid an unused variable warning; want this for debugging QString shortcut = action->shortcut().toString(); (void)shortcut; // avoid an unused variable warning; want this for debugging #endif if (action->shortcut() == sequence) { actions << action; } } // also have to check the actions on the object directly, without looking at children // specifically for the master MainWindow if (scopeRootWidget) { for (QAction* action : scopeRootWidget->actions()) { #ifdef SHOW_ACTION_INFO_IN_DEBUGGER QString actionName = action->text(); (void)actionName; // avoid an unused variable warning; want this for debugging QString shortcut = action->shortcut().toString(); (void)shortcut; // avoid an unused variable warning; want this for debugging #endif if (action->shortcut() == sequence) { actions << action; } } } // Menubars have child widgets that have actions // But menu bar child widgets (menu items) are only visible when they've been clicked on // so we don't want to test visibility for child widgets of menubars if (qobject_cast<QMenuBar*>(scopeRoot)) { checkVisibility = false; } // check the dock's central widget and the main window's // In some cases, they aren't in the scopeRoot's children, despite having the scopeRoot as their parent QDockWidget* dockWidget = qobject_cast<QDockWidget*>(scopeRoot); if (dockWidget) { actions << FindCandidateActions(dockWidget->widget(), sequence, previouslyVisited, checkVisibility); } QMainWindow* mainWindow = qobject_cast<QMainWindow*>(scopeRoot); if (mainWindow) { actions << FindCandidateActions(mainWindow->centralWidget(), sequence, previouslyVisited, checkVisibility); } for (QWidget* child : scopeRoot->findChildren<QWidget*>(QString(), Qt::FindDirectChildrenOnly)) { bool isMenu = (qobject_cast<QMenu*>(child) != nullptr); if ((child->windowFlags() & Qt::Window) && !isMenu) { // When going down the hierarchy stop at window boundaries, to not accidentally trigger // shortcuts from unfocused windows. Windows might be parented to this scope for purposes // "centering within parent" or lifetime. // Don't stop at menus though, as they are flagged as Qt::Window but are often the only thing that // actions are attached to. continue; } bool isDockWidget = (qobject_cast<QDockWidget*>(child) != nullptr); if ((isDockWidget && !actions.isEmpty()) || IsShortcutSearchBreak(child)) { // If we already found a candidate, don't go into dock widgets, they have lower priority // since they are not focused. // Also never go into viewpanes; viewpanes are their own separate shortcut context and they never take shortcuts from the main window continue; } actions << FindCandidateActions(child, sequence, previouslyVisited, checkVisibility); } return actions; } bool ShortcutDispatcher::FindCandidateActionAndFire(QObject* focusWidget, QShortcutEvent* shortcutEvent, QList<QAction*>& candidates, QSet<QObject*>& previouslyVisited) { candidates = FindCandidateActions(focusWidget, shortcutEvent->key(), previouslyVisited); QSet<QAction*> candidateSet = QSet<QAction*>::fromList(candidates); QAction* chosenAction = nullptr; int numCandidates = candidateSet.size(); if (numCandidates == 1) { chosenAction = candidates.first(); } else if (numCandidates > 1) { // If there are multiple candidates, choose the one that is parented to the ActionManager // since there are cases where panes with their own menu shortcuts that are docked // in the main window can be found in the same parent scope for (QAction* action : candidateSet) { if (qobject_cast<ActionManager*>(action->parent())) { chosenAction = action; break; } } } if (chosenAction) { if (chosenAction->isEnabled()) { // Navigation triggered - shortcut in general AzToolsFramework::EditorMetricsEventsBusAction editorMetricsEventsBusActionWrapper(AzToolsFramework::EditorMetricsEventsBusTraits::NavigationTrigger::Shortcut); // has to be send, not post, or the dispatcher will get the event again and won't know that it was the one that queued it bool isAmbiguous = false; QShortcutEvent newEvent(shortcutEvent->key(), isAmbiguous); QApplication::sendEvent(chosenAction, &newEvent); } shortcutEvent->accept(); return true; } return false; } ShortcutDispatcher::ShortcutDispatcher(QObject* parent) : QObject(parent) , m_currentlyHandlingShortcut(false) { qApp->installEventFilter(this); #if AZ_TRAIT_OS_PLATFORM_APPLE new MacNativeShortcutFilter(this); #endif } ShortcutDispatcher::~ShortcutDispatcher() { } bool ShortcutDispatcher::eventFilter(QObject* obj, QEvent* ev) { switch (ev->type()) { case QEvent::Shortcut: return shortcutFilter(obj, static_cast<QShortcutEvent*>(ev)); break; case QEvent::MouseButtonPress: if (!s_lastFocus || !IsAContainerForB(qobject_cast<QWidget*>(obj), s_lastFocus)) { setNewFocus(obj); } break; case QEvent::FocusIn: setNewFocus(obj); break; // we don't really care about focus out, because something should always have the focus // but I'm leaving this here, so that it's clear that this is intentional //case QEvent::FocusOut: // break; } return false; } QWidget* ShortcutDispatcher::focusWidget() { QWidget* focusWidget = s_lastFocus; // check the widget we tracked last if (!focusWidget) { // we don't have anything, so fall back to using the focus object focusWidget = qobject_cast<QWidget*>(qApp->focusObject()); // QApplication::focusWidget() doesn't always work } return focusWidget; } bool ShortcutDispatcher::shortcutFilter(QObject* obj, QShortcutEvent* shortcutEvent) { if (m_currentlyHandlingShortcut) { return false; } QScopedValueRollback<bool> recursiveCheck(m_currentlyHandlingShortcut, true); // prioritize m_actionOverrideObject if active if (m_actionOverrideObject != nullptr) { QList<QAction*> childActions = m_actionOverrideObject->findChildren<QAction*>(QString(), Qt::FindDirectChildrenOnly); // attempt to find shortcut in override const auto childActionIt = AZStd::find_if( childActions.begin(), childActions.end(), [shortcutEvent](QAction* child) { return child->shortcut() == shortcutEvent->key(); }); // trigger shortcut if (childActionIt != childActions.end()) { // navigation triggered - shortcut in general AzToolsFramework::EditorMetricsEventsBusAction editorMetricsEventsBusActionWrapper( AzToolsFramework::EditorMetricsEventsBusTraits::NavigationTrigger::Shortcut); // has to be send, not post, or the dispatcher will get the event again // and won't know that it was the one that queued it const bool isAmbiguous = false; QShortcutEvent newEvent(shortcutEvent->key(), isAmbiguous); QAction* action = *childActionIt; QApplication::sendEvent(action, &newEvent); shortcutEvent->accept(); return true; } } QWidget* currentFocusWidget = focusWidget(); // check the widget we tracked last if (!currentFocusWidget) { qWarning() << Q_FUNC_INFO << "No focus widget"; // Defensive. Doesn't happen. return false; } // Shortcut is ambiguous, lets resolve ambiguity and give preference to QActions in the most inner scope // Try below the focusWidget first: QSet<QObject*> previouslyVisited; QList<QAction*> candidates; if (FindCandidateActionAndFire(currentFocusWidget, shortcutEvent, candidates, previouslyVisited)) { return true; } // Now incrementally try bigger scopes. This handles complex cases several levels docking nesting QWidget* correctedTopLevel = nullptr; QWidget* p = currentFocusWidget; while (correctedTopLevel = FindParentScopeRoot(p)) { if (FindCandidateActionAndFire(correctedTopLevel, shortcutEvent, candidates, previouslyVisited)) { return true; } p = correctedTopLevel; } // Nothing else to do... shortcut is really ambiguous, or there's no actions, something for the developer to fix. // Here's some debug info : if (candidates.isEmpty()) { qWarning() << Q_FUNC_INFO << "No candidate QActions found"; } else { qWarning() << Q_FUNC_INFO << "Ambiguous shortcut:" << shortcutEvent->key() << "; focusWidget=" << qApp->focusWidget() << "Candidates=" << candidates << "; obj = " << obj << "Focused top-level=" << currentFocusWidget; for (auto ambiguousAction : candidates) { qWarning() << "action=" << ambiguousAction << "; action->parentWidget=" << ambiguousAction->parentWidget() << "; associatedWidgets=" << ambiguousAction->associatedWidgets() << "; shortcut=" << ambiguousAction->shortcut(); } } return false; } void ShortcutDispatcher::setNewFocus(QObject* obj) { // Unless every widget has strong focus, mouse clicks don't change the current focus widget // which is a little unintuitive, compared to how we expect focus to work, right now. // So instead of putting strong focus on everything, we detect focus change and mouse clicks QWidget* widget = qobject_cast<QWidget*>(obj); // we only watch widgets if (widget == nullptr) { return; } // track it for later s_lastFocus = widget; sendFocusMetricsData(obj); } void ShortcutDispatcher::sendFocusMetricsData(QObject* obj) { // if we can't find the parent widget in the following search, then we assume it's a main window QString parentWidgetName = "MainWindow"; while (obj != nullptr) { if (QtViewPaneManager::instance()->GetView(obj->objectName()) == obj) { parentWidgetName = obj->objectName().toUtf8(); break; } obj = obj->parent(); } if (!m_previousWidgetName.isEmpty() && parentWidgetName.compare(m_previousWidgetName) != 0) { SubmitMetricsEvent(parentWidgetName.toUtf8()); } m_previousWidgetName = parentWidgetName; } void ShortcutDispatcher::SubmitMetricsEvent(const char* attributeName) { //Send metrics event for the current focused view pane auto eventId = LyMetrics_CreateEvent(FOCUSED_VIEW_PANE_EVENT_NAME); // Add attribute to show what pane is focused LyMetrics_AddAttribute(eventId, FOCUSED_VIEW_PANE_ATTRIBUTE_NAME, attributeName); LyMetrics_SubmitEvent(eventId); } bool ShortcutDispatcher::IsShortcutSearchBreak(QWidget* widget) { return widget->property(AzQtComponents::SHORTCUT_DISPATCHER_CONTEXT_BREAK_PROPERTY).toBool(); } void ShortcutDispatcher::AttachOverride(QWidget* object) { m_actionOverrideObject = object; } void ShortcutDispatcher::DetachOverride() { m_actionOverrideObject = nullptr; } #include <ShortcutDispatcher.moc>
34.196007
172
0.654601
[ "object" ]
c012ab3cc6aa190c148b50aa0295f392b157ef0b
20,637
cc
C++
GLwrapper/glsupport.cc
BlurryLight/DiRenderLab
e07f2e5cbbb30511c9f610fc6e4c9d03c92ec3e3
[ "MIT" ]
2
2021-04-21T04:28:36.000Z
2022-03-04T07:55:11.000Z
GLwrapper/glsupport.cc
BlurryLight/DiRenderLab
e07f2e5cbbb30511c9f610fc6e4c9d03c92ec3e3
[ "MIT" ]
null
null
null
GLwrapper/glsupport.cc
BlurryLight/DiRenderLab
e07f2e5cbbb30511c9f610fc6e4c9d03c92ec3e3
[ "MIT" ]
2
2021-08-04T10:31:56.000Z
2021-11-20T09:22:24.000Z
// // Created by zhong on 2021/4/26. // #include <utility> #include <utils/cmake_vars.h> #include "glsupport.hh" #include "third_party/imgui/imgui.h" #include "third_party/imgui/imgui_impl_glfw.h" #include "third_party/imgui/imgui_impl_opengl3.h" using namespace DRL; using DRL::details::Mesh; using DRL::details::Vertex; float DRL::get_random_float(float min, float max) { static std::mt19937 generator; std::uniform_real_distribution<float> dis(min, max); return dis(generator); } void DRL::glDebugOutput(GLenum source, GLenum type, unsigned int id, GLenum severity, GLsizei length, const char *message, const void *userParam) { // clang-format off // ignore non-significant error/warning codes if(id == 131169 || id == 131185 || id == 131218 || id == 131204) return; std::stringstream ss; ss << "---------------" << "\n"; ss << "Debug message (" << id << "): " << message << "\n"; // clang-format off switch (source) { case GL_DEBUG_SOURCE_API: ss << "Source: API"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: ss << "Source: Window System"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER: ss << "Source: Shader Compiler"; break; case GL_DEBUG_SOURCE_THIRD_PARTY: ss << "Source: Third Party"; break; case GL_DEBUG_SOURCE_APPLICATION: ss << "Source: Application"; break; case GL_DEBUG_SOURCE_OTHER: ss << "Source: Other"; break; } ss << "\n"; switch (type) { case GL_DEBUG_TYPE_ERROR: ss << "Type: Error"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: ss << "Type: Deprecated Behaviour"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: ss << "Type: Undefined Behaviour"; break; case GL_DEBUG_TYPE_PORTABILITY: ss << "Type: Portability"; break; case GL_DEBUG_TYPE_PERFORMANCE: ss << "Type: Performance"; break; case GL_DEBUG_TYPE_MARKER: ss << "Type: Marker"; break; case GL_DEBUG_TYPE_PUSH_GROUP: ss << "Type: Push Group"; break; case GL_DEBUG_TYPE_POP_GROUP: ss << "Type: Pop Group"; break; case GL_DEBUG_TYPE_OTHER: ss << "Type: Other"; break; } ss << "\n"; switch (severity) { case GL_DEBUG_SEVERITY_HIGH: ss << "Severity: high"; break; case GL_DEBUG_SEVERITY_MEDIUM: ss << "Severity: medium"; break; case GL_DEBUG_SEVERITY_LOW: ss << "Severity: low"; break; case GL_DEBUG_SEVERITY_NOTIFICATION: ss << "Severity: notification"; break; } ss << "\n" <<std::endl; // clang-format on spdlog::error(ss.str()); if (severity == GL_DEBUG_SEVERITY_HIGH || severity == GL_DEBUG_SEVERITY_MEDIUM) { spdlog::shutdown(); std::quick_exit(-1); } } #ifndef NDEBUG void DRL::PostCallbackFunc(const char *name, void *funcptr, int len_args, ...) { (void)funcptr; (void)len_args; GLenum errorCode; if ((errorCode = glad_glGetError()) != GL_NO_ERROR) { std::string error; switch (errorCode) { case GL_INVALID_ENUM: error = "INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "INVALID_VALUE"; break; case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: error = "STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: error = "STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break; } spdlog::error("Error happens: {} {}", name, error); } } #endif void Model::loadModel(const fs::path &path) { // read file via ASSIMP Assimp::Importer importer; const aiScene *scene = importer.ReadFile( path.string(), aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); // check for errors if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl; return; } // retrieve the directory path of the filepath directory = fs::absolute(path.parent_path()); // process ASSIMP's root node recursively processNode(scene->mRootNode, scene); } void Model::processNode(aiNode *node, const aiScene *scene) { // process each mesh located at the current node for (unsigned int i = 0; i < node->mNumMeshes; i++) { // the node object only contains indices to index the actual objects in the // scene. the scene contains all the data, node is just to keep stuff // organized (like relations between nodes). aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; meshes.push_back(processMesh(mesh, scene)); } // after we've processed all of the meshes (if any) we then recursively // process each of the children nodes for (unsigned int i = 0; i < node->mNumChildren; i++) { processNode(node->mChildren[i], scene); } } Mesh Model::processMesh(aiMesh *mesh, const aiScene *scene) { // data to fill std::vector<Vertex> vertices; std::vector<unsigned int> indices; std::vector<details::Texture> textures; // walk through each of the mesh's vertices for (unsigned int i = 0; i < mesh->mNumVertices; i++) { Vertex vertex{}; glm::vec3 vector; // we declare a placeholder vector since assimp uses its // own vector class that doesn't directly convert to glm's // vec3 class so we transfer the data to this placeholder // glm::vec3 first. // positions vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; vertex.Position = vector; // normals vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; vertex.Normal = vector; // texture coordinates if (mesh->mTextureCoords[0]) // does the mesh contain texture coordinates? { glm::vec2 vec; // a vertex can contain up to 8 different texture coordinates. We thus // make the assumption that we won't use models where a vertex can have // multiple texture coordinates so we always take the first set (0). vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; vertex.TexCoords = vec; } else vertex.TexCoords = glm::vec2(0.0f, 0.0f); // tangent vector.x = mesh->mTangents[i].x; vector.y = mesh->mTangents[i].y; vector.z = mesh->mTangents[i].z; vertex.Tangent = vector; // bitangent vector.x = mesh->mBitangents[i].x; vector.y = mesh->mBitangents[i].y; vector.z = mesh->mBitangents[i].z; vertex.Bitangent = vector; vertices.push_back(vertex); } // now wak through each of the mesh's faces (a face is a mesh its triangle) // and retrieve the corresponding vertex indices. for (unsigned int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; // retrieve all indices of the face and store them in the indices vector for (unsigned int j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } // process materials aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex]; // we assume a convention for sampler names in the shaders. Each diffuse // texture should be named as 'texture_diffuseN' where N is a sequential // number ranging from 1 to MAX_SAMPLER_NUMBER. Same applies to other texture // as the following list summarizes: diffuse: texture_diffuseN specular: // texture_specularN normal: texture_normalN // 1. diffuse maps auto diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); // 2. specular maps auto specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); // 3. normal maps auto normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal"); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); // 4. height maps auto heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height"); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); // return a mesh object created from the extracted mesh data return Mesh(vertices, indices, textures); } std::vector<details::Texture> Model::loadMaterialTextures(aiMaterial *mat, aiTextureType type, const std::string &typeName) { std::vector<details::Texture> res; for (unsigned int i = 0; i < mat->GetTextureCount(type); i++) { aiString texture_path; mat->GetTexture(type, i, &texture_path); // check if texture was loaded before and if so, continue to next iteration: // skip loading a new texture bool skip = false; std::string texture_path_str(texture_path.C_Str()); if (textures_loaded.find(texture_path_str) != textures_loaded.end()) { res.push_back(textures_loaded[texture_path_str]); skip = true; // a texture with the same filepath has already been } if (!skip) { // if texture hasn't been loaded already, load it details::Texture texture; auto path = directory / texture_path_str; texture.tex_ptr = std::make_shared<DRL::Texture2D>(path, 3, gammaCorrection_, true); texture.tex_ptr->generateMipmap(); texture.type = typeName; // texture.path = str.C_Str(); res.push_back(texture); textures_loaded.emplace(path.string(), texture); // store it as texture loaded for entire model, to ensure we } } return res; } Mesh::Mesh(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices, std::vector<Texture> textures) : textures_(std::move(textures)), indices_nums_(static_cast<int>(indices.size())) { auto vbo = std::make_shared<DRL::VertexBuffer>( vertices.data(), vertices.size() * sizeof(details::Vertex), GL_DYNAMIC_STORAGE_BIT); auto ebo = std::make_shared<DRL::ElementBuffer>( indices.data(), indices.size() * sizeof(unsigned int), GL_DYNAMIC_STORAGE_BIT); vao_.lazy_bind_attrib(0, GL_FLOAT, 3, 0); // vertex vao_.lazy_bind_attrib(1, GL_FLOAT, 3, 3); // normal vao_.lazy_bind_attrib(2, GL_FLOAT, 2, 6); // texcoords vao_.lazy_bind_attrib(3, GL_FLOAT, 3, 8); // tangent vao_.lazy_bind_attrib(4, GL_FLOAT, 3, 11); // bitangent int num_of_elems = sizeof(Vertex) / sizeof(float); int elem_bytes = sizeof(float); vao_.update_bind(vbo, ebo, 0, num_of_elems, elem_bytes); } void Mesh::Draw(const Program &program) { // bind appropriate textures unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; for (unsigned int i = 0; i < textures_.size(); i++) { std::string number; std::string name = textures_[i].type; if (name == "texture_diffuse") number = std::to_string(diffuseNr++); else if (name == "texture_specular") number = std::to_string(specularNr++); // transfer unsigned int to stream else if (name == "texture_normal") number = std::to_string(normalNr++); // transfer unsigned int to stream else if (name == "texture_height") number = std::to_string(heightNr++); // transfer unsigned int to stream // now set the sampler to the correct texture unit // glUniform1i(glGetUniformLocation(program.handle(), (name + // number).c_str()), // i); program.set_uniform(name + number, i); textures_[i].tex_ptr->set_slot(i); textures_[i].tex_ptr->bind(); } { DRL::bind_guard gd(vao_); vao_.draw(GL_TRIANGLES, indices_nums_, GL_UNSIGNED_INT, nullptr); } for (auto &texture : textures_) { texture.tex_ptr->unbind(); } } void Camera::ProcessKeyboard(Camera_Movement direction, float deltaTime) { float velocity = MovementSpeed * deltaTime; if (direction == FORWARD) Position += Front * velocity; if (direction == BACKWARD) Position -= Front * velocity; if (direction == LEFT) Position -= Right * velocity; if (direction == RIGHT) Position += Right * velocity; } void Camera::ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch) { xoffset *= MouseSensitivity; yoffset *= MouseSensitivity; Yaw += xoffset; Pitch += yoffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (Pitch > 89.0f) Pitch = 89.0f; if (Pitch < -89.0f) Pitch = -89.0f; } // Update Front, Right and Up Vectors using the updated Euler angles updateCameraVectors(); } void Camera::ProcessMouseScroll(float yoffset) { if (Zoom >= 1.0f && Zoom <= 45.0f) Zoom -= yoffset; if (Zoom <= 1.0f) Zoom = 1.0f; if (Zoom >= 45.0f) Zoom = 45.0f; } void Camera::updateCameraVectors() { // Calculate the new Front vector glm::vec3 front; front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch)); front.y = sin(glm::radians(Pitch)); front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch)); Front = glm::normalize(front); // Also re-calculate the Right and Up vector Right = glm::normalize(glm::cross( Front, WorldUp)); // Normalize the vectors, because their length gets // closer to 0 the more you look up or down which // results in slower movement. Up = glm::normalize(glm::cross(Right, Front)); } Camera::Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM) { Position = glm::vec3(posX, posY, posZ); WorldUp = glm::vec3(upX, upY, upZ); Yaw = yaw; Pitch = pitch; updateCameraVectors(); } Camera::Camera(glm::vec3 position, glm::vec3 up, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM) { Position = position; WorldUp = up; Yaw = yaw; Pitch = pitch; updateCameraVectors(); } RenderBase::RenderBase() : RenderBase(BaseInfo{}) {} RenderBase::RenderBase(BaseInfo info) : info_(std::move(info)) { InitWindow(); spdlog::info("Root Dir: {}", DRL::ROOT_DIR); spdlog::info("Compiler: {} {}, Build Type: {}", BUILD_COMPILER, CXX_VER, BUILD_TYPE); spdlog::info("System: {} {}, Build UTC Time: {}", BUILD_SYSTEM_NAME, BUILD_SYSTEM_VERSION, BUILD_UTC_TIMESTAMP); } void RenderBase::InitWindow() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, info_.major_version); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, info_.minor_version); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, info_.debug); // glfw window creation // -------------------- GLFWwindow *window = glfwCreateWindow(info_.width, info_.height, info_.title.c_str(), nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); std::quick_exit(-1); } window_ = window; glfwSetWindowUserPointer(window, this); glfwMakeContextCurrent(window); glfwSwapInterval(0); auto resize_cb = [](GLFWwindow *win, int width, int height) { static_cast<RenderBase *>(glfwGetWindowUserPointer(win)) ->on_resize(width, height); }; auto mouse_cb = [](GLFWwindow *win, double xpos, double ypos) { static_cast<RenderBase *>(glfwGetWindowUserPointer(win)) ->on_mouse_move(xpos, ypos); }; auto scroll_cb = [](GLFWwindow *win, double xoffset, double yoffset) { static_cast<RenderBase *>(glfwGetWindowUserPointer(win)) ->on_mouse_scroll(xoffset, yoffset); }; auto key_cb = [](GLFWwindow *win, int key, int scancode, int action, int mods) { static_cast<RenderBase *>(glfwGetWindowUserPointer(win)) ->on_key(key, scancode, action, mods); }; glfwSetFramebufferSizeCallback(window, resize_cb); glfwSetCursorPosCallback(window, mouse_cb); glfwSetKeyCallback(window, key_cb); glfwSetScrollCallback(window, scroll_cb); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; std::quick_exit(-1); } #ifndef NDEBUG if (info_.debug) glad_set_post_callback(DRL::PostCallbackFunc); #endif if (info_.debug) { int flags; glGetIntegerv(GL_CONTEXT_FLAGS, &flags); if (flags & GL_CONTEXT_FLAG_DEBUG_BIT) { glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); // makes sure errors are // displayed synchronously glDebugMessageCallback(DRL::glDebugOutput, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); } } IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO &io = ImGui::GetIO(); (void)io; ImGui::StyleColorsDark(); ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init(info_.glsl_version.c_str()); } RenderBase::~RenderBase() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwTerminate(); } void RenderBase::loop() { AssertLog(bool(camera_), "Camera is uninitialized when loop"); setup_states(); while (!glfwWindowShouldClose(window_)) { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); auto currentFrame = (float)glfwGetTime(); deltaTime_ = currentFrame - lastFrame_; lastFrame_ = currentFrame; render(); processInput(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); glfwSwapBuffers(window_); glfwPollEvents(); } shutdown(); } void RenderBase::on_resize(int width, int height) { glViewport(0, 0, width, height); info_.width = width; info_.height = height; lastX_ = (float)info_.width / 2.0f; lastY_ = (float)info_.height / 2.0f; } void RenderBase::on_key(int key, int scancode, int action, int mods) { (void)mods; if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) { AllowMouseMove_ = !AllowMouseMove_; if (AllowMouseMove_) glfwSetInputMode(window_, GLFW_CURSOR, GLFW_CURSOR_DISABLED); else glfwSetInputMode(window_, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } } void RenderBase::on_mouse_scroll(double xoffset, double yoffset) { (void)xoffset; if (camera_) camera_->ProcessMouseScroll(yoffset); } void RenderBase::on_mouse_move(double xpos, double ypos) { if (!camera_) return; if (AllowMouseMove_) { if (firstMouse_) { lastX_ = xpos; lastY_ = ypos; firstMouse_ = false; } float xoffset = xpos - lastX_; float yoffset = lastY_ - ypos; // reversed since y-coordinates go from bottom to top lastX_ = xpos; lastY_ = ypos; camera_->ProcessMouseMovement(xoffset, yoffset); } else { firstMouse_ = true; } } void RenderBase::processInput() { if (glfwGetKey(window_, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window_, true); if (!camera_) return; // J for speed up // K for speed down if (glfwGetKey(window_, GLFW_KEY_J) == GLFW_PRESS) { camera_->MovementSpeed += 1.0; spdlog::info("Current camera speed:{}", camera_->MovementSpeed); } if (glfwGetKey(window_, GLFW_KEY_K) == GLFW_PRESS) { camera_->MovementSpeed = std::min(camera_->MovementSpeed - 1.0f, 0.0f); spdlog::info("Current camera speed:{}", camera_->MovementSpeed); } if (glfwGetKey(window_, GLFW_KEY_W) == GLFW_PRESS) camera_->ProcessKeyboard(DRL::FORWARD, deltaTime_); if (glfwGetKey(window_, GLFW_KEY_S) == GLFW_PRESS) camera_->ProcessKeyboard(DRL::BACKWARD, deltaTime_); if (glfwGetKey(window_, GLFW_KEY_A) == GLFW_PRESS) camera_->ProcessKeyboard(DRL::LEFT, deltaTime_); if (glfwGetKey(window_, GLFW_KEY_D) == GLFW_PRESS) camera_->ProcessKeyboard(DRL::RIGHT, deltaTime_); }
36.590426
90
0.658235
[ "mesh", "render", "object", "vector", "model" ]
c015c681a3b48b5aaf5f548bfb011c69877dcd5a
1,118
cpp
C++
Problems/CodeChef/Long/Div_2/MARCH20B/G_Partial.Winning_Ways_2.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/CodeChef/Long/Div_2/MARCH20B/G_Partial.Winning_Ways_2.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/CodeChef/Long/Div_2/MARCH20B/G_Partial.Winning_Ways_2.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define maxc 1003 #define maxn 100003 #define mod 998244353 #define pb push_back using namespace std; typedef map<int,int>::iterator mit; int T,n,m; int ar[maxn]; int comb[maxc][maxc]; void precalc() { for( int i = 0 ; i < maxc ; i++ ) comb[i][0] = 1; for( int i = 1 ; i < maxc ; i++ ) for( int j = 1 ; j <= i ; j++ ) comb[i][j] = ( comb[i-1][j] + comb[i-1][j-1] ) % mod; } int main() { precalc(); scanf("%d",&T); for( int tc = 1 ; tc <= T ; tc++ ) { scanf("%d",&n); for( int i = 1 ; i <= n ; i++ ) scanf("%d",&ar[i]); scanf("%d",&m); for( int q = 1 ; q <= m ; q++ ) { int l,r,ans=0,cntXor=0; vector<int> vec; map<int,int> hashh; scanf("%d%d",&l,&r); for( int i = l ; i <= r ; i++ ) hashh[ar[i]]++; for( mit miter = hashh.begin() ; miter != hashh.end() ; miter++ ) { int cnt = miter->second; vec.pb(cnt); cntXor ^= cnt; } for( int i = 0 ; i < (int) vec.size() ; i++ ) { int target = (cntXor ^ vec[i]); if(target < vec[i]) ans = ( ans + comb[vec[i]][target] ) % mod; } printf("%d\n",ans); } } return 0; }
21.921569
70
0.492844
[ "vector" ]
c01781488b485097efe31871ffc2dac3f28483f2
1,731
cpp
C++
code/cpp/hackerrank/stockmax.cpp
unknown1924/my-code-backup
13e52870c91351d37b89b52787e2e315230a921b
[ "Apache-2.0" ]
null
null
null
code/cpp/hackerrank/stockmax.cpp
unknown1924/my-code-backup
13e52870c91351d37b89b52787e2e315230a921b
[ "Apache-2.0" ]
null
null
null
code/cpp/hackerrank/stockmax.cpp
unknown1924/my-code-backup
13e52870c91351d37b89b52787e2e315230a921b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstring> #include <vector> using namespace std; int maxTransacTionReq(vector<int> a){ int res = 0; int n = a.size(); int t[n+1][n+1] = {{0}}; int maxprev = 0; memset(t, 0, sizeof(t)); for(int i = 0; i <= n; i++){ for(int j = 0; j <= n; j++){ cout << t[i][j] << ' ' ; } cout<< endl; } for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ for(int m = 0; m < j; m++){ maxprev = max(maxprev, a[j]-a[m] + t[i-1][m]); } t[i][j] = max(t[i][j-1], maxprev); } cout<< endl; } cout << endl; for(int i = 0; i <= n; i++){ for(int j = 0; j <= n; j++){ cout << t[i][j] << ' ' ; } cout<< endl; } return res; } int maxProfit(vector<int> a){ { int res = 0; int n = a.size(); int t[n+1][n+1] = {{0}}; int maxprev = 0; memset(t, 0, sizeof(t)); for(int i = 0; i <= n; i++){ for(int j = 0; j <= n; j++){ cout << t[i][j] << ' ' ; } cout<< endl; } for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ t[i][j] = max(t[i][j-1],t[i][j]*(i+1) - maxprev); } cout<< endl; } cout << endl; for(int i = 0; i <= n; i++){ for(int j = 0; j <= n; j++){ cout << t[i][j] << ' ' ; } cout<< endl; } return res; } } int main(){ vector<int> a{1,3,1,2}; vector<int> b{1,2,100}; cout << "\nThe max number of Transactions req is: " << endl; //cout << maxTransacTionReq(a) << endl; cout << "\nThe max profit made is: " << endl; cout << maxProfit(a) << endl; }
24.041667
64
0.391103
[ "vector" ]
c0187521609043aae5cb1b6823b2c8aea5663443
13,489
cpp
C++
thirdparty/win/miracl/miracl_osmt/source/curve/pairing/ake24blsa.cpp
namasikanam/MultipartyPSI
57fed04b6cb86b88eeede6f7fb50e9ccd3f84528
[ "Unlicense" ]
419
2016-03-15T18:07:22.000Z
2022-03-31T07:25:20.000Z
aby/src/abycore/util/Miracl/source/curve/pairing/ake24blsa.cpp
huxh10/SGDX
ed93ab5636e9ccc2a15f87572562641604a3cc2b
[ "Apache-2.0" ]
89
2016-05-12T17:29:14.000Z
2022-03-22T15:02:11.000Z
aby/src/abycore/util/Miracl/source/curve/pairing/ake24blsa.cpp
huxh10/SGDX
ed93ab5636e9ccc2a15f87572562641604a3cc2b
[ "Apache-2.0" ]
180
2016-03-15T23:49:25.000Z
2022-03-10T17:41:02.000Z
/* Scott's AKE Client/Server testbed See http://eprint.iacr.org/2002/164 On Windows compile as cl /O2 /GX /DZZNS=10 ake24blsa.cpp zzn24.cpp zzn8.cpp zzn4.cpp zzn2.cpp zzn.cpp ecn.cpp ecn4.cpp big.cpp miracl.lib for 64-bit computer. Change to /DZZNS=20 for 32-bit computer On Linux compile as g++ -O2 -DZZNS=10 ake24blsa.cpp zzn24.cpp zzn8.cpp zzn4.cpp zzn2.cpp zzn.cpp ecn.cpp ecn4.cpp big.cpp miracl.a -o ake24blsa Barreto-Lynn-Scott k=24 Curve - ate pairing The BLS curve generated is generated from an x parameter This version implements the ate pairing (which is optimal in this case) See bls24.cpp for a program to generate suitable bls24 curves Modified to prevent sub-group confinement attack */ #include <iostream> #include <fstream> #include <string.h> #include "ecn.h" #include <ctime> #include "ecn4.h" #include "zzn24.h" using namespace std; #ifdef MR_COUNT_OPS extern "C" { int fpc=0; int fpa=0; int fpx=0; int fpm2=0; int fpi2=0; int fpaq=0; int fpsq=0; int fpmq=0; } #endif #if MIRACL==64 Miracl precision(10,0); #else Miracl precision(20,0); #endif // Using SHA-256 as basic hash algorithm #define HASH_LEN 32 ZZn24 Frobenius(ZZn24 P, ZZn2 &X, int k) { ZZn24 Q=P; for (int i=0; i<k; i++) Q.powq(X); return Q; } // Suitable for p=7 mod 12 void set_frobenius_constant(ZZn2 &X) { Big p=get_modulus(); X.set((Big)1,(Big)1); // p=3 mod 8 X=pow(X,(p-7)/12); } // // Line from A to destination C. Let A=(x,y) // Line Y-slope.X-c=0, through A, so intercept c=y-slope.x // Line Y-slope.X-y+slope.x = (Y-y)-slope.(X-x) = 0 // Now evaluate at Q -> return (Qy-y)-slope.(Qx-x) // ZZn24 line(ECn4& A,ECn4& C,ZZn4& slope,ZZn& Qx,ZZn& Qy) { ZZn24 w; ZZn8 nn,dd; ZZn4 X,Y; A.get(X,Y); nn.set((ZZn4)-Qy,Y-slope*X); dd.set(slope*Qx); w.set(nn,dd); return w; } // // Add A=A+B (or A=A+A) // Return line function value // ZZn24 g(ECn4& A,ECn4& B,ZZn& Qx,ZZn& Qy) { ZZn4 lam; ZZn24 r; ECn4 P=A; // Evaluate line from A A.add(B,lam); if (A.iszero()) return (ZZn24)1; r=line(P,A,lam,Qx,Qy); return r; } // // This calculates p.A = (X^p,Y^p) quickly using Frobenius // 1. Extract A(x,y) from twisted curve to point on curve over full extension, as X=i^2.x and Y=i^3.y // where i=NR^(1/k) // 2. Using Frobenius calculate (X^p,Y^p) // 3. map back to twisted curve // Here we simplify things by doing whole calculation on the twisted curve // // Note we have to be careful as in detail it depends on w where p=w mod k // Its simplest if w=1. // ECn4 psi(ECn4 &A,ZZn2 &F,int n) { int i; ECn4 R; ZZn4 X,Y; ZZn2 FF,W; // Fast multiplication of A by q^n A.get(X,Y); FF=F*F; W=txx(txx(txx(FF*FF*FF))); for (i=0;i<n;i++) { // assumes p=7 mod 12 X.powq(W); X=tx(tx(FF*X)); Y.powq(W); Y=tx(tx(tx(FF*F*Y))); } R.set(X,Y); return R; } // Automatically generated by Luis Dominguez ZZn24 HardExpo(ZZn24 &f3x0, ZZn2 &X, Big &x){ //vector=[ 1, 2, 3 ] ZZn24 r; ZZn24 xA; ZZn24 xB; ZZn24 t0; ZZn24 t1; ZZn24 f3x1; ZZn24 f3x2; ZZn24 f3x3; ZZn24 f3x4; ZZn24 f3x5; ZZn24 f3x6; ZZn24 f3x7; ZZn24 f3x8; ZZn24 f3x9; f3x1=pow(f3x0,x); f3x2=pow(f3x1,x); f3x3=pow(f3x2,x); f3x4=pow(f3x3,x); f3x5=pow(f3x4,x); f3x6=pow(f3x5,x); f3x7=pow(f3x6,x); f3x8=pow(f3x7,x); f3x9=pow(f3x8,x); xA=f3x4*inverse(f3x8)*Frobenius(f3x3,X,1)*Frobenius(inverse(f3x7),X,1)*Frobenius(f3x2,X,2)*Frobenius(inverse(f3x6),X,2)*Frobenius(f3x1,X,3)*Frobenius(inverse(f3x5),X,3)*Frobenius(inverse(f3x4),X,4)*Frobenius(inverse(f3x3),X,5)*Frobenius(inverse(f3x2),X,6)*Frobenius(inverse(f3x1),X,7); xB=f3x0; t0=xA*xB; xA=inverse(f3x3)*inverse(f3x5)*f3x7*f3x9*Frobenius(inverse(f3x2),X,1)*Frobenius(inverse(f3x4),X,1)*Frobenius(f3x6,X,1)*Frobenius(f3x8,X,1)*Frobenius(inverse(f3x1),X,2)*Frobenius(inverse(f3x3),X,2)*Frobenius(f3x5,X,2)*Frobenius(f3x7,X,2)*Frobenius(inverse(f3x0),X,3)*Frobenius(inverse(f3x2),X,3)*Frobenius(f3x4,X,3)*Frobenius(f3x6,X,3)*Frobenius(f3x3,X,4)*Frobenius(f3x5,X,4)*Frobenius(f3x2,X,5)*Frobenius(f3x4,X,5)*Frobenius(f3x1,X,6)*Frobenius(f3x3,X,6)*Frobenius(f3x0,X,7)*Frobenius(f3x2,X,7); xB=f3x0; t1=xA*xB; t0=t0*t0; t0=t0*t1; r=t0; return r; } void SoftExpo(ZZn24 &f3, ZZn2 &X){ ZZn24 t0; int i; t0=f3; f3.conj(); f3/=t0; f3.mark_as_regular(); t0=f3; for (i=1;i<=4;i++) f3.powq(X); f3*=t0; f3.mark_as_unitary(); } // // R-ate Pairing - note denominator elimination has been applied // // P is a point of order q. Q(x,y) is a point of order q. // Note that P is a point on the sextic twist of the curve over Fp^2, Q(x,y) is a point on the // curve over the base field Fp // BOOL fast_pairing(ECn4& P,ZZn& Qx,ZZn& Qy,Big &x,ZZn2 &X,ZZn24& r) { ECn4 A; Big n; int i,nb; #ifdef MR_COUNT_OPS fpc=fpa=fpx=0; #endif n=x; // t-1 A=P; // remember A nb=bits(n); r=1; r.mark_as_miller(); //fpc=fpa=fpx=0; for (i=nb-2;i>=0;i--) { r*=r; r*=g(A,A,Qx,Qy); if (bit(n,i)) r*=g(A,P,Qx,Qy); } if (r.iszero()) return FALSE; #ifdef MR_COUNT_OPS cout << "Miller fpc= " << fpc << endl; cout << "Miller fpa= " << fpa << endl; cout << "Miller fpx= " << fpx << endl; fpa=fpc=fpx=0; #endif SoftExpo(r,X); r=HardExpo(r,X,x); #ifdef MR_COUNT_OPS cout << "FE fpc= " << fpc << endl; cout << "FE fpa= " << fpa << endl; cout << "FE fpx= " << fpx << endl; fpa=fpc=fpx=0; #endif return TRUE; } // // ecap(.) function // BOOL ecap(ECn4& P,ECn& Q,Big& x,ZZn2 &X,ZZn24& r) { BOOL Ok; Big xx,yy; ZZn Qx,Qy; Q.get(xx,yy); Qx=xx; Qy=yy; Ok=fast_pairing(P,Qx,Qy,x,X,r); if (Ok) return TRUE; return FALSE; } // Automatically generated by Luis Dominguez ECn4 HashG2(ECn4& Qx0, Big& x, ZZn2& X){ //vector=[ 1, 2, 3, 4 ] ECn4 r; ECn4 xA; ECn4 xB; ECn4 xC; ECn4 t0; ECn4 t1; ECn4 Qx0_; ECn4 Qx1; ECn4 Qx1_; ECn4 Qx2; ECn4 Qx2_; ECn4 Qx3; ECn4 Qx3_; ECn4 Qx4; ECn4 Qx4_; ECn4 Qx5; ECn4 Qx5_; ECn4 Qx6; ECn4 Qx6_; ECn4 Qx7; ECn4 Qx7_; ECn4 Qx8; ECn4 Qx8_; Qx0_=-(Qx0); Qx1=x*Qx0; Qx1_=-(Qx1); Qx2=x*Qx1; Qx2_=-(Qx2); Qx3=x*Qx2; Qx3_=-(Qx3); Qx4=x*Qx3; Qx4_=-(Qx4); Qx5=x*Qx4; Qx5_=-(Qx5); Qx6=x*Qx5; Qx6_=-(Qx6); Qx7=x*Qx6; Qx7_=-(Qx7); Qx8=x*Qx7; Qx8_=-(Qx8); xA=Qx0; xC=Qx7; xA+=xC; xC=psi(Qx2,X,4); xA+=xC; xB=Qx0; xC=Qx7; xB+=xC; xC=psi(Qx2,X,4); xB+=xC; t0=xA+xB; xB=Qx2_; xC=Qx3_; xB+=xC; xC=Qx8_; xB+=xC; xC=psi(Qx2,X,1); xB+=xC; xC=psi(Qx3_,X,1); xB+=xC; xC=psi(Qx1,X,6); xB+=xC; t0=t0+xB; xB=Qx4; xC=Qx5_; xB+=xC; xC=psi(Qx0_,X,4); xB+=xC; xC=psi(Qx4_,X,4); xB+=xC; xC=psi(Qx0,X,5); xB+=xC; xC=psi(Qx1_,X,5); xB+=xC; xC=psi(Qx2_,X,5); xB+=xC; xC=psi(Qx3,X,5); xB+=xC; t0=t0+xB; xA=Qx1; xC=psi(Qx0_,X,1); xA+=xC; xC=psi(Qx1,X,1); xA+=xC; xC=psi(Qx4_,X,1); xA+=xC; xC=psi(Qx5,X,1); xA+=xC; xC=psi(Qx0,X,2); xA+=xC; xC=psi(Qx1_,X,2); xA+=xC; xC=psi(Qx4_,X,2); xA+=xC; xC=psi(Qx5,X,2); xA+=xC; xC=psi(Qx0,X,3); xA+=xC; xC=psi(Qx1_,X,3); xA+=xC; xC=psi(Qx4_,X,3); xA+=xC; xC=psi(Qx5,X,3); xA+=xC; xC=psi(Qx1,X,4); xA+=xC; xC=psi(Qx3,X,4); xA+=xC; xC=psi(Qx0_,X,6); xA+=xC; xC=psi(Qx2_,X,6); xA+=xC; xB=Qx4; xC=Qx5_; xB+=xC; xC=psi(Qx0_,X,4); xB+=xC; xC=psi(Qx4_,X,4); xB+=xC; xC=psi(Qx0,X,5); xB+=xC; xC=psi(Qx1_,X,5); xB+=xC; xC=psi(Qx2_,X,5); xB+=xC; xC=psi(Qx3,X,5); xB+=xC; t1=xA+xB; t0=t0+t0; t0=t0+t1; r=t0; return r; } // // Hash functions // Big H2(ZZn24 x) { // Compress and hash an Fp24 to a big number sha256 sh; ZZn8 u; ZZn4 h,l; ZZn2 t,b; Big a,hash,p; ZZn xx[8]; char s[HASH_LEN]; int i,j,m; shs256_init(&sh); x.get(u); // compress to single ZZn4 u.get(l,h); l.get(t,b); t.get(xx[0],xx[1]); b.get(xx[2],xx[3]); h.get(t,b); t.get(xx[4],xx[5]); b.get(xx[6],xx[7]); for (i=0;i<8;i++) { a=(Big)xx[i]; while (a>0) { m=a%256; shs256_process(&sh,m); a/=256; } } shs256_hash(&sh,s); hash=from_binary(HASH_LEN,s); return hash; } Big H1(char *string) { // Hash a zero-terminated string to a number < modulus Big h,p; char s[HASH_LEN]; int i,j; sha256 sh; shs256_init(&sh); for (i=0;;i++) { if (string[i]==0) break; shs256_process(&sh,string[i]); } shs256_hash(&sh,s); p=get_modulus(); h=1; j=0; i=1; forever { h*=256; if (j==HASH_LEN) {h+=i++; j=0;} else h+=s[j++]; if (h>=p) break; } h%=p; return h; } // Hash and map a Server Identity to a curve point E_(Fp4) ECn4 hash_and_map4(char *ID) { int i; ECn4 S; ZZn4 X; ZZn2 t; Big x0=H1(ID); forever { x0+=1; t.set((ZZn)0,(ZZn)x0); X.set(t,(ZZn2)0); if (!S.set(X)) continue; break; } return S; } // Hash and Map a Client Identity to a curve point E_(Fp) of order q ECn hash_and_map(char *ID,Big cf) { ECn Q; Big x0=H1(ID); while (!Q.set(x0,x0)) x0+=1; Q*=cf; return Q; } void endomorph(ECn &A,ZZn &Beta) { // apply endomorphism P(x,y) = (Beta*x,y) where Beta is cube root of unity // Actually (Beta*x,-y) = x^4.P ZZn x,y; x=(A.get_point())->X; y=(A.get_point())->Y; y=-y; x*=Beta; copy(getbig(x),(A.get_point())->X); copy(getbig(y),(A.get_point())->Y); } // Use GLV endomorphism idea for multiplication in G1. ECn G1_mult(ECn &P,Big &e,Big &x,ZZn &Beta) { // return e*P; int i; ECn Q; Big x4,u[2]; x4=x*x; x4*=x4; u[0]=e%x4; u[1]=e/x4; Q=P; endomorph(Q,Beta); Q=mul(u[0],P,u[1],Q); return Q; } //.. for multiplication in G2 ECn4 G2_mult(ECn4 &P,Big e,Big &x,ZZn2 &X) { // return e*P; int i; ECn4 Q[8]; Big u[8]; for (i=0;i<8;i++) {u[i]=e%x; e/=x;} Q[0]=P; for (i=1;i<8;i++) Q[i]=psi(Q[i-1],X,1); // simple multi-addition return mul(8,Q,u); } //.. and for exponentiation in GT ZZn24 GT_pow(ZZn24 &res,Big e,Big &x,ZZn2 &X) { // return pow(res,e); int i,j; ZZn24 Y[8]; Big u[8]; for (i=0;i<8;i++) {u[i]=e%x; e/=x;} Y[0]=res; for (i=1;i<8;i++) {Y[i]=Y[i-1]; Y[i].powq(X);} // simple multi-exponentiation return pow(8,Y,u); } // Fast group membership check for GT // check if r is of order q // Test r^q=r^{(p+1-t)/cf}= 1 // so test r^p=r^x and r^cf !=1 // exploit cf=(x-1)*(x-1)/3 BOOL member(ZZn24 &r,Big &x,ZZn2 &X) { ZZn24 w=r; ZZn24 rx; if (r*conj(r)!=(ZZn24)1) return FALSE; // not unitary w.powq(X); rx=pow(r,x); if (w!=rx) return FALSE; if (r*pow(rx,x)==rx*rx) return FALSE; return TRUE; } int main() { miracl* mip=&precision; ZZn2 X; ECn Alice,Bob,sA,sB; ECn4 Server,sS; ZZn24 sp,ap,bp,res; Big a,b,s,ss,p,q,x,y,B,cf,t,n; ZZn Beta; int i; time_t seed; mip->IOBASE=16; x="E000000000058400"; // low Hamming weight = 7 t=1+x; p=(1+x+x*x-pow(x,4)+2*pow(x,5)-pow(x,6)+pow(x,8)-2*pow(x,9)+pow(x,10))/3; q=1-pow(x,4)+pow(x,8); n=p+1-t; cf=(x-1)*(x-1)/3; //=n/q cf=(x-1); // Neat trick! Whole group is non-cyclic - just has (x-1)^2 as a factor // So multiplication by x-1 is sufficient to create a point of order q ecurve((Big)0,(Big)6,p,MR_AFFINE); set_frobenius_constant(X); Beta=pow((ZZn)2,(p-1)/3); Beta*=Beta; // right cube root of unity time(&seed); irand((long)seed); ss=rand(q); // TA's super-secret mip->TWIST=MR_SEXTIC_D; // map Server to point on twisted curve E(Fp4) Server=hash_and_map4((char *)"Server"); Server=HashG2(Server,x,X); // fast multiplication by co-factor // Should be point at infinity // cout << "psi^2(Server-t*psi(Server)+p*Server= " << psi(Server,X,2)-t*psi(Server,X,1)+p*Server << endl; Alice=hash_and_map((char *)"Alice",cf); Bob= hash_and_map((char *)"Robert",cf); cout << "Alice, Bob and the Server visit Trusted Authority" << endl; sS=G2_mult(Server,ss,x,X); sA=G1_mult(Alice,ss,x,Beta); sB=G1_mult(Bob,ss,x,Beta); cout << "Alice and Server Key Exchange" << endl; a=rand(q); // Alice's random number s=rand(q); // Server's random number if (!ecap(Server,sA,x,X,res)) cout << "Trouble" << endl; if (!member(res,x,X)) { cout << "Wrong group order - aborting" << endl; exit(0); } ap=GT_pow(res,a,x,X); if (!ecap(sS,Alice,x,X,res)) cout << "Trouble" << endl; if (!member(res,x,X)) { cout << "Wrong group order - aborting" << endl; exit(0); } sp=GT_pow(res,s,x,X); cout << "Alice Key= " << H2(GT_pow(sp,a,x,X)) << endl; cout << "Server Key= " << H2(GT_pow(ap,s,x,X)) << endl; cout << "Bob and Server Key Exchange" << endl; b=rand(q); // Bob's random number s=rand(q); // Server's random number if (!ecap(Server,sB,x,X,res)) cout << "Trouble" << endl; if (!member(res,x,X)) { cout << "Wrong group order - aborting" << endl; exit(0); } bp=GT_pow(res,b,x,X); if (!ecap(sS,Bob,x,X,res)) cout << "Trouble" << endl; if (!member(res,x,X)) { cout << "Wrong group order - aborting" << endl; exit(0); } sp=GT_pow(res,s,x,X); cout << "Bob's Key= " << H2(GT_pow(sp,b,x,X)) << endl; cout << "Server Key= " << H2(GT_pow(bp,s,x,X)) << endl; return 0; }
18.945225
497
0.572244
[ "vector" ]
c01ca3469a0f7eb8bb4be8d56ef98da373a06390
8,767
cc
C++
src/envir/fileoutscalarmgr.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
15
2021-08-20T08:10:01.000Z
2022-03-24T21:24:50.000Z
src/envir/fileoutscalarmgr.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
1
2022-03-30T09:03:39.000Z
2022-03-30T09:03:39.000Z
src/envir/fileoutscalarmgr.cc
eniac/parallel-inet-omnet
810ed40aecac89efbd0b6a05ee10f44a09417178
[ "Xnet", "X11" ]
3
2021-08-20T08:10:34.000Z
2021-12-02T06:15:02.000Z
//========================================================================== // FILEOUTPUTSCALARMGR.CC - part of // OMNeT++/OMNEST // Discrete System Simulation in C++ // // Author: Andras Varga // //========================================================================== /*--------------------------------------------------------------* Copyright (C) 1992-2008 Andras Varga Copyright (C) 2006-2008 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #include "simkerneldefs.h" #include <assert.h> #include <string.h> #include <fstream> #include <locale.h> #include "opp_ctype.h" #include "cconfigoption.h" #include "fileutil.h" #include "envirbase.h" #include "csimulation.h" #include "cmodule.h" #include "cstatistic.h" #include "cdensityestbase.h" #include "fileoutscalarmgr.h" #include "ccomponenttype.h" #include "stringutil.h" #include "unitconversion.h" NAMESPACE_BEGIN #define SCALAR_FILE_VERSION 2 #define DEFAULT_PRECISION "14" Register_PerRunConfigOption(CFGID_OUTPUT_SCALAR_FILE, "output-scalar-file", CFG_FILENAME, "${resultdir}/${configname}-${runnumber}.sca", "Name for the output scalar file."); Register_PerRunConfigOption(CFGID_OUTPUT_SCALAR_PRECISION, "output-scalar-precision", CFG_INT, DEFAULT_PRECISION, "The number of significant digits for recording data into the output scalar file. The maximum value is ~15 (IEEE double precision)."); Register_PerRunConfigOption(CFGID_OUTPUT_SCALAR_FILE_APPEND, "output-scalar-file-append", CFG_BOOL, "false", "What to do when the output scalar file already exists: append to it (OMNeT++ 3.x behavior), or delete it and begin a new file (default)."); Register_PerObjectConfigOption(CFGID_SCALAR_RECORDING, "scalar-recording", KIND_SCALAR, CFG_BOOL, "true", "Whether the matching output scalars should be recorded. Syntax: <module-full-path>.<scalar-name>.scalar-recording=true/false. Example: **.queue.packetsDropped.scalar-recording=true"); Register_Class(cFileOutputScalarManager); #ifdef CHECK #undef CHECK #endif #define CHECK(fprintf) if (fprintf<0) throw cRuntimeError("Cannot write output scalar file `%s'", fname.c_str()) cFileOutputScalarManager::cFileOutputScalarManager() { f = NULL; prec = ev.getConfig()->getAsInt(CFGID_OUTPUT_SCALAR_PRECISION); } cFileOutputScalarManager::~cFileOutputScalarManager() { closeFile(); } void cFileOutputScalarManager::openFile() { mkPath(directoryOf(fname.c_str()).c_str()); f = fopen(fname.c_str(),"a"); if (f==NULL) throw cRuntimeError("Cannot open output scalar file `%s'", fname.c_str()); } void cFileOutputScalarManager::closeFile() { if (f) { fclose(f); f = NULL; } } void cFileOutputScalarManager::startRun() { // clean up file from previous runs closeFile(); fname = ev.getConfig()->getAsFilename(CFGID_OUTPUT_SCALAR_FILE).c_str(); dynamic_cast<EnvirBase *>(&ev)->processFileName(fname); if (ev.getConfig()->getAsBool(CFGID_OUTPUT_SCALAR_FILE_APPEND)==false) removeFile(fname.c_str(), "old output scalar file"); run.reset(); } void cFileOutputScalarManager::endRun() { closeFile(); } void cFileOutputScalarManager::init() { if (!f) { openFile(); if (!f) return; CHECK(fprintf(f, "version %d\n", SCALAR_FILE_VERSION)); } if (!run.initialized) { run.initRun(); // this is the first scalar written in this run, write out run attributes run.writeRunData(f, fname); // save iteration variables std::vector<const char *> v = ev.getConfigEx()->getIterationVariableNames(); for (int i=0; i<(int)v.size(); i++) { const char *name = v[i]; const char *value = ev.getConfigEx()->getVariable(v[i]); recordNumericIterationVariable(name, value); } } } void cFileOutputScalarManager::recordNumericIterationVariable(const char *name, const char *value) { char *e; setlocale(LC_NUMERIC, "C"); (void) strtod(value, &e); if (*e=='\0') { // plain number - just record as it is //XXX write with using an "itervar" keyword not "scalar" (needs to be understood by IDE as well) CHECK(fprintf(f, "scalar . \t%s \t%s\n", name, value)); } else if (e!=value) { // starts with a number, so it might be something like "100s"; if so, record it as scalar with "unit" attribute double d; std::string unit; bool parsedOK = false; try { d = UnitConversion::parseQuantity(value, unit); parsedOK = true; } catch (std::exception& e) { } if (parsedOK) { CHECK(fprintf(f, "scalar . \t%s \t%.*g\n", name, prec, d)); if (!unit.empty()) CHECK(fprintf(f,"attr unit %s\n", QUOTE(unit.c_str()))); } } } void cFileOutputScalarManager::recordScalar(cComponent *component, const char *name, double value, opp_string_map *attributes) { if (!run.initialized) init(); if (!f) return; if (!name || !name[0]) name = "(unnamed)"; bool enabled = ev.getConfig()->getAsBool((component->getFullPath()+"."+name).c_str(), CFGID_SCALAR_RECORDING); if (enabled) { CHECK(fprintf(f, "scalar %s \t%s \t%.*g\n", QUOTE(component->getFullPath().c_str()), QUOTE(name), prec, value)); if (attributes) for (opp_string_map::iterator it=attributes->begin(); it!=attributes->end(); it++) CHECK(fprintf(f,"attr %s %s\n", QUOTE(it->first.c_str()), QUOTE(it->second.c_str()))); } } void cFileOutputScalarManager::recordStatistic(cComponent *component, const char *name, cStatistic *statistic, opp_string_map *attributes) { if (!run.initialized) init(); if (!f) return; if (!name) name = statistic->getFullName(); if (!name || !name[0]) name = "(unnamed)"; // check that recording this statistic is not disabled as a whole std::string objectFullPath = component->getFullPath() + "." + name; bool enabled = ev.getConfig()->getAsBool(objectFullPath.c_str(), CFGID_SCALAR_RECORDING); if (!enabled) return; // file format: // statistic <modulepath> <statisticname> // field count 343 // field weights 343 // field mean 2.1233 // field stddev 1.345 // attr unit s // bin 0 3 // bin 10 13 // bin 20 19 // ... // In Scave, fields are read as separate scalars. CHECK(fprintf(f, "statistic %s \t%s\n", QUOTE(component->getFullPath().c_str()), QUOTE(name))); writeStatisticField("count", statistic->getCount()); writeStatisticField("mean", statistic->getMean()); writeStatisticField("stddev", statistic->getStddev()); writeStatisticField("sum", statistic->getSum()); writeStatisticField("sqrsum", statistic->getSqrSum()); writeStatisticField("min", statistic->getMin()); writeStatisticField("max", statistic->getMax()); if (statistic->isWeighted()) { writeStatisticField("weights", statistic->getWeights()); writeStatisticField("weightedSum", statistic->getWeightedSum()); writeStatisticField("sqrSumWeights", statistic->getSqrSumWeights()); writeStatisticField("weightedSqrSum", statistic->getWeightedSqrSum()); } if (attributes) for (opp_string_map::iterator it=attributes->begin(); it!=attributes->end(); it++) CHECK(fprintf(f,"attr %s %s\n", QUOTE(it->first.c_str()), QUOTE(it->second.c_str()))); if (dynamic_cast<cDensityEstBase *>(statistic)) { // check that recording the histogram is enabled bool enabled = ev.getConfig()->getAsBool((objectFullPath+":histogram").c_str(), CFGID_SCALAR_RECORDING); if (enabled) { cDensityEstBase *hist = (cDensityEstBase *)statistic; if (!hist->isTransformed()) hist->transform(); int n = hist->getNumCells(); if (n>0) { CHECK(fprintf(f, "bin\t-INF\t%lu\n", hist->getUnderflowCell())); for (int i=0; i<n; i++) CHECK(fprintf(f, "bin\t%.*g\t%.*g\n", prec, hist->getBasepoint(i), prec, hist->getCellValue(i))); CHECK(fprintf(f, "bin\t%.*g\t%lu\n", prec, hist->getBasepoint(n), hist->getOverflowCell())); } } } } const char *cFileOutputScalarManager::getFileName() const { return fname.c_str(); } void cFileOutputScalarManager::flush() { if (f) fflush(f); } NAMESPACE_END
33.208333
290
0.617771
[ "vector", "transform" ]
c01f29bef59591c7e6a8a8d163b2c7e37fbd7d26
16,155
cc
C++
pc/srtpfilter.cc
Aexyn/webrtc2
daea5bf2deb843567a792f22ea2047a037e09d78
[ "DOC", "BSD-3-Clause" ]
2
2018-01-16T13:29:45.000Z
2018-08-10T09:15:23.000Z
pc/srtpfilter.cc
Aexyn/webrtc2
daea5bf2deb843567a792f22ea2047a037e09d78
[ "DOC", "BSD-3-Clause" ]
null
null
null
pc/srtpfilter.cc
Aexyn/webrtc2
daea5bf2deb843567a792f22ea2047a037e09d78
[ "DOC", "BSD-3-Clause" ]
null
null
null
/* * Copyright 2009 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "pc/srtpfilter.h" #include <string.h> #include <algorithm> #include "media/base/rtputils.h" #include "pc/srtpsession.h" #include "rtc_base/base64.h" #include "rtc_base/buffer.h" #include "rtc_base/byteorder.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/stringencode.h" #include "rtc_base/timeutils.h" namespace cricket { // NOTE: This is called from ChannelManager D'tor. void ShutdownSrtp() { // If srtp_dealloc is not executed then this will clear all existing sessions. // This should be called when application is shutting down. SrtpSession::Terminate(); } SrtpFilter::SrtpFilter() { } SrtpFilter::~SrtpFilter() { } bool SrtpFilter::IsActive() const { return state_ >= ST_ACTIVE; } bool SrtpFilter::SetOffer(const std::vector<CryptoParams>& offer_params, ContentSource source) { if (!ExpectOffer(source)) { LOG(LS_ERROR) << "Wrong state to update SRTP offer"; return false; } return StoreParams(offer_params, source); } bool SrtpFilter::SetAnswer(const std::vector<CryptoParams>& answer_params, ContentSource source) { return DoSetAnswer(answer_params, source, true); } bool SrtpFilter::SetProvisionalAnswer( const std::vector<CryptoParams>& answer_params, ContentSource source) { return DoSetAnswer(answer_params, source, false); } bool SrtpFilter::SetRtpParams(int send_cs, const uint8_t* send_key, int send_key_len, int recv_cs, const uint8_t* recv_key, int recv_key_len) { if (IsActive()) { LOG(LS_ERROR) << "Tried to set SRTP Params when filter already active"; return false; } CreateSrtpSessions(); send_session_->SetEncryptedHeaderExtensionIds( send_encrypted_header_extension_ids_); if (!send_session_->SetSend(send_cs, send_key, send_key_len)) { return false; } recv_session_->SetEncryptedHeaderExtensionIds( recv_encrypted_header_extension_ids_); if (!recv_session_->SetRecv(recv_cs, recv_key, recv_key_len)) { return false; } state_ = ST_ACTIVE; LOG(LS_INFO) << "SRTP activated with negotiated parameters:" << " send cipher_suite " << send_cs << " recv cipher_suite " << recv_cs; return true; } bool SrtpFilter::UpdateRtpParams(int send_cs, const uint8_t* send_key, int send_key_len, int recv_cs, const uint8_t* recv_key, int recv_key_len) { if (!IsActive()) { LOG(LS_ERROR) << "Tried to update SRTP Params when filter is not active"; return false; } send_session_->SetEncryptedHeaderExtensionIds( send_encrypted_header_extension_ids_); if (!send_session_->UpdateSend(send_cs, send_key, send_key_len)) { return false; } recv_session_->SetEncryptedHeaderExtensionIds( recv_encrypted_header_extension_ids_); if (!recv_session_->UpdateRecv(recv_cs, recv_key, recv_key_len)) { return false; } LOG(LS_INFO) << "SRTP updated with negotiated parameters:" << " send cipher_suite " << send_cs << " recv cipher_suite " << recv_cs; return true; } // This function is provided separately because DTLS-SRTP behaves // differently in RTP/RTCP mux and non-mux modes. // // - In the non-muxed case, RTP and RTCP are keyed with different // keys (from different DTLS handshakes), and so we need a new // SrtpSession. // - In the muxed case, they are keyed with the same keys, so // this function is not needed bool SrtpFilter::SetRtcpParams(int send_cs, const uint8_t* send_key, int send_key_len, int recv_cs, const uint8_t* recv_key, int recv_key_len) { // This can only be called once, but can be safely called after // SetRtpParams if (send_rtcp_session_ || recv_rtcp_session_) { LOG(LS_ERROR) << "Tried to set SRTCP Params when filter already active"; return false; } send_rtcp_session_.reset(new SrtpSession()); if (!send_rtcp_session_->SetRecv(send_cs, send_key, send_key_len)) { return false; } recv_rtcp_session_.reset(new SrtpSession()); if (!recv_rtcp_session_->SetRecv(recv_cs, recv_key, recv_key_len)) { return false; } LOG(LS_INFO) << "SRTCP activated with negotiated parameters:" << " send cipher_suite " << send_cs << " recv cipher_suite " << recv_cs; return true; } bool SrtpFilter::ProtectRtp(void* p, int in_len, int max_len, int* out_len) { if (!IsActive()) { LOG(LS_WARNING) << "Failed to ProtectRtp: SRTP not active"; return false; } RTC_CHECK(send_session_); return send_session_->ProtectRtp(p, in_len, max_len, out_len); } bool SrtpFilter::ProtectRtp(void* p, int in_len, int max_len, int* out_len, int64_t* index) { if (!IsActive()) { LOG(LS_WARNING) << "Failed to ProtectRtp: SRTP not active"; return false; } RTC_CHECK(send_session_); return send_session_->ProtectRtp(p, in_len, max_len, out_len, index); } bool SrtpFilter::ProtectRtcp(void* p, int in_len, int max_len, int* out_len) { if (!IsActive()) { LOG(LS_WARNING) << "Failed to ProtectRtcp: SRTP not active"; return false; } if (send_rtcp_session_) { return send_rtcp_session_->ProtectRtcp(p, in_len, max_len, out_len); } else { RTC_CHECK(send_session_); return send_session_->ProtectRtcp(p, in_len, max_len, out_len); } } bool SrtpFilter::UnprotectRtp(void* p, int in_len, int* out_len) { if (!IsActive()) { LOG(LS_WARNING) << "Failed to UnprotectRtp: SRTP not active"; return false; } RTC_CHECK(recv_session_); return recv_session_->UnprotectRtp(p, in_len, out_len); } bool SrtpFilter::UnprotectRtcp(void* p, int in_len, int* out_len) { if (!IsActive()) { LOG(LS_WARNING) << "Failed to UnprotectRtcp: SRTP not active"; return false; } if (recv_rtcp_session_) { return recv_rtcp_session_->UnprotectRtcp(p, in_len, out_len); } else { RTC_CHECK(recv_session_); return recv_session_->UnprotectRtcp(p, in_len, out_len); } } bool SrtpFilter::GetRtpAuthParams(uint8_t** key, int* key_len, int* tag_len) { if (!IsActive()) { LOG(LS_WARNING) << "Failed to GetRtpAuthParams: SRTP not active"; return false; } RTC_CHECK(send_session_); return send_session_->GetRtpAuthParams(key, key_len, tag_len); } bool SrtpFilter::GetSrtpOverhead(int* srtp_overhead) const { if (!IsActive()) { LOG(LS_WARNING) << "Failed to GetSrtpOverhead: SRTP not active"; return false; } RTC_CHECK(send_session_); *srtp_overhead = send_session_->GetSrtpOverhead(); return true; } void SrtpFilter::EnableExternalAuth() { RTC_DCHECK(!IsActive()); external_auth_enabled_ = true; } bool SrtpFilter::IsExternalAuthEnabled() const { return external_auth_enabled_; } bool SrtpFilter::IsExternalAuthActive() const { if (!IsActive()) { LOG(LS_WARNING) << "Failed to check IsExternalAuthActive: SRTP not active"; return false; } RTC_CHECK(send_session_); return send_session_->IsExternalAuthActive(); } void SrtpFilter::SetEncryptedHeaderExtensionIds( ContentSource source, const std::vector<int>& extension_ids) { if (source == CS_LOCAL) { recv_encrypted_header_extension_ids_ = extension_ids; } else { send_encrypted_header_extension_ids_ = extension_ids; } } bool SrtpFilter::ExpectOffer(ContentSource source) { return ((state_ == ST_INIT) || (state_ == ST_ACTIVE) || (state_ == ST_SENTOFFER && source == CS_LOCAL) || (state_ == ST_SENTUPDATEDOFFER && source == CS_LOCAL) || (state_ == ST_RECEIVEDOFFER && source == CS_REMOTE) || (state_ == ST_RECEIVEDUPDATEDOFFER && source == CS_REMOTE)); } bool SrtpFilter::StoreParams(const std::vector<CryptoParams>& params, ContentSource source) { offer_params_ = params; if (state_ == ST_INIT) { state_ = (source == CS_LOCAL) ? ST_SENTOFFER : ST_RECEIVEDOFFER; } else if (state_ == ST_ACTIVE) { state_ = (source == CS_LOCAL) ? ST_SENTUPDATEDOFFER : ST_RECEIVEDUPDATEDOFFER; } return true; } bool SrtpFilter::ExpectAnswer(ContentSource source) { return ((state_ == ST_SENTOFFER && source == CS_REMOTE) || (state_ == ST_RECEIVEDOFFER && source == CS_LOCAL) || (state_ == ST_SENTUPDATEDOFFER && source == CS_REMOTE) || (state_ == ST_RECEIVEDUPDATEDOFFER && source == CS_LOCAL) || (state_ == ST_SENTPRANSWER_NO_CRYPTO && source == CS_LOCAL) || (state_ == ST_SENTPRANSWER && source == CS_LOCAL) || (state_ == ST_RECEIVEDPRANSWER_NO_CRYPTO && source == CS_REMOTE) || (state_ == ST_RECEIVEDPRANSWER && source == CS_REMOTE)); } bool SrtpFilter::DoSetAnswer(const std::vector<CryptoParams>& answer_params, ContentSource source, bool final) { if (!ExpectAnswer(source)) { LOG(LS_ERROR) << "Invalid state for SRTP answer"; return false; } // If the answer doesn't requests crypto complete the negotiation of an // unencrypted session. // Otherwise, finalize the parameters and apply them. if (answer_params.empty()) { if (final) { return ResetParams(); } else { // Need to wait for the final answer to decide if // we should go to Active state. state_ = (source == CS_LOCAL) ? ST_SENTPRANSWER_NO_CRYPTO : ST_RECEIVEDPRANSWER_NO_CRYPTO; return true; } } CryptoParams selected_params; if (!NegotiateParams(answer_params, &selected_params)) return false; const CryptoParams& send_params = (source == CS_REMOTE) ? selected_params : answer_params[0]; const CryptoParams& recv_params = (source == CS_REMOTE) ? answer_params[0] : selected_params; if (!ApplyParams(send_params, recv_params)) { return false; } if (final) { offer_params_.clear(); state_ = ST_ACTIVE; } else { state_ = (source == CS_LOCAL) ? ST_SENTPRANSWER : ST_RECEIVEDPRANSWER; } return true; } void SrtpFilter::CreateSrtpSessions() { send_session_.reset(new SrtpSession()); applied_send_params_ = CryptoParams(); recv_session_.reset(new SrtpSession()); applied_recv_params_ = CryptoParams(); if (external_auth_enabled_) { send_session_->EnableExternalAuth(); } } bool SrtpFilter::NegotiateParams(const std::vector<CryptoParams>& answer_params, CryptoParams* selected_params) { // We're processing an accept. We should have exactly one set of params, // unless the offer didn't mention crypto, in which case we shouldn't be here. bool ret = (answer_params.size() == 1U && !offer_params_.empty()); if (ret) { // We should find a match between the answer params and the offered params. std::vector<CryptoParams>::const_iterator it; for (it = offer_params_.begin(); it != offer_params_.end(); ++it) { if (answer_params[0].Matches(*it)) { break; } } if (it != offer_params_.end()) { *selected_params = *it; } else { ret = false; } } if (!ret) { LOG(LS_WARNING) << "Invalid parameters in SRTP answer"; } return ret; } bool SrtpFilter::ApplyParams(const CryptoParams& send_params, const CryptoParams& recv_params) { // TODO(jiayl): Split this method to apply send and receive CryptoParams // independently, so that we can skip one method when either send or receive // CryptoParams is unchanged. if (applied_send_params_.cipher_suite == send_params.cipher_suite && applied_send_params_.key_params == send_params.key_params && applied_recv_params_.cipher_suite == recv_params.cipher_suite && applied_recv_params_.key_params == recv_params.key_params) { LOG(LS_INFO) << "Applying the same SRTP parameters again. No-op."; // We do not want to reset the ROC if the keys are the same. So just return. return true; } int send_suite = rtc::SrtpCryptoSuiteFromName(send_params.cipher_suite); int recv_suite = rtc::SrtpCryptoSuiteFromName(recv_params.cipher_suite); if (send_suite == rtc::SRTP_INVALID_CRYPTO_SUITE || recv_suite == rtc::SRTP_INVALID_CRYPTO_SUITE) { LOG(LS_WARNING) << "Unknown crypto suite(s) received:" << " send cipher_suite " << send_params.cipher_suite << " recv cipher_suite " << recv_params.cipher_suite; return false; } int send_key_len, send_salt_len; int recv_key_len, recv_salt_len; if (!rtc::GetSrtpKeyAndSaltLengths(send_suite, &send_key_len, &send_salt_len) || !rtc::GetSrtpKeyAndSaltLengths(recv_suite, &recv_key_len, &recv_salt_len)) { LOG(LS_WARNING) << "Could not get lengths for crypto suite(s):" << " send cipher_suite " << send_params.cipher_suite << " recv cipher_suite " << recv_params.cipher_suite; return false; } // TODO(juberti): Zero these buffers after use. bool ret; rtc::Buffer send_key(send_key_len + send_salt_len); rtc::Buffer recv_key(recv_key_len + recv_salt_len); ret = (ParseKeyParams(send_params.key_params, send_key.data(), send_key.size()) && ParseKeyParams(recv_params.key_params, recv_key.data(), recv_key.size())); if (ret) { CreateSrtpSessions(); send_session_->SetEncryptedHeaderExtensionIds( send_encrypted_header_extension_ids_); recv_session_->SetEncryptedHeaderExtensionIds( recv_encrypted_header_extension_ids_); ret = (send_session_->SetSend( rtc::SrtpCryptoSuiteFromName(send_params.cipher_suite), send_key.data(), send_key.size()) && recv_session_->SetRecv( rtc::SrtpCryptoSuiteFromName(recv_params.cipher_suite), recv_key.data(), recv_key.size())); } if (ret) { LOG(LS_INFO) << "SRTP activated with negotiated parameters:" << " send cipher_suite " << send_params.cipher_suite << " recv cipher_suite " << recv_params.cipher_suite; applied_send_params_ = send_params; applied_recv_params_ = recv_params; } else { LOG(LS_WARNING) << "Failed to apply negotiated SRTP parameters"; } return ret; } bool SrtpFilter::ResetParams() { offer_params_.clear(); state_ = ST_INIT; send_session_ = nullptr; recv_session_ = nullptr; send_rtcp_session_ = nullptr; recv_rtcp_session_ = nullptr; LOG(LS_INFO) << "SRTP reset to init state"; return true; } bool SrtpFilter::ParseKeyParams(const std::string& key_params, uint8_t* key, size_t len) { // example key_params: "inline:YUJDZGVmZ2hpSktMbW9QUXJzVHVWd3l6MTIzNDU2" // Fail if key-method is wrong. if (key_params.find("inline:") != 0) { return false; } // Fail if base64 decode fails, or the key is the wrong size. std::string key_b64(key_params.substr(7)), key_str; if (!rtc::Base64::Decode(key_b64, rtc::Base64::DO_STRICT, &key_str, nullptr) || key_str.size() != len) { return false; } memcpy(key, key_str.c_str(), len); return true; } } // namespace cricket
33.172485
80
0.649892
[ "vector" ]
c022e3ce5c5d416d5432a87cf0a796aac124429e
11,555
cc
C++
src/algorithms/tests/rsapi.cc
revorg7/beliefbox
ba974b17fbb46ac98960f31dea66115be470000e
[ "OLDAP-2.3" ]
4
2015-12-02T23:16:44.000Z
2018-01-07T10:54:36.000Z
src/algorithms/tests/rsapi.cc
revorg7/beliefbox
ba974b17fbb46ac98960f31dea66115be470000e
[ "OLDAP-2.3" ]
2
2015-12-02T19:47:57.000Z
2018-10-14T13:08:40.000Z
src/algorithms/tests/rsapi.cc
revorg7/beliefbox
ba974b17fbb46ac98960f31dea66115be470000e
[ "OLDAP-2.3" ]
4
2018-01-14T14:23:18.000Z
2018-10-29T12:46:41.000Z
/* -*- Mode: C++; -*- */ // copyright (c) 2010 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com> /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifdef MAKE_MAIN #include "RSAPI.h" #include "Rollout.h" #include "MountainCar.h" #include "Pendulum.h" #include "RandomPolicy.h" #include "MersenneTwister.h" #include "RandomNumberGenerator.h" #include "KNNClassifier.h" #include "ClassifierMixture.h" #include "ClassifierPolicy.h" #include "EasyClock.h" #include <cstring> #include <getopt.h> struct PerformanceStatistics { real total_reward; real discounted_reward; real n_of_steps; real run_time; PerformanceStatistics() : total_reward(0), discounted_reward(0), n_of_steps(0), run_time(0) {} }; struct AveragePerformanceStatistics : PerformanceStatistics { int N; AveragePerformanceStatistics() : N(0) { } void Observe(PerformanceStatistics& x) { N++; real rN = (real) N; real irN = 1 / rN; real gamma = (rN - 1) * irN; total_reward = gamma * total_reward + (1 - gamma) * x.total_reward; discounted_reward = gamma * discounted_reward + (1 - gamma) * x.discounted_reward; n_of_steps = gamma * n_of_steps + (1 - gamma) * x.n_of_steps; run_time += x.run_time; } void Show() { printf ("%f %f %f %f # reward, discounted, steps, cpu-time\n", total_reward, discounted_reward, n_of_steps, run_time); } }; PerformanceStatistics Evaluate(Environment<Vector, int>* environment, AbstractPolicy<Vector, int>* policy, real gamma, int T); static const char* const help_text = "Usage: rsapi [options]\n\ \nOptions:\n\ --environment: {MountainCar, Pendulum}\n\ --n_states: number of states\n\ --gamma: reward discounting in [0,1]\n\ --n_iter: maximum number of policy iterations\n\ --horizon: rollout horizon\n\ --n_rollouts: number of rollouts\n\ --knn: number of nearest neighbours in KNN classifier\n\ --group: use grouped action training\n\ --resample: resample states from discounted state distribution\n\ --lipschitz: use a Lipschitz assumption with constant L\n\ --uniform: uniformly sample all states in representative set\n\ --upper_bound: use upper bound to sample states in set\n\ --error_bound: sample uniformly until error bound is attained\n\ \n"; int main(int argc, char* argv[]) { // Create a new environment Environment<Vector, int>* environment; MersenneTwisterRNG rng; enum SamplingMethod { UNIFORM, UPPER_BOUND, ERROR_BOUND }; int n_states = 100; real gamma = 0.99; int n_iter=10; int n_rollouts = 100; int horizon = -1; int n_neighbours = 1; char* environment_name = NULL; bool group_training = false; bool resample = false; real delta = 0.1; real Lipschitz = -1; enum SamplingMethod sampling_method = UPPER_BOUND; { // options int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = { {"n_states", required_argument, 0, 0}, //0 {"gamma", required_argument, 0, 0}, //1 {"n_iter", required_argument, 0, 0}, //2 {"n_rollouts", required_argument, 0, 0}, //3 {"horizon", required_argument, 0, 0}, //4 {"environment", required_argument, 0, 0}, //5 {"knn", required_argument, 0, 0}, //6 {"group", no_argument, 0, 0}, //7 {"resample", no_argument, 0, 0}, //8 {"delta", required_argument, 0, 0}, //9 {"lipschitz", required_argument, 0, 0}, //10 {"uniform", no_argument, 0, 0}, //11 {"upper_bound", no_argument, 0, 0}, //12 {"error_bound", no_argument, 0, 0}, //13 {0, 0, 0, 0} }; c = getopt_long (argc, argv, "", long_options, &option_index); if (c == -1) break; switch (c) { case 0: #if 0 printf ("option %s (%d)", long_options[option_index].name, option_index); if (optarg) printf (" with arg %s", optarg); printf ("\n"); #endif switch (option_index) { case 0: n_states = atoi(optarg); break; case 1: gamma = atof(optarg); break; case 2: n_iter = atoi(optarg); break; case 3: n_rollouts = atoi(optarg); break; case 4: horizon = atoi(optarg); break; case 5: environment_name = optarg; break; case 6: n_neighbours = atoi(optarg); break; case 7: group_training = true; break; case 8: resample = true; break; case 9: delta = atof(optarg); break; case 10: Lipschitz = atof(optarg); break; case 11: sampling_method = UNIFORM; break; case 12: sampling_method = UPPER_BOUND; break; case 13: sampling_method = ERROR_BOUND; break; default: fprintf (stderr, "Invalid options\n"); exit(0); break; } break; case '0': case '1': case '2': if (digit_optind != 0 && digit_optind != this_option_optind) printf ("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf ("option %c\n", c); break; default: std::cout << help_text; exit (-1); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) { printf ("%s ", argv[optind++]); } printf ("\n"); } } if (!environment_name) { fprintf(stderr, "Must specify environment\n"); exit(-1); } if (!strcmp(environment_name, "MountainCar")) { environment = new MountainCar(); } else if (!strcmp(environment_name, "Pendulum")) { environment = new Pendulum(); } else { fprintf(stderr, "Invalid environment name %s\n", environment_name); exit(-1); } // Place holder for the policy AbstractPolicy<Vector, int>* policy; // Start with a random policy! policy = new RandomPolicy(environment->getNActions(), &rng); int state_dimension = environment->getNStates(); Vector S_L = environment->StateLowerBound(); Vector S_U = environment->StateUpperBound(); printf("# State dimension: %d\n", state_dimension); printf("# S_L: "); S_L.print(stdout); printf("# S_U: "); S_U.print(stdout); //Classifier<Vector, int, Vector>* classifier = NULL; std::vector<Vector> state_vector(n_states); for (uint k=0; k<state_vector.size(); ++k) { Vector& state = state_vector[k]; state.Resize(S_L.Size()); for (int i=0; i<S_L.Size(); ++i) { state(i) = rng.uniform(S_L(i), S_U(i)); } } //RSAPI rsapi(environment, &rng, gamma); for (int iter=0; iter<n_iter; ++iter) { AveragePerformanceStatistics statistics; for (int i=0; i<100; ++i) { PerformanceStatistics run_statistics = Evaluate(environment, policy, gamma, 1000); statistics.Observe(run_statistics); } statistics.Show(); RSAPI rsapi(environment, &rng, gamma); rsapi.setPolicy(policy); for (uint k=0; k<state_vector.size(); ++k) { rsapi.AddState(state_vector[k]); } switch (sampling_method) { case UNIFORM: rsapi.SampleUniformly(n_rollouts, horizon); break; case ERROR_BOUND: rsapi.SampleToErrorBound(n_rollouts, horizon, delta); break; case UPPER_BOUND: rsapi.SampleUpperBound(n_rollouts, horizon, delta); break; } if (Lipschitz > 0) { rsapi.Bootstrap(); } //rsapi.ShowRollouts(); //int n_classifiers = 2; //std::vector<KNNClassifier*> experts(n_classifiers); //for (int i=0; i<n_classifiers; ++i) { //experts[i] = new KNNClassifier(state_dimension, environment->getNActions(), n_neighbours); //} //HashedClassifierMixture<KNNClassifier> hcm_classifier(state_dimension, environment->getNActions(), experts); //Classifier<Vector, int, Vector> new_classifier = hcm_classifier; //Classifier<Vector, int, Vector> *new_classifier = new HashedClassifierMixture<KNNClassifier>(state_dimension, environment->getNActions(), experts); Classifier<Vector, int, Vector>* new_classifier = new KNNClassifier(state_dimension, environment->getNActions(), n_neighbours); int n_improved_actions = 0; if (group_training) { n_improved_actions = rsapi.GroupTrainClassifier(new_classifier, delta); } else { n_improved_actions = rsapi.TrainClassifier(new_classifier, delta); } logmsg ("n: %d # improved actions\n", n_improved_actions); if (resample) { for (uint i=0; i<state_vector.size(); ++i) { if (rng.uniform() >= gamma) { state_vector[i] = rsapi.SampleStateFromPolicy(); } } } delete policy; policy = new ClassifierPolicy(new_classifier); //classifier = new_classifier; fflush(stdout); } delete policy; delete environment; } PerformanceStatistics Evaluate(Environment<Vector, int>* environment, AbstractPolicy<Vector, int>* policy, real gamma, int T) { PerformanceStatistics statistics; statistics.total_reward = 0; statistics.discounted_reward = 0; statistics.n_of_steps = 0; statistics.run_time = GetCPU(); real discount = 1; environment->Reset(); for (int t=0; t < T; ++t, ++statistics.n_of_steps) { Vector state = environment->getState(); real reward = environment->getReward(); statistics.total_reward += reward; statistics.discounted_reward += reward * discount; discount *= gamma; policy->setState(state); int action = policy->SelectAction(); bool action_ok = environment->Act(action); if (!action_ok) { break; } } statistics.run_time = GetCPU() - statistics.run_time; return statistics; } #endif
33.590116
152
0.547122
[ "vector" ]
c028ceed44d902502b5721a0d5ff1319508b9e36
2,609
hpp
C++
src/Features/Demo/NetworkGhostPlayer.hpp
ThisAMJ/SourceAutoRecord
95eaf15c383b6962f3638f2dd4e06e5b22bee999
[ "MIT" ]
42
2021-04-27T17:03:24.000Z
2022-03-03T18:56:13.000Z
src/Features/Demo/NetworkGhostPlayer.hpp
ThisAMJ/SourceAutoRecord
95eaf15c383b6962f3638f2dd4e06e5b22bee999
[ "MIT" ]
43
2021-04-27T21:20:06.000Z
2022-03-22T12:45:46.000Z
src/Features/Demo/NetworkGhostPlayer.hpp
ThisAMJ/SourceAutoRecord
95eaf15c383b6962f3638f2dd4e06e5b22bee999
[ "MIT" ]
29
2021-06-11T23:52:24.000Z
2022-03-30T14:33:46.000Z
#pragma once #include "Command.hpp" #include "Features/Demo/GhostEntity.hpp" #include "Features/Hud/Hud.hpp" #include "SFML/Network.hpp" #include "Utils/SDK.hpp" #include "Variable.hpp" #include <atomic> #include <chrono> #include <condition_variable> #include <memory> #include <mutex> #include <thread> #include <vector> enum class HEADER { NONE, PING, CONNECT, DISCONNECT, STOP_SERVER, MAP_CHANGE, HEART_BEAT, MESSAGE, COUNTDOWN, UPDATE, SPEEDRUN_FINISH, MODEL_CHANGE }; class NetworkManager { public: sf::TcpSocket tcpSocket; sf::UdpSocket udpSocket; sf::SocketSelector selector; sf::IpAddress serverIP; unsigned short int serverPort; sf::Uint32 ID; std::mutex ghostPoolLock; std::vector<std::shared_ptr<GhostEntity>> ghostPool; std::thread networkThread; std::condition_variable waitForRunning; sf::Clock pingClock; sf::Clock updateClock; std::string postCountdownCommands; std::chrono::time_point<std::chrono::steady_clock> timeLeft; int countdownStep; bool countdownShow; std::chrono::time_point<std::chrono::steady_clock> lastUpdateTime; public: std::atomic<bool> isConnected; std::atomic<bool> runThread; std::string name; bool isCountdownReady; std::string modelName; sf::Uint32 splitTicks = -1; sf::Uint32 splitTicksTotal = -1; bool disableSyncForLoad = false; public: NetworkManager(); void Connect(sf::IpAddress ip, unsigned short int port); void Disconnect(); void StopServer(); void PauseNetwork(); void ResumeNetwork(); void RunNetwork(); void SendPlayerData(); void NotifyMapChange(); void NotifySpeedrunFinished(const bool CM = false); void SendMessageToAll(std::string msg); void SendPing(); void ReceiveUDPUpdates(std::vector<sf::Packet> &buffer); void Treat(sf::Packet &packet, bool udp); void UpdateGhostsPosition(); std::shared_ptr<GhostEntity> GetGhostByID(sf::Uint32 ID); void UpdateGhostsSameMap(); void UpdateModel(const std::string modelName); bool AreAllGhostsAheadOrSameMap(); void SpawnAllGhosts(); void DeleteAllGhosts(); void SetupCountdown(std::string preCommands, std::string postCommands, sf::Uint32 duration); //Need this function to measure the ping in order to start the countdown at the same time void StartCountdown(); //Print the state of the countdown void UpdateCountdown(); void DrawNames(HudContext *ctx); bool IsSyncing(); }; extern NetworkManager networkManager; extern Variable ghost_TCP_only; extern Variable ghost_update_rate; extern Command ghost_connect; extern Command ghost_disconnect; extern Command ghost_message; extern Command ghost_ping; extern Command ghost_name;
22.885965
93
0.767344
[ "vector" ]
c0297852fc3509a81b82c846adaafe0c54b0cda2
12,224
cpp
C++
openstudiocore/src/project/Test/AlgorithmRecord_GTest.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
1
2016-12-29T08:45:03.000Z
2016-12-29T08:45:03.000Z
openstudiocore/src/project/Test/AlgorithmRecord_GTest.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
openstudiocore/src/project/Test/AlgorithmRecord_GTest.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include "ProjectFixture.hpp" #include "../AnalysisRecord.hpp" #include "../AlgorithmRecord.hpp" #include "../DesignOfExperimentsRecord.hpp" #include "../DesignOfExperimentsRecord_Impl.hpp" #include "../ProblemRecord.hpp" #include "../AttributeRecord.hpp" #include "../DataPointRecord.hpp" #include "../../analysis/Analysis.hpp" #include "../../analysis/Problem.hpp" #include "../../analysis/Variable.hpp" #include "../../analysis/DataPoint.hpp" #include "../../analysis/DesignOfExperiments.hpp" #include "../../analysis/DesignOfExperimentsOptions.hpp" #include "../../runmanager/lib/Workflow.hpp" #include "../../utilities/core/FileReference.hpp" #include "../../utilities/core/Containers.hpp" #include "../../utilities/data/Attribute.hpp" #include "../../utilities/data/Tag.hpp" using namespace openstudio; using namespace openstudio::runmanager; using namespace openstudio::analysis; using namespace openstudio::project; TEST_F(ProjectFixture, DesignOfExperiments_RoundTrip_PreRun) { DesignOfExperimentsOptions options(DesignOfExperimentsType::FullFactorial); options.setMaxIter(0); DesignOfExperiments algorithm(options); Analysis analysis("Analysis", Problem("Problem",VariableVector(),Workflow()), algorithm, FileReference(toPath("in.osm"))); ProjectDatabase database = getCleanDatabase("DesignOfExperiments_RoundTrip_PreRun"); AnalysisRecord analysisR(analysis,database); ASSERT_TRUE(analysisR.algorithmRecord()); ASSERT_TRUE(analysisR.algorithmRecord()->optionalCast<DesignOfExperimentsRecord>()); DesignOfExperimentsRecord doeR = analysisR.algorithmRecord()->cast<DesignOfExperimentsRecord>(); EXPECT_EQ(toString(algorithm.versionUUID()),toString(doeR.uuidLast())); EXPECT_EQ(algorithm.name(),doeR.name()); // Check round-tripped objects DesignOfExperiments algorithmCopy = doeR.designOfExperiments(); DesignOfExperimentsOptions optionsCopy = algorithmCopy.designOfExperimentsOptions(); // Standard AlgorithmOptions Items ASSERT_TRUE((options.maxIter() && optionsCopy.maxIter()) || (!options.maxIter() && !optionsCopy.maxIter())); if (options.maxIter()) { EXPECT_EQ(options.maxIter().get(),optionsCopy.maxIter().get()); } ASSERT_TRUE((options.maxSims() && optionsCopy.maxSims()) || (!options.maxSims() && !optionsCopy.maxSims())); if (options.maxSims()) { EXPECT_EQ(options.maxSims().get(),optionsCopy.maxSims().get()); } // DesignOfExperimentsOptions Items EXPECT_TRUE(options.designType() == optionsCopy.designType()); // Standard Algorithm Items EXPECT_EQ(algorithm.isComplete(),algorithmCopy.isComplete()); EXPECT_EQ(algorithm.failed(),algorithmCopy.failed()); EXPECT_EQ(algorithm.iter(),algorithmCopy.iter()); // DesignOfExperiments Items EXPECT_EQ(DesignOfExperiments::standardName(),algorithm.name()); EXPECT_EQ(DesignOfExperiments::standardName(),algorithmCopy.name()); } TEST_F(ProjectFixture, DesignOfExperiments_RoundTrip_PostRun) { DesignOfExperimentsOptions options(DesignOfExperimentsType::FullFactorial); options.setMaxSims(13); DesignOfExperiments algorithm(createUUID(), createUUID(), std::string(), std::string(), true, true, 0, options); Analysis analysis("Analysis", Problem("Problem",VariableVector(),Workflow()), algorithm, FileReference(toPath("in.osm"))); DataPoint dataPoint(createUUID(), createUUID(), std::string(), std::string(), std::string(), analysis.problem(), true, true, true, DataPointRunType::Local, std::vector<QVariant>(), DoubleVector(), openstudio::path(), boost::none, boost::none, boost::none, boost::none, std::vector<openstudio::path>(), TagVector(), AttributeVector()); EXPECT_TRUE(analysis.addDataPoint(dataPoint)); ProjectDatabase database = getCleanDatabase("DesignOfExperiments_RoundTrip_PostRun"); AnalysisRecord analysisR(analysis,database); ASSERT_TRUE(analysisR.algorithmRecord()); ASSERT_TRUE(analysisR.algorithmRecord()->optionalCast<DesignOfExperimentsRecord>()); DesignOfExperimentsRecord doeR = analysisR.algorithmRecord()->cast<DesignOfExperimentsRecord>(); EXPECT_EQ(toString(algorithm.versionUUID()),toString(doeR.uuidLast())); EXPECT_EQ(algorithm.name(),doeR.name()); // Check round-tripped objects DesignOfExperiments algorithmCopy = doeR.designOfExperiments(); DesignOfExperimentsOptions optionsCopy = algorithmCopy.designOfExperimentsOptions(); // Standard AlgorithmOptions Items ASSERT_TRUE((options.maxIter() && optionsCopy.maxIter()) || (!options.maxIter() && !optionsCopy.maxIter())); if (options.maxIter()) { EXPECT_EQ(options.maxIter().get(),optionsCopy.maxIter().get()); } ASSERT_TRUE((options.maxSims() && optionsCopy.maxSims()) || (!options.maxSims() && !optionsCopy.maxSims())); if (options.maxSims()) { EXPECT_EQ(options.maxSims().get(),optionsCopy.maxSims().get()); } // DesignOfExperimentsOptions Items EXPECT_TRUE(options.designType() == optionsCopy.designType()); // Standard Algorithm Items EXPECT_EQ(algorithm.isComplete(),algorithmCopy.isComplete()); EXPECT_EQ(algorithm.failed(),algorithmCopy.failed()); EXPECT_EQ(algorithm.iter(),algorithmCopy.iter()); // DesignOfExperiments Items EXPECT_EQ(DesignOfExperiments::standardName(),algorithm.name()); EXPECT_EQ(DesignOfExperiments::standardName(),algorithmCopy.name()); } TEST_F(ProjectFixture, DesignOfExperiments_RemoveAlgorithm) { DesignOfExperimentsOptions options(DesignOfExperimentsType::FullFactorial); options.setMaxSims(13); DesignOfExperiments algorithm(createUUID(), createUUID(), std::string(), std::string(), true, true, 0, options); Analysis analysis("Analysis", Problem("Problem",VariableVector(),Workflow()), algorithm, FileReference(toPath("in.osm"))); DataPoint dataPoint(createUUID(), createUUID(), std::string(), std::string(), std::string(), analysis.problem(), true, true, true, DataPointRunType::Local, std::vector<QVariant>(), DoubleVector(), openstudio::path(), boost::none, boost::none, boost::none, boost::none, std::vector<openstudio::path>(), TagVector(), AttributeVector()); EXPECT_TRUE(analysis.addDataPoint(dataPoint)); ProjectDatabase database = getCleanDatabase("DesignOfExperiments_RemoveAlgorithm"); AnalysisRecord analysisR(analysis,database); ASSERT_TRUE(analysisR.algorithmRecord()); ASSERT_TRUE(analysisR.algorithmRecord()->optionalCast<DesignOfExperimentsRecord>()); DesignOfExperimentsRecord doeR = analysisR.algorithmRecord()->cast<DesignOfExperimentsRecord>(); // pre-conditions EXPECT_EQ(1u,AlgorithmRecord::getAlgorithmRecords(database).size()); EXPECT_FALSE(AttributeRecord::getAttributeRecords(database).empty()); // lists algorithm options // ETH@20120928 Kind of odd that this is allowed. Breaks Analysis interface. database.removeRecord(doeR); database.save(); // post-conditions EXPECT_TRUE(AlgorithmRecord::getAlgorithmRecords(database).empty()); EXPECT_TRUE(AttributeRecord::getAttributeRecords(database).empty()); // ETH@20120928 - This is bad consequence of letting AlgorithmRecord be removed on its own. // At the very least, parent pointers back to child should be nulled out when child is removed. // But perhaps no child records be removable through the public interface? EXPECT_DEATH(Analysis analysisCopy = analysisR.analysis(),".*"); } TEST_F(ProjectFixture, DesignOfExperiments_RemoveAnalysis) { DesignOfExperimentsOptions options(DesignOfExperimentsType::FullFactorial); options.setMaxSims(13); DesignOfExperiments algorithm(createUUID(), createUUID(), std::string(), std::string(), true, true, 0, options); Analysis analysis("Analysis", Problem("Problem",VariableVector(),Workflow()), algorithm, FileReference(toPath("in.osm"))); DataPoint dataPoint(createUUID(), createUUID(), std::string(), std::string(), std::string(), analysis.problem(), true, true, true, DataPointRunType::Local, std::vector<QVariant>(), DoubleVector(), openstudio::path(), boost::none, boost::none, boost::none, boost::none, std::vector<openstudio::path>(), TagVector(), AttributeVector()); EXPECT_TRUE(analysis.addDataPoint(dataPoint)); ProjectDatabase database = getCleanDatabase("DesignOfExperiments_RemoveAnalysis"); AnalysisRecord analysisR(analysis,database); // pre-conditions EXPECT_EQ(1u,AnalysisRecord::getAnalysisRecords(database).size()); EXPECT_EQ(1u,ProblemRecord::getProblemRecords(database).size()); EXPECT_EQ(1u,AlgorithmRecord::getAlgorithmRecords(database).size()); EXPECT_FALSE(AttributeRecord::getAttributeRecords(database).empty()); // lists algorithm options EXPECT_EQ(1u,DataPointRecord::getDataPointRecords(database).size()); database.removeRecord(analysisR); database.save(); // post-conditions EXPECT_TRUE(AnalysisRecord::getAnalysisRecords(database).empty()); EXPECT_TRUE(ProblemRecord::getProblemRecords(database).empty()); EXPECT_TRUE(AlgorithmRecord::getAlgorithmRecords(database).empty()); EXPECT_TRUE(AttributeRecord::getAttributeRecords(database).empty()); EXPECT_TRUE(DataPointRecord::getDataPointRecords(database).empty()); }
42.151724
98
0.61592
[ "vector" ]
c029c15feeb4752ecae842e21c71c201a58ecb9e
9,169
cc
C++
src/statistics/ContextTreeKDTree.cc
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
src/statistics/ContextTreeKDTree.cc
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
src/statistics/ContextTreeKDTree.cc
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
/* -*- Mode: c++; -*- */ // copyright (c) 2010 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com> /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "ContextTreeKDTree.h" #include <cmath> #include "BetaDistribution.h" #include "Random.h" #undef LOG_CALCULATIONS /** Create the root node of the tree */ ContextTreeKDTree::Node::Node(ContextTreeKDTree& tree_, const Vector& lower_bound_, const Vector& upper_bound_) : tree(tree_), #ifdef USE_GAUSSIAN_MIX gaussian((upper_bound_ + lower_bound_) * 0.5, 1.0, 1.0, Matrix::Unity(upper_bound_.Size(), upper_bound_.Size())), // gaussian(lower_bound_, upper_bound_), w_gaussian(0.5), #endif // beta_product(lower_bound_, upper_bound_), lower_bound(lower_bound_), upper_bound(upper_bound_), volume(Volume(upper_bound - lower_bound)), depth(0), prev(NULL), next(tree.n_branches), alpha(tree.n_branches), w(0.5), log_w(0), log_w_prior(-log(2)), S(0) { assert(lower_bound < upper_bound); splitting_dimension = ArgMax(upper_bound - lower_bound); #ifdef RANDOM_SPLITS real phi = 0.1 + 0.8 * urandom(); mid_point = phi * upper_bound[splitting_dimension] + (1 - phi) * lower_bound[splitting_dimension]; #else mid_point = (upper_bound[splitting_dimension] + lower_bound[splitting_dimension]) / 2.0; #endif } /** Make a new leaf node. In order to avoid overfitting, the weights are fixed. That way, the contribution of the leaf nodes is small. */ ContextTreeKDTree::Node::Node(ContextTreeKDTree::Node* prev_, const Vector& lower_bound_, const Vector& upper_bound_) : tree(prev_->tree), #ifdef USE_GAUSSIAN_MIX gaussian((upper_bound_ + lower_bound_) * 0.5, 1.0, 1.0, prev_->gaussian.T_n), // Matrix::Unity(upper_bound_.Size(), upper_bound_.Size())), // gaussian(lower_bound_, upper_bound_), w_gaussian(0.5), #endif // beta_product(lower_bound_, upper_bound_), lower_bound(lower_bound_), upper_bound(upper_bound_), volume(Volume(upper_bound - lower_bound)), depth(prev_->depth + 1), prev(prev_), next(tree.n_branches), alpha(tree.n_branches), log_w(0), // log_w_prior(-(real) depth * log(2)), log_w_prior(-log(2)), S(0) { assert(lower_bound < upper_bound); splitting_dimension = ArgMax(upper_bound - lower_bound); #ifdef RANDOM_SPLITS real phi = 0.1 + 0.8 * urandom(); mid_point = phi * upper_bound[splitting_dimension] + (1 - phi) * lower_bound[splitting_dimension]; #else mid_point = (upper_bound[splitting_dimension] + lower_bound[splitting_dimension]) / 2.0; #endif w = exp(log_w_prior); for (int i = 0; i < tree.n_branches; ++i) { next[i] = NULL; } } /// make sure to kill all ContextTreeKDTree::Node::~Node() { for (int i = 0; i < tree.n_branches; ++i) { delete next[i]; } } /** Observe new data, adapt parameters. Each node corresponds to an interval C. The probability of \f$x\f$ is \f[ P(X | C_k) = U(C_k) w_k + (1 - w_k) [a_{k,0} / n_k P(X | C_{k,0}) + a_{k,1} / n_k P(X | C_{k,1})] \f] of course, if \f$X \in C_k^i\f$ then \f[ P(X | C_k) = U(C_k) w_k + (1 - w_k) [a_{k,i} / n_k P(X | C_{k,i}] \f] Or in long hand \f[ P(X | C) = P(U | C) P(X | U, C) + [1 - P(U | C)] \sum_{C'} P(X | C') P(C' | C, \not U) \f] That means that \f[ P(U | X, C) = P(X | U, C) P(U | C) / P(X | C). \f] This algorithm uses the same structure of uniform / non-uniform mixture as in Marcus Hutter's work Bayesian Infinite Trees. However, it is significantly simplified by using an explicit online posterior recursion. */ real ContextTreeKDTree::Node::Observe(const Vector& x, real probability) { // Which interval is the x lying at int k; if (x[splitting_dimension] < mid_point) { k = 0; } else { k = 1; } // Calculate the local distribution real P_uniform = 1.0 / volume; // Volume (upper_bound - lower_bound); // P_uniform *= beta_product.Observe(x); #ifdef USE_GAUSSIAN_MIX real P_gaussian = gaussian.Observe(x); assert(P_gaussian >= 0); real P_local = w_gaussian * P_gaussian + (1 - w_gaussian) * P_uniform; assert(P_local >= 0); w_gaussian *= P_gaussian / P_local; #else real P_local = P_uniform; #endif // printf ("P_u = %f\n", P_uniform); // probability of recursion // P is the probability in the remainder of the chain. P = (1.0 + alpha[k]) / (2.0 + S); // adapt parameters alpha[k]++; S++; // real threshold = 1; //log(depth); real threshold = pow(1.1, (real)depth); if ((tree.max_depth == 0 || depth < tree.max_depth) && S > threshold) { if (!next[k]) { if (k == 0) { Vector new_bound = upper_bound; new_bound(splitting_dimension) = mid_point; next[k] = new Node(this, lower_bound, new_bound); } else { Vector new_bound = lower_bound; new_bound(splitting_dimension) = mid_point; next[k] = new Node(this, new_bound, upper_bound); } } P *= next[k]->Observe(x, P); } else { // There are four options when there are no further // children. // The first is to assume a uniform distribution on the k-th // interval. Since there are two intervals, multiple by two. // P *= 2 * P_local; // The second is to just stop. P = P_local; // The third is to use the interval probability // P = P; // The final is to set the next probability to zero. // P = 0; } #ifdef LOG_CALCULATIONS w = exp(log_w_prior + log_w); #endif real total_probability = P_local * w + (1 - w) * P; // posterior weight #ifdef LOG_CALCULATIONS log_w = log(w * P_local / total_probability) - log_w_prior; #else w *= P_local / total_probability; #endif assert(w >= 0 && w <= 1); #if 0 std::cout << depth << ": P(y|h_k)=" << P << ", P(h_k|B_k)=" << w << ", P(y|B_{k-1})="<< probability << ", P(y|B_k)=" << total_probability << std::endl; #endif return total_probability; } /** Observe new data, adapt parameters. We again ignore the probability given by the previous model, since this is a much simpler case. We only care about the fact that the previous model posits a uniform distribution for the interval of the current model, while the current model posits a mixture of two uniform distributions. */ real ContextTreeKDTree::Node::pdf(const Vector& x, real probability) { int k; if (x[splitting_dimension] < mid_point) { k = 0; } else { k = 1; } real P_uniform = 1.0 / volume; // Volume(upper_bound - lower_bound); #ifdef USE_GAUSSIAN_MIX real P_gaussian = gaussian.pdf(x); real P_local = w_gaussian * P_gaussian + (1 - w_gaussian) * P_uniform; #else real P_local = P_uniform; #endif P = (1.0 + alpha[k]) / (2.0 + S); // real threshold = 1; real threshold = pow(1.1, (real)depth); if (S > threshold && next[k]) { P *= next[k]->pdf(x, P); } else { // P *= 2 * P_local; P = P_local; } #ifdef LOG_CALCULATIONS w = exp(log_w_prior + log_w); #endif real total_probability = P_local * w + (1 - w) * P; return total_probability; } void ContextTreeKDTree::Node::Show() { printf("%d %f %f\n", depth, w, volume); for (int k = 0; k < tree.n_branches; ++k) { if (next[k]) { next[k]->Show(); } } return; } int ContextTreeKDTree::Node::NChildren() { int my_children = 0; for (int k = 0; k < tree.n_branches; ++k) { if (next[k]) { my_children++; my_children += next[k]->NChildren(); } } return my_children; } /// n_branches is a bit of a silly thing, deprecated ContextTreeKDTree::ContextTreeKDTree(int n_branches_, int max_depth_, const Vector& lower_bound, const Vector& upper_bound) : n_branches(n_branches_), max_depth(max_depth_) { root = new Node(*this, lower_bound, upper_bound); } ContextTreeKDTree::~ContextTreeKDTree() { delete root; } real ContextTreeKDTree::Observe(const Vector& x) { return root->Observe(x, 1); } real ContextTreeKDTree::pdf(const Vector& x) { return root->pdf(x, 1); } void ContextTreeKDTree::Show() { root->Show(); std::cout << "Total contexts: " << NChildren() << std::endl; } int ContextTreeKDTree::NChildren() { return root->NChildren(); }
29.577419
80
0.590141
[ "vector", "model" ]
c02a24686f1fbb517cac97a865e5117fd8e84a49
6,843
cc
C++
runtime/vm/compiler/stub_code_compiler.cc
matthewlloyd/sdk
fd898a53c60c2044f6a51fc7d6630a6305525565
[ "BSD-3-Clause" ]
1
2020-07-22T04:15:41.000Z
2020-07-22T04:15:41.000Z
runtime/vm/compiler/stub_code_compiler.cc
don-k-jacob/sdk
e51c40158e041501275e62389015b3533e065ffa
[ "BSD-3-Clause" ]
null
null
null
runtime/vm/compiler/stub_code_compiler.cc
don-k-jacob/sdk
e51c40158e041501275e62389015b3533e065ffa
[ "BSD-3-Clause" ]
1
2021-06-05T07:28:45.000Z
2021-06-05T07:28:45.000Z
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/compiler/runtime_api.h" #include "vm/globals.h" // For `StubCodeCompiler::GenerateAllocateUnhandledExceptionStub` #include "vm/compiler/backend/il.h" #define SHOULD_NOT_INCLUDE_RUNTIME #include "vm/compiler/stub_code_compiler.h" #include "vm/compiler/assembler/assembler.h" #define __ assembler-> namespace dart { namespace compiler { void StubCodeCompiler::GenerateInitStaticFieldStub(Assembler* assembler) { __ EnterStubFrame(); __ PushObject(NullObject()); // Make room for result. __ PushRegister(InitStaticFieldABI::kFieldReg); __ CallRuntime(kInitStaticFieldRuntimeEntry, /*argument_count=*/1); __ Drop(1); __ PopRegister(InitStaticFieldABI::kResultReg); __ LeaveStubFrame(); __ Ret(); } void StubCodeCompiler::GenerateInitInstanceFieldStub(Assembler* assembler) { __ EnterStubFrame(); __ PushObject(NullObject()); // Make room for result. __ PushRegister(InitInstanceFieldABI::kInstanceReg); __ PushRegister(InitInstanceFieldABI::kFieldReg); __ CallRuntime(kInitInstanceFieldRuntimeEntry, /*argument_count=*/2); __ Drop(2); __ PopRegister(InitInstanceFieldABI::kResultReg); __ LeaveStubFrame(); __ Ret(); } void StubCodeCompiler::GenerateInitLateInstanceFieldStub(Assembler* assembler, bool is_final) { const Register kFunctionReg = InitLateInstanceFieldInternalRegs::kFunctionReg; const Register kInstanceReg = InitInstanceFieldABI::kInstanceReg; const Register kFieldReg = InitInstanceFieldABI::kFieldReg; const Register kAddressReg = InitLateInstanceFieldInternalRegs::kAddressReg; const Register kScratchReg = InitLateInstanceFieldInternalRegs::kScratchReg; __ EnterStubFrame(); // Save for later. __ PushRegisterPair(kInstanceReg, kFieldReg); // Call initializer function. __ PushRegister(kInstanceReg); static_assert( InitInstanceFieldABI::kResultReg == CallingConventions::kReturnReg, "Result is a return value from initializer"); __ LoadField(kFunctionReg, FieldAddress(InitInstanceFieldABI::kFieldReg, target::Field::initializer_function_offset())); if (!FLAG_precompiled_mode || !FLAG_use_bare_instructions) { __ LoadField(CODE_REG, FieldAddress(kFunctionReg, target::Function::code_offset())); if (FLAG_enable_interpreter) { // InterpretCall stub needs arguments descriptor for all function calls. __ LoadObject(ARGS_DESC_REG, CastHandle<Object>(OneArgArgumentsDescriptor())); } else { // Load a GC-safe value for the arguments descriptor (unused but tagged). __ LoadImmediate(ARGS_DESC_REG, 0); } } __ Call(FieldAddress(kFunctionReg, target::Function::entry_point_offset())); __ Drop(1); // Drop argument. __ PopRegisterPair(kInstanceReg, kFieldReg); __ LoadField( kScratchReg, FieldAddress(kFieldReg, target::Field::host_offset_or_field_id_offset())); __ LoadFieldAddressForRegOffset(kAddressReg, kInstanceReg, kScratchReg); Label throw_exception; if (is_final) { __ LoadMemoryValue(kScratchReg, kAddressReg, 0); __ CompareObject(kScratchReg, SentinelObject()); __ BranchIf(NOT_EQUAL, &throw_exception); } #if defined(TARGET_ARCH_IA32) // On IA32 StoreIntoObject clobbers value register, so scratch // register is used in StoreIntoObject to preserve kResultReg. __ MoveRegister(kScratchReg, InitInstanceFieldABI::kResultReg); __ StoreIntoObject(kInstanceReg, Address(kAddressReg, 0), kScratchReg); #else __ StoreIntoObject(kInstanceReg, Address(kAddressReg, 0), InitInstanceFieldABI::kResultReg); #endif // defined(TARGET_ARCH_IA32) __ LeaveStubFrame(); __ Ret(); if (is_final) { __ Bind(&throw_exception); __ PushObject(NullObject()); // Make room for (unused) result. __ PushRegister(kFieldReg); __ CallRuntime(kLateInitializationErrorRuntimeEntry, /*argument_count=*/1); __ Breakpoint(); } } void StubCodeCompiler::GenerateInitLateInstanceFieldStub(Assembler* assembler) { GenerateInitLateInstanceFieldStub(assembler, /*is_final=*/false); } void StubCodeCompiler::GenerateInitLateFinalInstanceFieldStub( Assembler* assembler) { GenerateInitLateInstanceFieldStub(assembler, /*is_final=*/true); } void StubCodeCompiler::GenerateThrowStub(Assembler* assembler) { __ EnterStubFrame(); __ PushObject(NullObject()); // Make room for (unused) result. __ PushRegister(ThrowABI::kExceptionReg); __ CallRuntime(kThrowRuntimeEntry, /*argument_count=*/1); __ Breakpoint(); } void StubCodeCompiler::GenerateReThrowStub(Assembler* assembler) { __ EnterStubFrame(); __ PushObject(NullObject()); // Make room for (unused) result. __ PushRegister(ReThrowABI::kExceptionReg); __ PushRegister(ReThrowABI::kStackTraceReg); __ CallRuntime(kReThrowRuntimeEntry, /*argument_count=*/2); __ Breakpoint(); } void StubCodeCompiler::GenerateAssertBooleanStub(Assembler* assembler) { __ EnterStubFrame(); __ PushObject(NullObject()); // Make room for (unused) result. __ PushRegister(AssertBooleanABI::kObjectReg); __ CallRuntime(kNonBoolTypeErrorRuntimeEntry, /*argument_count=*/1); __ Breakpoint(); } void StubCodeCompiler::GenerateInstanceOfStub(Assembler* assembler) { __ EnterStubFrame(); __ PushObject(NullObject()); // Make room for the result. __ PushRegister(TypeTestABI::kInstanceReg); __ PushRegister(TypeTestABI::kDstTypeReg); __ PushRegister(TypeTestABI::kInstantiatorTypeArgumentsReg); __ PushRegister(TypeTestABI::kFunctionTypeArgumentsReg); __ PushRegister(TypeTestABI::kSubtypeTestCacheReg); __ CallRuntime(kInstanceofRuntimeEntry, /*argument_count=*/5); __ Drop(5); __ PopRegister(TypeTestABI::kResultReg); __ LeaveStubFrame(); __ Ret(); } // The UnhandledException class lives in the VM isolate, so it cannot cache // an allocation stub for itself. Instead, we cache it in the stub code list. void StubCodeCompiler::GenerateAllocateUnhandledExceptionStub( Assembler* assembler) { Thread* thread = Thread::Current(); auto class_table = thread->isolate()->class_table(); ASSERT(class_table->HasValidClassAt(kUnhandledExceptionCid)); const auto& cls = Class::ZoneHandle(thread->zone(), class_table->At(kUnhandledExceptionCid)); ASSERT(!cls.IsNull()); GenerateAllocationStubForClass(assembler, nullptr, cls, Code::Handle(Code::null()), Code::Handle(Code::null())); } } // namespace compiler } // namespace dart
36.593583
80
0.734035
[ "object" ]
c02d5ef07070b621df628ca74ace4b8ede74a1d3
556
hh
C++
qset.hh
JoeyEremondi/treewidth-memoization
5cd6be9e05bba189d14409f28c37805948ef11b3
[ "BSD-3-Clause" ]
1
2015-07-25T15:09:11.000Z
2015-07-25T15:09:11.000Z
qset.hh
JoeyEremondi/treewidth-memoization
5cd6be9e05bba189d14409f28c37805948ef11b3
[ "BSD-3-Clause" ]
1
2015-09-19T00:44:24.000Z
2015-09-21T16:47:12.000Z
qset.hh
JoeyEremondi/treewidth-memoization
5cd6be9e05bba189d14409f28c37805948ef11b3
[ "BSD-3-Clause" ]
null
null
null
#ifndef __QSET__HH #define __QSET__HH #include <cstdlib> #include <iostream> #include <vector> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_traits.hpp> #include "VSet.hh" #include "graphTypes.hh" //Adapted from http://stackoverflow.com/questions/14470566/how-to-traverse-graph-in-boost-use-bfs int sizeQ(int n, const VSet &S, Vertex v, const Graph &G); void findQvalues(int n, const VSet &S, const Graph &G, std::vector<int>& outValues); int qCheck(int n, VSet S, Vertex v, Graph G); std::string showSet(VSet S); #endif
20.592593
97
0.735612
[ "vector" ]
c02f093efdfba2468543bed139d84322b2d8ff22
4,639
cpp
C++
src/app/qgsmaptoolsplitparts.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/app/qgsmaptoolsplitparts.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/app/qgsmaptoolsplitparts.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsmaptoolsplitparts.h --------------------- begin : April 2013 copyright : (C) 2013 Denis Rouzaud email : denis.rouzaud@gmail.com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgisapp.h" #include "qgsmessagebar.h" #include "qgsmapcanvas.h" #include "qgsproject.h" #include "qgsmaptoolsplitparts.h" #include "qgssnappingutils.h" #include "qgsvectorlayer.h" #include "qgsmapmouseevent.h" QgsMapToolSplitParts::QgsMapToolSplitParts( QgsMapCanvas *canvas ) : QgsMapToolCapture( canvas, QgisApp::instance()->cadDockWidget(), QgsMapToolCapture::CaptureLine ) { mToolName = tr( "Split parts" ); setSnapToLayerGridEnabled( false ); } void QgsMapToolSplitParts::cadCanvasReleaseEvent( QgsMapMouseEvent *e ) { //check if we operate on a vector layer QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() ); if ( !vlayer ) { notifyNotVectorLayer(); return; } if ( !vlayer->isEditable() ) { notifyNotEditableLayer(); return; } bool split = false; //add point to list and to rubber band if ( e->button() == Qt::LeftButton ) { //If we snap the first point on a vertex of a line layer, we directly split the feature at this point if ( vlayer->geometryType() == QgsWkbTypes::LineGeometry && points().isEmpty() ) { QgsPointLocator::Match m = mCanvas->snappingUtils()->snapToCurrentLayer( e->pos(), QgsPointLocator::Vertex ); if ( m.isValid() ) { split = true; } } int error = addVertex( e->mapPoint() ); if ( error == 1 ) { //current layer is not a vector layer return; } else if ( error == 2 ) { //problem with coordinate transformation QgisApp::instance()->messageBar()->pushMessage( tr( "Coordinate transform error" ), tr( "Cannot transform the point to the layers coordinate system" ), Qgis::Info, QgisApp::instance()->messageTimeout() ); return; } startCapturing(); } else if ( e->button() == Qt::RightButton ) { split = true; } if ( split ) { deleteTempRubberBand(); //bring up dialog if a split was not possible (polygon) or only done once (line) bool topologicalEditing = QgsProject::instance()->topologicalEditing(); vlayer->beginEditCommand( tr( "Parts split" ) ); QgsGeometry::OperationResult returnCode = vlayer->splitParts( points(), topologicalEditing ); vlayer->endEditCommand(); if ( returnCode == QgsGeometry::OperationResult::NothingHappened ) { QgisApp::instance()->messageBar()->pushMessage( tr( "No parts were split" ), tr( "If there are selected parts, the split tool only applies to those. If you would like to split all parts under the split line, clear the selection." ), Qgis::Warning, QgisApp::instance()->messageTimeout() ); } else if ( returnCode == QgsGeometry::OperationResult::GeometryEngineError ) { QgisApp::instance()->messageBar()->pushMessage( tr( "No part split done" ), tr( "Cut edges detected. Make sure the line splits parts into multiple parts." ), Qgis::Warning, QgisApp::instance()->messageTimeout() ); } else if ( returnCode == QgsGeometry::OperationResult::InvalidBaseGeometry ) { QgisApp::instance()->messageBar()->pushMessage( tr( "No part split done" ), tr( "The geometry is invalid. Please repair before trying to split it." ), Qgis::Warning, QgisApp::instance()->messageTimeout() ); } else if ( returnCode != QgsGeometry::OperationResult::Success ) { //several intersections but only one split (most likely line) QgisApp::instance()->messageBar()->pushMessage( tr( "Split error" ), tr( "An error occurred during splitting." ), Qgis::Warning, QgisApp::instance()->messageTimeout() ); } stopCapturing(); } }
34.619403
163
0.580513
[ "geometry", "vector", "transform" ]
c031e17fcb121d4aa204e3c77a2b8a9640df9ee6
3,972
cpp
C++
Equinox/GameObject.cpp
CLENJOPOMI/EquinoxEngine
d8bfa29188f9f25818c95e746ee66d237e46d25f
[ "MIT" ]
2
2017-02-05T15:45:46.000Z
2017-02-05T15:45:53.000Z
Equinox/GameObject.cpp
CLENJOPOMI/Enjopongine
d8bfa29188f9f25818c95e746ee66d237e46d25f
[ "MIT" ]
73
2017-01-17T20:34:24.000Z
2017-08-29T16:57:26.000Z
Equinox/GameObject.cpp
CLENJOPOMI/EquinoxEngine
d8bfa29188f9f25818c95e746ee66d237e46d25f
[ "MIT" ]
1
2017-11-09T19:32:50.000Z
2017-11-09T19:32:50.000Z
#include "GameObject.h" #include "BaseComponent.h" #include "Globals.h" #include <GL/glew.h> #include "TransformComponent.h" #include <MathGeoLib/include/Math/float4x4.h> #include "Engine.h" #include "ModuleEditor.h" GameObject::GameObject() { BoundingBox.SetNegativeInfinity(); } GameObject::~GameObject() { } void GameObject::SetParent(GameObject* new_parent) { if(_parent != nullptr) { _parent->RemoveChild(this); } new_parent->_childs.push_back(this); _parent = new_parent; } GameObject* GameObject::GetParent() const { return _parent; } const std::vector<GameObject*>& GameObject::GetChilds() const { return _childs; } void GameObject::AddChild(GameObject* child) { if (child != nullptr) { child->SetParent(this); } } void GameObject::RemoveChild(const GameObject* child) { if(!_childs.empty()) { for (auto it = _childs.begin(); it != _childs.cend(); ++it) { if (*it == child) { _childs.erase(it); break; } } } } const std::list<BaseComponent*>& GameObject::GetComponents() const { return _components; } void GameObject::AddComponent(BaseComponent* component) { if (component != nullptr) { component->Parent = this; _components.push_back(component); if (component->Name == "Transform") _transform = static_cast<TransformComponent*>(component); } } BaseComponent* GameObject::GetComponentByName(const std::string& name) const { for (BaseComponent* component : _components) { if (component->Name == name) return component; } return nullptr; } void GameObject::DeleteComponentByName(const std::string& name) { if(!_components.empty()) { for (auto it = _components.begin(); it != _components.cend(); ++it) { if ((*it)->Name == name) { _components.erase(it); (*it)->CleanUp(); RELEASE(*it); } } } } void GameObject::DeleteComponent(BaseComponent* component) { _components.remove(component); } TransformComponent* GameObject::GetTransform() const { return _transform; } void GameObject::DrawBoundingBox() { ::DrawBoundingBox(BoundingBox); } void GameObject::DrawHierachy() { GLboolean light = glIsEnabled(GL_LIGHTING); glDisable(GL_LIGHTING); glColor4f(0.f, 0.f, 1.f, 1.f); float4x4 transform = float4x4::identity; for (GameObject* child : _childs) child->DrawHierachy(transform); glColor4f(1.f, 1.f, 1.f, 1.f); if (light) glEnable(GL_LIGHTING); } void GameObject::DrawHierachy(const float4x4& transformMatrix) { float4x4 localMatrix = transformMatrix * _transform->GetTransformMatrix(); if (_parent && _parent->_transform) { glBegin(GL_LINES); float3 parentPos = transformMatrix.Col3(3); glVertex3fv(reinterpret_cast<GLfloat*>(&parentPos)); float3 position = localMatrix.Col3(3); glVertex3fv(reinterpret_cast<GLfloat*>(&position)); glEnd(); } for (GameObject* child : _childs) child->DrawHierachy(localMatrix); } void GameObject::Update(float dt) { glPushMatrix(); glEnableClientState(GL_TEXTURE_COORD_ARRAY); for (BaseComponent* baseComponent : _components) { if (baseComponent->Enabled) { if (App->editor->IsPlaying()) { if (_isPlaying) baseComponent->Update(dt); else // TODO: When serialization is available, back up gameobject tree to disk { BaseComponent::CreateBackup(baseComponent); baseComponent->BeginPlay(); } } else { if (_isPlaying) // TODO: When serialization is available, restore gameobject tree from disk { baseComponent->EndPlay(); BaseComponent::RestoreBackup(baseComponent); } else baseComponent->EditorUpdate(App->editor->IsPaused() ? 0 : dt); } } } _isPlaying = App->editor->IsPlaying(); glBindTexture(GL_TEXTURE_2D, 0); glDisableClientState(GL_TEXTURE_COORD_ARRAY); for (GameObject* child : _childs) { child->Update(dt); } glPopMatrix(); } bool GameObject::CleanUp() { for (BaseComponent* component : _components) { component->CleanUp(); RELEASE(component); } return true; }
18.560748
95
0.694864
[ "vector", "transform" ]
c033331c1dd47f4846783b56b8419c74b524fdf4
13,167
cpp
C++
libglwinsys/glw_main.cpp
fcarreiro/genesis
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
[ "MIT" ]
null
null
null
libglwinsys/glw_main.cpp
fcarreiro/genesis
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
[ "MIT" ]
null
null
null
libglwinsys/glw_main.cpp
fcarreiro/genesis
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
[ "MIT" ]
null
null
null
#include <cstdlib> #include <windows.h> #include <string> #include <list> #include <gl/gl.h> #include "glwinsys.h" ////////////////////////////////////////////////////////////////////////// // glWinsys class constructor & destructor ////////////////////////////////////////////////////////////////////////// glWinsys::glWinsys() : m_Desktop(0), m_bMouseBoundaryCheck(false), m_uiCursorTexture(0), m_iCursorWidth(32), m_iCursorHeight(32), m_CursorAlpha(255), m_bHotSpotDebug(false) { // initialize variables } glWinsys::~glWinsys() { // destroy windows and uninitialze if needed free(); } ////////////////////////////////////////////////////////////////////////// // initialize() : Initializes virtual desktop ////////////////////////////////////////////////////////////////////////// bool glWinsys::initialize(int desk_width, int desk_height) { // previous instance? if(m_Desktop) return false; // create desktop m_Desktop = new glw_window(); if(!m_Desktop) return false; // set desktop size m_Desktop->setSize(desk_width, desk_height); // reset key states resetKeyStates(); // reset mouse position (center) m_MousePosition.x = desk_width / 2; m_MousePosition.y = desk_height / 2; // reset boundary check m_bMouseBoundaryCheck = false; // no error return true; } ////////////////////////////////////////////////////////////////////////// // free() : Destroys all the windows ////////////////////////////////////////////////////////////////////////// void glWinsys::free() { // destroy desktop delete m_Desktop; m_Desktop = 0; } ////////////////////////////////////////////////////////////////////////// // render() : Renders the whole window scene // this functions is just a renderall shortcut ////////////////////////////////////////////////////////////////////////// void glWinsys::render() const { render(GLWL_ALL); } ////////////////////////////////////////////////////////////////////////// // render() : Renders the selected layers ////////////////////////////////////////////////////////////////////////// void glWinsys::render(unsigned char layers) const { // if we haven't been initialized we return if(!m_Desktop) return; // save our 3d matrices glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); // start 2d mode glOrtho(0, m_Desktop->getWidth(), m_Desktop->getHeight(), 0, 0, 1); // save modified bits glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_LIGHTING_BIT); // setup new state glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_LIGHTING); glShadeModel(GL_FLAT); // blending options (translcency) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); // render windows if(layers & GLWL_WINDOWS) { m_Desktop->renderChildren(); } // render mouse if(layers & GLWL_MOUSE) { // draw cursor with a texture if we have it if(m_uiCursorTexture) { glBindTexture(GL_TEXTURE_2D, m_uiCursorTexture); glEnable(GL_TEXTURE_2D); } // or else draw a white rectangle else { glDisable(GL_TEXTURE_2D); } // blend modes and color glColor4ub(255, 255, 255, m_CursorAlpha); // draw it glBegin(GL_TRIANGLE_STRIP); glTexCoord2i(0, 1); glVertex2i(m_MousePosition.x, m_MousePosition.y); glTexCoord2i(0, 0); glVertex2i(m_MousePosition.x, m_MousePosition.y + m_iCursorHeight); glTexCoord2i(1, 1); glVertex2i(m_MousePosition.x + m_iCursorWidth, m_MousePosition.y); glTexCoord2i(1, 0); glVertex2i(m_MousePosition.x + m_iCursorWidth, m_MousePosition.y + m_iCursorHeight); glEnd(); // hot spot debug if(m_bHotSpotDebug) { // draw one white point with 4 black corners glDisable(GL_TEXTURE_2D); glBegin(GL_POINTS); glColor4ub(255, 255, 255, 255); glVertex2i(m_MousePosition.x + m_CursorHotSpot.x, m_MousePosition.y + m_CursorHotSpot.y); glColor4ub(0, 0, 0, 255); glVertex2i(m_MousePosition.x + m_CursorHotSpot.x - 1, m_MousePosition.y + m_CursorHotSpot.y - 1); glVertex2i(m_MousePosition.x + m_CursorHotSpot.x + 1, m_MousePosition.y + m_CursorHotSpot.y + 1); glVertex2i(m_MousePosition.x + m_CursorHotSpot.x - 1, m_MousePosition.y + m_CursorHotSpot.y + 1); glVertex2i(m_MousePosition.x + m_CursorHotSpot.x + 1, m_MousePosition.y + m_CursorHotSpot.y - 1); glEnd(); } } // restore bits glPopAttrib(); // back to our 3d matrices glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } ////////////////////////////////////////////////////////////////////////// // resetKeyStates() : Resets mouse and keyboard key states ////////////////////////////////////////////////////////////////////////// void glWinsys::resetKeyStates() { // clear arrays memset(m_Keys, 0, sizeof(m_Keys)); memset(m_MouseKeys, 0, sizeof(m_MouseKeys)); } ////////////////////////////////////////////////////////////////////////// // setMouseBoundCheck() : This function activates/deactivates the off-window // mouse boundary check ////////////////////////////////////////////////////////////////////////// void glWinsys::setMouseBoundCheck(bool check) { m_bMouseBoundaryCheck = check; } ////////////////////////////////////////////////////////////////////////// // setMousePos() : Sets winsys mouse position ////////////////////////////////////////////////////////////////////////// void glWinsys::setMousePos(int x, int y) { // check if it goes out of bounds if(m_bMouseBoundaryCheck && m_Desktop) { // x check if(x < 0) x = 0; else if(x > m_Desktop->getWidth()) x = m_Desktop->getWidth(); // y check if(y < 0) y = 0; else if(y > m_Desktop->getHeight()) y = m_Desktop->getHeight(); } // set mouse position m_MousePosition.x = x; m_MousePosition.y = y; } ////////////////////////////////////////////////////////////////////////// // setMouseRelPos() : Sets winsys mouse relative position ////////////////////////////////////////////////////////////////////////// void glWinsys::setMouseRelPos(int x, int y) { // save old position glw_point old_position = m_MousePosition; // set mouse new position m_MousePosition.x += x; m_MousePosition.y += y; // check if it goes out of bounds if(m_bMouseBoundaryCheck && m_Desktop) { // x check if(m_MousePosition.x < 0) { m_MousePosition.x = 0; } else if(m_MousePosition.x > m_Desktop->getWidth()) { m_MousePosition.x = m_Desktop->getWidth(); } // y check if(m_MousePosition.y < 0) { m_MousePosition.y = 0; } else if(m_MousePosition.y > m_Desktop->getHeight()) { m_MousePosition.y = m_Desktop->getHeight(); } } // find window at position before moving glw_window *topmost; topmost = m_Desktop->getTopmostAt(old_position.x + m_CursorHotSpot.x, old_position.y + m_CursorHotSpot.y); if(!topmost) return; // prepare message glw_point relative(m_MousePosition.x - old_position.x, m_MousePosition.y - old_position.y); // send the message topmost->sendMessage(GLWM_MOUSEMOVE, (glw_param) &m_MousePosition, (glw_param) &relative); } ////////////////////////////////////////////////////////////////////////// // getMousePos() : Queries winsys mouse position ////////////////////////////////////////////////////////////////////////// void glWinsys::getMousePos(int *x, int *y) const { // pass mouse position if(x) *x = m_MousePosition.x; if(y) *y = m_MousePosition.y; } ////////////////////////////////////////////////////////////////////////// // setDesktopSize() : Sets virtual desktop size ////////////////////////////////////////////////////////////////////////// void glWinsys::setDesktopSize(int width, int height) { // set new size if(m_Desktop) m_Desktop->setSize(width, height); } ////////////////////////////////////////////////////////////////////////// // getDesktopSize() : Gets virtual desktop size ////////////////////////////////////////////////////////////////////////// void glWinsys::getDesktopSize(int *width, int *height) const { // if we haven't initialized return if(!m_Desktop) return; // pass desktop size if(width) *width = m_Desktop->getWidth(); if(height) *height = m_Desktop->getHeight(); } ////////////////////////////////////////////////////////////////////////// // setCursorAlpha() : Sets mouse cursor alpha intensity ////////////////////////////////////////////////////////////////////////// void glWinsys::setCursorAlpha(unsigned char alpha) { m_CursorAlpha = alpha; } ////////////////////////////////////////////////////////////////////////// // setCursorSize() : Sets mouse cursor size ////////////////////////////////////////////////////////////////////////// void glWinsys::setCursorSize(int width, int height) { // check if(width <= 0 || height <= 0) return; // set m_iCursorWidth = width; m_iCursorHeight = height; } ////////////////////////////////////////////////////////////////////////// // setHotSpotDebug() : If enabled shows a point at the cursor's hot spot ////////////////////////////////////////////////////////////////////////// void glWinsys::setHotSpotDebug(bool state) { m_bHotSpotDebug = state; } ////////////////////////////////////////////////////////////////////////// // setCursorHotSpot() : Sets mouse cursor click point ////////////////////////////////////////////////////////////////////////// void glWinsys::setCursorHotSpot(int x, int y) { // check if(x <= 0 || y <= 0 || x > m_iCursorWidth || y > m_iCursorHeight) return; // set m_CursorHotSpot.x = x; m_CursorHotSpot.y = y; } ////////////////////////////////////////////////////////////////////////// // setCursorTexture() : Sets mouse cursor OpenGL texture ////////////////////////////////////////////////////////////////////////// void glWinsys::setCursorTexture(GLuint texture) { // if we provide a valid texture we set it if(texture > 0) m_uiCursorTexture = texture; } ////////////////////////////////////////////////////////////////////////// // setKeyPress() : Sets key state to active ////////////////////////////////////////////////////////////////////////// void glWinsys::setKeyPress(glw_key key) { m_Keys[key] = true; } ////////////////////////////////////////////////////////////////////////// // setKeyRelease() : Sets key state to inactive ////////////////////////////////////////////////////////////////////////// void glWinsys::setKeyRelease(glw_key key) { m_Keys[key] = false; } ////////////////////////////////////////////////////////////////////////// // getKeyState() : Returns key state (pressed/unpressed) ////////////////////////////////////////////////////////////////////////// bool glWinsys::getKeyState(glw_key key) const { return m_Keys[key]; } ////////////////////////////////////////////////////////////////////////// // setMousePress() : Sets key state to active ////////////////////////////////////////////////////////////////////////// void glWinsys::setMousePress(glw_mousekey key) { // we havent been initialized if(!m_Desktop) return; // set pressed key flag m_MouseKeys[key] = true; // find picked window (at mouse + hotspot) glw_window *topmost; topmost = m_Desktop->getTopmostAt(m_MousePosition.x + m_CursorHotSpot.x, m_MousePosition.y + m_CursorHotSpot.y); if(!topmost) return; // send picked window the message topmost->sendMessage(GLWM_MOUSEDOWN, (glw_param) key, (glw_param) &m_MousePosition); } ////////////////////////////////////////////////////////////////////////// // setMouseRelease() : Sets key state to inactive ////////////////////////////////////////////////////////////////////////// void glWinsys::setMouseRelease(glw_mousekey key) { // set released key flag m_MouseKeys[key] = false; // get topmost window glw_window *topmost; topmost = m_Desktop->getTopmost(); if(!topmost) return; // send picked window the message topmost->sendMessage(GLWM_MOUSEUP, (glw_param) key, (glw_param) &m_MousePosition); } ////////////////////////////////////////////////////////////////////////// // getMouseState() : Returns key state (pressed/unpressed) ////////////////////////////////////////////////////////////////////////// bool glWinsys::getMouseState(glw_mousekey key) const { return m_MouseKeys[key]; } ////////////////////////////////////////////////////////////////////////// // getDesktop() : Returns the root window ////////////////////////////////////////////////////////////////////////// glw_window *glWinsys::getDesktop() const { return m_Desktop; } ////////////////////////////////////////////////////////////////////////// // End //////////////////////////////////////////////////////////////////////////
28.316129
78
0.481127
[ "render", "3d" ]
c0351e7ba8db673d05926a38d44396b6bbb5e773
2,949
cpp
C++
cpp-examples/Aspose.Font.Examples.CPP/source/LoadFont/LoadCff.cpp
aspose-font/Aspose.Font-Doc-md
f524be19aeb010df7757eb3447d0f64cf93c7b85
[ "MIT" ]
null
null
null
cpp-examples/Aspose.Font.Examples.CPP/source/LoadFont/LoadCff.cpp
aspose-font/Aspose.Font-Doc-md
f524be19aeb010df7757eb3447d0f64cf93c7b85
[ "MIT" ]
null
null
null
cpp-examples/Aspose.Font.Examples.CPP/source/LoadFont/LoadCff.cpp
aspose-font/Aspose.Font-Doc-md
f524be19aeb010df7757eb3447d0f64cf93c7b85
[ "MIT" ]
null
null
null
#include "aspose_pch.h" #include "LoadCff.h" #include <system/io/path.h> #include <system/io/file_info.h> #include <system/io/file.h> #include <system/console.h> #include <system/array.h> #include <Aspose.Font.Cpp/src/Sources/FontFileDefinition.h> #include <Aspose.Font.Cpp/src/Sources/FontDefinition.h> #include <Aspose.Font.Cpp/src/Sources/ByteContentStreamSource.h> #include <Aspose.Font.Cpp/src/FontType.h> #include <Aspose.Font.Cpp/src/Font.h> #include <cstdint> using namespace Aspose::Font::Sources; namespace Aspose { namespace Font { namespace Examples { namespace LoadFont { RTTI_INFO_IMPL_HASH(84180077u, ::Aspose::Font::Examples::LoadFont::LoadCff, ThisTypeBaseTypesInfo); LoadCff::LoadCff() : Aspose::Font::Examples::LoadFont::LoadFontBase() { } void LoadCff::Run() { System::Console::WriteLine(u"\nRun load fonts of compact font format examples"); LoadExample1(); LoadExample2(); } void LoadCff::LoadExample1() { PrintExampleTitle(u"Loading from file CenturyGothic.cff using FileInfo object", 1); //ExampleStart: 1 System::String fontPath = System::IO::Path::Combine(get_DataDir(), u"CenturyGothic.cff"); System::String fontSource = u"file CenturyGothic.cff"; // Initialize FontDefinition object passing CFF as FontType value and using FontFileDefinition // based on FileInfo object, fileExtension value is calculated automatically from FileInfo fields. System::SharedPtr<FontFileDefinition> fileDef = System::MakeObject<FontFileDefinition>(System::MakeObject<System::IO::FileInfo>(fontPath)); System::SharedPtr<FontDefinition> fontDef = System::MakeObject<FontDefinition>(Aspose::Font::FontType::CFF, fileDef); // Load font and print results System::SharedPtr<Aspose::Font::Font> font = Aspose::Font::Font::Open(fontDef); PrintSimpleFontInfo(font, fontSource); //ExampleEnd: 1 } void LoadCff::LoadExample2() { PrintExampleTitle(u"Loading from byte array", 2); //ExampleStart: 2 System::String fontPath = System::IO::Path::Combine(get_DataDir(), u"CenturyGothic.cff"); System::String fontSource = u"memory byte array based on file CenturyGothic.cff"; // Load font binary data into byte array System::ArrayPtr<uint8_t> fontBytes = System::IO::File::ReadAllBytes(fontPath); // Initialize FontDefinition object passing CFF as FontType value, "cff" as fileExtension value, // and ByteContentStreamSource object based on fontBytes array System::SharedPtr<FontDefinition> fontDef = System::MakeObject<FontDefinition>(Aspose::Font::FontType::CFF, u"ttf", System::MakeObject<ByteContentStreamSource>(fontBytes)); // Load font and print results System::SharedPtr<Aspose::Font::Font> font = Aspose::Font::Font::Open(fontDef); PrintSimpleFontInfo(font, fontSource); //ExampleEnd: 2 } } // namespace LoadFont } // namespace Examples } // namespace Font } // namespace Aspose
34.694118
176
0.731095
[ "object" ]
c03b677f34c9404856c56ef182c7e489eb009cd1
1,507
hpp
C++
climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/InputEventMouseButton.hpp
jerry871002/CSE201-project
c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4
[ "MIT" ]
5
2021-05-27T21:50:33.000Z
2022-01-28T11:54:32.000Z
climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/InputEventMouseButton.hpp
jerry871002/CSE201-project
c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4
[ "MIT" ]
null
null
null
climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/InputEventMouseButton.hpp
jerry871002/CSE201-project
c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4
[ "MIT" ]
1
2021-01-04T21:12:05.000Z
2021-01-04T21:12:05.000Z
#ifndef GODOT_CPP_INPUTEVENTMOUSEBUTTON_HPP #define GODOT_CPP_INPUTEVENTMOUSEBUTTON_HPP #include <gdnative_api_struct.gen.h> #include <stdint.h> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include "InputEventMouse.hpp" namespace godot { class InputEventMouseButton : public InputEventMouse { struct ___method_bindings { godot_method_bind *mb_get_button_index; godot_method_bind *mb_get_factor; godot_method_bind *mb_is_doubleclick; godot_method_bind *mb_set_button_index; godot_method_bind *mb_set_doubleclick; godot_method_bind *mb_set_factor; godot_method_bind *mb_set_pressed; }; static ___method_bindings ___mb; static void *_detail_class_tag; public: static void ___init_method_bindings(); inline static size_t ___get_id() { return (size_t)_detail_class_tag; } static inline const char *___get_class_name() { return (const char *) "InputEventMouseButton"; } static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; } // enums // constants static InputEventMouseButton *_new(); // methods int64_t get_button_index() const; real_t get_factor(); bool is_doubleclick() const; void set_button_index(const int64_t button_index); void set_doubleclick(const bool doubleclick); void set_factor(const real_t factor); void set_pressed(const bool pressed); }; } #endif
27.4
245
0.79363
[ "object" ]
c03c17294bf34aa3126de76b624e3a006372e4bf
1,779
cpp
C++
BashuOJ-Code/5101.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/5101.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/5101.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<iomanip> #include<algorithm> #include<queue> #include<stack> #include<vector> #define ri register int #define ll long long using namespace std; const int MAXN=1005; vector<int>a[MAXN]; bool Flag=0; int N,M,part,Ans; int Color[MAXN],Belong[MAXN],Len[MAXN],dist[MAXN]; bool vst[MAXN]; inline const int GetInt() { int num=0,bj=1; char c=getchar(); while(!isdigit(c))bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(isdigit(c))num=num*10+c-'0',c=getchar(); return num*bj; } void DFS_Color(int u,int col) { Color[u]=col; vector<int>::iterator it; for(it=a[u].begin();it!=a[u].end();++it) { if(!Color[*it])DFS_Color(*it,3-col); else if(Color[*it]!=3-col){Flag=1;return;} } } inline bool Check() { for(ri i=1;i<=N;i++) { if(!Color[i]) { DFS_Color(i,1); if(Flag)return 1; } } return 0; } void DFS(int u) { Belong[u]=part; vector<int>::iterator it; for(it=a[u].begin();it!=a[u].end();++it) if(!Belong[*it])DFS(*it); } int BFS(int v0) { int ret=0; queue<int>q; memset(vst,0,sizeof(vst)); q.push(v0),dist[v0]=0,vst[v0]=1; while(!q.empty()) { int now=q.front();q.pop(); vector<int>::iterator it; for(it=a[now].begin();it!=a[now].end();++it) { if(vst[*it])continue; vst[*it]=1,dist[*it]=dist[now]+1; ret=max(ret,dist[*it]); q.push(*it); } } return ret; } int main() { N=GetInt(),M=GetInt(); for(ri i=1;i<=M;i++) { int u=GetInt(),v=GetInt(); a[u].push_back(v); a[v].push_back(u); } if(Check())return printf("-1\n"),0; for(ri i=1;i<=N;i++) if(!Belong[i])part++,DFS(i); for(ri i=1;i<=N;i++)Len[Belong[i]]=max(Len[Belong[i]],BFS(i));//ÇóÁ¬Í¨¿éµÄÖ±¾¶ for(ri i=1;i<=part;i++)Ans+=Len[i]; printf("%d\n",Ans); return 0; }
18.925532
80
0.602586
[ "vector" ]
c04be85a0184f4266fa8b6aea553d0dbf1d5aa7f
6,635
cpp
C++
src/ui/linux/TogglDesktop/autocompletecombobox.cpp
thomwiggers/toggldesktop
fd4796d89aa28eb77b9fc12217065d5e57aa07ee
[ "BSD-3-Clause" ]
null
null
null
src/ui/linux/TogglDesktop/autocompletecombobox.cpp
thomwiggers/toggldesktop
fd4796d89aa28eb77b9fc12217065d5e57aa07ee
[ "BSD-3-Clause" ]
null
null
null
src/ui/linux/TogglDesktop/autocompletecombobox.cpp
thomwiggers/toggldesktop
fd4796d89aa28eb77b9fc12217065d5e57aa07ee
[ "BSD-3-Clause" ]
null
null
null
#include "autocompletecombobox.h" #include "autocompletelistmodel.h" #include "autocompletelistview.h" #include <QDebug> AutocompleteComboBox::AutocompleteComboBox(QWidget *parent) : QComboBox(parent) , completer(new AutocompleteCompleter(this)) , proxyModel(new AutocompleteProxyModel(this)) , listView(qobject_cast<AutocompleteListView*>(completer->popup())) { setEditable(true); completer->installEventFilter(this); listView->installEventFilter(this); lineEdit()->installEventFilter(this); lineEdit()->setFrame(false); completer->setModel(proxyModel); setCompleter(completer); disconnect(completer, SIGNAL(highlighted(QString)), lineEdit(), nullptr); connect(listView, &AutocompleteListView::visibleChanged, this, &AutocompleteComboBox::onDropdownVisibleChanged); connect(lineEdit(), &QLineEdit::textEdited, proxyModel, &AutocompleteProxyModel::setFilterFixedString); connect(listView, &AutocompleteListView::selected, this, &AutocompleteComboBox::onDropdownSelected); } void AutocompleteComboBox::setModel(QAbstractItemModel *model) { proxyModel->setSourceModel(model); } void AutocompleteComboBox::showPopup() { completer->complete(); } bool AutocompleteComboBox::eventFilter(QObject *o, QEvent *e) { // this is an ugly hack, this SHOULD happen in the FocusIn event but that actually never occurs if (o == lineEdit()) { auto retval = QComboBox::eventFilter(o, e); disconnect(completer, SIGNAL(highlighted(QString)), lineEdit(), nullptr); // there were text rendering glitches, this fixes the issue by forcing a repaint on every keypress if (e->type() == QEvent::KeyPress) { lineEdit()->repaint(); } return retval; } else if (e->type() == QEvent::KeyPress) { auto ke = reinterpret_cast<QKeyEvent*>(e); switch (ke->key()) { case Qt::Key_Tab: case Qt::Key_Escape: cancelSelection(); return true; case Qt::Key_Enter: case Qt::Key_Return: { if (ke->modifiers() & Qt::CTRL) { cancelSelection(); e->ignore(); return true; } if (listView->currentIndex().isValid()) { listView->keyPressEvent(ke); } else { listView->hide(); emit returnPressed(); } return true; } case Qt::Key_PageDown: case Qt::Key_PageUp: case Qt::Key_Up: case Qt::Key_Down: if (!listView->isVisible()) completer->complete(); else listView->keyPressEvent(ke); return true; default: QComboBox::keyPressEvent(ke); //lineEdit()->keyPressEvent(ke); return true; } } else { return QComboBox::eventFilter(o, e); } } AutocompleteView *AutocompleteComboBox::currentView() { return qvariant_cast<AutocompleteView*>(listView->currentIndex().data(Qt::UserRole)); } void AutocompleteComboBox::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Enter: case Qt::Key_Return: if (event->modifiers() & Qt::CTRL) { event->ignore(); return; } emit returnPressed(); break; case Qt::Key_PageDown: case Qt::Key_PageUp: case Qt::Key_Down: case Qt::Key_Up: if (!listView->isVisible()) completer->complete(); else listView->keyPressEvent(event); break; default: QComboBox::keyPressEvent(event); } } void AutocompleteComboBox::onDropdownVisibleChanged() { if (listView->isVisible()) { proxyModel->setFilterFixedString(currentText()); } } void AutocompleteComboBox::onDropdownSelected(AutocompleteView *item) { if (item) { switch (item->Type) { case 0: emit projectSelected(item->ProjectLabel, item->ProjectID, item->ProjectColor, item->TaskLabel, item->TaskID); emit billableChanged(item->Billable); emit tagsChanged(item->Tags); emit timeEntrySelected(item->Text); setCurrentText(item->Description); break; case 1: emit projectSelected(item->ProjectLabel, item->ProjectID, item->ProjectColor, item->TaskLabel, item->TaskID); emit billableChanged(item->Billable); setCurrentText(item->ProjectLabel + (item->ClientLabel.isEmpty() ? "" : ". " + item->ClientLabel)); break; case 2: emit projectSelected(item->Text, item->ProjectID, item->ProjectColor, QString(), 0); setCurrentText(item->ProjectLabel + (item->ClientLabel.isEmpty() ? "" : ". " + item->ClientLabel)); break; default: break; } } emit activated(listView->currentIndex().row()); } void AutocompleteComboBox::cancelSelection() { listView->setVisible(false); } AutocompleteCompleter::AutocompleteCompleter(QWidget *parent) : QCompleter(parent) { setMaxVisibleItems(20); setPopup(new AutocompleteListView(parent)); setCompletionMode(QCompleter::UnfilteredPopupCompletion); } bool AutocompleteCompleter::eventFilter(QObject *o, QEvent *e) { // completely ignore key events in the filter and let the combobox handle them if (e->type() == QEvent::KeyPress) { return false; } return QCompleter::eventFilter(o, e); } AutocompleteProxyModel::AutocompleteProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { setFilterRole(Qt::UserRole); } bool AutocompleteProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { QString input = filterRegExp().pattern(); QStringList words = input.split(" "); auto view = qvariant_cast<AutocompleteView*>(sourceModel()->data(sourceModel()->index(source_row, 0), Qt::UserRole)); for (auto word : words) { if (word.isEmpty() && words.count() > 1) continue; if (view->_Children.isEmpty()) { if (view->Description.contains(word, Qt::CaseInsensitive)) return true; if (view->Text.contains(word, Qt::CaseInsensitive)) return true; } for (auto v : view->_Children) { if (v->Description.contains(word, Qt::CaseInsensitive)) return true; if (v->Text.contains(word, Qt::CaseInsensitive)) return true; } } return false; }
33.680203
121
0.617634
[ "model" ]
c04c82b3fcd220e7ed1b5edd032a2a67e8a60d42
4,696
cpp
C++
skia/tools/viewer/NIMASlide.cpp
jiangkang/renderer-dog
8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85
[ "MIT" ]
1
2019-03-25T15:37:48.000Z
2019-03-25T15:37:48.000Z
tools/viewer/NIMASlide.cpp
bryphe/esy-skia
9810a02f28270535de10b584bffc536182224c83
[ "BSD-3-Clause" ]
1
2020-09-13T11:08:17.000Z
2020-09-13T11:08:17.000Z
skia/tools/viewer/NIMASlide.cpp
jiangkang/renderer-dog
8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85
[ "MIT" ]
null
null
null
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "NIMASlide.h" #include "AnimTimer.h" #include "Resources.h" #include "SkOSPath.h" #include "imgui.h" #include "nima/NimaActor.h" #include <algorithm> #include <cmath> using namespace sk_app; using namespace nima; // ImGui expects an array of const char* when displaying a ListBox. This function is for an // overload of ImGui::ListBox that takes a getter so that ListBox works with // std::vector<std::string>. static bool vector_getter(void* v, int index, const char** out) { auto vector = reinterpret_cast<std::vector<std::string>*>(v); *out = vector->at(index).c_str(); return true; } ////////////////////////////////////////////////////////////////////////////////////////////////// NIMASlide::NIMASlide(const SkString& name, const SkString& path) : fBasePath() , fActor(nullptr) , fAnimationIndex(0) , fPlaying(true) , fTime(0.0f) , fRenderFlags(0) { fName = name; // Get the path components. SkString baseName = SkOSPath::Basename(path.c_str()); baseName.resize(baseName.size() - 5); SkString dirName = SkOSPath::Dirname(path.c_str()); SkString basePath = SkOSPath::Join(dirName.c_str(), baseName.c_str()); // Save the base path. fBasePath = std::string(basePath.c_str()); } NIMASlide::~NIMASlide() {} SkISize NIMASlide::getDimensions() const { return SkISize::MakeEmpty(); // TODO } void NIMASlide::draw(SkCanvas* canvas) { canvas->save(); for (int i = 0; i < 10; i ++) { for (int j = 0; j < 10; j ++) { canvas->save(); canvas->translate(1250 - 250 * i, 1250 - 250 * j); canvas->scale(0.5, -0.5); // Render the actor. fActor->setAnimation(fAnimationIndex); fActor->render(canvas, fRenderFlags); canvas->restore(); } } canvas->restore(); // Render the GUI. this->renderGUI(); } void NIMASlide::load(SkScalar winWidth, SkScalar winHeight) { this->resetActor(); } void NIMASlide::unload() { // Discard resources. fActor.reset(nullptr); } bool NIMASlide::animate(const AnimTimer& timer) { // Apply the animation. if (fActor) { float time = std::fmod(timer.secs(), fActor->duration()); fActor->seek(time); } return true; } bool NIMASlide::onChar(SkUnichar c) { return false; } bool NIMASlide::onMouse(SkScalar x, SkScalar y, Window::InputState state, uint32_t modifiers) { return false; } void NIMASlide::resetActor() { // Create the actor. std::string nimaPath = fBasePath + ".nima"; std::string texturePath = fBasePath + ".png"; fActor = std::make_unique<NimaActor>(nimaPath, texturePath); } void NIMASlide::renderGUI() { ImGui::SetNextWindowSize(ImVec2(300, 0)); ImGui::Begin("NIMA"); // List of animations. auto animations = const_cast<std::vector<std::string>&>(fActor->getAnimationNames()); ImGui::PushItemWidth(-1); if (ImGui::ListBox("Animations", &fAnimationIndex, vector_getter, reinterpret_cast<void*>(&animations), animations.size(), 5)) { resetActor(); } // Playback control. ImGui::Spacing(); if (ImGui::Button("Play")) { fPlaying = true; } ImGui::SameLine(); if (ImGui::Button("Pause")) { fPlaying = false; } // Time slider. ImGui::PushItemWidth(-1); ImGui::SliderFloat("Time", &fTime, 0.0f, fActor->duration(), "Time: %.3f"); // Backend control. int useImmediate = SkToBool(fRenderFlags & kImmediate_RenderFlag); ImGui::Spacing(); ImGui::RadioButton("Skia Backend", &useImmediate, 0); ImGui::RadioButton("Immediate Backend", &useImmediate, 1); if (useImmediate) { fRenderFlags |= kImmediate_RenderFlag; } else { fRenderFlags &= ~kImmediate_RenderFlag; } // Cache control. bool useCache = SkToBool(fRenderFlags & kCache_RenderFlag); ImGui::Spacing(); ImGui::Checkbox("Cache Vertices", &useCache); if (useCache) { fRenderFlags |= kCache_RenderFlag; } else { fRenderFlags &= ~kCache_RenderFlag; } // Bounding box toggle. bool drawBounds = SkToBool(fRenderFlags & kBounds_RenderFlag); ImGui::Spacing(); ImGui::Checkbox("Draw Bounds", &drawBounds); if (drawBounds) { fRenderFlags |= kBounds_RenderFlag; } else { fRenderFlags &= ~kBounds_RenderFlag; } ImGui::End(); }
26.234637
98
0.600937
[ "render", "vector" ]
c04e4bd701a9b342ad71f037b106deaa6edfd6dd
3,331
cc
C++
components/query_tiles/android/tile_provider_bridge.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/query_tiles/android/tile_provider_bridge.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/query_tiles/android/tile_provider_bridge.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/query_tiles/android/tile_provider_bridge.h" #include <memory> #include <string> #include <vector> #include "base/android/callback_android.h" #include "base/android/jni_string.h" #include "base/bind.h" #include "components/query_tiles/android/tile_conversion_bridge.h" #include "components/query_tiles/jni_headers/TileProviderBridge_jni.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/image/image.h" using base::android::AttachCurrentThread; namespace query_tiles { namespace { const char kTileProviderBridgeKey[] = "tile_provider_bridge"; void RunGetTilesCallback(const JavaRef<jobject>& j_callback, std::vector<Tile> tiles) { JNIEnv* env = AttachCurrentThread(); RunObjectCallbackAndroid( j_callback, TileConversionBridge::CreateJavaTiles(env, std::move(tiles))); } void RunGetTileCallback(const JavaRef<jobject>& j_callback, absl::optional<Tile> tile) { JNIEnv* env = AttachCurrentThread(); RunObjectCallbackAndroid( j_callback, TileConversionBridge::CreateJavaTiles( env, tile.has_value() ? std::move(tile->sub_tiles) : std::vector<std::unique_ptr<Tile>>())); } } // namespace // static ScopedJavaLocalRef<jobject> TileProviderBridge::GetBridgeForTileService( TileService* tile_service) { if (!tile_service->GetUserData(kTileProviderBridgeKey)) { tile_service->SetUserData( kTileProviderBridgeKey, std::make_unique<TileProviderBridge>(tile_service)); } TileProviderBridge* bridge = static_cast<TileProviderBridge*>( tile_service->GetUserData(kTileProviderBridgeKey)); return ScopedJavaLocalRef<jobject>(bridge->java_obj_); } TileProviderBridge::TileProviderBridge(TileService* tile_service) : tile_service_(tile_service) { DCHECK(tile_service_); JNIEnv* env = base::android::AttachCurrentThread(); java_obj_.Reset( env, Java_TileProviderBridge_create(env, reinterpret_cast<int64_t>(this)) .obj()); } TileProviderBridge::~TileProviderBridge() { JNIEnv* env = base::android::AttachCurrentThread(); Java_TileProviderBridge_clearNativePtr(env, java_obj_); } void TileProviderBridge::GetQueryTiles(JNIEnv* env, const JavaParamRef<jobject>& jcaller, const JavaParamRef<jstring>& j_tile_id, const JavaParamRef<jobject>& jcallback) { // TODO(qinmin): refactor TileService to use a single call to handle both // cases. if (j_tile_id.is_null()) { tile_service_->GetQueryTiles(base::BindOnce( &RunGetTilesCallback, ScopedJavaGlobalRef<jobject>(jcallback))); } else { tile_service_->GetTile( ConvertJavaStringToUTF8(env, j_tile_id), base::BindOnce(&RunGetTileCallback, ScopedJavaGlobalRef<jobject>(jcallback))); } } void TileProviderBridge::OnTileClicked(JNIEnv* env, const JavaParamRef<jstring>& j_tile_id) { tile_service_->OnTileClicked(ConvertJavaStringToUTF8(env, j_tile_id)); } } // namespace query_tiles
34.340206
80
0.698589
[ "vector" ]
c04f03ba53761b502ab84c12a02e4f5557c91e6b
5,739
hpp
C++
openstudiocore/src/pat_app/RunTabController.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
4
2015-05-02T21:04:15.000Z
2015-10-28T09:47:22.000Z
openstudiocore/src/pat_app/RunTabController.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
null
null
null
openstudiocore/src/pat_app/RunTabController.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
1
2020-11-12T21:52:36.000Z
2020-11-12T21:52:36.000Z
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef PATAPP_RUNTABCONTROLLER_HPP #define PATAPP_RUNTABCONTROLLER_HPP #include "../shared_gui_components/OSListController.hpp" #include "../shared_gui_components/OSListView.hpp" #include "PatConstants.hpp" #include "../analysis/Analysis.hpp" #include "../analysis/DataPoint.hpp" #include "../analysis/Measure.hpp" #include "../analysis/Problem.hpp" #include "../analysisdriver/AnalysisDriverEnums.hpp" #include "../runmanager/lib/Job.hpp" #include <QObject> #include <QPointer> #include <QSharedPointer> namespace openstudio { class VagrantProvider; namespace pat { class RunView; class DataPointRunListController; class DataPointRunItemDelegate; /// Controller class for the entire run tab class RunTabController : public QObject { Q_OBJECT public: QPointer<RunView> runView; RunTabController(); virtual ~RunTabController(); public slots: void onPlayButtonClicked(); void onIterationProgress(); void onDataPointQueued(const openstudio::UUID& analysis, const openstudio::UUID& dataPoint); void onDataPointResultsCleared(const openstudio::UUID& dataPoint); void requestRefresh(); void refresh(); void onRadianceEnabledChanged(bool t_radianceEnabled); void seedChanged(); bool checkSeedForRadianceWarningsAndErrors(boost::optional<model::Model> &t_seedModel, runmanager::RunManager &t_runManager); private: bool m_refreshScheduled; bool m_radianceEnabled; QSharedPointer<DataPointRunListController> m_dataPointRunListController; QSharedPointer<DataPointRunItemDelegate> m_dataPointRunItemDelegate; REGISTER_LOGGER("openstudio.pat.RunTabController"); // converts UUID to index i and emits signal to get DataPoint job details to refresh void emitDataPointChanged(const openstudio::UUID& dataPoint); void showRadianceWarningsAndErrors(const std::vector<std::string> & warnings, const std::vector<std::string> & errors); }; /// Controller class for the list of data points on the run tab class DataPointRunListController : public OSListController { Q_OBJECT public: DataPointRunListController(const openstudio::analysis::Analysis& analysis); virtual ~DataPointRunListController() {} /// The OSListItem returned will be a DataPointRunListItem QSharedPointer<OSListItem> itemAt(int i) override; int count() override; void emitItemChanged(int i); private: openstudio::analysis::Analysis m_analysis; }; /// Item representing a data point on the run tab class DataPointRunListItem : public OSListItem { Q_OBJECT public: DataPointRunListItem(const openstudio::analysis::DataPoint& dataPoint); virtual ~DataPointRunListItem() {} openstudio::analysis::DataPoint dataPoint() const; private: std::vector<openstudio::analysis::DataPoint> dataPoints(); openstudio::analysis::DataPoint m_dataPoint; }; /// Delegate which creates a DataPointRunListItem class DataPointRunItemDelegate : public OSItemDelegate { Q_OBJECT public: virtual ~DataPointRunItemDelegate() {} /// Widget returned will be a DataPointRunListItem QWidget * view(QSharedPointer<OSListItem> dataSource) override; signals: void dataPointResultsCleared(const openstudio::UUID& dataPoint); }; /// Controller class for the list jobs for a data points on the run tab class DataPointJobController : public OSListController { Q_OBJECT public: DataPointJobController(const analysis::DataPoint& dataPoint); virtual ~DataPointJobController() {} /// The OSListItem returned will be a DataPointJobItem QSharedPointer<OSListItem> itemAt(int i) override; int count() override; private: std::vector<analysis::WorkflowStepJob> getJobsByWorkflowStep(const openstudio::analysis::DataPoint& dataPoint); analysis::DataPoint m_dataPoint; }; /// Item representing a job for a data point on the run tab class DataPointJobItem : public OSListItem { Q_OBJECT public: DataPointJobItem(const analysis::WorkflowStepJob& workflowStepJob); virtual ~DataPointJobItem() {} analysis::WorkflowStepJob workflowStepJob() const; private: analysis::WorkflowStepJob m_workflowStepJob; }; /// Delegate which creates a DataPointJobItemView class DataPointJobItemDelegate : public OSItemDelegate { Q_OBJECT public: virtual ~DataPointJobItemDelegate() {} /// Widget returned will be a DataPointJobItemView QWidget * view(QSharedPointer<OSListItem> dataSource) override; }; } } // openstudio #endif // PATAPP_RUNTABCONTROLLER_HPP
25.968326
130
0.709531
[ "vector", "model" ]
c04f28b501d15f3b754113b6095dd65252a630c5
18,681
cpp
C++
driver/src/sick_generic_laser.cpp
wdross/sick_scan_xd
4359c3db964972c6e562767525eeec7ecfbc3628
[ "Apache-2.0" ]
null
null
null
driver/src/sick_generic_laser.cpp
wdross/sick_scan_xd
4359c3db964972c6e562767525eeec7ecfbc3628
[ "Apache-2.0" ]
null
null
null
driver/src/sick_generic_laser.cpp
wdross/sick_scan_xd
4359c3db964972c6e562767525eeec7ecfbc3628
[ "Apache-2.0" ]
null
null
null
/** * \file * \brief Laser Scanner Main Handling * Copyright (C) 2013, Osnabrueck University * Copyright (C) 2017,2018 Ing.-Buero Dr. Michael Lehning, Hildesheim * Copyright (C) 2017,2018 SICK AG, Waldkirch * * 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. * * 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 Osnabrueck University nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * Neither the name of SICK AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission * * Neither the name of Ing.-Buero Dr. Michael Lehning 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. * * Last modified: 21st Aug 2018 * * Authors: * Michael Lehning <michael.lehning@lehning.de> * Jochen Sprickerhof <jochen@sprickerhof.de> * Martin Günther <mguenthe@uos.de> * * */ #ifdef _MSC_VER //#define _WIN32_WINNT 0x0501 #pragma warning(disable: 4996) #pragma warning(disable: 4267) #endif #include <sick_scan/sick_ros_wrapper.h> #if defined LDMRS_SUPPORT && LDMRS_SUPPORT > 0 #include <sick_scan/ldmrs/sick_ldmrs_node.h> #endif #include <sick_scan/sick_scan_common_tcp.h> #include <sick_scan/sick_generic_parser.h> #include <sick_scan/sick_generic_laser.h> #include <sick_scan/sick_scan_services.h> #include <sick_scan/sick_generic_monitoring.h> #include "launchparser.h" #if __ROS_VERSION != 1 // launchparser for native Windows/Linux and ROS-2 #define USE_LAUNCHPARSER // settings and parameter by LaunchParser #endif #define _USE_MATH_DEFINES #include <math.h> #include <string> #include <stdio.h> #include <stdlib.h> #include <signal.h> #define DELETE_PTR(p) if(p){delete(p);p=0;} static bool isInitialized = false; static sick_scan::SickScanCommonTcp *s_scanner = NULL; static std::string versionInfo = "???"; void setVersionInfo(std::string _versionInfo) { versionInfo = _versionInfo; } std::string getVersionInfo() { return (versionInfo); } NodeRunState runState = scanner_init; /*! \brief splitting expressions like <tag>:=<value> into <tag> and <value> \param [In] tagVal: string expression like <tag>:=<value> \param [Out] tag: Tag after Parsing \param [Ozt] val: Value after Parsing \return Result of matching process (true: matching expression found, false: no match found) */ bool getTagVal(std::string tagVal, std::string &tag, std::string &val) { bool ret = false; std::size_t pos; pos = tagVal.find(":="); tag = ""; val = ""; if (pos == std::string::npos) { ret = false; } else { tag = tagVal.substr(0, pos); val = tagVal.substr(pos + 2); ret = true; } return (ret); } void rosSignalHandler(int signalRecv) { ROS_INFO_STREAM("Caught signal " << signalRecv << "\n"); ROS_INFO_STREAM("good bye\n"); ROS_INFO_STREAM("You are leaving the following version of this node:\n"); ROS_INFO_STREAM(getVersionInfo() << "\n"); if (s_scanner != NULL) { if (isInitialized) { s_scanner->stopScanData(); } runState = scanner_finalize; } rosShutdown(); } inline bool ends_with(std::string const &value, std::string const &ending) { if (ending.size() > value.size()) { return false; } return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } /*! \brief Parses an optional launchfile and sets all parameters. This function is used at startup to enable system independant parameter handling for native Linux/Windows, ROS-1 and ROS-2. Parameter are overwritten by optional commandline arguments \param argc: Number of commandline arguments \param argv: commandline arguments \param nodeName name of the ROS-node \return exit-code \sa main */ bool parseLaunchfileSetParameter(rosNodePtr nhPriv, int argc, char **argv) { std::string tag; std::string val; int launchArgcFileIdx = -1; for (int n = 1; n < argc; n++) { std::string extKey = ".launch"; std::string argv_str = argv[n]; if (ends_with(argv_str, extKey)) { launchArgcFileIdx = n; std::vector<std::string> tagList, typeList, valList; LaunchParser launchParser; bool ret = launchParser.parseFile(argv_str, tagList, typeList, valList); if (ret == false) { ROS_INFO_STREAM("Cannot parse launch file (check existence and content): >>>" << argv_str << "<<<\n"); exit(-1); } for (size_t i = 0; i < tagList.size(); i++) { printf("%-30s %-10s %-20s\n", tagList[i].c_str(), typeList[i].c_str(), valList[i].c_str()); if(typeList[i] == "bool" && !valList[i].empty()) rosSetParam(nhPriv, tagList[i], (bool)(valList[i][0] == '1' || valList[i][0] == 't' || valList[i][0] == 'T')); else if(typeList[i] == "int" && !valList[i].empty()) rosSetParam(nhPriv, tagList[i], (int)std::stoi(valList[i])); else if(typeList[i] == "float" && !valList[i].empty()) rosSetParam(nhPriv, tagList[i], (float)std::stof(valList[i])); else if(typeList[i] == "double" && !valList[i].empty()) rosSetParam(nhPriv, tagList[i], (double)std::stod(valList[i])); else // parameter type "string" rosSetParam(nhPriv, tagList[i], valList[i]); } } } for (int n = 1; n < argc; n++) { std::string argv_str = argv[n]; if (getTagVal(argv_str, tag, val)) { rosSetParam(nhPriv, tag, val); } else { if (launchArgcFileIdx != n) { ROS_ERROR_STREAM("## ERROR parseLaunchfileSetParameter(): Tag-Value setting not valid. Use pattern: <tag>:=<value> (e.g. hostname:=192.168.0.4) (Check the entry: " << argv_str << ")\n"); return false; } } } return true; } /*! \brief Internal Startup routine. \param argc: Number of Arguments \param argv: Argument variable \param nodeName name of the ROS-node \return exit-code \sa main */ int mainGenericLaser(int argc, char **argv, std::string nodeName, rosNodePtr nhPriv) { std::string tag; std::string val; bool doInternalDebug = false; bool emulSensor = false; for (int i = 0; i < argc; i++) { std::string argv_str = argv[i]; if (getTagVal(argv_str, tag, val)) { if (tag.compare("__internalDebug") == 0) { int debugState = 0; sscanf(val.c_str(), "%d", &debugState); if (debugState > 0) { doInternalDebug = true; } } if (tag.compare("__emulSensor") == 0) { int dummyState = 0; sscanf(val.c_str(), "%d", &dummyState); if (dummyState > 0) { emulSensor = true; } } } } #ifdef USE_LAUNCHPARSER if(!parseLaunchfileSetParameter(nhPriv, argc, argv)) { ROS_ERROR_STREAM("## ERROR sick_generic_laser: parseLaunchfileSetParameter() failed, aborting\n"); exit(-1); } #endif std::string scannerName; rosDeclareParam(nhPriv, "scanner_type", scannerName); rosGetParam(nhPriv, "scanner_type", scannerName); if (false == rosGetParam(nhPriv, "scanner_type", scannerName) || scannerName.empty()) { ROS_ERROR_STREAM("cannot find parameter ""scanner_type"" in the param set. Please specify scanner_type."); ROS_ERROR_STREAM("Try to set " << nodeName << " as fallback.\n"); scannerName = nodeName; } std::string cloud_topic = "cloud"; rosDeclareParam(nhPriv, "hostname", "192.168.0.4"); rosDeclareParam(nhPriv, "imu_enable", true); rosDeclareParam(nhPriv, "cloud_topic", cloud_topic); if (doInternalDebug) { #ifdef ROSSIMU nhPriv->setParam("name", scannerName); rossimu_settings(*nhPriv); // just for tiny simulations under Visual C++ #else rosSetParam(nhPriv, "hostname", "192.168.0.4"); rosSetParam(nhPriv, "imu_enable", true); rosSetParam(nhPriv, "cloud_topic", "cloud"); #endif } rosGetParam(nhPriv, "cloud_topic", cloud_topic); // check for TCP - use if ~hostname is set. bool useTCP = false; std::string hostname; if (rosGetParam(nhPriv, "hostname", hostname)) { useTCP = true; } bool changeIP = false; std::string sNewIp; rosDeclareParam(nhPriv, "new_IP_address", sNewIp); if (rosGetParam(nhPriv, "new_IP_address", sNewIp) && !sNewIp.empty()) { changeIP = true; } std::string port = "2112"; rosDeclareParam(nhPriv, "port", port); rosGetParam(nhPriv, "port", port); int timelimit = 5; rosDeclareParam(nhPriv, "timelimit", timelimit); rosGetParam(nhPriv, "timelimit", timelimit); bool subscribe_datagram = false; rosDeclareParam(nhPriv, "subscribe_datagram", subscribe_datagram); rosGetParam(nhPriv, "subscribe_datagram", subscribe_datagram); int device_number = 0; rosDeclareParam(nhPriv, "device_number", device_number); rosGetParam(nhPriv, "device_number", device_number); int verboseLevel = 0; rosDeclareParam(nhPriv, "verboseLevel", verboseLevel); rosGetParam(nhPriv, "verboseLevel", verboseLevel); std::string frame_id = "cloud"; rosDeclareParam(nhPriv, "frame_id", frame_id); rosGetParam(nhPriv, "frame_id", frame_id); if(scannerName == "sick_ldmrs") { #if defined LDMRS_SUPPORT && LDMRS_SUPPORT > 0 ROS_INFO("Initializing LDMRS..."); sick_scan::SickLdmrsNode ldmrs; int result = ldmrs.init(nhPriv, hostname, frame_id); if(result != sick_scan::ExitSuccess) { ROS_ERROR("LDMRS initialization failed."); return sick_scan::ExitError; } ROS_INFO("LDMRS initialized."); rosSpin(nhPriv); return sick_scan::ExitSuccess; #else ROS_ERROR("LDMRS not supported. Please build sick_scan with option LDMRS_SUPPORT"); return sick_scan::ExitError; #endif } sick_scan::SickGenericParser *parser = new sick_scan::SickGenericParser(scannerName); char colaDialectId = 'A'; // A or B (Ascii or Binary) float range_min = parser->get_range_min(); rosDeclareParam(nhPriv, "range_min", range_min); if (rosGetParam(nhPriv, "range_min", range_min)) { parser->set_range_min(range_min); } float range_max = parser->get_range_max(); rosDeclareParam(nhPriv, "range_max", range_max); if (rosGetParam(nhPriv, "range_max", range_max)) { parser->set_range_max(range_max); } float time_increment = parser->get_time_increment(); rosDeclareParam(nhPriv, "time_increment", time_increment); if (rosGetParam(nhPriv, "time_increment", time_increment)) { parser->set_time_increment(time_increment); } /* * Check, if parameter for protocol type is set */ bool use_binary_protocol = true; rosDeclareParam(nhPriv, "emul_sensor", emulSensor); if (true == rosGetParam(nhPriv, "emul_sensor", emulSensor)) { ROS_INFO_STREAM("Found emul_sensor overwriting default settings. Emulation:" << (emulSensor ? "True" : "False")); } rosDeclareParam(nhPriv, "use_binary_protocol", use_binary_protocol); if (true == rosGetParam(nhPriv, "use_binary_protocol", use_binary_protocol)) { ROS_INFO("Found sopas_protocol_type param overwriting default protocol:"); if (use_binary_protocol == true) { ROS_INFO("Binary protocol activated"); } else { if (parser->getCurrentParamPtr()->getNumberOfLayers() > 4) { rosSetParam(nhPriv, "sopas_protocol_type", true); use_binary_protocol = true; ROS_WARN("This scanner type does not support ASCII communication.\n" "Binary communication has been activated.\n" "The parameter \"sopas_protocol_type\" has been set to \"True\"."); } else { ROS_INFO("ASCII protocol activated"); } } parser->getCurrentParamPtr()->setUseBinaryProtocol(use_binary_protocol); } if (parser->getCurrentParamPtr()->getUseBinaryProtocol()) { colaDialectId = 'B'; } else { colaDialectId = 'A'; } sick_scan::SickScanMonitor* scan_msg_monitor = 0; sick_scan::PointCloudMonitor* pointcloud_monitor = 0; bool message_monitoring_enabled = true; int read_timeout_millisec_default = READ_TIMEOUT_MILLISEC_DEFAULT; int read_timeout_millisec_startup = READ_TIMEOUT_MILLISEC_STARTUP; int read_timeout_millisec_kill_node = READ_TIMEOUT_MILLISEC_KILL_NODE; rosDeclareParam(nhPriv, "message_monitoring_enabled", message_monitoring_enabled); rosGetParam(nhPriv, "message_monitoring_enabled", message_monitoring_enabled); rosDeclareParam(nhPriv, "read_timeout_millisec_default", read_timeout_millisec_default); rosGetParam(nhPriv, "read_timeout_millisec_default", read_timeout_millisec_default); rosDeclareParam(nhPriv, "read_timeout_millisec_startup", read_timeout_millisec_startup); rosGetParam(nhPriv, "read_timeout_millisec_startup", read_timeout_millisec_startup); rosDeclareParam(nhPriv, "read_timeout_millisec_kill_node", read_timeout_millisec_kill_node); rosGetParam(nhPriv, "read_timeout_millisec_kill_node", read_timeout_millisec_kill_node); int message_monitoring_read_timeout_millisec = read_timeout_millisec_default; int pointcloud_monitoring_timeout_millisec = read_timeout_millisec_kill_node; if(message_monitoring_enabled) { scan_msg_monitor = new sick_scan::SickScanMonitor(message_monitoring_read_timeout_millisec); #if __ROS_VERSION > 0 // point cloud monitoring in Linux-ROS pointcloud_monitor = new sick_scan::PointCloudMonitor(); pointcloud_monitor->startPointCloudMonitoring(nhPriv, pointcloud_monitoring_timeout_millisec, cloud_topic); #endif } bool start_services = true; sick_scan::SickScanServices* services = 0; int result = sick_scan::ExitError; //sick_scan::SickScanConfig cfg; while (rosOk() && runState != scanner_finalize) { switch (runState) { case scanner_init: ROS_INFO_STREAM("Start initialising scanner [Ip: " << hostname << "] [Port:" << port << "]"); // attempt to connect/reconnect DELETE_PTR(s_scanner); // disconnect scanner if (useTCP) { s_scanner = new sick_scan::SickScanCommonTcp(hostname, port, timelimit, nhPriv, parser, colaDialectId); } else { ROS_ERROR("TCP is not switched on. Probably hostname or port not set. Use roslaunch to start node."); exit(-1); } if (emulSensor) { s_scanner->setEmulSensor(true); } result = s_scanner->init(nhPriv); if (result == sick_scan::ExitError || result == sick_scan::ExitFatal) { ROS_ERROR("## ERROR in mainGenericLaser: init failed, retrying..."); // ROS_ERROR("init failed, shutting down"); continue; // return result; } // Start ROS services rosDeclareParam(nhPriv, "start_services", start_services); rosGetParam(nhPriv, "start_services", start_services); if (true == start_services) { services = new sick_scan::SickScanServices(nhPriv, s_scanner, parser->getCurrentParamPtr()->getUseBinaryProtocol()); ROS_INFO("SickScanServices: ros services initialized"); } isInitialized = true; signal(SIGINT, SIG_DFL); // change back to standard signal handler after initialising if (result == sick_scan::ExitSuccess) // OK -> loop again { if (changeIP) { runState = scanner_finalize; } runState = scanner_run; // after initialising switch to run state } else { runState = scanner_init; // If there was an error, try to restart scanner } break; case scanner_run: if (result == sick_scan::ExitSuccess) // OK -> loop again { rosSpinOnce(nhPriv); result = s_scanner->loopOnce(nhPriv); if(scan_msg_monitor && message_monitoring_enabled) // Monitor scanner messages { result = scan_msg_monitor->checkStateReinitOnError(nhPriv, runState, s_scanner, parser, services); if(result != sick_scan::ExitSuccess) // scanner re-init failed after read timeout or tcp error { ROS_ERROR("## ERROR in sick_generic_laser main loop: read timeout, scanner re-init failed"); } } } else { runState = scanner_finalize; // interrupt } case scanner_finalize: break; // ExitError or similiar -> interrupt while-Loop default: ROS_ERROR("Invalid run state in main loop"); break; } } if(pointcloud_monitor) pointcloud_monitor->stopPointCloudMonitoring(); DELETE_PTR(scan_msg_monitor); DELETE_PTR(pointcloud_monitor); DELETE_PTR(services); DELETE_PTR(s_scanner); // close connnect DELETE_PTR(parser); // close parser return result; }
33.598921
197
0.681495
[ "vector" ]
c04f9d792981885faa816601fb2f56986e44a8a3
221
hpp
C++
include/get_image_distance.hpp
Fadis/genetic_fm
415158b02e2c0dad8fafc81b5762b8889e493f10
[ "MIT" ]
34
2016-10-08T08:55:30.000Z
2021-08-17T03:19:54.000Z
include/get_image_distance.hpp
Fadis/genetic_fm
415158b02e2c0dad8fafc81b5762b8889e493f10
[ "MIT" ]
null
null
null
include/get_image_distance.hpp
Fadis/genetic_fm
415158b02e2c0dad8fafc81b5762b8889e493f10
[ "MIT" ]
1
2018-06-21T00:06:30.000Z
2018-06-21T00:06:30.000Z
#ifndef WAV2IMAGE_GET_IMAGE_DISTANCE_H #define WAV2IMAGE_GET_IMAGE_DISTANCE_H #include <cstdint> #include <vector> double get_image_distance( const std::vector< uint8_t > &l, const std::vector< uint8_t > &r ); #endif
20.090909
94
0.778281
[ "vector" ]
c051a52fc2e56d7a5c93c8b326d98831a119238c
4,355
cpp
C++
irohad/network/impl/block_loader_impl.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
1
2017-01-15T08:47:16.000Z
2017-01-15T08:47:16.000Z
irohad/network/impl/block_loader_impl.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
1
2017-11-08T02:34:24.000Z
2017-11-08T02:34:24.000Z
irohad/network/impl/block_loader_impl.cpp
laSinteZ/iroha
78f152a85ee2b3b86db7b705831938e96a186c36
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * 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 "network/impl/block_loader_impl.hpp" #include <grpc++/create_channel.h> using namespace iroha::ametsuchi; using namespace iroha::model; using namespace iroha::network; BlockLoaderImpl::BlockLoaderImpl( std::shared_ptr<PeerQuery> peer_query, std::shared_ptr<BlockQuery> block_query, std::shared_ptr<model::ModelCryptoProvider> crypto_provider) : peer_query_(std::move(peer_query)), block_query_(std::move(block_query)), crypto_provider_(crypto_provider) { log_ = logger::log("BlockLoaderImpl"); } rxcpp::observable<Block> BlockLoaderImpl::retrieveBlocks( model::Peer::KeyType peer_pubkey) { return rxcpp::observable<>::create<Block>( [this, peer_pubkey](auto subscriber) { nonstd::optional<Block> top_block; block_query_->getTopBlocks(1) .subscribe_on(rxcpp::observe_on_new_thread()) .as_blocking() .subscribe([&top_block](auto block) { top_block = block; }); if (not top_block.has_value()) { log_->error("Failed to retrieve top block"); subscriber.on_completed(); return; } auto peer = this->findPeer(peer_pubkey); if (not peer.has_value()) { log_->error("Cannot find peer"); subscriber.on_completed(); return; } proto::BlocksRequest request; grpc::ClientContext context; protocol::Block block; // request next block to our top request.set_height(top_block->height + 1); auto reader = this->getPeerStub(peer.value()).retrieveBlocks(&context, request); while (reader->Read(&block)) { auto &&result = factory_.deserialize(block); if (not crypto_provider_->verify(result)) { log_->error("Block signatures are invalid"); context.TryCancel(); } else { subscriber.on_next(result); } } reader->Finish(); subscriber.on_completed(); }); } nonstd::optional<Block> BlockLoaderImpl::retrieveBlock( Peer::KeyType peer_pubkey, Block::HashType block_hash) { auto peer = findPeer(peer_pubkey); if (not peer.has_value()) { log_->error("Cannot find peer"); return nonstd::nullopt; } proto::BlockRequest request; grpc::ClientContext context; protocol::Block block; // request block with specified hash request.set_hash(block_hash.to_string()); auto status = getPeerStub(peer.value()).retrieveBlock(&context, request, &block); if (not status.ok()) { log_->error(status.error_message()); return nonstd::nullopt; } auto &&result = factory_.deserialize(block); if (not crypto_provider_->verify(result)) { log_->error("Block signatures are invalid"); return nonstd::nullopt; } return result; } nonstd::optional<Peer> BlockLoaderImpl::findPeer(Peer::KeyType pubkey) { auto peers = peer_query_->getLedgerPeers(); if (not peers.has_value()) { log_->error("Failed to retrieve peers"); return nonstd::nullopt; } auto it = std::find_if( peers.value().begin(), peers.value().end(), [pubkey](auto peer) { return peer.pubkey == pubkey; }); if (it == peers.value().end()) { log_->error("Failed to find requested peer"); return nonstd::nullopt; } return *it; } proto::Loader::Stub &BlockLoaderImpl::getPeerStub(const Peer &peer) { auto it = peer_connections_.find(peer); if (it == peer_connections_.end()) { it = peer_connections_.insert(std::make_pair(peer, proto::Loader::NewStub( grpc::CreateChannel(peer.address, grpc::InsecureChannelCredentials())))).first; } return *it->second; }
31.557971
78
0.656028
[ "model" ]
c052e40d867a5529c99a6439e153d9322f76a3ef
33,154
cpp
C++
src/mame/drivers/mcatadv.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/mcatadv.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/mcatadv.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Paul Priest, David Haywood /****************************************************************************** 'Face' LINDA board driver by Paul Priest + David Haywood ******************************************************************************* Games on this Hardware Magical Cat Adventure (c)1993 Wintechno Nostradamus (c)1993 Face ******************************************************************************* Hardware Overview: Magical Cat (C) 1993 Wintechno Board Name: LINDA5 Main CPU: 68000-16 Sound CPU: Z80 Sound Chip: YMF286-K Custom: FACE FX1037 x1 038 x2 (As in Cave) Nostradamus (C) 1993 FACE Board Name: LINDA25 Main CPU: MC68000P12F 16MHz Sound CPU: Z8400B PS (Goldstar) Sound chip: YMF286-K & Y3016-F Graphics chips: 176 Pin PQFP 038 9330EX705 176 Pin PQFP 038 9320EX702 176 Pin PQFP FX1037 FACE FA01-2075 (Face Custom) OSC 28.000 MHz - SEOAN SX0-T100 OSC 16.000 MHz - Sunny SC0-010T 8 Way DIP Switch x 2 Push Button Test Switch Roms: NOS-PO-U 2740000PC-15 (68k Program) U29 - Odd NOS-PE-U 2740000PC-15 (68k Program) U30 - Even NOS-PS D27C020-15 (Z80 program) U9 As labelled on PCB, with location: NOS-SO-00.U83- NOS-SO-01.U85 \ NOS-SO-02.U87 | Sprites Odd/Even (These are 27C8001) NOS-SE-00.U82 | NOS-SE-01.U84 / NOS-SE-02.U86- U92 & U93 are unpopulated NOS-SN-00.U53 Sound samples (Near the YMF286-K) NOS-B0-00.U58- NOS-B0-01.U59 \ Background (separate for each 038 chip?) NOS-B1-00.U60 / NOS-B1-01.U61- YMF286-K is compatible to YM2610 - see psikyo.c driver 038 9320EX702 / 038 9330EX705 - see Cave.c driver Note # = Pin #1 PCB Layout: +----------------------------------------------------------------------------+ | ___________ |_ || NOS-B1-00 | J| |#___________| ________ ________ A| | ___________ __________ |NOS-PO-U| |NOS-PE-U| M| || NOS-B1-01 | | | #________| #________| M| |#___________| | 038 | ___________________ _______ A| | | 9330EX705| | MC68000P12F | |NOS-PS | | | |__________# | 16MHz | #_______| C| | #___________________| ___________ o| | ___________ __________ | Z8400B PS | n| || NOS-B0-00 | | | #___________| n| |#___________| | 038 | ______________ e| | ___________ | 9320EX702| SW1 | YMF286-K | c| || NOS-B0-01 | |__________# _________ #______________| t| |#___________| |FX1037 # SW2 _______ i| | |(C) Face | ___________ |Y3016-F# o| | |FA01-2075| | NOS-SN-00 | |_______| n| | |_________| #___________| _| | ______ ___ ___ ___ ___ ___ ___ | ||OSC 28| # N |# N |# N | E # N |# N |# N | E | |#______| | O || O || O | m | O || O || O | m | | | S || S || S | p | S || S || S | p | | Empty | | || | || | | t | | || | || | | t | | OSC | S || S || S | y | S || S || S | y | | ______ | E || E || E | | O || O || O | | ||OSC 16| | | || | || | | S | | || | || | | S | |#______| | 0 || 0 || 0 | C | 0 || 0 || 0 | C | | | 0 || 1 || 2 | K | 0 || 1 || 2 | K | | PUSHBTN |___||___||___| T |___||___||___| T | +----------------------------------------------------------------------------+ ******************************************************************************* Stephh's notes (based on the games M68000 code and some tests) : 1) "mcatadv*' - Player 1 Button 3 is only used in the "test" mode : * to select "OBJECT ROM CHECK" * in "BG ROM", to change the background number - Do NOT trust the "NORMAL TESTMODE" for the system inputs ! - The Japan version has extra GFX/anims and it's harder than the other set. 2) 'nost*' - When entering the "test mode", you need to press SERVICE1 to cycle through the different screens. ******************************************************************************* todo: Flip Screen ******************************************************************************* trivia: Magical Cat Adventure tests for 'MASICAL CAT ADVENTURE' in RAM on start-up and will write it there if not found, expecting a reset, great engrish ;-) ******************************************************************************/ #include "emu.h" #include "includes/mcatadv.h" #include "cpu/m68000/m68000.h" #include "cpu/z80/z80.h" #include "machine/gen_latch.h" #include "sound/ymopn.h" #include "screen.h" #include "speaker.h" template<int Chip> void mcatadv_state::get_banked_color(bool tiledim, u32 &color, u32 &pri, u32 &code) { pri |= 0x8; color += m_palette_bank[Chip] * 0x40; } /*** Main CPU ***/ #if 0 // mcat only.. install read handler? void mcatadv_state::mcat_coin_w(u8 data) { machine().bookkeeping().coin_counter_w(0, data & 0x10); machine().bookkeeping().coin_counter_w(1, data & 0x20); machine().bookkeeping().coin_lockout_w(0, ~data & 0x40); machine().bookkeeping().coin_lockout_w(1, ~data & 0x80); } #endif u16 mcatadv_state::mcat_wd_r() { if (!machine().side_effects_disabled()) m_watchdog->watchdog_reset(); return 0xc00; } void mcatadv_state::mcatadv_map(address_map &map) { map(0x000000, 0x0fffff).rom(); map(0x100000, 0x10ffff).ram(); // map(0x180018, 0x18001f).nopr(); // ? map(0x200000, 0x200005).rw(m_tilemap[0], FUNC(tilemap038_device::vregs_r), FUNC(tilemap038_device::vregs_w)); map(0x300000, 0x300005).rw(m_tilemap[1], FUNC(tilemap038_device::vregs_r), FUNC(tilemap038_device::vregs_w)); map(0x400000, 0x401fff).m(m_tilemap[0], FUNC(tilemap038_device::vram_16x16_map)); // Tilemap 0 map(0x500000, 0x501fff).m(m_tilemap[1], FUNC(tilemap038_device::vram_16x16_map)); // Tilemap 1 map(0x600000, 0x601fff).ram().w(m_palette, FUNC(palette_device::write16)).share("palette"); map(0x602000, 0x602fff).ram(); // Bigger than needs to be? map(0x700000, 0x707fff).ram().share("spriteram"); // Sprites, two halves for double buffering map(0x708000, 0x70ffff).ram(); // Tests more than is needed? map(0x800000, 0x800001).portr("P1"); map(0x800002, 0x800003).portr("P2"); // map(0x900000, 0x900000).w(FUNC(mcatadv_state::mcat_coin_w)); // Lockout / Counter MCAT Only map(0xa00000, 0xa00001).portr("DSW1"); map(0xa00002, 0xa00003).portr("DSW2"); map(0xb00000, 0xb0000f).ram().share("vidregs"); map(0xb00018, 0xb00019).w(m_watchdog, FUNC(watchdog_timer_device::reset16_w)); // NOST Only map(0xb0001e, 0xb0001f).r(FUNC(mcatadv_state::mcat_wd_r)); // MCAT Only map(0xc00001, 0xc00001).r("soundlatch2", FUNC(generic_latch_8_device::read)); map(0xc00000, 0xc00001).w("soundlatch", FUNC(generic_latch_8_device::write)).umask16(0x00ff).cswidth(16); } /*** Sound ***/ void mcatadv_state::mcatadv_sound_bw_w(u8 data) { m_soundbank->set_entry(data); } void mcatadv_state::mcatadv_sound_map(address_map &map) { map(0x0000, 0x3fff).rom(); // ROM map(0x4000, 0xbfff).bankr("soundbank"); // ROM map(0xc000, 0xdfff).ram(); // RAM map(0xe000, 0xe003).rw("ymsnd", FUNC(ym2610_device::read), FUNC(ym2610_device::write)); map(0xf000, 0xf000).w(FUNC(mcatadv_state::mcatadv_sound_bw_w)); } void mcatadv_state::mcatadv_sound_io_map(address_map &map) { map.global_mask(0xff); map(0x80, 0x80).r("soundlatch", FUNC(generic_latch_8_device::read)).w("soundlatch2", FUNC(generic_latch_8_device::write)); } void mcatadv_state::nost_sound_map(address_map &map) { map(0x0000, 0x7fff).rom(); // ROM map(0x8000, 0xbfff).bankr("soundbank"); // ROM map(0xc000, 0xdfff).ram(); // RAM } void mcatadv_state::nost_sound_io_map(address_map &map) { map.global_mask(0xff); map(0x00, 0x03).w("ymsnd", FUNC(ym2610_device::write)); map(0x04, 0x07).r("ymsnd", FUNC(ym2610_device::read)); map(0x40, 0x40).w(FUNC(mcatadv_state::mcatadv_sound_bw_w)); map(0x80, 0x80).r("soundlatch", FUNC(generic_latch_8_device::read)).w("soundlatch2", FUNC(generic_latch_8_device::write)); } /*** Inputs ***/ static INPUT_PORTS_START( mcatadv ) PORT_START("P1") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) // "Fire" PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) // "Jump" PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) // See notes PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0xfe00, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("P2") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) // "Fire" PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) // "Jump" PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_BIT( 0xfc00, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("DSW1") PORT_BIT( 0x00ff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW1:1") PORT_DIPSETTING( 0x0000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0100, DEF_STR( On ) ) PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("SW1:2") PORT_DIPSETTING( 0x0200, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_SERVICE_DIPLOC( 0x0400, IP_ACTIVE_LOW, "SW1:3" ) PORT_DIPNAME( 0x0800, 0x0800, "Coin Mode" ) PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x0800, "Mode 1" ) PORT_DIPSETTING( 0x0000, "Mode 2" ) PORT_DIPNAME( 0x3000, 0x3000, DEF_STR( Coin_A ) ) PORT_DIPLOCATION("SW1:5,6") PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0000) PORT_DIPSETTING( 0x1000, DEF_STR( 3C_1C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0000) PORT_DIPSETTING( 0x1000, DEF_STR( 2C_1C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0800) PORT_DIPSETTING( 0x3000, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0000, DEF_STR( 2C_3C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0800) PORT_DIPSETTING( 0x2000, DEF_STR( 1C_2C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0800) PORT_DIPSETTING( 0x2000, DEF_STR( 1C_4C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0000) PORT_DIPNAME( 0xc000, 0xc000, DEF_STR( Coin_B ) ) PORT_DIPLOCATION("SW1:7,8") PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0000) PORT_DIPSETTING( 0x4000, DEF_STR( 3C_1C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0000) PORT_DIPSETTING( 0x4000, DEF_STR( 2C_1C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0800) PORT_DIPSETTING( 0xc000, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0000, DEF_STR( 2C_3C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0800) PORT_DIPSETTING( 0x8000, DEF_STR( 1C_2C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0800) PORT_DIPSETTING( 0x8000, DEF_STR( 1C_4C ) ) PORT_CONDITION("DSW1", 0x0800, EQUALS, 0x0000) PORT_START("DSW2") PORT_BIT( 0x00ff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_DIPNAME( 0x0300, 0x0300, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SW2:1,2") PORT_DIPSETTING( 0x0200, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x0300, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x0100, DEF_STR( Hard ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Hardest ) ) PORT_DIPNAME( 0x0c00, 0x0c00, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW2:3,4") PORT_DIPSETTING( 0x0400, "2" ) PORT_DIPSETTING( 0x0c00, "3" ) PORT_DIPSETTING( 0x0800, "4" ) PORT_DIPSETTING( 0x0000, "5" ) PORT_DIPNAME( 0x3000, 0x3000, "Energy" ) PORT_DIPLOCATION("SW2:5,6") PORT_DIPSETTING( 0x3000, "3" ) PORT_DIPSETTING( 0x2000, "4" ) PORT_DIPSETTING( 0x1000, "5" ) PORT_DIPSETTING( 0x0000, "8" ) PORT_DIPNAME( 0xc000, 0xc000, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW2:7,8") PORT_DIPSETTING( 0x4000, "Upright 1 Player" ) PORT_DIPSETTING( 0xc000, "Upright 2 Players" ) PORT_DIPSETTING( 0x8000, DEF_STR( Cocktail ) ) // PORT_DIPSETTING( 0x0000, "Upright 2 Players" ) // duplicated setting (NEVER tested) INPUT_PORTS_END static INPUT_PORTS_START( nost ) PORT_START("P1") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_UNKNOWN ) // Button 2 in "test mode" PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) // Button 3 in "test mode" PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_UNKNOWN ) // "test" 3 in "test mode" PORT_BIT( 0x0800, IP_ACTIVE_HIGH, IPT_UNKNOWN ) // Must be LOW or startup freezes ! PORT_BIT( 0xf400, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("P2") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_UNKNOWN ) // Button 2 in "test mode" PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) // Button 3 in "test mode" PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_BIT( 0xfc00, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("DSW1") PORT_DIPNAME( 0x0300, 0x0300, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW1:1,2") PORT_DIPSETTING( 0x0200, "2" ) PORT_DIPSETTING( 0x0300, "3" ) PORT_DIPSETTING( 0x0100, "4" ) PORT_DIPSETTING( 0x0000, "5" ) PORT_DIPNAME( 0x0c00, 0x0c00, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SW1:3,4") PORT_DIPSETTING( 0x0800, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x0c00, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x0400, DEF_STR( Hard ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Hardest ) ) PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("SW1:5") PORT_DIPSETTING( 0x1000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW1:6") PORT_DIPSETTING( 0x0000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x2000, DEF_STR( On ) ) PORT_DIPNAME( 0xc000, 0xc000, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW1:7,8") PORT_DIPSETTING( 0x8000, "500k 1000k" ) PORT_DIPSETTING( 0xc000, "800k 1500k" ) PORT_DIPSETTING( 0x4000, "1000k 2000k" ) PORT_DIPSETTING( 0x0000, DEF_STR( None ) ) PORT_START("DSW2") PORT_DIPNAME( 0x0700, 0x0700, DEF_STR( Coin_A ) ) PORT_DIPLOCATION("SW2:1,2,3") PORT_DIPSETTING( 0x0200, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0400, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0100, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x0700, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0300, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x0600, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0500, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0x3800, 0x3800, DEF_STR( Coin_B ) ) PORT_DIPLOCATION("SW2:4,5,6") PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x1000, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x2000, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0800, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x3800, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x1800, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x3000, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x2800, DEF_STR( 1C_3C ) ) PORT_DIPUNUSED_DIPLOC( 0x4000, 0x4000, "SW2:7" ) /* Listed as "Unused" */ PORT_SERVICE_DIPLOC( 0x8000, IP_ACTIVE_LOW, "SW2:8" ) INPUT_PORTS_END /*** GFX Decode ***/ static GFXDECODE_START( gfx_mcatadv ) GFXDECODE_ENTRY( "bg0", 0, gfx_8x8x4_packed_msb, 0, 0x200 ) GFXDECODE_ENTRY( "bg1", 0, gfx_8x8x4_packed_msb, 0, 0x200 ) GFXDECODE_END void mcatadv_state::machine_start() { const u32 max = memregion("soundcpu")->bytes()/0x4000; m_soundbank->configure_entries(0, max, memregion("soundcpu")->base(), 0x4000); m_soundbank->set_entry(1); save_item(NAME(m_palette_bank)); } void mcatadv_state::mcatadv(machine_config &config) { /* basic machine hardware */ M68000(config, m_maincpu, XTAL(16'000'000)); /* verified on pcb */ m_maincpu->set_addrmap(AS_PROGRAM, &mcatadv_state::mcatadv_map); m_maincpu->set_vblank_int("screen", FUNC(mcatadv_state::irq1_line_hold)); Z80(config, m_soundcpu, XTAL(16'000'000)/4); /* verified on pcb */ m_soundcpu->set_addrmap(AS_PROGRAM, &mcatadv_state::mcatadv_sound_map); m_soundcpu->set_addrmap(AS_IO, &mcatadv_state::mcatadv_sound_io_map); /* video hardware */ screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER)); screen.set_refresh_hz(60); screen.set_vblank_time(ATTOSECONDS_IN_USEC(0)); screen.set_size(320, 256); screen.set_visarea(0, 320-1, 0, 224-1); screen.set_screen_update(FUNC(mcatadv_state::screen_update_mcatadv)); screen.screen_vblank().set(FUNC(mcatadv_state::screen_vblank_mcatadv)); screen.set_palette(m_palette); GFXDECODE(config, m_gfxdecode, m_palette, gfx_mcatadv); PALETTE(config, m_palette).set_format(palette_device::xGRB_555, 0x2000/2); TMAP038(config, m_tilemap[0]); m_tilemap[0]->set_gfxdecode_tag(m_gfxdecode); m_tilemap[0]->set_gfx(0); m_tilemap[0]->set_tile_callback(FUNC(mcatadv_state::get_banked_color<0>)); TMAP038(config, m_tilemap[1]); m_tilemap[1]->set_gfxdecode_tag(m_gfxdecode); m_tilemap[1]->set_gfx(1); m_tilemap[1]->set_tile_callback(FUNC(mcatadv_state::get_banked_color<1>)); WATCHDOG_TIMER(config, m_watchdog).set_time(attotime::from_seconds(3)); /* a guess, and certainly wrong */ /* sound hardware */ SPEAKER(config, "mono").front_center(); GENERIC_LATCH_8(config, "soundlatch").data_pending_callback().set_inputline(m_soundcpu, INPUT_LINE_NMI); GENERIC_LATCH_8(config, "soundlatch2"); ym2610_device &ymsnd(YM2610(config, "ymsnd", XTAL(16'000'000)/2)); /* verified on pcb */ ymsnd.irq_handler().set_inputline(m_soundcpu, 0); ymsnd.add_route(0, "mono", 0.32); ymsnd.add_route(1, "mono", 0.5); ymsnd.add_route(2, "mono", 0.5); } void mcatadv_state::nost(machine_config &config) { mcatadv(config); m_soundcpu->set_addrmap(AS_PROGRAM, &mcatadv_state::nost_sound_map); m_soundcpu->set_addrmap(AS_IO, &mcatadv_state::nost_sound_io_map); ym2610_device &ymsnd(YM2610(config.replace(), "ymsnd", XTAL(16'000'000)/2)); /* verified on pcb */ ymsnd.irq_handler().set_inputline(m_soundcpu, 0); ymsnd.add_route(0, "mono", 0.2); ymsnd.add_route(1, "mono", 0.5); ymsnd.add_route(2, "mono", 0.5); } ROM_START( mcatadv ) ROM_REGION( 0x100000, "maincpu", 0 ) /* M68000 */ ROM_LOAD16_BYTE( "mca-u30e", 0x00000, 0x80000, CRC(c62fbb65) SHA1(39a30a165d4811141db8687a4849626bef8e778e) ) ROM_LOAD16_BYTE( "mca-u29e", 0x00001, 0x80000, CRC(cf21227c) SHA1(4012811ebfe3c709ab49946f8138bc4bad881ef7) ) ROM_REGION( 0x020000, "soundcpu", 0 ) /* Z80-A */ ROM_LOAD( "u9.bin", 0x00000, 0x20000, CRC(fda05171) SHA1(2c69292573ec35034572fa824c0cae2839d23919) ) ROM_REGION( 0x800000, "sprdata", ROMREGION_ERASEFF ) /* Sprites */ ROM_LOAD16_BYTE( "mca-u82.bin", 0x000000, 0x100000, CRC(5f01d746) SHA1(11b241456e15299912ee365eedb8f9d5e5ca875d) ) ROM_LOAD16_BYTE( "mca-u83.bin", 0x000001, 0x100000, CRC(4e1be5a6) SHA1(cb19aad42dba54d6a4a33859f27254c2a3271e8c) ) ROM_LOAD16_BYTE( "mca-u84.bin", 0x200000, 0x080000, CRC(df202790) SHA1(f6ae54e799af195860ed0ab3c85138cf2f10efa6) ) ROM_LOAD16_BYTE( "mca-u85.bin", 0x200001, 0x080000, CRC(a85771d2) SHA1(a1817cd72f5bf0a4f24a37c782dc63ecec3b8e68) ) ROM_LOAD16_BYTE( "mca-u86e", 0x400000, 0x080000, CRC(017bf1da) SHA1(f6446a7219275c0eff62129f59fdfa3a6a3e06c8) ) ROM_LOAD16_BYTE( "mca-u87e", 0x400001, 0x080000, CRC(bc9dc9b9) SHA1(f525c9f994d5107752aa4d3a499ee376ec75f42b) ) ROM_REGION( 0x080000, "bg0", 0 ) /* BG0 */ ROM_LOAD( "mca-u58.bin", 0x000000, 0x080000, CRC(3a8186e2) SHA1(129c220d72608a8839f779ce1a6cfec8646dbf23) ) ROM_REGION( 0x280000, "bg1", 0 ) /* BG1 */ ROM_LOAD( "mca-u60.bin", 0x000000, 0x100000, CRC(c8942614) SHA1(244fccb9abbb04e33839dd2cd0e2de430819a18c) ) ROM_LOAD( "mca-u61.bin", 0x100000, 0x100000, CRC(51af66c9) SHA1(1055cf78ea286f02003b0d1bf08c2d7829b36f90) ) ROM_LOAD( "mca-u100", 0x200000, 0x080000, CRC(b273f1b0) SHA1(39318fe2aaf2792b85426ec6791b3360ac964de3) ) ROM_REGION( 0x80000, "ymsnd:adpcma", 0 ) /* Samples */ ROM_LOAD( "mca-u53.bin", 0x00000, 0x80000, CRC(64c76e05) SHA1(379cef5e0cba78d0e886c9cede41985850a3afb7) ) ROM_END ROM_START( mcatadvj ) ROM_REGION( 0x100000, "maincpu", 0 ) /* M68000 */ ROM_LOAD16_BYTE( "u30.bin", 0x00000, 0x80000, CRC(05762f42) SHA1(3675fb606bf9d7be9462324e68263f4a6c2fea1c) ) ROM_LOAD16_BYTE( "u29.bin", 0x00001, 0x80000, CRC(4c59d648) SHA1(2ab77ea254f2c11fc016078cedcab2fffbe5ee1b) ) ROM_REGION( 0x020000, "soundcpu", 0 ) /* Z80-A */ ROM_LOAD( "u9.bin", 0x00000, 0x20000, CRC(fda05171) SHA1(2c69292573ec35034572fa824c0cae2839d23919) ) ROM_REGION( 0x800000, "sprdata", ROMREGION_ERASEFF ) /* Sprites */ ROM_LOAD16_BYTE( "mca-u82.bin", 0x000000, 0x100000, CRC(5f01d746) SHA1(11b241456e15299912ee365eedb8f9d5e5ca875d) ) ROM_LOAD16_BYTE( "mca-u83.bin", 0x000001, 0x100000, CRC(4e1be5a6) SHA1(cb19aad42dba54d6a4a33859f27254c2a3271e8c) ) ROM_LOAD16_BYTE( "mca-u84.bin", 0x200000, 0x080000, CRC(df202790) SHA1(f6ae54e799af195860ed0ab3c85138cf2f10efa6) ) ROM_LOAD16_BYTE( "mca-u85.bin", 0x200001, 0x080000, CRC(a85771d2) SHA1(a1817cd72f5bf0a4f24a37c782dc63ecec3b8e68) ) ROM_LOAD16_BYTE( "u86.bin", 0x400000, 0x080000, CRC(2d3725ed) SHA1(8b4c0f280eb901113d842848ffc26371be7b6067) ) ROM_LOAD16_BYTE( "u87.bin", 0x400001, 0x080000, CRC(4ddefe08) SHA1(5ade0a694d73f4f3891c1ab7757e37a88afcbf54) ) ROM_REGION( 0x080000, "bg0", 0 ) /* BG0 */ ROM_LOAD( "mca-u58.bin", 0x000000, 0x080000, CRC(3a8186e2) SHA1(129c220d72608a8839f779ce1a6cfec8646dbf23) ) ROM_REGION( 0x280000, "bg1", 0 ) /* BG1 */ ROM_LOAD( "mca-u60.bin", 0x000000, 0x100000, CRC(c8942614) SHA1(244fccb9abbb04e33839dd2cd0e2de430819a18c) ) ROM_LOAD( "mca-u61.bin", 0x100000, 0x100000, CRC(51af66c9) SHA1(1055cf78ea286f02003b0d1bf08c2d7829b36f90) ) ROM_LOAD( "u100.bin", 0x200000, 0x080000, CRC(e2c311da) SHA1(cc3217484524de94704869eaa9ce1b90393039d8) ) ROM_REGION( 0x80000, "ymsnd:adpcma", 0 ) /* Samples */ ROM_LOAD( "mca-u53.bin", 0x00000, 0x80000, CRC(64c76e05) SHA1(379cef5e0cba78d0e886c9cede41985850a3afb7) ) ROM_END ROM_START( catt ) ROM_REGION( 0x100000, "maincpu", 0 ) /* M68000 */ ROM_LOAD16_BYTE( "catt-u30.bin", 0x00000, 0x80000, CRC(8c921e1e) SHA1(2fdaa9b743e1731f3cfe9d8334f1b759cf46855d) ) ROM_LOAD16_BYTE( "catt-u29.bin", 0x00001, 0x80000, CRC(e725af6d) SHA1(78c08fa5744a6a953e13c0ff39736ccd4875fb72) ) ROM_REGION( 0x020000, "soundcpu", 0 ) /* Z80-A */ ROM_LOAD( "u9.bin", 0x00000, 0x20000, CRC(fda05171) SHA1(2c69292573ec35034572fa824c0cae2839d23919) ) ROM_REGION( 0x800000, "sprdata", ROMREGION_ERASEFF ) /* Sprites */ ROM_LOAD16_BYTE( "mca-u82.bin", 0x000000, 0x100000, CRC(5f01d746) SHA1(11b241456e15299912ee365eedb8f9d5e5ca875d) ) ROM_LOAD16_BYTE( "mca-u83.bin", 0x000001, 0x100000, CRC(4e1be5a6) SHA1(cb19aad42dba54d6a4a33859f27254c2a3271e8c) ) ROM_LOAD16_BYTE( "u84.bin", 0x200000, 0x100000, CRC(843fd624) SHA1(2e16d8a909fe9447da37a87428bff0734af59a00) ) ROM_LOAD16_BYTE( "u85.bin", 0x200001, 0x100000, CRC(5ee7b628) SHA1(feedc212ed4893d784dc6b3361930b9199c6876d) ) ROM_LOAD16_BYTE( "mca-u86e", 0x400000, 0x080000, CRC(017bf1da) SHA1(f6446a7219275c0eff62129f59fdfa3a6a3e06c8) ) ROM_LOAD16_BYTE( "mca-u87e", 0x400001, 0x080000, CRC(bc9dc9b9) SHA1(f525c9f994d5107752aa4d3a499ee376ec75f42b) ) ROM_REGION( 0x100000, "bg0", 0 ) /* BG0 */ ROM_LOAD( "u58.bin", 0x00000, 0x100000, CRC(73c9343a) SHA1(9efdddbad6244c1ed267bd954563ab43a1017c96) ) ROM_REGION( 0x280000, "bg1", 0 ) /* BG1 */ ROM_LOAD( "mca-u60.bin", 0x000000, 0x100000, CRC(c8942614) SHA1(244fccb9abbb04e33839dd2cd0e2de430819a18c) ) ROM_LOAD( "mca-u61.bin", 0x100000, 0x100000, CRC(51af66c9) SHA1(1055cf78ea286f02003b0d1bf08c2d7829b36f90) ) ROM_LOAD( "mca-u100", 0x200000, 0x080000, CRC(b273f1b0) SHA1(39318fe2aaf2792b85426ec6791b3360ac964de3) ) ROM_REGION( 0x100000, "ymsnd:adpcma", 0 ) /* Samples */ ROM_LOAD( "u53.bin", 0x00000, 0x100000, CRC(99f2a624) SHA1(799e8e40e8bdcc8fa4cd763a366cc32473038a49) ) ROM_REGION( 0x0400, "plds", 0 ) ROM_LOAD( "peel18cv8.u1", 0x0000, 0x0155, NO_DUMP ) ROM_LOAD( "gal16v8a.u10", 0x0200, 0x0117, NO_DUMP ) ROM_END ROM_START( nost ) ROM_REGION( 0x100000, "maincpu", 0 ) /* M68000 */ ROM_LOAD16_BYTE( "nos-pe-u.bin", 0x00000, 0x80000, CRC(4b080149) SHA1(e1dbbe5bf554c7c5731cc3079850f257417e3caa) ) ROM_LOAD16_BYTE( "nos-po-u.bin", 0x00001, 0x80000, CRC(9e3cd6d9) SHA1(db5351ff9a05f602eceae62c0051c16ae0e4ead9) ) ROM_REGION( 0x040000, "soundcpu", 0 ) /* Z80-A */ ROM_LOAD( "nos-ps.u9", 0x00000, 0x40000, CRC(832551e9) SHA1(86fc481b1849f378c88593594129197c69ea1359) ) ROM_REGION( 0x800000, "sprdata", ROMREGION_ERASEFF ) /* Sprites */ ROM_LOAD16_BYTE( "nos-se-0.u82", 0x000000, 0x100000, CRC(9d99108d) SHA1(466540989d7b1b7f6dc7acbae74f6a8201973d45) ) ROM_LOAD16_BYTE( "nos-so-0.u83", 0x000001, 0x100000, CRC(7df0fc7e) SHA1(2e064cb5367b2839d736d339c4f1a44785b4eedf) ) ROM_LOAD16_BYTE( "nos-se-1.u84", 0x200000, 0x100000, CRC(aad07607) SHA1(89c51a9cb6b8d8ed3a357f5d8ac8399ff1c7ad46) ) ROM_LOAD16_BYTE( "nos-so-1.u85", 0x200001, 0x100000, CRC(83d0012c) SHA1(831d36521693891f44e7adcc2ba63fef5d493821) ) ROM_LOAD16_BYTE( "nos-se-2.u86", 0x400000, 0x080000, CRC(d99e6005) SHA1(49aae72111334ff5cd0fd86500882f559ff921f9) ) ROM_LOAD16_BYTE( "nos-so-2.u87", 0x400001, 0x080000, CRC(f60e8ef3) SHA1(4f7472b5a465e6cc6a5df520ebfe6a544739dd28) ) ROM_REGION( 0x180000, "bg0", 0 ) /* BG0 */ ROM_LOAD( "nos-b0-0.u58", 0x000000, 0x100000, CRC(0214b0f2) SHA1(678fa3dc739323bda6d7bbb1c7a573c976d69356) ) ROM_LOAD( "nos-b0-1.u59", 0x100000, 0x080000, CRC(3f8b6b34) SHA1(94c48614782ce6405965bcf6029e3bcc24a6d84f) ) ROM_REGION( 0x180000, "bg1", 0 ) /* BG1 */ ROM_LOAD( "nos-b1-0.u60", 0x000000, 0x100000, CRC(ba6fd0c7) SHA1(516d6e0c4dc6fb12ec9f30877ea1c582e7440a19) ) ROM_LOAD( "nos-b1-1.u61", 0x100000, 0x080000, CRC(dabd8009) SHA1(1862645b8d6216c3ec2b8dbf74816b8e29dea14f) ) ROM_REGION( 0x100000, "ymsnd:adpcma", 0 ) /* Samples */ ROM_LOAD( "nossn-00.u53", 0x00000, 0x100000, CRC(3bd1bcbc) SHA1(1bcad43792e985402db4eca122676c2c555f3313) ) ROM_END ROM_START( nostj ) ROM_REGION( 0x100000, "maincpu", 0 ) /* M68000 */ ROM_LOAD16_BYTE( "nos-pe-j.u30", 0x00000, 0x80000, CRC(4b080149) SHA1(e1dbbe5bf554c7c5731cc3079850f257417e3caa) ) ROM_LOAD16_BYTE( "nos-po-j.u29", 0x00001, 0x80000, CRC(7fe241de) SHA1(aa4ffd81cb73efc59690c2038ae9375021a775a4) ) ROM_REGION( 0x040000, "soundcpu", 0 ) /* Z80-A */ ROM_LOAD( "nos-ps.u9", 0x00000, 0x40000, CRC(832551e9) SHA1(86fc481b1849f378c88593594129197c69ea1359) ) ROM_REGION( 0x800000, "sprdata", ROMREGION_ERASEFF ) /* Sprites */ ROM_LOAD16_BYTE( "nos-se-0.u82", 0x000000, 0x100000, CRC(9d99108d) SHA1(466540989d7b1b7f6dc7acbae74f6a8201973d45) ) ROM_LOAD16_BYTE( "nos-so-0.u83", 0x000001, 0x100000, CRC(7df0fc7e) SHA1(2e064cb5367b2839d736d339c4f1a44785b4eedf) ) ROM_LOAD16_BYTE( "nos-se-1.u84", 0x200000, 0x100000, CRC(aad07607) SHA1(89c51a9cb6b8d8ed3a357f5d8ac8399ff1c7ad46) ) ROM_LOAD16_BYTE( "nos-so-1.u85", 0x200001, 0x100000, CRC(83d0012c) SHA1(831d36521693891f44e7adcc2ba63fef5d493821) ) ROM_LOAD16_BYTE( "nos-se-2.u86", 0x400000, 0x080000, CRC(d99e6005) SHA1(49aae72111334ff5cd0fd86500882f559ff921f9) ) ROM_LOAD16_BYTE( "nos-so-2.u87", 0x400001, 0x080000, CRC(f60e8ef3) SHA1(4f7472b5a465e6cc6a5df520ebfe6a544739dd28) ) ROM_REGION( 0x180000, "bg0", 0 ) /* BG0 */ ROM_LOAD( "nos-b0-0.u58", 0x000000, 0x100000, CRC(0214b0f2) SHA1(678fa3dc739323bda6d7bbb1c7a573c976d69356) ) ROM_LOAD( "nos-b0-1.u59", 0x100000, 0x080000, CRC(3f8b6b34) SHA1(94c48614782ce6405965bcf6029e3bcc24a6d84f) ) ROM_REGION( 0x180000, "bg1", 0 ) /* BG1 */ ROM_LOAD( "nos-b1-0.u60", 0x000000, 0x100000, CRC(ba6fd0c7) SHA1(516d6e0c4dc6fb12ec9f30877ea1c582e7440a19) ) ROM_LOAD( "nos-b1-1.u61", 0x100000, 0x080000, CRC(dabd8009) SHA1(1862645b8d6216c3ec2b8dbf74816b8e29dea14f) ) ROM_REGION( 0x100000, "ymsnd:adpcma", 0 ) /* Samples */ ROM_LOAD( "nossn-00.u53", 0x00000, 0x100000, CRC(3bd1bcbc) SHA1(1bcad43792e985402db4eca122676c2c555f3313) ) ROM_END ROM_START( nostk ) ROM_REGION( 0x100000, "maincpu", 0 ) /* M68000 */ ROM_LOAD16_BYTE( "nos-pe-t.u30", 0x00000, 0x80000, CRC(bee5fbc8) SHA1(a8361fa004bb31471f973ece51a9a87b9f3438ab) ) ROM_LOAD16_BYTE( "nos-po-t.u29", 0x00001, 0x80000, CRC(f4736331) SHA1(7a6db2db1a4dbf105c22e15deff6f6032e04609c) ) ROM_REGION( 0x040000, "soundcpu", 0 ) /* Z80-A */ ROM_LOAD( "nos-ps.u9", 0x00000, 0x40000, CRC(832551e9) SHA1(86fc481b1849f378c88593594129197c69ea1359) ) ROM_REGION( 0x800000, "sprdata", ROMREGION_ERASEFF ) /* Sprites */ ROM_LOAD16_BYTE( "nos-se-0.u82", 0x000000, 0x100000, CRC(9d99108d) SHA1(466540989d7b1b7f6dc7acbae74f6a8201973d45) ) ROM_LOAD16_BYTE( "nos-so-0.u83", 0x000001, 0x100000, CRC(7df0fc7e) SHA1(2e064cb5367b2839d736d339c4f1a44785b4eedf) ) ROM_LOAD16_BYTE( "nos-se-1.u84", 0x200000, 0x100000, CRC(aad07607) SHA1(89c51a9cb6b8d8ed3a357f5d8ac8399ff1c7ad46) ) ROM_LOAD16_BYTE( "nos-so-1.u85", 0x200001, 0x100000, CRC(83d0012c) SHA1(831d36521693891f44e7adcc2ba63fef5d493821) ) ROM_LOAD16_BYTE( "nos-se-2.u86", 0x400000, 0x080000, CRC(d99e6005) SHA1(49aae72111334ff5cd0fd86500882f559ff921f9) ) ROM_LOAD16_BYTE( "nos-so-2.u87", 0x400001, 0x080000, CRC(f60e8ef3) SHA1(4f7472b5a465e6cc6a5df520ebfe6a544739dd28) ) ROM_REGION( 0x180000, "bg0", 0 ) /* BG0 */ ROM_LOAD( "nos-b0-0.u58", 0x000000, 0x100000, CRC(0214b0f2) SHA1(678fa3dc739323bda6d7bbb1c7a573c976d69356) ) ROM_LOAD( "nos-b0-1.u59", 0x100000, 0x080000, CRC(3f8b6b34) SHA1(94c48614782ce6405965bcf6029e3bcc24a6d84f) ) ROM_REGION( 0x180000, "bg1", 0 ) /* BG1 */ ROM_LOAD( "nos-b1-0.u60", 0x000000, 0x100000, CRC(ba6fd0c7) SHA1(516d6e0c4dc6fb12ec9f30877ea1c582e7440a19) ) ROM_LOAD( "nos-b1-1.u61", 0x100000, 0x080000, CRC(dabd8009) SHA1(1862645b8d6216c3ec2b8dbf74816b8e29dea14f) ) ROM_REGION( 0x100000, "ymsnd:adpcma", 0 ) /* Samples */ ROM_LOAD( "nossn-00.u53", 0x00000, 0x100000, CRC(3bd1bcbc) SHA1(1bcad43792e985402db4eca122676c2c555f3313) ) ROM_END GAME( 1993, mcatadv, 0, mcatadv, mcatadv, mcatadv_state, empty_init, ROT0, "Wintechno", "Magical Cat Adventure", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1993, mcatadvj, mcatadv, mcatadv, mcatadv, mcatadv_state, empty_init, ROT0, "Wintechno", "Magical Cat Adventure (Japan)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1993, catt, mcatadv, mcatadv, mcatadv, mcatadv_state, empty_init, ROT0, "Wintechno", "Catt (Japan)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1993, nost, 0, nost, nost, mcatadv_state, empty_init, ROT270, "Face", "Nostradamus", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1993, nostj, nost, nost, nost, mcatadv_state, empty_init, ROT270, "Face", "Nostradamus (Japan)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE ) GAME( 1993, nostk, nost, nost, nost, mcatadv_state, empty_init, ROT270, "Face", "Nostradamus (Korea)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
49.631737
175
0.684472
[ "object" ]
c05692aecdaf43068f35d1e3b02ad2c2dcd0c50f
643
hpp
C++
experiment/py_wrapper/py_session.hpp
daiwei89/hotbox
11922d0fd23d0b532c0a3842c4c7723e29a166e2
[ "BSD-3-Clause" ]
null
null
null
experiment/py_wrapper/py_session.hpp
daiwei89/hotbox
11922d0fd23d0b532c0a3842c4c7723e29a166e2
[ "BSD-3-Clause" ]
null
null
null
experiment/py_wrapper/py_session.hpp
daiwei89/hotbox
11922d0fd23d0b532c0a3842c4c7723e29a166e2
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <boost/python.hpp> #include "client/session.hpp" #include <iostream> #include <vector> using namespace boost::python; namespace hotbox { class PYSession { public: PYSession(){}; PYSession(Session* ss); ~PYSession(); BigInt GetNumData() const; dict GetData(BigInt begin = 0, BigInt end = -1); private: Session* session_; template<class T> static list VectorToList(std::vector<T> vector) { typename std::vector<T>::iterator iter; list list; for (iter = vector.begin(); iter != vector.end(); ++iter) { list.append(*iter); } return list; } }; }
18.911765
64
0.62675
[ "vector" ]
c05742e59122c3a9eece391d31bc3a5844f1b37e
7,626
cc
C++
src/C/BoringSSL/boringssl-078abceb/tool/transport_common.cc
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C/BoringSSL/boringssl-078abceb/tool/transport_common.cc
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/BoringSSL/boringssl-078abceb/tool/transport_common.cc
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* Copyright (c) 2014, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <openssl/base.h> #include <string> #include <vector> #include <errno.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #if !defined(OPENSSL_WINDOWS) #include <arpa/inet.h> #include <fcntl.h> #include <netdb.h> #include <netinet/in.h> #include <sys/select.h> #include <sys/socket.h> #include <unistd.h> #else #define NOMINMAX #include <io.h> #pragma warning(push, 3) #include <WinSock2.h> #include <WS2tcpip.h> #pragma warning(pop) typedef int ssize_t; #pragma comment(lib, "Ws2_32.lib") #endif #include <openssl/err.h> #include <openssl/ssl.h> #include "internal.h" #if !defined(OPENSSL_WINDOWS) static int closesocket(int sock) { return close(sock); } #endif bool InitSocketLibrary() { #if defined(OPENSSL_WINDOWS) WSADATA wsaData; int err = WSAStartup(MAKEWORD(2, 2), &wsaData); if (err != 0) { fprintf(stderr, "WSAStartup failed with error %d\n", err); return false; } #endif return true; } // Connect sets |*out_sock| to be a socket connected to the destination given // in |hostname_and_port|, which should be of the form "www.example.com:123". // It returns true on success and false otherwise. bool Connect(int *out_sock, const std::string &hostname_and_port) { const size_t colon_offset = hostname_and_port.find_last_of(':'); std::string hostname, port; if (colon_offset == std::string::npos) { hostname = hostname_and_port; port = "443"; } else { hostname = hostname_and_port.substr(0, colon_offset); port = hostname_and_port.substr(colon_offset + 1); } struct addrinfo hint, *result; memset(&hint, 0, sizeof(hint)); hint.ai_family = AF_UNSPEC; hint.ai_socktype = SOCK_STREAM; int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result); if (ret != 0) { fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret)); return false; } bool ok = false; char buf[256]; *out_sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (*out_sock < 0) { perror("socket"); goto out; } switch (result->ai_family) { case AF_INET: { struct sockaddr_in *sin = reinterpret_cast<struct sockaddr_in *>(result->ai_addr); fprintf(stderr, "Connecting to %s:%d\n", inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)), ntohs(sin->sin_port)); break; } case AF_INET6: { struct sockaddr_in6 *sin6 = reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr); fprintf(stderr, "Connecting to [%s]:%d\n", inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)), ntohs(sin6->sin6_port)); break; } } if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) { perror("connect"); goto out; } ok = true; out: freeaddrinfo(result); return ok; } bool Accept(int *out_sock, const std::string &port) { struct sockaddr_in addr, cli_addr; socklen_t cli_addr_len = sizeof(cli_addr); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(atoi(port.c_str())); bool ok = false; int server_sock = -1; server_sock = socket(addr.sin_family, SOCK_STREAM, 0); if (server_sock < 0) { perror("socket"); goto out; } if (bind(server_sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) { perror("connect"); goto out; } listen(server_sock, 1); *out_sock = accept(server_sock, (struct sockaddr*)&cli_addr, &cli_addr_len); ok = true; out: closesocket(server_sock); return ok; } void PrintConnectionInfo(const SSL *ssl) { const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl); fprintf(stderr, " Version: %s\n", SSL_get_version(ssl)); fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_get_name(cipher)); fprintf(stderr, " Secure renegotiation: %s\n", SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no"); } bool SocketSetNonBlocking(int sock, bool is_non_blocking) { bool ok; #if defined(OPENSSL_WINDOWS) u_long arg = is_non_blocking; ok = 0 == ioctlsocket(sock, FIONBIO, &arg); #else int flags = fcntl(sock, F_GETFL, 0); if (flags < 0) { return false; } if (is_non_blocking) { flags |= O_NONBLOCK; } else { flags &= ~O_NONBLOCK; } ok = 0 == fcntl(sock, F_SETFL, flags); #endif if (!ok) { fprintf(stderr, "Failed to set socket non-blocking.\n"); } return ok; } // PrintErrorCallback is a callback function from OpenSSL's // |ERR_print_errors_cb| that writes errors to a given |FILE*|. int PrintErrorCallback(const char *str, size_t len, void *ctx) { fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx)); return 1; } bool TransferData(SSL *ssl, int sock) { bool stdin_open = true; fd_set read_fds; FD_ZERO(&read_fds); if (!SocketSetNonBlocking(sock, true)) { return false; } for (;;) { if (stdin_open) { FD_SET(0, &read_fds); } FD_SET(sock, &read_fds); int ret = select(sock + 1, &read_fds, NULL, NULL, NULL); if (ret <= 0) { perror("select"); return false; } if (FD_ISSET(0, &read_fds)) { uint8_t buffer[512]; ssize_t n; do { n = read(0, buffer, sizeof(buffer)); } while (n == -1 && errno == EINTR); if (n == 0) { FD_CLR(0, &read_fds); stdin_open = false; #if !defined(OPENSSL_WINDOWS) shutdown(sock, SHUT_WR); #else shutdown(sock, SD_SEND); #endif continue; } else if (n < 0) { perror("read from stdin"); return false; } if (!SocketSetNonBlocking(sock, false)) { return false; } int ssl_ret = SSL_write(ssl, buffer, n); if (!SocketSetNonBlocking(sock, true)) { return false; } if (ssl_ret <= 0) { int ssl_err = SSL_get_error(ssl, ssl_ret); fprintf(stderr, "Error while writing: %d\n", ssl_err); ERR_print_errors_cb(PrintErrorCallback, stderr); return false; } else if (ssl_ret != n) { fprintf(stderr, "Short write from SSL_write.\n"); return false; } } if (FD_ISSET(sock, &read_fds)) { uint8_t buffer[512]; int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer)); if (ssl_ret < 0) { int ssl_err = SSL_get_error(ssl, ssl_ret); if (ssl_err == SSL_ERROR_WANT_READ) { continue; } fprintf(stderr, "Error while reading: %d\n", ssl_err); ERR_print_errors_cb(PrintErrorCallback, stderr); return false; } else if (ssl_ret == 0) { return true; } ssize_t n; do { n = write(1, buffer, ssl_ret); } while (n == -1 && errno == EINTR); if (n != ssl_ret) { fprintf(stderr, "Short write to stderr.\n"); return false; } } } }
25.505017
79
0.638211
[ "vector" ]
c05e75e0ef933d429da3c17e38104ee0b3a867a0
5,166
cpp
C++
Builds/JuceLibraryCode/modules/juce_graphics/juce_graphics.cpp
eriser/CSL
6f4646369f0c90ea90e2c113374044818ab37ded
[ "BSD-4-Clause-UC" ]
null
null
null
Builds/JuceLibraryCode/modules/juce_graphics/juce_graphics.cpp
eriser/CSL
6f4646369f0c90ea90e2c113374044818ab37ded
[ "BSD-4-Clause-UC" ]
null
null
null
Builds/JuceLibraryCode/modules/juce_graphics/juce_graphics.cpp
eriser/CSL
6f4646369f0c90ea90e2c113374044818ab37ded
[ "BSD-4-Clause-UC" ]
null
null
null
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #if defined (__JUCE_GRAPHICS_MODULE_JUCEHEADER__) && ! JUCE_AMALGAMATED_INCLUDE /* When you add this cpp file to your project, you mustn't include it in a file where you've already included any other headers - just put it inside a file on its own, possibly with your config flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix header files that the compiler may be using. */ #error "Incorrect use of JUCE cpp file" #endif // Your project must contain an AppConfig.h file with your project-specific settings in it, // and your header search path must make it accessible to the module's files. #include "AppConfig.h" #include "../juce_core/native/juce_BasicNativeHeaders.h" #include "juce_graphics.h" //============================================================================== #if JUCE_MAC #import <QuartzCore/QuartzCore.h> #elif JUCE_WINDOWS #if JUCE_USE_DIRECTWRITE /* If you hit a compile error trying to include these files, you may need to update your version of the Windows SDK to the latest one. The DirectWrite and Direct2D headers are in the version 7 SDKs. */ #include <d2d1.h> #include <dwrite.h> #endif #elif JUCE_IOS #import <QuartzCore/QuartzCore.h> #import <CoreText/CoreText.h> #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 #error "JUCE no longer supports targets earlier than iOS 3.2" #endif #elif JUCE_LINUX #include <ft2build.h> #include FT_FREETYPE_H #undef SIZEOF #endif #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && JUCE_USE_COREIMAGE_LOADER #define JUCE_USING_COREIMAGE_LOADER 1 #else #define JUCE_USING_COREIMAGE_LOADER 0 #endif //============================================================================== namespace juce { #include "colour/juce_Colour.cpp" #include "colour/juce_ColourGradient.cpp" #include "colour/juce_Colours.cpp" #include "colour/juce_FillType.cpp" #include "geometry/juce_AffineTransform.cpp" #include "geometry/juce_EdgeTable.cpp" #include "geometry/juce_Path.cpp" #include "geometry/juce_PathIterator.cpp" #include "geometry/juce_PathStrokeType.cpp" #include "geometry/juce_RectangleList.cpp" #include "placement/juce_Justification.cpp" #include "placement/juce_RectanglePlacement.cpp" #include "contexts/juce_GraphicsContext.cpp" #include "contexts/juce_LowLevelGraphicsPostScriptRenderer.cpp" #include "contexts/juce_LowLevelGraphicsSoftwareRenderer.cpp" #include "images/juce_Image.cpp" #include "images/juce_ImageCache.cpp" #include "images/juce_ImageConvolutionKernel.cpp" #include "images/juce_ImageFileFormat.cpp" #include "image_formats/juce_GIFLoader.cpp" #include "image_formats/juce_JPEGLoader.cpp" #include "image_formats/juce_PNGLoader.cpp" #include "fonts/juce_AttributedString.cpp" #include "fonts/juce_Typeface.cpp" #include "fonts/juce_CustomTypeface.cpp" #include "fonts/juce_Font.cpp" #include "fonts/juce_GlyphArrangement.cpp" #include "fonts/juce_TextLayout.cpp" #include "effects/juce_DropShadowEffect.cpp" #include "effects/juce_GlowEffect.cpp" //============================================================================== #if JUCE_MAC || JUCE_IOS #include "../juce_core/native/juce_osx_ObjCHelpers.h" #include "native/juce_mac_CoreGraphicsHelpers.h" #include "native/juce_mac_Fonts.mm" #include "native/juce_mac_CoreGraphicsContext.mm" #elif JUCE_WINDOWS #include "../juce_core/native/juce_win32_ComSmartPtr.h" #include "native/juce_win32_DirectWriteTypeface.cpp" #include "native/juce_win32_DirectWriteTypeLayout.cpp" #include "native/juce_win32_Fonts.cpp" #if JUCE_DIRECT2D #include "native/juce_win32_Direct2DGraphicsContext.cpp" #endif #elif JUCE_LINUX #include "native/juce_linux_Fonts.cpp" #elif JUCE_ANDROID #include "../juce_core/native/juce_android_JNIHelpers.h" #include "native/juce_android_GraphicsContext.cpp" #include "native/juce_android_Fonts.cpp" #endif }
37.434783
106
0.683314
[ "geometry" ]
c0613a7a6dc6e6c18ed112e88ff61a0de1c1acb1
1,268
cp
C++
Final/minutes_solution.cp
chenchuw/EC602-Design-by-Software
c233c9d08a67abc47235282fedd866d67ccaf4ce
[ "MIT" ]
null
null
null
Final/minutes_solution.cp
chenchuw/EC602-Design-by-Software
c233c9d08a67abc47235282fedd866d67ccaf4ce
[ "MIT" ]
null
null
null
Final/minutes_solution.cp
chenchuw/EC602-Design-by-Software
c233c9d08a67abc47235282fedd866d67ccaf4ce
[ "MIT" ]
1
2022-01-11T20:23:47.000Z
2022-01-11T20:23:47.000Z
// Midterm Two: C++ // Solution #include<string> #include<vector> #include<iostream> using std::string; using std::vector; using std::cout; using std::to_string; const int MINPERDAY = 1440; const int MINPERHR = 60; namespace my { string get_minute(int label, bool exceptions = true) { string minute, hour; if (label<0 or label >= MINPERDAY) { if (exceptions) throw "bad label"; return "??:??"; } minute = to_string(label % MINPERHR); hour = to_string(label / MINPERHR); if (minute.size() == 1) minute = "0" + minute; if (hour.size() == 1) hour = "0" + hour; return hour + ":" + minute; } } class Minute { bool exceptions; public: Minute(bool enable_exception = true) { exceptions = enable_exception; } string get_minute(int i) { return my::get_minute(i, exceptions); } vector<string> all_minutes() { vector<string> m(MINPERDAY); for (int i = 0; i < MINPERDAY; i++) m.at(i) = get_minute(i); return m; } } ; int main() { // this is not the best example of a test suite. cout << my::get_minute(1439) << "\n"; Minute m; cout << m.get_minute(45) << "\n"; vector<string> v = m.all_minutes(); cout << v.at(1234) << "\n"; Minute t(false); cout << t.get_minute(-1) << "\n"; }
19.507692
54
0.608833
[ "vector" ]
c0642d03fafaa6d1b45291ab605bfbb6bfc32a07
15,076
cpp
C++
c_cxx/OpenVINO_EP/Linux/squeezenet_classification/squeezenet_cpp_app_io.cpp
intel/onnxruntime-inference-examples
f05aab432391c3410140264eebba8b7920d80463
[ "MIT" ]
1
2022-02-25T08:04:41.000Z
2022-02-25T08:04:41.000Z
c_cxx/OpenVINO_EP/Linux/squeezenet_classification/squeezenet_cpp_app_io.cpp
intel/onnxruntime-inference-examples
f05aab432391c3410140264eebba8b7920d80463
[ "MIT" ]
5
2021-11-25T14:45:24.000Z
2022-03-30T07:38:56.000Z
c_cxx/OpenVINO_EP/Linux/squeezenet_classification/squeezenet_cpp_app_io.cpp
intel/onnxruntime-inference-examples
f05aab432391c3410140264eebba8b7920d80463
[ "MIT" ]
1
2021-12-14T14:35:36.000Z
2021-12-14T14:35:36.000Z
/* Copyright (C) 2021, Intel Corporation SPDX-License-Identifier: Apache-2.0 Portions of this software are copyright of their respective authors and released under the MIT license: - ONNX-Runtime-Inference, Copyright 2020 Lei Mao. For licensing see https://github.com/leimao/ONNX-Runtime-Inference/blob/main/LICENSE.md */ #include <onnxruntime_cxx_api.h> #include <opencv2/dnn/dnn.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include <chrono> #include <cmath> #include <exception> #include <fstream> #include <iostream> #include <limits> #include <numeric> #include <string> #include <vector> #include <stdexcept> // To use runtime_error #include <CL/cl2.hpp> #define CL_HPP_MINIMUM_OPENCL_VERSION 120 #define CL_HPP_TARGET_OPENCL_VERSION 120 struct OpenCL { cl::Context _context; cl::Device _device; cl::CommandQueue _queue; explicit OpenCL(std::shared_ptr<std::vector<cl_context_properties>> media_api_context_properties = nullptr) { // get Intel iGPU OCL device, create context and queue { const unsigned int refVendorID = 0x8086; cl_uint n = 0; clGetPlatformIDs(0, NULL, &n); // Get platform list std::vector<cl_platform_id> platform_ids(n); clGetPlatformIDs(n, platform_ids.data(), NULL); for (auto& id : platform_ids) { cl::Platform platform = cl::Platform(id); std::vector<cl::Device> devices; platform.getDevices(CL_DEVICE_TYPE_GPU, &devices); for (auto& d : devices) { if (refVendorID == d.getInfo<CL_DEVICE_VENDOR_ID>()) { _device = d; _context = cl::Context(_device); break; } } } cl_command_queue_properties props = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE; _queue = cl::CommandQueue(_context, _device, props); } } explicit OpenCL(cl_context context) { // user-supplied context handle _context = cl::Context(context); _device = cl::Device(_context.getInfo<CL_CONTEXT_DEVICES>()[0]); cl_command_queue_properties props = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE; _queue = cl::CommandQueue(_context, _device, props); } }; template <typename T> T vectorProduct(const std::vector<T>& v) { return accumulate(v.begin(), v.end(), 1, std::multiplies<T>()); } /** * @brief Operator overloading for printing vectors * @tparam T * @param os * @param v * @return std::ostream& */ template <typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { os << v[i]; if (i != v.size() - 1) { os << ", "; } } os << "]"; return os; } // Function to validate the input image file extension. bool imageFileExtension(std::string str) { // is empty throw error if (str.empty()) throw std::runtime_error("[ ERROR ] The image File path is empty"); size_t pos = str.rfind('.'); if (pos == std::string::npos) return false; std::string ext = str.substr(pos+1); if (ext == "jpg" || ext == "jpeg" || ext == "gif" || ext == "png" || ext == "jfif" || ext == "JPG" || ext == "JPEG" || ext == "GIF" || ext == "PNG" || ext == "JFIF") { return true; } return false; } // Function to read the labels from the labelFilepath. std::vector<std::string> readLabels(std::string& labelFilepath) { std::vector<std::string> labels; std::string line; std::ifstream fp(labelFilepath); while (std::getline(fp, line)) { labels.push_back(line); } return labels; } // Function to validate the input model file extension. bool checkModelExtension(const std::string& filename) { if(filename.empty()) { throw std::runtime_error("[ ERROR ] The Model file path is empty"); } size_t pos = filename.rfind('.'); if (pos == std::string::npos) return false; std::string ext = filename.substr(pos+1); if (ext == "onnx") return true; return false; } // Function to validate the Label file extension. bool checkLabelFileExtension(const std::string& filename) { size_t pos = filename.rfind('.'); if (filename.empty()) { throw std::runtime_error("[ ERROR ] The Label file path is empty"); } if (pos == std::string::npos) return false; std::string ext = filename.substr(pos+1); if (ext == "txt") { return true; } else { return false; } } //Handling divide by zero float division(float num, float den){ if (den == 0) { throw std::runtime_error("[ ERROR ] Math error: Attempted to divide by Zero\n"); } return (num / den); } void printHelp() { std::cout << "To run the model, use the following command:\n"; std::cout << "Example: ./run_squeezenet <path_to_the_model> <path_to_the_image> <path_to_the_classes_file>" << std::endl; std::cout << "\n Example: ./run_squeezenet squeezenet1.1-7.onnx demo.jpeg synset.txt \n" << std::endl; } int main(int argc, char* argv[]) { if(argc == 2) { std::string option = argv[1]; if (option == "--help" || option == "-help" || option == "--h" || option == "-h") { printHelp(); } return 0; } else if(argc != 4) { std::cout << "[ ERROR ] you have used the wrong command to run your program." << std::endl; printHelp(); return 0; } std::string instanceName{"image-classification-inference"}; std::string modelFilepath = argv[1]; // .onnx file //validate ModelFilePath checkModelExtension(modelFilepath); if(!checkModelExtension(modelFilepath)) { throw std::runtime_error("[ ERROR ] The ModelFilepath is not correct. Make sure you are setting the path to an onnx model file (.onnx)"); } std::string imageFilepath = argv[2]; // Validate ImageFilePath imageFileExtension(imageFilepath); if(!imageFileExtension(imageFilepath)) { throw std::runtime_error("[ ERROR ] The imageFilepath doesn't have correct image extension. Choose from jpeg, jpg, gif, png, PNG, jfif"); } std::ifstream f(imageFilepath.c_str()); if(!f.good()) { throw std::runtime_error("[ ERROR ] The imageFilepath is not set correctly or doesn't exist"); } // Validate LabelFilePath std::string labelFilepath = argv[3]; if(!checkLabelFileExtension(labelFilepath)) { throw std::runtime_error("[ ERROR ] The LabelFilepath is not set correctly and the labels file should end with extension .txt"); } std::vector<std::string> labels{readLabels(labelFilepath)}; Ort::Env env(OrtLoggingLevel::ORT_LOGGING_LEVEL_FATAL, instanceName.c_str()); Ort::SessionOptions sessionOptions; sessionOptions.SetIntraOpNumThreads(1); auto ocl_instance = std::make_shared<OpenCL>(); //Appending OpenVINO Execution Provider API // Using OPENVINO backend OrtOpenVINOProviderOptions options; options.device_type = "GPU_FP32"; //Another option is: GPU_FP16 options.context = (void *) ocl_instance->_context.get() ; std::cout << "OpenVINO device type is set to: " << options.device_type << std::endl; sessionOptions.AppendExecutionProvider_OpenVINO(options); // Sets graph optimization level // Available levels are // ORT_DISABLE_ALL -> To disable all optimizations // ORT_ENABLE_BASIC -> To enable basic optimizations ( Such as redundant node // removals) ORT_ENABLE_EXTENDED -> To enable extended optimizations // (Includes level 1 + more complex optimizations like node fusions) // ORT_ENABLE_ALL -> To Enable All possible optimizations sessionOptions.SetGraphOptimizationLevel( GraphOptimizationLevel::ORT_DISABLE_ALL); //Creation: The Ort::Session is created here Ort::Session session(env, modelFilepath.c_str(), sessionOptions); Ort::AllocatorWithDefaultOptions allocator; Ort::MemoryInfo info_gpu("OpenVINO_GPU", OrtAllocatorType::OrtDeviceAllocator, 0, OrtMemTypeDefault); size_t numInputNodes = session.GetInputCount(); size_t numOutputNodes = session.GetOutputCount(); std::cout << "Number of Input Nodes: " << numInputNodes << std::endl; std::cout << "Number of Output Nodes: " << numOutputNodes << std::endl; const char* inputName = session.GetInputName(0, allocator); std::cout << "Input Name: " << inputName << std::endl; Ort::TypeInfo inputTypeInfo = session.GetInputTypeInfo(0); auto inputTensorInfo = inputTypeInfo.GetTensorTypeAndShapeInfo(); ONNXTensorElementDataType inputType = inputTensorInfo.GetElementType(); std::cout << "Input Type: " << inputType << std::endl; std::vector<int64_t> inputDims = inputTensorInfo.GetShape(); std::cout << "Input Dimensions: " << inputDims << std::endl; const char* outputName = session.GetOutputName(0, allocator); std::cout << "Output Name: " << outputName << std::endl; Ort::TypeInfo outputTypeInfo = session.GetOutputTypeInfo(0); auto outputTensorInfo = outputTypeInfo.GetTensorTypeAndShapeInfo(); ONNXTensorElementDataType outputType = outputTensorInfo.GetElementType(); std::cout << "Output Type: " << outputType << std::endl; std::vector<int64_t> outputDims = outputTensorInfo.GetShape(); std::cout << "Output Dimensions: " << outputDims << std::endl; //pre-processing the Image // step 1: Read an image in HWC BGR UINT8 format. cv::Mat imageBGR = cv::imread(imageFilepath, cv::ImreadModes::IMREAD_COLOR); // step 2: Resize the image. cv::Mat resizedImageBGR, resizedImageRGB, resizedImage, preprocessedImage; cv::resize(imageBGR, resizedImageBGR, cv::Size(inputDims.at(3), inputDims.at(2)), cv::InterpolationFlags::INTER_CUBIC); // step 3: Convert the image to HWC RGB UINT8 format. cv::cvtColor(resizedImageBGR, resizedImageRGB, cv::ColorConversionCodes::COLOR_BGR2RGB); // step 4: Convert the image to HWC RGB float format by dividing each pixel by 255. resizedImageRGB.convertTo(resizedImage, CV_32F, 1.0 / 255); // step 5: Split the RGB channels from the image. cv::Mat channels[3]; cv::split(resizedImage, channels); //step 6: Normalize each channel. // Normalization per channel // Normalization parameters obtained from // https://github.com/onnx/models/tree/master/vision/classification/squeezenet channels[0] = (channels[0] - 0.485) / 0.229; channels[1] = (channels[1] - 0.456) / 0.224; channels[2] = (channels[2] - 0.406) / 0.225; //step 7: Merge the RGB channels back to the image. cv::merge(channels, 3, resizedImage); // step 8: Convert the image to CHW RGB float format. // HWC to CHW cv::dnn::blobFromImage(resizedImage, preprocessedImage); //Run Inference std::vector<const char*> inputNames{inputName}; std::vector<const char*> outputNames{outputName}; /* To run inference using ONNX Runtime, the user is responsible for creating and managing the input and output buffers. The buffers are IO Binding Buffers created on Remote Folders to create Remote Blob*/ size_t inputTensorSize = vectorProduct(inputDims); std::vector<float> inputTensorValues(inputTensorSize); inputTensorValues.assign(preprocessedImage.begin<float>(), preprocessedImage.end<float>()); size_t imgSize = inputTensorSize*4; cl_int err; cl::Buffer shared_buffer(ocl_instance->_context, CL_MEM_READ_WRITE, imgSize, NULL, &err); { void *buffer = (void *)preprocessedImage.ptr(); ocl_instance->_queue.enqueueWriteBuffer(shared_buffer, true, 0, imgSize, buffer); } //To pass to OrtValue wrap the buffer in shared buffer void *shared_buffer_void = static_cast<void *>(&shared_buffer); size_t outputTensorSize = vectorProduct(outputDims); std::vector<float> outputTensorValues(outputTensorSize); Ort::Value inputTensors = Ort::Value::CreateTensor( info_gpu, shared_buffer_void, imgSize, inputDims.data(), inputDims.size(), ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); assert(("Output tensor size should equal to the label set size.", labels.size() == outputTensorSize)); size_t imgSizeO = outputTensorSize*4; cl::Buffer shared_buffer_out(ocl_instance->_context, CL_MEM_READ_WRITE, imgSizeO, NULL, &err); //To pass the ORT Value wrap the output buffer in shared buffer void *shared_buffer_out_void = static_cast<void *>(&shared_buffer_out); Ort::Value outputTensors = Ort::Value::CreateTensor( info_gpu, shared_buffer_out_void, imgSizeO, outputDims.data(), outputDims.size(), ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); std::cout << "Before Running\n"; session.Run(Ort::RunOptions{nullptr}, inputNames.data(), &inputTensors, 1, outputNames.data(), &outputTensors, 1); int predId = 0; float activation = 0; float maxActivation = std::numeric_limits<float>::lowest(); float expSum = 0; uint8_t *ary = (uint8_t*) malloc(imgSizeO); ocl_instance->_queue.enqueueReadBuffer(shared_buffer_out, true, 0, imgSizeO, ary); float outputTensorArray[outputTensorSize] ; std::memcpy(outputTensorArray, ary, imgSizeO); /* The inference result could be found in the buffer for the output tensors, which are usually the buffer from std::vector instances. */ for (int i = 0; i < labels.size(); i++) { activation = outputTensorArray[i]; expSum += std::exp(activation); if (activation > maxActivation) { predId = i; maxActivation = activation; } } std::cout << "Predicted Label ID: " << predId << std::endl; std::cout << "Predicted Label: " << labels.at(predId) << std::endl; float result; try { result = division(std::exp(maxActivation), expSum); std::cout << "Uncalibrated Confidence: " << result << std::endl; } catch (std::runtime_error& e) { std::cout << "Exception occurred" << std::endl << e.what(); } // Measure latency int numTests{10}; std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); //Run: Running the session is done in the Run() method: for (int i = 0; i < numTests; i++) { // session.Run(Ort::RunOptions{nullptr}, binding); session.Run(Ort::RunOptions{nullptr}, inputNames.data(), &inputTensors, 1, outputNames.data(), &outputTensors, 1); //session.Run(Ort::RunOptions{nullptr}, binding); } std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::cout << "Minimum Inference Latency: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() / static_cast<float>(numTests) << " ms" << std::endl; return 0; }
36.240385
145
0.652295
[ "vector", "model" ]
c0643da09941d82ce14c4ff119cb679ac0b482b9
10,193
cpp
C++
sample/sssampledriver.cpp
ebio-snu/cvtdriver
d76375c8ab5aacece3bb0dd9f9c556128d7193a7
[ "MIT" ]
null
null
null
sample/sssampledriver.cpp
ebio-snu/cvtdriver
d76375c8ab5aacece3bb0dd9f9c556128d7193a7
[ "MIT" ]
10
2018-03-19T12:29:37.000Z
2018-04-01T05:17:33.000Z
sample/sssampledriver.cpp
ebio-snu/cvtdriver
d76375c8ab5aacece3bb0dd9f9c556128d7193a7
[ "MIT" ]
null
null
null
/** Copyright © 2018 ebio lab. SNU. All Rights Reserved. @file sssampledriver.cpp @date 2018-03-22, JoonYong @author Kim, JoonYong <tombraid@snu.ac.kr> This file is for server-side sample driver. refer from: https://github.com/ebio-snu/cvtdriver */ #include <iostream> #include <sstream> #include <string> #include <queue> #include <boost/config.hpp> #include <glog/logging.h> #include <mysql_connection.h> #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #include "../spec/cvtdevice.h" #include "../spec/cvtdriver.h" using namespace std; using namespace stdcvt; namespace ebiodriver { // 센서에 기능을 추가하고 싶을때 사용할 수 있다는 예시 // CvtSensor 는 id로 문자열을 처리하지만, SSSensor는 숫자로 처리함 // 실제로 사용하지는 않음 class SSSensor : public CvtSensor { public: SSSensor(int devid, stdcvt::devtype_t devtype, stdcvt::devsec_t section, stdcvt::devtarget_t target, stdcvt::devstat_t devstatus, stdcvt::obsunit_t unit) : stdcvt::CvtSensor (to_string(devid), devtype, section, target, devstatus, unit) { } }; // 모터에 기능을 추가하고 싶을때 사용할 수 있다는 예시 // CvtMotor 는 id로 문자열을 처리하지만, SSMotor는 숫자로 처리함 // 실제로 사용하지는 않음 class SSMotor : public CvtMotor{ public: SSMotor(int devid, stdcvt::devtype_t devtype, stdcvt::devsec_t section, stdcvt::devtarget_t target, stdcvt::devstat_t devstatus) : stdcvt::CvtMotor(to_string(devid), devtype, section, target, devstatus) { } }; // 스위치에 기능을 추가하고 싶을때 사용할 수 있다는 예시 // CvtActuator는 id로 문자열을 처리하지만, SSSwitch는 숫자로 처리함 // 실제로 사용하지는 않음 class SSSwitch : public CvtActuator { public: SSSwitch(int devid, stdcvt::devtype_t devtype, stdcvt::devsec_t section, stdcvt::devtarget_t target, stdcvt::devstat_t devstatus) : stdcvt::CvtActuator(to_string(devid), devtype, section, target, devstatus) { } }; class SSSampleDriver : public CvtDriver { private: int _lastcmdid; ///< 명령아이디 시퀀스 queue<CvtCommand *> _cmdq; ///< 명령 큐 vector<CvtDevice *> _devvec; ///< 디바이스 벡터 string _host; ///< 디비 호스트 string _user; ///< 디비 사용자 string _pass; ///< 디비 사용자 암호 string _db; ///< 디비명 sql::Driver *_driver; ///< 디비 드라이버 sql::Connection *_con; ///< 디비 연결자 public: /** 새로운 SS드라이버를 생성한다. */ SSSampleDriver() : stdcvt::CvtDriver (2001, 100) { _lastcmdid = 0; _host = _user = _pass = _db = ""; updated(); // 샘플 SS드라이버는 직접 통신을 수행하지 않기 때문에, 테스트 통과를 위해서 넣음. } ~SSSampleDriver () { } /** 드라이버 제작자가 부여하는 버전번호를 확인한다. @return 문자열 형식의 버전번호 */ string getversion () { return "V0.1.0"; } /** 드라이버 제작자가 부여하는 모델번호를 확인한다. @return 문자열 형식의 모델번호 */ string getmodel () { return "ebioss_v1"; } /** 드라이버 제조사명을 확인한다. 컨버터에서는 제조사명을 로깅용도로만 사용한다. @return 문자열 형식의 제조사명 */ string getcompany () { return "EBIO lab. SNU."; } /** 드라이버를 초기화 한다. 드라이버 동작을 위한 option 은 key-value 형식으로 전달된다. @param option 드라이버동작을 위한 옵션 @return 초기화 성공 여부 */ bool initialize (CvtOption option) { LOG(INFO) << "SSSampleDriver initialized."; _host = option.get("host"); _user = option.get("user"); _pass = option.get("pass"); _db = option.get("db"); try { _driver = get_driver_instance(); _con = _driver->connect(_host, _user, _pass); _con->setSchema(_db); } catch (sql::SQLException &e) { LOG(ERROR) << "# open ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } try { sql::Statement *stmt; stmt = _con->createStatement(); stmt->execute ("TRUNCATE TABLE commands"); delete stmt; } catch (sql::SQLException &e) { LOG(ERROR) << "# Truncate commands ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } return true; } /** 드라이버를 종료한다. @return 종료 성공 여부 */ bool finalize () { delete _con; LOG(INFO) << "SSSampleDriver finalized."; return true; } /** 드라이버간 상태교환을 하기전에 호출되는 메소드로 전처리를 수행한다. @return 전처리 성공 여부 */ bool preprocess () { //read command from DB try { sql::PreparedStatement *prepstmt; sql::ResultSet *res; CvtCommand *pcmd; prepstmt = _con->prepareStatement("SELECT id, devtype, section, target, onoff, ratio from commands where id > ?"); prepstmt->setInt(1, _lastcmdid); res = prepstmt->executeQuery(); while (res->next()) { if (CvtDevice::getgroup((devtype_t)res->getInt(2)) == DG_MOTOR) { CvtDeviceSpec tmpspec((devtype_t)res->getInt(2), (devsec_t)res->getInt64(3), (devtarget_t)res->getInt(4)); pcmd = new CvtRatioCommand (res->getInt(1), &tmpspec, (res->getInt(5) > 0) ? true: false, res->getDouble(6)); } else if (res->getInt(2) / 10000 == DG_SWITCH) { CvtDeviceSpec tmpspec((devtype_t)res->getInt(2), (devsec_t)res->getInt64(3), (devtarget_t)res->getInt(4)); pcmd = new CvtCommand (res->getInt(1), &tmpspec, res->getInt(5)>0? true: false); } else { continue; } _lastcmdid = pcmd->getid (); _cmdq.push (pcmd); } delete res; delete prepstmt; } catch (sql::SQLException &e) { LOG(ERROR) << "# command select ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } updated(); // 샘플 SS드라이버는 직접 통신을 수행하지 않기 때문에, 테스트 통과를 위해서 넣음. return true; } /** 드라이버간 상태교환이 이루어진 이후에 호출되는 메소드로 후처리를 수행한다. @return 후처리 성공 여부 */ bool postprocess () { //write observation to DB try { sql::Statement *stmt; stmt = _con->createStatement(); stmt->execute ("TRUNCATE TABLE devices"); delete stmt; } catch (sql::SQLException &e) { LOG(ERROR) << "# Truncate devices ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } try { sql::PreparedStatement *prepstmt; prepstmt = _con->prepareStatement( "INSERT INTO devices(id, devtype, section, target, status, value, unit)" " VALUES (?, ?, ?, ?, ?, ?, ?)"); for (vector<CvtDevice *>::size_type i = 0; i < _devvec.size(); ++i) { prepstmt->setString(1, _devvec[i]->getid()); prepstmt->setInt(2, (_devvec[i]->getspec())->gettype()); prepstmt->setInt64(3, (_devvec[i]->getspec())->getsection()); prepstmt->setInt(4, (_devvec[i]->getspec())->gettarget()); prepstmt->setInt(5, _devvec[i]->getstatus()); if (CvtMotor *pmotor= dynamic_cast<CvtMotor *>(_devvec[i])) { // younger first LOG(INFO) << "motor : " << pmotor->tostring(); LOG(INFO) << "motor current : " << pmotor->getcurrent(); prepstmt->setDouble(6, pmotor->getcurrent ()); prepstmt->setInt(7, OU_NONE); } else if (CvtActuator *pactuator = dynamic_cast<CvtActuator *>(_devvec[i])) { prepstmt->setDouble(6, 0); prepstmt->setInt(7, OU_NONE); } else if (CvtSensor *psensor = dynamic_cast<CvtSensor *>(_devvec[i])) { prepstmt->setDouble(6, psensor->readobservation ()); prepstmt->setInt(7, psensor->getunit ()); } prepstmt->execute (); delete _devvec[i]; } _con->commit (); delete prepstmt; _devvec.clear (); } catch (sql::SQLException &e) { LOG(ERROR) << "# Insert devices ERR: SQLException " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )"; return false; } return true; } /** 드라이버가 관리하고 있는 장비의 포인터를 꺼내준다. @param index 얻고자 하는 장비의 인덱스 번호. 0에서 시작한다. @return 인덱스에 해당하는 장비의 포인터. NULL 이라면 이후에 장비가 없다는 의미이다. */ CvtDevice *getdevice(int index) { return nullptr; } /** 전달된 장비의 정보를 획득한다. 다른 드라이버의 장비정보를 입력해주기 위해 컨버터가 호출한다. @param pdevice 다른 드라이버의 장비 포인터 @return 성공여부. 관심이 없는 장비인 경우라도 문제가 없으면 true를 리턴한다. */ bool sharedevice(CvtDevice *pdevice) { CvtDevice *newdev = pdevice->clone (); _devvec.push_back (newdev); return true; } /** 다른 드라이버가 관리하고 있는 장비를 제어하고자 할때 명령을 전달한다. 명령을 전달하지 않는 드라이버라면 그냥 NULL을 리턴하도록 만들면 된다. @return 인덱스에 해당하는 명령의 포인터. NULL 이라면 이후에 명령이 없다는 의미이다. */ CvtCommand *getcommand() { if (_cmdq.empty ()) return nullptr; CvtCommand *pcmd = _cmdq.front(); _cmdq.pop (); return pcmd; } /** 다른 드라이버로부터 명령을 받아 처리한다. @param pcmd 명령에 대한 포인터 @return 실제 명령의 처리 여부가 아니라 명령을 수신했는지 여부이다. 해당 명령을 실행할 장비가 없다면 false이다. */ bool control(CvtCommand *pcmd) { return false; } }; extern "C" BOOST_SYMBOL_EXPORT SSSampleDriver plugin; SSSampleDriver plugin; } // namespace ebiodriver
31.363077
126
0.532817
[ "vector" ]
c06b7f09dafd7d6643c45ff63b500eeddc6002d1
4,412
cpp
C++
src/v1/async.cpp
DanglingPointer/async
2ff2a430e698ee386a03c8b7e872d7da24187d81
[ "Apache-2.0" ]
3
2020-06-11T11:06:13.000Z
2021-12-19T12:58:08.000Z
src/v1/async.cpp
DanglingPointer/async
2ff2a430e698ee386a03c8b7e872d7da24187d81
[ "Apache-2.0" ]
null
null
null
src/v1/async.cpp
DanglingPointer/async
2ff2a430e698ee386a03c8b7e872d7da24187d81
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019 Mikhail Vasilyev * * 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 "callback.hpp" #include "canceller.hpp" /** * Flag layout: * 0 * 0 1 2 3 4 5 6 7 8 * +-+-+-+-+-+-+-+-+ * | ID=6 |C|A| * +-+-+-+-+-+-+-+-+ * * * CallbackId layout: * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | ID=6 | INDEX=26 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * * A - alive bit. 1 = callback object exists, 0 = callback has gone out of scope. * * C - cancelled bit. Set when callback is being cancelled explicitly by its creator * (i.e. via Canceller::CancelCallback()). * * ID - unique operation id in order to be able to reuse a flag once its previous operation has * finished. Incremented each time the flag is used for a new operation. * NB! Will wrap around eventually which might cause CallbackId clashes. To mitigate this * somewhat, a CallbackId is set to nullopt once we know that the operation is inactive or * cancelled. * * INDEX - position of flag in the array storing all flags (i.e. m_activeFlags in Canceller). * */ namespace async::v1 { namespace { constexpr uint8_t MASK_ALIVE = 1 << 7; constexpr uint8_t MASK_CANCELLED = 1 << 6; constexpr int ID_LENGTH = 6; constexpr uint8_t MASK_ID = (1 << ID_LENGTH) - 1; } // namespace namespace internal { AtomicFlagRef::AtomicFlagRef(std::atomic<uint8_t> * block) noexcept : m_block(block) {} bool AtomicFlagRef::IsEmpty() const noexcept { return m_block == nullptr; } bool AtomicFlagRef::IsAlive() const noexcept { assert(!IsEmpty()); return (m_block->load() & MASK_ALIVE) != 0; } bool AtomicFlagRef::IsCancelled() const noexcept { assert(!IsEmpty()); return (m_block->load() & MASK_CANCELLED) != 0; } uint32_t AtomicFlagRef::GetId() const noexcept { assert(!IsEmpty()); return m_block->load() & MASK_ID; } void AtomicFlagRef::Activate() noexcept { assert(!IsEmpty()); m_block->fetch_add(1); m_block->fetch_or(MASK_ALIVE); m_block->fetch_and(static_cast<uint8_t>(~MASK_CANCELLED)); } void AtomicFlagRef::Deactivate() noexcept { assert(!IsEmpty()); m_block->fetch_and(static_cast<uint8_t>(~MASK_ALIVE)); } void AtomicFlagRef::Cancel() noexcept { assert(!IsEmpty()); m_block->fetch_or(MASK_CANCELLED); } bool operator==(AtomicFlagRef lhs, AtomicFlagRef rhs) noexcept { return lhs.m_block == rhs.m_block; } bool operator!=(AtomicFlagRef lhs, AtomicFlagRef rhs) noexcept { return !(lhs == rhs); } const std::shared_ptr<CancellerToken> & GlobalCancellerToken() { static auto s_token = std::make_shared<CancellerToken>(); return s_token; } uint32_t MakeCallbackId(AtomicFlagRef flagRef, size_t index) noexcept { uint32_t ret = index << ID_LENGTH; ret |= flagRef.GetId(); return ret; } size_t GetFlagIndex(uint32_t callbackId) noexcept { return callbackId >> ID_LENGTH; } uint32_t GetOperationId(uint32_t callbackId) noexcept { return callbackId & MASK_ID; } } // namespace internal void OnAllCompleted::Detach() { if (m_state) { assert(m_state->trackedCount >= 10'000U); m_state->trackedCount -= 10'000U; if (m_state->firedCount == m_state->trackedCount) { m_state->listener(); delete m_state; m_state = nullptr; } } } void OnAnyCompleted::Detach() { if (m_state) { assert(m_state->trackedCount >= 10'000U); m_state->trackedCount -= 10'000U; if (m_state->firedCount > 0U) { m_state->listener(); } if (m_state->firedCount == m_state->trackedCount) { delete m_state; m_state = nullptr; } } } } // namespace async::v1
26.578313
95
0.6335
[ "object" ]
c06da721499d47cf429f1a857437e296de7d69c9
3,176
cpp
C++
eval_movement/src/main.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
1
2016-11-02T08:42:05.000Z
2016-11-02T08:42:05.000Z
eval_movement/src/main.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
null
null
null
eval_movement/src/main.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <random> #include "slide_algorithm/algorithm.hpp" #include "data_type.hpp" #include "test_tool.hpp" int main(int argc, char* argv[]) { // スコープ長いけれど…… std::string const output_filename = "report_movement"; if(argc != 2 || argc != 4)\ if(argc != 2 && argc != 4) { std::cout << "Usage: " << argv[0] << " 試行回数 [分割数タテ 分割数ヨコ]" << std::endl; //std::quick_exit(-1); return -1; } bool const is_fixed = argc == 4; int const try_num = std::atoi(argv[1]); auto const split_num = is_fixed ? std::make_pair(std::atoi(argv[3]), std::atoi(argv[2])) : std::make_pair(-1, -1); std::mt19937 mt; std::uniform_int_distribution<int> select_dist(1, 20); // 選択可能回数生成器 std::uniform_int_distribution<int> size_dist (2, 16); // サイズ生成器 std::uniform_int_distribution<int> cost_dist (1, 50); // コスト生成器 for(int n=0; n<try_num; ++n) { int const problem_id = 0; // 仮 std::string const player_id = "0"; //仮 std::pair<int,int> const size = is_fixed ? split_num : std::make_pair(size_dist(mt), size_dist(mt)); int const selectable = select_dist(mt); int const cost_select = cost_dist(mt); int const cost_change = cost_dist(mt); std::vector<std::vector<point_type>> block( size.second, std::vector<point_type>(size.first, {-1, -1}) ); std::uniform_int_distribution<int> x_dist(0, size.first - 1); std::uniform_int_distribution<int> y_dist(0, size.second - 1); for(int i=0; i<size.second; ++i) { for(int j=0; j<size.first; ++j) { int x, y; do { x = x_dist(mt); y = y_dist(mt); } while(!(block[y][x] == point_type{-1, -1})); block[y][x] = point_type{j, i}; } } // テストデータ発行 question_data question{ problem_id, player_id, size, selectable, cost_select, cost_change, block }; // 実行から評価まで algorithm algo; algo.reset(question); // テストデータのセット // エミュレータ起動 test_tool::emulator emu(question); // 評価保存先ファイルを開き,問題データを書き込む std::ofstream ofs(output_filename + std::to_string(n) + ".csv"); ofs << "[Question]\n"; for(auto const& line : block) { for(auto const& elem : line) { ofs << R"(")" << elem.x << "," << elem.y << R"(", )"; } ofs << "\n"; } ofs << "\n"; ofs << "[Answer]\n"; ofs << "回数,間違い位置数,コスト\n"; int counter = 0; while(auto first_result = algo.get()) // 解答が受け取れる間ループ { // 評価 auto const evaluate = emu.start(first_result.get()); // 書出 ofs << counter+1 << "," <<evaluate.wrong << "," << evaluate.cost << "\n"; ++counter; // テストなので解答回数をカウントする必要あるかなと } } return 0; }
28.357143
118
0.494332
[ "vector" ]
c06da802750d5be4dc7ab7f6ddaf7c80afb429e2
9,582
hpp
C++
include/UnityEngine/ProBuilder/ObjectPool_1.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/ProBuilder/ObjectPool_1.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/ProBuilder/ObjectPool_1.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.IDisposable #include "System/IDisposable.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: Queue`1<T> template<typename T> class Queue_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: Func`1<TResult> template<typename TResult> class Func_1; // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Forward declaring type: ObjectPool`1<T> template<typename T> class ObjectPool_1; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::UnityEngine::ProBuilder::ObjectPool_1, "UnityEngine.ProBuilder", "ObjectPool`1"); // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // WARNING Size may be invalid! // Autogenerated type: UnityEngine.ProBuilder.ObjectPool`1 // [TokenAttribute] Offset: FFFFFFFF template<typename T> class ObjectPool_1 : public ::Il2CppObject/*, public ::System::IDisposable*/ { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Boolean m_IsDisposed // Size: 0x1 // Offset: 0x0 bool m_IsDisposed; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Collections.Generic.Queue`1<T> m_Pool // Size: 0x8 // Offset: 0x0 ::System::Collections::Generic::Queue_1<T>* m_Pool; // Field size check static_assert(sizeof(::System::Collections::Generic::Queue_1<T>*) == 0x8); // public System.Int32 desiredSize // Size: 0x4 // Offset: 0x0 int desiredSize; // Field size check static_assert(sizeof(int) == 0x4); // public System.Func`1<T> constructor // Size: 0x8 // Offset: 0x0 ::System::Func_1<T>* constructor; // Field size check static_assert(sizeof(::System::Func_1<T>*) == 0x8); // public System.Action`1<T> destructor // Size: 0x8 // Offset: 0x0 ::System::Action_1<T>* destructor; // Field size check static_assert(sizeof(::System::Action_1<T>*) == 0x8); public: // Creating interface conversion operator: operator ::System::IDisposable operator ::System::IDisposable() noexcept { return *reinterpret_cast<::System::IDisposable*>(this); } // Autogenerated instance field getter // Get instance field: private System.Boolean m_IsDisposed bool& dyn_m_IsDisposed() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::dyn_m_IsDisposed"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_IsDisposed"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Collections.Generic.Queue`1<T> m_Pool ::System::Collections::Generic::Queue_1<T>*& dyn_m_Pool() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::dyn_m_Pool"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_Pool"))->offset; return *reinterpret_cast<::System::Collections::Generic::Queue_1<T>**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Int32 desiredSize int& dyn_desiredSize() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::dyn_desiredSize"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "desiredSize"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Func`1<T> constructor ::System::Func_1<T>*& dyn_constructor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::dyn_constructor"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "constructor"))->offset; return *reinterpret_cast<::System::Func_1<T>**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Action`1<T> destructor ::System::Action_1<T>*& dyn_destructor() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::dyn_destructor"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "destructor"))->offset; return *reinterpret_cast<::System::Action_1<T>**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // public System.Void .ctor(System.Int32 initialSize, System.Int32 desiredSize, System.Func`1<T> constructor, System.Action`1<T> destructor, System.Boolean lazyInitialization) // Offset: 0xFFFFFFFFFFFFFFFF template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ObjectPool_1<T>* New_ctor(int initialSize, int desiredSize, ::System::Func_1<T>* constructor, ::System::Action_1<T>* destructor, bool lazyInitialization) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ObjectPool_1<T>*, creationType>(initialSize, desiredSize, constructor, destructor, lazyInitialization))); } // public T Dequeue() // Offset: 0xFFFFFFFFFFFFFFFF T Dequeue() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::Dequeue"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Dequeue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<T, false>(this, ___internal__method); } // public System.Void Enqueue(T obj) // Offset: 0xFFFFFFFFFFFFFFFF void Enqueue(T obj) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::Enqueue"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Enqueue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(obj)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, obj); } // public System.Void Empty() // Offset: 0xFFFFFFFFFFFFFFFF void Empty() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::Empty"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Empty", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // public System.Void Dispose() // Offset: 0xFFFFFFFFFFFFFFFF void Dispose() { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::Dispose"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Dispose", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // private System.Void Dispose(System.Boolean disposing) // Offset: 0xFFFFFFFFFFFFFFFF void Dispose(bool disposing) { static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ProBuilder::ObjectPool_1::Dispose"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Dispose", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(disposing)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, disposing); } }; // UnityEngine.ProBuilder.ObjectPool`1 // Could not write size check! Type: UnityEngine.ProBuilder.ObjectPool`1 is generic, or has no fields that are valid for size checks! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
53.831461
205
0.705489
[ "vector" ]
c0710d747a2c46641504eb6379cb7e7b0ba280a5
1,121
cpp
C++
C++/C++ Fundamentals Sept 2019/05. STRINGS AND STREAMS/codecpp/src/TheNoiseAndTheSignal_2.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
1
2019-07-21T13:00:31.000Z
2019-07-21T13:00:31.000Z
C++/C++ Fundamentals Sept 2019/05. STRINGS AND STREAMS/codecpp/src/TheNoiseAndTheSignal_2.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
C++/C++ Fundamentals Sept 2019/05. STRINGS AND STREAMS/codecpp/src/TheNoiseAndTheSignal_2.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
#include <iostream> #include<string> #include<sstream> #include <vector> using namespace std; int main() { std::string line; std::getline(std::cin, line); std::istringstream lineStream(line); std::string currentWord; std::string noise; while (lineStream >> currentWord) { size_t size = (int) currentWord.size(); std::string currNoise; for (size_t i = 0; i < size; ++i) { char16_t c = currentWord[i]; if (isdigit(c)) { currentWord[i] = ' '; } } std::istringstream currentWordStream(currentWord); std::string currentWord2; while (currentWordStream >> currentWord2) { currNoise += currentWord2; } if (noise.empty()) { noise = currNoise; } else if (currNoise.size() >= noise.size()) { if (currNoise < noise) { noise = currNoise; } } } if (!noise.empty()) { std::cout << noise << std::endl; } else { std::cout << "no noise" << std::endl; } return 0; }
21.980392
58
0.512935
[ "vector" ]
c072c0da830b28ca952308ac5791e648956b389e
5,389
cpp
C++
source/thewizardplusplus/anna/sound/OpenALAudioDevice.cpp
thewizardplusplus/anna-sound
317cb26b9d968e2813a45cc7579b0dbe3451c282
[ "MIT" ]
null
null
null
source/thewizardplusplus/anna/sound/OpenALAudioDevice.cpp
thewizardplusplus/anna-sound
317cb26b9d968e2813a45cc7579b0dbe3451c282
[ "MIT" ]
null
null
null
source/thewizardplusplus/anna/sound/OpenALAudioDevice.cpp
thewizardplusplus/anna-sound
317cb26b9d968e2813a45cc7579b0dbe3451c282
[ "MIT" ]
null
null
null
#include "OpenALAudioDevice.h" #include "exceptions/UnableToOpenOpenALDeviceException.h" #include "exceptions/UnableToCreateOpenALContextException.h" #include "OpenALListener.h" #include "exceptions/UnableToCreateOpenALSourceException.h" #include "OpenALSource.h" #include "exceptions/UnableToCreateOpenALBufferException.h" #include "OpenALBuffer.h" #include "exceptions/UnableToSetOpenALBufferException.h" #include <AL/al.h> using namespace thewizardplusplus::anna::sound; using namespace thewizardplusplus::anna::sound::exceptions; OpenALAudioDevice::OpenALAudioDevice(AudioDeviceAttribute::Map context_attributes) : openal_device(NULL), openal_context(NULL) { openal_device = alcOpenDevice(NULL); if (openal_device == NULL) { throw UnableToOpenOpenALDeviceException(); } int* attributes = NULL; if (context_attributes.size()) { attributes = new int[context_attributes.size() * 2 + 1]; AudioDeviceAttribute::Map::const_iterator i = context_attributes. begin(); int j = 0; for (; i != context_attributes.end(); ++i) { switch (i->first) { case AudioDeviceAttribute::FREQUENCY: attributes[j] = ALC_FREQUENCY; break; case AudioDeviceAttribute::REFRESH: attributes[j] = ALC_REFRESH; break; case AudioDeviceAttribute::SYNC: attributes[j] = ALC_SYNC; break; case AudioDeviceAttribute::MONO_SOURCES: attributes[j] = ALC_MONO_SOURCES; break; case AudioDeviceAttribute::STEREO_SOURCES: attributes[j] = ALC_STEREO_SOURCES; break; } j++; attributes[j] = i->second; j++; } attributes[j] = 0; } openal_context = alcCreateContext(openal_device, attributes); delete[] attributes; attributes = NULL; if (openal_context == NULL) { throw UnableToCreateOpenALContextException(); } alcMakeContextCurrent(openal_context); listener = new OpenALListener(); } OpenALAudioDevice::~OpenALAudioDevice(void) { SourceMap::iterator i = sources.begin(); for (; i != sources.end(); ++i) { delete i->first; } BufferMap::iterator j = buffers.begin(); for (; j != buffers.end(); ++j) { delete j->first; } alcMakeContextCurrent(NULL); alcDestroyContext(openal_context); openal_context = NULL; alcCloseDevice(openal_device); openal_device = NULL; } float OpenALAudioDevice::getDopplerFactor(void) const { return alGetFloat(AL_DOPPLER_FACTOR); } void OpenALAudioDevice::setDopplerFactor(float value) { alDopplerFactor(value); } float OpenALAudioDevice::getSpeedOfSound(void) const { return alGetFloat(AL_SPEED_OF_SOUND); } void OpenALAudioDevice::setSpeedOfSound(float units_per_second) { alSpeedOfSound(units_per_second); } DistanceModel::Types OpenALAudioDevice::getDistanceModel(void) const { switch (alGetInteger(AL_DISTANCE_MODEL)) { case AL_NONE: return DistanceModel::NONE; case AL_LINEAR_DISTANCE: return DistanceModel::LINEAR_DISTANCE; case AL_LINEAR_DISTANCE_CLAMPED: return DistanceModel::LINEAR_DISTANCE_CLAMPED; case AL_INVERSE_DISTANCE: return DistanceModel::INVERSE_DISTANCE; case AL_INVERSE_DISTANCE_CLAMPED: return DistanceModel::INVERSE_DISTANCE_CLAMPED; case AL_EXPONENT_DISTANCE: return DistanceModel::EXPONENT_DISTANCE; case AL_EXPONENT_DISTANCE_CLAMPED: return DistanceModel::EXPONENT_DISTANCE_CLAMPED; default: return DistanceModel::UNKNOWN; } } void OpenALAudioDevice::setDistanceModel(DistanceModel::Types model) { switch (model) { case DistanceModel::NONE: alDistanceModel(AL_NONE); break; case DistanceModel::LINEAR_DISTANCE: alDistanceModel(AL_LINEAR_DISTANCE); break; case DistanceModel::LINEAR_DISTANCE_CLAMPED: alDistanceModel(AL_LINEAR_DISTANCE_CLAMPED); break; case DistanceModel::INVERSE_DISTANCE: alDistanceModel(AL_INVERSE_DISTANCE); break; case DistanceModel::INVERSE_DISTANCE_CLAMPED: alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); break; case DistanceModel::EXPONENT_DISTANCE: alDistanceModel(AL_EXPONENT_DISTANCE); break; case DistanceModel::EXPONENT_DISTANCE_CLAMPED: alDistanceModel(AL_EXPONENT_DISTANCE_CLAMPED); break; case DistanceModel::UNKNOWN: alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); break; } } Source* OpenALAudioDevice::createSource(void) { unsigned int openal_source = 0; alGenSources(1, &openal_source); if (alGetError() != AL_NO_ERROR) { throw UnableToCreateOpenALSourceException(); } Source* source = new OpenALSource(this, openal_source); sources[source] = openal_source; return source; } Source* OpenALAudioDevice::takeOutSource(Source* source) { sources.erase(source); return source; } Buffer* OpenALAudioDevice::createBuffer(void) { unsigned int openal_buffer = 0; alGenBuffers(1, &openal_buffer); if (alGetError() != AL_NO_ERROR) { throw UnableToCreateOpenALBufferException(); } Buffer* buffer = new OpenALBuffer(this, openal_buffer); buffers[buffer] = openal_buffer; return buffer; } Buffer* OpenALAudioDevice::takeOutBuffer(Buffer* buffer) { buffers.erase(buffer); return buffer; } void OpenALAudioDevice::join(Buffer* buffer, Source* source) { if (buffers.count(buffer) && sources.count(source)) { alSourcei(sources[source], AL_BUFFER, buffers[buffer]); } else if (buffer == NULL && sources.count(source)) { alSourcei(sources[source], AL_BUFFER, 0); } else { return; } if (alGetError() != AL_NO_ERROR) { throw UnableToSetOpenALBufferException(); } }
26.546798
70
0.75784
[ "model" ]
c07449062d43406ce848c3627c89d3287569f145
26,162
cpp
C++
src/Main.cpp
clayne/ShaderToggler
dfa7b29904544cec81c2cd8f8c9eeb520b7c4669
[ "MIT" ]
3
2022-02-26T22:07:40.000Z
2022-03-28T19:53:00.000Z
src/Main.cpp
clayne/ShaderToggler
dfa7b29904544cec81c2cd8f8c9eeb520b7c4669
[ "MIT" ]
null
null
null
src/Main.cpp
clayne/ShaderToggler
dfa7b29904544cec81c2cd8f8c9eeb520b7c4669
[ "MIT" ]
1
2022-02-26T22:07:42.000Z
2022-02-26T22:07:42.000Z
/////////////////////////////////////////////////////////////////////// // // Part of ShaderToggler, a shader toggler add on for Reshade 5+ which allows you // to define groups of shaders to toggle them on/off with one key press // // (c) Frans 'Otis_Inf' Bouma. // // All rights reserved. // https://github.com/FransBouma/ShaderToggler // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ///////////////////////////////////////////////////////////////////////// #define IMGUI_DISABLE_INCLUDE_IMCONFIG_H #define ImTextureID unsigned long long // Change ImGui texture ID type to that of a 'reshade::api::resource_view' handle #include <imgui.h> #include <reshade.hpp> #include "crc32_hash.hpp" #include "ShaderManager.h" #include "CDataFile.h" #include "ToggleGroup.h" #include <vector> using namespace reshade::api; using namespace ShaderToggler; extern "C" __declspec(dllexport) const char *NAME = "Shader Toggler"; extern "C" __declspec(dllexport) const char *DESCRIPTION = "Add-on which allows you to define groups of game shaders to toggle on/off with one key press."; struct __declspec(uuid("038B03AA-4C75-443B-A695-752D80797037")) CommandListDataContainer { uint64_t activePixelShaderPipeline; uint64_t activeVertexShaderPipeline; }; #define FRAMECOUNT_COLLECTION_PHASE_DEFAULT 250; #define HASH_FILE_NAME "ShaderToggler.ini" static ShaderToggler::ShaderManager g_pixelShaderManager; static ShaderToggler::ShaderManager g_vertexShaderManager; static KeyData g_keyCollector; static atomic_uint32_t g_activeCollectorFrameCounter = 0; static std::vector<ToggleGroup> g_toggleGroups; static atomic_int g_toggleGroupIdKeyBindingEditing = -1; static atomic_int g_toggleGroupIdShaderEditing = -1; static float g_overlayOpacity = 1.0f; static int g_startValueFramecountCollectionPhase = FRAMECOUNT_COLLECTION_PHASE_DEFAULT; /// <summary> /// Calculates a crc32 hash from the passed in shader bytecode. The hash is used to identity the shader in future runs. /// </summary> /// <param name="shaderData"></param> /// <returns></returns> static uint32_t calculateShaderHash(void* shaderData) { if(nullptr==shaderData) { return 0; } const auto shaderDesc = *static_cast<shader_desc *>(shaderData); return compute_crc32(static_cast<const uint8_t *>(shaderDesc.code), shaderDesc.code_size); } /// <summary> /// Adds a default group with VK_CAPITAL as toggle key. Only used if there aren't any groups defined in the ini file. /// </summary> void addDefaultGroup() { ToggleGroup toAdd("Default", ToggleGroup::getNewGroupId()); toAdd.setToggleKey(VK_CAPITAL, false, false, false); g_toggleGroups.push_back(toAdd); } /// <summary> /// Loads the defined hashes and groups from the shaderToggler.ini file. /// </summary> void loadShaderTogglerIniFile() { // Will assume it's started at the start of the application and therefore no groups are present. CDataFile iniFile; if(!iniFile.Load(HASH_FILE_NAME)) { // not there return; } int groupCounter = 0; const int numberOfGroups = iniFile.GetInt("AmountGroups", "General"); if(numberOfGroups==INT_MIN) { // old format file? addDefaultGroup(); groupCounter=-1; // enforce old format read for pre 1.0 ini file. } else { for(int i=0;i<numberOfGroups;i++) { g_toggleGroups.push_back(ToggleGroup("", ToggleGroup::getNewGroupId())); } } for(auto& group: g_toggleGroups) { group.loadState(iniFile, groupCounter); // groupCounter is normally 0 or greater. For when the old format is detected, it's -1 (and there's 1 group). groupCounter++; } } /// <summary> /// Saves the currently known toggle groups with their shader hashes to the shadertoggler.ini file /// </summary> void saveShaderTogglerIniFile() { // format: first section with # of groups, then per group a section with pixel and vertex shaders, as well as their name and key value. // groups are stored with "Group" + group counter, starting with 0. CDataFile iniFile; iniFile.SetInt("AmountGroups", g_toggleGroups.size(), "", "General"); int groupCounter = 0; for(const auto& group: g_toggleGroups) { group.saveState(iniFile, groupCounter); groupCounter++; } iniFile.SetFileName(HASH_FILE_NAME); iniFile.Save(); } static void onInitCommandList(command_list *commandList) { commandList->create_private_data<CommandListDataContainer>(); } static void onDestroyCommandList(command_list *commandList) { commandList->destroy_private_data<CommandListDataContainer>(); } static void onResetCommandList(command_list *commandList) { CommandListDataContainer &commandListData = commandList->get_private_data<CommandListDataContainer>(); commandListData.activePixelShaderPipeline = -1; commandListData.activeVertexShaderPipeline = -1; } static void onInitPipeline(device *device, pipeline_layout, uint32_t subobjectCount, const pipeline_subobject *subobjects, pipeline pipelineHandle) { // shader has been created, we will now create a hash and store it with the handle we got. for (uint32_t i = 0; i < subobjectCount; ++i) { switch (subobjects[i].type) { case pipeline_subobject_type::vertex_shader: { g_vertexShaderManager.addHashHandlePair(calculateShaderHash(subobjects[i].data), pipelineHandle.handle); } break; case pipeline_subobject_type::pixel_shader: { g_pixelShaderManager.addHashHandlePair(calculateShaderHash(subobjects[i].data), pipelineHandle.handle); } break; } } } static void onDestroyPipeline(device *device, pipeline pipelineHandle) { g_pixelShaderManager.removeHandle(pipelineHandle.handle); g_vertexShaderManager.removeHandle(pipelineHandle.handle); } static void displayIsPartOfToggleGroup() { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 0.0f, 1.0f)); ImGui::SameLine(); ImGui::Text(" Shader is part of this toggle group."); ImGui::PopStyleColor(); } static void onReshadeOverlay(reshade::api::effect_runtime *runtime) { if(g_toggleGroupIdShaderEditing>=0) { ImGui::SetNextWindowBgAlpha(g_overlayOpacity); ImGui::SetNextWindowPos(ImVec2(10, 10)); if (!ImGui::Begin("ShaderTogglerInfo", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) { ImGui::End(); return; } string editingGroupName = ""; for(auto& group:g_toggleGroups) { if(group.getId()==g_toggleGroupIdShaderEditing) { editingGroupName = group.getName(); break; } } ImGui::Text("# of pipelines with vertex shaders: %d. # of different vertex shaders gathered: %d.", g_vertexShaderManager.getPipelineCount(), g_vertexShaderManager.getShaderCount()); ImGui::Text("# of pipelines with pixel shaders: %d. # of different pixel shaders gathered: %d.", g_pixelShaderManager.getPipelineCount(), g_pixelShaderManager.getShaderCount()); if(g_activeCollectorFrameCounter > 0) { const uint32_t counterValue = g_activeCollectorFrameCounter; ImGui::Text("Collecting active shaders... frames to go: %d", counterValue); } else { if(g_vertexShaderManager.isInHuntingMode() || g_pixelShaderManager.isInHuntingMode()) { ImGui::Text("Editing the shaders for group: %s", editingGroupName.c_str()); } if(g_vertexShaderManager.isInHuntingMode()) { ImGui::Text("# of vertex shaders active: %d. # of vertex shaders in group: %d", g_vertexShaderManager.getAmountShaderHashesCollected(), g_vertexShaderManager.getMarkedShaderCount()); ImGui::Text("Current selected vertex shader: %d / %d.", g_vertexShaderManager.getActiveHuntedShaderIndex(), g_vertexShaderManager.getAmountShaderHashesCollected()); if(g_vertexShaderManager.isHuntedShaderMarked()) { displayIsPartOfToggleGroup(); } } if(g_pixelShaderManager.isInHuntingMode()) { ImGui::Text("# of pixel shaders active: %d. # of pixel shaders in group: %d", g_pixelShaderManager.getAmountShaderHashesCollected(), g_pixelShaderManager.getMarkedShaderCount()); ImGui::Text("Current selected pixel shader: %d / %d", g_pixelShaderManager.getActiveHuntedShaderIndex(), g_pixelShaderManager.getAmountShaderHashesCollected()); if(g_pixelShaderManager.isHuntedShaderMarked()) { displayIsPartOfToggleGroup(); } } } ImGui::End(); } } static void onBindPipeline(command_list* commandList, pipeline_stage stages, pipeline pipelineHandle) { if(nullptr!=commandList && pipelineHandle.handle!=0) { const bool handleHasPixelShaderAttached = g_pixelShaderManager.isKnownHandle(pipelineHandle.handle); const bool handleHasVertexShaderAttached = g_vertexShaderManager.isKnownHandle(pipelineHandle.handle); if(!handleHasPixelShaderAttached && !handleHasVertexShaderAttached) { // draw call with unknown handle, don't collect it return; } CommandListDataContainer &commandListData = commandList->get_private_data<CommandListDataContainer>(); switch(stages) { case pipeline_stage::all: if(g_activeCollectorFrameCounter>0) { // in collection mode if(handleHasPixelShaderAttached) { g_pixelShaderManager.addActivePipelineHandle(pipelineHandle.handle); } if(handleHasVertexShaderAttached) { g_vertexShaderManager.addActivePipelineHandle(pipelineHandle.handle); } } else { commandListData.activePixelShaderPipeline = handleHasPixelShaderAttached ? pipelineHandle.handle : -1; commandListData.activeVertexShaderPipeline = handleHasVertexShaderAttached ? pipelineHandle.handle : -1; } break; case pipeline_stage::pixel_shader: if(handleHasPixelShaderAttached) { if(g_activeCollectorFrameCounter>0) { // in collection mode g_pixelShaderManager.addActivePipelineHandle(pipelineHandle.handle); } commandListData.activePixelShaderPipeline = pipelineHandle.handle; } break; case pipeline_stage::vertex_shader: if(handleHasVertexShaderAttached) { if(g_activeCollectorFrameCounter>0) { // in collection mode g_vertexShaderManager.addActivePipelineHandle(pipelineHandle.handle); } commandListData.activeVertexShaderPipeline = pipelineHandle.handle; } break; } } } /// <summary> /// This function will return true if the command list specified has one or more shader hashes which are currently marked to be hidden. Otherwise false. /// </summary> /// <param name="commandList"></param> /// <returns>true if the draw call has to be blocked</returns> bool blockDrawCallForCommandList(command_list* commandList) { if(nullptr==commandList) { return false; } const CommandListDataContainer &commandListData = commandList->get_private_data<CommandListDataContainer>(); uint32_t shaderHash = g_pixelShaderManager.getShaderHash(commandListData.activePixelShaderPipeline); bool blockCall = g_pixelShaderManager.isBlockedShader(shaderHash); for(auto& group : g_toggleGroups) { blockCall |= group.isBlockedPixelShader(shaderHash); } shaderHash = g_vertexShaderManager.getShaderHash(commandListData.activeVertexShaderPipeline); blockCall |= g_vertexShaderManager.isBlockedShader(shaderHash); for(auto& group : g_toggleGroups) { blockCall |= group.isBlockedVertexShader(shaderHash); } return blockCall; } static bool onDraw(command_list* commandList, uint32_t vertex_count, uint32_t instance_count, uint32_t first_vertex, uint32_t first_instance) { // check if for this command list the active shader handles are part of the blocked set. If so, return true return blockDrawCallForCommandList(commandList); } static bool onDrawIndexed(command_list* commandList, uint32_t index_count, uint32_t instance_count, uint32_t first_index, int32_t vertex_offset, uint32_t first_instance) { // same as onDraw return blockDrawCallForCommandList(commandList); } static bool onDrawOrDispatchIndirect(command_list* commandList, indirect_command type, resource buffer, uint64_t offset, uint32_t draw_count, uint32_t stride) { switch(type) { case indirect_command::unknown: case indirect_command::draw: case indirect_command::draw_indexed: // same as OnDraw return blockDrawCallForCommandList(commandList); // the rest aren't blocked } return false; } static void onReshadePresent(effect_runtime* runtime) { if(g_activeCollectorFrameCounter>0) { --g_activeCollectorFrameCounter; } for(auto& group: g_toggleGroups) { if(group.isToggleKeyPressed(runtime)) { group.toggleActive(); // if the group's shaders are being edited, it should toggle the ones currently marked. if(group.getId() == g_toggleGroupIdShaderEditing) { g_vertexShaderManager.toggleHideMarkedShaders(); g_pixelShaderManager.toggleHideMarkedShaders(); } } } // hardcoded hunting keys. // If Ctrl is pressed too, it'll step to the next marked shader (if any) // Numpad 1: previous pixel shader // Numpad 2: next pixel shader // Numpad 3: mark current pixel shader as part of the toggle group // Numpad 4: previous vertex shader // Numpad 5: next vertex shader // Numpad 6: mark current vertex shader as part of the toggle group if(runtime->is_key_pressed(VK_NUMPAD1)) { g_pixelShaderManager.huntPreviousShader(runtime->is_key_down(VK_CONTROL)); } if(runtime->is_key_pressed(VK_NUMPAD2)) { g_pixelShaderManager.huntNextShader(runtime->is_key_down(VK_CONTROL)); } if(runtime->is_key_pressed(VK_NUMPAD3)) { g_pixelShaderManager.toggleMarkOnHuntedShader(); } if(runtime->is_key_pressed(VK_NUMPAD4)) { g_vertexShaderManager.huntPreviousShader(runtime->is_key_down(VK_CONTROL)); } if(runtime->is_key_pressed(VK_NUMPAD5)) { g_vertexShaderManager.huntNextShader(runtime->is_key_down(VK_CONTROL)); } if(runtime->is_key_pressed(VK_NUMPAD6)) { g_vertexShaderManager.toggleMarkOnHuntedShader(); } } /// <summary> /// Function which marks the end of a keybinding editing cycle /// </summary> /// <param name="acceptCollectedBinding"></param> /// <param name="groupEditing"></param> void endKeyBindingEditing(bool acceptCollectedBinding, ToggleGroup& groupEditing) { if (acceptCollectedBinding && g_toggleGroupIdKeyBindingEditing == groupEditing.getId() && g_keyCollector.isValid()) { groupEditing.setToggleKey(g_keyCollector); } g_toggleGroupIdKeyBindingEditing = -1; g_keyCollector.clear(); } /// <summary> /// Function which marks the start of a keybinding editing cycle for the passed in toggle group /// </summary> /// <param name="groupEditing"></param> void startKeyBindingEditing(ToggleGroup& groupEditing) { if (g_toggleGroupIdKeyBindingEditing == groupEditing.getId()) { return; } if (g_toggleGroupIdKeyBindingEditing >= 0) { endKeyBindingEditing(false, groupEditing); } g_toggleGroupIdKeyBindingEditing = groupEditing.getId(); } /// <summary> /// Function which marks the end of a shader editing cycle for a given toggle group /// </summary> /// <param name="acceptCollectedShaderHashes"></param> /// <param name="groupEditing"></param> void endShaderEditing(bool acceptCollectedShaderHashes, ToggleGroup& groupEditing) { if(acceptCollectedShaderHashes && g_toggleGroupIdShaderEditing == groupEditing.getId()) { groupEditing.storeCollectedHashes(g_pixelShaderManager.getMarkedShaderHashes(), g_vertexShaderManager.getMarkedShaderHashes()); g_pixelShaderManager.stopHuntingMode(); g_vertexShaderManager.stopHuntingMode(); } g_toggleGroupIdShaderEditing = -1; } /// <summary> /// Function which marks the start of a shader editing cycle for a given toggle group. /// </summary> /// <param name="groupEditing"></param> void startShaderEditing(ToggleGroup& groupEditing) { if(g_toggleGroupIdShaderEditing==groupEditing.getId()) { return; } if(g_toggleGroupIdShaderEditing >= 0) { endShaderEditing(false, groupEditing); } g_toggleGroupIdShaderEditing = groupEditing.getId(); g_activeCollectorFrameCounter = g_startValueFramecountCollectionPhase; g_pixelShaderManager.startHuntingMode(groupEditing.getPixelShaderHashes()); g_vertexShaderManager.startHuntingMode(groupEditing.getVertexShaderHashes()); // after copying them to the managers, we can now clear the group's shader. groupEditing.clearHashes(); } static void showHelpMarker(const char* desc) { ImGui::TextDisabled("(?)"); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(450.0f); ImGui::TextUnformatted(desc); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } } static void displaySettings(reshade::api::effect_runtime *runtime) { if (g_toggleGroupIdKeyBindingEditing >= 0) { // a keybinding is being edited. Read current pressed keys into the collector, cumulatively; g_keyCollector.collectKeysPressed(runtime); } if(ImGui::CollapsingHeader("General info and help")) { ImGui::PushTextWrapPos(); ImGui::TextUnformatted("The Shader Toggler allows you to create one or more groups with shaders to toggle on/off. You can assign a keyboard shortcut (including using keys like Shift, Alt and Control) to each group, including a handy name. Each group can have one or more vertex or pixel shaders assigned to it. When you press the assigned keyboard shortcut, any draw calls using these shaders will be disabled, effectively hiding the elements in the 3D scene."); ImGui::TextUnformatted("\nThe following (hardcoded) keyboard shortcuts are used when you click a group's 'Change Shaders' button:"); ImGui::TextUnformatted("* Numpad 1 and Numpad 2: previous/next pixel shader"); ImGui::TextUnformatted("* Ctrl + Numpad 1 and Ctrl + Numpad 2: previous/next marked pixel shader in the group"); ImGui::TextUnformatted("* Numpad 3: mark/unmark the current pixel shader as being part of the group"); ImGui::TextUnformatted("* Numpad 4 and Numpad 5: previous/next vertex shader"); ImGui::TextUnformatted("* Ctrl + Numpad 4 and Ctrl + Numpad 5: previous/next marked vertex shader in the group"); ImGui::TextUnformatted("* Numpad 6: mark/unmark the current vertex shader as being part of the group"); ImGui::TextUnformatted("\nWhen you step through the shaders, the current shader is disabled in the 3D scene so you can see if that's the shader you were looking for."); ImGui::TextUnformatted("When you're done, make sure you click 'Save all toggle groups' to preserve the groups you defined so next time you start your game they're loaded in and you can use them right away."); ImGui::PopTextWrapPos(); } ImGui::AlignTextToFramePadding(); if(ImGui::CollapsingHeader("Shader selection parameters", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::AlignTextToFramePadding(); ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); ImGui::SliderFloat("Overlay opacity", &g_overlayOpacity, 0.2f, 1.0f); ImGui::AlignTextToFramePadding(); ImGui::SliderInt("# of frames to collect", &g_startValueFramecountCollectionPhase, 10, 1000); ImGui::SameLine(); showHelpMarker("This is the number of frames the addon will collect active shaders. Set this to a high number if the shader you want to mark is only used occasionally. Only shaders that are used in the frames collected can be marked."); ImGui::PopItemWidth(); } ImGui::Separator(); if(ImGui::CollapsingHeader("List of Toggle Groups", ImGuiTreeNodeFlags_DefaultOpen)) { if(ImGui::Button(" New ")) { addDefaultGroup(); } ImGui::Separator(); std::vector<ToggleGroup> toRemove; for(auto& group : g_toggleGroups) { ImGui::PushID(group.getId()); ImGui::AlignTextToFramePadding(); if(ImGui::Button("X")) { toRemove.push_back(group); } ImGui::SameLine(); ImGui::Text(" %d ", group.getId()); ImGui::SameLine(); if(ImGui::Button("Edit")) { group.setEditing(true); } ImGui::SameLine(); if(g_toggleGroupIdShaderEditing>=0) { if(g_toggleGroupIdShaderEditing==group.getId()) { if(ImGui::Button(" Done ")) { endShaderEditing(true, group); } } else { ImGui::BeginDisabled(true); ImGui::Button(" "); ImGui::EndDisabled(); } } else { if(ImGui::Button("Change shaders")) { ImGui::SameLine(); startShaderEditing(group); } } ImGui::SameLine(); ImGui::Text(" %s (%s%s)", group.getName().c_str() , group.getToggleKeyAsString().c_str(), group.isActive() ? ", is active" : ""); if(group.isEditing()) { ImGui::Separator(); ImGui::Text("Edit group %d", group.getId()); // Name of group char tmpBuffer[150]; const string& name = group.getName(); strncpy_s(tmpBuffer, 150, name.c_str(), name.size()); ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.7f); ImGui::AlignTextToFramePadding(); ImGui::Text("Name"); ImGui::SameLine(ImGui::GetWindowWidth() * 0.2f); ImGui::InputText("##Name", tmpBuffer, 149); group.setName(tmpBuffer); ImGui::PopItemWidth(); // Key binding of group bool isKeyEditing = false; ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); ImGui::AlignTextToFramePadding(); ImGui::Text("Key shortcut"); ImGui::SameLine(ImGui::GetWindowWidth() * 0.2f); string textBoxContents = (g_toggleGroupIdKeyBindingEditing == group.getId()) ? g_keyCollector.getKeyAsString() : group.getToggleKeyAsString(); // The 'press a key' is inside keycollector string toggleKeyName = group.getToggleKeyAsString(); ImGui::InputText("##Key shortcut", (char*)textBoxContents.c_str(), textBoxContents.size(), ImGuiInputTextFlags_ReadOnly); if(ImGui::IsItemClicked()) { startKeyBindingEditing(group); } if(g_toggleGroupIdKeyBindingEditing==group.getId()) { isKeyEditing = true; ImGui::SameLine(); if (ImGui::Button("OK")) { endKeyBindingEditing(true, group); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { endKeyBindingEditing(false, group); } } ImGui::PopItemWidth(); if(!isKeyEditing) { if(ImGui::Button("OK")) { group.setEditing(false); g_toggleGroupIdKeyBindingEditing = -1; g_keyCollector.clear(); } } ImGui::Separator(); } ImGui::PopID(); } if(toRemove.size()>0) { // switch off keybinding editing or shader editing, if in progress g_toggleGroupIdKeyBindingEditing = -1; g_keyCollector.clear(); g_toggleGroupIdShaderEditing = -1; g_pixelShaderManager.stopHuntingMode(); g_vertexShaderManager.stopHuntingMode(); } for(const auto& group : toRemove) { std::erase(g_toggleGroups, group); } ImGui::Separator(); if(g_toggleGroups.size()>0) { if(ImGui::Button("Save all Toggle Groups")) { saveShaderTogglerIniFile(); } } } } BOOL APIENTRY DllMain(HMODULE hModule, DWORD fdwReason, LPVOID) { switch (fdwReason) { case DLL_PROCESS_ATTACH: if (!reshade::register_addon(hModule)) { return FALSE; } reshade::register_event<reshade::addon_event::init_pipeline>(onInitPipeline); reshade::register_event<reshade::addon_event::init_command_list>(onInitCommandList); reshade::register_event<reshade::addon_event::destroy_command_list>(onDestroyCommandList); reshade::register_event<reshade::addon_event::reset_command_list>(onResetCommandList); reshade::register_event<reshade::addon_event::destroy_pipeline>(onDestroyPipeline); reshade::register_event<reshade::addon_event::reshade_overlay>(onReshadeOverlay); reshade::register_event<reshade::addon_event::reshade_present>(onReshadePresent); reshade::register_event<reshade::addon_event::bind_pipeline>(onBindPipeline); reshade::register_event<reshade::addon_event::draw>(onDraw); reshade::register_event<reshade::addon_event::draw_indexed>(onDrawIndexed); reshade::register_event<reshade::addon_event::draw_or_dispatch_indirect>(onDrawOrDispatchIndirect); reshade::register_overlay(nullptr, &displaySettings); loadShaderTogglerIniFile(); break; case DLL_PROCESS_DETACH: reshade::unregister_event<reshade::addon_event::reshade_present>(onReshadePresent); reshade::unregister_event<reshade::addon_event::destroy_pipeline>(onDestroyPipeline); reshade::unregister_event<reshade::addon_event::init_pipeline>(onInitPipeline); reshade::unregister_event<reshade::addon_event::reshade_overlay>(onReshadeOverlay); reshade::unregister_event<reshade::addon_event::bind_pipeline>(onBindPipeline); reshade::unregister_event<reshade::addon_event::draw>(onDraw); reshade::unregister_event<reshade::addon_event::draw_indexed>(onDrawIndexed); reshade::unregister_event<reshade::addon_event::draw_or_dispatch_indirect>(onDrawOrDispatchIndirect); reshade::unregister_event<reshade::addon_event::init_command_list>(onInitCommandList); reshade::unregister_event<reshade::addon_event::destroy_command_list>(onDestroyCommandList); reshade::unregister_event<reshade::addon_event::reset_command_list>(onResetCommandList); reshade::unregister_overlay(nullptr, &displaySettings); reshade::unregister_addon(hModule); break; } return TRUE; }
34.836218
464
0.74463
[ "vector", "3d" ]
c07a5c72eca5aa3f55eb4541afc113b9287f0722
31,133
cpp
C++
final/scanner.cpp
AegirAexx/tsam
db59349f2e6acce5e75bd9ecedb3d0d1d5a1b664
[ "Unlicense" ]
null
null
null
final/scanner.cpp
AegirAexx/tsam
db59349f2e6acce5e75bd9ecedb3d0d1d5a1b664
[ "Unlicense" ]
null
null
null
final/scanner.cpp
AegirAexx/tsam
db59349f2e6acce5e75bd9ecedb3d0d1d5a1b664
[ "Unlicense" ]
null
null
null
// COM: dagur17@ru.is & aegir15@ru.is - Reykjavik University - 2019. // COM: UDP port scanner for T-409-TSAM Assignment 3 / Project 2. #include <iostream> #include <vector> #include <fstream> #include <regex> #include <thread> #include <chrono> #include <cerrno> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <netinet/ip_icmp.h> // TODO: ------------------------------------------------------ // FIXME: ------------------------------------------------------ // FEAT: ------------------------------------------------------ // DAGUR: ------------------------------------------------------ // HACK: ------------------------------------------------------ // COM: ------------------------------------------------------ // TODO: ROMOVE. FOR DEBUGING. void printByteArray(int bufferLength, char buffer[]){ for (int i {0}; i < bufferLength; ++i) { printf("%02X%s", (uint8_t)buffer[i], (i + 1)%16 ? " " : "\n"); } std::cout << std::endl; } // COM: Port datatypes. struct port { int portNumber; bool isReceived = false; void initialize (int portNumber) { this->portNumber = portNumber; } }; struct openPort { int portNumber; std::string message {0}; std::string payload {0}; std::string secretPhrase {0}; bool isEvil = false; bool isKnock = false; bool isSecret = false; bool isOracle = false; bool isPortfwd = false; bool isChecksum = false; bool isReceived = false; bool isLastStand = false; bool isFinalMessage = false; bool isMasterOfTheUniverse = false; //bool isFinalMessage = false; // FEAT: Add toggle() function for boolean? void initialize (int portNumber) { this->portNumber = portNumber; } }; struct pseudo_header { // FEAT: This is our data struct. Change name and make out own} // COM: Unsigned datatypes. u_int32_t source_address; u_int32_t dest_address; u_int8_t placeholder; u_int8_t protocol; u_int16_t udp_length; }; // COM: Functions prototypes. // TODO: LOOK FOR PARAMETERS NOT USED. REMOVE!!. void recvPacket(int portlow, int porthigh, std::string sourceAddress, bool &isSent, std::vector<port> &ports); void sendPacket(int portlow, int porthigh, std::string destinationAddress, std::string sourceAddress, bool &isSent); void sendToOpenPorts(std::string destinationAddress, std::string sourceAddress, bool &isSent, std::vector<openPort> &openPorts); void recvUDPPacket(std::string sourceAddress, bool &isSent, std::vector<openPort> &openPorts); unsigned short checksum(unsigned short *ptr, int nbytes); std::string getIP(); // TODO: LOOK INTO CLOSING SOCKETS ON SEND AND RECV! // FIXME: CLOSE SOCKET. // COM: Main program. int main(int argc, char* argv[]) { bool isVerbose {false}; // COM: Check user input arguments. if(argc != 4) { if(argc != 5) { std::cout << "Usage: ./scanner [destination IP] [port low] [port high]" << std::endl; exit(0); } if(argv[4] == "--verbose" || argv[4] == "-v") { isVerbose = true; } std::cout << "Usage: ./scanner [destination IP] [port low] [port high] --verbose" << std::endl; exit(0); } // PART: Part one: Port scanner. // COM: Part one: Port scanner. // COM: bool isSent {false}; // COM: IP addresses and port range. std::string sourceAddress(getIP()); std::string destinationAddress (argv[1]); int portLow {atoi(argv[2])}; int portHigh {atoi(argv[3])}; // COM: Validating port range. if(portLow > portHigh) { std::cout << "Enter the lower port before the higher port" << std::endl; std::cout << "Usage: ./scanner [source IP] [destination IP] [port low] [port high]" << std::endl; exit(0); } // COM: Datastructure to hold the initial batch of ports. std::vector<port> ports; // COM: Initialize each port with a portnumber. for(int i {portLow}; i <= portHigh; ++i) { port initPort; initPort.initialize(i); ports.push_back(initPort); } // COM: The first wave of threads. Make first contact. Recieve ICMP. std::thread sendThread (sendPacket, portLow, portHigh, destinationAddress, sourceAddress, std::ref(isSent)); std::thread recvThread (recvPacket, portLow, portHigh, sourceAddress, std::ref(isSent), std::ref(ports)); sendThread.join(); recvThread.join(); // COM: Part two: The open ports. // COM: // COM: Reset flag. isSent = false; // COM: Datastructure to hold the batch of open ports. std::vector<openPort> openPorts; // COM: Transfer relevant ports to new data structue. for(size_t i {0}; i < ports.size(); ++i) { if(ports[i].isReceived == false) { openPort openPort; openPort.initialize(ports[i].portNumber); openPorts.push_back(openPort); } } // for(size_t i {0}; i < openPorts.size(); ++i) { // std::cout << "Open Port is# " << openPorts[i].portNumber << std::endl; // DEBUG: // std::cout << "message " << openPorts[i].message << std::endl; // DEBUG: // std::cout << "payload " << openPorts[i].payload << std::endl; // DEBUG: // } // PART: Part two: Initial contact with open ports. Update payload for Portfwd // COM: The second wave of threads. Recieve UDP. Only go if there are any open ports. if(openPorts.size() > 0) { std::thread sendOpenThread (sendToOpenPorts, destinationAddress, sourceAddress, std::ref(isSent), std::ref(openPorts)); std::thread recvUDPPacketThread (recvUDPPacket, sourceAddress, std::ref(isSent), std::ref(openPorts)); sendOpenThread.join(); recvUDPPacketThread.join(); } else { std::cout << "All ports seem to be closed, " + destinationAddress + " maybe down, try again later." << std::endl; exit(0); } // PART: Part three: Deliver and update paylod from Evilbit and Checksum. // COM: Part Three: The port interaction. // COM: std::string oraclePayload(""); int oracleIndex; std::string secretPhrase; isSent = false; //Setja false a alla i open ports for(size_t i {0}; i < openPorts.size(); ++i) { openPorts[i].isReceived = false; // FEAT: A toggle function would be awesome. } //sendum aftur a alla nema nu vitum vid hver er evil og cumsom os.frv. og sendum eftir tvi std::thread sendThread2 (sendToOpenPorts, destinationAddress, sourceAddress, std::ref(isSent), std::ref(openPorts)); std::thread recvUDPPacketThread2 (recvUDPPacket, sourceAddress, std::ref(isSent), std::ref(openPorts)); recvUDPPacketThread2.join(); sendThread2.join(); // PART: Part four: Set up to send correct ports to Oracle. for(size_t i {0}; i < openPorts.size(); ++i) { std::cout << "Open Port is# " << openPorts[i].portNumber << std::endl; // DEBUG: std::cout << "message " << openPorts[i].message << std::endl; // DEBUG: std::cout << "payload " << openPorts[i].payload << std::endl; // DEBUG: } // fara i gegnum oll portin og gera videigandi adgerdir vid evil, cumsuum o.s.frv for(size_t i {0}; i < openPorts.size(); ++i) { if(openPorts[i].isEvil) { // COM: Setting up a RegEx search. std::string evil(openPorts[i].message); std::smatch match; std::regex expression("[0-9]"); std::string tempStr; // COM: Create the new string. while(std::regex_search (evil, match, expression)) { for(auto x : match) { tempStr.append(x); } evil = match.suffix().str(); } oraclePayload += tempStr + ","; std::cout << "Tempstr ******************8: " << tempStr << std::endl; // DEBUG: } else if (openPorts[i].isPortfwd) { oraclePayload += openPorts[i].payload + ","; std::cout << "PortMongo ***************8: " << openPorts[i].payload << std::endl; // DEBUG: } else if (openPorts[i].isChecksum) { // COM: Setting up a RegEx search. std::string check(openPorts[i].message); std::smatch match; std::regex expression("\"(.*?)\""); std::string tempStr; std::cout << "openPorts[i].message :" << openPorts[i].message << std::endl; // DEBUG: // COM: Create the new string. // while(std::regex_search (check, match, expression)) { // for(auto x : match) { // tempStr += x; // } // check = match.suffix().str(); // } if(std::regex_search (check, match, expression)) { tempStr = match.str(1); } std::cout << "tempStr :" << tempStr << std::endl; // DEBUG: // COM: We have the secret Phrase. secretPhrase.append(tempStr); } else if (openPorts[i].isOracle){ oracleIndex = i; } } //Laga kommu oraclePayload.erase(oraclePayload.size() - 1, oraclePayload.size() - 1); std::cout << "oracleIndex " << oracleIndex << std::endl; // DEBUG: std::cout << "oraclePayload " << oraclePayload << std::endl; // DEBUG: std::cout << "secretPhrase " << secretPhrase << std::endl; // DEBUG: //hlada openPorts[oracleIndex].payload = oraclePayload; openPorts[oracleIndex].isLastStand = true; openPorts[oracleIndex].isReceived = false; // DAGUR: senda a oracle og receive-a skilabodin tilbaka og geyma i payload //setjum false tvi vid aetlum ad senda a alla isSent = false; //Herna er oracle ad fa payload og message i oracle aetti ad vera knock knock rodin eftir thetta std::thread sendToOracleThread (sendToOpenPorts, destinationAddress, sourceAddress, std::ref(isSent), std::ref(openPorts)); std::thread recvFromOracleThread (recvUDPPacket, sourceAddress, std::ref(isSent), std::ref(openPorts)); sendToOracleThread.join(); recvFromOracleThread.join(); // PART: Part five: Set up & send on correct ports according to the Oracle. // DAGUR: bua til vector af opnum portum med portunum sem vid faum ur message std::vector<openPort> lastMessage; std::cout << "Knock knock rod: " << openPorts[oracleIndex].message << std::endl; // DEBUG: //Vinna ur knock knock rod std::string knockKnock(openPorts[oracleIndex].message); std::smatch match; std::regex expression("[4][0-9][0-9][0-9]"); std::string tempStr; std::sregex_iterator currentMatch(knockKnock.begin(), knockKnock.end(), expression); // Used to determine if there are any more matches std::sregex_iterator lastMatch; // While the current match doesn't equal the last while(currentMatch != lastMatch){ std::smatch match = *currentMatch; std::cout << match.str() << std::endl; // DEBUG: //std::string port(match.str()); openPort openPort; openPort.initialize(atoi(match.str().c_str())); //openPort.isFinalMessage = true; lastMessage.push_back(openPort); currentMatch++; } std::cout << std::endl; // DAGUR: oracle[oracleIndex].message segir okkur rodina push back a lastMessage vectorinn for(size_t i {0}; i < lastMessage.size(); ++i) { if(i == lastMessage.size() - 1) { lastMessage[i].isReceived = false; lastMessage[i].secretPhrase = secretPhrase; lastMessage[i].isSecret = true; lastMessage[i].isMasterOfTheUniverse = true; } else { lastMessage[i].isReceived = false; lastMessage[i].isKnock = true; } } // DAGUR: loop-a i gegn og setja isKnock flaggann a hja ollum nema sidast // DAGUR: setja isSecret flaggan a sidasta // DAGUR: geyma secret phrase i secretphrase breytunni sem fer a openPorts struct-id // DAGUR: sendum svo a allt i rettri rod knock knock og svo secret phrase og svo receive a thad og tha er allt komid isSent = false; std::thread sendLast (sendToOpenPorts, destinationAddress, sourceAddress, std::ref(isSent), std::ref(lastMessage)); std::thread recvLast (recvUDPPacket, sourceAddress, std::ref(isSent), std::ref(lastMessage)); sendLast.join(); recvLast.join(); for(size_t i {0}; i < lastMessage.size(); ++i) { if(lastMessage[i].isMasterOfTheUniverse) { std::cout << "Final message " << lastMessage[i].message << std::endl; // DEBUG: } } // TODO: // FIXME: return 0; } // COM: The Main receiver function. Accepts ICMP packets. void recvPacket(int portlow, int porthigh, std::string sourceAddress, bool &isSent, std::vector<port> &ports) { int recvSocket {0}; int received {-1}; unsigned int received_len {0}; int bound {0}; char buffer[1024] {0}; while (!isSent) { // COM: Initializing the socket structure. sockaddr_in socketAddress; socketAddress.sin_family = AF_INET; socketAddress.sin_port = htons(50000); inet_pton(AF_INET, sourceAddress.c_str(), &socketAddress.sin_addr); // COM: Initializing socket. recvSocket = socket( AF_INET, SOCK_RAW, IPPROTO_ICMP ); if(recvSocket < 0){ std::perror("### Create socket failed"); } // COM: Binding the socket to IP address og port. bound = bind( recvSocket, (struct sockaddr *) &socketAddress, sizeof(struct sockaddr_in) ); if(bound < 0){ std::perror("### Failed to bind"); } // COM: Initializing a timeout period. struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; // COM: Customizing socket options. Set timeout. int setSockOpt = setsockopt( recvSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout) ); if(setSockOpt < 0){ std::perror("### Failed to set sock opt"); } // COM: Atempting to received ICMP packets. received = recvfrom( recvSocket, buffer, 1024, 0, (struct sockaddr *) &socketAddress, &received_len ); // COM: If there is any data recieved, we look at the raw buffer. if(received > 0) { short * portPtr; int currentPort = htons(*portPtr); int index = currentPort - portlow; unsigned char *ICMPcode; // COM: The port number from sender. portPtr = (short *)&buffer[50]; // COM: ICMP code ID. ICMPcode = (unsigned char*) &buffer[21]; // COM: Making the data usable with bit shifting and masking. int code = ((htons(*ICMPcode) >> 8) & 0xffff); // COM: Toggling the received flag. if (code == 3 && !ports[index].isReceived) { ports[index].isReceived = true; std::cout << "ICMP message code is " << code << ". " << "Port #" << currentPort << " is closed." << std::endl; // DEBUG: } } // COM: Clearing buffer and recevied data flag. memset(buffer, 0, 1024); received = -1; } } // TODO: ROMOVE THE WHOLE CUSTOM FEATURE?? NEEDS SOME OVERHAUL. void sendPacket(int portlow, int porthigh, std::string destinationAddress, std::string sourceAddress, bool &isSent) { int sendSocket {0}; std::string data = "ping"; for(int port {portlow}; port <= porthigh; ++port) { sockaddr_in socketAddress; socketAddress.sin_family = AF_INET; socketAddress.sin_port = htons(port); inet_pton(AF_INET, destinationAddress.c_str(), &socketAddress.sin_addr); sendSocket = socket( AF_INET, SOCK_RAW, IPPROTO_RAW ); if(sendSocket < 0){ std::perror("### Create UDP_socket failed"); } //setsockopt // int val = 1; // int sockoption = setsockopt(sendSocket, IPPROTO_IP, IP_HDRINCL, &val, sizeof(val)); // if(sockoption < 0) { // perror("setsockopt HDRINCL_IP failed"); // exit(0); // } // ***** create header **** // COM: Datagram buffer and pointer. char datagram[4096] {0}; char *pseudogram; // COM: IP, UDP and Pseudo header structures. struct iphdr *iph = (struct iphdr *) datagram; struct udphdr *udph = (struct udphdr *) (datagram + sizeof (struct iphdr)); struct pseudo_header psh; // DAGUR: data sett aftan vid udp header data = datagram + sizeof(struct iphdr) + sizeof (struct udphdr); // COM: Fill in the IP Header iph->ihl = 5; iph->version = 4; iph->tos = 0; iph->tot_len = sizeof (struct iphdr) + sizeof (struct udphdr) + strlen(data.c_str()); iph->id = htonl (54321); //Id of this packet - DOES NOT SEEM TO MATTER WHAT VALUE IS HERE. DYNAMIC??? iph->frag_off = 0;//htons(0x8000); // EVILBIT GAURINN!!! SENDA SEM BIG-ENDIAN htons() 0x8000 > 0x00 0x80 (|=) iph->ttl = 255; iph->protocol = IPPROTO_UDP; // WHAT IS THE POINT OF THE SAME THING IN socket() ABOVE????? iph->check = 0; //Set to 0 before calculating checksum iph->saddr = inet_addr (sourceAddress.c_str()); //Spoof the source ip address iph->daddr = socketAddress.sin_addr.s_addr; // IP checksum iph->check = checksum ((unsigned short *) datagram, iph->tot_len); // UDP header udph->source = htons (50000); //nota svarið frá Servernum til að búa til þetta, source portið verður destination port og öfugt udph->dest = htons (port); udph->len = htons(8 + data.size()); //tcp header size udph->check = 0; //leave checksum 0 now, filled later by pseudo header // Now the UDP checksum using the pseudo header psh.source_address = inet_addr(sourceAddress.c_str()); psh.dest_address = socketAddress.sin_addr.s_addr; psh.placeholder = 0; psh.protocol = IPPROTO_UDP; psh.udp_length = htons(sizeof(struct udphdr) + data.size() ); int psize = sizeof(struct pseudo_header) + sizeof(struct udphdr) + data.size(); //muna ad gera free pseudogram = (char*) malloc(psize); //pusla saman pseudoheader + UDP heade + data memcpy(pseudogram , (char*) &psh , sizeof (struct pseudo_header)); memcpy(pseudogram + sizeof(struct pseudo_header) , udph , sizeof(struct udphdr) + data.size()); //Reikna ut UDP checksum udph->check = checksum((unsigned short*) pseudogram , psize); //send message for(int i {0}; i < 5; ++i) { sendto( sendSocket, datagram, iph->tot_len, MSG_CONFIRM, (const struct sockaddr *) &socketAddress, sizeof(socketAddress) ); std::this_thread::sleep_for(std::chrono::milliseconds(500)); } free(pseudogram); } isSent = true; } // FIXME: Add comments?? How it works? Where it came from?? unsigned short checksum(unsigned short *ptr, int bytes) { long sum {0}; unsigned short oddbyte; short answer; while(bytes > 1) { sum += *ptr++; bytes -= 2; } if(bytes == 1) { oddbyte = 0; *((u_char*) &oddbyte) = *(u_char*) ptr; sum += oddbyte; } sum = (sum >> 16) + (sum & 0xffff); sum = sum + (sum >> 16); answer = (short) ~sum; return(answer); } // TODO: NEEDS COMMENTS AND SMALL TWEAKS. void sendToOpenPorts(std::string destinationAddress, std::string sourceAddress, bool &isSent, std::vector<openPort> &openPorts) { int sendSocket {0}; char *data; for(size_t port {0}; port < openPorts.size(); ++port) { sockaddr_in socketAddress; socketAddress.sin_family = AF_INET; socketAddress.sin_port = htons(port); inet_pton(AF_INET, destinationAddress.c_str(), &socketAddress.sin_addr); sendSocket = socket( AF_INET, SOCK_RAW, IPPROTO_RAW ); if(sendSocket < 0){ std::perror("### Create UDP_socket failed"); } int val = 1; int sockoption = setsockopt(sendSocket, IPPROTO_IP, IP_HDRINCL, &val, sizeof(val)); if(sockoption < 0) { std::perror("### setsockopt() failed"); exit(0); } char datagram[4096] {0}; char *pseudogram; struct iphdr *iph = (struct iphdr *) datagram; struct udphdr *udph = (struct udphdr *) (datagram + sizeof (struct iphdr)); struct pseudo_header psh; data = datagram + sizeof(struct iphdr) + sizeof (struct udphdr); if(openPorts[port].isLastStand) { // Ef thetta er oracle payload strcpy(data, openPorts[port].payload.c_str()); } else if (openPorts[port].isKnock) { strcpy(data, "knock\n"); std::cout << data; std::cout << "Knocking on port # " << openPorts[port].portNumber << " index " << port << std::endl; } else if (openPorts[port].isSecret) { strcpy(data, openPorts[port].secretPhrase.c_str()); std::cout << data; std::cout << "Sending secret to port # " << openPorts[port].portNumber << " index " << port << std::endl; } else { strcpy(data, "aa"); } iph->ihl = 5; iph->version = 4; iph->tos = 0; iph->tot_len = sizeof (struct iphdr) + sizeof (struct udphdr) + strlen(data); iph->id = htonl (54321); if(openPorts[port].isEvil) { iph->frag_off |= htons(0x8000); } else { iph->frag_off = 0; } iph->ttl = 255; iph->protocol = IPPROTO_UDP; iph->check = 0; iph->saddr = inet_addr (sourceAddress.c_str()); iph->daddr = socketAddress.sin_addr.s_addr; iph->check = checksum ((unsigned short *) datagram, iph->tot_len); udph->source = htons (50000); udph->dest = htons (openPorts[port].portNumber); udph->len = htons(8 + strlen(data)); udph->check = 0; psh.source_address = inet_addr(sourceAddress.c_str()); psh.dest_address = socketAddress.sin_addr.s_addr; psh.placeholder = 0; psh.protocol = IPPROTO_UDP; psh.udp_length = htons(sizeof(struct udphdr) + strlen(data)); if(openPorts[port].isChecksum) { int psize = sizeof(struct pseudo_header) + sizeof(struct udphdr); pseudogram = (char*) malloc(psize); // COM: Create Pseudo header + UDP header + data structure in memory. memcpy( pseudogram, (char*) &psh, sizeof (struct pseudo_header) ); memcpy( pseudogram + sizeof(struct pseudo_header), udph, sizeof(struct udphdr) ); // COM: Calculate the UDP checksum. // COM: Get the invert of checksum without the data. short checksumUDP = ~(checksum((unsigned short*) pseudogram , psize)); // COM: Invert of of the value gathered from one of the ports. // TODO: ADD DYNAMICALLY GATHERED CHECKSUM VALUE. unsigned short target = 0x0ff2; // HACK: // COM: checksum should be udph->check = htons(0xf00d); // HACK: // COM: Calculate what the unknown data. short d = htons(target) - checksumUDP; // COM: The data bytes are set to what need to be so checksum adds up. u_char one = d; u_char two = (d >> 8); // COM: The data then gets injected. data[0] = one; data[1] = two; } else { int psize = sizeof(struct pseudo_header) + sizeof(struct udphdr) + strlen(data); pseudogram = (char*) malloc(psize); memcpy( pseudogram, (char*) &psh, sizeof (struct pseudo_header) ); memcpy( pseudogram + sizeof(struct pseudo_header), udph, sizeof(struct udphdr) + strlen(data) ); udph->check = checksum((unsigned short*) pseudogram , psize); } // COM: Packet getting sent. for(int i {0}; i < 3; ++i) { sendto( sendSocket, datagram, iph->tot_len, MSG_CONFIRM, (const struct sockaddr *) &socketAddress, sizeof(socketAddress) ); std::this_thread::sleep_for(std::chrono::milliseconds(250)); } free(pseudogram); } isSent = true; } // TODO: FINISH UP. NEEDS COMMENTS AND REFACTOR/TWEAKS. void recvUDPPacket(std::string sourceAddress, bool &isSent, std::vector<openPort> &openPorts) { int recvSocket {0}; int received {-1}; unsigned int received_len {0}; int bound {0}; char buffer[1024] {0}; char *data; while (!isSent) { sockaddr_in socketAddress; socketAddress.sin_family = AF_INET; socketAddress.sin_port = htons(50000); inet_pton(AF_INET, sourceAddress.c_str(), &socketAddress.sin_addr); recvSocket = socket( AF_INET, SOCK_RAW, IPPROTO_UDP ); if(recvSocket < 0){ std::perror("### Create socket failed"); } bound = bind( recvSocket, (struct sockaddr *) &socketAddress, sizeof(struct sockaddr_in) ); if(bound < 0){ std::perror("### Failed to bind"); } struct timeval timeout; timeout.tv_sec = 2; timeout.tv_usec = 0; int setSockOpt = setsockopt(recvSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); if(setSockOpt < 0){ std::perror("### Failed to set sock opt"); } received = recvfrom( recvSocket, buffer, 1024, 0, (struct sockaddr *) &socketAddress, &received_len ); if(received > 0) { short * portPtr; portPtr = (short *)&buffer[20]; int sourcePort = htons(*portPtr); //convert-a data partinum i streng data = buffer + sizeof(struct iphdr) + sizeof (struct udphdr); // finna rett stak i vektornum int index; for(size_t i {0}; i < openPorts.size(); ++i) { if(openPorts[i].portNumber == sourcePort) { index = i; } } if (openPorts[index].isReceived == false) { openPorts[index].isReceived = true; openPorts[index].message = data; //std::cout << "Message from port no# " << std::dec << sourcePort << " is: " << std::endl; //std::cout << data << std::endl; } //Herna finnum vid ut hver er hvad, isEvil, isOracle, isPortMongo, isChecksum if(!openPorts[index].isEvil && !openPorts[index].isOracle && !openPorts[index].isPortfwd && !openPorts[index].isChecksum) { std::string str1(data), ret; //Check if number std::smatch match2; std::regex exp2("[0-9]"); std::string retStr2; while (std::regex_search (str1,match2,exp2)) { for (auto x1:match2) retStr2 += x1; str1 = match2.suffix().str(); } if(retStr2.size() > 0) { if(atoi(retStr2.c_str()) > 4100) { // //geri checksum openPorts[index].isChecksum = true; std::cout << "Checksum set as true on port #: " << openPorts[index].portNumber << std::endl; std::cout << retStr2 << std::endl; openPorts[index].payload = retStr2; } else { //geri port openPorts[index].isPortfwd = true; openPorts[index].payload = retStr2; std::cout << "Portfwd set as true on port #: " << openPorts[index].portNumber << std::endl; std::cout << str1 << std::endl; std::cout << "Payload: "<< openPorts[index].payload << std::endl; } } else { //Check if evil or oracle std::smatch match; std::regex exp("evil"); std::string retStr; while (std::regex_search (str1,match,exp)) { for (auto x1:match) retStr += x1; str1 = match.suffix().str(); } if(retStr.size() > 0) { //er evil openPorts[index].isEvil = true; std::cout << "Evil set as true on port #: " << openPorts[index].portNumber << std::endl; std::cout << str1 << std::endl; } else { openPorts[index].isOracle = true; std::cout << "Oracle set as true on port #: " << openPorts[index].portNumber << std::endl; std::cout << str1 << std::endl; } } if(openPorts[index].isFinalMessage && openPorts[index].isMasterOfTheUniverse) { openPorts[index].message = data; std::cout << "MasterOfTheUniverse set as true on port #: " << openPorts[index].portNumber << std::endl; } } } memset(buffer, 0, 1024); received = -1; } } // COM: Simple function that asks the system for the host IP. Linux and BSD only. std::string getIP() { std::string ipNumber; std::ifstream syscall; std::vector<std::string> ipNumbers; system("hostname -I | cut -d \" \" -f 1 > ddc4960d35d7a58843cdaf6cbec393b9"); syscall.open("ddc4960d35d7a58843cdaf6cbec393b9"); while (std::getline(syscall, ipNumber)){ ipNumbers.push_back(ipNumber); } syscall.close(); system("rm ddc4960d35d7a58843cdaf6cbec393b9"); return ipNumbers.at(0); }
34.249725
136
0.550959
[ "vector" ]
c07c3b653d7a1ef90702840bbad5fae4e8047853
8,949
cpp
C++
extensions/azure/processors/PutAzureDataLakeStorage.cpp
hunyadi-dev/nifi-minifi-cpp
5b72bddfd04da510cd4cfaa1734e021732dfe03e
[ "Apache-2.0", "OpenSSL" ]
null
null
null
extensions/azure/processors/PutAzureDataLakeStorage.cpp
hunyadi-dev/nifi-minifi-cpp
5b72bddfd04da510cd4cfaa1734e021732dfe03e
[ "Apache-2.0", "OpenSSL" ]
null
null
null
extensions/azure/processors/PutAzureDataLakeStorage.cpp
hunyadi-dev/nifi-minifi-cpp
5b72bddfd04da510cd4cfaa1734e021732dfe03e
[ "Apache-2.0", "OpenSSL" ]
null
null
null
/** * @file PutAzureDataLakeStorage.cpp * PutAzureDataLakeStorage class implementation * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PutAzureDataLakeStorage.h" #include "utils/ProcessorConfigUtils.h" #include "utils/gsl.h" #include "controllerservices/AzureStorageCredentialsService.h" #include "core/Resource.h" namespace org::apache::nifi::minifi::azure::processors { const core::Property PutAzureDataLakeStorage::FilesystemName( core::PropertyBuilder::createProperty("Filesystem Name") ->withDescription("Name of the Azure Storage File System. It is assumed to be already existing.") ->supportsExpressionLanguage(true) ->isRequired(true) ->build()); const core::Property PutAzureDataLakeStorage::DirectoryName( core::PropertyBuilder::createProperty("Directory Name") ->withDescription("Name of the Azure Storage Directory. The Directory Name cannot contain a leading '/'. " "If left empty it designates the root directory. The directory will be created if not already existing.") ->supportsExpressionLanguage(true) ->build()); const core::Property PutAzureDataLakeStorage::FileName( core::PropertyBuilder::createProperty("File Name") ->withDescription("The filename to be uploaded. If left empty the filename attribute will be used by default.") ->supportsExpressionLanguage(true) ->build()); const core::Property PutAzureDataLakeStorage::ConflictResolutionStrategy( core::PropertyBuilder::createProperty("Conflict Resolution Strategy") ->withDescription("Indicates what should happen when a file with the same name already exists in the output directory.") ->isRequired(true) ->withDefaultValue<std::string>(toString(FileExistsResolutionStrategy::FAIL_FLOW)) ->withAllowableValues<std::string>(FileExistsResolutionStrategy::values()) ->build()); const core::Relationship PutAzureDataLakeStorage::Success("success", "Files that have been successfully written to Azure storage are transferred to this relationship"); const core::Relationship PutAzureDataLakeStorage::Failure("failure", "Files that could not be written to Azure storage for some reason are transferred to this relationship"); void PutAzureDataLakeStorage::initialize() { // Set the supported properties setSupportedProperties({ AzureStorageCredentialsService, FilesystemName, DirectoryName, FileName, ConflictResolutionStrategy }); // Set the supported relationships setSupportedRelationships({ Success, Failure }); } void PutAzureDataLakeStorage::onSchedule(const std::shared_ptr<core::ProcessContext>& context, const std::shared_ptr<core::ProcessSessionFactory>& /*sessionFactory*/) { std::optional<storage::AzureStorageCredentials> credentials; std::tie(std::ignore, credentials) = getCredentialsFromControllerService(context); if (!credentials) { throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Azure Storage Credentials Service property missing or invalid"); } if (!credentials->isValid()) { throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Azure Storage Credentials Service properties are not set or invalid"); } credentials_ = *credentials; conflict_resolution_strategy_ = FileExistsResolutionStrategy::parse( utils::parsePropertyWithAllowableValuesOrThrow(*context, ConflictResolutionStrategy.getName(), FileExistsResolutionStrategy::values()).c_str()); } std::optional<storage::PutAzureDataLakeStorageParameters> PutAzureDataLakeStorage::buildUploadParameters( const std::shared_ptr<core::ProcessContext>& context, const std::shared_ptr<core::FlowFile>& flow_file) { storage::PutAzureDataLakeStorageParameters params; params.credentials = credentials_; params.replace_file = conflict_resolution_strategy_ == FileExistsResolutionStrategy::REPLACE_FILE; if (!context->getProperty(FilesystemName, params.file_system_name, flow_file) || params.file_system_name.empty()) { logger_->log_error("Filesystem Name '%s' is invalid or empty!", params.file_system_name); return std::nullopt; } context->getProperty(DirectoryName, params.directory_name, flow_file); context->getProperty(FileName, params.filename, flow_file); if (params.filename.empty() && (!flow_file->getAttribute("filename", params.filename) || params.filename.empty())) { logger_->log_error("No File Name is set and default object key 'filename' attribute could not be found!"); return std::nullopt; } return params; } void PutAzureDataLakeStorage::onTrigger(const std::shared_ptr<core::ProcessContext>& context, const std::shared_ptr<core::ProcessSession>& session) { logger_->log_trace("PutAzureDataLakeStorage onTrigger"); std::shared_ptr<core::FlowFile> flow_file = session->get(); if (!flow_file) { context->yield(); return; } const auto params = buildUploadParameters(context, flow_file); if (!params) { session->transfer(flow_file, Failure); return; } storage::UploadDataLakeStorageResult result; { // TODO(lordgamez): This can be removed after maximum allowed threads are implemented. See https://issues.apache.org/jira/browse/MINIFICPP-1566 std::lock_guard<std::mutex> lock(azure_storage_mutex_); PutAzureDataLakeStorage::ReadCallback callback(flow_file->getSize(), azure_data_lake_storage_, *params, logger_); session->read(flow_file, &callback); result = callback.getResult(); } if (result.result_code == storage::UploadResultCode::FILE_ALREADY_EXISTS) { gsl_Expects(conflict_resolution_strategy_ != FileExistsResolutionStrategy::REPLACE_FILE); if (conflict_resolution_strategy_ == FileExistsResolutionStrategy::FAIL_FLOW) { logger_->log_error("Failed to upload file '%s/%s' to filesystem '%s' on Azure Data Lake storage because file already exists", params->directory_name, params->filename, params->file_system_name); session->transfer(flow_file, Failure); return; } else if (conflict_resolution_strategy_ == FileExistsResolutionStrategy::IGNORE_REQUEST) { logger_->log_debug("Upload of file '%s/%s' was ignored because it already exits in filesystem '%s' on Azure Data Lake Storage", params->directory_name, params->filename, params->file_system_name); session->transfer(flow_file, Success); return; } } else if (result.result_code == storage::UploadResultCode::FAILURE) { logger_->log_error("Failed to upload file '%s/%s' to filesystem '%s' on Azure Data Lake storage", params->directory_name, params->filename, params->file_system_name); session->transfer(flow_file, Failure); } else { session->putAttribute(flow_file, "azure.filesystem", params->file_system_name); session->putAttribute(flow_file, "azure.directory", params->directory_name); session->putAttribute(flow_file, "azure.filename", params->filename); session->putAttribute(flow_file, "azure.primaryUri", result.primary_uri); session->putAttribute(flow_file, "azure.length", std::to_string(flow_file->getSize())); logger_->log_debug("Successfully uploaded file '%s/%s' to filesystem '%s' on Azure Data Lake storage", params->directory_name, params->filename, params->file_system_name); session->transfer(flow_file, Success); } } PutAzureDataLakeStorage::ReadCallback::ReadCallback( uint64_t flow_size, storage::AzureDataLakeStorage& azure_data_lake_storage, const storage::PutAzureDataLakeStorageParameters& params, std::shared_ptr<logging::Logger> logger) : flow_size_(flow_size), azure_data_lake_storage_(azure_data_lake_storage), params_(params), logger_(std::move(logger)) { } int64_t PutAzureDataLakeStorage::ReadCallback::process(const std::shared_ptr<io::BaseStream>& stream) { std::vector<uint8_t> buffer; size_t read_ret = stream->read(buffer, flow_size_); if (io::isError(read_ret) || read_ret != flow_size_) { return -1; } result_ = azure_data_lake_storage_.uploadFile(params_, gsl::make_span(buffer.data(), flow_size_)); return read_ret; } REGISTER_RESOURCE(PutAzureDataLakeStorage, "Puts content into an Azure Data Lake Storage Gen 2"); } // namespace org::apache::nifi::minifi::azure::processors
48.372973
180
0.75595
[ "object", "vector" ]
c080ecc1313976007a1f359d98eccb8d0705015f
3,359
cpp
C++
solutions/LeetCode/C++/284.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/284.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/284.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission // Below is the interface for Iterator, which is already defined for you. // **DO NOT** modify the interface for Iterator. #insert <stack> using namespace std; class Iterator { struct Data; Data* data; public: Iterator(const vector<int>& nums); Iterator(const Iterator& iter); virtual ~Iterator(); // Returns the next element in the iteration. int next(); // Returns true if the iteration has more elements. bool hasNext() const; }; class PeekingIterator : public Iterator { private: stack <int> mVals; public: PeekingIterator(const vector<int>& nums) : Iterator(nums) { // Initialize any member here. // **DO NOT** save a copy of nums and manipulate it directly. // You should only use the Iterator interface methods. } // Returns the next element in the iteration without advancing the iterator. int peek() { if(mVals.empty()){ int val = Iterator::next(); mVals.push(val); return val; } else return mVals.top(); } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { if(mVals.empty()){ return Iterator::next(); } else { int val = mVals.top(); mVals.pop(); return val; } } bool hasNext() const { return (mVals.empty()) ? Iterator::hasNext() : true; } }; __________________________________________________________________________________________________ sample 9716 kb submission // Below is the interface for Iterator, which is already defined for you. // **DO NOT** modify the interface for Iterator. class Iterator { struct Data; Data* data; public: Iterator(const vector<int>& nums); Iterator(const Iterator& iter); virtual ~Iterator(); // Returns the next element in the iteration. int next(); // Returns true if the iteration has more elements. bool hasNext() const; }; class PeekingIterator : public Iterator { public: int current = 0; bool hasnext = true; PeekingIterator(const vector<int>& nums) : Iterator(nums) { // Initialize any member here. // **DO NOT** save a copy of nums and manipulate it directly. // You should only use the Iterator interface methods. if(Iterator::hasNext()) { current = Iterator::next(); hasnext = true; } else hasnext = false; } // Returns the next element in the iteration without advancing the iterator. int peek() { if(!hasnext) return -1; else return current; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { int temp = current; if(Iterator::hasNext()) current = Iterator::next(); else hasnext = false; return temp; } bool hasNext() const { return hasnext; } }; __________________________________________________________________________________________________
25.641221
98
0.617148
[ "vector" ]
c08bd55976a2240fdb92d34f64626bd615d2250d
2,596
cpp
C++
snippets/cpp/VS_Snippets_Winforms/GetData2/CPP/getdata2.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/GetData2/CPP/getdata2.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/GetData2/CPP/getdata2.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
#using <System.dll> #using <System.Drawing.dll> #using <System.Windows.Forms.dll> #using <System.Data.dll> using namespace System; using namespace System::Drawing; using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Windows::Forms; using namespace System::Data; /// <summary> /// Summary description for Form1. /// </summary> public ref class Form1: public System::Windows::Forms::Form { private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container^ components; public: Form1() { components = nullptr; // // Required for Windows Form Designer support // InitializeComponent(); GetData2(); // // TODO: Add any constructor code after InitializeComponent call // } public: ~Form1() { if ( components != nullptr ) { delete components; } } private: /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent() { // // Form1 // this->ClientSize = System::Drawing::Size( 292, 276 ); this->Name = "Form1"; this->Text = "Form1"; this->Load += gcnew System::EventHandler( this, &Form1::Form1_Load ); } // <snippet1> private: void GetData2() { // Creates a component. Component^ myComponent = gcnew Component; // Creates a data object, and assigns it the component. DataObject^ myDataObject = gcnew DataObject( myComponent ); // Creates a type, myType, to store the type of data. Type^ myType = myComponent->GetType(); // Retrieves the data using myType to represent its type. Object^ myObject = myDataObject->GetData( myType ); if ( myObject != nullptr ) MessageBox::Show( "The data type stored in the data object is " + myObject->GetType()->Name + "." ); else MessageBox::Show( "Data of the specified type was not stored in the data object." ); } // </snippet1> void Form1_Load( Object^ /*sender*/, System::EventArgs^ /*e*/ ){} }; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] int main() { Application::Run( gcnew Form1 ); } /* * Output: * Parameter args for method ParamArrayAndDesc has a description attribute. * The description is: "This argument is a ParamArray" * Parameter args for method ParamArrayAndDesc has the ParamArray attribute. */
23.6
96
0.629815
[ "object" ]
c08da97823a43adaf3fe77de41315e870e29ab5f
3,928
hpp
C++
include/VROSC/PatchData.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/VROSC/PatchData.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/VROSC/PatchData.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.ScriptableObject #include "UnityEngine/ScriptableObject.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Type namespace: VROSC namespace VROSC { // Forward declaring type: PatchData class PatchData; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::PatchData); DEFINE_IL2CPP_ARG_TYPE(::VROSC::PatchData*, "VROSC", "PatchData"); // Type namespace: VROSC namespace VROSC { // Size: 0x24 #pragma pack(push, 1) // Autogenerated type: VROSC.PatchData // [TokenAttribute] Offset: FFFFFFFF // [CreateAssetMenuAttribute] Offset: 77F670 class PatchData : public ::UnityEngine::ScriptableObject { public: public: // private System.String _displayName // Size: 0x8 // Offset: 0x18 ::StringW displayName; // Field size check static_assert(sizeof(::StringW) == 0x8); // private System.Int32 _helmChannel // Size: 0x4 // Offset: 0x20 int helmChannel; // Field size check static_assert(sizeof(int) == 0x4); public: // Deleting conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept = delete; // Get instance field reference: private System.String _displayName [[deprecated("Use field access instead!")]] ::StringW& dyn__displayName(); // Get instance field reference: private System.Int32 _helmChannel [[deprecated("Use field access instead!")]] int& dyn__helmChannel(); // public System.String get_DisplayName() // Offset: 0xADD494 ::StringW get_DisplayName(); // public System.Int32 get_HelmChannel() // Offset: 0xADD49C int get_HelmChannel(); // public System.Void .ctor() // Offset: 0xADD4A4 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PatchData* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::PatchData::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PatchData*, creationType>())); } }; // VROSC.PatchData #pragma pack(pop) static check_size<sizeof(PatchData), 32 + sizeof(int)> __VROSC_PatchDataSizeCheck; static_assert(sizeof(PatchData) == 0x24); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::PatchData::get_DisplayName // Il2CppName: get_DisplayName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (VROSC::PatchData::*)()>(&VROSC::PatchData::get_DisplayName)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::PatchData*), "get_DisplayName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::PatchData::get_HelmChannel // Il2CppName: get_HelmChannel template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::PatchData::*)()>(&VROSC::PatchData::get_HelmChannel)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::PatchData*), "get_HelmChannel", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::PatchData::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
42.695652
150
0.716395
[ "vector" ]
c08e45237f71f40a92f6f3c1cbd861c021cae90d
6,163
cxx
C++
vtkm/rendering/LineRendererBatcher.cxx
Kitware/vtk-m
b24a878f72b288d69c9da8c7ac33f08db6d39ba9
[ "BSD-3-Clause" ]
null
null
null
vtkm/rendering/LineRendererBatcher.cxx
Kitware/vtk-m
b24a878f72b288d69c9da8c7ac33f08db6d39ba9
[ "BSD-3-Clause" ]
null
null
null
vtkm/rendering/LineRendererBatcher.cxx
Kitware/vtk-m
b24a878f72b288d69c9da8c7ac33f08db6d39ba9
[ "BSD-3-Clause" ]
null
null
null
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/rendering/LineRendererBatcher.h> #include <vtkm/worklet/WorkletMapField.h> namespace vtkm { namespace rendering { namespace { using ColorsArrayHandle = vtkm::cont::ArrayHandle<vtkm::Vec4f_32>; using PointsArrayHandle = vtkm::cont::ArrayHandle<vtkm::Vec3f_32>; struct RenderLine : public vtkm::worklet::WorkletMapField { using ColorBufferType = vtkm::rendering::Canvas::ColorBufferType; using DepthBufferType = vtkm::rendering::Canvas::DepthBufferType; using ControlSignature = void(FieldIn, FieldIn, FieldIn, WholeArrayInOut, WholeArrayInOut); using ExecutionSignature = void(_1, _2, _3, _4, _5); using InputDomain = _1; VTKM_CONT RenderLine() {} VTKM_CONT RenderLine(vtkm::Id width, vtkm::Id height) : Width(width) , Height(height) { } template <typename ColorBufferPortal, typename DepthBufferPortal> VTKM_EXEC void operator()(const vtkm::Vec3f_32& start, const vtkm::Vec3f_32& end, const vtkm::Vec4f_32& color, ColorBufferPortal& colorBuffer, DepthBufferPortal& depthBuffer) const { vtkm::Id x0 = static_cast<vtkm::Id>(vtkm::Round(start[0])); vtkm::Id y0 = static_cast<vtkm::Id>(vtkm::Round(start[1])); vtkm::Float32 z0 = static_cast<vtkm::Float32>(start[2]); vtkm::Id x1 = static_cast<vtkm::Id>(vtkm::Round(end[0])); vtkm::Id y1 = static_cast<vtkm::Id>(vtkm::Round(end[1])); vtkm::Float32 z1 = static_cast<vtkm::Float32>(end[2]); vtkm::Id dx = vtkm::Abs(x1 - x0), sx = x0 < x1 ? 1 : -1; vtkm::Id dy = -vtkm::Abs(y1 - y0), sy = y0 < y1 ? 1 : -1; vtkm::Id err = dx + dy, err2 = 0; const vtkm::Id xStart = x0; const vtkm::Id yStart = y0; const vtkm::Float32 pdist = vtkm::Sqrt(vtkm::Float32(dx * dx) + vtkm::Float32(dy * dy)); while (x0 >= 0 && x0 < this->Width && y0 >= 0 && y0 < this->Height) { vtkm::Float32 deltaX = static_cast<vtkm::Float32>(x0 - xStart); vtkm::Float32 deltaY = static_cast<vtkm::Float32>(y0 - yStart); // Depth is wrong, but its far less wrong that it used to be. // These depth values are in screen space, which have been // potentially tranformed by a perspective correction. // To interpolated the depth correctly, there must be a perspective correction. // I haven't looked, but the wireframmer probably suffers from this too. // Additionally, this should not happen on the CPU. Annotations take // far longer than the the geometry. vtkm::Float32 t = pdist == 0.f ? 1.0f : vtkm::Sqrt(deltaX * deltaX + deltaY * deltaY) / pdist; t = vtkm::Min(1.f, vtkm::Max(0.f, t)); vtkm::Float32 z = vtkm::Lerp(z0, z1, t); vtkm::Id index = y0 * this->Width + x0; vtkm::Vec4f_32 currentColor = colorBuffer.Get(index); vtkm::Float32 currentZ = depthBuffer.Get(index); bool blend = currentColor[3] < 1.f && z > currentZ; if (currentZ > z || blend) { vtkm::Vec4f_32 writeColor = color; vtkm::Float32 depth = z; if (blend) { // If there is any transparency, all alphas // have been pre-mulitplied vtkm::Float32 alpha = (1.f - currentColor[3]); writeColor[0] = currentColor[0] + color[0] * alpha; writeColor[1] = currentColor[1] + color[1] * alpha; writeColor[2] = currentColor[2] + color[2] * alpha; writeColor[3] = 1.f * alpha + currentColor[3]; // we are always drawing opaque lines // keep the current z. Line z interpolation is not accurate // Matt: this is correct. Interpolation is wrong depth = currentZ; } depthBuffer.Set(index, depth); colorBuffer.Set(index, writeColor); } if (x0 == x1 && y0 == y1) { break; } err2 = err * 2; if (err2 >= dy) { err += dy; x0 += sx; } if (err2 <= dx) { err += dx; y0 += sy; } } } vtkm::Id Width; vtkm::Id Height; }; // struct RenderLine } // namespace LineRendererBatcher::LineRendererBatcher() {} void LineRendererBatcher::BatchLine(const vtkm::Vec3f_64& start, const vtkm::Vec3f_64& end, const vtkm::rendering::Color& color) { vtkm::Vec3f_32 start32(static_cast<vtkm::Float32>(start[0]), static_cast<vtkm::Float32>(start[1]), static_cast<vtkm::Float32>(start[2])); vtkm::Vec3f_32 end32(static_cast<vtkm::Float32>(end[0]), static_cast<vtkm::Float32>(end[1]), static_cast<vtkm::Float32>(end[2])); this->BatchLine(start32, end32, color); } void LineRendererBatcher::BatchLine(const vtkm::Vec3f_32& start, const vtkm::Vec3f_32& end, const vtkm::rendering::Color& color) { this->Starts.push_back(start); this->Ends.push_back(end); this->Colors.push_back(color.Components); } void LineRendererBatcher::Render(const vtkm::rendering::Canvas* canvas) const { PointsArrayHandle starts = vtkm::cont::make_ArrayHandle(this->Starts, vtkm::CopyFlag::Off); PointsArrayHandle ends = vtkm::cont::make_ArrayHandle(this->Ends, vtkm::CopyFlag::Off); ColorsArrayHandle colors = vtkm::cont::make_ArrayHandle(this->Colors, vtkm::CopyFlag::Off); vtkm::cont::Invoker invoker; invoker(RenderLine(canvas->GetWidth(), canvas->GetHeight()), starts, ends, colors, canvas->GetColorBuffer(), canvas->GetDepthBuffer()); } } } // namespace vtkm::rendering
36.467456
100
0.595165
[ "geometry", "render" ]
c08f8bf52d8369ede66c879f29a267a4a45a6cad
11,700
cc
C++
content/browser/background_sync/background_sync_scheduler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
content/browser/background_sync/background_sync_scheduler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
content/browser/background_sync/background_sync_scheduler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/background_sync/background_sync_scheduler.h" #include <map> #include <vector> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/task_environment.h" #include "base/time/time.h" #include "build/build_config.h" #include "content/browser/background_sync/background_sync_scheduler.h" #include "content/browser/storage_partition_impl.h" #include "content/common/content_export.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/content_client.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" #include "content/test/mock_background_sync_controller.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace content { namespace { const char kUrl_1[] = "https://example.com"; const char kUrl_2[] = "https://whereswaldo.com"; class TestBrowserClient : public ContentBrowserClient { public: TestBrowserClient() = default; ~TestBrowserClient() override = default; StoragePartitionConfig GetStoragePartitionConfigForSite( BrowserContext* browser_context, const GURL& site) override { return content::StoragePartitionConfig::Create( browser_context, "PartitionDomain" + site.spec(), "Partition" + site.spec(), false /* in_memory */); } }; } // namespace class BackgroundSyncSchedulerTest : public testing::Test { public: BackgroundSyncSchedulerTest() : task_environment_(BrowserTaskEnvironment::MainThreadType::UI) {} void ScheduleDelayedProcessing(const GURL& url, blink::mojom::BackgroundSyncType sync_type, base::TimeDelta delay, base::OnceClosure delayed_task) { auto* scheduler = BackgroundSyncScheduler::GetFor(&test_browser_context_); DCHECK(scheduler); auto* storage_partition = static_cast<StoragePartitionImpl*>( test_browser_context_.GetStoragePartitionForUrl(url)); DCHECK(storage_partition); scheduler->ScheduleDelayedProcessing(storage_partition, sync_type, delay, std::move(delayed_task)); } void CancelDelayedProcessing(const GURL& url, blink::mojom::BackgroundSyncType sync_type) { auto* scheduler = BackgroundSyncScheduler::GetFor(&test_browser_context_); DCHECK(scheduler); auto* storage_partition = static_cast<StoragePartitionImpl*>( test_browser_context_.GetStoragePartitionForUrl(url)); DCHECK(storage_partition); scheduler->CancelDelayedProcessing(storage_partition, sync_type); } MockBackgroundSyncController* GetController() { return static_cast<MockBackgroundSyncController*>( test_browser_context_.GetBackgroundSyncController()); } base::TimeDelta GetBrowserWakeupDelay( blink::mojom::BackgroundSyncType sync_type) { return GetController()->GetBrowserWakeupDelay(sync_type); } base::TimeTicks GetBrowserWakeupTime() { auto* scheduler = BackgroundSyncScheduler::GetFor(&test_browser_context_); DCHECK(scheduler); return scheduler ->scheduled_wakeup_time_[blink::mojom::BackgroundSyncType::ONE_SHOT]; } void SetUp() override { original_client_ = SetBrowserClientForTesting(&browser_client_); } void TearDown() override { SetBrowserClientForTesting(original_client_); } protected: BrowserTaskEnvironment task_environment_; TestBrowserClient browser_client_; raw_ptr<ContentBrowserClient> original_client_; TestBrowserContext test_browser_context_; }; TEST_F(BackgroundSyncSchedulerTest, ScheduleInvokesCallback) { base::RunLoop run_loop; ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Milliseconds(1), run_loop.QuitClosure()); run_loop.Run(); } TEST_F(BackgroundSyncSchedulerTest, ZeroDelayScheduleDoesNotInvokeCallback) { bool was_called = false; ScheduleDelayedProcessing( GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::TimeDelta(), base::BindOnce([](bool* was_called) { *was_called = true; }, &was_called)); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(was_called); } TEST_F(BackgroundSyncSchedulerTest, CancelDoesNotInvokeCallback) { bool was_called = false; ScheduleDelayedProcessing( GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Minutes(1), base::BindOnce([](bool* was_called) { *was_called = true; }, &was_called)); base::RunLoop().RunUntilIdle(); ASSERT_FALSE(was_called); CancelDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(was_called); } TEST_F(BackgroundSyncSchedulerTest, SchedulingTwiceOverwritesTimer) { bool was_called = false; ScheduleDelayedProcessing( GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Seconds(1), base::BindOnce([](bool* was_called) { *was_called = true; }, &was_called)); base::RunLoop().RunUntilIdle(); ASSERT_FALSE(was_called); base::RunLoop run_loop; ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Milliseconds(1), run_loop.QuitClosure()); run_loop.Run(); EXPECT_FALSE(was_called); } TEST_F(BackgroundSyncSchedulerTest, MultipleStoragePartitions) { base::RunLoop run_loop_1, run_loop_2; ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Seconds(1), run_loop_1.QuitClosure()); ScheduleDelayedProcessing(GURL(kUrl_2), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Milliseconds(1), run_loop_2.QuitClosure()); run_loop_1.Run(); run_loop_2.Run(); } TEST_F(BackgroundSyncSchedulerTest, ScheduleBothTypesOfSync) { base::RunLoop run_loop_1, run_loop_2; ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Milliseconds(1), run_loop_1.QuitClosure()); ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::PERIODIC, base::Milliseconds(1), run_loop_2.QuitClosure()); run_loop_1.Run(); run_loop_2.Run(); } #if defined(OS_ANDROID) TEST_F(BackgroundSyncSchedulerTest, BrowserWakeupScheduled) { ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Seconds(1), base::DoNothing()); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Seconds(1)); ScheduleDelayedProcessing(GURL(kUrl_2), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Milliseconds(1), base::DoNothing()); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Milliseconds(1)); } TEST_F(BackgroundSyncSchedulerTest, BrowserWakeupScheduleSecondAfterFirstFinishes) { base::RunLoop run_loop_1; ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Milliseconds(1), run_loop_1.QuitClosure()); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Milliseconds(1)); run_loop_1.Run(); ScheduleDelayedProcessing(GURL(kUrl_2), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Minutes(1), base::DoNothing()); EXPECT_GT(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Milliseconds(1)); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Minutes(1)); } TEST_F(BackgroundSyncSchedulerTest, BrowserWakeupScheduleOneOfEachType) { ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::PERIODIC, base::Seconds(1), base::DoNothing()); base::RunLoop().RunUntilIdle(); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::PERIODIC), base::Seconds(1)); ScheduleDelayedProcessing(GURL(kUrl_2), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Minutes(1), base::DoNothing()); base::RunLoop().RunUntilIdle(); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Minutes(1)); } TEST_F(BackgroundSyncSchedulerTest, BrowserWakeupScheduleThenCancel) { ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::PERIODIC, base::Minutes(1), base::DoNothing()); base::RunLoop().RunUntilIdle(); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::PERIODIC), base::Minutes(1)); CancelDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::PERIODIC); base::RunLoop().RunUntilIdle(); EXPECT_EQ(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::PERIODIC), base::TimeDelta::Max()); } TEST_F(BackgroundSyncSchedulerTest, CancelingOneTypeDoesNotAffectAnother) { ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::PERIODIC, base::Minutes(1), base::DoNothing()); ScheduleDelayedProcessing(GURL(kUrl_2), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Seconds(1), base::DoNothing()); CancelDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::PERIODIC); base::RunLoop().RunUntilIdle(); EXPECT_EQ(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::PERIODIC), base::TimeDelta::Max()); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Seconds(1)); } TEST_F(BackgroundSyncSchedulerTest, CancelingProcessingForOneStorageParitionUpdatesBrowserWakeup) { ScheduleDelayedProcessing(GURL(kUrl_1), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Minutes(1), base::DoNothing()); ScheduleDelayedProcessing(GURL(kUrl_2), blink::mojom::BackgroundSyncType::ONE_SHOT, base::Seconds(1), base::DoNothing()); base::RunLoop().RunUntilIdle(); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Seconds(1)); auto wakeup_time1 = GetBrowserWakeupTime(); CancelDelayedProcessing(GURL(kUrl_2), blink::mojom::BackgroundSyncType::ONE_SHOT); base::RunLoop().RunUntilIdle(); EXPECT_LE(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Minutes(1)); EXPECT_GT(GetBrowserWakeupDelay(blink::mojom::BackgroundSyncType::ONE_SHOT), base::Seconds(1)); EXPECT_LT(wakeup_time1, GetBrowserWakeupTime()); } #endif } // namespace content
38.486842
78
0.678034
[ "vector" ]
6a4dd0ee1c32665765f994fc0f21588cba42ee47
1,007
cpp
C++
lib/src/Components/CMesh.cpp
F4r3n/FarenMediaLibrary
3f71054df7178ca79781b101ca2d58cd95a20a43
[ "Apache-2.0" ]
7
2016-09-09T16:43:15.000Z
2021-06-16T22:32:33.000Z
lib/src/Components/CMesh.cpp
F4r3n/FarenMediaLibrary
3f71054df7178ca79781b101ca2d58cd95a20a43
[ "Apache-2.0" ]
null
null
null
lib/src/Components/CMesh.cpp
F4r3n/FarenMediaLibrary
3f71054df7178ca79781b101ca2d58cd95a20a43
[ "Apache-2.0" ]
1
2020-01-05T19:22:32.000Z
2020-01-05T19:22:32.000Z
#include "Components/CMesh.h" #include "Resource/ResourcesManager.h" #include <memory> #include "Core/Math/Functions.h" #include <EntityManager.h> #include "Rendering/Model.hpp" #include <nlohmann/json.hpp> using namespace fmc; CMesh::~CMesh() { } CMesh::CMesh() { _name = "Mesh"; _type = "Quad"; model = fm::ResourcesManager::get().getResource<fm::Model>(_type); } bool CMesh::Serialize(nlohmann::json &ioJson) const { ioJson["type"] = _type; return true; } bool CMesh::Read(const nlohmann::json &inJSON) { _type = inJSON["type"]; model = fm::ResourcesManager::get().getResource<fm::Model>(_type); return true; } const std::string& CMesh::GetName() const { return _name; } bool CMesh::IsmodelReady() { return model != nullptr; } void CMesh::SetType(const std::string &type) { _type = type; } void CMesh::Destroy() { EntityManager::get().removeComponent<CMesh>(BaseComponent::_IDEntity); } CMesh::CMesh(std::string type) { _type = type; _name = "Mesh"; }
17.666667
74
0.67428
[ "mesh", "model" ]
6a527010fa3492d7989b25a01beb126fe3c8dc02
15,972
cpp
C++
B2G/gecko/tools/reorder/grope.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/tools/reorder/grope.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/tools/reorder/grope.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A program that computes a function ordering for an executable based on runtime profile information. This program is directly based on work done by Roger Chickering <rogc@netscape.com> in <http://bugzilla.mozilla.org/show_bug.cgi?id=65845> to implement Nat Friedman's <nat@nat.org> `grope', _GNU Rope - A Subroutine Position Optimizer_ <http://www.hungry.com/~shaver/grope/grope.ps> Specifically, it implements the procedure re-ordering algorithm described in: K. Pettis and R. Hansen. ``Profile-Guided Core Position.'' In _Proceedings of the Int. Conference on Programming Language Design and Implementation_, pages 16-27, June 1990. */ #include <assert.h> #include <fstream> #include <hash_set> #include <map> #include <set> #include <list> #include <vector> #include <limits.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include "elf_symbol_table.h" #define _GNU_SOURCE #include <getopt.h> elf_symbol_table symtab; // Straight outta plhash.c! #define GOLDEN_RATIO 0x9E3779B9U struct hash<const Elf32_Sym *> { size_t operator()(const Elf32_Sym *sym) const { return (reinterpret_cast<size_t>(sym) >> 4) * GOLDEN_RATIO; } }; typedef unsigned int call_count_t; struct call_graph_arc { const Elf32_Sym *m_from; const Elf32_Sym *m_to; call_count_t m_count; call_graph_arc(const Elf32_Sym *left, const Elf32_Sym *right, call_count_t count = 0) : m_count(count) { assert(left != right); if (left > right) { m_from = left; m_to = right; } else { m_from = right; m_to = left; } } friend bool operator==(const call_graph_arc &lhs, const call_graph_arc &rhs) { return (lhs.m_from == rhs.m_from) && (lhs.m_to == rhs.m_to); } friend ostream & operator<<(ostream &out, const call_graph_arc &arc) { out << &arc << ": "; out.form("<(%s %s) %d>", symtab.get_symbol_name(arc.m_from), symtab.get_symbol_name(arc.m_to), arc.m_count); return out; } }; struct hash<call_graph_arc *> { size_t operator()(const call_graph_arc* arc) const { size_t result; result = reinterpret_cast<unsigned long>(arc->m_from); result ^= reinterpret_cast<unsigned long>(arc->m_to) >> 16; result ^= reinterpret_cast<unsigned long>(arc->m_to) << 16; result *= GOLDEN_RATIO; return result; } }; struct equal_to<call_graph_arc *> { bool operator()(const call_graph_arc* lhs, const call_graph_arc *rhs) const { return *lhs == *rhs; } }; typedef hash_set<call_graph_arc *> arc_container_t; arc_container_t arcs; typedef multimap<const Elf32_Sym *, call_graph_arc *> arc_map_t; arc_map_t from_map; arc_map_t to_map; struct less_call_graph_arc_count { bool operator()(const call_graph_arc *lhs, const call_graph_arc *rhs) const { if (lhs->m_count == rhs->m_count) { if (lhs->m_from == rhs->m_from) return lhs->m_to > rhs->m_to; return lhs->m_from > rhs->m_from; } return lhs->m_count > rhs->m_count; } }; typedef set<call_graph_arc *, less_call_graph_arc_count> arc_count_index_t; bool opt_debug = false; const char *opt_out = "order.out"; int opt_tick = 0; bool opt_verbose = false; int opt_window = 16; static struct option long_options[] = { { "debug", no_argument, 0, 'd' }, { "exe", required_argument, 0, 'e' }, { "help", no_argument, 0, '?' }, { "out", required_argument, 0, 'o' }, { "tick", optional_argument, 0, 't' }, { "verbose", no_argument, 0, 'v' }, { "window", required_argument, 0, 'w' }, { 0, 0, 0, 0 } }; //---------------------------------------------------------------------- static void usage(const char *name) { cerr << "usage: " << name << " [options] [<file> ...]" << endl; cerr << " Options:" << endl; cerr << " --debug, -d" << endl; cerr << " Print lots of verbose debugging cruft." << endl; cerr << " --exe=<image>, -e <image> (required)" << endl; cerr << " Specify the executable image from which to read symbol information." << endl; cerr << " --help, -?" << endl; cerr << " Print this message and exit." << endl; cerr << " --out=<file>, -o <file>" << endl; cerr << " Specify the output file to which to dump the symbol ordering of the" << endl; cerr << " best individual (default is `order.out')." << endl; cerr << " --tick[=<num>], -t [<num>]" << endl; cerr << " When reading address data, print a dot to stderr every <num>th" << endl; cerr << " address processed from the call trace. If specified with no argument," << endl; cerr << " a dot will be printed for every million addresses processed." << endl; cerr << " --verbose, -v" << endl; cerr << " Issue progress messages to stderr." << endl; cerr << " --window=<num>, -w <num>" << endl; cerr << " Use a sliding window instead of pagination to score orderings." << endl; } /** * Using the symbol table, map a stream of address references into a * callgraph. */ static void map_addrs(int fd) { long long total_calls = 0; typedef list<const Elf32_Sym *> window_t; window_t window; int window_size = 0; unsigned int buf[128]; ssize_t cb; while ((cb = read(fd, buf, sizeof buf)) > 0) { if (cb % sizeof buf[0]) fprintf(stderr, "unaligned read\n"); unsigned int *addr = buf; unsigned int *limit = buf + (cb / 4); for (; addr < limit; ++addr) { const Elf32_Sym *sym = symtab.lookup(*addr); if (! sym) continue; ++total_calls; window.push_front(sym); if (window_size >= opt_window) window.pop_back(); else ++window_size; window_t::const_iterator i = window.begin(); window_t::const_iterator end = window.end(); for (; i != end; ++i) { if (sym != *i) { call_graph_arc *arc; call_graph_arc key(sym, *i); arc_container_t::iterator iter = arcs.find(&key); if (iter == arcs.end()) { arc = new call_graph_arc(sym, *i); arcs.insert(arc); from_map.insert(arc_map_t::value_type(arc->m_from, arc)); to_map.insert(arc_map_t::value_type(arc->m_to, arc)); } else arc = const_cast<call_graph_arc *>(*iter); ++(arc->m_count); } } if (opt_verbose && opt_tick && (total_calls % opt_tick == 0)) { cerr << "."; flush(cerr); } } } if (opt_verbose) { if (opt_tick) cerr << endl; cerr << "Total calls: " << total_calls << endl; } } static void remove_from(arc_map_t& map, const Elf32_Sym *sym, const call_graph_arc *arc) { pair<arc_map_t::iterator, arc_map_t::iterator> p = map.equal_range(sym); for (arc_map_t::iterator i = p.first; i != p.second; ++i) { if (i->second == arc) { map.erase(i); break; } } } /** * The main program */ int main(int argc, char *argv[]) { const char *opt_exe = 0; int c; while (1) { int option_index = 0; c = getopt_long(argc, argv, "?de:o:t:vw:", long_options, &option_index); if (c < 0) break; switch (c) { case '?': usage(argv[0]); return 0; case 'd': opt_debug = true; break; case 'e': opt_exe = optarg; break; case 'o': opt_out = optarg; break; case 't': opt_tick = optarg ? atoi(optarg) : 1000000; break; case 'v': opt_verbose = true; break; case 'w': opt_window = atoi(optarg); if (opt_window <= 0) { cerr << "invalid window size: " << opt_window << endl; return 1; } break; default: usage(argv[0]); return 1; } } // Make sure an image was specified if (! opt_exe) { usage(argv[0]); return 1; } // Read the sym table. symtab.init(opt_exe); // Process addresses to construct the weighted call graph. if (optind >= argc) { map_addrs(STDIN_FILENO); } else { do { int fd = open(argv[optind], O_RDONLY); if (fd < 0) { perror(argv[optind]); return 1; } map_addrs(fd); close(fd); } while (++optind < argc); } // Emit the ordering. ofstream out(opt_out); // Collect all of the arcs into a sorted container, with arcs // having the largest weight at the front. arc_count_index_t sorted_arcs(arcs.begin(), arcs.end()); while (sorted_arcs.size()) { if (opt_debug) { cerr << "==========================================" << endl << endl; cerr << "Sorted Arcs:" << endl; for (arc_count_index_t::const_iterator iter = sorted_arcs.begin(); iter != sorted_arcs.end(); ++iter) { cerr << **iter << endl; } cerr << endl << "Arc Container:" << endl; for (arc_container_t::const_iterator iter = arcs.begin(); iter != arcs.end(); ++iter) { cerr << **iter << endl; } cerr << endl << "From Map:" << endl; for (arc_map_t::const_iterator iter = from_map.begin(); iter != from_map.end(); ++iter) { cerr << symtab.get_symbol_name(iter->first) << ": " << *(iter->second) << endl; } cerr << endl << "To Map:" << endl; for (arc_map_t::const_iterator iter = to_map.begin(); iter != to_map.end(); ++iter) { cerr << symtab.get_symbol_name(iter->first) << ": " << *(iter->second) << endl; } cerr << endl; } // The first arc in the sorted set will have the largest // weight. Pull it out, and emit its sink. arc_count_index_t::iterator max = sorted_arcs.begin(); call_graph_arc *arc = const_cast<call_graph_arc *>(*max); sorted_arcs.erase(max); if (opt_debug) cerr << "pulling " << *arc << endl; arcs.erase(arc); remove_from(from_map, arc->m_from, arc); remove_from(to_map, arc->m_to, arc); out << symtab.get_symbol_name(arc->m_to) << endl; // Merge arc->m_to into arc->m_from. First, modify anything // that used to point to arc->m_to to point to arc->m_from. typedef list<call_graph_arc *> arc_list_t; arc_list_t map_add_queue; pair<arc_map_t::iterator, arc_map_t::iterator> p; // Find all the arcs that point to arc->m_to. p = to_map.equal_range(arc->m_to); for (arc_map_t::iterator i = p.first; i != p.second; ++i) { // Remove the arc that points to arc->m_to (`doomed') from // all of our indicies. call_graph_arc *doomed = i->second; const Elf32_Sym *source = doomed->m_from; sorted_arcs.erase(doomed); arcs.erase(doomed); remove_from(from_map, source, doomed); // N.B. that `doomed' will be removed from the `to_map' // after the loop completes. // Create a new (or locate an existing) arc whose source // was the doomed arc's source, and whose sink is // arc->m_from (i.e., the node that subsumed arc->m_to). call_graph_arc *merge; call_graph_arc key = call_graph_arc(source, arc->m_from); arc_container_t::iterator iter = arcs.find(&key); if (iter == arcs.end()) { merge = new call_graph_arc(source, arc->m_from); arcs.insert(merge); from_map.insert(arc_map_t::value_type(merge->m_from, merge)); map_add_queue.push_back(merge); } else { // We found an existing arc: temporarily remove it // from the sorted index. merge = const_cast<call_graph_arc *>(*iter); sorted_arcs.erase(merge); } // Include the doomed arc's weight in the merged arc, and // (re-)insert it into the sorted index. merge->m_count += doomed->m_count; sorted_arcs.insert(merge); delete doomed; } to_map.erase(p.first, p.second); for (arc_list_t::iterator merge = map_add_queue.begin(); merge != map_add_queue.end(); map_add_queue.erase(merge++)) { to_map.insert(arc_map_t::value_type((*merge)->m_to, *merge)); } // Now, roll anything that arc->m_to used to point at into // what arc->m_from now points at. // Collect all of the arcs that originate at arc->m_to. p = from_map.equal_range(arc->m_to); for (arc_map_t::iterator i = p.first; i != p.second; ++i) { // Remove the arc originating from arc->m_to (`doomed') // from all of our indicies. call_graph_arc *doomed = i->second; const Elf32_Sym *sink = doomed->m_to; // There shouldn't be any self-referential arcs. assert(sink != arc->m_to); sorted_arcs.erase(doomed); arcs.erase(doomed); remove_from(to_map, sink, doomed); // N.B. that `doomed' will be removed from the `from_map' // once the loop completes. // Create a new (or locate an existing) arc whose source // is arc->m_from and whose sink was the removed arc's // sink. call_graph_arc *merge; call_graph_arc key = call_graph_arc(arc->m_from, sink); arc_container_t::iterator iter = arcs.find(&key); if (iter == arcs.end()) { merge = new call_graph_arc(arc->m_from, sink); arcs.insert(merge); map_add_queue.push_back(merge); to_map.insert(arc_map_t::value_type(merge->m_to, merge)); } else { // We found an existing arc: temporarily remove it // from the sorted index. merge = const_cast<call_graph_arc *>(*iter); sorted_arcs.erase(merge); } // Include the doomed arc's weight in the merged arc, and // (re-)insert it into the sorted index. merge->m_count += doomed->m_count; sorted_arcs.insert(merge); delete doomed; } from_map.erase(p.first, p.second); for (arc_list_t::iterator merge = map_add_queue.begin(); merge != map_add_queue.end(); map_add_queue.erase(merge++)) { from_map.insert(arc_map_t::value_type((*merge)->m_from, *merge)); } } out.close(); return 0; }
29.966229
98
0.531117
[ "vector" ]
6a5557daf1593937563642a8de643652c4da4021
18,729
hpp
C++
include/System/Text/RegularExpressions/RegexWriter.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/Text/RegularExpressions/RegexWriter.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/System/Text/RegularExpressions/RegexWriter.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: Dictionary`2<TKey, TValue> template<typename TKey, typename TValue> class Dictionary_2; // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: Hashtable class Hashtable; } // Forward declaring namespace: System::Text::RegularExpressions namespace System::Text::RegularExpressions { // Forward declaring type: RegexCode class RegexCode; // Forward declaring type: RegexTree class RegexTree; // Forward declaring type: RegexNode class RegexNode; } // Forward declaring namespace: System namespace System { // Forward declaring type: ArgumentException class ArgumentException; } // Completed forward declares // Type namespace: System.Text.RegularExpressions namespace System::Text::RegularExpressions { // Size: 0x58 #pragma pack(push, 1) // Autogenerated type: System.Text.RegularExpressions.RegexWriter // [TokenAttribute] Offset: FFFFFFFF class RegexWriter : public ::Il2CppObject { public: // System.Int32[] _intStack // Size: 0x8 // Offset: 0x10 ::Array<int>* intStack; // Field size check static_assert(sizeof(::Array<int>*) == 0x8); // System.Int32 _depth // Size: 0x4 // Offset: 0x18 int depth; // Field size check static_assert(sizeof(int) == 0x4); // Padding between fields: depth and: emitted char __padding1[0x4] = {}; // System.Int32[] _emitted // Size: 0x8 // Offset: 0x20 ::Array<int>* emitted; // Field size check static_assert(sizeof(::Array<int>*) == 0x8); // System.Int32 _curpos // Size: 0x4 // Offset: 0x28 int curpos; // Field size check static_assert(sizeof(int) == 0x4); // Padding between fields: curpos and: stringhash char __padding3[0x4] = {}; // System.Collections.Generic.Dictionary`2<System.String,System.Int32> _stringhash // Size: 0x8 // Offset: 0x30 System::Collections::Generic::Dictionary_2<::Il2CppString*, int>* stringhash; // Field size check static_assert(sizeof(System::Collections::Generic::Dictionary_2<::Il2CppString*, int>*) == 0x8); // System.Collections.Generic.List`1<System.String> _stringtable // Size: 0x8 // Offset: 0x38 System::Collections::Generic::List_1<::Il2CppString*>* stringtable; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<::Il2CppString*>*) == 0x8); // System.Boolean _counting // Size: 0x1 // Offset: 0x40 bool counting; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: counting and: count char __padding6[0x3] = {}; // System.Int32 _count // Size: 0x4 // Offset: 0x44 int count; // Field size check static_assert(sizeof(int) == 0x4); // System.Int32 _trackcount // Size: 0x4 // Offset: 0x48 int trackcount; // Field size check static_assert(sizeof(int) == 0x4); // Padding between fields: trackcount and: caps char __padding8[0x4] = {}; // System.Collections.Hashtable _caps // Size: 0x8 // Offset: 0x50 System::Collections::Hashtable* caps; // Field size check static_assert(sizeof(System::Collections::Hashtable*) == 0x8); // Creating value type constructor for type: RegexWriter RegexWriter(::Array<int>* intStack_ = {}, int depth_ = {}, ::Array<int>* emitted_ = {}, int curpos_ = {}, System::Collections::Generic::Dictionary_2<::Il2CppString*, int>* stringhash_ = {}, System::Collections::Generic::List_1<::Il2CppString*>* stringtable_ = {}, bool counting_ = {}, int count_ = {}, int trackcount_ = {}, System::Collections::Hashtable* caps_ = {}) noexcept : intStack{intStack_}, depth{depth_}, emitted{emitted_}, curpos{curpos_}, stringhash{stringhash_}, stringtable{stringtable_}, counting{counting_}, count{count_}, trackcount{trackcount_}, caps{caps_} {} // Get instance field reference: System.Int32[] _intStack ::Array<int>*& dyn__intStack(); // Get instance field reference: System.Int32 _depth int& dyn__depth(); // Get instance field reference: System.Int32[] _emitted ::Array<int>*& dyn__emitted(); // Get instance field reference: System.Int32 _curpos int& dyn__curpos(); // Get instance field reference: System.Collections.Generic.Dictionary`2<System.String,System.Int32> _stringhash System::Collections::Generic::Dictionary_2<::Il2CppString*, int>*& dyn__stringhash(); // Get instance field reference: System.Collections.Generic.List`1<System.String> _stringtable System::Collections::Generic::List_1<::Il2CppString*>*& dyn__stringtable(); // Get instance field reference: System.Boolean _counting bool& dyn__counting(); // Get instance field reference: System.Int32 _count int& dyn__count(); // Get instance field reference: System.Int32 _trackcount int& dyn__trackcount(); // Get instance field reference: System.Collections.Hashtable _caps System::Collections::Hashtable*& dyn__caps(); // static System.Text.RegularExpressions.RegexCode Write(System.Text.RegularExpressions.RegexTree t) // Offset: 0x19A6D8C static System::Text::RegularExpressions::RegexCode* Write(System::Text::RegularExpressions::RegexTree* t); // System.Void PushInt(System.Int32 I) // Offset: 0x19A724C void PushInt(int I); // System.Boolean EmptyStack() // Offset: 0x19A732C bool EmptyStack(); // System.Int32 PopInt() // Offset: 0x19A733C int PopInt(); // System.Int32 CurPos() // Offset: 0x19A7384 int CurPos(); // System.Void PatchJump(System.Int32 Offset, System.Int32 jumpDest) // Offset: 0x19A738C void PatchJump(int Offset, int jumpDest); // System.Void Emit(System.Int32 op) // Offset: 0x19A73CC void Emit(int op); // System.Void Emit(System.Int32 op, System.Int32 opd1) // Offset: 0x19A7464 void Emit(int op, int opd1); // System.Void Emit(System.Int32 op, System.Int32 opd1, System.Int32 opd2) // Offset: 0x19A7524 void Emit(int op, int opd1, int opd2); // System.Int32 StringCode(System.String str) // Offset: 0x19A760C int StringCode(::Il2CppString* str); // System.ArgumentException MakeException(System.String message) // Offset: 0x19A7718 System::ArgumentException* MakeException(::Il2CppString* message); // System.Int32 MapCapnum(System.Int32 capnum) // Offset: 0x19A777C int MapCapnum(int capnum); // System.Text.RegularExpressions.RegexCode RegexCodeFromRegexTree(System.Text.RegularExpressions.RegexTree tree) // Offset: 0x19A6EB8 System::Text::RegularExpressions::RegexCode* RegexCodeFromRegexTree(System::Text::RegularExpressions::RegexTree* tree); // System.Void EmitFragment(System.Int32 nodetype, System.Text.RegularExpressions.RegexNode node, System.Int32 CurIndex) // Offset: 0x19A7838 void EmitFragment(int nodetype, System::Text::RegularExpressions::RegexNode* node, int CurIndex); // private System.Void .ctor() // Offset: 0x19A6DF4 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RegexWriter* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Text::RegularExpressions::RegexWriter::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RegexWriter*, creationType>())); } }; // System.Text.RegularExpressions.RegexWriter #pragma pack(pop) static check_size<sizeof(RegexWriter), 80 + sizeof(System::Collections::Hashtable*)> __System_Text_RegularExpressions_RegexWriterSizeCheck; static_assert(sizeof(RegexWriter) == 0x58); } DEFINE_IL2CPP_ARG_TYPE(System::Text::RegularExpressions::RegexWriter*, "System.Text.RegularExpressions", "RegexWriter"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::Write // Il2CppName: Write template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Text::RegularExpressions::RegexCode* (*)(System::Text::RegularExpressions::RegexTree*)>(&System::Text::RegularExpressions::RegexWriter::Write)> { static const MethodInfo* get() { static auto* t = &::il2cpp_utils::GetClassFromName("System.Text.RegularExpressions", "RegexTree")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "Write", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{t}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::PushInt // Il2CppName: PushInt template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Text::RegularExpressions::RegexWriter::*)(int)>(&System::Text::RegularExpressions::RegexWriter::PushInt)> { static const MethodInfo* get() { static auto* I = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "PushInt", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{I}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::EmptyStack // Il2CppName: EmptyStack template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Text::RegularExpressions::RegexWriter::*)()>(&System::Text::RegularExpressions::RegexWriter::EmptyStack)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "EmptyStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::PopInt // Il2CppName: PopInt template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Text::RegularExpressions::RegexWriter::*)()>(&System::Text::RegularExpressions::RegexWriter::PopInt)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "PopInt", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::CurPos // Il2CppName: CurPos template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Text::RegularExpressions::RegexWriter::*)()>(&System::Text::RegularExpressions::RegexWriter::CurPos)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "CurPos", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::PatchJump // Il2CppName: PatchJump template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Text::RegularExpressions::RegexWriter::*)(int, int)>(&System::Text::RegularExpressions::RegexWriter::PatchJump)> { static const MethodInfo* get() { static auto* Offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* jumpDest = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "PatchJump", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{Offset, jumpDest}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::Emit // Il2CppName: Emit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Text::RegularExpressions::RegexWriter::*)(int)>(&System::Text::RegularExpressions::RegexWriter::Emit)> { static const MethodInfo* get() { static auto* op = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "Emit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{op}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::Emit // Il2CppName: Emit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Text::RegularExpressions::RegexWriter::*)(int, int)>(&System::Text::RegularExpressions::RegexWriter::Emit)> { static const MethodInfo* get() { static auto* op = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* opd1 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "Emit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{op, opd1}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::Emit // Il2CppName: Emit template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Text::RegularExpressions::RegexWriter::*)(int, int, int)>(&System::Text::RegularExpressions::RegexWriter::Emit)> { static const MethodInfo* get() { static auto* op = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* opd1 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* opd2 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "Emit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{op, opd1, opd2}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::StringCode // Il2CppName: StringCode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Text::RegularExpressions::RegexWriter::*)(::Il2CppString*)>(&System::Text::RegularExpressions::RegexWriter::StringCode)> { static const MethodInfo* get() { static auto* str = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "StringCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{str}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::MakeException // Il2CppName: MakeException template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::ArgumentException* (System::Text::RegularExpressions::RegexWriter::*)(::Il2CppString*)>(&System::Text::RegularExpressions::RegexWriter::MakeException)> { static const MethodInfo* get() { static auto* message = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "MakeException", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{message}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::MapCapnum // Il2CppName: MapCapnum template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Text::RegularExpressions::RegexWriter::*)(int)>(&System::Text::RegularExpressions::RegexWriter::MapCapnum)> { static const MethodInfo* get() { static auto* capnum = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "MapCapnum", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{capnum}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::RegexCodeFromRegexTree // Il2CppName: RegexCodeFromRegexTree template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Text::RegularExpressions::RegexCode* (System::Text::RegularExpressions::RegexWriter::*)(System::Text::RegularExpressions::RegexTree*)>(&System::Text::RegularExpressions::RegexWriter::RegexCodeFromRegexTree)> { static const MethodInfo* get() { static auto* tree = &::il2cpp_utils::GetClassFromName("System.Text.RegularExpressions", "RegexTree")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "RegexCodeFromRegexTree", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{tree}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::EmitFragment // Il2CppName: EmitFragment template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Text::RegularExpressions::RegexWriter::*)(int, System::Text::RegularExpressions::RegexNode*, int)>(&System::Text::RegularExpressions::RegexWriter::EmitFragment)> { static const MethodInfo* get() { static auto* nodetype = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* node = &::il2cpp_utils::GetClassFromName("System.Text.RegularExpressions", "RegexNode")->byval_arg; static auto* CurIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Text::RegularExpressions::RegexWriter*), "EmitFragment", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{nodetype, node, CurIndex}); } }; // Writing MetadataGetter for method: System::Text::RegularExpressions::RegexWriter::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
56.412651
583
0.716109
[ "object", "vector" ]
6a5561c62447c2f014f068459264b32d87e971d5
1,912
cc
C++
security/key_test.cc
iceb0y/trunk
8d21be238d8478691f947ce1ecf905ac9b75787b
[ "Apache-2.0" ]
6
2019-12-01T00:49:31.000Z
2020-07-26T07:35:07.000Z
security/key_test.cc
iceboy233/trunk
83024a83f07a587e00a3f2e1906361de521d8f12
[ "Apache-2.0" ]
null
null
null
security/key_test.cc
iceboy233/trunk
83024a83f07a587e00a3f2e1906361de521d8f12
[ "Apache-2.0" ]
1
2020-07-26T06:39:30.000Z
2020-07-26T06:39:30.000Z
#include "security/key.h" #include <vector> #include <gtest/gtest.h> namespace security { namespace { TEST(Key, Fingerprint) { EXPECT_EQ(Key{{}}.fingerprint(), 0x903df1a0ade0b876); } TEST(Key, Fingerprint1) { EXPECT_EQ(Key{{1}}.fingerprint(), 0x9311ece17c0ad3c5); } TEST(Key, DecryptInvalid) { Key key{{}}; NonceArray nonce{}; std::array<uint8_t, 16> buffer{}; EXPECT_EQ( key.decrypt(buffer, nonce.data(), buffer.data()), std::numeric_limits<size_t>::max()); } struct TestVector { std::vector<uint8_t> plain; std::vector<uint8_t> crypt; }; class VectorTest : public testing::TestWithParam<TestVector> {}; TEST_P(VectorTest, Encrypt) { const TestVector &vector = GetParam(); Key key{{}}; NonceArray nonce{}; std::vector<uint8_t> output(vector.plain.size() + Key::encrypt_overhead); EXPECT_EQ(key.encrypt(vector.plain, nonce.data(), output.data()), vector.crypt.size()); output.resize(vector.crypt.size()); EXPECT_EQ(output, vector.crypt); } TEST_P(VectorTest, Decrypt) { const TestVector &vector = GetParam(); Key key{{}}; NonceArray nonce{}; std::vector<uint8_t> output(vector.crypt.size()); EXPECT_EQ(key.decrypt(vector.crypt, nonce.data(), output.data()), vector.plain.size()); output.resize(vector.plain.size()); EXPECT_EQ(output, vector.plain); } INSTANTIATE_TEST_CASE_P(VectorTest, VectorTest, testing::Values( TestVector{ {}, { 0x4e, 0xb9, 0x72, 0xc9, 0xa8, 0xfb, 0x3a, 0x1b, 0x38, 0x2b, 0xb4, 0xd3, 0x6f, 0x5f, 0xfa, 0xd1, }, }, TestVector{ {1, 2, 3, 4, 5}, { 0x9e, 0x05, 0xe4, 0xba, 0x50, 0xfa, 0x7c, 0xdb, 0x85, 0x24, 0xdc, 0xa5, 0x8a, 0xfc, 0xe4, 0x39, 0x97, 0x9c, 0x7d, 0xf8, 0x10, }, } )); } // namespace } // namespace security
25.493333
77
0.610879
[ "vector" ]
6a55aaef1dfa39c2a3604b9010611b2c8dec78ba
7,423
cpp
C++
cop3014-foundations/bullard/_old/COP3014_2016R_HW5/COP3014_2016R_HW5/call_stats3 (6).cpp
chrisbcarl/FAU-Computer-Science
98e247bda17bad97a285c01bf2b36af07d9f4239
[ "MIT" ]
null
null
null
cop3014-foundations/bullard/_old/COP3014_2016R_HW5/COP3014_2016R_HW5/call_stats3 (6).cpp
chrisbcarl/FAU-Computer-Science
98e247bda17bad97a285c01bf2b36af07d9f4239
[ "MIT" ]
null
null
null
cop3014-foundations/bullard/_old/COP3014_2016R_HW5/COP3014_2016R_HW5/call_stats3 (6).cpp
chrisbcarl/FAU-Computer-Science
98e247bda17bad97a285c01bf2b36af07d9f4239
[ "MIT" ]
null
null
null
/******************************************************************************* Name: Christopher Carl Z#: Z23146703 Course: Foundations of Computer Science (COP3014) Professor: Dr. Lofton Bullard Due Date: 16.06.19 Due Time: 23:30 Total Points: 100 Assignment 3: Call Cost Calculator w/ File I/O Streams Description: This assignment is an extension of Assignment#2. You will implement a program called "call_stats3.cpp" to process customer call records. Each customer call record contains seven fields, which are as follows: 1) a ten digit cell phone number (string, no dashes), 2) the number of relay stations used in making the call (integer), 3) the length of the call in minutes (integer), 4) the net cost of the call (double), 5) the tax rate (double), 6) the call tax (double) and 7) the total cost of the call (double). Your program will have 3 functions: Input, Process and Output. Your main program will call each function until the end of the datafile has been read. Each call record will be printed to a data file. Following are the descriptions of the functionality of each function: LOG: 16.06.16, 18:44 - start 16.06.16, 19:06 - logic completed, first compile, works 16.06.16, 19:16 - documentation added 16.06.16, 19:16 - formatting for readability/80char rule 16.06.16, 19:24 - final edits BUG: FOUND: FIXED: DESCIRPTION: b0001 16.06.16,19:06 - Last line gets processed twice?! 16.06.16,19:21 If the input has a last line, then the eof() is not satisfied and therefore fills it with something. If this were an encryption problem, we'd have strange translations instead of just a doubly processed line. *******************************************************************************/ #include <iostream> #include <ios> #include <string> #include <fstream> using namespace std; class call_record { public: string cell_number; int relays; int call_length; double net_cost; double tax_rate; double call_tax; double total_cost_of_call; }; void Input(ifstream &, call_record &); void Output(const call_record &); void Process(const call_record &); /* Name: Input Precondition: VARS all initialized in higher function VARS: ifstream in call_record customer_record Postcondition: VAR customer_record contains new data Description: Get input (values of cell_number, relays, and call_length) from a data text file. Each "line" of this data text file becomes the same object, customer_record which becomes processed by void Process() */ void Input(ifstream & in_stream, call_record & customer_record) { in_stream >> customer_record.cell_number; in_stream >> customer_record.relays; in_stream >> customer_record.call_length; } /* Name: Process Precondition: VARS all defined in higher function VARS: call_record customer_record Postcondition: VARS all calculated in higher function Description: Processes all attributes in the call_record object customer_record and assign the computed attributes to the customer_record object */ void Process(call_record & customer_record) { if (0 >= customer_record.relays) { customer_record.call_tax = 0.00; } if ((01 <= customer_record.relays) && (customer_record.relays <= 05)) { customer_record.call_tax = 0.01; } if ((06 <= customer_record.relays) && (customer_record.relays <= 11)) { customer_record.call_tax = 0.03; } if ((12 <= customer_record.relays) && (customer_record.relays <= 20)) { customer_record.call_tax = 0.05; } if ((21 <= customer_record.relays) && (customer_record.relays <= 50)) { customer_record.call_tax = 0.08; } if ((customer_record.relays > 50)) { customer_record.call_tax = 0.12; } customer_record.tax_rate = customer_record.call_tax; customer_record.net_cost = (customer_record.relays / 50.0 * 0.40 * customer_record.call_length); customer_record.call_tax = customer_record.net_cost * customer_record.call_tax; customer_record.total_cost_of_call = customer_record.net_cost + customer_record.call_tax; } /* Name: Output Precondition: VARS all initialized in higher function VARS: call_record customer_record Postcondition: VAR customer_record contains no new data Description: Outputs the individual attributes of the call_record object customer_record to the user. */ void Output(const call_record & customer_record) { cout << endl << endl; cout << "FIELD: VALUE:" << endl; cout << "== == == == == == == == == == == == == == == ==" << endl; cout << "Cell Phone " << customer_record.cell_number << endl; cout << "Number of Relay Station " << customer_record.relays << endl; cout << "Minutes Used " << customer_record.call_length << " minutes" << endl; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Net Cost $" << customer_record.net_cost << endl; cout << "Tax Rate $" << customer_record.tax_rate << endl; cout << "Call Tax $" << customer_record.call_tax << endl; cout << "Total Cost of Call $" << customer_record.total_cost_of_call << endl; cout << endl << endl; } /* Name: Output (overload) Precondition: VARS all initialized in higher function VARS: ofstream out_stream call_record customer_record Postcondition: VAR customer_record contains no new data Description: Outputs the individual attributes of the call_record object customer_record to the output file stream. */ void Output(ofstream & out_stream, const call_record & customer_record) { //out_stream << endl << endl; //out_stream << "FIELD: VALUE:" << endl; //out_stream << "== == == == == == == == == == == == == == == ==" << endl; out_stream << customer_record.cell_number << "\t"; out_stream << customer_record.relays << "\t"; out_stream << customer_record.call_length << "\t"; out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2); out_stream << customer_record.net_cost << "\t"; out_stream << customer_record.tax_rate << "\t"; out_stream << customer_record.call_tax << "\t"; out_stream << customer_record.total_cost_of_call << "\t"; out_stream << endl; } int main(int argc, const char * argv[]) { call_record customer_record_n; ifstream in_stream; //declaring an input file stream ofstream out_stream; //declaring an output file stream string user_response = "y"; string input_filename = "call_data.txt"; string output_filename = "weekly_call_info.txt"; do { cout << "Use default file name? "; getline(cin, user_response); if ((user_response != "Y") && (user_response != "y")) { cout << "Enter the file name to parse: "; getline(cin, input_filename); cout << endl << endl; } in_stream.open(input_filename); out_stream.open(output_filename); if (in_stream.fail()) { cout << "Input file did not open correctly" << endl; } else { do { Input(in_stream, customer_record_n); Process(customer_record_n); Output(customer_record_n); Output(out_stream, customer_record_n); } while (!in_stream.eof()); } in_stream.close(); out_stream.close(); cout << "Would you like to do another calculation (Y or N): "; getline(cin, user_response); cout << endl << endl; } while (user_response == "y" || user_response == "Y"); return 0; }
27.290441
80
0.677219
[ "object" ]
6a5a094b58ed758e8cabde13f8bfea3f89beb2e5
6,810
cpp
C++
thrift/lib/cpp2/protocol/nimble/test/DecodeNimbleBlockTest.cpp
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
null
null
null
thrift/lib/cpp2/protocol/nimble/test/DecodeNimbleBlockTest.cpp
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
1
2022-03-03T09:40:25.000Z
2022-03-03T09:40:25.000Z
thrift/lib/cpp2/protocol/nimble/test/DecodeNimbleBlockTest.cpp
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstring> #include <folly/Format.h> #include <folly/String.h> #include <folly/container/Array.h> #include <folly/portability/GTest.h> #include <thrift/lib/cpp2/protocol/nimble/ChunkRepr.h> #include <thrift/lib/cpp2/protocol/nimble/ControlBitHelpers.h> #include <thrift/lib/cpp2/protocol/nimble/DecodeNimbleBlock.h> #include <thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.h> namespace apache { namespace thrift { namespace detail { template <ChunkRepr repr, bool vectorizeEncoder, bool vectorizeDecoder> void runRoundTripTest( const std::array<std::uint32_t, kChunksPerBlock>& unencoded) { std::array<unsigned char, kMaxBytesPerBlock> encoded; std::array<std::uint32_t, kChunksPerBlock> decoded; unsigned char control; int encodedSize = encodeNimbleBlock<repr, vectorizeEncoder>( unencoded.data(), &control, encoded.data()); std::memset(&encoded[encodedSize], 0x99, kMaxBytesPerBlock - encodedSize); int decodedSize = decodeNimbleBlock<repr, vectorizeDecoder>( control, folly::ByteRange(encoded), decoded.data()); EXPECT_TRUE(encodedSize == decodedSize && unencoded == decoded) << folly::sformat( "Round trip failed in encoding {}, with data[{}] " "(encodedSize == {}, decodedSize == {})", repr == ChunkRepr::kRaw ? "Raw" : "Zigzag", folly::join(", ", unencoded), encodedSize, decodedSize); } template <ChunkRepr repr, bool vectorizeEncoder, bool vectorizeDecoder> void runHandPickedDecodeTest() { std::array<std::uint32_t, kChunksPerBlock> testData[] = { {0, 0, 0, 0}, {(std::uint32_t)-1, 2, 3, 4}, {1000, 255, 256, (std::uint32_t)-1000}, {0, 0xABCD, 0, 0}, {0xABCDEF, 0, 0x8000, 0}, {0, 5000, 0x7FFF, (std::uint32_t)-0x7FFF}, {0xFF, 0xFFFF, 0xFFFFFF, 0xFFFFFFFF}, {(std::uint32_t)-0xFF, (std::uint32_t)-0xFFFF, (std::uint32_t)-0xFFFFFF, (std::uint32_t)-0xFFFFFFFF}, {0x80, 0x8000, 0x800000, 0x80000000}, {(std::uint32_t)-0x80, (std::uint32_t)-0x8000, (std::uint32_t)-0x800000, (std::uint32_t)-0x80000000}, }; for (const std::array<std::uint32_t, kChunksPerBlock>& unencoded : testData) { runRoundTripTest<repr, vectorizeEncoder, vectorizeDecoder>(unencoded); } } template <typename T> class NimbleDecodeTest : public ::testing::Test {}; struct NonvectorizedImpl { constexpr static bool vectorize = false; }; struct VectorizedImpl { constexpr static bool vectorize = true; }; using DecodeParamTypes = ::testing::Types<NonvectorizedImpl, VectorizedImpl>; TYPED_TEST_CASE(NimbleDecodeTest, DecodeParamTypes); template <typename T> class NimbleEncodeDecodeTest : public ::testing::Test {}; template <bool vecEnc, bool vecDec> struct EncodeDecodeParam { constexpr static bool vectorizeEncoder = vecEnc; constexpr static bool vectorizeDecoder = vecDec; }; using EncodeDecodeParamTypes = ::testing::Types< EncodeDecodeParam<false, false>, EncodeDecodeParam<false, true>, EncodeDecodeParam<true, false>, EncodeDecodeParam<true, true>>; TYPED_TEST_CASE(NimbleEncodeDecodeTest, EncodeDecodeParamTypes); TYPED_TEST(NimbleEncodeDecodeTest, DecodesHandPickedZigzag) { runHandPickedDecodeTest< ChunkRepr::kZigzag, TypeParam::vectorizeEncoder, TypeParam::vectorizeDecoder>(); } TYPED_TEST(NimbleEncodeDecodeTest, DecodesHandPickedRaw) { runHandPickedDecodeTest< ChunkRepr::kRaw, TypeParam::vectorizeEncoder, TypeParam::vectorizeDecoder>(); } template <ChunkRepr repr, bool vectorizeEncoder, bool vectorizeDecoder> void runInterestingRoundTripTest() { // clang-format off std::vector<std::uint32_t> vec { 0, 1, 100, 127, 128, 129, 200, 255, 256, 257, 10*1000, 32767, 32768, 32769, 50*1000, (1U << 16) - 1, (1U << 16), (1U << 16) + 1, 100*1000, (1U << 24) - 1, (1U << 24), (1U << 24) + 1, 20*1000*1000, 0xFFFFFFFEU, 0xFFFFFFFFU }; // clang-format on for (std::uint32_t i0 : vec) { for (std::uint32_t i1 : vec) { for (std::uint32_t i2 : vec) { for (std::uint32_t i3 : vec) { std::array<std::uint32_t, kChunksPerBlock> unencoded = { i0, i1, i2, i3}; runRoundTripTest<repr, vectorizeEncoder, vectorizeDecoder>(unencoded); } } } } } TYPED_TEST(NimbleEncodeDecodeTest, DecodesInterestingZigzag) { runInterestingRoundTripTest< ChunkRepr::kZigzag, TypeParam::vectorizeEncoder, TypeParam::vectorizeDecoder>(); } TYPED_TEST(NimbleEncodeDecodeTest, DecodesInterestingRaw) { runInterestingRoundTripTest< ChunkRepr::kRaw, TypeParam::vectorizeEncoder, TypeParam::vectorizeDecoder>(); } TYPED_TEST(NimbleDecodeTest, DecodesExtraZeros) { // Some use cases have people reserve a full chunk up front, even if they // won't need it until later on. The current iteration of the encoder won't // support these cases, but we should check it. // clang-format off std::array<unsigned char, kMaxBytesPerBlock> data = { /* chunk 0 */ 0, // = 0, 1 byte /* chunk 1 */ 0, 1, // = 256, 2 bytes, /* chunk 2 */ 0, 0, 0, 0, // = 0, 4 bytes /* chunk 3 */ 2, 0, 0, 1, // = 16777218, 4 bytes // data from next set of chunks; should be ignored. 68, 97, 118, 105, 100, }; // clang-format on std::array<std::uint32_t, kChunksPerBlock> decoded; std::uint8_t control = 0b11'11'10'01; int bytesDecoded = decodeNimbleBlock<ChunkRepr::kRaw, TypeParam::vectorize>( control, folly::ByteRange(data), decoded.data()); EXPECT_EQ(11, bytesDecoded); EXPECT_EQ(0, decoded[0]); EXPECT_EQ(256, decoded[1]); EXPECT_EQ(0, decoded[2]); EXPECT_EQ(16777218, decoded[3]); bytesDecoded = decodeNimbleBlock<ChunkRepr::kZigzag, TypeParam::vectorize>( control, folly::ByteRange(data), decoded.data()); EXPECT_EQ(11, bytesDecoded); EXPECT_EQ(zigzagDecode(0), decoded[0]); EXPECT_EQ(zigzagDecode(256), decoded[1]); EXPECT_EQ(zigzagDecode(0), decoded[2]); EXPECT_EQ(zigzagDecode(16777218), decoded[3]); } } // namespace detail } // namespace thrift } // namespace apache
31.82243
80
0.681791
[ "vector" ]
6a5e7ccfce50da5d8670759f92ebd4a775c48953
39,850
cc
C++
src/clustering/table_contract/coordinator/calculate_contracts.cc
zadcha/rethinkdb
bb4f5cc28242dc1e29e9a46a8a931ec54420070c
[ "Apache-2.0" ]
21,684
2015-01-01T03:42:20.000Z
2022-03-30T13:32:44.000Z
src/clustering/table_contract/coordinator/calculate_contracts.cc
RethonkDB/rethonkdb
8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee
[ "Apache-2.0" ]
4,067
2015-01-01T00:04:51.000Z
2022-03-30T13:42:56.000Z
src/clustering/table_contract/coordinator/calculate_contracts.cc
RethonkDB/rethonkdb
8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee
[ "Apache-2.0" ]
1,901
2015-01-01T21:05:59.000Z
2022-03-21T08:14:25.000Z
// Copyright 2010-2015 RethinkDB, all rights reserved. #include "clustering/table_contract/coordinator/calculate_contracts.hpp" #include "clustering/table_contract/branch_history_gc.hpp" #include "clustering/table_contract/cpu_sharding.hpp" #include "logger.hpp" /* A `contract_ack_t` is not necessarily homogeneous. It may have different `version_t`s for different regions, and a region with a single `version_t` may need to be split further depending on the branch history. Since `calculate_contract()` assumes it's processing a homogeneous input, we need to break the `contract_ack_t` into homogeneous pieces. `contract_ack_frag_t` is like a homogeneous version of `contract_ack_t`; in place of the `region_map_t<version_t>` it has a single `state_timestamp_t`. Use `break_ack_into_fragments()` to convert a `contract_ack_t` into a `region_map_t<contract_ack_frag_t>`. */ class contract_ack_frag_t { public: bool operator==(const contract_ack_frag_t &x) const { return state == x.state && version == x.version && common_ancestor == x.common_ancestor && branch == x.branch; } bool operator!=(const contract_ack_frag_t &x) const { return !(*this == x); } /* `state` and `branch` are the same as the corresponding fields of the original `contract_ack_t` */ contract_ack_t::state_t state; optional<branch_id_t> branch; /* `version` is the value of the `version` field of the original `contract_ack_t` for the specific sub-region this fragment applies to. */ optional<version_t> version; /* `common_ancestor` is the timestamp of the last common ancestor of the original `contract_ack_t` and the `current_branch` in the Raft state for the specific sub-region this fragment applies to. If `version` is blank, this will always be blank; if `version` is present, `common_ancestor` might or might not be blank depending on whether we expect to use the value. */ optional<state_timestamp_t> common_ancestor; }; region_map_t<contract_ack_frag_t> break_ack_into_fragments( const region_t &region, const contract_ack_t &ack, const region_map_t<branch_id_t> &current_branches, const branch_history_reader_t *raft_branch_history, bool compute_common_ancestor) { contract_ack_frag_t base_frag; base_frag.state = ack.state; base_frag.branch = ack.branch; if (!static_cast<bool>(ack.version)) { return region_map_t<contract_ack_frag_t>(region, base_frag); } else if (compute_common_ancestor) { branch_history_combiner_t combined_branch_history( raft_branch_history, &ack.branch_history); /* Fragment over branches and then over versions within each branch. */ return ack.version->map_multi(region, [&](const region_t &ack_version_reg, const version_t &vers) { base_frag.version = make_optional(vers); return current_branches.map_multi(ack_version_reg, [&](const region_t &branch_reg, const branch_id_t &branch) { region_map_t<version_t> points_on_canonical_branch; try { points_on_canonical_branch = version_find_branch_common(&combined_branch_history, vers, branch, branch_reg); } catch (const missing_branch_exc_t &) { #ifndef NDEBUG crash("Branch history is incomplete"); #else logERR("The branch history is incomplete. This probably means " "that there is a bug in RethinkDB. Please report this " "at https://github.com/rethinkdb/rethinkdb/issues/ ."); /* Recover by using the root branch */ points_on_canonical_branch = region_map_t<version_t>(region_t::universe(), version_t::zero()); #endif } return points_on_canonical_branch.map(branch_reg, [&](const version_t &common_vers) { base_frag.common_ancestor = make_optional(common_vers.timestamp); return base_frag; }); }); }); } else { return ack.version->map(region, [&](const version_t &vers) { base_frag.version = make_optional(vers); return base_frag; }); } } /* `invisible_to_majority_of_set()` returns `true` if `target` definitely cannot be seen by a majority of the servers in `judges`. If we can't see one of the servers in `judges`, we'll assume it can see `target` to reduce spurious failoves. */ bool invisible_to_majority_of_set( const server_id_t &target, const std::set<server_id_t> &judges, watchable_map_t<std::pair<server_id_t, server_id_t>, empty_value_t> * connections_map) { size_t count = 0; for (const server_id_t &s : judges) { if (connections_map->get_key(std::make_pair(s, target)).has_value() || !connections_map->get_key(std::make_pair(s, s)).has_value()) { ++count; } } return !(count > judges.size() / 2); } /* A small helper function for `calculate_contract()` to test whether a given replica is currently streaming. */ bool is_streaming( const contract_t &old_c, const std::map<server_id_t, contract_ack_frag_t> &acks, server_id_t server) { auto it = acks.find(server); if (it != acks.end() && (it->second.state == contract_ack_t::state_t::secondary_streaming || (static_cast<bool>(old_c.primary) && old_c.primary->server == server))) { return true; } else { return false; } } /* `calculate_contract()` calculates a new contract for a region. Whenever any of the inputs changes, the coordinator will call `update_contract()` to compute a contract for each range of keys. The new contract will often be the same as the old, in which case it doesn't get a new contract ID. */ contract_t calculate_contract( /* The old contract that contains this region. */ const contract_t &old_c, /* The user-specified configuration for the shard containing this region. */ const table_config_t::shard_t &config, /* Contract acks from replicas regarding `old_c`. If a replica hasn't sent us an ack *specifically* for `old_c`, it won't appear in this map; we don't include acks for contracts that were in the same region before `old_c`. */ const std::map<server_id_t, contract_ack_frag_t> &acks, /* This `watchable_map_t` will have an entry for (X, Y) if we can see server X and server X can see server Y. */ watchable_map_t<std::pair<server_id_t, server_id_t>, empty_value_t> * connections_map) { contract_t new_c = old_c; /* If there are new servers in `config.all_replicas`, add them to `c.replicas` */ new_c.replicas.insert(config.all_replicas.begin(), config.all_replicas.end()); /* If there is a mismatch between `config.voting_replicas()` and `c.voters`, then add and/or remove voters until both sets match. There are three important restrictions we have to consider here: 1. We should not remove voters if that would reduce the total number of voters below the minimum of the size of the current voter set and the size of the configured voter set. Consider the case where a user wants to replace a few replicas by different ones. Without this restriction, we would often remove all the old replicas from the voters set before enough of the new replicas would become streaming to replace them. 2. To increase availability in some scenarios, we also don't remove replicas if that would mean being left with less than a majority of streaming replicas. 3. Only replicas that are streaming are guaranteed to have a complete branch history. Once we make a replica voting, some parts of our logic assume that the branch history is intact (most importantly our call to `break_ack_into_fragments()` in `calculate_all_contracts()`). To avoid this condition, we only add a replica to the voters list after it has started streaming. See https://github.com/rethinkdb/rethinkdb/issues/4866 for more details. */ std::set<server_id_t> config_voting_replicas = config.voting_replicas(); if (!static_cast<bool>(old_c.temp_voters) && old_c.voters != config_voting_replicas) { bool voters_changed = false; std::set<server_id_t> new_voters = old_c.voters; /* Step 1: Check if we can add any voters */ for (const server_id_t &server : config_voting_replicas) { if (old_c.voters.count(server)) { /* The replica is already a voter */ continue; } if (is_streaming(old_c, acks, server)) { /* The replica is streaming. We can add it to the voter set. */ new_voters.insert(server); voters_changed = true; } } /* Step 2: Remove voters */ /* We try to remove non-streaming replicas first before we start removing streaming ones to maximize availability in case a replica fails. */ std::list<server_id_t> to_remove; for (const server_id_t &server : new_voters) { if (config_voting_replicas.count(server) > 0) { /* The replica should remain a voter */ continue; } if (is_streaming(old_c, acks, server)) { /* The replica is streaming. Put it at the end of the `to_remove` list. */ to_remove.push_back(server); } else { /* The replica is not streaming. Removing it doesn't hurt availability, so we put it at the front of the `to_remove` list. */ to_remove.push_front(server); } } size_t num_streaming = 0; for (const server_id_t &server : new_voters) { if (is_streaming(old_c, acks, server)) { ++num_streaming; } } size_t min_voters_size = std::min(old_c.voters.size(), config_voting_replicas.size()); for (const server_id_t &server_to_remove : to_remove) { /* Check if we can remove more voters without going below `min_voters_size`, and without losing a majority of streaming voters. */ size_t remaining_streaming = is_streaming(old_c, acks, server_to_remove) ? num_streaming - 1 : num_streaming; size_t remaining_total = new_voters.size() - 1; bool would_lose_majority = remaining_streaming <= remaining_total / 2; if (would_lose_majority || new_voters.size() <= min_voters_size) { break; } new_voters.erase(server_to_remove); voters_changed = true; } /* Step 3: If anything changed, stage the new voter set into `temp_voters` */ rassert(voters_changed == (old_c.voters != new_voters)); if (voters_changed) { new_c.temp_voters.set(new_voters); } } /* If we already initiated a voter change by setting `temp_voters`, it might be time to commit that change by setting `voters` to `temp_voters`. */ if (static_cast<bool>(old_c.temp_voters)) { /* Before we change `voters`, we have to make sure that we'll preserve the invariant that every acked write is on a majority of `voters`. This is mostly the job of the primary; it will not report `primary_ready` unless it is requiring acks from a majority of both `voters` and `temp_voters` before acking writes to the client, *and* it has ensured that every write that was acked before that policy was implemented has been backfilled to a majority of `temp_voters`. So we can't switch voters unless the primary reports `primary_ready`. See `primary_execution_t::is_contract_ackable` for the detailed semantics of the `primary_ready` state. */ if (static_cast<bool>(old_c.primary) && acks.count(old_c.primary->server) == 1 && acks.at(old_c.primary->server).state == contract_ack_t::state_t::primary_ready) { /* The `acks` we just checked are based on `old_c`, so we really shouldn't commit any different set of `temp_voters`. */ guarantee(new_c.temp_voters == old_c.temp_voters); /* OK, it's safe to commit. */ new_c.voters = *new_c.temp_voters; new_c.temp_voters.reset(); } } /* `visible_voters` includes all members of `voters` and `temp_voters` which could be visible to a majority of `voters` (and `temp_voters`, if `temp_voters` exists). Note that if the coordinator can't see server X, it will assume server X can see every other server; this reduces spurious failovers when the coordinator loses contact with other servers. */ std::set<server_id_t> visible_voters; for (const server_id_t &server : new_c.replicas) { if (new_c.voters.count(server) == 0 && (!static_cast<bool>(new_c.temp_voters) || new_c.temp_voters->count(server) == 0)) { continue; } if (invisible_to_majority_of_set(server, new_c.voters, connections_map)) { continue; } if (static_cast<bool>(new_c.temp_voters)) { if (invisible_to_majority_of_set( server, *new_c.temp_voters, connections_map)) { continue; } } visible_voters.insert(server); } /* If a server was removed from `config.replicas` and `c.voters` but it's still in `c.replicas`, then remove it. And if it's primary, then make it not be primary. */ bool should_kill_primary = false; for (const server_id_t &server : old_c.replicas) { if (config.all_replicas.count(server) == 0 && new_c.voters.count(server) == 0 && (!static_cast<bool>(new_c.temp_voters) || new_c.temp_voters->count(server) == 0)) { new_c.replicas.erase(server); if (static_cast<bool>(old_c.primary) && old_c.primary->server == server) { /* Actual killing happens further down */ should_kill_primary = true; } } } /* If we don't have a primary, choose a primary. Servers are not eligible to be a primary unless they are carrying every acked write. There will be at least one eligible server if and only if we have reports from a majority of `new_c.voters`. In addition, we must choose `config.primary_replica` if it is eligible. If `config.primary_replica` has not sent an ack, we must wait for the failover timeout to elapse before electing a different replica. This is to make sure that we won't elect the wrong replica simply because the user's designated primary took a little longer to send the ack. */ if (!static_cast<bool>(old_c.primary) && !old_c.after_emergency_repair) { /* We have an invariant that every acked write must be on the path from the root of the branch history to `old_c.branch`. So we project each voter's state onto that path, then sort them by position along the path. Any voter that is at least as up to date, according to that metric, as more than half of the voters (including itself) is eligible. We also take into account whether a server is visible to its peers when deciding which server to select. */ /* First, collect the states from the servers, and sort them by how up-to-date they are. Note that we use the server ID as a secondary sorting key. This mean we tend to pick the same server if we run the algorithm twice; this helps to reduce unnecessary fragmentation. */ std::vector<std::pair<state_timestamp_t, server_id_t> > sorted_candidates; for (const server_id_t &server : new_c.voters) { if (acks.count(server) == 1 && acks.at(server).state == contract_ack_t::state_t::secondary_need_primary) { sorted_candidates.push_back( std::make_pair(*(acks.at(server).common_ancestor), server)); } } std::sort(sorted_candidates.begin(), sorted_candidates.end()); /* Second, determine which servers are eligible to become primary on the basis of their data and their visibility to their peers. */ std::vector<server_id_t> eligible_candidates; for (size_t i = 0; i < sorted_candidates.size(); ++i) { server_id_t server = sorted_candidates[i].second; /* If the server is not visible to more than half of its peers, then it is not eligible to be primary */ if (visible_voters.count(server) == 0) { continue; } /* `up_to_date_count` is the number of servers that `server` is at least as up-to-date as. We know `server` must be at least as up-to-date as itself and all of the servers that are earlier in the list. */ size_t up_to_date_count = i + 1; /* If there are several servers with the same timestamp, they will appear together in the list. So `server` may be at least as up-to-date as some of the servers that appear after it in the list. */ while (up_to_date_count < sorted_candidates.size() && sorted_candidates[up_to_date_count].first == sorted_candidates[i].first) { ++up_to_date_count; } /* OK, now `up_to_date_count` is the number of servers that this server is at least as up-to-date as. */ if (up_to_date_count > new_c.voters.size() / 2) { eligible_candidates.push_back(server); } } /* OK, now we can pick a primary. */ auto it = std::find(eligible_candidates.begin(), eligible_candidates.end(), config.primary_replica); if (it != eligible_candidates.end()) { /* The user's designated primary is eligible, so use it. */ contract_t::primary_t p; p.server = config.primary_replica; new_c.primary.set(p); } else if (!eligible_candidates.empty()) { /* The user's designated primary is ineligible. We have to decide if we'll wait for the user's designated primary to become eligible, or use one of the other eligible candidates. */ if (!config.primary_replica.get_uuid().is_nil() && visible_voters.count(config.primary_replica) == 1 && acks.count(config.primary_replica) == 0) { /* The user's designated primary is visible to a majority of its peers, and the only reason it was disqualified is because we haven't seen an ack from it yet. So we'll wait for it to send in an ack rather than electing a different primary. */ } else { /* We won't wait for it. */ contract_t::primary_t p; /* `eligible_candidates` is ordered by how up-to-date they are */ p.server = eligible_candidates.back(); new_c.primary.set(p); } } } else if (!static_cast<bool>(old_c.primary) && old_c.after_emergency_repair) { /* If we recently completed an emergency repair operation, we use a different procedure to pick the primary: we require all voters to be present, and then we pick the voter with the highest version, regardless of `current_branch`. The reason we can't take `current_branch` into account is that the emergency repair might create gaps in the branch history, so we can't reliably compute each replica's position on `current_branch`. The reason we require all replicas to be present is to make the emergency repair safer. For example, imagine if a table has three voters, A, B, and C. Suppose that voter B is lagging behind the others, and voter C is removed by emergency repair. Then the normal algorithm could pick voter B as the primary, even though it's missing some data. */ server_id_t best_primary = server_id_t::from_server_uuid(nil_uuid()); state_timestamp_t best_timestamp = state_timestamp_t::zero(); bool all_present = true; for (const server_id_t &server : new_c.voters) { if (acks.count(server) == 1 && acks.at(server).state == contract_ack_t::state_t::secondary_need_primary) { state_timestamp_t timestamp = acks.at(server).version->timestamp; if (best_primary.get_uuid().is_nil() || timestamp > best_timestamp) { best_primary = server; best_timestamp = timestamp; } } else { all_present = false; break; } } if (all_present) { contract_t::primary_t p; p.server = best_primary; new_c.primary.set(p); } } /* Sometimes we already have a primary, but we need to pick a different one. There are three such situations: - The existing primary is disconnected - The existing primary isn't `config.primary_replica`, and `config.primary_replica` is ready to take over the role - `config.primary_replica` isn't ready to take over the role, but the existing primary isn't even supposed to be a replica anymore. In the first situation, we'll simply remove `c.primary`. In the second and third situations, we'll first set `c.primary->warm_shutdown` to `true`, and then only once the primary acknowledges that, we'll remove `c.primary`. Either way, once the replicas acknowledge the contract in which we removed `c.primary`, the logic earlier in this function will select a new primary. Note that we can't go straight from the old primary to the new one; we need a majority of replicas to promise to stop receiving updates from the old primary before it's safe to elect a new one. */ if (static_cast<bool>(old_c.primary)) { /* Note we already checked for the case where the old primary wasn't supposed to be a replica. If this is so, then `should_kill_primary` will already be set to `true`. */ /* Check if we need to do an auto-failover. The precise form of this condition isn't important for correctness. If we do an auto-failover when the primary isn't actually dead, or don't do an auto-failover when the primary is actually dead, the worst that will happen is we'll lose availability. */ if (!should_kill_primary && visible_voters.count(old_c.primary->server) == 0) { should_kill_primary = true; } if (should_kill_primary) { new_c.primary.reset(); } else if (old_c.primary->server != config.primary_replica) { /* The old primary is still a valid replica, but it isn't equal to `config.primary_replica`. So we have to do a hand-over to ensure that after we kill the primary, `config.primary_replica` will be a valid candidate. */ if (old_c.primary->hand_over != make_optional(config.primary_replica)) { /* We haven't started the hand-over yet, or we're in the middle of a hand-over to a different primary. */ if (acks.count(config.primary_replica) == 1 && acks.at(config.primary_replica).state == contract_ack_t::state_t::secondary_streaming && visible_voters.count(config.primary_replica) == 1) { /* The new primary is ready, so begin the hand-over. */ new_c.primary->hand_over.set(config.primary_replica); } else { /* We're not ready to switch to the new primary yet. */ if (static_cast<bool>(old_c.primary->hand_over)) { /* We were in the middle of a hand over to a different primary, and then the user changed `config.primary_replica`. But the new primary isn't ready yet, so cancel the old hand-over. (This is very uncommon.) */ new_c.primary->hand_over.reset(); } } } else { /* We're already in the process of handing over to the new primary. */ if (acks.count(old_c.primary->server) == 1 && acks.at(old_c.primary->server).state == contract_ack_t::state_t::primary_ready) { /* The hand over is complete. Now it's safe to stop the old primary. The new primary will be started later, after a majority of the replicas acknowledge that they are no longer listening for writes from the old primary. See `primary_execution_t::is_contract_ackable` for a detailed explanation of what the `primary_ready` state implies. */ new_c.primary.reset(); } else if (visible_voters.count(config.primary_replica) == 0) { /* Something went wrong with the new primary before the hand-over was complete. So abort the hand-over. */ new_c.primary->hand_over.reset(); } } } else { if (static_cast<bool>(old_c.primary->hand_over)) { /* We were in the middle of a hand over, but then the user changed `config.primary_replica` back to what it was before. (This is very uncommon.) */ new_c.primary->hand_over.reset(); } } } return new_c; } /* `calculate_all_contracts()` is sort of like `calculate_contract()` except that it applies to the whole set of contracts instead of to a single contract. It takes the inputs that `calculate_contract()` needs, but in sharded form; then breaks the key space into small enough chunks that the inputs are homogeneous across each chunk; then calls `calculate_contract()` on each chunk. The output is in the form of a diff instead of a set of new contracts. We need a diff to put in the `table_raft_state_t::change_t::new_contracts_t`, and we need to compute the diff anyway in order to reuse contract IDs for contracts that haven't changed, so it makes sense to combine those two diff processes. */ void calculate_all_contracts( const table_raft_state_t &old_state, const std::map<contract_id_t, std::map<server_id_t, contract_ack_t> > &acks, watchable_map_t<std::pair<server_id_t, server_id_t>, empty_value_t> *connections_map, std::set<contract_id_t> *remove_contracts_out, std::map<contract_id_t, std::pair<region_t, contract_t> > *add_contracts_out, std::map<region_t, branch_id_t> *register_current_branches_out, std::set<branch_id_t> *remove_branches_out, branch_history_t *add_branches_out) { ASSERT_FINITE_CORO_WAITING; /* Initially, we put every branch into `remove_branches_out`. Then as we process contracts, we "mark branches live" by removing them from `remove_branches_out`. */ for (const auto &pair : old_state.branch_history.branches) { remove_branches_out->insert(pair.first); } std::vector<region_t> new_contract_region_vector; std::vector<contract_t> new_contract_vector; /* We want to break the key-space into sub-regions small enough that the contract, table config, and ack versions are all constant across the sub-region. First we iterate over all contracts: */ for (const std::pair<contract_id_t, std::pair<region_t, contract_t> > &cpair : old_state.contracts) { /* Next iterate over all shards of the table config and find the ones that overlap the contract in question: */ for (size_t shard_index = 0; shard_index < old_state.config.config.shards.size(); ++shard_index) { region_t region = region_intersection( cpair.second.first, region_t(old_state.config.shard_scheme.get_shard_range(shard_index))); if (region_is_empty(region)) { continue; } /* Find acks for this contract. If there aren't any acks for this contract, then `acks` might not even have an empty map, so we need to construct an empty map in that case. */ const std::map<server_id_t, contract_ack_t> *this_contract_acks; { static const std::map<server_id_t, contract_ack_t> empty_ack_map; auto it = acks.find(cpair.first); this_contract_acks = (it == acks.end()) ? &empty_ack_map : &it->second; } /* Now collect the acks for this contract into `ack_frags`. `ack_frags` is homogeneous at first and then it gets fragmented as we iterate over `acks`. */ region_map_t<std::map<server_id_t, contract_ack_frag_t> > frags_by_server( region); for (const auto &pair : *this_contract_acks) { /* Sanity-check the ack */ DEBUG_ONLY_CODE(pair.second.sanity_check( pair.first, cpair.first, old_state)); /* There are two situations where we don't compute the common ancestor: 1. If the server sending the ack is not in `voters` or `temp_voters` 2. If the contract has the `after_emergency_repair` flag set In these situations, we don't need the common ancestor, but computing it might be dangerous because the branch history might be incomplete. */ bool compute_common_ancestor = (cpair.second.second.voters.count(pair.first) == 1 || (static_cast<bool>(cpair.second.second.temp_voters) && cpair.second.second.temp_voters->count(pair.first) == 1)) && !cpair.second.second.after_emergency_repair; region_map_t<contract_ack_frag_t> frags = break_ack_into_fragments( region, pair.second, old_state.current_branches, &old_state.branch_history, compute_common_ancestor); frags.visit(region, [&](const region_t &reg, const contract_ack_frag_t &frag) { frags_by_server.visit_mutable(reg, [&](const region_t &, std::map<server_id_t, contract_ack_frag_t> *acks_map) { auto res = acks_map->insert( std::make_pair(pair.first, frag)); guarantee(res.second); }); }); } frags_by_server.visit(region, [&](const region_t &reg, const std::map<server_id_t, contract_ack_frag_t> &acks_map) { /* We've finally collected all the inputs to `calculate_contract()` and broken the key space into regions across which the inputs are homogeneous. So now we can actually call it. */ const contract_t &old_contract = cpair.second.second; contract_t new_contract = calculate_contract( old_contract, old_state.config.config.shards[shard_index], acks_map, connections_map); /* Register a branch if a primary is asking us to */ optional<branch_id_t> registered_new_branch; if (static_cast<bool>(old_contract.primary) && static_cast<bool>(new_contract.primary) && old_contract.primary->server == new_contract.primary->server && acks_map.count(old_contract.primary->server) == 1 && acks_map.at(old_contract.primary->server).state == contract_ack_t::state_t::primary_need_branch) { branch_id_t to_register = *acks_map.at(old_contract.primary->server).branch; bool already_registered = true; old_state.current_branches.visit(reg, [&](const region_t &, const branch_id_t &cur_branch) { already_registered &= (cur_branch == to_register); }); if (!already_registered) { auto res = register_current_branches_out->insert( std::make_pair(reg, to_register)); guarantee(res.second); /* Due to branch garbage collection on the executor, the branch history in the contract_ack might be incomplete. Usually this isn't a problem, because the executor is only going to garbage collect branches when it is sure that the current branches are already present in the Raft state. In that case `copy_branch_history_for_branch()` is not going to traverse to the GCed branches. However this assumption no longer holds if the Raft state has just been overwritten by an emergency repair operation. Hence we ignore missing branches in the copy operation. */ bool ignore_missing_branches = old_contract.after_emergency_repair; copy_branch_history_for_branch( to_register, this_contract_acks->at( old_contract.primary->server).branch_history, old_state, ignore_missing_branches, add_branches_out); registered_new_branch = make_optional(to_register); } } /* Check to what extent we can confirm that the replicas are on `current_branch`. We'll use this to determine when it's safe to GC and whether we can switch off the `after_emergency_repair` flag (if it was on). */ bool can_gc_branch_history = true, can_end_after_emergency_repair = true; for (const server_id_t &server : new_contract.replicas) { auto it = this_contract_acks->find(server); if (it == this_contract_acks->end() || ( it->second.state != contract_ack_t::state_t::primary_ready && it->second.state != contract_ack_t::state_t::secondary_streaming)) { /* At least one replica can't be confirmed to be on `current_branch`, so we should keep the branch history around in order to make it easy for that replica to rejoin later. */ can_gc_branch_history = false; if (new_contract.voters.count(server) == 1 || (static_cast<bool>(new_contract.temp_voters) && new_contract.temp_voters->count(server) == 1)) { /* If the `after_emergency_repair` flag is set to `true`, we need to leave it set to `true` until we can confirm that the branch history is intact. */ can_end_after_emergency_repair = false; } } } /* Branch history GC. The key decision is whether we should only keep `current_branch`, or whether we need to keep all of its ancestors too. */ old_state.current_branches.visit(reg, [&](const region_t &subregion, const branch_id_t &current_branch) { if (!current_branch.is_nil()) { if (can_gc_branch_history) { remove_branches_out->erase(current_branch); } else { mark_all_ancestors_live(current_branch, subregion, &old_state.branch_history, remove_branches_out); } } }); if (can_end_after_emergency_repair) { new_contract.after_emergency_repair = false; } new_contract_region_vector.push_back(reg); new_contract_vector.push_back(new_contract); }); } } /* Put the new contracts into a `region_map_t` to coalesce adjacent regions that have identical contracts */ region_map_t<contract_t> new_contract_region_map = region_map_t<contract_t>::from_unordered_fragments( std::move(new_contract_region_vector), std::move(new_contract_vector)); /* Slice the new contracts by CPU shard and by user shard, so that no contract spans more than one CPU shard or user shard. */ std::map<region_t, contract_t> new_contract_map; for (size_t cpu = 0; cpu < CPU_SHARDING_FACTOR; ++cpu) { region_t region = cpu_sharding_subspace(cpu); for (size_t shard = 0; shard < old_state.config.config.shards.size(); ++shard) { region.inner = old_state.config.shard_scheme.get_shard_range(shard); new_contract_region_map.visit(region, [&](const region_t &reg, const contract_t &contract) { guarantee(reg.beg == region.beg && reg.end == region.end); new_contract_map.insert(std::make_pair(reg, contract)); }); } } /* Diff the new contracts against the old contracts */ for (const auto &cpair : old_state.contracts) { auto it = new_contract_map.find(cpair.second.first); if (it != new_contract_map.end() && it->second == cpair.second.second) { /* The contract was unchanged. Remove it from `new_contract_map` to signal that we don't need to assign it a new ID. */ new_contract_map.erase(it); } else { /* The contract was changed. So delete the old one. */ remove_contracts_out->insert(cpair.first); } } for (const auto &pair : new_contract_map) { /* The contracts remaining in `new_contract_map` are actually new; whatever contracts used to cover their region have been deleted. So assign them contract IDs and export them. */ add_contracts_out->insert(std::make_pair(generate_uuid(), pair)); } }
52.228047
89
0.605471
[ "vector" ]
6a6047bc41e561201492d35f94add55c1700e209
1,759
cpp
C++
python/bindings_so3.cpp
pettni/manif
81e9498af69417e4b2ed463d2bcf4b57007c1ca8
[ "MIT" ]
1
2021-02-19T07:05:48.000Z
2021-02-19T07:05:48.000Z
python/bindings_so3.cpp
xusong0zju/manif
6138a90eb3866002fd7ed7e0d79e3ab4420ae775
[ "MIT" ]
null
null
null
python/bindings_so3.cpp
xusong0zju/manif
6138a90eb3866002fd7ed7e0d79e3ab4420ae775
[ "MIT" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/operators.h> #include <pybind11/eigen.h> #include <pybind11/stl.h> #include "manif/SO3.h" #include "bindings_optional.h" #include "bindings_lie_group_base.h" #include "bindings_tangent_base.h" namespace py = pybind11; void wrap_SO3(py::module &m) { using Scalar = manif::SO3d::Scalar; using Quaternion = Eigen::Quaternion<Scalar>; py::class_<manif::LieGroupBase<manif::SO3d>, std::unique_ptr<manif::LieGroupBase<manif::SO3d>, py::nodelete>> SO3_base(m, "_SO3Base"); py::class_<manif::TangentBase<manif::SO3Tangentd>, std::unique_ptr<manif::TangentBase<manif::SO3Tangentd>, py::nodelete>> SO3_tan_base(m, "_SO3TangentBase"); py::class_<manif::SO3d, manif::LieGroupBase<manif::SO3d>> SO3(m, "SO3"); py::class_<manif::SO3Tangentd, manif::TangentBase<manif::SO3Tangentd>> SO3_tan(m, "SO3Tangent"); // group SO3.def(py::init<const Scalar, const Scalar, const Scalar>()); SO3.def(py::init<const Scalar, const Scalar, const Scalar, const Scalar>()); // SO3.def(py::init<const Quaternion&>()); // SO3.def(py::init<const Eigen::AngleAxis<Scalar>&>()); wrap_lie_group_base<manif::SO3d, manif::LieGroupBase<manif::SO3d>>(SO3); SO3.def("transform", &manif::SO3d::transform); SO3.def("rotation", &manif::SO3d::rotation); SO3.def("x", &manif::SO3d::x); SO3.def("y", &manif::SO3d::y); SO3.def("z", &manif::SO3d::z); SO3.def("w", &manif::SO3d::w); // SO3.def("quat", &manif::SO3d::quat); SO3.def("normalize", &manif::SO3d::normalize); // tangent wrap_tangent_base<manif::SO3Tangentd, manif::TangentBase<manif::SO3Tangentd>>(SO3_tan); SO3_tan.def("x", &manif::SO3Tangentd::x); SO3_tan.def("y", &manif::SO3Tangentd::y); SO3_tan.def("z", &manif::SO3Tangentd::z); }
34.490196
159
0.69187
[ "transform" ]
6a683e5f5d193a6adc13b8a12bd4d75894fc0d8e
16,799
cc
C++
content/browser/renderer_host/media/service_video_capture_provider_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
content/browser/renderer_host/media/service_video_capture_provider_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
content/browser/renderer_host/media/service_video_capture_provider_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/media/service_video_capture_provider.h" #include "base/run_loop.h" #include "base/test/mock_callback.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "content/public/browser/video_capture_device_launcher.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/video_capture/public/mojom/device_factory.mojom.h" #include "services/video_capture/public/mojom/device_factory_provider.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::Mock; using testing::Invoke; using testing::_; namespace content { static const std::string kStubDeviceId = "StubDevice"; static const media::VideoCaptureParams kArbitraryParams; static const base::WeakPtr<media::VideoFrameReceiver> kNullReceiver; static const auto kIgnoreLogMessageCB = base::BindRepeating([](const std::string&) {}); class MockServiceConnector : public ServiceVideoCaptureProvider::ServiceConnector { public: MockServiceConnector() {} MOCK_METHOD1(BindFactoryProvider, void(video_capture::mojom::DeviceFactoryProviderPtr* provider)); }; class MockDeviceFactoryProvider : public video_capture::mojom::DeviceFactoryProvider { public: void ConnectToDeviceFactory( video_capture::mojom::DeviceFactoryRequest request) override { DoConnectToDeviceFactory(request); } MOCK_METHOD1(SetShutdownDelayInSeconds, void(float seconds)); MOCK_METHOD1(DoConnectToDeviceFactory, void(video_capture::mojom::DeviceFactoryRequest& request)); }; class MockDeviceFactory : public video_capture::mojom::DeviceFactory { public: void GetDeviceInfos(GetDeviceInfosCallback callback) override { DoGetDeviceInfos(callback); } void CreateDevice(const std::string& device_id, video_capture::mojom::DeviceRequest device_request, CreateDeviceCallback callback) override { DoCreateDevice(device_id, &device_request, callback); } void AddSharedMemoryVirtualDevice( const media::VideoCaptureDeviceInfo& device_info, video_capture::mojom::ProducerPtr producer, video_capture::mojom::SharedMemoryVirtualDeviceRequest virtual_device) override { DoAddVirtualDevice(device_info, producer.get(), &virtual_device); } void AddTextureVirtualDevice(const media::VideoCaptureDeviceInfo& device_info, video_capture::mojom::TextureVirtualDeviceRequest virtual_device) override { NOTIMPLEMENTED(); } MOCK_METHOD1(DoGetDeviceInfos, void(GetDeviceInfosCallback& callback)); MOCK_METHOD3(DoCreateDevice, void(const std::string& device_id, video_capture::mojom::DeviceRequest* device_request, CreateDeviceCallback& callback)); MOCK_METHOD3(DoAddVirtualDevice, void(const media::VideoCaptureDeviceInfo& device_info, video_capture::mojom::ProducerProxy* producer, video_capture::mojom::SharedMemoryVirtualDeviceRequest* virtual_device_request)); }; class MockVideoCaptureDeviceLauncherCallbacks : public VideoCaptureDeviceLauncher::Callbacks { public: void OnDeviceLaunched( std::unique_ptr<LaunchedVideoCaptureDevice> device) override { DoOnDeviceLaunched(&device); } MOCK_METHOD1(DoOnDeviceLaunched, void(std::unique_ptr<LaunchedVideoCaptureDevice>* device)); MOCK_METHOD0(OnDeviceLaunchFailed, void()); MOCK_METHOD0(OnDeviceLaunchAborted, void()); }; class ServiceVideoCaptureProviderTest : public testing::Test { public: ServiceVideoCaptureProviderTest() : factory_provider_binding_(&mock_device_factory_provider_), device_factory_binding_(&mock_device_factory_) {} ~ServiceVideoCaptureProviderTest() override {} protected: void SetUp() override { auto mock_service_connector = std::make_unique<MockServiceConnector>(); mock_service_connector_ = mock_service_connector.get(); provider_ = std::make_unique<ServiceVideoCaptureProvider>( std::move(mock_service_connector), kIgnoreLogMessageCB); ON_CALL(*mock_service_connector_, BindFactoryProvider(_)) .WillByDefault( Invoke([this](video_capture::mojom::DeviceFactoryProviderPtr* device_factory_provider) { if (factory_provider_binding_.is_bound()) factory_provider_binding_.Close(); factory_provider_binding_.Bind( mojo::MakeRequest(device_factory_provider)); })); ON_CALL(mock_device_factory_provider_, DoConnectToDeviceFactory(_)) .WillByDefault( Invoke([this](video_capture::mojom::DeviceFactoryRequest& request) { if (device_factory_binding_.is_bound()) device_factory_binding_.Close(); device_factory_binding_.Bind(std::move(request)); wait_for_connection_to_service_.Quit(); })); } void TearDown() override {} base::test::ScopedTaskEnvironment scoped_task_environment_; MockServiceConnector* mock_service_connector_; MockDeviceFactoryProvider mock_device_factory_provider_; mojo::Binding<video_capture::mojom::DeviceFactoryProvider> factory_provider_binding_; MockDeviceFactory mock_device_factory_; mojo::Binding<video_capture::mojom::DeviceFactory> device_factory_binding_; std::unique_ptr<ServiceVideoCaptureProvider> provider_; base::MockCallback<VideoCaptureProvider::GetDeviceInfosCallback> results_cb_; base::MockCallback< video_capture::mojom::DeviceFactory::GetDeviceInfosCallback> service_cb_; base::RunLoop wait_for_connection_to_service_; private: DISALLOW_COPY_AND_ASSIGN(ServiceVideoCaptureProviderTest); }; // Tests that if connection to the service is lost during an outstanding call // to GetDeviceInfos(), the callback passed into GetDeviceInfos() still gets // invoked. TEST_F(ServiceVideoCaptureProviderTest, GetDeviceInfosAsyncInvokesCallbackWhenLosingConnection) { base::RunLoop run_loop; video_capture::mojom::DeviceFactory::GetDeviceInfosCallback callback_to_be_called_by_service; base::RunLoop wait_for_call_to_arrive_at_service; EXPECT_CALL(mock_device_factory_, DoGetDeviceInfos(_)) .WillOnce(Invoke( [&callback_to_be_called_by_service, &wait_for_call_to_arrive_at_service]( video_capture::mojom::DeviceFactory::GetDeviceInfosCallback& callback) { // Hold on to the callback so we can drop it later. callback_to_be_called_by_service = std::move(callback); wait_for_call_to_arrive_at_service.Quit(); })); base::RunLoop wait_for_callback_from_service; EXPECT_CALL(results_cb_, Run(_)) .WillOnce(Invoke( [&wait_for_callback_from_service]( const std::vector<media::VideoCaptureDeviceInfo>& results) { EXPECT_EQ(0u, results.size()); wait_for_callback_from_service.Quit(); })); // Exercise provider_->GetDeviceInfosAsync(results_cb_.Get()); wait_for_call_to_arrive_at_service.Run(); // Simulate that the service goes down by cutting the connections. device_factory_binding_.Close(); factory_provider_binding_.Close(); wait_for_callback_from_service.Run(); } // Tests that |ServiceVideoCaptureProvider| closes the connection to the service // after successfully processing a single request to GetDeviceInfos(). TEST_F(ServiceVideoCaptureProviderTest, ClosesServiceConnectionAfterGetDeviceInfos) { // Setup part 1 video_capture::mojom::DeviceFactory::GetDeviceInfosCallback callback_to_be_called_by_service; base::RunLoop wait_for_call_to_arrive_at_service; EXPECT_CALL(mock_device_factory_, DoGetDeviceInfos(_)) .WillOnce(Invoke( [&callback_to_be_called_by_service, &wait_for_call_to_arrive_at_service]( video_capture::mojom::DeviceFactory::GetDeviceInfosCallback& callback) { // Hold on to the callback so we can drop it later. callback_to_be_called_by_service = std::move(callback); wait_for_call_to_arrive_at_service.Quit(); })); // Exercise part 1: Make request to the service provider_->GetDeviceInfosAsync(results_cb_.Get()); wait_for_call_to_arrive_at_service.Run(); // Setup part 2: Now that the connection to the service is established, we can // listen for disconnects. base::RunLoop wait_for_connection_to_device_factory_to_close; base::RunLoop wait_for_connection_to_device_factory_provider_to_close; device_factory_binding_.set_connection_error_handler( base::BindOnce([](base::RunLoop* run_loop) { run_loop->Quit(); }, &wait_for_connection_to_device_factory_to_close)); factory_provider_binding_.set_connection_error_handler( base::BindOnce([](base::RunLoop* run_loop) { run_loop->Quit(); }, &wait_for_connection_to_device_factory_provider_to_close)); // Exercise part 2: The service responds std::vector<media::VideoCaptureDeviceInfo> arbitrarily_empty_results; base::ResetAndReturn(&callback_to_be_called_by_service) .Run(arbitrarily_empty_results); // Verification: Expect |provider_| to close the connection to the service. wait_for_connection_to_device_factory_to_close.Run(); wait_for_connection_to_device_factory_provider_to_close.Run(); } // Tests that |ServiceVideoCaptureProvider| does not close the connection to the // service while at least one previously handed out VideoCaptureDeviceLauncher // instance is still using it. Then confirms that it closes the connection as // soon as the last VideoCaptureDeviceLauncher instance is released. TEST_F(ServiceVideoCaptureProviderTest, KeepsServiceConnectionWhileDeviceLauncherAlive) { ON_CALL(mock_device_factory_, DoGetDeviceInfos(_)) .WillByDefault(Invoke([](video_capture::mojom::DeviceFactory:: GetDeviceInfosCallback& callback) { std::vector<media::VideoCaptureDeviceInfo> arbitrarily_empty_results; base::ResetAndReturn(&callback).Run(arbitrarily_empty_results); })); ON_CALL(mock_device_factory_, DoCreateDevice(_, _, _)) .WillByDefault( Invoke([](const std::string& device_id, video_capture::mojom::DeviceRequest* device_request, video_capture::mojom::DeviceFactory::CreateDeviceCallback& callback) { base::ResetAndReturn(&callback).Run( video_capture::mojom::DeviceAccessResultCode::SUCCESS); })); MockVideoCaptureDeviceLauncherCallbacks mock_callbacks; // Exercise part 1: Create a device launcher and hold on to it. auto device_launcher_1 = provider_->CreateDeviceLauncher(); base::RunLoop wait_for_launch_1; device_launcher_1->LaunchDeviceAsync( kStubDeviceId, content::MEDIA_DEVICE_VIDEO_CAPTURE, kArbitraryParams, kNullReceiver, base::DoNothing(), &mock_callbacks, wait_for_launch_1.QuitClosure()); wait_for_connection_to_service_.Run(); wait_for_launch_1.Run(); // Monitor if connection gets closed bool connection_has_been_closed = false; device_factory_binding_.set_connection_error_handler(base::BindOnce( [](bool* connection_has_been_closed) { *connection_has_been_closed = true; }, &connection_has_been_closed)); factory_provider_binding_.set_connection_error_handler(base::BindOnce( [](bool* connection_has_been_closed) { *connection_has_been_closed = true; }, &connection_has_been_closed)); // Exercise part 2: Make a few GetDeviceInfosAsync requests base::RunLoop wait_for_get_device_infos_response_1; base::RunLoop wait_for_get_device_infos_response_2; provider_->GetDeviceInfosAsync(base::BindOnce( [](base::RunLoop* run_loop, const std::vector<media::VideoCaptureDeviceInfo>&) { run_loop->Quit(); }, &wait_for_get_device_infos_response_1)); provider_->GetDeviceInfosAsync(base::BindOnce( [](base::RunLoop* run_loop, const std::vector<media::VideoCaptureDeviceInfo>&) { run_loop->Quit(); }, &wait_for_get_device_infos_response_2)); wait_for_get_device_infos_response_1.Run(); { base::RunLoop give_provider_chance_to_disconnect; give_provider_chance_to_disconnect.RunUntilIdle(); } ASSERT_FALSE(connection_has_been_closed); wait_for_get_device_infos_response_2.Run(); { base::RunLoop give_provider_chance_to_disconnect; give_provider_chance_to_disconnect.RunUntilIdle(); } ASSERT_FALSE(connection_has_been_closed); // Exercise part 3: Create and release another device launcher auto device_launcher_2 = provider_->CreateDeviceLauncher(); base::RunLoop wait_for_launch_2; device_launcher_2->LaunchDeviceAsync( kStubDeviceId, content::MEDIA_DEVICE_VIDEO_CAPTURE, kArbitraryParams, kNullReceiver, base::DoNothing(), &mock_callbacks, wait_for_launch_2.QuitClosure()); wait_for_launch_2.Run(); device_launcher_2.reset(); { base::RunLoop give_provider_chance_to_disconnect; give_provider_chance_to_disconnect.RunUntilIdle(); } ASSERT_FALSE(connection_has_been_closed); // Exercise part 3: Release the initial device launcher. device_launcher_1.reset(); { base::RunLoop give_provider_chance_to_disconnect; give_provider_chance_to_disconnect.RunUntilIdle(); } ASSERT_TRUE(connection_has_been_closed); } // Tests that |ServiceVideoCaptureProvider| does not close the connection to the // service while at least one answer to a GetDeviceInfos() request is still // pending. Confirms that it closes the connection as soon as the last pending // request is answered. TEST_F(ServiceVideoCaptureProviderTest, DoesNotCloseServiceConnectionWhileGetDeviceInfoResponsePending) { // When GetDeviceInfos gets called, hold on to the callbacks, but do not // yet invoke them. std::vector<video_capture::mojom::DeviceFactory::GetDeviceInfosCallback> callbacks_to_be_called_by_service; ON_CALL(mock_device_factory_, DoGetDeviceInfos(_)) .WillByDefault(Invoke( [&callbacks_to_be_called_by_service]( video_capture::mojom::DeviceFactory::GetDeviceInfosCallback& callback) { callbacks_to_be_called_by_service.push_back(std::move(callback)); })); // Make initial call to GetDeviceInfosAsync(). The service does not yet // respond. provider_->GetDeviceInfosAsync( base::BindOnce([](const std::vector<media::VideoCaptureDeviceInfo>&) {})); // Make an additional call to GetDeviceInfosAsync(). provider_->GetDeviceInfosAsync( base::BindOnce([](const std::vector<media::VideoCaptureDeviceInfo>&) {})); { base::RunLoop give_mojo_chance_to_process; give_mojo_chance_to_process.RunUntilIdle(); } ASSERT_EQ(2u, callbacks_to_be_called_by_service.size()); // Monitor if connection gets closed bool connection_has_been_closed = false; device_factory_binding_.set_connection_error_handler(base::BindOnce( [](bool* connection_has_been_closed) { *connection_has_been_closed = true; }, &connection_has_been_closed)); factory_provider_binding_.set_connection_error_handler(base::BindOnce( [](bool* connection_has_been_closed) { *connection_has_been_closed = true; }, &connection_has_been_closed)); // The service now responds to the first request. std::vector<media::VideoCaptureDeviceInfo> arbitrarily_empty_results; base::ResetAndReturn(&callbacks_to_be_called_by_service[0]) .Run(arbitrarily_empty_results); { base::RunLoop give_provider_chance_to_disconnect; give_provider_chance_to_disconnect.RunUntilIdle(); } ASSERT_FALSE(connection_has_been_closed); // Create and release a device launcher auto device_launcher = provider_->CreateDeviceLauncher(); device_launcher.reset(); { base::RunLoop give_provider_chance_to_disconnect; give_provider_chance_to_disconnect.RunUntilIdle(); } ASSERT_FALSE(connection_has_been_closed); // The service now responds to the second request. base::ResetAndReturn(&callbacks_to_be_called_by_service[1]) .Run(arbitrarily_empty_results); { base::RunLoop give_provider_chance_to_disconnect; give_provider_chance_to_disconnect.RunUntilIdle(); } ASSERT_TRUE(connection_has_been_closed); } } // namespace content
40.973171
80
0.740818
[ "vector" ]
6a69e41738bb6b5878e9d989989703159b2ac00a
9,503
cpp
C++
Homework08/HW08Problem01.cpp
rux616/c101
5ef350b286d4f599f4070d79e63fc9cde65fd9ae
[ "MIT" ]
null
null
null
Homework08/HW08Problem01.cpp
rux616/c101
5ef350b286d4f599f4070d79e63fc9cde65fd9ae
[ "MIT" ]
null
null
null
Homework08/HW08Problem01.cpp
rux616/c101
5ef350b286d4f599f4070d79e63fc9cde65fd9ae
[ "MIT" ]
null
null
null
/* Name: Dan Cassidy Date: 2013-10-21 Homework #: 08 Problem #: 01 Source File: HW08Problem01.cpp Class: C-101 MW 1030 Action: This program adds two fractions together and displays them in either reduced form or as a whole number if possible. */ #include <iostream> #include <iomanip> #include <stdlib.h> using namespace std; void ReadData(int &, int &, int &, int &); void SumFraction(int, int, int, int, int &, int &); int GCD(int, int); void DisplayData(int, int, int, int, int, int); unsigned NumDigits(unsigned); void main() { int Numerator1, Denominator1, Numerator2, Denominator2, NumeratorS, DenominatorS; char Continue; do { system("cls"); cout << "This program adds fractions.\n"; cout << "============================\n"; ReadData(Numerator1, Denominator1, Numerator2, Denominator2); SumFraction(Numerator1, Denominator1, Numerator2, Denominator2, NumeratorS, DenominatorS); cout << endl; DisplayData(Numerator1, Denominator1, Numerator2, Denominator2, NumeratorS, DenominatorS); cout << endl; cout << "----------------------------\n"; cout << "Continue? Y or N: "; cin >> Continue; } while (Continue == 'Y' || Continue == 'y'); } /****************************** ReadData ****************************************************************** Action: Prompts the user for input and then reads the input into respective variables Paremeters: IN: None OUT: int Numerator1, holds the first numerator asked for OUT: int Denominator1, holds the first denominator asked for OUT: int Numerator2, holds the second numerator asked for OUT: int Denominator2, holds the second denominator asked for Returns: Nothing, except through reference parameters Precondition: None **********************************************************************************************************/ void ReadData(int &Numerator1, int &Denominator1, int &Numerator2, int &Denominator2) { cout << "Enter numerator 1: "; cin >> Numerator1; cout << "Enter denominator 1: "; cin >> Denominator1; cout << "\n"; cout << "Enter numerator 2: "; cin >> Numerator2; cout << "Enter denominator 2: "; cin >> Denominator2; } /****************************** SumFraction *************************************************************** Action: Adds two fractions together and reduces them to lowest terms Paremeters: IN: int Numer1, holds the numerator of the first fraction IN: int Denom1, holds the denominator of the first fraction IN: int Numer2, holds the numerator of the second fraction IN: int Denom2, holds the denominator of the second fraction OUT: int NumeratorS, holds the reduced numerator of the sum fraction OUT: int DenominatorS, holds the reduced denominator of the sum fraction Returns: Nothing, except through reference parameters Precondition: IN parameters should be non-negative **********************************************************************************************************/ void SumFraction(int Numer1, int Denom1, int Numer2, int Denom2, int &NumeratorS, int &DenominatorS) { int GCDLocal; NumeratorS = (Numer1 * Denom2) + (Denom1 * Numer2); DenominatorS = Denom1 * Denom2; GCDLocal = GCD(NumeratorS, DenominatorS); if (GCDLocal == 0) GCDLocal = 1; NumeratorS /= GCDLocal; DenominatorS /= GCDLocal; } /****************************** GCD *********************************************************************** Action: Uses Euclid's algorithm to return the greatest common divisor of two numbers Paremeters: IN: int Num1, integer that holds the first number to analyze IN: int Num2, integer that holds the second number to analyze OUT: None Returns: Integer that holds the greatest common divisor of int Num1 and int Num2 Precondition: None **********************************************************************************************************/ int GCD(int Num1, int Num2) { int Temp; while (Num2 != 0) { Temp = Num2; Num2 = Num1 % Num2; Num1 = Temp; } return Num1; } /****************************** DisplayData *************************************************************** Action: Displays the fractions and sum nicely Paremeters: IN: int Numer1, holds the numerator of the first fraction IN: int Denom1, holds the denominator of the first fraction IN: int Numer2, holds the numerator of the second fraction IN: int Denom2, holds the denominator of the second fraction IN: int NumerS, holds the reduced numerator of the sum fraction IN: int DenomS, holds the reduced denominator of the sum fraction OUT: None Returns: Nothing Precondition: None **********************************************************************************************************/ void DisplayData(int Numer1, int Denom1, int Numer2, int Denom2, int NumerS, int DenomS) { // Declare and determine the length of the different numbers -- for use in centering the numbers later unsigned N1Length = Numer1 >= 0 ? NumDigits(Numer1) : NumDigits(-Numer1) + 1; unsigned D1Length = Denom1 >= 0 ? NumDigits(Denom1) : NumDigits(-Denom1) + 1; unsigned N2Length = Numer2 >= 0 ? NumDigits(Numer2) : NumDigits(-Numer2) + 1; unsigned D2Length = Denom2 >= 0 ? NumDigits(Denom2) : NumDigits(-Denom2) + 1; unsigned NSLength = NumerS >= 0 ? NumDigits(NumerS) : NumDigits(-NumerS) + 1; unsigned DSLength = DenomS >= 0 ? NumDigits(DenomS) : NumDigits(-DenomS) + 1; unsigned F1Length = N1Length >= D1Length ? N1Length : D1Length; unsigned F2Length = N2Length >= D2Length ? N2Length : D2Length; unsigned FSLength = NSLength >= DSLength ? NSLength : DSLength; // Displays the first line and centers the numbers in their respective fractions with setw cout << " "; cout << " " << setw( int( (F1Length + N1Length) / 2.0 + 0.5 ) ) << Numer1 << setw( int( (F1Length - N1Length) / 2.0 + 1.0 ) ) << " "; cout << " "; cout << " " << setw( int( (F2Length + N2Length) / 2.0 + 0.5 ) ) << Numer2 << setw( int( (F2Length - N2Length) / 2.0 + 1.0 ) ) << " "; cout << " "; if (DenomS != 1 && DenomS != -1) cout << " " << setw( int( (FSLength + NSLength) / 2.0 + 0.5 ) ) << NumerS; // Displays the middle line cout << setfill('-') << "\n "; cout << "-" << setw(F1Length) << "-" << "-"; cout << " + "; cout << "-" << setw(F2Length) << "-" << "-"; cout << " = "; if (DenomS != 1 && DenomS != -1) cout << "-" << setw(FSLength) << "-" << "-"; else cout << NumerS / DenomS; // Displays the third line and centers the numbers in their respective fractions with setw cout << setfill(' ') << "\n "; cout << " " << setw( int( (F1Length + D1Length) / 2.0 + 0.5 ) ) << Denom1 << setw( int( (F1Length - D1Length) / 2.0 + 1.0 ) ) << " "; cout << " "; cout << " " << setw( int( (F2Length + D2Length) / 2.0 + 0.5 ) ) << Denom2 << setw( int( (F2Length - D2Length) / 2.0 + 1.0 ) ) << " "; cout << " "; if (DenomS != 1 && DenomS != 1) cout << " " << setw( int( (FSLength + DSLength) / 2.0 + 0.5 ) ) << DenomS; cout << "\n"; } /****************************** NumDigits ***************************************************************** Action: Recursively determines the number of digits in a number Credits: Found at http://stackoverflow.com/a/3068415 Paremeters: IN: unsigned Num, holds the number whose length is to be determined OUT: None Returns: The number of digits of unsigned Num Precondition: Num must be non-negative **********************************************************************************************************/ unsigned NumDigits(unsigned Num) { if (Num < 10) return 1; return 1 + NumDigits(Num / 10); } /* PROGRAM OUTPUT Test Case 0: Special Tests the layout of the program. Further tests will use only the output of DisplayData in the interest of saving space. This program adds fractions. ============================ Enter numerator 1: 1 Enter denominator 1: 2 Enter numerator 2: 3 Enter denominator 2: 4 1 3 5 --- + --- = --- 2 4 4 ---------------------------- Continue? Y or N: Test Case 1: Limit (Numerator1 = 0, Denominator1 = 3, Numerator2 = 5, Denominator2 = 4) Tests adding fractions with zeroes and fractions where both numerator and denominator are single digits. 0 5 5 --- + --- = --- 3 4 4 Test Case 2: Normal (Numerator1 = 1, Denominator1 = 10, Numerator2 = 1, Denominator2 = 100) Tests adding fractions that can not be reduced. 1 1 11 ---- + ----- = ----- 10 100 100 Test Case 3: Normal (Numerator1 = 1, Denominator1 = 10, Numerator2 = 6, Denominator2 = 20) Tests the GCD function to ensure it is working properly. 1 6 2 ---- + ---- = --- 10 20 5 Test Case 4: Normal (Numerator1 = 3, Denominator1 = 1, Numerator2 = 10, Denominator2 = 1) Tests the addition of whole numbers and the DisplayData function's ability to recognize and render a whole number as such. 3 10 --- + ---- = 13 1 1 Test Case 5: Normal (Numerator1 = 5, Denominator1 = 4, Numerator2 = 1, Denominator2 = 2) Tests the addition of proper and improper fractions. 5 1 7 --- + --- = --- 4 2 4 Test Case 6: Special (Numerator1 = 1, Denominator1 = 1000, Numerator2 = 1, Denominator2 = 10000) Tests larger numbers and the DisplayData function's ability to center all the numbers. 1 3 13 ------ + ------- = ------- 1000 10000 10000 */
34.060932
107
0.574871
[ "render" ]
6a6a37e4ebd226fd144191fb7f3b3e0b562e54b7
52,006
cpp
C++
Plugins~/Src/MeshSyncClient3dsMax/msmaxContext.cpp
kant/MeshSyncDCCPlugins
6f63058032c9a8de553e36b0f9f3c7d2c2988150
[ "Apache-2.0" ]
null
null
null
Plugins~/Src/MeshSyncClient3dsMax/msmaxContext.cpp
kant/MeshSyncDCCPlugins
6f63058032c9a8de553e36b0f9f3c7d2c2988150
[ "Apache-2.0" ]
null
null
null
Plugins~/Src/MeshSyncClient3dsMax/msmaxContext.cpp
kant/MeshSyncDCCPlugins
6f63058032c9a8de553e36b0f9f3c7d2c2988150
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "msmaxContext.h" #include "msmaxUtils.h" #include "msmaxCallbacks.h" #include "MeshSync/SceneGraph/msCamera.h" #include "MeshSync/SceneGraph/msMesh.h" #include "MeshSync/Utility/msMaterialExt.h" //AsStandardMaterial #include "MeshSyncClient/SettingsUtilities.h" #ifdef _WIN32 #pragma comment(lib, "core.lib") #pragma comment(lib, "geom.lib") #pragma comment(lib, "mesh.lib") #pragma comment(lib, "poly.lib") #pragma comment(lib, "mnmath.lib") #pragma comment(lib, "maxutil.lib") #pragma comment(lib, "maxscrpt.lib") #pragma comment(lib, "paramblk2.lib") #pragma comment(lib, "menus.lib") #pragma comment(lib, "Morpher.lib") #endif static void OnStartup(void *param, NotifyInfo *info) { msmaxGetContext().onStartup(); } static void OnShutdown(void *param, NotifyInfo *info) { msmaxGetContext().onShutdown(); } static void OnNodeRenamed(void *param, NotifyInfo *info) { msmaxGetContext().onNodeRenamed(); } static void OnPreNewScene(void *param, NotifyInfo *info) { msmaxGetContext().onNewScene(); } static void OnPostNewScene(void *param, NotifyInfo *info) { msmaxGetContext().update(); } static void FeedDeferredCallsImpl(void*) { msmaxGetContext().feedDeferredCalls(); } static void FeedDeferredCalls() { // call FeedDeferredCallsImpl from main thread // https://help.autodesk.com/view/3DSMAX/2017/ENU/?guid=__files_GUID_0FA27485_D808_40B7_8465_B1C293077597_htm const UINT WM_TRIGGER_CALLBACK = WM_USER + 4764; ::PostMessage(GetCOREInterface()->GetMAXHWnd(), WM_TRIGGER_CALLBACK, (WPARAM)&FeedDeferredCallsImpl, (LPARAM)nullptr); } ms::Identifier msmaxContext::TreeNode::getIdentifier() const { return { path, id }; } void msmaxContext::TreeNode::clearDirty() { dirty_trans = dirty_geom = false; } void msmaxContext::TreeNode::clearState() { dst = nullptr; } void msmaxContext::AnimationRecord::operator()(msmaxContext * _this) { (_this->*extractor)(*dst, node); } msmaxContext& msmaxContext::getInstance() { static msmaxContext s_instance; return s_instance; } msmaxContext::msmaxContext() { std::time( &m_time_to_update_scene); RegisterNotification(OnStartup, this, NOTIFY_SYSTEM_STARTUP); RegisterNotification(OnShutdown, this, NOTIFY_SYSTEM_SHUTDOWN); } msmaxContext::~msmaxContext() { // releasing resources is done by onShutdown() } MaxSyncSettings& msmaxContext::getSettings() { return m_settings; } MaxCacheSettings& msmaxContext::getCacheSettings() { return m_cache_settings; } void msmaxContext::onStartup() { GetCOREInterface()->RegisterViewportDisplayCallback(TRUE, &msmaxViewportDisplayCallback::getInstance()); GetCOREInterface()->RegisterTimeChangeCallback(&msmaxTimeChangeCallback::getInstance()); RegisterNotification(&OnNodeRenamed, this, NOTIFY_NODE_RENAMED); RegisterNotification(&OnPreNewScene, this, NOTIFY_SYSTEM_PRE_RESET ); RegisterNotification(&OnPostNewScene, this, NOTIFY_SYSTEM_POST_RESET); RegisterNotification(&OnPreNewScene, this, NOTIFY_SYSTEM_PRE_NEW ); RegisterNotification(&OnPostNewScene, this, NOTIFY_SYSTEM_POST_NEW); RegisterNotification(&OnPreNewScene, this, NOTIFY_FILE_PRE_OPEN ); RegisterNotification(&OnPostNewScene, this, NOTIFY_FILE_POST_OPEN); m_cbkey = GetISceneEventManager()->RegisterCallback(msmaxNodeCallback::getInstance().GetINodeEventCallback()); registerMenu(); } void msmaxContext::onShutdown() { wait(); unregisterMenu(); m_texture_manager.clear(); m_material_manager.clear(); m_entity_manager.clear(); m_animations.clear(); m_node_records.clear(); } void msmaxContext::onNewScene() { for (auto& kvp : m_node_records) { m_entity_manager.erase(kvp.second.getIdentifier()); } m_node_records.clear(); m_scene_updated = true; } void msmaxContext::onSceneUpdated() { m_scene_updated = true; } void msmaxContext::onTimeChanged() { if (m_settings.auto_sync) m_pending_request = MeshSyncClient::ObjectScope::All; } void msmaxContext::onNodeAdded(INode * n) { m_scene_updated = true; } void msmaxContext::onNodeDeleted(INode * n) { m_scene_updated = true; auto it = m_node_records.find(n); if (it != m_node_records.end()) { m_entity_manager.erase(it->second.getIdentifier()); m_node_records.erase(it); } } void msmaxContext::onNodeRenamed() { const uint32_t UPDATE_DELAY_SEC = 3; time_t cur_time; time( &cur_time ); m_time_to_update_scene = cur_time + UPDATE_DELAY_SEC; m_scene_updated = true; } void msmaxContext::onNodeLinkChanged(INode *n) { m_scene_updated = true; } void msmaxContext::onNodeUpdated(INode *n) { auto& rec = getNodeRecord(n); m_dirty = rec.dirty_trans = true; } void msmaxContext::onGeometryUpdated(INode *n) { auto& rec = getNodeRecord(n); m_dirty = rec.dirty_trans = rec.dirty_geom = true; } void msmaxContext::onRepaint() { update(); } void msmaxContext::logInfo(const char * format, ...) { const int MaxBuf = 2048; char buf[MaxBuf]; va_list args; va_start(args, format); vsprintf(buf, format, args); { auto mes = mu::ToWCS(buf); the_listener->edit_stream->wputs(mes.c_str()); the_listener->edit_stream->wflush(); } va_end(args); } bool msmaxContext::isServerAvailable() { m_sender.client_settings = m_settings.client_settings; return m_sender.isServerAvaileble(); } const std::string& msmaxContext::getErrorMessage() { return m_sender.getErrorMessage(); } void msmaxContext::wait() { m_sender.wait(); } void msmaxContext::update() { time_t cur_time; time( &cur_time ); if (m_scene_updated && cur_time > m_time_to_update_scene) { updateRecords(); m_scene_updated = false; if (m_settings.auto_sync) { m_pending_request = MeshSyncClient::ObjectScope::All; } } if (m_settings.auto_sync && m_pending_request == MeshSyncClient::ObjectScope::None && m_dirty) { m_pending_request = MeshSyncClient::ObjectScope::Updated; } if (m_pending_request != MeshSyncClient::ObjectScope::None) { if (sendObjects(m_pending_request, false)) { m_pending_request = MeshSyncClient::ObjectScope::None; } } } bool msmaxContext::sendObjects(MeshSyncClient::ObjectScope scope, bool dirty_all) { if (m_sender.isExporting()) return false; m_settings.Validate(); m_material_manager.setAlwaysMarkDirty(dirty_all); m_entity_manager.setAlwaysMarkDirty(dirty_all); m_texture_manager.setAlwaysMarkDirty(false); // false because too heavy if (m_settings.sync_meshes) exportMaterials(); int num_exported = 0; auto nodes = getNodes(scope); auto export_objects = [&]() { for (auto& n : nodes) { if (exportObject(n->node, true)) ++num_exported; } }; if (m_settings.use_render_meshes) { for (auto& n : nodes) m_render_scope.addNode(n->node); m_render_scope.prepare(GetTime()); m_render_scope.scope(export_objects); } else { export_objects(); } if (num_exported > 0) kickAsyncExport(); // cleanup intermediate data m_material_records.clear(); m_dirty = false; return true; } bool msmaxContext::sendMaterials(bool dirty_all) { if (m_sender.isExporting()) return false; m_settings.Validate(); m_material_manager.setAlwaysMarkDirty(dirty_all); m_texture_manager.setAlwaysMarkDirty(dirty_all); exportMaterials(); // send kickAsyncExport(); // cleanup intermediate data m_material_records.clear(); return true; } bool msmaxContext::sendAnimations(MeshSyncClient::ObjectScope scope) { m_sender.wait(); m_settings.Validate(); const float frame_rate = (float)::GetFrameRate(); const float frame_step = std::max(m_settings.frame_step, 0.1f); // create default clip m_animations.clear(); m_animations.push_back(ms::AnimationClip::create()); auto& clip = *m_animations.back(); clip.frame_rate = frame_rate * std::max(1.0f / frame_step, 1.0f); // gather target data int num_exported = 0; auto nodes = getNodes(scope); for (auto n : nodes) { if (exportAnimations(n->node, false)) ++num_exported; } // advance frame and record animation auto time_range = GetCOREInterface()->GetAnimRange(); auto time_start = time_range.Start(); auto time_end = time_range.End(); auto interval = ToTicks(frame_step / frame_rate); for (TimeValue t = time_start;;) { m_current_time_tick = t; m_anim_time = ToSeconds(t - time_start); for (auto& kvp : m_anim_records) kvp.second(this); if (t >= time_end) break; else t += interval; } // cleanup intermediate data m_anim_records.clear(); if (!m_animations.empty()) kickAsyncExport(); return true; } static DWORD WINAPI CB_Dummy(LPVOID arg) { return 0; } static int ExceptionFilter(unsigned int code, struct _EXCEPTION_POINTERS *ep) { return EXCEPTION_EXECUTE_HANDLER; } bool msmaxContext::exportCache(const MaxCacheSettings& cache_settings) { using namespace MeshSyncClient; const float frame_rate = (float)::GetFrameRate(); const float frame_step = std::max(cache_settings.frame_step, 0.1f); const MaxSyncSettings settings_old = m_settings; m_settings.ignore_non_renderable = cache_settings.ignore_non_renderable; m_settings.use_render_meshes = cache_settings.use_render_meshes; SettingsUtilities::ApplyCacheToSyncSettings(cache_settings, &m_settings); const float sampleRate = frame_rate * std::max(1.0f / frame_step, 1.0f); const ms::OSceneCacheSettings oscs = SettingsUtilities::CreateOSceneCacheSettings(sampleRate, cache_settings); if (!m_cache_writer.open(cache_settings.path.c_str(), oscs)) { m_settings = settings_old; return false; } m_material_manager.setAlwaysMarkDirty(true); m_entity_manager.setAlwaysMarkDirty(true); const MaterialFrameRange material_range = cache_settings.material_frame_range; const std::vector<msmaxContext::TreeNode*> nodes = getNodes(cache_settings.object_scope); auto *ifs = GetCOREInterface(); if (cache_settings.frame_range == MeshSyncClient::FrameRange::Current) { m_anim_time = 0.0f; m_current_time_tick = ifs->GetTime(); DoExportSceneCache(0, material_range, nodes); } else { ifs->ProgressStart(L"Exporting Scene Cache", TRUE, CB_Dummy, nullptr); int sceneIndex = 0; TimeValue time_start = 0, time_end = 0, interval = 0; if (cache_settings.frame_range == MeshSyncClient::FrameRange::Custom) { // custom frame range time_start = cache_settings.frame_begin * ::GetTicksPerFrame(); time_end = cache_settings.frame_end * ::GetTicksPerFrame(); } else { // all active frames auto time_range = ifs->GetAnimRange(); time_start = time_range.Start(); time_end = time_range.End(); } interval = ToTicks(frame_step / frame_rate); time_end = std::max(time_end, time_start); // sanitize for (TimeValue t = time_start;;) { m_current_time_tick = t; m_anim_time = ToSeconds(t - time_start); DoExportSceneCache(sceneIndex, material_range, nodes); ++sceneIndex; const float progress = float(m_current_time_tick - time_start) / float(time_end - time_start) * 100.0f; ifs->ProgressUpdate((int)progress); if (t >= time_end) { // end of time range break; } else if (ifs->GetCancel()) { // cancel requested ifs->SetCancel(FALSE); break; } else { t += interval; } } ifs->ProgressEnd(); } // cleanup intermediate data m_material_records.clear(); m_settings = settings_old; m_cache_writer.close(); return true; } void msmaxContext::DoExportSceneCache(const int sceneIndex, const MeshSyncClient::MaterialFrameRange materialFrameRange, const std::vector<msmaxContext::TreeNode*>& nodes) { if (sceneIndex == 0 || materialFrameRange == MeshSyncClient::MaterialFrameRange::All) { // exportMaterials() is needed to export material IDs in meshes exportMaterials(); m_material_manager.clearDirtyFlags(); } auto export_objects = [&]() { for (const std::vector<msmaxContext::TreeNode*>::value_type& n : nodes) exportObject(n->node, true); }; if (m_settings.use_render_meshes) { for (const std::vector<msmaxContext::TreeNode*>::value_type& n : nodes) m_render_scope.addNode(n->node); m_render_scope.prepare(GetTime()); m_render_scope.scope(export_objects); } else { export_objects(); } if (materialFrameRange == MeshSyncClient::MaterialFrameRange::None || (materialFrameRange == MeshSyncClient::MaterialFrameRange::One && sceneIndex != 0)) { m_material_manager.clearDirtyFlags(); } m_texture_manager.clearDirtyFlags(); kickAsyncExport(); } //---------------------------------------------------------------------------------------------------------------------- bool msmaxContext::recvScene() { return false; } void msmaxContext::updateRecords(bool track_delete) { struct ExistRecord { std::string path; bool exists; bool operator<(const ExistRecord& v) const { return path < v.path; } bool operator<(const std::string& v) const { return path < v; } }; std::vector<ExistRecord> old_records; if (track_delete) { // create path list to detect rename / re-parent old_records.reserve(m_node_records.size()); for (auto& kvp : m_node_records) old_records.push_back({ std::move(kvp.second.path), false }); std::sort(old_records.begin(), old_records.end()); } // re-construct records std::vector<TreeNode*> nodes; nodes.reserve(m_node_records.size()); m_node_records.clear(); EnumerateAllNode([this, &nodes](INode *n) { nodes.push_back(&getNodeRecord(n)); }); // sort nodes by path and assign indices std::sort(nodes.begin(), nodes.end(), [](auto *a, auto *b) { return a->path < b->path; }); size_t n = nodes.size(); for (size_t i = 0; i < n; ++i) nodes[i]->index = (int)i; if (track_delete) { // erase renamed / re-parented objects for (auto& kvp : m_node_records) { auto it = std::lower_bound(old_records.begin(), old_records.end(), kvp.second.path); if (it != old_records.end() && it->path == kvp.second.path) it->exists = true; } for (auto& r : old_records) { if (!r.exists) m_entity_manager.erase(r.path); } } } msmaxContext::TreeNode& msmaxContext::getNodeRecord(INode *n) { auto& rec = m_node_records[n]; if (!rec.node) { rec.node = n; rec.name = GetNameW(n); rec.path = GetPath(n); } return rec; } std::vector<msmaxContext::TreeNode*> msmaxContext::getNodes(MeshSyncClient::ObjectScope scope) { std::vector<TreeNode*> ret; ret.reserve(m_node_records.size()); switch (scope) { case MeshSyncClient::ObjectScope::All: for (auto& kvp : m_node_records) ret.push_back(&kvp.second); break; case MeshSyncClient::ObjectScope::Updated: for (auto& kvp : m_node_records) { if (kvp.second.dirty_trans || kvp.second.dirty_geom) ret.push_back(&kvp.second); } break; case MeshSyncClient::ObjectScope::Selected: for (auto& kvp : m_node_records) { if (kvp.second.node->Selected()) ret.push_back(&kvp.second); } break; } std::sort(ret.begin(), ret.end(), [](auto& a, auto& b) { return a->index < b->index; }); return ret; } void msmaxContext::kickAsyncExport() { for (auto& t : m_async_tasks) t.wait(); m_async_tasks.clear(); for (auto *t : m_tmp_triobj) t->DeleteMe(); m_tmp_triobj.clear(); for (auto *t : m_tmp_meshes) t->DeleteThis(); m_tmp_meshes.clear(); for (auto& kvp : m_node_records) kvp.second.clearState(); float to_meter = (float)GetMasterScale(UNITS_METERS); using Exporter = ms::AsyncSceneExporter; Exporter *exporter = m_settings.ExportSceneCache ? (Exporter*)&m_cache_writer : (Exporter*)&m_sender; // begin async send exporter->on_prepare = [this, to_meter, exporter]() { if (auto sender = dynamic_cast<ms::AsyncSceneSender*>(exporter)) { sender->client_settings = m_settings.client_settings; } else if (auto writer = dynamic_cast<ms::AsyncSceneCacheWriter*>(exporter)) { writer->time = m_anim_time; } auto& t = *exporter; t.scene_settings.handedness = ms::Handedness::RightZUp; t.scene_settings.scale_factor = m_settings.scale_factor / to_meter; t.textures = m_texture_manager.getDirtyTextures(); t.materials = m_material_manager.getDirtyMaterials(); t.transforms = m_entity_manager.getDirtyTransforms(); t.geometries = m_entity_manager.getDirtyGeometries(); t.animations = m_animations; t.deleted_materials = m_material_manager.getDeleted(); t.deleted_entities = m_entity_manager.getDeleted(); }; exporter->on_success = [this]() { m_material_ids.clearDirtyFlags(); m_texture_manager.clearDirtyFlags(); m_material_manager.clearDirtyFlags(); m_entity_manager.clearDirtyFlags(); m_animations.clear(); }; exporter->kick(); } int msmaxContext::exportTexture(const std::string & path, ms::TextureType type) { return m_texture_manager.addFile(path, type); } void msmaxContext::exportMaterials() { auto *mtllib = GetCOREInterface()->GetSceneMtls(); int count = mtllib->Count(); int material_index = 0; // 3ds max allows faces to have no material. add dummy material for them. { auto dst = ms::Material::create(); dst->id = m_material_ids.getID(nullptr); dst->index = material_index++; dst->name = "Default"; m_material_manager.add(dst); } for (int mi = 0; mi < count; ++mi) { auto do_export = [this, &material_index](Mtl *mtl) -> int // return material id { auto dst = ms::Material::create(); dst->id = m_material_ids.getID(mtl); dst->index = material_index++; dst->name = GetName(mtl); ms::StandardMaterial& dstmat = ms::AsStandardMaterial(*dst); dstmat.setColor(to_color(mtl->GetDiffuse())); // export textures if (m_settings.sync_textures && mtl->ClassID() == Class_ID(DMTL_CLASS_ID, 0)) { auto stdmat = (StdMat*)mtl; auto export_texture = [this, stdmat](int tid, ms::TextureType ttype) -> int { if (stdmat->MapEnabled(tid)) { auto tex = stdmat->GetSubTexmap(tid); if (tex && tex->ClassID() == Class_ID(BMTEX_CLASS_ID, 0x00)) { MaxSDK::Util::Path path(((BitmapTex*)tex)->GetMapName()); path.ConvertToAbsolute(); if (path.Exists()) { return exportTexture(mu::ToMBS(path.GetCStr()), ttype); } } } return -1; }; const int DIFFUSE_MAP_ID = 1; const int NORMAL_MAP_ID = 8; dstmat.setColorMap(export_texture(DIFFUSE_MAP_ID, ms::TextureType::Default)); dstmat.setBumpMap(export_texture(NORMAL_MAP_ID, ms::TextureType::NormalMap)); } m_material_manager.add(dst); return dst->id; }; auto mtlbase = (*mtllib)[mi]; if (mtlbase->SuperClassID() != MATERIAL_CLASS_ID) continue; auto mtl = (Mtl*)mtlbase; auto& rec = m_material_records[mtl]; int num_submtls = mtl->NumSubMtls(); if (num_submtls == 0) { // no submaterials. export self. rec.material_id = do_export(mtl); } else { // export submaterials for (int si = 0; si < num_submtls; ++si) { auto submtl = mtl->GetSubMtl(si); if (!submtl) continue; auto it = m_material_records.find(submtl); if (it != m_material_records.end()) rec.submaterial_ids.push_back(it->second.material_id); else rec.submaterial_ids.push_back(do_export(submtl)); } } } m_material_ids.eraseStaleRecords(); m_material_manager.eraseStaleMaterials(); } ms::TransformPtr msmaxContext::exportObject(INode *n, bool tip) { if (!n || !n->GetObjectRef()) return nullptr; auto& rec = getNodeRecord(n); if (rec.dst) return nullptr; auto *obj = GetBaseObject(n); rec.baseobj = obj; ms::TransformPtr ret; auto handle_parent = [&]() { exportObject(n->GetParentNode(), false); }; auto handle_transform = [&]() { handle_parent(); ret = exportTransform(rec); }; auto handle_instance = [&]() -> bool { // always make per-instance meshes if bake_transform if (m_settings.BakeTransform) return false; // check if the node is instance EachInstance(n, [this, &rec, &ret](INode *instance) { if (ret || (m_settings.ignore_non_renderable && !IsRenderable(instance))) return; auto& irec = getNodeRecord(instance); if (irec.dst && irec.dst->reference.empty()) ret = exportInstance(rec, irec.dst); }); return ret != nullptr; }; if (IsMesh(obj) && (!m_settings.ignore_non_renderable || IsRenderable(n))) { // export bones // this must be before extractMeshData() because meshes can be bones in 3ds Max if (m_settings.sync_bones && !m_settings.BakeModifiers) { EachBone(n, [this](INode *bone) { exportObject(bone, false); }); } if (m_settings.sync_meshes || m_settings.sync_blendshapes) { handle_parent(); if (!handle_instance()) ret = exportMesh(rec); } else if (!tip) handle_transform(); } else { if (IsCamera(obj) && m_settings.sync_cameras) { handle_parent(); ret = exportCamera(rec); } else if (IsLight(obj) && m_settings.sync_lights) { handle_parent(); ret = exportLight(rec); } else if (!tip) { handle_transform(); } } rec.clearDirty(); return ret; } mu::float4x4 msmaxContext::getPivotMatrix(INode *n) { auto t = to_float3(n->GetObjOffsetPos()); auto r = to_quatf(n->GetObjOffsetRot()); return mu::transform(t, r, mu::float3::one()); } mu::float4x4 msmaxContext::getWorldMatrix(INode *n, TimeValue t, bool cancel_camera_correction) { auto obj = n->GetObjectRef(); bool is_camera = IsCamera(obj); bool is_light = IsLight(obj); mu::float4x4 r; if (m_settings.BakeTransform) { auto get_matrix = [&]() { // https://help.autodesk.com/view/3DSMAX/2016/ENU/?guid=__files_GUID_2E4E41D4_1B52_48C8_8ABA_3D3C9910CB2C_htm Matrix3 m; m = n->GetObjTMAfterWSM(t); if (m.IsIdentity()) m = n->GetObjTMBeforeWSM(t); // cancel scale m.NoScale(); r = to_float4x4(m); }; if (is_camera && IsPhysicalCamera(obj) && cancel_camera_correction) { // cancel tilt/shift effect MaxSDK::IPhysicalCamera::RenderTransformEvaluationGuard guard(n, t); get_matrix(); } else { get_matrix(); } } else { r = to_float4x4(n->GetNodeTM(t)); } if (is_camera || is_light) { // camera/light correction return mu::float4x4{ { {-r[0][0],-r[0][1],-r[0][2],-r[0][3]}, { r[1][0], r[1][1], r[1][2], r[1][3]}, {-r[2][0],-r[2][1],-r[2][2],-r[2][3]}, { r[3][0], r[3][1], r[3][2], r[3][3]}, } }; } else { return r; } } void msmaxContext::extractTransform(TreeNode& n, TimeValue t, mu::float3& pos, mu::quatf& rot, mu::float3& scale, ms::VisibilityFlags& vis, mu::float4x4 *dst_world, mu::float4x4 *dst_local) { vis = { true, VisibleInRender(n.node, t), VisibleInViewport(n.node) }; auto do_extract = [&](const mu::float4x4& mat) { mu::extract_trs(mat, pos, rot, scale); return mat; }; auto obj = n.node->GetObjectRef(); if (m_settings.BakeTransform) { if (IsCamera(obj) || IsLight(obj)) { // on camera/light, extract from global matrix auto mat = do_extract(getWorldMatrix(n.node, t)); if (dst_world) *dst_world = mat; if (dst_local) *dst_local = mat; } else { // on mesh, transform is applied to vertices when bake_transform pos = mu::float3::zero(); rot = mu::quatf::identity(); scale = mu::float3::one(); if (dst_world) *dst_world = mu::float4x4::identity(); if (dst_local) *dst_local = mu::float4x4::identity(); } } else { auto world = getWorldMatrix(n.node, t); auto local = world; if (auto parent = n.node->GetParentNode()) local *= mu::invert(getWorldMatrix(parent, t)); do_extract(local); if (dst_world) *dst_world = world; if (dst_local) *dst_local = local; } } void msmaxContext::extractTransform(TreeNode& n, TimeValue t, ms::Transform& dst) { extractTransform(n, GetTime(), dst.position, dst.rotation, dst.scale, dst.visibility, &dst.world_matrix, &dst.local_matrix); } void msmaxContext::extractCameraData(TreeNode& n, TimeValue t, bool& ortho, float& fov, float& near_plane, float& far_plane, float& focal_length, mu::float2& sensor_size, mu::float2& lens_shift, mu::float4x4 *view_mat) { auto *cam = dynamic_cast<GenCamera*>(n.baseobj); if (!cam) return; float aspect = GetCOREInterface()->GetRendImageAspect(); ortho = cam->IsOrtho(); { float hfov = cam->GetFOV(t); // CameraObject::GetFOV() returns horizontal fov. we need vertical one. float vfov = 2.0f * std::atan(std::tan(hfov / 2.0f) / aspect); fov = vfov * mu::RadToDeg; } if (cam->GetManualClip()) { near_plane = cam->GetClipDist(t, CAM_HITHER_CLIP); far_plane = cam->GetClipDist(t, CAM_YON_CLIP); } else { near_plane = far_plane = 0.0f; } if (auto* pcam = dynamic_cast<MaxSDK::IPhysicalCamera*>(cam)) { float to_mm = (float)GetMasterScale(UNITS_MILLIMETERS); Interval interval; // focal length in mm focal_length = pcam->GetEffectiveLensFocalLength(t, interval) * to_mm; float film_width = pcam->GetFilmWidth(t, interval) * to_mm; // sensor size in mm sensor_size.x = film_width; sensor_size.y = film_width / aspect; // lens shift in percent auto shift = pcam->GetFilmPlaneOffset(t, interval); lens_shift = -to_float2(shift); lens_shift.y *= aspect; //// todo: handle tilt correction //if (m_settings.bake_modifiers && view_mat) { // auto tilt_correction = to_float2(pcam->GetTiltCorrection(t, interval)); // if (tilt_correction != mu::float2::zero()) { // auto mat = getGlobalMatrix(n.node, t, false); // *view_mat = mu::invert(mat); // } //} } else { focal_length = 0.0f; sensor_size = mu::float2::zero(); lens_shift = mu::float2::zero(); } } void msmaxContext::extractLightData(TreeNode& n, TimeValue t, ms::Light::LightType& ltype, ms::Light::ShadowType& stype, mu::float4& color, float& intensity, float& spot_angle) { auto *light = dynamic_cast<GenLight*>(n.baseobj); if (!light) return; switch (light->Type()) { case TSPOT_LIGHT: case FSPOT_LIGHT: // fall through { ltype = ms::Light::LightType::Spot; spot_angle = light->GetHotspot(t); break; } case DIR_LIGHT: case TDIR_LIGHT: // fall through case LightscapeLight::TARGET_POINT_TYPE: case LightscapeLight::TARGET_LINEAR_TYPE: case LightscapeLight::TARGET_AREA_TYPE: case LightscapeLight::TARGET_DISC_TYPE: case LightscapeLight::TARGET_SPHERE_TYPE: case LightscapeLight::TARGET_CYLINDER_TYPE: { ltype = ms::Light::LightType::Directional; break; } case OMNI_LIGHT: default: // fall through { ltype = ms::Light::LightType::Point; break; } } stype = light->GetShadow() != 0 ? ms::Light::ShadowType::Soft : ms::Light::ShadowType::None; (mu::float3&)color = to_float3(light->GetRGBColor(t)); intensity = light->GetIntensity(t); } template<class T> std::shared_ptr<T> msmaxContext::createEntity(TreeNode& n) { auto ret = T::create(); auto& dst = *ret; dst.path = n.path; dst.index = n.index; n.dst = ret; return ret; } ms::TransformPtr msmaxContext::exportTransform(TreeNode& n) { auto t = GetTime(); auto ret = createEntity<ms::Transform>(n); auto& dst = *ret; extractTransform(n, t, dst); m_entity_manager.add(ret); return ret; } ms::TransformPtr msmaxContext::exportInstance(TreeNode& n, ms::TransformPtr base) { if (!base) return nullptr; auto t = GetTime(); auto ret = createEntity<ms::Transform>(n); auto& dst = *ret; extractTransform(n, t, dst); dst.reference = base->path; m_entity_manager.add(ret); return ret; } ms::TransformPtr msmaxContext::exportCamera(TreeNode& n) { TimeValue t = GetTime(); std::shared_ptr<ms::Camera> ret = createEntity<ms::Camera>(n); ms::Camera& dst = *ret; extractTransform(n, t, dst); extractCameraData(n, t, dst.is_ortho, dst.fov, dst.near_plane, dst.far_plane, dst.focal_length, dst.sensor_size, dst.lens_shift, &dst.view_matrix); m_entity_manager.add(ret); return ret; } ms::TransformPtr msmaxContext::exportLight(TreeNode& n) { auto t = GetTime(); auto ret = createEntity<ms::Light>(n); auto& dst = *ret; extractTransform(n, t, dst); extractLightData(n, GetTime(), dst.light_type, dst.shadow_type, dst.color, dst.intensity, dst.spot_angle); m_entity_manager.add(ret); return ret; } static void ExtractNormals(ms::Mesh& dst, Mesh& mesh) { auto* nspec = (MeshNormalSpec*)mesh.GetInterface(MESH_NORMAL_SPEC_INTERFACE); if (nspec && nspec->GetFlag(MESH_NORMAL_NORMALS_BUILT)) { // there is nspec. I can simply copy normals from it. int num_faces = nspec->GetNumFaces(); auto *faces = nspec->GetFaceArray(); auto *normals = nspec->GetNormalArray(); dst.normals.resize_discard(dst.indices.size()); int ii = 0; for (int fi = 0; fi < num_faces; ++fi) { auto *idx = faces[fi].GetNormalIDArray(); for (int ci = 0; ci < 3; ++ci) { dst.normals[ii++] = to_float3(normals[idx[ci]]); } } } else { auto get_normal = [&mesh](int face_index, int vertex_index) -> mu::float3 { const auto& rv = mesh.getRVert(vertex_index); const auto& face = mesh.faces[face_index]; DWORD smGroup = face.smGroup; int num_normals = 0; Point3 ret; if (rv.rFlags & SPECIFIED_NORMAL) { ret = rv.rn.getNormal(); } else if ((num_normals = rv.rFlags & NORCT_MASK) != 0 && smGroup) { if (num_normals == 1) { ret = rv.rn.getNormal(); } else { for (int i = 0; i < num_normals; i++) { if (rv.ern[i].getSmGroup() & smGroup) { ret = rv.ern[i].getNormal(); } } } } else { ret = mesh.getFaceNormal(face_index); } return to_float3(ret); }; // make sure normal is allocated mesh.checkNormals(TRUE); dst.normals.resize_discard(dst.indices.size()); int num_faces = mesh.numFaces; const auto *faces = mesh.faces; for (int fi = 0; fi < num_faces; ++fi) { auto& face = faces[fi]; for (int i = 0; i < 3; ++i) { dst.normals[fi * 3 + i] = get_normal(fi, face.v[i]); } } } } static void GenSmoothNormals(ms::Mesh& dst, Mesh& mesh) { int num_faces = mesh.numFaces; const auto *points = (mu::float3*)mesh.verts; const auto *faces = mesh.faces; // gen face normals RawVector<mu::float3> face_normals; face_normals.resize_discard(num_faces); for (int fi = 0; fi < num_faces; ++fi) { const auto& face = faces[fi]; auto p0 = points[face.v[0]]; auto p1 = points[face.v[1]]; auto p2 = points[face.v[2]]; auto n = mu::cross(p1 - p0, p2 - p0); face_normals[fi] = n; // note: not normalized at this point } // build vertex -> faces connection info mu::MeshConnectionInfo connection; connection.buildConnection(dst.indices, 3, dst.points); dst.normals.resize_discard(dst.indices.size()); int ii = 0; for (int fi = 0; fi < num_faces; ++fi) { const auto& face = faces[fi]; if (face.smGroup != 0) { // average normals with neighbor faces that have same smoothing group for (int ci = 0; ci < 3; ++ci) { auto n = face_normals[fi]; connection.eachConnectedFaces(face.v[ci], [&](int fi2, int) { if (fi2 == fi) return; const auto& face2 = faces[fi2]; if (face.smGroup & face2.smGroup) { n += face_normals[fi2]; } }); dst.normals[ii++] = mu::normalize(n); } } else { for (int ci = 0; ci < 3; ++ci) { auto n = face_normals[fi]; dst.normals[ii++] = mu::normalize(n); } } } } ms::TransformPtr msmaxContext::exportMesh(TreeNode& n) { auto inode = n.node; auto t = GetTime(); Mesh *mesh = nullptr; TriObject *tri = nullptr; bool needs_delete = false; // send mesh contents even if the node is hidden. if (m_settings.sync_meshes) { tri = m_settings.BakeModifiers? GetFinalMesh(inode, needs_delete) : GetSourceMesh(inode, needs_delete); if (tri) { if (needs_delete) m_tmp_triobj.push_back(tri); if (m_settings.use_render_meshes) { // get render mesh // todo: support multiple meshes BOOL del; NullView view; mesh = tri->GetRenderMesh(t, inode, view, del); if (del) m_tmp_meshes.push_back(mesh); } else { // get viewport mesh mesh = &tri->GetMesh(); } if (mesh) mesh->checkNormals(TRUE); } } if (!mesh) { // camera target and a few other objects are renderable mesh (GEOMOBJECT_CLASS_ID and Renderable() returns true) // but doesn't have valid mesh. I have no idea why... export as transform. return exportTransform(n); } auto ret = createEntity<ms::Mesh>(n); extractTransform(n, t, *ret); auto task = [this, ret, inode, mesh]() { doExtractMeshData(*ret, inode, mesh); m_entity_manager.add(ret); }; if (m_settings.multithreaded) m_async_tasks.push_back(std::async(std::launch::async, task)); else task(); return ret; } void msmaxContext::doExtractMeshData(ms::Mesh &dst, INode *n, Mesh *mesh) { auto t = GetTime(); if (mesh) { if (m_settings.BakeTransform) { // in this case transform is applied to vertices (dst.position/rotation/scale is identity) dst.refine_settings.local2world = to_float4x4(n->GetObjTMAfterWSM(t)); dst.refine_settings.flags.Set(ms::MESH_REFINE_FLAG_LOCAL2WORLD, true); } else { if (m_settings.BakeModifiers) { dst.refine_settings.local2world = to_float4x4(n->GetObjTMAfterWSM(t)); if (m_settings.flatten_hierarchy) dst.refine_settings.local2world *= mu::invert(dst.toMatrix()); else dst.refine_settings.local2world *= mu::invert(dst.world_matrix); dst.refine_settings.flags.Set(ms::MESH_REFINE_FLAG_LOCAL2WORLD, true); } else { // handle pivot dst.refine_settings.local2world = getPivotMatrix(n); dst.refine_settings.flags.Set(ms::MESH_REFINE_FLAG_LOCAL2WORLD, true); } } // faces int num_faces = mesh->numFaces; int num_indices = num_faces * 3; // all faces in Mesh are triangle { dst.counts.clear(); dst.counts.resize(num_faces, 3); dst.material_ids.resize_discard(num_faces); const auto& mrec = m_material_records[n->GetMtl()]; if (!mrec.submaterial_ids.empty()) for (int mid : mrec.submaterial_ids) m_material_manager.markDirty(mid); else m_material_manager.markDirty(mrec.material_id); auto *faces = mesh->faces; dst.indices.resize_discard(num_indices); for (int fi = 0; fi < num_faces; ++fi) { auto& face = faces[fi]; int gid = mesh->getFaceMtlIndex(fi); int mid = 0; if (!mrec.submaterial_ids.empty()) { // multi-materials int midx = std::min(gid, (int)mrec.submaterial_ids.size() - 1); mid = mrec.submaterial_ids[midx]; } else // single material mid = mrec.material_id; // use upper 16 bit as face group id dst.material_ids[fi] = mid | (gid << 16); for (int i = 0; i < 3; ++i) dst.indices[fi * 3 + i] = face.v[i]; } } // points const int num_vertices = mesh->numVerts; dst.points.resize_discard(num_vertices); dst.points.assign((mu::float3*)mesh->verts, (mu::float3*)mesh->verts + num_vertices); // normals if (m_settings.sync_normals) { ExtractNormals(dst, *mesh); } // uv if (m_settings.sync_uvs) { const int num_uv = mesh->numTVerts; TVFace* uv_Faces = mesh->tvFace; UVVert* uv_vertices = mesh->tVerts; if (num_uv && uv_Faces && uv_vertices) { dst.m_uv[0].resize_discard(num_indices); for (int fi = 0; fi < num_faces; ++fi) { for (int i = 0; i < 3; ++i) { dst.m_uv[0][fi * 3 + i] = to_float2(uv_vertices[uv_Faces[fi].t[i]]); } } } } // colors if (m_settings.sync_colors) { int num_colors = mesh->numCVerts; auto *vc_faces = mesh->vcFace; auto *vc_vertices = mesh->vertCol; if (num_colors && vc_faces && vc_vertices) { dst.colors.resize_discard(num_indices); for (int fi = 0; fi < num_faces; ++fi) { for (int i = 0; i < 3; ++i) { dst.colors[fi * 3 + i] = to_color(vc_vertices[vc_faces[fi].t[i]]); } } } } if (!m_settings.BakeModifiers && m_settings.sync_bones) { auto *mod = FindSkin(n); if (mod && mod->IsEnabled()) { ISkin* skin = (ISkin*)mod->GetInterface(I_SKIN); ISkinContextData* ctx = skin->GetContextInterface(n); int num_bones = skin->GetNumBones(); int num_vertices = ctx->GetNumPoints(); if (num_vertices != dst.points.size()) { // topology is changed by modifiers. this case is not supported. } else { // allocate bones and extract bindposes. // note: in max, bindpose is [skin_matrix * inv_bone_matrix] Matrix3 skin_matrix; skin->GetSkinInitTM(n, skin_matrix); for (int bi = 0; bi < num_bones; ++bi) { INode* bone = skin->GetBone(bi); Matrix3 bone_matrix; skin->GetBoneInitTM(bone, bone_matrix); std::shared_ptr<ms::BoneData> bd = ms::BoneData::create(); dst.bones.push_back(bd); bd->bindpose = to_float4x4(skin_matrix) * mu::invert(to_float4x4(bone_matrix)); bd->weights.resize_zeroclear(dst.points.size()); // allocate weights auto bit = m_node_records.find(bone); if (bit != m_node_records.end()) { bd->path = bit->second.path; } } // get weights for (int vi = 0; vi < num_vertices; ++vi) { int num_affected_bones = ctx->GetNumAssignedBones(vi); for (int bi = 0; bi < num_affected_bones; ++bi) { int bone_index = ctx->GetAssignedBone(vi, bi); float bone_weight = ctx->GetBoneWeight(vi, bi); dst.bones[bone_index]->weights[vi] = bone_weight; } } } } } } if (!m_settings.BakeModifiers && m_settings.sync_blendshapes) { // handle blendshape auto *mod = FindMorph(n); if (mod && mod->IsEnabled()) { int num_faces = (int)dst.counts.size(); int num_points = (int)dst.points.size(); int num_normals = (int)dst.normals.size(); MaxMorphModifier morph(mod); int num_channels = morph.NumMorphChannels(); for (int ci = 0; ci < num_channels; ++ci) { auto channel = morph.GetMorphChannel(ci); auto num_targets = channel.NumProgressiveMorphTargets(); if (!channel.IsActive() || !channel.IsValid() || num_targets == 0 || channel.NumMorphPoints() != num_points) continue; auto dbs = ms::BlendShapeData::create(); for (int ti = 0; ti < num_targets; ++ti) { if (!channel.IsValidProgressiveMorphTargetIndex(ti)) continue; dbs->frames.push_back(ms::BlendShapeFrameData::create()); auto& frame = *dbs->frames.back(); frame.weight = channel.GetProgressiveMorphWeight(ti); // workaround. if (frame.weight == 0.0f) frame.weight = 100.0f; // gen delta frame.points.resize_discard(num_points); for (int vi = 0; vi < num_points; ++vi) frame.points[vi] = to_float3(channel.GetProgressiveMorphPoint(ti, vi)) - dst.points[vi]; } if (!dbs->frames.empty()) { dbs->name = mu::ToMBS(channel.GetName()); dbs->weight = channel.GetMorphWeight(t); dst.blendshapes.push_back(dbs); } } } } { if (dst.normals.empty()) dst.refine_settings.flags.Set(ms::MESH_REFINE_FLAG_GEN_NORMALS, true); if (dst.tangents.empty()) dst.refine_settings.flags.Set(ms::MESH_REFINE_FLAG_GEN_TANGENTS, true); dst.refine_settings.flags.Set(ms::MESH_REFINE_FLAG_FLIP_FACES, m_settings.flip_faces); dst.refine_settings.flags.Set(ms::MESH_REFINE_FLAG_MAKE_DOUBLE_SIDED, m_settings.make_double_sided); dst.md_flags.Set(ms::MESH_DATA_FLAG_HAS_FACE_GROUPS, true); } } bool msmaxContext::exportAnimations(INode *n, bool force) { if (!n || !n->GetObjectRef()) return false; auto it = m_anim_records.find(n); if (it != m_anim_records.end()) return false; auto *obj = GetBaseObject(n); ms::TransformAnimationPtr ret; AnimationRecord::extractor_t extractor = nullptr; if (IsMesh(obj) && (!m_settings.ignore_non_renderable || IsRenderable(n))) { exportAnimations(n->GetParentNode(), true); if (m_settings.sync_bones && !m_settings.BakeModifiers) { EachBone(n, [this](INode *bone) { exportAnimations(bone, true); }); } ret = ms::MeshAnimation::create(); extractor = &msmaxContext::extractMeshAnimation; } else { if (IsCamera(obj) && m_settings.sync_cameras) { exportAnimations(n->GetParentNode(), true); ret = ms::CameraAnimation::create(); extractor = &msmaxContext::extractCameraAnimation; } else if (IsLight(obj) && m_settings.sync_lights) { exportAnimations(n->GetParentNode(), true); ret = ms::LightAnimation::create(); extractor = &msmaxContext::extractLightAnimation; } else if (force) { exportAnimations(n->GetParentNode(), true); ret = ms::TransformAnimation::create(); extractor = &msmaxContext::extractTransformAnimation; } } if (ret) { m_animations.front()->addAnimation(ret); ret->path = GetPath(n); auto& ar = m_anim_records[n]; ar.dst = ret; ar.node = &getNodeRecord(n); ar.extractor = extractor; } return ret != nullptr; } void msmaxContext::extractTransformAnimation(ms::TransformAnimation& dst_, TreeNode *n) { auto& dst = (ms::TransformAnimation&)dst_; mu::float3 pos; mu::quatf rot; mu::float3 scale; ms::VisibilityFlags vis; extractTransform(*n, m_current_time_tick, pos, rot, scale, vis); float t = m_anim_time; dst.translation.push_back({ t, pos }); dst.rotation.push_back({ t, rot }); dst.scale.push_back({ t, scale }); dst.visible.push_back({ t, (int)vis.visible_in_render }); } void msmaxContext::extractCameraAnimation(ms::TransformAnimation& dst_, TreeNode *n) { extractTransformAnimation(dst_, n); float t = m_anim_time; auto& dst = (ms::CameraAnimation&)dst_; bool ortho; float fov, near_plane, far_plane, focal_length; mu::float2 sensor_size, lens_shift; extractCameraData(*n, m_current_time_tick, ortho, fov, near_plane, far_plane, focal_length, sensor_size, lens_shift); dst.fov.push_back({ t, fov }); dst.near_plane.push_back({ t, near_plane }); dst.far_plane.push_back({ t, far_plane }); if (focal_length > 0.0f) { dst.focal_length.push_back({ t, focal_length }); dst.sensor_size.push_back({ t, sensor_size }); dst.lens_shift.push_back({ t, lens_shift }); } } void msmaxContext::extractLightAnimation(ms::TransformAnimation& dst_, TreeNode *n) { extractTransformAnimation(dst_, n); float t = m_anim_time; auto& dst = (ms::LightAnimation&)dst_; ms::Light::LightType ltype; ms::Light::ShadowType stype; mu::float4 color; float intensity, spot_angle; extractLightData(*n, m_current_time_tick, ltype, stype, color, intensity, spot_angle); dst.color.push_back({ t, color }); dst.intensity.push_back({ t, intensity }); if (ltype == ms::Light::LightType::Spot) dst.spot_angle.push_back({ t, spot_angle }); } void msmaxContext::extractMeshAnimation(ms::TransformAnimation& dst_, TreeNode *n) { extractTransformAnimation(dst_, n); float t = m_anim_time; auto& dst = (ms::MeshAnimation&)dst_; if (m_settings.sync_blendshapes) { auto *mod = FindMorph(n->node); if (mod) { MaxMorphModifier morph(mod); int num_channels = morph.NumMorphChannels(); for (int ci = 0; ci < num_channels; ++ci) { auto channel = morph.GetMorphChannel(ci); auto tnode = channel.GetMorphTarget(); if (!tnode || !channel.IsActive() || !channel.IsValid()) continue; auto name = mu::ToMBS(channel.GetName()); dst.getBlendshapeCurve(name).push_back({ t, channel.GetMorphWeight(m_current_time_tick) }); } } } } void msmaxContext::addDeferredCall(const std::function<void()>& c) { { std::unique_lock<std::mutex> l(m_mutex); m_deferred_calls.push_back(c); } FeedDeferredCalls(); } void msmaxContext::feedDeferredCalls() { std::unique_lock<std::mutex> l(m_mutex); for (auto& c : m_deferred_calls) c(); m_deferred_calls.clear(); } TimeValue msmaxContext::getExportTime() const { if (m_settings.ExportSceneCache) return m_current_time_tick; else return GetCOREInterface()->GetTime(); } bool msmaxSendScene(MeshSyncClient::ExportTarget target, MeshSyncClient::ObjectScope scope) { auto& ctx = msmaxGetContext(); if (!ctx.isServerAvailable()) { ctx.logInfo("MeshSync: Server not available. %s", ctx.getErrorMessage().c_str()); return false; } auto body = [&ctx, target, scope]() { if (target == MeshSyncClient::ExportTarget::Objects) { ctx.wait(); ctx.sendObjects(scope, true); } else if (target == MeshSyncClient::ExportTarget::Materials) { ctx.wait(); ctx.sendMaterials(true); } else if (target == MeshSyncClient::ExportTarget::Animations) { ctx.wait(); ctx.sendAnimations(scope); } else if (target == MeshSyncClient::ExportTarget::Everything) { ctx.wait(); ctx.sendMaterials(true); ctx.wait(); ctx.sendObjects(scope, true); ctx.wait(); ctx.sendAnimations(scope); } }; ctx.addDeferredCall(body); return true; } bool msmaxExportCache(const MaxCacheSettings& cache_settings) { auto& ctx = msmaxGetContext(); auto body = [&ctx, cache_settings]() { ctx.exportCache(cache_settings); }; ctx.addDeferredCall(body); return true; }
31.499697
128
0.585279
[ "mesh", "render", "vector", "transform" ]
6a6ca1cf9ff501037204ff4e3de11e6c5446b544
1,361
cpp
C++
tests/matrix.cpp
KPO-2020-2021/zad3-Olszowy21
03b2212358a2dc2211b9b4ffde4a5f3d41352e01
[ "Unlicense" ]
null
null
null
tests/matrix.cpp
KPO-2020-2021/zad3-Olszowy21
03b2212358a2dc2211b9b4ffde4a5f3d41352e01
[ "Unlicense" ]
null
null
null
tests/matrix.cpp
KPO-2020-2021/zad3-Olszowy21
03b2212358a2dc2211b9b4ffde4a5f3d41352e01
[ "Unlicense" ]
null
null
null
#include "../tests/doctest/doctest.h" #include "matrix.hh" #include "size.hh" #include "vector.hh" #include "rectangle.hh" TEST_CASE("Test konstruktorów bezparametrycznych") { Matrix macierz = Matrix(); Matrix test; test(0, 0) = 0; test(1, 0) = 0; test(0, 1) = 0; test(1, 1) = 0; CHECK(macierz == test); } TEST_CASE("Test konstruktorów parametrycznych") { double tmp[SIZE][SIZE]; tmp[0][0] = 1; tmp[0][1] = 2; tmp[1][0] = 3; tmp[1][1] = 4; Matrix macierz = Matrix(tmp); Matrix test; test(0, 0) = 1.000001; test(1, 0) = 3.0000009; test(0, 1) = 2.0000005; test(1, 1) = 4.00000000005; CHECK(macierz == test); } TEST_CASE("Test przeciążenia mnożenia MACIERZ * WEKTOR") { Matrix macierz; Vector wektor(2, 2); Vector test; Vector Wynik(6, 12); macierz(0, 0) = 1; macierz(1, 0) = 2; macierz(0, 1) = 2; macierz(1, 1) = 4; test = macierz * wektor; CHECK(Wynik == test); } TEST_CASE("Test operatora []") { Matrix macierz = Matrix(); std::ostringstream Strumien_out; Strumien_out << macierz.operator[](0); CHECK("0" == Strumien_out.str()); } TEST_CASE("Test operatora ()") { Matrix macierz = Matrix(); std::ostringstream Strumien_out; Strumien_out << macierz(1, 1); CHECK("0" == Strumien_out.str()); }
17.0125
56
0.58119
[ "vector" ]
6a75fe81ef4fda2385f94e3a2b2bd2e939d1e5c5
2,927
cpp
C++
src/third_party/angle/src/libANGLE/SizedMRUCache_unittest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
src/third_party/angle/src/libANGLE/SizedMRUCache_unittest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
src/third_party/angle/src/libANGLE/SizedMRUCache_unittest.cpp
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
null
null
null
// // Copyright 2017 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // SizedMRUCache_unittest.h: Unit tests for the sized MRU cached. #include <gtest/gtest.h> #include "libANGLE/SizedMRUCache.h" namespace angle { using Blob = std::vector<uint8_t>; Blob MakeBlob(size_t size) { Blob blob; for (uint8_t value = 0; value < size; ++value) { blob.push_back(value); } return blob; } // Test a cache with a value that takes up maximum size. TEST(SizedMRUCacheTest, MaxSizedValue) { constexpr size_t kSize = 32; SizedMRUCache<std::string, Blob> sizedCache(kSize); EXPECT_TRUE(sizedCache.put("test", MakeBlob(kSize), kSize)); EXPECT_EQ(32u, sizedCache.size()); EXPECT_FALSE(sizedCache.empty()); EXPECT_TRUE(sizedCache.put("test2", MakeBlob(kSize), kSize)); EXPECT_EQ(32u, sizedCache.size()); EXPECT_FALSE(sizedCache.empty()); const Blob *blob = nullptr; EXPECT_FALSE(sizedCache.get("test", &blob)); sizedCache.clear(); EXPECT_TRUE(sizedCache.empty()); } // Test a cache with many small values, that it can handle unlimited inserts. TEST(SizedMRUCacheTest, ManySmallValues) { constexpr size_t kSize = 32; SizedMRUCache<size_t, size_t> sizedCache(kSize); for (size_t value = 0; value < kSize; ++value) { size_t valueCopy = value; EXPECT_TRUE(sizedCache.put(value, std::move(valueCopy), 1)); const size_t *qvalue = nullptr; EXPECT_TRUE(sizedCache.get(value, &qvalue)); if (qvalue) { EXPECT_EQ(value, *qvalue); } } EXPECT_EQ(32u, sizedCache.size()); EXPECT_FALSE(sizedCache.empty()); // Putting one element evicts the first element. EXPECT_TRUE(sizedCache.put(kSize, std::move(static_cast<int>(kSize)), 1)); const size_t *qvalue = nullptr; EXPECT_FALSE(sizedCache.get(0, &qvalue)); // Putting one large element cleans out the whole stack. EXPECT_TRUE(sizedCache.put(kSize + 1, kSize + 1, kSize)); EXPECT_EQ(32u, sizedCache.size()); EXPECT_FALSE(sizedCache.empty()); for (size_t value = 0; value <= kSize; ++value) { EXPECT_FALSE(sizedCache.get(value, &qvalue)); } EXPECT_TRUE(sizedCache.get(kSize + 1, &qvalue)); if (qvalue) { EXPECT_EQ(kSize + 1, *qvalue); } // Put a bunch of items in the cache sequentially. for (size_t value = 0; value < kSize * 10; ++value) { size_t valueCopy = value; EXPECT_TRUE(sizedCache.put(value, std::move(valueCopy), 1)); } EXPECT_EQ(32u, sizedCache.size()); } // Tests putting an oversize element. TEST(SizedMRUCacheTest, OversizeValue) { constexpr size_t kSize = 32; SizedMRUCache<size_t, size_t> sizedCache(kSize); EXPECT_FALSE(sizedCache.put(5, 5, 100)); } } // namespace angle
26.369369
78
0.65972
[ "vector" ]
6a7be820c1f4e47587e8f3cc23cd355a5deb3235
5,934
cpp
C++
cpp/open3d/t/geometry/TriangleMesh.cpp
leomariga/Open3D
d197339fcd29ad0803a182ef8953d89e563f94d7
[ "MIT" ]
1
2021-06-27T22:04:38.000Z
2021-06-27T22:04:38.000Z
cpp/open3d/t/geometry/TriangleMesh.cpp
leomariga/Open3D
d197339fcd29ad0803a182ef8953d89e563f94d7
[ "MIT" ]
null
null
null
cpp/open3d/t/geometry/TriangleMesh.cpp
leomariga/Open3D
d197339fcd29ad0803a182ef8953d89e563f94d7
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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 "open3d/t/geometry/TriangleMesh.h" #include <Eigen/Core> #include <string> #include <unordered_map> #include "open3d/core/EigenConverter.h" #include "open3d/core/ShapeUtil.h" #include "open3d/core/Tensor.h" namespace open3d { namespace t { namespace geometry { TriangleMesh::TriangleMesh(const core::Device &device) : Geometry(Geometry::GeometryType::TriangleMesh, 3), device_(device), vertex_attr_(TensorMap("vertices")), triangle_attr_(TensorMap("triangles")) {} TriangleMesh::TriangleMesh(const core::Tensor &vertices, const core::Tensor &triangles) : TriangleMesh([&]() { if (vertices.GetDevice() != triangles.GetDevice()) { utility::LogError( "vertices' device {} does not match triangles' device " "{}.", vertices.GetDevice().ToString(), triangles.GetDevice().ToString()); } return vertices.GetDevice(); }()) { SetVertices(vertices); SetTriangles(triangles); } geometry::TriangleMesh TriangleMesh::FromLegacyTriangleMesh( const open3d::geometry::TriangleMesh &mesh_legacy, core::Dtype float_dtype, core::Dtype int_dtype, const core::Device &device) { if (float_dtype != core::Dtype::Float32 && float_dtype != core::Dtype::Float64) { utility::LogError("float_dtype must be Float32 or Float64, but got {}.", float_dtype.ToString()); } if (int_dtype != core::Dtype::Int32 && int_dtype != core::Dtype::Int64) { utility::LogError("int_dtype must be Int32 or Int64, but got {}.", int_dtype.ToString()); } TriangleMesh mesh(device); if (mesh_legacy.HasVertices()) { mesh.SetVertices(core::eigen_converter::EigenVector3dVectorToTensor( mesh_legacy.vertices_, float_dtype, device)); } else { utility::LogWarning("Creating from empty legacy TriangleMesh."); } if (mesh_legacy.HasVertexColors()) { mesh.SetVertexColors(core::eigen_converter::EigenVector3dVectorToTensor( mesh_legacy.vertex_colors_, float_dtype, device)); } if (mesh_legacy.HasVertexNormals()) { mesh.SetVertexNormals( core::eigen_converter::EigenVector3dVectorToTensor( mesh_legacy.vertex_normals_, float_dtype, device)); } if (mesh_legacy.HasTriangles()) { mesh.SetTriangles(core::eigen_converter::EigenVector3iVectorToTensor( mesh_legacy.triangles_, int_dtype, device)); } if (mesh_legacy.HasTriangleNormals()) { mesh.SetTriangleNormals( core::eigen_converter::EigenVector3dVectorToTensor( mesh_legacy.triangle_normals_, float_dtype, device)); } return mesh; } open3d::geometry::TriangleMesh TriangleMesh::ToLegacyTriangleMesh() const { open3d::geometry::TriangleMesh mesh_legacy; if (HasVertices()) { mesh_legacy.vertices_ = core::eigen_converter::TensorToEigenVector3dVector( GetVertices()); } if (HasVertexColors()) { mesh_legacy.vertex_colors_ = core::eigen_converter::TensorToEigenVector3dVector( GetVertexColors()); } if (HasVertexNormals()) { mesh_legacy.vertex_normals_ = core::eigen_converter::TensorToEigenVector3dVector( GetVertexNormals()); } if (HasTriangles()) { mesh_legacy.triangles_ = core::eigen_converter::TensorToEigenVector3iVector( GetTriangles()); } if (HasTriangleNormals()) { mesh_legacy.triangle_normals_ = core::eigen_converter::TensorToEigenVector3dVector( GetTriangleNormals()); } return mesh_legacy; } TriangleMesh TriangleMesh::To(const core::Device &device, bool copy) const { if (!copy && GetDevice() == device) { return *this; } TriangleMesh mesh(device); for (const auto &kv : triangle_attr_) { mesh.SetTriangleAttr(kv.first, kv.second.To(device, /*copy=*/true)); } for (const auto &kv : vertex_attr_) { mesh.SetVertexAttr(kv.first, kv.second.To(device, /*copy=*/true)); } return mesh; } } // namespace geometry } // namespace t } // namespace open3d
38.532468
80
0.612403
[ "mesh", "geometry" ]
6a7e7ad506efea6afc790ca2511732e1c4bbfab4
9,152
cc
C++
chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.h" #include <utility> #include "chrome/browser/ui/views/accessibility/non_accessible_image_view.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/webauthn/authenticator_request_sheet_model.h" #include "chrome/browser/webauthn/authenticator_request_dialog_model.h" #include "chrome/grit/generated_resources.h" #include "components/strings/grit/components_strings.h" #include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/native_theme/native_theme.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/button/image_button_factory.h" #include "ui/views/controls/label.h" #include "ui/views/controls/progress_bar.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/metadata/metadata_impl_macros.h" namespace { // Fixed height of the illustration shown in the top half of the sheet. constexpr int kIllustrationHeight = 148; // Height of the progress bar style activity indicator shown at the top of some // sheets. constexpr int kActivityIndicatorHeight = 4; using ImageColorScheme = AuthenticatorRequestSheetModel::ImageColorScheme; } // namespace using views::BoxLayout; AuthenticatorRequestSheetView::AuthenticatorRequestSheetView( std::unique_ptr<AuthenticatorRequestSheetModel> model) : model_(std::move(model)) {} AuthenticatorRequestSheetView::~AuthenticatorRequestSheetView() = default; void AuthenticatorRequestSheetView::ReInitChildViews() { RemoveAllChildViews(true /* delete_children */); // No need to add further spacing between the upper and lower half. The image // is designed to fill the dialog's top half without any border/margins, and // the |lower_half| will already contain the standard dialog borders. SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(), 0 /* between_child_spacing */)); std::unique_ptr<views::View> upper_half = CreateIllustrationWithOverlays(); std::unique_ptr<views::View> lower_half = CreateContentsBelowIllustration(); AddChildView(upper_half.release()); AddChildView(lower_half.release()); InvalidateLayout(); } views::View* AuthenticatorRequestSheetView::GetInitiallyFocusedView() { return step_specific_content_; } std::unique_ptr<views::View> AuthenticatorRequestSheetView::BuildStepSpecificContent() { return nullptr; } std::unique_ptr<views::View> AuthenticatorRequestSheetView::CreateIllustrationWithOverlays() { const int illustration_width = ChromeLayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_MODAL_DIALOG_PREFERRED_WIDTH); const gfx::Size illustration_size(illustration_width, kIllustrationHeight); // The container view has no layout, so its preferred size is hardcoded to // match the size of the image, and all overlays are absolutely positioned. auto image_with_overlays = std::make_unique<views::View>(); image_with_overlays->SetPreferredSize(illustration_size); auto image_view = std::make_unique<NonAccessibleImageView>(); step_illustration_ = image_view.get(); UpdateIconImageFromModel(); image_view->SetSize(illustration_size); image_view->SetVerticalAlignment(views::ImageView::Alignment::kLeading); image_with_overlays->AddChildView(image_view.release()); if (model()->IsActivityIndicatorVisible()) { auto activity_indicator = std::make_unique<views::ProgressBar>( kActivityIndicatorHeight, false /* allow_round_corner */); activity_indicator->SetValue(-1 /* inifinite animation */); activity_indicator->SetBackgroundColor(SK_ColorTRANSPARENT); activity_indicator->SetPreferredSize( gfx::Size(illustration_width, kActivityIndicatorHeight)); activity_indicator->SizeToPreferredSize(); image_with_overlays->AddChildView(activity_indicator.release()); } if (model()->IsBackButtonVisible()) { auto back_arrow = views::CreateVectorImageButton(base::BindRepeating( &AuthenticatorRequestSheetModel::OnBack, base::Unretained(model()))); back_arrow->SetAccessibleName(l10n_util::GetStringUTF16( IDS_BACK_BUTTON_AUTHENTICATOR_REQUEST_DIALOG)); // Position the back button so that there is the standard amount of padding // between the top/left side of the back button and the dialog borders. const gfx::Insets dialog_insets = views::LayoutProvider::Get()->GetDialogInsetsForContentType( views::CONTROL, views::CONTROL); auto color_reference = std::make_unique<views::Label>( base::string16(), views::style::CONTEXT_DIALOG_TITLE, views::style::STYLE_PRIMARY); back_arrow->SizeToPreferredSize(); back_arrow->SetX(dialog_insets.left()); back_arrow->SetY(dialog_insets.top()); back_arrow_ = back_arrow.get(); back_arrow_button_ = image_with_overlays->AddChildView(std::move(back_arrow)); UpdateIconColors(); } return image_with_overlays; } std::unique_ptr<views::View> AuthenticatorRequestSheetView::CreateContentsBelowIllustration() { auto contents = std::make_unique<views::View>(); BoxLayout* contents_layout = contents->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(), views::LayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_UNRELATED_CONTROL_VERTICAL))); contents->SetBorder(views::CreateEmptyBorder( views::LayoutProvider::Get()->GetDialogInsetsForContentType( views::CONTROL, views::CONTROL))); auto label_container = std::make_unique<views::View>(); label_container->SetLayoutManager(std::make_unique<BoxLayout>( BoxLayout::Orientation::kVertical, gfx::Insets(), views::LayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_RELATED_CONTROL_VERTICAL))); auto title_label = std::make_unique<views::Label>( model()->GetStepTitle(), views::style::CONTEXT_DIALOG_TITLE, views::style::STYLE_PRIMARY); title_label->SetMultiLine(true); title_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); title_label->SetAllowCharacterBreak(true); label_container->AddChildView(title_label.release()); base::string16 description = model()->GetStepDescription(); if (!description.empty()) { auto description_label = std::make_unique<views::Label>( std::move(description), views::style::CONTEXT_DIALOG_BODY_TEXT); description_label->SetMultiLine(true); description_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); description_label->SetAllowCharacterBreak(true); label_container->AddChildView(description_label.release()); } base::string16 additional_desciption = model()->GetAdditionalDescription(); if (!additional_desciption.empty()) { auto label = std::make_unique<views::Label>(std::move(additional_desciption), views::style::CONTEXT_DIALOG_BODY_TEXT); label->SetMultiLine(true); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetAllowCharacterBreak(true); label_container->AddChildView(label.release()); } contents->AddChildView(label_container.release()); std::unique_ptr<views::View> step_specific_content = BuildStepSpecificContent(); if (step_specific_content) { step_specific_content_ = step_specific_content.get(); contents->AddChildView(step_specific_content.release()); contents_layout->SetFlexForView(step_specific_content_, 1); } base::string16 error = model()->GetError(); if (!error.empty()) { auto error_label = std::make_unique<views::Label>( std::move(error), views::style::CONTEXT_LABEL, STYLE_RED); error_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); error_label->SetMultiLine(true); error_label_ = contents->AddChildView(std::move(error_label)); } return contents; } void AuthenticatorRequestSheetView::OnThemeChanged() { views::View::OnThemeChanged(); UpdateIconImageFromModel(); UpdateIconColors(); } void AuthenticatorRequestSheetView::UpdateIconImageFromModel() { if (!step_illustration_) return; gfx::IconDescription icon_description(model()->GetStepIllustration( GetNativeTheme()->ShouldUseDarkColors() ? ImageColorScheme::kDark : ImageColorScheme::kLight)); step_illustration_->SetImage(gfx::CreateVectorIcon(icon_description)); } void AuthenticatorRequestSheetView::UpdateIconColors() { if (back_arrow_) { views::SetImageFromVectorIcon( back_arrow_, vector_icons::kBackArrowIcon, color_utils::DeriveDefaultIconColor(views::style::GetColor( *this, views::style::CONTEXT_LABEL, views::style::STYLE_PRIMARY))); } } BEGIN_METADATA(AuthenticatorRequestSheetView, views::View) END_METADATA
40.140351
80
0.753278
[ "model" ]
6a7ff5ee74e0f8b0d56a2394bcce0bc5b1e9166e
31,911
cpp
C++
AllJoyn/Samples/ZWaveAdapter/AdapterLib/ZWaveAdapter.cpp
shuWebDev/samples
4b2c23cf16bdbe58cb2beba7c202c85242419d2e
[ "MIT" ]
null
null
null
AllJoyn/Samples/ZWaveAdapter/AdapterLib/ZWaveAdapter.cpp
shuWebDev/samples
4b2c23cf16bdbe58cb2beba7c202c85242419d2e
[ "MIT" ]
null
null
null
AllJoyn/Samples/ZWaveAdapter/AdapterLib/ZWaveAdapter.cpp
shuWebDev/samples
4b2c23cf16bdbe58cb2beba7c202c85242419d2e
[ "MIT" ]
1
2018-07-16T06:29:08.000Z
2018-07-16T06:29:08.000Z
// Copyright (c) 2015, Microsoft Corporation // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include "pch.h" #include "ZWaveAdapter.h" #include "ZWaveAdapterDevice.h" #include "ZWaveAdapterProperty.h" #include "ZWaveAdapterSignal.h" #include "ZWaveAdapterValue.h" #include "ZWaveAdapterMethod.h" #include "SwitchControlPanelHandler.h" #include "UniversalControlPanelHandler.h" #include "LSFHandler.h" #include "Misc.h" //openzwave #include "Options.h" #include "Manager.h" #include <ppltasks.h> using namespace Platform; using namespace Platform::Collections; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Storage; using namespace Windows::Devices::SerialCommunication; using namespace Windows::Devices::Enumeration; using namespace Concurrency; using namespace BridgeRT; using namespace DsbCommon; using namespace OpenZWave; using namespace std; using namespace concurrency; using namespace Windows::System::Threading; namespace AdapterLib { // {7C78ED73-E66D-4DE0-AE67-085443E1941D} static const GUID DSB_ZWAVE_APPLICATION_GUID = { 0x7c78ed73, 0xe66d, 0x4de0,{ 0xae, 0x67, 0x8, 0x54, 0x43, 0xe1, 0x94, 0x1d } }; // Light Bulb (from Dimmable Switch) // Manufacturer: Linear static const std::string LINEAR__LIGHT_BULB__PRODUCT_TYPE = "4754"; static const std::string LINEAR__LIGHT_BULB__PRODUCT_ID = "3038"; // Light Bulb (from Switch) // Manufacturer: Aeon switch static const std::string AEON__LIGHT_BULB__PRODUCT_TYPE = "0003"; static const std::string AEON__LIGHT_BULB__PRODUCT_ID = "0018"; // // ZWaveAdapter class. // Description: // The class that implements the ZWave Adapter as IAdapter. // ZWaveAdapter::ZWaveAdapter() : m_pMgr(nullptr) , m_bShutdown(false) { Windows::ApplicationModel::Package^ package = Windows::ApplicationModel::Package::Current; Windows::ApplicationModel::PackageId^ packageId = package->Id; Windows::ApplicationModel::PackageVersion versionFromPkg = packageId->Version; this->m_vendor = ref new String(cVendor.c_str()); this->m_adapterName = ref new String(cAdapterName.c_str()); // the adapter prefix must be something like "com.mycompany" (only alpha num and dots) // it is used by the Device System Bridge as root string for all services and interfaces it exposes this->m_exposedAdapterPrefix = ref new String(cAdapterPrefix.c_str()); this->m_exposedApplicationGuid = Platform::Guid(DSB_ZWAVE_APPLICATION_GUID); if (nullptr != package && nullptr != packageId) { this->m_exposedApplicationName = packageId->Name; this->m_version = versionFromPkg.Major.ToString() + L"." + versionFromPkg.Minor.ToString() + L"." + versionFromPkg.Revision.ToString() + L"." + versionFromPkg.Build.ToString(); } else { this->m_exposedApplicationName = L"DeviceSystemBridge"; this->m_version = L"0.0.0.0"; } } ZWaveAdapter::~ZWaveAdapter() { Shutdown(); } _Use_decl_annotations_ uint32 ZWaveAdapter::GetConfiguration(Platform::Array<byte>^* ConfigurationDataPtr) { uint32 status = ERROR_SUCCESS; // Sync access to configuration parameters AutoLock sync(&m_configLock, true); String^ configurationXml; status = WIN32_FROM_HRESULT(m_adapterConfig.GetConfig(&configurationXml)); if (status != ERROR_SUCCESS) { goto done; } status = StringToArray(configurationXml, ConfigurationDataPtr); done: return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::SetConfiguration(const Platform::Array<byte>^ ConfigurationData) { uint32 status = ERROR_SUCCESS; // Sync access to configuration parameters AutoLock sync(&m_configLock, true); try { String^ configurationXml = ref new String((wchar_t*)ConfigurationData->Data); status = WIN32_FROM_HRESULT(m_adapterConfig.SetConfig(configurationXml)); } catch (Platform::OutOfMemoryException^ ex) { status = WIN32_FROM_HRESULT(ex->HResult); goto done; } done: return status; } uint32 ZWaveAdapter::Initialize() { uint32 status = ERROR_SUCCESS; status = WIN32_FROM_HRESULT(m_adapterConfig.Init()); if (status != ERROR_SUCCESS) { goto done; } m_bShutdown = false; //configurations Options::Create(ConvertTo<string>(AdapterConfig::GetConfigPath()), ConvertTo<string>(AdapterConfig::GetUserPath()), ""); Options::Get()->AddOptionBool("Logging", false); //Disable logging Options::Get()->AddOptionInt("PollInterval", 500); Options::Get()->AddOptionBool("IntervalBetweenPolls", true); Options::Get()->AddOptionBool("ConsoleOutput", false); Options::Get()->AddOptionBool("SaveConfiguration", false); Options::Get()->AddOptionString("ControllerPath", "", false); Options::Get()->AddOptionInt("ControllerInterface", (int)(Driver::ControllerInterface_Serial)); Options::Get()->AddOptionInt("NetworkMonitorInterval", 30000); //30 seconds Options::Get()->Lock(); //instantiate the Manager object m_pMgr = Manager::Create(); //add awatcher for notification m_pMgr->AddWatcher(OnNotification, reinterpret_cast<void*>(this)); //create signals status = CreateSignals(); if (status != ERROR_SUCCESS) { goto done; } //Get the network monitor interval int32 nInterval; Options::Get()->GetOptionAsInt("NetworkMonitorInterval", &nInterval); m_networkMonitorTimeout = nInterval * 10000; //in 100 nano second interval StartDeviceDiscovery(); done: return status; } uint32 ZWaveAdapter::Shutdown() { uint32 status = ERROR_SUCCESS; m_bShutdown = true; if (m_DiscoveryTimer) { m_DiscoveryTimer->Cancel(); m_DiscoveryTimer = nullptr; } if (m_MonitorTimer) { m_MonitorTimer->Cancel(); m_MonitorTimer = nullptr; } Manager::Destroy(); m_pMgr = nullptr; Options::Destroy(); return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::EnumDevices(ENUM_DEVICES_OPTIONS Options, IAdapterDeviceVector^* DeviceListPtr, IAdapterIoRequest^* RequestPtr) { uint32 status = ERROR_SUCCESS; UNREFERENCED_PARAMETER(Options); if (RequestPtr != nullptr) { *RequestPtr = nullptr; } if (DeviceListPtr == nullptr) { status = ERROR_INVALID_PARAMETER; goto done; } { AutoLock sync(&m_deviceListLock, true); //just return whatever list we have. the device will be notified as they arrive *DeviceListPtr = ref new AdapterDeviceVector(m_devices); } done: return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::GetProperty(IAdapterProperty^ Property, IAdapterIoRequest^* RequestPtr) { uint32 status = ERROR_SUCCESS; if (RequestPtr != nullptr) { *RequestPtr = nullptr; } ZWaveAdapterProperty^ adapterProperty = dynamic_cast<ZWaveAdapterProperty^>(Property); ZWaveAdapterDevice^ device = nullptr; if (adapterProperty == nullptr) { status = ERROR_INVALID_HANDLE; goto done; } { //get the device first auto iter = FindDevice(m_devices, adapterProperty->m_valueId.GetHomeId(), adapterProperty->m_valueId.GetNodeId()); if (iter == m_devices.end()) { status = ERROR_INVALID_HANDLE; goto done; } device = dynamic_cast<ZWaveAdapterDevice^>(*iter); } //get the property object from the internal device list { auto iter = device->GetProperty(adapterProperty->m_valueId); if (iter == device->m_properties.end()) { status = ERROR_INVALID_HANDLE; goto done; } //refresh value dynamic_cast<ZWaveAdapterProperty^>(*iter)->UpdateValue(); auto attributes = dynamic_cast<ZWaveAdapterProperty^>(*iter)->m_attributes; adapterProperty->m_attributes = attributes; } done: return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::SetProperty(IAdapterProperty^ Property, IAdapterIoRequest^* RequestPtr) { uint32 status = ERROR_SUCCESS; if (RequestPtr != nullptr) { *RequestPtr = nullptr; } ZWaveAdapterProperty^ adapterProperty = dynamic_cast<ZWaveAdapterProperty^>(Property); ZWaveAdapterValue^ attribute = nullptr; if (adapterProperty == nullptr) { status = ERROR_INVALID_HANDLE; goto done; } //only the value field is settable attribute = adapterProperty->GetAttributeByName(ref new String(ValueName.c_str())); if (attribute == nullptr) { status = ERROR_INVALID_HANDLE; goto done; } status = adapterProperty->SetValue(attribute->Data); done: return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::GetPropertyValue( IAdapterProperty^ Property, String^ AttributeName, IAdapterValue^* ValuePtr, IAdapterIoRequest^* RequestPtr ) { uint32 status = ERROR_SUCCESS; if (RequestPtr != nullptr) { *RequestPtr = nullptr; } ZWaveAdapterProperty^ adapterProperty = dynamic_cast<ZWaveAdapterProperty^>(Property); ZWaveAdapterDevice^ device = nullptr; ZWaveAdapterValue^ attribute = nullptr; if (adapterProperty == nullptr) { status = ERROR_INVALID_HANDLE; goto done; } { //get the device first auto iter = FindDevice(m_devices, adapterProperty->m_valueId.GetHomeId(), adapterProperty->m_valueId.GetNodeId()); if (iter == m_devices.end()) { status = ERROR_INVALID_HANDLE; goto done; } device = dynamic_cast<ZWaveAdapterDevice^>(*iter); } //get the property object from the internal device list { auto iter = device->GetProperty(adapterProperty->m_valueId); if (iter == device->m_properties.end()) { status = ERROR_INVALID_HANDLE; goto done; } //refresh value dynamic_cast<ZWaveAdapterProperty^>(*iter)->UpdateValue(); attribute = dynamic_cast<ZWaveAdapterProperty^>(*iter)->GetAttributeByName(AttributeName);; if (attribute == nullptr) { status = ERROR_NOT_FOUND; goto done; } try { *ValuePtr = ref new ZWaveAdapterValue(attribute); } catch (OutOfMemoryException^) { status = ERROR_NOT_ENOUGH_MEMORY; goto done; } } done: return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::SetPropertyValue( IAdapterProperty^ Property, IAdapterValue^ Value, IAdapterIoRequest^* RequestPtr ) { uint32 status = ERROR_SUCCESS; if (RequestPtr != nullptr) { *RequestPtr = nullptr; } ZWaveAdapterProperty^ adapterProperty = dynamic_cast<ZWaveAdapterProperty^>(Property); if (adapterProperty == nullptr) { status = ERROR_INVALID_HANDLE; goto done; } //only setting to value attribute permitted if (ValueName != Value->Name->Data()) { status = ERROR_NOT_SUPPORTED; goto done; } status = adapterProperty->SetValue(Value->Data); done: return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::CallMethod(IAdapterMethod^ Method, IAdapterIoRequest^* RequestPtr) { if (RequestPtr != nullptr) { *RequestPtr = nullptr; } ZWaveAdapterMethod^ adapterMethod = dynamic_cast<ZWaveAdapterMethod^>(Method); if (adapterMethod == nullptr) { return ERROR_INVALID_PARAMETER; } adapterMethod->Execute(); return adapterMethod->HResult; } _Use_decl_annotations_ uint32 ZWaveAdapter::RegisterSignalListener( IAdapterSignal^ Signal, IAdapterSignalListener^ Listener, Object^ ListenerContext ) { uint32 status = ERROR_SUCCESS; try { // Sync access to listeners list AutoLock sync(&m_signalLock, true); // We use the hash code as the signal key int mmapkey = Signal->GetHashCode(); // check if the listener is already registered for the signal auto handlers = m_signalListeners.equal_range(mmapkey); for (auto iter = handlers.first; iter != handlers.second; ++iter) { if (iter->second.Listener == Listener) { goto done; } } // add it to the map. m_signalListeners.insert({ mmapkey, SIGNAL_LISTENER_ENTRY(Signal, Listener, ListenerContext) }); } catch (OutOfMemoryException^) { status = ERROR_NOT_ENOUGH_MEMORY; goto done; } done: return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::UnregisterSignalListener(IAdapterSignal^ Signal, IAdapterSignalListener^ Listener) { uint32 status = ERROR_NOT_FOUND; // Sync access to listeners list AutoLock sync(&m_signalLock, true); // We use the hash code as the signal key int mmapkey = Signal->GetHashCode(); // get all the listeners for the SignalHandle auto handlers = m_signalListeners.equal_range(mmapkey); for (auto iter = handlers.first; iter != handlers.second; ++iter) { if (iter->second.Listener == Listener) { // found it remove it m_signalListeners.erase(iter); status = ERROR_SUCCESS; break; } } return status; } _Use_decl_annotations_ uint32 ZWaveAdapter::NotifySignalListener(IAdapterSignal^ Signal) { uint32 status = ERROR_INVALID_HANDLE; // Sync access to listeners list AutoLock sync(&m_signalLock, true); // We use the hash code as the signal key int mmapkey = Signal->GetHashCode(); // Iterate through listeners auto handlerRange = m_signalListeners.equal_range(mmapkey); vector<pair<int, SIGNAL_LISTENER_ENTRY>> handlers(handlerRange.first, handlerRange.second); for (auto iter = handlers.begin(); iter != handlers.end(); ++iter) { // Notify the listener IAdapterSignalListener^ listener = iter->second.Listener; Object^ listenerContext = iter->second.Context; listener->AdapterSignalHandler(Signal, listenerContext); status = ERROR_SUCCESS; } return status; } uint32 ZWaveAdapter::CreateSignals() { uint32 status = ERROR_SUCCESS; try { // Device arrival signal ZWaveAdapterSignal^ signal = ref new ZWaveAdapterSignal(Constants::DEVICE_ARRIVAL_SIGNAL); signal->AddParam(ref new ZWaveAdapterValue( Constants::DEVICE_ARRIVAL__DEVICE_HANDLE, ref new ZWaveAdapterDevice(0, 0) //place holder ) ); m_signals.push_back(signal); //Device removal signal signal = ref new ZWaveAdapterSignal(Constants::DEVICE_REMOVAL_SIGNAL); signal->AddParam(ref new ZWaveAdapterValue( Constants::DEVICE_REMOVAL__DEVICE_HANDLE, ref new ZWaveAdapterDevice(0, 0) //place holder ) ); m_signals.push_back(signal); } catch (OutOfMemoryException^) { status = ERROR_NOT_ENOUGH_MEMORY; } return status; } vector<IAdapterDevice^>::iterator ZWaveAdapter::FindDevice(vector<IAdapterDevice^>& deviceList, uint32 homeId, uint32 nodeId) { return find_if(deviceList.begin(), deviceList.end(), [=](IAdapterDevice^ device) { return ((dynamic_cast<ZWaveAdapterDevice^>(device))->m_homeId == homeId) && ((dynamic_cast<ZWaveAdapterDevice^>(device))->m_nodeId == nodeId); }); } IAdapterSignal^ ZWaveAdapter::GetSignal(String^ name) { for (auto signal : m_signals) { if (signal->Name == name) { return signal; } } return nullptr; } void ZWaveAdapter::StartDeviceDiscovery() { string path; int inf = static_cast<int>(Driver::ControllerInterface_Serial); if (Options::Get()) { Options::Get()->GetOptionAsString("ControllerPath", &path); Options::Get()->GetOptionAsInt("ControllerInterface", &inf); auto selector = SerialDevice::GetDeviceSelector(); create_task(DeviceInformation::FindAllAsync(selector)) .then([path, inf, this](DeviceInformationCollection ^ devices) { for (auto iterator = devices->First(); iterator->HasCurrent; iterator->MoveNext()) { string currentId = ConvertTo<string>(iterator->Current->Id); if (currentId.find(path) != string::npos && m_pMgr) { m_pMgr->AddDriver(currentId, (Driver::ControllerInterface)inf); } } }); } //Set the time for next discovery TimeSpan ts; ts.Duration = m_networkMonitorTimeout; m_DiscoveryTimer = ThreadPoolTimer::CreateTimer(ref new TimerElapsedHandler([this](ThreadPoolTimer^ timer) { StartDeviceDiscovery(); }), ts); } void ZWaveAdapter::AddDevice(const uint32 homeId, const uint8 nodeId, bool bPending) { AutoLock sync(&m_deviceListLock, true); if(bPending) { ZWaveAdapterDevice^ device = ref new ZWaveAdapterDevice(homeId, nodeId); m_pendingDevices.push_back(device); } else { auto iter = FindDevice(m_pendingDevices, homeId, nodeId); if (iter != m_pendingDevices.end()) { ZWaveAdapterDevice^ currDevice = dynamic_cast<ZWaveAdapterDevice^>(*iter); currDevice->Initialize(); m_devices.push_back(currDevice); m_pendingDevices.erase(iter); // Create a Control Panel for *any* device UniversalControlPanelHandler^ myControlPanel = ref new UniversalControlPanelHandler(currDevice); currDevice->ControlPanelHandler = myControlPanel; // Create a Lighting Service Handler if the device is a lighting device std::string deviceProductType = m_pMgr->GetNodeProductType(homeId, nodeId); std::string deviceProductId = m_pMgr->GetNodeProductId(homeId, nodeId); if ((LINEAR__LIGHT_BULB__PRODUCT_TYPE == deviceProductType && LINEAR__LIGHT_BULB__PRODUCT_ID == deviceProductId) // || // (AEON__LIGHT_BULB__PRODUCT_TYPE == deviceProductType && // AEON__LIGHT_BULB__PRODUCT_ID == deviceProductId) ) { currDevice->SetParent(this); currDevice->AddLampStateChangedSignal(); currDevice->LightingServiceHandler = ref new LSFHandler(currDevice); } //notify the signal AutoLock sync2(&m_signalLock, true); IAdapterSignal^ signal = GetSignal(Constants::DEVICE_ARRIVAL_SIGNAL); if (signal != nullptr) { // Set the 'Device_Handle' signal parameter signal->Params->GetAt(0)->Data = m_devices.back(); NotifySignalListener(signal); } } } } void ZWaveAdapter::RemoveDevice(const uint32 homeId, const uint8 nodeId, bool bMoveToPending) { AutoLock sync(&m_deviceListLock, true); // Remove the node from our list auto iter = FindDevice(m_devices, homeId, nodeId); if (iter != m_devices.end()) { //notify the signal AutoLock sync2(&m_signalLock, true); IAdapterSignal^ signal = GetSignal(Constants::DEVICE_REMOVAL_SIGNAL); if (signal != nullptr) { // Set the 'Device_Handle' signal parameter signal->Params->GetAt(0)->Data = *iter; NotifySignalListener(signal); } if (bMoveToPending) { m_pendingDevices.push_back(*iter); } //now erase it m_devices.erase(iter); } else if(!bMoveToPending) { //check if the device is in pending list and remove it iter = FindDevice(m_pendingDevices, homeId, nodeId); if (iter != m_pendingDevices.end()) { m_pendingDevices.erase(iter); //no need to notify the signal as it was never announced } } } void ZWaveAdapter::RemoveAllDevices(uint32 homeId) { AutoLock sync(&m_deviceListLock, true); AutoLock sync2(&m_signalLock, true); //remove devices from m_devices list auto iter = m_devices.begin(); while(iter != m_devices.end()) { auto device = dynamic_cast<ZWaveAdapterDevice^>(*iter); if (device->m_homeId == homeId) { //notify IAdapterSignal^ signal = GetSignal(Constants::DEVICE_REMOVAL_SIGNAL); if (signal != nullptr) { // Set the 'Device_Handle' signal parameter signal->Params->GetAt(0)->Data = device; NotifySignalListener(signal); } iter = m_devices.erase(iter); } else { ++iter; } } //also remove devices from m_pendingDevices list iter = m_pendingDevices.begin(); while (iter != m_pendingDevices.end()) { auto device = dynamic_cast<ZWaveAdapterDevice^>(*iter); if (device->m_homeId == homeId) { iter = m_pendingDevices.erase(iter); } else { ++iter; } } } void ZWaveAdapter::OnNotification(Notification const* _notification, void* _context) { ZWaveAdapter^ adapter = reinterpret_cast<ZWaveAdapter^>(_context); uint32 const homeId = _notification->GetHomeId(); uint8 const nodeId = _notification->GetNodeId(); try { switch (_notification->GetType()) { case Notification::Type_Notification: { uint8 notifCode = _notification->GetNotification(); switch (notifCode) { case Notification::NotificationCode::Code_Dead: { //The device is dead, move the device to pending devices adapter->RemoveDevice(nodeId, true); break; } case Notification::NotificationCode::Code_Alive: { //if we had already received the info before, move the device to m_devices //and notify Device arrival. //If the info has not been received yet, leave it in m_pendindDevices as more info will follow. if (Manager::Get()->IsNodeInfoReceived(homeId, nodeId)) { adapter->AddDevice(homeId, nodeId, false); } break; } } //switch break; } case Notification::Type_DriverReady: { //Start the DeviceMonitor timer TimeSpan ts; ts.Duration = adapter->m_networkMonitorTimeout; adapter->m_MonitorTimer = ThreadPoolTimer::CreatePeriodicTimer(ref new TimerElapsedHandler([homeId](ThreadPoolTimer^ timer) { if (Manager::Get()) { Manager::Get()->TestNetwork(homeId, 1); } }), ts); break; } case Notification::Type_DriverRemoved: case Notification::Type_DriverFailed: { if (adapter->m_MonitorTimer) { adapter->m_MonitorTimer->Cancel(); adapter->m_MonitorTimer = nullptr; } adapter->RemoveAllDevices(homeId); if ((_notification->GetType() == Notification::Type_DriverFailed) && !(adapter->m_bShutdown)) { //remove the driver if (homeId != 0) { create_task([homeId]() { Manager::Get()->RemoveDriver(Manager::Get()->GetControllerPath(homeId)); }); } } break; } case Notification::Type_NodeAdded: { // Add the new node to our pending device list as we dont yet have all the values for the node adapter->AddDevice(homeId, nodeId, true); break; } case Notification::Type_NodeRemoved: { // Remove the node from our list adapter->RemoveDevice(homeId, nodeId); break; } case Notification::Type_NodeQueriesComplete: { //move the device from the pending list to actual list and notify the signal adapter->AddDevice(homeId, nodeId, false); break; } case Notification::Type_ValueAdded: { //Value added should be received only during the addition of node. Hence look in the pending device list auto iter = adapter->FindDevice(adapter->m_pendingDevices, homeId, nodeId); if (iter != adapter->m_pendingDevices.end()) { //add the value ValueID value = _notification->GetValueID(); dynamic_cast<ZWaveAdapterDevice^>(*iter)->AddPropertyValue(value); } break; } case Notification::Type_ValueRemoved: { //Value removed should be received only during the addition of node. Hence look in the pending device list auto iter = adapter->FindDevice(adapter->m_pendingDevices, homeId, nodeId); if (iter != adapter->m_pendingDevices.end()) { //remove the value dynamic_cast<ZWaveAdapterDevice^>(*iter)->RemovePropertyValue(_notification->GetValueID()); } break; } case Notification::Type_ValueChanged: { //look into device list auto iter = adapter->FindDevice(adapter->m_devices, homeId, nodeId); if (iter != adapter->m_devices.end()) { ZWaveAdapterDevice^ device = dynamic_cast<ZWaveAdapterDevice^>(*iter); //add the value device->UpdatePropertyValue(_notification->GetValueID()); //notify the signal AutoLock sync(&adapter->m_signalLock, true); IAdapterSignal^ signal = device->GetSignal(Constants::CHANGE_OF_VALUE_SIGNAL); if (signal != nullptr) { ZWaveAdapterProperty^ adapterProperty = nullptr; ZWaveAdapterValue^ adapterValue = nullptr; auto adapterPropertyIter = device->GetProperty(_notification->GetValueID()); if (adapterPropertyIter != device->m_properties.end()) { adapterProperty = dynamic_cast<ZWaveAdapterProperty^>(*adapterPropertyIter); //get the AdapterValue adapterValue = adapterProperty->GetAttributeByName(ref new String(ValueName.c_str())); // Set the 'Property_Handle' signal parameter signal->Params->GetAt(0)->Data = adapterProperty; // Set the 'Property_Handle' signal parameter signal->Params->GetAt(1)->Data = adapterValue; adapter->NotifySignalListener(signal); } } } break; } default: break; } } catch (Exception^) { //just ignore } } } // namespace AdapterLib
32.830247
188
0.554072
[ "object", "vector" ]
6a84594f25e78d1bad74131744c27402885b1dad
2,540
cpp
C++
modules/functional/src/voxelization/vox.cpp
Masterchef365/pvcnn
db13331a46f672e74e7b5bde60e7bf30d445cd2d
[ "MIT" ]
477
2019-12-10T01:03:43.000Z
2022-03-28T14:10:08.000Z
modules/functional/src/voxelization/vox.cpp
chaomath/pvcnn
8f07316611067e9a0e2df8b35e4a729a03e0806b
[ "MIT" ]
57
2019-12-10T10:14:26.000Z
2022-03-26T04:59:43.000Z
modules/functional/src/voxelization/vox.cpp
chaomath/pvcnn
8f07316611067e9a0e2df8b35e4a729a03e0806b
[ "MIT" ]
126
2019-12-10T07:59:50.000Z
2022-03-12T07:21:19.000Z
#include "vox.hpp" #include "vox.cuh" #include "../utils.hpp" /* Function: average pool voxelization (forward) Args: features: features, FloatTensor[b, c, n] coords : coords of each point, IntTensor[b, 3, n] resolution : voxel resolution Return: out : outputs, FloatTensor[b, c, s], s = r ** 3 ind : voxel index of each point, IntTensor[b, n] cnt : #points in each voxel index, IntTensor[b, s] */ std::vector<at::Tensor> avg_voxelize_forward(const at::Tensor features, const at::Tensor coords, const int resolution) { CHECK_CUDA(features); CHECK_CUDA(coords); CHECK_CONTIGUOUS(features); CHECK_CONTIGUOUS(coords); CHECK_IS_FLOAT(features); CHECK_IS_INT(coords); int b = features.size(0); int c = features.size(1); int n = features.size(2); int r = resolution; int r2 = r * r; int r3 = r2 * r; at::Tensor ind = torch::zeros( {b, n}, at::device(features.device()).dtype(at::ScalarType::Int)); at::Tensor out = torch::zeros( {b, c, r3}, at::device(features.device()).dtype(at::ScalarType::Float)); at::Tensor cnt = torch::zeros( {b, r3}, at::device(features.device()).dtype(at::ScalarType::Int)); avg_voxelize(b, c, n, r, r2, r3, coords.data_ptr<int>(), features.data_ptr<float>(), ind.data_ptr<int>(), cnt.data_ptr<int>(), out.data_ptr<float>()); return {out, ind, cnt}; } /* Function: average pool voxelization (backward) Args: grad_y : grad outputs, FloatTensor[b, c, s] indices: voxel index of each point, IntTensor[b, n] cnt : #points in each voxel index, IntTensor[b, s] Return: grad_x : grad inputs, FloatTensor[b, c, n] */ at::Tensor avg_voxelize_backward(const at::Tensor grad_y, const at::Tensor indices, const at::Tensor cnt) { CHECK_CUDA(grad_y); CHECK_CUDA(indices); CHECK_CUDA(cnt); CHECK_CONTIGUOUS(grad_y); CHECK_CONTIGUOUS(indices); CHECK_CONTIGUOUS(cnt); CHECK_IS_FLOAT(grad_y); CHECK_IS_INT(indices); CHECK_IS_INT(cnt); int b = grad_y.size(0); int c = grad_y.size(1); int s = grad_y.size(2); int n = indices.size(1); at::Tensor grad_x = torch::zeros( {b, c, n}, at::device(grad_y.device()).dtype(at::ScalarType::Float)); avg_voxelize_grad(b, c, n, s, indices.data_ptr<int>(), cnt.data_ptr<int>(), grad_y.data_ptr<float>(), grad_x.data_ptr<float>()); return grad_x; }
32.987013
78
0.612205
[ "vector" ]
6a85485a4f4f583c286bb787bf80b5c3b6d58842
9,852
cpp
C++
addons/Outdated_WIP_Reference/Test_Weapon_01_Modified/config.cpp
hoxxii/Autismo_Seals_Unit_Mod
5e27dbac2066c435215859b70c861b0abbfb3b95
[ "OLDAP-2.3" ]
null
null
null
addons/Outdated_WIP_Reference/Test_Weapon_01_Modified/config.cpp
hoxxii/Autismo_Seals_Unit_Mod
5e27dbac2066c435215859b70c861b0abbfb3b95
[ "OLDAP-2.3" ]
null
null
null
addons/Outdated_WIP_Reference/Test_Weapon_01_Modified/config.cpp
hoxxii/Autismo_Seals_Unit_Mod
5e27dbac2066c435215859b70c861b0abbfb3b95
[ "OLDAP-2.3" ]
null
null
null
#include "basicdefines_A3.hpp" #include "cfgMagazines.hpp" /// specific magazines for this rifle #include "cfgAmmo.hpp" /// specific ammo for this rifle class CfgPatches { class Test_weapon_F { units[]={}; weapons[]={"Test_weapon_01_F", "Test_weapon_01_holo_pointer_F"}; requiredVersion=0.1; requiredAddons[]={"A3_Weapons_F", "Test_Sounds_F"}; }; }; /// All firemodes, to be sure class Mode_SemiAuto; class Mode_Burst; class Mode_FullAuto; /// Weapon slots class SlotInfo; class MuzzleSlot; class CowsSlot; class PointerSlot; class UnderBarrelSlot; #include "cfgRecoils.hpp" /// specific recoil patterns for this rifle #include "cfgMagazines.hpp" /// specific magazines for this rifle #include "cfgAmmo.hpp" /// specific ammo for this rifle class CfgWeapons { class Rifle; class Rifle_Base_F: Rifle { class WeaponSlotsInfo; class GunParticles; }; class UGL_F; class Test_weapon_01_Base_F: Rifle_Base_F /// Just basic values common for all testing rifle variants { magazines[] = {30Rnd_test_mag_Tracer, 10Rnd_test_mag, 30Rnd_test_mag, test_mag_group}; /// original custom made magazines and a group of several standardized mags reloadAction = "GestureReloadMX"; /// MX hand animation actually fits this rifle well magazineReloadSwitchPhase = 0.4; /// part of reload animation when new magazine ammo count should affect "revolving" animation source discreteDistanceInitIndex = 0; /// Ironsight zeroing is the lowest value by default // Size of recoil sway of the cursor maxRecoilSway=0.0125; // Speed at which the recoil sway goes back to zero (from maxRecoilSway to 0 in 1/swayDecaySpeed seconds) swayDecaySpeed=1.25; /// inertia coefficient of the weapon inertia = 0.5; /// positive value defines speed of the muzzle independent on the magazine setting, negative value is a coefficient of magazine initSpeed initSpeed = -1; /// this means that initSpeed of magazine is used class GunParticles : GunParticles { class SecondEffect { positionName = "Nabojnicestart"; directionName = "Nabojniceend"; effectName = "CaselessAmmoCloud"; }; }; class WeaponSlotsInfo: WeaponSlotsInfo { class MuzzleSlot: MuzzleSlot { linkProxy = "\A3\data_f\proxies\weapon_slots\MUZZLE"; /// this can be set, but having some common helps a bit compatibleItems[] = {"test_suppressor"}; /// A custom made suppressor for this weapon iconPosition[] = {0.0, 0.45}; /// position of the slot icon inside of the weapon icon, relative to top-left corner in {right, down} format iconScale = 0.2; /// scale of icon described in iconPicture iconPicture = "\A3\Weapons_F\Data\UI\attachment_muzzle.paa"; /// icon for selected slot iconPinpoint = "Center"; /// top, bottom, left, right, center alignment of the icon on snap point }; class CowsSlot: CowsSlot /// default accessories for this slot { iconPosition[] = {0.5, 0.35}; iconScale = 0.2; }; class PointerSlot: PointerSlot /// default accessories for this slot { iconPosition[] = {0.20, 0.45}; iconScale = 0.25; }; class UnderBarrelSlot: UnderBarrelSlot /// using test bipod { iconPosition[] = {0.2, 0.7}; iconScale = 0.2; compatibleItems[] = {"test_bipod_01_F"}; }; }; ///////////////////////////////////////////////////// I R O N S I G H T S ///////////////////////////////////////////////////// opticsZoomMin=0.375; opticsZoomMax=1.1; opticsZoomInit=0.75; distanceZoomMin = 300; distanceZoomMax = 300; ///////////////////////////////////////////////////// I R O N S I G H T S ///////////////////////////////////////////////////// descriptionShort = "Testing weapon with grenade launcher"; /// displayed on mouseOver in Inventory handAnim[] = {"OFP2_ManSkeleton", "\A3\Weapons_F\Rifles\MX\data\Anim\MX_gl.rtm"}; /// MX hand animation actually fits this rifle well dexterity = 1.8; //caseless ammo// caseless[] = {"",1,1,1}; /// no sound of ejected brass soundBullet[] = {caseless,1}; selectionFireAnim = "muzzleFlash"; /// are we able to get rid of all the zaslehs? modes[] = {Single, FullAuto, fullauto_medium, single_medium_optics1, single_far_optics2}; /// Includes fire modes for AI ////////////////////////////////////////////////////// NO OPTICS /////////////////////////////////////////////////////////// class Single: Mode_SemiAuto /// Pew { // the new parameter to distinguish muzzle accessories type sounds[] = { StandardSound, // default sound SilencedSound // silenced sound - weapon with silencer on }; class StandardSound { // array of sounds (SoundSet names) to be played at the game event (shot) // number of SoundSets in array is not limited // consider that several ms lag could appear between each SoundSet is played // closure (bolt action) sound definition should be part of SoundSet soundSetShot[] = { Test_Weapon_01_Shot_SoundSet, Test_Weapon_01_Tail_SoundSet }; }; class SilencedSound { soundSetShot[] = { Test_Weapon_01_silencerShot_SoundSet, Test_Weapon_01_silencerTail_SoundSet }; }; reloadTime = 0.096; /// means some 625 rounds per minute dispersion = 0.00087; /// A bit less than 3 MOA recoil = "recoil_single_Test_rifle_01"; /// defined in cfgRecoils recoilProne = "recoil_single_prone_Test_rifle_01"; /// defined in cfgRecoils minRange = 2; minRangeProbab = 0.5; /// Task Force Balance black magic - this is the probability which AI thinks it would hit target at set range with midRange = 200; midRangeProbab = 0.7; /// it is no real probability of hit, just used for AI to compute if the shot is worth to take - AI chooses highest maxRange = 400; maxRangeProbab = 0.3; /// probability of the weapon, does some calculation and compares it with calculated probability of other weapons }; class FullAuto: Mode_FullAuto /// Pew-pew-pew-pew-pew { sounds[] = { StandardSound, SilencedSound }; class StandardSound { soundSetShot[] = { Test_Weapon_01_Shot_SoundSet, Test_Weapon_01_Tail_SoundSet }; }; class SilencedSound { soundSetShot[] = { Test_Weapon_01_silencerShot_SoundSet, Test_Weapon_01_silencerTail_SoundSet }; }; reloadTime = 0.096; dispersion = 0.00087; recoil = "recoil_auto_Test_rifle_01"; /// defined in cfgRecoils recoilProne = "recoil_auto_prone_Test_rifle_01"; /// defined in cfgRecoils minRange = 0; minRangeProbab = 0.9; midRange = 15; midRangeProbab = 0.7; maxRange = 30; maxRangeProbab = 0.1; aiRateOfFire = 0.000001; }; class fullauto_medium: FullAuto /// Pew, pew, pew only for AI { showToPlayer = 0; burst = 3; minRange = 2; minRangeProbab = 0.5; midRange = 75; midRangeProbab = 0.7; maxRange = 150; maxRangeProbab = 0.05; aiRateOfFire = 2.0; aiRateOfFireDistance = 200; }; //////////////////////////////////////////////////// OPTICS ////////////////////////////////////////////////// class single_medium_optics1: Single /// Pew for AI with collimator sights { requiredOpticType = 1; showToPlayer = 0; minRange = 2; minRangeProbab = 0.2; midRange = 450; midRangeProbab = 0.7; maxRange = 600; maxRangeProbab = 0.2; aiRateOfFire = 6; aiRateOfFireDistance = 600; }; class single_far_optics2: single_medium_optics1 /// Pew for AI with better sights { requiredOpticType = 2; showToPlayer = 0; minRange = 100; minRangeProbab = 0.1; midRange = 500; midRangeProbab = 0.6; maxRange = 700; maxRangeProbab = 0.05; aiRateOfFire = 8; aiRateOfFireDistance = 700; }; class Test_GL_F: UGL_F /// Some grenade launcher to have some more fun { displayName = "Test grenade launcher"; descriptionShort = "TGL"; useModelOptics = false; useExternalOptic = false; /// Doesn't use optics from the attachment, has it's own magazines[] = {1Rnd_HE_Grenade_shell}; cameraDir = "OP_look"; discreteDistance[] = {100, 200, 300, 400}; discreteDistanceCameraPoint[] = {"OP_eye", "OP_eye2", "OP_eye3", "OP_eye4"}; /// the angle of gun changes with zeroing discreteDistanceInitIndex = 1; /// 200 is the default zero }; aiDispersionCoefY=6.0; /// AI should have some degree of greater dispersion for initial shoots aiDispersionCoefX=4.0; /// AI should have some degree of greater dispersion for initial shoots drySound[]={"A3\sounds_f\weapons\Other\dry_1", db-5, 1, 10}; /// custom made sounds reloadMagazineSound[]={"A3\sounds_f\weapons\reloads\new_MX",db-8,1, 30}; /// custom made sounds }; class Test_weapon_01_F: Test_weapon_01_Base_F { scope = 2; /// should be visible and useable in game displayName = "Test weapon"; /// some name model = "Test_weapon_01\test_weapon_01_F.p3d"; /// path to model picture = "Test_weapon_01\Data\UI\gear_test_weapon_01_X_CA.paa"; /// different accessories have M, S, T instead of X UiPicture = "\A3\Weapons_F\Data\UI\icon_gl_CA.paa"; /// weapon with grenade launcher should be marked such way weaponInfoType = "RscWeaponZeroing"; /// display with zeroing is good for iron sights muzzles[] = {this, Test_GL_F}; /// to be able to switch between bullet muzzle and TGL class WeaponSlotsInfo: WeaponSlotsInfo { mass = 100; /// some rough estimate }; }; /**** SLOTABLE WEAPONS ****/ class Test_weapon_01_holo_pointer_F: Test_weapon_01_F /// standard issue variant with holo optics and laser pointer { class LinkedItems { class LinkedItemsOptic { slot = "CowsSlot"; item = "optic_Holosight"; }; class LinkedItemsAcc { slot = "PointerSlot"; item = "acc_pointer_IR"; }; }; }; /// include accessory from separate file to not clutter this one #include "accessory.hpp" };
32.84
164
0.664941
[ "model" ]
6a86d4e6a1026f3d43096416a4a2bf784a269e45
2,725
cpp
C++
examples/MolmodelInstallTestNoViz.cpp
MadCatX/molmodel
5abde979e1780dcc61a4b05affcba6e116250585
[ "MIT" ]
null
null
null
examples/MolmodelInstallTestNoViz.cpp
MadCatX/molmodel
5abde979e1780dcc61a4b05affcba6e116250585
[ "MIT" ]
1
2020-12-09T16:45:16.000Z
2020-12-09T16:56:52.000Z
examples/MolmodelInstallTestNoViz.cpp
MadCatX/molmodel
5abde979e1780dcc61a4b05affcba6e116250585
[ "MIT" ]
4
2020-06-23T18:24:37.000Z
2021-04-29T14:44:25.000Z
/* -------------------------------------------------------------------------- * * SimTK Molmodel installation test program (without Visualizer) * * -------------------------------------------------------------------------- * * Run this program to verify that Molmodel has been installed properly. This * * requires that Simbody is also installed. However, we do not use the * * Visualizer here in case you don't have that available. To test for * * complete functionality run MolmodelInstallTest instead. * * * * Authors: Michael Sherman * * -------------------------------------------------------------------------- */ #include "Molmodel.h" #include <iostream> #include <exception> using namespace SimTK; int main() { try { std::clog << "MolmodelInstallTestNoViz: you should see a pdb file of a small protein\n" " sent to stdout.\n"; // molecule-specialized simbody System CompoundSystem system; SimbodyMatterSubsystem matter(system); DecorationSubsystem decorations(system); // molecular force field DuMMForceFieldSubsystem forceField(system); forceField.loadAmber99Parameters(); // Create a five-residue protein. Neutral end caps are automatically // added unless you suppress them. This is // (Ace-) Ser-Ile-Met-Thr-Lys (-Nac). Protein protein("SIMTK"); protein.assignBiotypes(); system.adoptCompound(protein); // finalize mapping of atoms to bodies system.modelCompounds(); // Generate a pdb frame every 100fs. system.addEventReporter(new PeriodicPdbWriter(system, std::cout, 0.100)); // Maintain a constant temperature. (This isn't a very good // thermostat -- consider NoseHooverThermostat instead.) system.addEventHandler(new VelocityRescalingThermostat( system, 293.15, 0.1)); // Instantiate simbody model and get default state State state = system.realizeTopology(); // Relax the structure before dynamics run LocalEnergyMinimizer::minimizeEnergy(system, state, 15.0); // Simulate it. VerletIntegrator integ(system); TimeStepper ts(system, integ); ts.initialize(state); ts.stepTo(1.0); // 1ps (10 frame) std::clog << "MolmodelInstallTestNoViz: done.\n"; return 0; } catch(const std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; return 1; } catch(...) { std::cerr << "ERROR: An unknown exception was raised" << std::endl; return 1; } }
34.493671
83
0.561835
[ "model" ]
6a889abf1bf3a39e7a3ca49a5d50d04ffe4a69d7
3,781
cpp
C++
examples_glfwold/607_PbdCloth/main.cpp
fixedchaos/delfem2
c8a7a000ec6a51c44bc45bc6ad0d0106d9315ade
[ "MIT" ]
null
null
null
examples_glfwold/607_PbdCloth/main.cpp
fixedchaos/delfem2
c8a7a000ec6a51c44bc45bc6ad0d0106d9315ade
[ "MIT" ]
null
null
null
examples_glfwold/607_PbdCloth/main.cpp
fixedchaos/delfem2
c8a7a000ec6a51c44bc45bc6ad0d0106d9315ade
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Nobuyuki Umetani * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <cstdlib> #include <vector> #include <set> #include "delfem2/dtri.h" #include "delfem2/objf_geo3.h" #include "delfem2/objfdtri_objfdtri23.h" #include "delfem2/dtri2_v2dtri.h" // -------------- #include <GLFW/glfw3.h> #include "delfem2/opengl/caddtri_v3_glold.h" #include "delfem2/opengl/funcs_glold.h" #include "delfem2/opengl/glfw/viewer_glfw.h" namespace dfm2 = delfem2; // ------------------------------------ std::vector<dfm2::CDynPntSur> aPo2D; std::vector<dfm2::CDynTri> aETri; std::vector<dfm2::CVec2d> aVec2; std::vector<unsigned int> aLine; std::vector<double> aXYZ; // deformed vertex positions std::vector<double> aXYZt; std::vector<double> aUVW; // deformed vertex velocity std::vector<int> aBCFlag; // boundary condition flag (0:free 1:fixed) //const double mass_point = 0.01; const double dt = 0.01; const double gravity[3] = {0.0, 0.0, -10.0}; bool is_animation = false; // ------------------------------------- void StepTime() { dfm2::PBD_Pre3D(aXYZt, dt, gravity, aXYZ, aUVW, aBCFlag); dfm2::PBD_TriStrain(aXYZt.data(), aXYZt.size()/3, aETri, aVec2); dfm2::PBD_Bend(aXYZt.data(), aXYZt.size()/3, aETri, aVec2, 1.0); dfm2::PBD_Seam(aXYZt.data(), aXYZt.size()/3, aLine.data(), aLine.size()/2); dfm2::PBD_Post(aXYZ, aUVW, dt, aXYZt, aBCFlag); } // ------------------------------------- void myGlutDisplay(void) { ::glPointSize(5); ::glLineWidth(1); { ::glDisable(GL_LIGHTING); ::glColor3d(0.8, 0.8, 0.8); /* float color[4] = {200.0/256.0, 200.0/256.0, 200.0/256.0,1.0f}; ::glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,color); ::glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,color); ::glEnable(GL_DEPTH_TEST); */ // DrawMeshTri3D_FaceNorm(aXYZ, aTri); } ::glDisable(GL_LIGHTING); ::glColor3d(0,0,0); delfem2::opengl::DrawMeshDynTri3D_Edge(aXYZ, aETri); } int main(int argc,char* argv[]) { { std::vector< std::vector<double> > aaXY; aaXY.resize(1); double xys[12] = { -0.5,-0.5, +0.5,-0.5, +0.5,+0.5, +0.1,+0.6, -0.1,+0.6, -0.5,+0.5, }; aaXY[0].assign(xys,xys+12); GenMesh(aPo2D,aETri,aVec2, aaXY, 0.05, 0.05); } // ------------- const int np = aPo2D.size(); aXYZ.resize(np*3); for(int ip=0;ip<np;++ip){ aXYZ[ip*3+0] = aVec2[ip].x(); aXYZ[ip*3+1] = aVec2[ip].y(); aXYZ[ip*3+2] = 0.0; } aXYZt = aXYZ; aUVW.resize(np*3,0.0); aBCFlag.resize(np,0); for(int ip=0;ip<np;++ip){ if( aXYZ[ip*3+1] > +0.59 ){ aBCFlag[ip] = 1; } } aLine.clear(); { // make aLine std::map<int,int> mapY2Ip; for(int ip=0;ip<np;++ip){ if( aXYZ[ip*3+0] > +0.49 ){ double y0 = aXYZ[ip*3+1]; int iy = (int)(y0/0.0132); mapY2Ip[iy] = ip; } } for(int ip=0;ip<np;++ip){ if( aXYZ[ip*3+0] < -0.49 ){ double y1 = aXYZ[ip*3+1]; int iy = (int)(y1/0.0132); assert( mapY2Ip.find(iy) != mapY2Ip.end() ); int ip0 = mapY2Ip[iy]; aLine.push_back(ip); aLine.push_back(ip0); } } } dfm2::opengl::CViewer_GLFW viewer; viewer.Init_oldGL(); viewer.nav.camera.view_height = 1.0; viewer.nav.camera.camera_rot_mode = delfem2::CCamera<double>::CAMERA_ROT_MODE::TBALL; delfem2::opengl::setSomeLighting(); while (!glfwWindowShouldClose(viewer.window)) { StepTime(); viewer.DrawBegin_oldGL(); myGlutDisplay(); viewer.DrawEnd_oldGL(); } glfwDestroyWindow(viewer.window); glfwTerminate(); exit(EXIT_SUCCESS); }
25.206667
87
0.580799
[ "vector" ]
6a8cfa26ab62dc96d3d6208d5518755d98370e1c
8,617
cc
C++
device/vr/openxr/openxr_input_helper.cc
avaer/overlay
6833fa7793fc1f0fffeea45efdfcfe13662389a3
[ "MIT" ]
null
null
null
device/vr/openxr/openxr_input_helper.cc
avaer/overlay
6833fa7793fc1f0fffeea45efdfcfe13662389a3
[ "MIT" ]
null
null
null
device/vr/openxr/openxr_input_helper.cc
avaer/overlay
6833fa7793fc1f0fffeea45efdfcfe13662389a3
[ "MIT" ]
2
2021-05-09T13:19:25.000Z
2021-07-03T22:36:08.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/vr/openxr/openxr_input_helper.h" #include "device/vr/openxr/openxr_util.h" #include "device/vr/util/xr_standard_gamepad_builder.h" namespace device { namespace { base::Optional<GamepadBuilder::ButtonData> GetAxisButtonData( OpenXrAxisType openxr_button_type, base::Optional<GamepadButton> button_data, std::vector<double> axis) { GamepadBuilder::ButtonData data; if (!button_data || axis.size() != 2) { return base::nullopt; } switch (openxr_button_type) { case OpenXrAxisType::kThumbstick: data.type = GamepadBuilder::ButtonData::Type::kThumbstick; break; case OpenXrAxisType::kTrackpad: data.type = GamepadBuilder::ButtonData::Type::kTouchpad; break; } data.touched = button_data->touched; data.pressed = button_data->pressed; data.value = button_data->value; // Invert the y axis because -1 is up in the Gamepad API, but down in // OpenXR. data.x_axis = axis.at(0); data.y_axis = -axis.at(1); return data; } } // namespace XrResult OpenXRInputHelper::CreateOpenXRInputHelper( XrInstance instance, XrSession session, XrSpace local_space, std::unique_ptr<OpenXRInputHelper>* helper) { XrResult xr_result; std::unique_ptr<OpenXRInputHelper> new_helper = std::make_unique<OpenXRInputHelper>(session, local_space); // This map is used to store bindings for different kinds of interaction // profiles. This allows the runtime to choose a different input sources based // on availability. std::map<XrPath, std::vector<XrActionSuggestedBinding>> bindings; for (size_t i = 0; i < new_helper->controller_states_.size(); i++) { RETURN_IF_XR_FAILED(new_helper->controller_states_[i].controller.Initialize( static_cast<OpenXrHandednessType>(i), instance, session, &bindings)); new_helper->controller_states_[i].primary_button_pressed = false; } for (auto it = bindings.begin(); it != bindings.end(); it++) { XrInteractionProfileSuggestedBinding profile_suggested_bindings = { XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING}; profile_suggested_bindings.interactionProfile = it->first; profile_suggested_bindings.suggestedBindings = it->second.data(); profile_suggested_bindings.countSuggestedBindings = it->second.size(); RETURN_IF_XR_FAILED(xrSuggestInteractionProfileBindings( instance, &profile_suggested_bindings)); } std::vector<XrActionSet> action_sets(new_helper->controller_states_.size()); for (size_t i = 0; i < new_helper->controller_states_.size(); i++) { action_sets[i] = new_helper->controller_states_[i].controller.GetActionSet(); } XrSessionActionSetsAttachInfo attach_info = { XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO}; attach_info.countActionSets = action_sets.size(); attach_info.actionSets = action_sets.data(); RETURN_IF_XR_FAILED(xrAttachSessionActionSets(session, &attach_info)); *helper = std::move(new_helper); return xr_result; } OpenXRInputHelper::OpenXRInputHelper(XrSession session, XrSpace local_space) : session_(session), local_space_(local_space) {} OpenXRInputHelper::~OpenXRInputHelper() = default; mojom::XRGamepadDataPtr OpenXRInputHelper::GetGamepadData( XrTime predicted_display_time) { if (XR_FAILED(SyncActions(predicted_display_time))) return nullptr; mojom::XRGamepadDataPtr gamepad_data_ptr = mojom::XRGamepadData::New(); for (const OpenXrControllerState& controller_state : controller_states_) { const OpenXrController& controller = controller_state.controller; mojom::XRGamepadPtr gamepad_ptr = mojom::XRGamepad::New(); gamepad_ptr->controller_id = controller.GetId(); gamepad_ptr->timestamp = base::TimeTicks::Now(); gamepad_ptr->hand = controller.GetHandness(); std::vector<mojom::XRGamepadButtonPtr> buttons = controller.GetWebVrButtons(); if (buttons.empty()) continue; gamepad_ptr->buttons = std::move(buttons); std::vector<double> axes = controller.GetWebVrAxes(); if (axes.empty()) continue; gamepad_ptr->axes = std::move(axes); gamepad_ptr->pose = controller.GetPose(predicted_display_time, local_space_); if (!gamepad_ptr->pose) continue; gamepad_ptr->can_provide_position = gamepad_ptr->pose->position.has_value(); gamepad_ptr->can_provide_orientation = gamepad_ptr->pose->orientation.has_value(); gamepad_data_ptr->gamepads.push_back(std::move(gamepad_ptr)); } return gamepad_data_ptr; } std::vector<mojom::XRInputSourceStatePtr> OpenXRInputHelper::GetInputState( XrTime predicted_display_time) { std::vector<mojom::XRInputSourceStatePtr> input_states; if (XR_FAILED(SyncActions(predicted_display_time))) { for (OpenXrControllerState& state : controller_states_) { state.primary_button_pressed = false; } return input_states; } for (uint32_t i = 0; i < controller_states_.size(); i++) { device::OpenXrController* controller = &controller_states_[i].controller; base::Optional<GamepadButton> trigger_button = controller->GetButton(OpenXrButtonType::kTrigger); // Having a trigger button is the minimum for an webxr input. // No trigger button indicates input is not connected. if (!trigger_button) { continue; } device::mojom::XRInputSourceStatePtr state = device::mojom::XRInputSourceState::New(); // ID 0 will cause a DCHECK in the hash table used on the blink side. // To ensure that we don't have any collisions with other ids, increment // all of the ids by one. state->source_id = i + 1; state->description = controller->GetDescription(predicted_display_time); state->grip = controller->GetMojoFromGripTransform(predicted_display_time, local_space_); state->emulated_position = false; state->primary_input_pressed = trigger_button.value().pressed; state->primary_input_clicked = controller_states_[i].primary_button_pressed && !state->primary_input_pressed; controller_states_[i].primary_button_pressed = state->primary_input_pressed; state->gamepad = GetWebXRGamepad(*controller); input_states.push_back(std::move(state)); } return input_states; } base::Optional<Gamepad> OpenXRInputHelper::GetWebXRGamepad( const OpenXrController& controller) const { XRStandardGamepadBuilder builder(controller.GetHandness()); base::Optional<GamepadButton> trigger_button = controller.GetButton(OpenXrButtonType::kTrigger); if (!trigger_button) return base::nullopt; builder.SetPrimaryButton(trigger_button.value()); base::Optional<GamepadButton> squeeze_button = controller.GetButton(OpenXrButtonType::kSqueeze); if (squeeze_button) builder.SetSecondaryButton(squeeze_button.value()); base::Optional<GamepadButton> trackpad_button = controller.GetButton(OpenXrButtonType::kTrackpad); std::vector<double> trackpad_axis = controller.GetAxis(OpenXrAxisType::kTrackpad); base::Optional<GamepadBuilder::ButtonData> trackpad_button_data = GetAxisButtonData(OpenXrAxisType::kTrackpad, trackpad_button, trackpad_axis); if (trackpad_button_data) builder.SetTouchpadData(trackpad_button_data.value()); base::Optional<GamepadButton> thumbstick_button = controller.GetButton(OpenXrButtonType::kThumbstick); std::vector<double> thumbstick_axis = controller.GetAxis(OpenXrAxisType::kThumbstick); base::Optional<GamepadBuilder::ButtonData> thumbstick_button_data = GetAxisButtonData(OpenXrAxisType::kThumbstick, thumbstick_button, thumbstick_axis); if (thumbstick_button_data) builder.SetThumbstickData(thumbstick_button_data.value()); return builder.GetGamepad(); } XrResult OpenXRInputHelper::SyncActions(XrTime predicted_display_time) { std::vector<XrActiveActionSet> active_action_sets(controller_states_.size()); for (size_t i = 0; i < controller_states_.size(); i++) { active_action_sets[i].actionSet = controller_states_[i].controller.GetActionSet(); active_action_sets[i].subactionPath = XR_NULL_PATH; } XrActionsSyncInfo sync_info = {XR_TYPE_ACTIONS_SYNC_INFO}; sync_info.countActiveActionSets = active_action_sets.size(); sync_info.activeActionSets = active_action_sets.data(); return xrSyncActions(session_, &sync_info); } } // namespace device
36.512712
80
0.736799
[ "vector" ]
6a8e4880fe2774b6e3d7fd95110865c21f8f0b2f
13,945
cc
C++
kernel/proc.cc
Anton-Cao/sv6
f525c4d588d3cfe750867990902b882cd4a21fad
[ "MIT-0" ]
null
null
null
kernel/proc.cc
Anton-Cao/sv6
f525c4d588d3cfe750867990902b882cd4a21fad
[ "MIT-0" ]
null
null
null
kernel/proc.cc
Anton-Cao/sv6
f525c4d588d3cfe750867990902b882cd4a21fad
[ "MIT-0" ]
null
null
null
#include "types.h" #include "kernel.hh" #include "mmu.h" #include "amd64.h" #include "spinlock.hh" #include "condvar.hh" #include "proc.hh" #include "cpu.hh" #include "bits.hh" #include "kmtrace.hh" #include "kalloc.hh" #include "vm.hh" #include "ns.hh" #include "work.hh" #include "filetable.hh" #include <uk/fcntl.h> #include <uk/unistd.h> #include <uk/wait.h> u64 proc::hash(const u32 &p) { return p; } xns<u32, proc*, proc::hash> *xnspid __mpalign__; struct proc *bootproc __mpalign__; #if MTRACE struct kstack_tag kstack_tag[NCPU]; #endif enum { sched_debug = 0 }; proc::proc(int npid) : kstack(0), qstack(0), killed(0), tf(0), uaccess_(0), user_fs_(0), pid(npid), parent(0), context(0), tsc(0), curcycles(0), cpuid(0), fpu_state(nullptr), cpu_pin(0), oncv(0), cv_wakeup(0), futex_lock("proc::futex_lock", LOCKSTAT_PROC), unmap_tlbreq_(0), data_cpuid(-1), in_exec_(0), yield_(false), upath(nullptr), uargv(nullptr), exception_inuse(0), magic(PROC_MAGIC), unmapped_hint(0), state_(EMBRYO) { snprintf(lockname, sizeof(lockname), "cv:proc:%d", pid); lock = spinlock(lockname+3, LOCKSTAT_PROC); cv = new condvar(lockname); gc = new gc_handle(); memset(__cxa_eh_global, 0, sizeof(__cxa_eh_global)); memset(sig, 0, sizeof(sig)); } proc::~proc(void) { magic = 0; if (fpu_state) kmfree(fpu_state, FXSAVE_BYTES); fpu_state = nullptr; } void proc::set_state(enum procstate s) { switch(state_) { case EMBRYO: if (s != RUNNABLE) panic("EMBRYO -> %u", s); break; case SLEEPING: if (s != RUNNABLE) panic("SLEEPING -> %u", s); break; case RUNNABLE: if (s != RUNNING && s != RUNNABLE) panic("RUNNABLE -> %u", s); break; case RUNNING: if (s != RUNNABLE && s != SLEEPING && s != ZOMBIE) panic("RUNNING -> %u", s); break; case ZOMBIE: panic("ZOMBIE -> %u", s); } state_ = s; } int proc::set_cpu_pin(int cpu) { if (cpu < -1 || cpu >= ncpu) return -1; acquire(&lock); if (myproc() != this) panic("set_cpu_pin not implemented for non-current proc"); if (cpu == -1) { cpu_pin = 0; release(&lock); return 0; } // Since we're the current proc, there's no runq to get off. // post_swtch will put us on the new runq. cpuid = cpu; cpu_pin = 1; myproc()->set_state(RUNNABLE); sched(); assert(mycpu()->id == cpu); return 0; } // Give up the CPU for one scheduling round. void yield(void) { acquire(&myproc()->lock); //DOC: yieldlock myproc()->set_state(RUNNABLE); myproc()->yield_ = false; sched(); } // A fork child's very first scheduling by scheduler() // will swtch here. "Return" to user space. u64 forkret(void) { post_swtch(); // Just for the first process. can't do it earlier // b/c file system code needs a process context // in which to call condvar::sleep(). if(myproc()->cwd == nullptr) { mtstart(forkret, myproc()); myproc()->cwd = namei(myproc()->cwd, "/"); mtstop(myproc()); } if (myproc()->cwd_m == nullptr) myproc()->cwd_m = namei(myproc()->cwd_m, "/"); // Return to "caller", actually trapret (see allocproc). return myproc()->user_fs_; } // Exit the current process. Does not return. // An exited process remains in the zombie state // until its parent calls wait() to find out it exited. void exit(int status) { int wakeupinit; if(myproc() == bootproc) panic("init exiting"); myproc()->ftable.reset(); myproc()->cwd.reset(); myproc()->status = (status & __WAIT_STATUS_VAL_MASK) | __WAIT_STATUS_EXITED; // Pass abandoned children to init. wakeupinit = 0; while (!myproc()->childq.empty()) { auto &p = myproc()->childq.front(); myproc()->childq.pop_front(); scoped_acquire pl(&p.lock); scoped_acquire bl(&bootproc->lock); p.parent = bootproc; if(p.get_state() == ZOMBIE) { wakeupinit = 1; } bootproc->childq.push_back(&p); } // Release vmap if (myproc()->vmap != nullptr) { sref<vmap> vmap = std::move(myproc()->vmap); // Switch to kernel page table, since we may be just about to // destroy the current page table. switchvm(myproc()); // Remove user visible state associated with this proc from vmap. vmap->remove((uptr)myproc(), PGSIZE); vmap->remove((uptr)myproc()->kstack, KSTACKSIZE); } // Lock the parent first, since otherwise we might deadlock. if (myproc()->parent != nullptr) acquire(&myproc()->parent->lock); acquire(&(myproc()->lock)); // Kernel threads might not have a parent if (myproc()->parent != nullptr) { release(&myproc()->parent->lock); myproc()->parent->cv->wake_all(); } else { idlezombie(myproc()); } if (wakeupinit) bootproc->cv->wake_all(); // Clean up FPU state if (myproc()->fpu_state) { // Make sure no CPUs think this process is the FPU owner for (int i = 0; i < ncpu; ++i) { struct proc *copy = myproc(); atomic_compare_exchange_strong(&cpus[i].fpu_owner, &copy, (proc*)nullptr); } } // Jump into the scheduler, never to return. myproc()->set_state(ZOMBIE); sched(); panic("zombie exit"); } static void freeproc(struct proc *p) { delete p; } proc* proc::alloc(void) { char *sp; proc* p; p = new proc(xnspid->allockey()); if (p == nullptr) throw_bad_alloc(); p->cpuid = mycpu()->id; #if MTRACE p->mtrace_stacks.curr = -1; #endif if (!xnspid->insert(p->pid, p)) panic("allocproc: ns_insert"); // Allocate kernel stacks. try { if(!(p->qstack = (char*) kalloc("qstack", KSTACKSIZE))) throw_bad_alloc(); #if KSTACK_DEBUG && false // TODO: fix kstack debugging // vmalloc the stack to surround it with guard pages so we can // detect stack over/underflows. p->kstack_vm = vmalloc<char[]>(KSTACKSIZE); p->kstack = p->kstack_vm.get(); #else if(!(p->kstack = (char*) kalloc("kstack", KSTACKSIZE))) throw_bad_alloc(); #endif } catch (...) { if (!xnspid->remove(p->pid, &p)) panic("allocproc: ns_remove"); freeproc(p); throw; } sp = p->kstack + KSTACKSIZE; // Leave room for trap frame. sp -= sizeof *p->tf; p->tf = (struct trapframe*)sp; // amd64 ABI mandates sp % 16 == 0 before a call instruction // (or after executing a ret instruction) if ((uptr) sp % 16) panic("allocproc: misaligned sp"); // Set up new context to start executing at forkret, // which returns to trapret. sp -= 8; *(u64*)sp = (u64)trapret; sp -= sizeof *p->context; p->context = (struct context*)sp; memset(p->context, 0, sizeof *p->context); p->context->rip = (uptr)forkret; return p; } void proc::init_vmap() { vmap->insert(vmdesc(this, this), (uptr)this, PGSIZE); vmap->insert(vmdesc(qstack, kstack), (uptr)kstack, KSTACKSIZE); } void initproc(void) { xnspid = new xns<u32, proc*, proc::hash>(false); if (xnspid == 0) panic("pinit"); } // Kill the process with the given pid. // Process won't exit until it returns // to user space (see trap in trap.c). int proc::kill(void) { acquire(&lock); killed = 1; if(get_state() == SLEEPING) { // we need to wake p up if it is condvar::sleep()ing. // can't change p from SLEEPING to RUNNABLE since that // would make some condvar->waiters a dangling reference, // and the non-zero p->cv_next will cause a future panic. // can't release p->lock then call wake_all() since the // cv might be deallocated while we're using it // (pipes dynamically allocate condvars). // can't call p->oncv.wake_all() since that results in // deadlock (wake_all() acquires p->lock). // changed the wake_all API to avoid double locking of p. oncv->wake_all(0, this); } release(&lock); return 0; } int proc::kill(int pid) { struct proc *p; // XXX The one use of lookup and it is wrong: it should return a locked // proc structure, or be in an RCU epoch. Now another process can delete // p between lookup and kill. p = xnspid->lookup(pid); if (p == 0) { panic("kill"); return -1; } return p->kill(); } // Print a process listing to console. For debugging. // Runs when user types ^P on console. // No lock to avoid wedging a stuck machine further. void procdumpall(void) { static const char *states[] = { /* [EMBRYO] = */ "embryo", /* [SLEEPING] = */ "sleep ", /* [RUNNABLE] = */ "runble", /* [RUNNING] = */ "run ", /* [ZOMBIE] = */ "zombie" }; const char *name = "(no name)"; const char *state; uptr pc[10]; for (proc *p : xnspid) { if(p->get_state() >= 0 && p->get_state() < NELEM(states) && states[p->get_state()]) state = states[p->get_state()]; else state = "???"; if (p->name && p->name[0] != 0) name = p->name; cprintf("\n%-3d %-10s %8s %2u %lu\n", p->pid, name, state, p->cpuid, p->tsc); if(p->get_state() == SLEEPING){ getcallerpcs((void*)p->context->rbp, pc, NELEM(pc)); for(int i=0; i<10 && pc[i] != 0; i++) cprintf(" %lx\n", pc[i]); } } } // Create a new process copying p as the parent. Sets up stack to // return as if from system call. By default, the new process shares // nothing with its parent and it is made RUNNABLE. struct proc* doclone(clone_flags flags) { struct proc *np; // cprintf("%d: fork\n", myproc()->pid); // Allocate process. if((np = proc::alloc()) == 0) return nullptr; auto proc_cleanup = scoped_cleanup([&np]() { if (!xnspid->remove(np->pid, &np)) panic("fork: ns_remove"); freeproc(np); }); if (flags & CLONE_SHARE_VMAP) { np->vmap = myproc()->vmap; } else if (!(flags & CLONE_NO_VMAP)) { // Copy process state from p. np->vmap = myproc()->vmap->copy(); } np->init_vmap(); np->parent = myproc(); *np->tf = *myproc()->tf; np->cpu_pin = myproc()->cpu_pin; np->data_cpuid = myproc()->data_cpuid; np->run_cpuid_ = myproc()->run_cpuid_; np->user_fs_ = myproc()->user_fs_; memcpy(np->sig, myproc()->sig, sizeof(np->sig)); // Clear %eax so that fork returns 0 in the child. np->tf->rax = 0; if (flags & CLONE_SHARE_FTABLE) { np->ftable = myproc()->ftable; } else if (!(flags & CLONE_NO_FTABLE)) { np->ftable = myproc()->ftable->copy(); } np->cwd = myproc()->cwd; np->cwd_m = myproc()->cwd_m; safestrcpy(np->name, myproc()->name, sizeof(myproc()->name)); acquire(&myproc()->lock); myproc()->childq.push_back(np); release(&myproc()->lock); np->cpuid = mycpu()->id; if (!(flags & CLONE_NO_RUN)) { acquire(&np->lock); addrun(np); release(&np->lock); } proc_cleanup.dismiss(); return np; } void finishproc(struct proc *p, bool removepid) { if (removepid && !xnspid->remove(p->pid, &p)) panic("finishproc: ns_remove"); #if !KSTACK_DEBUG if (p->kstack) kfree(p->kstack, KSTACKSIZE); #endif p->pid = 0; p->parent = 0; p->name[0] = 0; p->killed = 0; freeproc(p); } struct finishproc_work : public dwork { finishproc_work(proc *p) : dwork(), p_(p) {} virtual void run() override { finishproc(p_, 0); delete this; }; proc* p_; NEW_DELETE_OPS(finishproc_work) }; // Wait for a child process to exit and return its pid. // Return -1 if this process has no children. int wait(int wpid, userptr<int> status) { int havekids, pid; for(;;){ // Scan children for ZOMBIEs havekids = 0; acquire(&myproc()->lock); for (auto it = myproc()->childq.begin(); it != myproc()->childq.end(); it++) { proc &p = *it; acquire(&p.lock); if (wpid == -1 || wpid == p.pid) { havekids = 1; if(p.get_state() == ZOMBIE){ release(&p.lock); // noone else better be trying to lock p pid = p.pid; myproc()->childq.erase(it); release(&myproc()->lock); if (status) { status.store(&p.status); } proc *np = &p; if (!xnspid->remove(pid, &np)) panic("wait: ns_remove"); finishproc_work *w = new finishproc_work(&p); assert(dwork_push(w, p.run_cpuid_) >= 0); return pid; } } release(&p.lock); } // No point waiting if we don't have any children. if(!havekids || myproc()->killed){ release(&myproc()->lock); return -1; } // Wait for children to exit. (See wakeup1 call in proc_exit.) myproc()->cv->sleep(&myproc()->lock); release(&myproc()->lock); } } void threadhelper(void (*fn)(void *), void *arg) { post_swtch(); mtstart(fn, myproc()); fn(arg); exit(0); } struct proc* threadalloc(void (*fn)(void *), void *arg) { struct proc *p; p = proc::alloc(); if (p == nullptr) return 0; auto proc_cleanup = scoped_cleanup([&p]() { if (!xnspid->remove(p->pid, &p)) panic("fork: ns_remove"); freeproc(p); }); p->vmap = vmap::alloc(); if (p->vmap == nullptr) return 0; p->init_vmap(); // XXX can threadstub be deleted? p->context->rip = (u64)threadstub; p->context->r12 = (u64)fn; p->context->r13 = (u64)arg; p->parent = nullptr; p->cwd.reset(); proc_cleanup.dismiss(); return p; } struct proc* threadpin(void (*fn)(void*), void *arg, const char *name, int cpu) { struct proc *p; p = threadalloc(fn, arg); if (p == nullptr) panic("threadpin: alloc"); snprintf(p->name, sizeof(p->name), "%s", name); p->cpuid = cpu; p->cpu_pin = 1; acquire(&p->lock); addrun(p); release(&p->lock); return p; } bool proc::deliver_signal(int signo) { if (signo < 0 || signo >= NSIG) return false; if (sig[signo].sa_handler == 0) return false; trapframe tf_save = *tf; tf->rsp -= 128; // skip redzone tf->rsp -= sizeof(tf_save); if (putmem((void*) tf->rsp, &tf_save, sizeof(tf_save)) < 0) return false; tf->rsp -= 8; if (putmem((void*) tf->rsp, &sig[signo].sa_restorer, 8) < 0) return false; tf->rip = (u64) sig[signo].sa_handler; tf->rdi = signo; return true; }
22.898194
82
0.604231
[ "3d" ]
6a90a6e4d8de0e1fd8f61706696736621c3ac0cb
2,883
cpp
C++
be/src/vec/functions/hll_hash.cpp
aopangzi/incubator-doris
40c1fa2335f4ecedfa4865dca66d5ffbc4dedda7
[ "Apache-2.0" ]
2
2022-01-26T15:24:34.000Z
2022-02-10T09:07:33.000Z
be/src/vec/functions/hll_hash.cpp
aopangzi/incubator-doris
40c1fa2335f4ecedfa4865dca66d5ffbc4dedda7
[ "Apache-2.0" ]
1
2022-02-28T12:55:37.000Z
2022-02-28T12:55:37.000Z
be/src/vec/functions/hll_hash.cpp
aopangzi/incubator-doris
40c1fa2335f4ecedfa4865dca66d5ffbc4dedda7
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "exprs/hll_function.h" #include "olap/hll.h" #include "udf/udf.h" #include "vec/functions/function_always_not_nullable.h" #include "vec/functions/simple_function_factory.h" #include "vec/data_types/data_type_hll.h" namespace doris::vectorized { struct HLLHash { static constexpr auto name = "hll_hash"; using ReturnType = DataTypeHLL; static void vector(const ColumnString::Chars& data, const ColumnString::Offsets& offsets, MutableColumnPtr& col_res) { auto* res_column = reinterpret_cast<ColumnHLL*>(col_res.get()); auto& res_data = res_column->get_data(); size_t size = offsets.size(); for (size_t i = 0; i < size; ++i) { const char* raw_str = reinterpret_cast<const char*>(&data[offsets[i - 1]]); size_t str_size = offsets[i] - offsets[i - 1] - 1; uint64_t hash_value = HashUtil::murmur_hash64A(raw_str, str_size, HashUtil::MURMUR_SEED); res_data[i].update(hash_value); } } static void vector_nullable(const ColumnString::Chars& data, const ColumnString::Offsets& offsets, const NullMap& nullmap, MutableColumnPtr& col_res) { auto* res_column = reinterpret_cast<ColumnHLL*>(col_res.get()); auto& res_data = res_column->get_data(); size_t size = offsets.size(); for (size_t i = 0; i < size; ++i) { if (nullmap[i]) { continue; } else { const char* raw_str = reinterpret_cast<const char*>(&data[offsets[i - 1]]); size_t str_size = offsets[i] - offsets[i - 1] - 1; uint64_t hash_value = HashUtil::murmur_hash64A(raw_str, str_size, HashUtil::MURMUR_SEED); res_data[i].update(hash_value); } } } }; using FunctionHLLHash = FunctionAlwaysNotNullable<HLLHash>; void register_function_hll_hash(SimpleFunctionFactory& factory) { factory.register_function<FunctionHLLHash>(); } } // namespace doris::vectorized
39.493151
105
0.658689
[ "vector" ]
6a94691eae5cc1f6794079238b87c978bc86afba
5,803
cc
C++
src/rewriter.cc
xiaomaolau/sbexr
77b445492bb7ef03bef5b0cd119d7331856dfa26
[ "BSD-2-Clause-FreeBSD" ]
15
2017-05-13T23:17:36.000Z
2022-03-26T17:29:28.000Z
src/rewriter.cc
xiaomaolau/sbexr
77b445492bb7ef03bef5b0cd119d7331856dfa26
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/rewriter.cc
xiaomaolau/sbexr
77b445492bb7ef03bef5b0cd119d7331856dfa26
[ "BSD-2-Clause-FreeBSD" ]
1
2019-05-18T13:54:38.000Z
2019-05-18T13:54:38.000Z
// Copyright (c) 2017 Carlo Contavalli (ccontavalli@gmail.com). // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY Carlo Contavalli ''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 Carlo Contavalli 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. // // The views and conclusions contained in the software and documentation are // those of the authors and should not be interpreted as representing official // policies, either expressed or implied, of Carlo Contavalli. #include "rewriter.h" #include <iostream> const char _kTagString[] = "Tag"; struct TagSet { // HTML TAGS need to be nested correctly, for example: // <a><span></span></a> // we need to open first the tags that are closed the latest, // and close first the tags that were opened the latest. // Lists the tags to open, sorted by the largest closing offset first. std::multimap<ssize_t, Tag*, std::greater<ssize_t>> opens; // Lists the tags to close, sorted by the largest opening offset first. // Additionally, closes for opens in the same position should preserve // the correct order. std::multimap<ssize_t, Tag*, std::greater<ssize_t>> closes; }; // Key is the offset, value is a set of tags to open or close at that offset. using TagSetsMap = std::map<ssize_t, std::unique_ptr<TagSet>>; std::unique_ptr<TagSet>& GetTagset(TagSetsMap* ts, ssize_t position); bool AddOpen(TagSetsMap* ts, Tag* tag); bool AddClose(TagSetsMap* ts, Tag* tag, int order); uint64_t gl_bytes_wasted_on_duplication = 0; void HtmlRewriter::Add(Tag tag) { tags_.emplace_back(std::move(tag)); } std::unique_ptr<TagSet>& GetTagset(TagSetsMap* ts, ssize_t position) { auto& tagset = (*ts)[position]; if (tagset == nullptr) tagset = std::move(llvm::make_unique<TagSet>()); return tagset; } bool AddOpen(TagSetsMap* ts, Tag* tag) { if (tag->open < 0) return false; auto& tagset = GetTagset(ts, tag->open); auto it = tagset->opens.lower_bound(tag->close); for (; it != tagset->opens.end(); ++it) { if (it->first != tag->close) break; if (*it->second == *tag) { // gl_bytes_wasted_on_duplication += to_print.size(); // std::cerr << "AVOIDING DUP TAG " << filename.str() << " " << to_print // << " offset " << retval.size() << " wasted " // << GetHumanValue(gl_bytes_wasted_on_duplication) << // std::endl; return false; } } tagset->opens.emplace_hint(it, std::make_pair(tag->close, tag)); return true; } bool AddClose(TagSetsMap* ts, Tag* tag, int order) { if (tag->close < 0) return false; auto& tagset = GetTagset(ts, tag->close); tagset->closes.emplace(std::make_pair((tag->open << 10) + order, tag)); return true; } std::string HtmlRewriter::Generate(const StringRef& filename, const StringRef& body) { TagSetsMap tagsets; for (auto& tag : tags_) AddOpen(&tagsets, &tag); const char* data = body.data(); const auto size = body.size(); std::string retval; auto CloseTag = [&retval](const Tag& tag) { retval.append("</"); retval.append(tag.tag); retval.append(">"); }; int pos = 0, start = 0; for (const auto& it : tagsets) { auto nextstop = std::min<ssize_t>(size, it.first); const auto& tagset = it.second; for (; pos < nextstop; ++pos) { if (data[pos] == '&' || data[pos] == '<' || data[pos] == '>') { retval.append(data + start, pos - start); start = pos + 1; switch (data[pos]) { case '&': retval.append("&amp;"); break; case '<': retval.append("&lt;"); break; case '>': retval.append("&gt;"); break; } } } retval.append(data + start, pos - start); start = pos; for (const auto& ait : tagset->closes) { const auto& tag = ait.second; if (tag == nullptr) continue; CloseTag(*tag); } int order = 0; for (auto& ait : tagset->opens) { std::string to_print; auto& tag = ait.second; if (tag == nullptr) continue; ++order; to_print.append("<"); to_print.append(tag->tag); if (!tag->attributes.empty()) { to_print.append(" "); to_print.append(tag->attributes.data(), tag->attributes.size()); } to_print.append(">"); if (tag->close >= 0) { if (pos >= tag->close) { CloseTag(*tag); } else { AddClose(&tagsets, tag, order); } } retval.append(to_print); } } // Ensure deletion / cleaning the vector. std::vector<Tag>().swap(tags_); retval.shrink_to_fit(); return retval; }
32.971591
79
0.636912
[ "vector" ]
6a97837e00227ba6e4ba5da43ac10bedb816f4be
7,627
cpp
C++
cegui/src/ScriptModules/Python/bindings/output/CEGUI/GlobalEventSet.pypp.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
257
2020-01-03T10:13:29.000Z
2022-03-26T14:55:12.000Z
cegui/src/ScriptModules/Python/bindings/output/CEGUI/GlobalEventSet.pypp.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
116
2020-01-09T18:13:13.000Z
2022-03-15T18:32:02.000Z
cegui/src/ScriptModules/Python/bindings/output/CEGUI/GlobalEventSet.pypp.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
58
2020-01-09T03:07:02.000Z
2022-03-22T17:21:36.000Z
// This file has been generated by Py++. #include "boost/python.hpp" #include "generators/include/python_CEGUI.h" #include "GlobalEventSet.pypp.hpp" namespace bp = boost::python; struct GlobalEventSet_wrapper : CEGUI::GlobalEventSet, bp::wrapper< CEGUI::GlobalEventSet > { GlobalEventSet_wrapper( ) : CEGUI::GlobalEventSet( ) , bp::wrapper< CEGUI::GlobalEventSet >(){ // null constructor } virtual void fireEvent( ::CEGUI::String const & name, ::CEGUI::EventArgs & args, ::CEGUI::String const & eventNamespace="" ) { if( bp::override func_fireEvent = this->get_override( "fireEvent" ) ) func_fireEvent( boost::ref(name), boost::ref(args), boost::ref(eventNamespace) ); else{ this->CEGUI::GlobalEventSet::fireEvent( boost::ref(name), boost::ref(args), boost::ref(eventNamespace) ); } } void default_fireEvent( ::CEGUI::String const & name, ::CEGUI::EventArgs & args, ::CEGUI::String const & eventNamespace="" ) { CEGUI::GlobalEventSet::fireEvent( boost::ref(name), boost::ref(args), boost::ref(eventNamespace) ); } void fireEvent_impl( ::CEGUI::String const & name, ::CEGUI::EventArgs & args ){ CEGUI::EventSet::fireEvent_impl( boost::ref(name), boost::ref(args) ); } ::CEGUI::ScriptModule * getScriptModule( ) const { return CEGUI::EventSet::getScriptModule( ); } virtual ::CEGUI::RefCounted< CEGUI::BoundSlot > subscribeScriptedEvent( ::CEGUI::String const & name, ::CEGUI::String const & subscriber_name ) { if( bp::override func_subscribeScriptedEvent = this->get_override( "subscribeScriptedEvent" ) ) return func_subscribeScriptedEvent( boost::ref(name), boost::ref(subscriber_name) ); else{ return this->CEGUI::EventSet::subscribeScriptedEvent( boost::ref(name), boost::ref(subscriber_name) ); } } ::CEGUI::RefCounted< CEGUI::BoundSlot > default_subscribeScriptedEvent( ::CEGUI::String const & name, ::CEGUI::String const & subscriber_name ) { return CEGUI::EventSet::subscribeScriptedEvent( boost::ref(name), boost::ref(subscriber_name) ); } virtual ::CEGUI::RefCounted< CEGUI::BoundSlot > subscribeScriptedEvent( ::CEGUI::String const & name, unsigned int group, ::CEGUI::String const & subscriber_name ) { if( bp::override func_subscribeScriptedEvent = this->get_override( "subscribeScriptedEvent" ) ) return func_subscribeScriptedEvent( boost::ref(name), group, boost::ref(subscriber_name) ); else{ return this->CEGUI::EventSet::subscribeScriptedEvent( boost::ref(name), group, boost::ref(subscriber_name) ); } } ::CEGUI::RefCounted< CEGUI::BoundSlot > default_subscribeScriptedEvent( ::CEGUI::String const & name, unsigned int group, ::CEGUI::String const & subscriber_name ) { return CEGUI::EventSet::subscribeScriptedEvent( boost::ref(name), group, boost::ref(subscriber_name) ); } }; void register_GlobalEventSet_class(){ { //::CEGUI::GlobalEventSet typedef bp::class_< GlobalEventSet_wrapper, bp::bases< CEGUI::EventSet, CEGUI::Singleton< CEGUI::GlobalEventSet > >, boost::noncopyable > GlobalEventSet_exposer_t; GlobalEventSet_exposer_t GlobalEventSet_exposer = GlobalEventSet_exposer_t( "GlobalEventSet", bp::init< >() ); bp::scope GlobalEventSet_scope( GlobalEventSet_exposer ); { //::CEGUI::GlobalEventSet::fireEvent typedef void ( ::CEGUI::GlobalEventSet::*fireEvent_function_type )( ::CEGUI::String const &,::CEGUI::EventArgs &,::CEGUI::String const & ) ; typedef void ( GlobalEventSet_wrapper::*default_fireEvent_function_type )( ::CEGUI::String const &,::CEGUI::EventArgs &,::CEGUI::String const & ) ; GlobalEventSet_exposer.def( "fireEvent" , fireEvent_function_type(&::CEGUI::GlobalEventSet::fireEvent) , default_fireEvent_function_type(&GlobalEventSet_wrapper::default_fireEvent) , ( bp::arg("name"), bp::arg("args"), bp::arg("eventNamespace")="" ) ); } { //::CEGUI::GlobalEventSet::getSingleton typedef ::CEGUI::GlobalEventSet & ( *getSingleton_function_type )( ); GlobalEventSet_exposer.def( "getSingleton" , getSingleton_function_type( &::CEGUI::GlobalEventSet::getSingleton ) , bp::return_value_policy< bp::reference_existing_object >() , "*!\n\ \n\ Return singleton System object\n\ \n\ @return\n\ Singleton System object\n\ *\n" ); } { //::CEGUI::EventSet::fireEvent_impl typedef void ( GlobalEventSet_wrapper::*fireEvent_impl_function_type )( ::CEGUI::String const &,::CEGUI::EventArgs & ) ; GlobalEventSet_exposer.def( "fireEvent_impl" , fireEvent_impl_function_type( &GlobalEventSet_wrapper::fireEvent_impl ) , ( bp::arg("name"), bp::arg("args") ) , "! Implementation event firing member\n" ); } { //::CEGUI::EventSet::getScriptModule typedef ::CEGUI::ScriptModule * ( GlobalEventSet_wrapper::*getScriptModule_function_type )( ) const; GlobalEventSet_exposer.def( "getScriptModule" , getScriptModule_function_type( &GlobalEventSet_wrapper::getScriptModule ) , bp::return_value_policy< bp::reference_existing_object >() , "! Implementation event firing member\n\ ! Helper to return the script module pointer or throw.\n" ); } { //::CEGUI::EventSet::subscribeScriptedEvent typedef ::CEGUI::RefCounted< CEGUI::BoundSlot > ( ::CEGUI::EventSet::*subscribeScriptedEvent_function_type )( ::CEGUI::String const &,::CEGUI::String const & ) ; typedef ::CEGUI::RefCounted< CEGUI::BoundSlot > ( GlobalEventSet_wrapper::*default_subscribeScriptedEvent_function_type )( ::CEGUI::String const &,::CEGUI::String const & ) ; GlobalEventSet_exposer.def( "subscribeScriptedEvent" , subscribeScriptedEvent_function_type(&::CEGUI::EventSet::subscribeScriptedEvent) , default_subscribeScriptedEvent_function_type(&GlobalEventSet_wrapper::default_subscribeScriptedEvent) , ( bp::arg("name"), bp::arg("subscriber_name") ) ); } { //::CEGUI::EventSet::subscribeScriptedEvent typedef ::CEGUI::RefCounted< CEGUI::BoundSlot > ( ::CEGUI::EventSet::*subscribeScriptedEvent_function_type )( ::CEGUI::String const &,unsigned int,::CEGUI::String const & ) ; typedef ::CEGUI::RefCounted< CEGUI::BoundSlot > ( GlobalEventSet_wrapper::*default_subscribeScriptedEvent_function_type )( ::CEGUI::String const &,unsigned int,::CEGUI::String const & ) ; GlobalEventSet_exposer.def( "subscribeScriptedEvent" , subscribeScriptedEvent_function_type(&::CEGUI::EventSet::subscribeScriptedEvent) , default_subscribeScriptedEvent_function_type(&GlobalEventSet_wrapper::default_subscribeScriptedEvent) , ( bp::arg("name"), bp::arg("group"), bp::arg("subscriber_name") ) ); } GlobalEventSet_exposer.staticmethod( "getSingleton" ); } }
50.846667
199
0.628425
[ "object" ]
6a985c808501306543b3ed069bb7f0d8696e60a5
3,691
hpp
C++
include/llogl/shader.hpp
Borgleader/llogl
5aa5088536c3057dfb193a358f13a127beda7df8
[ "Unlicense" ]
1
2015-08-23T20:23:05.000Z
2015-08-23T20:23:05.000Z
include/llogl/shader.hpp
Borgleader/llogl
5aa5088536c3057dfb193a358f13a127beda7df8
[ "Unlicense" ]
null
null
null
include/llogl/shader.hpp
Borgleader/llogl
5aa5088536c3057dfb193a358f13a127beda7df8
[ "Unlicense" ]
null
null
null
#pragma once #include <exception> #include <string> #include <vector> #include "glid.hpp" #include "noncopyable.hpp" #include "opengl.hpp" #include "util.hpp" namespace llogl { namespace v1 { enum class shader_type: GLuint { vertex = gl::VERTEX_SHADER, geometry = gl::GEOMETRY_SHADER, fragment = gl::FRAGMENT_SHADER, compute = gl::COMPUTE_SHADER, tess_control = gl::TESS_CONTROL_SHADER, tess_evaluation = gl::TESS_EVALUATION_SHADER, }; template <shader_type T> class shader: noncopyable<shader<T>> { public: shader(): id() { } shader(shader&& other): id(std::move(other.id)) { } shader& operator=(shader&& other) { id = std::move(other.id); return *this; } static GLuint create() { GLuint id = 0; id = gl::CreateShader(static_cast<GLuint>(T)); return id; } static void destroy(GLuint& id) { gl::DeleteShader(id); id = 0; } static shader<T> create_from_file(std::string filepath) { return create_from_string(util::load_file_content<std::string>(filepath)); } static shader<T> create_from_string(const std::string& shader_source, std::string* out_log = nullptr) { shader<T> shader; GLint shader_length = GLint(shader_source.length()); auto shader_cstr = shader_source.c_str(); gl::ShaderSource(shader.id.get(), 1, &shader_cstr, &shader_length); gl::CompileShader(shader.id.get()); GLint compile_error = gl::GetError(); GLint is_compiled = 0; gl::GetShaderiv(shader.id.get(), gl::COMPILE_STATUS, &is_compiled); struct shader_compilation_exception : public std::exception { shader_compilation_exception(const std::string& error) : error(error) {} const char* what() const override { return error.c_str(); } private: std::string error; }; GLint log_length = 0; gl::GetShaderiv(shader.id.get(), gl::INFO_LOG_LENGTH, &log_length); if (log_length > 1) { std::string tmp_log; std::string& log = out_log ? *out_log : tmp_log; log.resize(log_length); gl::GetShaderInfoLog(shader.id.get(), log_length, &log_length, &log[0]); } else if (out_log) { out_log->clear(); } if(is_compiled != gl::TRUE_) throw shader_compilation_exception(std::to_string(compile_error)); return shader; } private: glid<shader<T>> id; friend GLuint get_id<shader<T>>(const shader<T>& t); }; typedef shader<shader_type::vertex> vertex_shader; typedef shader<shader_type::geometry> geometry_shader; typedef shader<shader_type::fragment> fragment_shader; typedef shader<shader_type::compute> compute_shader; typedef shader<shader_type::tess_control> tess_control_shader; typedef shader<shader_type::tess_evaluation> tess_evaluation_shader; } using namespace v1; }
30.00813
113
0.515578
[ "geometry", "vector" ]
6a9c00039d3c1bf291ec7add680db8b3cabfa774
2,849
cc
C++
google/cloud/dialogflow_es/conversation_datasets_connection_idempotency_policy.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/dialogflow_es/conversation_datasets_connection_idempotency_policy.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/dialogflow_es/conversation_datasets_connection_idempotency_policy.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/dialogflow/v2/conversation_dataset.proto #include "google/cloud/dialogflow_es/conversation_datasets_connection_idempotency_policy.h" #include "absl/memory/memory.h" #include <memory> namespace google { namespace cloud { namespace dialogflow_es { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using ::google::cloud::Idempotency; ConversationDatasetsConnectionIdempotencyPolicy:: ~ConversationDatasetsConnectionIdempotencyPolicy() = default; namespace { class DefaultConversationDatasetsConnectionIdempotencyPolicy : public ConversationDatasetsConnectionIdempotencyPolicy { public: ~DefaultConversationDatasetsConnectionIdempotencyPolicy() override = default; /// Create a new copy of this object. std::unique_ptr<ConversationDatasetsConnectionIdempotencyPolicy> clone() const override { return absl::make_unique< DefaultConversationDatasetsConnectionIdempotencyPolicy>(*this); } Idempotency CreateConversationDataset( google::cloud::dialogflow::v2::CreateConversationDatasetRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency GetConversationDataset( google::cloud::dialogflow::v2::GetConversationDatasetRequest const&) override { return Idempotency::kIdempotent; } Idempotency ListConversationDatasets( google::cloud::dialogflow::v2::ListConversationDatasetsRequest) override { return Idempotency::kIdempotent; } Idempotency DeleteConversationDataset( google::cloud::dialogflow::v2::DeleteConversationDatasetRequest const&) override { return Idempotency::kNonIdempotent; } Idempotency ImportConversationData( google::cloud::dialogflow::v2::ImportConversationDataRequest const&) override { return Idempotency::kNonIdempotent; } }; } // namespace std::unique_ptr<ConversationDatasetsConnectionIdempotencyPolicy> MakeDefaultConversationDatasetsConnectionIdempotencyPolicy() { return absl::make_unique< DefaultConversationDatasetsConnectionIdempotencyPolicy>(); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace dialogflow_es } // namespace cloud } // namespace google
32.747126
91
0.777817
[ "object" ]
6aa8b058b6ce3f3a592f9803d7ed9e8ae08578f3
4,322
cpp
C++
Sources/Internal/Scene3D/Systems/RenderUpdateSystem.cpp
BlitzModder/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
4
2019-11-15T11:30:00.000Z
2021-12-27T21:16:31.000Z
Sources/Internal/Scene3D/Systems/RenderUpdateSystem.cpp
TTopox/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/Scene3D/Systems/RenderUpdateSystem.cpp
TTopox/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
4
2017-04-07T04:32:41.000Z
2021-12-27T21:55:49.000Z
#include "Scene3D/Systems/RenderUpdateSystem.h" #include "Scene3D/Entity.h" #include "Scene3D/Components/RenderComponent.h" #include "Scene3D/Components/TransformComponent.h" #include "Scene3D/Lod/LodComponent.h" #include "Scene3D/Components/SwitchComponent.h" #include "Scene3D/Components/ComponentHelpers.h" #include "Scene3D/Components/SingleComponents/TransformSingleComponent.h" #include "Render/Highlevel/Frustum.h" #include "Render/Highlevel/Camera.h" #include "Render/Highlevel/Landscape.h" #include "Render/Highlevel/RenderLayer.h" #include "Render/Highlevel/RenderPass.h" #include "Render/Highlevel/RenderBatch.h" #include "Render/Highlevel/RenderSystem.h" #include "Debug/ProfilerCPU.h" #include "Debug/ProfilerMarkerNames.h" #include "Scene3D/Scene.h" namespace DAVA { RenderUpdateSystem::RenderUpdateSystem(Scene* scene) : SceneSystem(scene) { } void RenderUpdateSystem::AddEntity(Entity* entity) { RenderObject* renderObject = entity->GetComponent<RenderComponent>()->GetRenderObject(); if (!renderObject) return; Matrix4* worldTransformPointer = entity->GetComponent<TransformComponent>()->GetWorldTransformPtr(); renderObject->SetWorldTransformPtr(worldTransformPointer); UpdateActiveIndexes(entity, renderObject); entityObjectMap.emplace(entity, renderObject); GetScene()->GetRenderSystem()->RenderPermanent(renderObject); } void RenderUpdateSystem::RemoveEntity(Entity* entity) { auto renderObjectIter = entityObjectMap.find(entity); if (renderObjectIter != entityObjectMap.end()) { RenderObject* renderObject = renderObjectIter->second; if (renderObject != nullptr) { GetScene()->GetRenderSystem()->RemoveFromRender(renderObject); entityObjectMap.erase(entity); } } } void RenderUpdateSystem::PrepareForRemove() { RenderSystem* renderSystem = GetScene()->GetRenderSystem(); for (const auto& node : entityObjectMap) { renderSystem->RemoveFromRender(node.second); } entityObjectMap.clear(); } void RenderUpdateSystem::Process(float32 timeElapsed) { DAVA_PROFILER_CPU_SCOPE(ProfilerCPUMarkerName::SCENE_RENDER_UPDATE_SYSTEM); TransformSingleComponent* tsc = GetScene()->transformSingleComponent; for (auto& pair : tsc->worldTransformChanged.map) { if (pair.first->GetComponentsCount(Type::Instance<RenderComponent>()) > 0) { for (Entity* entity : pair.second) { RenderComponent* rc = entity->GetComponent<RenderComponent>(); RenderObject* renderObject = rc->GetRenderObject(); if (renderObject) { // Update new transform pointer, and mark that transform is changed Matrix4* worldTransformPointer = entity->GetComponent<TransformComponent>()->GetWorldTransformPtr(); renderObject->SetWorldTransformPtr(worldTransformPointer); entity->GetScene()->renderSystem->MarkForUpdate(renderObject); Matrix4 inverseWorldTransform = Matrix4::IDENTITY; worldTransformPointer->GetInverse(inverseWorldTransform); renderObject->SetInverseTransform(inverseWorldTransform); } } } } RenderSystem* renderSystem = GetScene()->GetRenderSystem(); renderSystem->SetMainCamera(GetScene()->GetCurrentCamera()); renderSystem->SetDrawCamera(GetScene()->GetDrawCamera()); GetScene()->GetRenderSystem()->Update(timeElapsed); } void RenderUpdateSystem::UpdateActiveIndexes(Entity* entity, RenderObject* object) { Entity* parent; // search effective lod index parent = entity; while (nullptr != parent) { LodComponent* lc = GetLodComponent(parent); if (nullptr != lc) { object->SetLodIndex(lc->GetCurrentLod()); break; } parent = parent->GetParent(); } // search effective switch index parent = entity; while (nullptr != parent) { SwitchComponent* sc = GetSwitchComponent(parent); if (nullptr != sc) { object->SetSwitchIndex(sc->GetSwitchIndex()); break; } parent = parent->GetParent(); } } };
32.253731
120
0.676539
[ "render", "object", "transform" ]
6aadf1e446f9f7879e265e004d9fa5d2c02f110d
10,361
cpp
C++
interfaces/innerkits/appverify/test/unittest/src/hap_byte_buffer_test.cpp
openharmony-sig-ci/security_appverify
5c705c648c87383f3ab4cbdae187933db9138e76
[ "Apache-2.0" ]
null
null
null
interfaces/innerkits/appverify/test/unittest/src/hap_byte_buffer_test.cpp
openharmony-sig-ci/security_appverify
5c705c648c87383f3ab4cbdae187933db9138e76
[ "Apache-2.0" ]
null
null
null
interfaces/innerkits/appverify/test/unittest/src/hap_byte_buffer_test.cpp
openharmony-sig-ci/security_appverify
5c705c648c87383f3ab4cbdae187933db9138e76
[ "Apache-2.0" ]
1
2021-09-13T11:13:32.000Z
2021-09-13T11:13:32.000Z
/* * Copyright (C) 2021 Huawei Device Co., Ltd. * 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 "hap_byte_buffer_test.h" #include <gtest/gtest.h> #include "common/hap_byte_buffer.h" #include "securec.h" #include "test_const.h" using namespace testing::ext; using namespace OHOS::Security::Verify; namespace { class HapByteBufferTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); }; void HapByteBufferTest::SetUpTestCase(void) { } void HapByteBufferTest::TearDownTestCase(void) { } void HapByteBufferTest::SetUp() { } void HapByteBufferTest::TearDown() { } /** * @tc.name: Test HapByteBuffer Constructor and overload function. * @tc.desc: The static function will return an object of HapByteBuffer; * @tc.type: FUNC */ HWTEST_F (HapByteBufferTest, HapByteBuffer001, TestSize.Level1) { /* * @tc.steps: step1. Run HapByteBuffer(buffer1). * @tc.expected: step1. The returned object is the same as buffer1. */ HapByteBuffer buffer1; HapByteBuffer buffer2(buffer1); bool judge = (buffer2.GetCapacity() == buffer1.GetCapacity()) && (buffer2.GetPosition() == buffer1.GetPosition()) && (buffer2.GetLimit() == buffer1.GetLimit()) && (buffer2.GetBufferPtr() == nullptr); ASSERT_TRUE(judge); /* * @tc.steps: step1. Run overloaded function =. * @tc.expected: step1. The left object is the same as right object. */ HapByteBuffer buffer3(TEST_HAPBYTEBUFFER_LENGTH); buffer3.PutInt32(0, 0); HapByteBuffer buffer4(TEST_HAPBYTEBUFFER_LENGTH); buffer4.PutInt32(0, TEST_HAPBYTEBUFFER_INT32_DATA); buffer3 = buffer4; ASSERT_TRUE(buffer3.IsEqual(buffer4)); } /** * @tc.name: Test a HapByteBuffer object's operation of GetInt and Put * @tc.desc: The static function will return data from HapByteBuffer's buffer * @tc.type: FUNC */ HWTEST_F (HapByteBufferTest, GetIntAndPutOperation001, TestSize.Level1) { /* * @tc.steps: step1. Create an empty buffer and get data from it. * @tc.expected: step1. The return result is false. */ HapByteBuffer emptyBuffer; int dataInt32; ASSERT_FALSE(emptyBuffer.GetInt32(dataInt32)); long long dataInt64; ASSERT_FALSE(emptyBuffer.GetInt64(dataInt64)); unsigned short dataUInt16; ASSERT_FALSE(emptyBuffer.GetUInt16(0, dataUInt16)); /* * @tc.steps: step2. Create a HapByteBuffer with one byte's buffer and get data from second byte. * @tc.expected: step2. The return result is false. */ HapByteBuffer testBuffer(1); char testChar = TEST_HAPBYTEBUFFER_CHAR_DATA; testBuffer.PutData(0, &testChar, sizeof(testChar)); unsigned int dataUInt32; ASSERT_FALSE(testBuffer.GetUInt32(1, dataUInt32)); ASSERT_FALSE(testBuffer.GetInt32(1, dataInt32)); ASSERT_FALSE(testBuffer.GetInt64(1, dataInt64)); ASSERT_FALSE(testBuffer.GetUInt16(1, dataUInt16)); /* * @tc.steps: step3. Get data from negative position. * @tc.expected: step3. The return result is false. */ ASSERT_FALSE(testBuffer.GetInt64(TEST_HAPBYTEBUFFER_INVALID_INDEX, dataInt64)); /* * @tc.steps: step4. Put data to buffer and get data from it. * @tc.expected: step4. The return data is same as which we put. */ HapByteBuffer testBuffer2(TEST_HAPBYTEBUFFER_LENGTH); testBuffer2.PutByte(0, testChar); char testUInt16[TEST_HAPBYTEBUFFER_UINT16_LENGTH]; errno_t err; err = memcpy_s(testUInt16, sizeof(testUInt16), &TEST_HAPBYTEBUFFER_UINT16_DATA, sizeof(TEST_HAPBYTEBUFFER_UINT16_DATA)); ASSERT_EQ(err, EOK); testBuffer2.PutData(sizeof(char), testUInt16, sizeof(testUInt16)); int testInt32 = TEST_HAPBYTEBUFFER_INT32_DATA; testBuffer2.PutInt32(sizeof(char) + sizeof(unsigned short), testInt32); char testInt64[TEST_HAPBYTEBUFFER_INT64_LENGTH]; err = memcpy_s(testInt64, sizeof(testInt64), &TEST_HAPBYTEBUFFER_INT64_DATA, sizeof(TEST_HAPBYTEBUFFER_INT64_DATA)); ASSERT_EQ(err, EOK); testBuffer2.PutData(TEST_HAPBYTEBUFFER_LENGTH - sizeof(testInt64), testInt64, sizeof(testInt64)); ASSERT_TRUE(testBuffer2.GetUInt32(sizeof(char) + sizeof(unsigned short), dataUInt32)); ASSERT_EQ(dataUInt32, TEST_HAPBYTEBUFFER_UINT32_DATA); ASSERT_TRUE(testBuffer2.GetInt32(sizeof(char) + sizeof(unsigned short), dataInt32)); ASSERT_EQ(dataInt32, TEST_HAPBYTEBUFFER_INT32_DATA); ASSERT_TRUE(testBuffer2.GetInt64(TEST_HAPBYTEBUFFER_LENGTH - sizeof(testInt64), dataInt64)); ASSERT_EQ(dataInt64, TEST_HAPBYTEBUFFER_INT64_DATA); ASSERT_TRUE(testBuffer2.GetUInt16(sizeof(char), dataUInt16)); ASSERT_EQ(dataUInt16, TEST_HAPBYTEBUFFER_UINT16_DATA); } /** * @tc.name: Test HapByteBuffer function of slice * @tc.desc: The static function will get an object after slice and detect it is right; * @tc.type: FUNC */ HWTEST_F (HapByteBufferTest, Slice001, TestSize.Level1) { /* * @tc.steps: step1. Set a fixed length buffer. * @tc.expected: step1. The return is same as value is set. */ HapByteBuffer buffer1(TEST_HAPBYTEBUFFER_LENGTH_2); buffer1.SetCapacity(TEST_HAPBYTEBUFFER_LENGTH); ASSERT_TRUE(buffer1.GetCapacity() == TEST_HAPBYTEBUFFER_LENGTH); /* * @tc.steps: step2. Slice buffer. * @tc.expected: step2. The return is the target length after slice. */ buffer1.PutInt32(0, TEST_HAPBYTEBUFFER_INT32_DATA); buffer1.PutInt32(sizeof(int), TEST_HAPBYTEBUFFER_INT32_DATA_2); buffer1.SetPosition(sizeof(int)); buffer1.SetLimit(sizeof(int) + sizeof(int)); buffer1.Slice(); ASSERT_TRUE(buffer1.Remaining() == sizeof(int)); /* * @tc.steps: step3. Get int32 from buffer1. * @tc.expected: step3. The return result is equal to TEST_HAPBYTEBUFFER_INT32_DATA_2. */ int testDataInt32; ASSERT_TRUE(buffer1.GetInt32(testDataInt32)); ASSERT_EQ(testDataInt32, TEST_HAPBYTEBUFFER_INT32_DATA_2); /* * @tc.steps: step4. Slice continue, reset position and limit, and calculate if buffer has remain. * @tc.expected: step4. The return result is true. */ buffer1.Slice(); buffer1.Clear(); ASSERT_TRUE(buffer1.HasRemaining()); } /** * @tc.name: Test HapByteBuffer function of CopyPartialBuffer * @tc.desc: The static function will copy data from an object, detect the data is right; * @tc.type: FUNC */ HWTEST_F (HapByteBufferTest, CopyPartialBuffer001, TestSize.Level1) { /* * @tc.steps: step1. Copy 8 bytes data from 10st-position in a 15 bytes length buffer. * @tc.expected: step1. The return result is false. */ HapByteBuffer buffer1(TEST_HAPBYTEBUFFER_LENGTH); buffer1.PutInt32(0, TEST_HAPBYTEBUFFER_INT32_DATA); buffer1.PutInt32(sizeof(int), TEST_HAPBYTEBUFFER_INT32_DATA_2); HapByteBuffer buffer2(TEST_HAPBYTEBUFFER_LENGTH); buffer1.SetPosition(TEST_HAPBYTEBUFFER_POSITION); ASSERT_FALSE(buffer2.CopyPartialBuffer(buffer1, TEST_HAPBYTEBUFFER_LENGTH_2)); /* * @tc.steps: step2. Copy 8 bytes data from first-position in a 15 bytes length buffer. * @tc.expected: step2. Buffer2 return is targeted value. */ buffer1.Clear(); buffer2.CopyPartialBuffer(buffer1, TEST_HAPBYTEBUFFER_LENGTH_2); int target1; ASSERT_TRUE(buffer2.GetInt32(target1)); ASSERT_EQ(target1, TEST_HAPBYTEBUFFER_INT32_DATA); int target2; ASSERT_TRUE(buffer2.GetInt32(target2)); ASSERT_EQ(target2, TEST_HAPBYTEBUFFER_INT32_DATA_2); } /** * @tc.name: Test HapByteBuffer function of IsEqual001 * @tc.desc: The static function will return two object whether is equal. * @tc.type: FUNC */ HWTEST_F (HapByteBufferTest, IsEqual001, TestSize.Level1) { /* * @tc.steps: step1. Create a buffer, and compare it with itself. * @tc.expected: step1. The return result is true. */ char testChar[TEST_HAPBYTEBUFFER_LENGTH] = "Hello, world!!"; HapByteBuffer buffer1(TEST_HAPBYTEBUFFER_LENGTH); buffer1.PutData(0, testChar, TEST_HAPBYTEBUFFER_LENGTH); ASSERT_TRUE(buffer1.IsEqual(buffer1)); /* * @tc.steps: step2. Create another buffer and compare it with buffer1. * @tc.expected: step2. The return result is false. */ HapByteBuffer buffer2; ASSERT_FALSE(buffer1.IsEqual(buffer2)); /* * @tc.steps: step3. Set length of buffer2 same as buffer1. * @tc.expected: step3. The return result is false. */ buffer2.SetCapacity(TEST_HAPBYTEBUFFER_LENGTH); ASSERT_FALSE(buffer1.IsEqual(buffer2)); /* * @tc.steps: step4. Use copy constructor to create an buffer3, and compare it with buffer1. * @tc.expected: step4. The return result is true. */ HapByteBuffer buffer3(buffer1); ASSERT_TRUE(buffer1.IsEqual(buffer3)); } /** * @tc.name: Test HapByteBuffer function of IsEqual002 * @tc.desc: The static function will return whether the value in buffer is equal to a string. * @tc.type: FUNC */ HWTEST_F (HapByteBufferTest, IsEqual002, TestSize.Level1) { /* * @tc.steps: step1. Create a buffer and string, and compare. * @tc.expected: step1. The return is false. */ std::string testStr = "Hello, world!!!"; HapByteBuffer buffer1; const HapByteBuffer& buffer2 = buffer1; buffer1 = buffer2; ASSERT_FALSE(buffer1.IsEqual(testStr)); /* * @tc.steps: step2. Set length of buffer1 same as string. * @tc.expected: step2. The return is false. */ buffer1.SetCapacity(static_cast<int>(testStr.size())); ASSERT_FALSE(buffer1.IsEqual(testStr)); /* * @tc.steps: step3. Put string to buffer1 and compare. * @tc.expected: step3. The return is true. */ for (int i = 0; i < static_cast<int>(testStr.size()); i++) { buffer1.PutByte(i, testStr[i]); } ASSERT_TRUE(buffer1.IsEqual(testStr)); } }
36.227273
102
0.711418
[ "object" ]
6ab4002f17b20db388d5a0cb740d09fc1f31d4e1
7,903
cpp
C++
src/geos_utils.cpp
chapmanjacobd/exactextract
b1d12537f9b882e628d7268c5860923cfe309337
[ "Apache-2.0" ]
null
null
null
src/geos_utils.cpp
chapmanjacobd/exactextract
b1d12537f9b882e628d7268c5860923cfe309337
[ "Apache-2.0" ]
null
null
null
src/geos_utils.cpp
chapmanjacobd/exactextract
b1d12537f9b882e628d7268c5860923cfe309337
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018-2020 ISciences, LLC. // All rights reserved. // // This software is 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 "geos_utils.h" #include <stdexcept> #if !HAVE_380 static inline int GEOSCoordSeq_setXY_r(GEOSContextHandle_t context, GEOSCoordSequence* seq, unsigned int idx, double x, double y) { return GEOSCoordSeq_setX_r(context, seq, idx, x) && GEOSCoordSeq_setY_r(context, seq, idx, y); } #endif namespace exactextract { geom_ptr_r geos_make_box_polygon(GEOSContextHandle_t context, const Box & b) { auto seq = geos_ptr(context, GEOSCoordSeq_create_r(context, 5, 2)); GEOSCoordSeq_setXY_r(context, seq.get(), 0, b.xmin, b.ymin); GEOSCoordSeq_setXY_r(context, seq.get(), 1, b.xmax, b.ymin); GEOSCoordSeq_setXY_r(context, seq.get(), 2, b.xmax, b.ymax); GEOSCoordSeq_setXY_r(context, seq.get(), 3, b.xmin, b.ymax); GEOSCoordSeq_setXY_r(context, seq.get(), 4, b.xmin, b.ymin); auto shell = geos_ptr(context, GEOSGeom_createLinearRing_r(context, seq.release())); return geos_ptr(context, GEOSGeom_createPolygon_r(context, shell.release(), nullptr, 0)); } bool segment_intersection( GEOSContextHandle_t context, const Coordinate &a0, const Coordinate &a1, const Coordinate &b0, const Coordinate &b1, Coordinate &result) { #if HAVE_370 int code = GEOSSegmentIntersection_r(context, a0.x, a0.y, a1.x, a1.y, b0.x, b0.y, b1.x, b1.y, &result.x, &result.y); if (!code) { throw std::runtime_error("Error in GEOSSegmentIntersection_r"); } return code == 1; #else auto seqa = GEOSCoordSeq_create_ptr(context, 2, 2); auto seqb = GEOSCoordSeq_create_ptr(context, 2, 2); GEOSCoordSeq_setX_r(context, seqa.get(), 0, a0.x); GEOSCoordSeq_setY_r(context, seqa.get(), 0, a0.y); GEOSCoordSeq_setX_r(context, seqa.get(), 1, a1.x); GEOSCoordSeq_setY_r(context, seqa.get(), 1, a1.y); GEOSCoordSeq_setX_r(context, seqb.get(), 0, b0.x); GEOSCoordSeq_setY_r(context, seqb.get(), 0, b0.y); GEOSCoordSeq_setX_r(context, seqb.get(), 1, b1.x); GEOSCoordSeq_setY_r(context, seqb.get(), 1, b1.y); auto geom_a = GEOSGeom_createLineString_ptr(context, seqa.release()); auto geom_b = GEOSGeom_createLineString_ptr(context, seqb.release()); geom_ptr_r intersection = geos_ptr(context, GEOSIntersection_r(context, geom_a.get(), geom_b.get())); if (GEOSisEmpty_r(context, intersection.get())) { return false; } if (GEOSGeomTypeId_r(context, intersection.get()) != GEOS_POINT) { return false; } GEOSGeomGetX_r(context, intersection.get(), &result.x); GEOSGeomGetY_r(context, intersection.get(), &result.y); return true; #endif } Box geos_get_box(GEOSContextHandle_t context, const GEOSGeometry* g) { double xmin, ymin, xmax, ymax; #if HAVE_370 if (!(GEOSGeom_getXMin_r(context, g, &xmin) && GEOSGeom_getYMin_r(context, g, &ymin) && GEOSGeom_getXMax_r(context, g, &xmax) && GEOSGeom_getYMax_r(context, g, &ymax))) { throw std::runtime_error("Error getting geometry extent."); } #else geom_ptr_r env = geos_ptr(context, GEOSEnvelope_r(context, g)); const GEOSGeometry* ring = GEOSGetExteriorRing_r(context, env.get()); const GEOSCoordSequence* seq = GEOSGeom_getCoordSeq_r(context, ring); xmin = std::numeric_limits<double>::max(); ymin = std::numeric_limits<double>::max(); xmax = std::numeric_limits<double>::lowest(); ymax = std::numeric_limits<double>::lowest(); for (unsigned int i = 0; i < 4; i++) { double x, y; if (!GEOSCoordSeq_getX_r(context, seq, i, &x) || !GEOSCoordSeq_getY_r(context, seq, i, &y)) { throw std::runtime_error("Error reading coordinates."); } xmin = std::min(xmin, x); ymin = std::min(ymin, y); xmax = std::max(xmax, x); ymax = std::max(ymax, y); } #endif return {xmin, ymin, xmax, ymax}; } std::vector<Box> geos_get_component_boxes(GEOSContextHandle_t context, const GEOSGeometry* g) { size_t n = static_cast<size_t>(GEOSGetNumGeometries_r(context, g)); std::vector<Box> boxes; boxes.reserve(n); for (size_t i = 0; i < n; i++) { boxes.push_back(geos_get_box(context, GEOSGetGeometryN_r(context, g, i))); } return boxes; } bool geos_is_ccw(GEOSContextHandle_t context, const GEOSCoordSequence *s) { #if HAVE_370 char result; if (!GEOSCoordSeq_isCCW_r(context, s, &result)) { throw std::runtime_error("Error calling GEOSCoordSeq_isCCW_r."); } return result; #else std::vector<Coordinate> coords = read(context, s); if (coords.size() < 4) { throw std::runtime_error("Ring has fewer than 4 points, so orientation cannot be determined."); } // find highest point size_t hi_index = (size_t) std::distance( coords.begin(), std::max_element(coords.begin(), coords.end(), [](const auto& a, const auto&b) { return a.y < b.y; }) ); // find distinct point before highest point size_t i_prev = hi_index; do { if (i_prev == 0) { i_prev = coords.size() - 1; } else { i_prev--; } } while (i_prev != hi_index && coords[i_prev] == coords[hi_index]); // find distinct point after highest point size_t i_next = hi_index; do { i_next = (i_next + 1) % coords.size(); } while (i_next != hi_index && coords[i_next] == coords[hi_index]); Coordinate& a = coords[i_prev]; Coordinate& b = coords[hi_index]; Coordinate& c = coords[i_next]; if (a == b || b == c || a == c) { return false; } int disc = GEOSOrientationIndex_r(context, a.x, a.y, b.x, b.y, c.x, c.y); if (disc == 0) { // poly is CCW if prev x is right of next x return (a.x > b.x); } else { // if area is positive, points are ordered CCW return disc > 0; } #endif } std::vector<Coordinate> read(GEOSContextHandle_t context, const GEOSCoordSequence *s) { unsigned int size; if (!GEOSCoordSeq_getSize_r(context, s, &size)) { throw std::runtime_error("Error calling GEOSCoordSeq_getSize."); } std::vector<Coordinate> coords{size}; for (unsigned int i = 0; i < size; i++) { if (!GEOSCoordSeq_getX_r(context, s, i, &(coords[i].x)) || !GEOSCoordSeq_getY_r(context, s, i, &(coords[i].y))) { throw std::runtime_error("Error reading coordinates."); } } return coords; } }
35.439462
125
0.582057
[ "geometry", "vector" ]
6ab615a782330cbb4e485fd365a2d7ef2f72d708
8,541
cpp
C++
src/msgpack_unpack.cpp
qorelanguage/module-msgpack
a8bedb2ccdea89912fd5eef2e54d33dc009cafed
[ "MIT" ]
null
null
null
src/msgpack_unpack.cpp
qorelanguage/module-msgpack
a8bedb2ccdea89912fd5eef2e54d33dc009cafed
[ "MIT" ]
1
2019-01-04T15:45:42.000Z
2019-01-04T15:45:42.000Z
src/msgpack_unpack.cpp
qorelanguage/module-msgpack
a8bedb2ccdea89912fd5eef2e54d33dc009cafed
[ "MIT" ]
null
null
null
/* -*- mode: c++; indent-tabs-mode: nil -*- */ /* msgpack_unpack.cpp Qore MessagePack module Copyright (C) 2018 Qore Technologies, s.r.o. 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 "msgpack_unpack.h" // std #include <climits> #include <cstdint> // module sources #include "msgpack_extensions.h" #include "MsgPackException.h" #include "MsgPackExtension.h" #include "QC_MsgPackExtension.h" namespace msgpack { namespace intern { QoreListNode* msgpack_unpack_array(mpack_reader_t* reader, mpack_tag_t tag, OperationMode mode, ExceptionSink* xsink) { // prepare list ReferenceHolder<QoreListNode> list(new QoreListNode, xsink); // read all elements uint32_t size = mpack_tag_array_count(&tag); for (uint32_t i = 0; i < size; i++) { list->push(msgpack_unpack_value(reader, mode, xsink), xsink); } mpack_done_array(reader); return list.release(); } BinaryNode* msgpack_unpack_binary(mpack_reader_t* reader, mpack_tag_t tag, ExceptionSink* xsink) { uint32_t size = mpack_tag_bin_length(&tag); // prepare binary node SimpleRefHolder<BinaryNode> bin(new BinaryNode); bin->preallocate(size); // read binary mpack_read_bytes(reader, static_cast<char*>(const_cast<void*>(bin->getPtr())), size); mpack_done_bin(reader); return bin.release(); } AbstractQoreNode* msgpack_unpack_ext(mpack_reader_t* reader, mpack_tag_t tag, OperationMode mode, ExceptionSink* xsink) { switch (mode) { case MSGPACK_SIMPLE_MODE: { // handle MessagePack built-in extension types first if (mpack_tag_ext_exttype(&tag) == MPACK_EXTTYPE_TIMESTAMP) return msgpack_unpack_ext_timestamp(reader, tag, xsink); // otherwise unpack as an extension object uint32_t size = mpack_tag_ext_length(&tag); SimpleRefHolder<BinaryNode> bin(new BinaryNode); bin->preallocate(size); mpack_read_bytes(reader, (char*) bin->getPtr(), size); mpack_done_ext(reader); return new QoreObject(QC_MSGPACKEXTENSION, getProgram(), new MsgPackExtension(mpack_tag_ext_exttype(&tag), bin.release())); } case MSGPACK_QORE_MODE: { switch (mpack_tag_ext_exttype(&tag)) { // MessagePack built-in types case MPACK_EXTTYPE_TIMESTAMP: return msgpack_unpack_ext_timestamp(reader, tag, xsink); // Qore extension types case MSGPACK_EXT_QORE_NULL: return msgpack_unpack_ext_null(reader, tag, xsink); case MSGPACK_EXT_QORE_DATE: return msgpack_unpack_ext_date(reader, tag, xsink); case MSGPACK_EXT_QORE_NUMBER: return msgpack_unpack_ext_number(reader, tag, xsink); case MSGPACK_EXT_QORE_STRING: return msgpack_unpack_ext_string(reader, tag, xsink); default: mpack_reader_flag_error(reader, mpack_error_data); break; } break; } default: break; } return nullptr; } QoreHashNode* msgpack_unpack_map(mpack_reader_t* reader, mpack_tag_t tag, OperationMode mode, ExceptionSink* xsink) { // prepare hash ReferenceHolder<QoreHashNode> hash(new QoreHashNode, xsink); // read all elements uint32_t size = mpack_tag_map_count(&tag); for (uint32_t i = 0; i < size; i++) { // read key and value ValueHolder key(msgpack_unpack_value(reader, mode, xsink), xsink); ValueHolder value(msgpack_unpack_value(reader, mode, xsink), xsink); // check key and value if (!(*key || *value) || key->getType() != NT_STRING) { mpack_reader_flag_error(reader, mpack_error_data); break; } // add element to hash hash->setKeyValue(key->get<QoreStringNode>()->c_str(), value.release(), xsink); } mpack_done_map(reader); return hash.release(); } QoreStringNode* msgpack_unpack_string(mpack_reader_t* reader, mpack_tag_t tag, ExceptionSink* xsink) { uint32_t size = mpack_tag_str_length(&tag); // prepare string node and buffer for reading SimpleRefHolder<QoreStringNode> str(new QoreStringNode); str->allocate(size+1); qore_size_t allocated = str->capacity(); char* buffer = str->giveBuffer(); // read string mpack_read_utf8(reader, buffer, size); buffer[size] = '\0'; str->set(buffer, size, allocated, QCS_UTF8); mpack_done_str(reader); return str.release(); } QoreValue msgpack_unpack_value(mpack_reader_t* reader, OperationMode mode, ExceptionSink* xsink) { mpack_tag_t tag = mpack_read_tag(reader); switch (mpack_tag_type(&tag)) { case mpack_type_array: return msgpack_unpack_array(reader, tag, mode, xsink); case mpack_type_bin: return msgpack_unpack_binary(reader, tag, xsink); case mpack_type_bool: return mpack_tag_bool_value(&tag); case mpack_type_double: return mpack_tag_double_value(&tag); case mpack_type_ext: return msgpack_unpack_ext(reader, tag, mode, xsink); case mpack_type_float: return mpack_tag_float_value(&tag); case mpack_type_int: return mpack_tag_int_value(&tag); case mpack_type_map: return msgpack_unpack_map(reader, tag, mode, xsink); case mpack_type_nil: return QoreValue(); case mpack_type_str: return msgpack_unpack_string(reader, tag, xsink); case mpack_type_uint: { uint64_t val = mpack_tag_uint_value(&tag); if (val <= LLONG_MAX) return static_cast<int64>(val); return new QoreNumberNode(static_cast<double>(val)); } default: mpack_reader_flag_error(reader, mpack_error_data); break; } return QoreValue(); } //------------------------- // msgpack_unpack function //------------------------- QoreValue msgpack_unpack(const BinaryNode* data, OperationMode mode, ExceptionSink* xsink) { ValueHolder unpacked(xsink); const char* dataCheck = nullptr; const char* buffer = static_cast<const char*>(data->getPtr()); size_t remaining = 0; size_t size = data->size(); mpack_reader_t reader; // return nothing if no data if (buffer == nullptr || size == 0) return QoreValue(); // initialize reader mpack_reader_init_data(&reader, buffer, size); // unpack the data do { QoreValue node = msgpack_unpack_value(&reader, mode, xsink); if (*unpacked) { ReferenceHolder<QoreListNode> list(xsink); if (unpacked->getType() == NT_LIST) list = unpacked.release().get<QoreListNode>(); else list = new QoreListNode(autoTypeInfo); list->push(node, xsink); unpacked = list.release(); } else { unpacked = node; } remaining = mpack_reader_remaining(&reader, &dataCheck); } while (remaining && dataCheck); // finish reading mpack_error_t result = mpack_reader_destroy(&reader); if (result != mpack_ok) { throw msgpack::getMsgPackException(result); } // return unpacked Qore node return unpacked.release(); } } // namespace intern } // namespace msgpack
34.719512
135
0.648636
[ "object" ]
6abf1b4364ada6040355916a8013a5e01ace0889
2,209
cpp
C++
shim_and_sl/ShimBufferTracker.cpp
aosp-goes-brrbrr/packages_modules_NeuralNetworks
87a14e21ce905ce7c4584fe9a53e4397a4d33c67
[ "Apache-2.0" ]
null
null
null
shim_and_sl/ShimBufferTracker.cpp
aosp-goes-brrbrr/packages_modules_NeuralNetworks
87a14e21ce905ce7c4584fe9a53e4397a4d33c67
[ "Apache-2.0" ]
null
null
null
shim_and_sl/ShimBufferTracker.cpp
aosp-goes-brrbrr/packages_modules_NeuralNetworks
87a14e21ce905ce7c4584fe9a53e4397a4d33c67
[ "Apache-2.0" ]
2
2021-11-28T11:20:31.000Z
2021-11-28T11:28:38.000Z
/* * Copyright (C) 2021 The Android Open Source Project * * 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. */ #define LOG_TAG "ShimBufferTracker" #include "ShimBufferTracker.h" #include "ShimDevice.h" #include <android-base/logging.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> using namespace ::android::nn::sl_wrapper; namespace aidl::android::hardware::neuralnetworks { std::unique_ptr<ShimBufferTracker::Token> ShimBufferTracker::add( std::shared_ptr<::android::nn::sl_wrapper::Memory> buffer) { if (buffer == nullptr) { return nullptr; } std::lock_guard<std::mutex> guard(mMutex); uint32_t token = 0; if (mFreeTokens.empty()) { token = mTokenToBuffers.size(); mTokenToBuffers.push_back(std::move(buffer)); } else { token = mFreeTokens.top(); mFreeTokens.pop(); mTokenToBuffers[token] = std::move(buffer); } return std::make_unique<Token>(token, shared_from_this()); } std::shared_ptr<::android::nn::sl_wrapper::Memory> ShimBufferTracker::get(uint32_t token) const { std::lock_guard<std::mutex> guard(mMutex); if (mTokenToBuffers.size() <= token || mTokenToBuffers[token] == nullptr) { LOG(ERROR) << "ShimBufferTracker::get -- unknown token " << token; return nullptr; } return mTokenToBuffers[token]; } void ShimBufferTracker::free(uint32_t token) { std::lock_guard<std::mutex> guard(mMutex); CHECK_LT(token, mTokenToBuffers.size()); CHECK(mTokenToBuffers[token] != nullptr); mTokenToBuffers[token] = nullptr; mFreeTokens.push(token); } } // namespace aidl::android::hardware::neuralnetworks
31.557143
97
0.695337
[ "vector" ]
6ac15c9c77420e496a74b1f662120a91bff042dd
141,547
cpp
C++
roomedit/owl-6.34/source/window.cpp
Meridian59Kor/Meridian59
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
[ "FSFAP" ]
119
2015-08-19T17:57:01.000Z
2022-03-30T01:41:51.000Z
roomedit/owl-6.34/source/window.cpp
Meridian59Kor/Meridian59
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
[ "FSFAP" ]
120
2015-01-01T13:02:04.000Z
2015-08-14T20:06:27.000Z
roomedit/owl-6.34/source/window.cpp
Meridian59Kor/Meridian59
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
[ "FSFAP" ]
46
2015-08-16T23:21:34.000Z
2022-02-05T01:08:22.000Z
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1991, 1996 by Borland International, All Rights Reserved // /// \file /// Implementation of TWindow. This defines the basic behavior of all Windows. //---------------------------------------------------------------------------- #include <owl/pch.h> #include <owl/defs.h> #include <owl/window.h> #include <owl/applicat.h> #include <owl/appdict.h> #include <owl/scroller.h> #include <owl/gdiobjec.h> #include <owl/menu.h> #include <owl/framewin.h> #include <owl/commctrl.h> #include <owl/shellitm.h> #include <owl/tooltip.h> #if defined(BI_MULTI_THREAD_RTL) #include <owl/thread.h> #endif #include <stdlib.h> #include <stdio.h> #if defined(BI_NEED_ZMOUSE_H) # include <api_upd/zmouse.h> #else #include <zmouse.h> #endif #include <owl/registry.h> #include <owl/hlpmanag.h> //THelpHitInfo #if defined(__BORLANDC__) # pragma option -w-ccc // Disable "Condition is always true/false" #endif using namespace std; namespace owl { OWL_DIAGINFO; DIAG_DECLARE_GROUP(OwlMsg); // diagnostic group for message tracing DIAG_DEFINE_GROUP_INIT(OWL_INI, OwlWin, 1, 0); // diag. group for windows DIAG_DEFINE_GROUP_INIT(OWL_INI, OwlCmd, 1, 0); // diag. group for commands } // OWL namespace // // Define to use rtti to create unique window ids for the message cache // #define OWL_RTTI_MSGCACHE # define TYPE_UNIQUE_UINT32(t) reinterpret_cast<uint32>(typeid(t).name()) bool gBatchMode = false; // true if we were invoked to do batch processing // which means windows should be invisible and whatnot // currently this is only set if we have an output parameter namespace owl { // // Externs defined in owl.cpp // extern _OWLFUNC(void) SetCreationWindow(owl::TWindow*); extern _OWLFUNC(owl::TWindow*) GetCreationWindow(); extern _OWLDATA(uint) GetWindowPtrMsgId; DEFINE_RESPONSE_TABLE(TWindow) EV_WM_SETCURSOR, EV_WM_SIZE, EV_WM_MOVE, EV_WM_COMPAREITEM, EV_WM_DELETEITEM, EV_WM_DRAWITEM, EV_WM_MEASUREITEM, EV_WM_VSCROLL, EV_WM_HSCROLL, EV_WM_CHILDINVALID, EV_WM_ERASEBKGND, EV_WM_CTLCOLOR, EV_WM_PAINT, EV_WM_LBUTTONDOWN, EV_WM_KILLFOCUS, EV_MESSAGE(WM_CTLCOLORMSGBOX, EvWin32CtlColor), EV_MESSAGE(WM_CTLCOLOREDIT, EvWin32CtlColor), EV_MESSAGE(WM_CTLCOLORLISTBOX, EvWin32CtlColor), EV_MESSAGE(WM_CTLCOLORBTN, EvWin32CtlColor), EV_MESSAGE(WM_CTLCOLORDLG, EvWin32CtlColor), EV_MESSAGE(WM_CTLCOLORSCROLLBAR, EvWin32CtlColor), EV_MESSAGE(WM_CTLCOLORSTATIC, EvWin32CtlColor), EV_WM_CREATE, EV_WM_CLOSE, EV_WM_DESTROY, EV_WM_NCDESTROY, EV_WM_QUERYENDSESSION, EV_WM_ENDSESSION, EV_WM_SYSCOLORCHANGE, EV_WM_INITMENUPOPUP, EV_WM_CONTEXTMENU, EV_WM_ENTERIDLE, EV_WM_MOUSEWHEEL, END_RESPONSE_TABLE; /// \class TCommandEnabler /// /// An abstract base class used for automatic enabling and disabling of commands, /// TCommandEnabler is a class from which you can derive other classes, each one /// having its own command enabler. For example, TButtonGadgetEnabler is a derived /// class that's a command enabler for button gadgets, and TMenuItemEnabler is a /// derived class that's a command enabler for menu items. Although your derived /// classes are likely to use only the functions Enable, SetCheck, and GetHandled, /// all of TCommandEnabler's functions are described so that you can better /// understand how ObjectWindows uses command processing. The following paragraphs /// explain the dynamics of command processing. /// /// /// <b>Handling command messages</b> /// /// Commands are messages of the windows WM_COMMAND type that have associated /// command identifiers (for example, CM_FILEMENU). When the user selects an item /// from a menu or a toolbar, when a control sends a notification message to its /// parent window, or when an accelerator keystroke is translated, a WM_COMMAND /// message is sent to a window. /// /// /// <b>Responding to command messages</b> /// /// A command is handled differently depending on which type of command a window /// receives. Menu items and accelerator commands are handled by adding a command /// entry to a message response table using the EV_COMMAND macro. The entry requires /// two arguments: /// - A command identifier (for example, CM_LISTUNDO) /// - A member function (for example, CMEditUndo) /// /// Child ID notifications, messages that a child window sends to its parent window, /// are handling by using one of the notification macros defined in the header file /// windowev.h. /// It is also possible to handle a child ID notification at the child window by /// adding an entry to the child's message response table using the /// EV_NOTIFY_AT_CHILD macro. This entry requires the following arguments: /// - A notification message (for example, LBN_DBLCLK) /// - A member function (for example, CmEditItem) /// /// <b>TWindow command processing</b> /// /// One of the classes designed to handle command processing, TWindow performs basic /// command processing according to these steps: /// - 1. The member function WindowProc calls the virtual member function EvCommand. /// - 2. EvCommand checks to see if the window has requested handling the command by /// looking up the command in the message response table. /// - 3. If the window has requested handling the command identifier by using the /// EV_COMMAND macro, the command is dispatched. /// /// TWindow also handles Child ID notifications at the child window level. /// /// /// <b>TFrameWindow command processing</b> /// /// TFrameWindow provides specialized command processing by overriding its member /// function EvCommand and sending the command down the command chain (that is, the /// chain of windows from the focus window back up to the frame itself, the original /// receiver of the command message). /// /// If no window in the command chain handles the command, TFrameWindow delegates /// the command to the application object. Although this last step is theoretically /// performed by the frame window, it is actually done by TWindow's member function, /// DefaultProcessing(). /// /// /// <b>Invoking EvCommand</b> /// /// When TFrameWindow sends a command down the command chain, it does not directly /// dispatch the command; instead, it invokes the window's EvCommand member /// function. This procedure gives the windows in the command chain the flexibility /// to handle a command by overriding the member function EvCommand instead of being /// limited to handling only the commands requested by the EV_COMMAND macro. /// /// /// <b>Handling command enable messages</b> /// /// Most applications expend considerable energy updating menu items and tool bar /// buttons to provide the necessary feedback indicating that a command has been /// enabled. In order to simplify this procedure, ObjectWindows lets the event /// handler that is going to handle the command make the decision about whether or /// not to enable or disable a command. /// /// Although the WM_COMMAND_ENABLE message is sent down the same command chain as /// the WM_COMMAND event; exactly when the WM_COMMAND_ENABLE message is sent depends /// on the type of command enabling that needs to be processed. /// /// /// <b>Command enabling for menu items</b> /// /// TFrameWindow performs this type of command enabling when it receives a /// WM_INITMENUPOPUP message. It sends this message before a menu list appears. /// ObjectWindows then identifies the menu commands using the command IDs and sends /// requests for the commands to be enabled. /// /// Note that because Object Windows actively maintains toolbars and menu items, any /// changes made to the variables involved in the command enabling functions are /// implemented dynamically and not just when a window is activated. /// /// /// <b>Command enabling for toolbar buttons</b> /// /// This type of command enabling is performed during idle processing (in the /// IdleAction function). The Default Message-Processing Flowchart that accompanies /// TWindow::DefaultProcessing is a graphical illustration of this process. /// /// /// <b>Creating specialized command enablers</b> /// /// Associated with the WM_COMMAND_ENABLE message is an object of the /// TCommandEnabler type. This family of command enablers includes specialized /// command enablers for menu items and toolbar buttons. /// /// As you can see from TCommandEnabler's class declaration, you can do /// considerably more than simply enable or disable a command using the command /// enabler. For example, you have the ability to change the text associated with /// the command as well as the state of the command. /// /// /// <b>Using the EV_COMMAND_ENABLE macro</b> /// /// You can use the EV_COMMAND_ENABLE macro to handle WM_COMMAND_ENABLE messages. /// Just as you do with the EV_COMMAND macro, you specify the command identifier /// that you want to handle and the member function you want to invoke to handle the /// message. /// /// /// <b>Automatically enabling and disabling commands</b> /// /// ObjectWindows simplifies enabling and disabling of commands by automatically /// disabling commands for which there are no associated handlers. TFrameWindow's /// member function EvCommandEnable performs this operation, which involves /// completing a two-pass algorithm: /// - 1. The first pass sends a WM_COMMAND_ENABLE message down the command chain /// giving each window an explicit opportunity to do the command enabling. /// - 2. If no window handles the command enabling request, then ObjectWindows checks /// to see whether any windows in the command chain are going to handle the command /// through any associated EV_COMMAND entries in their response tables. If there is /// a command handler in one of the response tables, then the command is enabled; /// otherwise it is disabled. /// /// Because of this implicit command enabling or disabling, you do not need to (and /// actually should not) do explicit command enabling unless you want to change the /// command text, change the command state, or conditionally enable or disable the /// command. /// /// If you handle commands indirectly by overriding the member function EvCommand /// instead of using the EV_COMMAND macro to add a response table entry, then /// ObjectWindows will not be aware that you are handling the command. Consequently, /// the command may be automatically disabled. Should this occur, the appropriate /// action to take is to also override the member function EvCommandEnable and /// explicitly enable the command. // /// Constructs the TCommandEnabler object with the specified command ID. Sets the /// message responder (hWndReceiver) to zero. // TCommandEnabler::TCommandEnabler(uint id, HWND hReceiver) : Id(id), HWndReceiver(hReceiver) { Flags = 0; } // /// Enables or disables the command sender. When Enable is called, it sets the /// Handled flag. // void TCommandEnabler::Enable(bool) { Flags |= WasHandled; } void TWindow::TraceWindowPlacement() { WINDOWPLACEMENT wp; GetWindowPlacement(&wp); TRACEX(OwlWin,1,"PLACEMENT=" << (TRect&)wp.rcNormalPosition << " Hwnd=" << GetHandle() << "min=" << wp.ptMinPosition.x << " " << wp.ptMinPosition.y); // << " min=" << (TPoint&)wp.ptMinPosition " max=" << (TPoint&)wp.ptMaxPosition); // << " showCmd=" << wp.showCmd << " flags=" << wp.flags); } // /// Adds this to the child list of parent if nonzero, and calls EnableAutoCreate so /// that this will be created and displayed along with parent. Also sets the title /// of the window and initializes the window's creation attributes. /// /// The following paragraphs describe procedures common to both constructor /// syntaxes. module specifies the application or DLL that owns the TWindow /// instance. ObjectWindows needs the correct value of module to find needed /// resources. If module is 0, TWindow sets its module according to the following /// rules: /// - If the window has a parent, the parent's module is used. /// - If the TWindow constructor is invoked from an application, the /// module is set to the application. /// - If the TWindow constructor is invoked from a DLL that is /// dynamically linked with the ObjectWindows DLL and the currently running /// application is linked the same way, the module is set to the currently running /// application. /// - If the TWindow constructor is invoked from a DLL that is /// statically linked with the ObjectWindows library or the invoking DLL is /// dynamically linked with ObjectWindows DLL but the currently running application /// is not, no default is used for setting the module. Instead, a TXInvalidModule /// exception is thrown and the object is not created. // TWindow::TWindow(TWindow* parent, LPCTSTR title, TModule* module) : InstanceProc(0), DefaultProc(0), Handle(0), Title(0), Module(0) { Init(parent, title, module); } // /// String-aware overload // TWindow::TWindow(TWindow* parent, const tstring& title, TModule* module) : InstanceProc(0), DefaultProc(0), Handle(0), Title(0), Module(0) { Init(parent, title, module); } // /// Constructs a TWindow that is used as an alias for a non-ObjectWindows window, /// and sets wfAlias. Because the HWND is already available, this constructor, /// unlike the other TWindow constructor, performs the "thunking" and extraction of /// HWND information instead of waiting until the function Create creates the /// interface element. /// /// The following paragraphs describe procedures common to both constructor /// syntaxes. module specifies the application or DLL that owns the TWindow /// instance. ObjectWindows needs the correct value of module to find needed /// resources. If module is 0, TWindow sets its module according to the following /// rules: /// - If the window has a parent, the parent's module is used. /// - If the TWindow constructor is invoked from an application, the /// module is set to the application. /// - If the TWindow constructor is invoked from a DLL that is /// dynamically linked with the ObjectWindows DLL and the currently running /// application is linked the same way, the module is set to the currently running /// application. /// - If the TWindow constructor is invoked from a DLL that is /// statically linked with the ObjectWindows library or the invoking DLL is /// dynamically linked with ObjectWindows DLL but the currently running application /// is not, no default is used for setting the module. Instead, a TXInvalidModule /// exception is thrown and the object is not created. TWindow::TWindow(HWND handle, TModule* module) : InstanceProc(0), DefaultProc(0), Handle(0), Title(0), Module(0) { PRECONDITION(handle); Init(handle, module); } // /// Protected constructor for use by immediate virtually derived classes. /// Immediate derivitives must call an Init() before constructions are done. // TWindow::TWindow() : InstanceProc(0), DefaultProc(0), Handle(0), Title(0), Module(0) { } // /// Normal initialization of a default constructed TWindow. Is ignored if /// called more than once. // void TWindow::Init(TWindow* parent, LPCTSTR title, TModule* module) { if (!InstanceProc) { SetCaption(title); PerformInit(parent, module); EnableAutoCreate(); // Initialize creation attributes // Attr.Style = WS_CHILD | WS_VISIBLE; Attr.X = Attr.Y = Attr.W = Attr.H = 0; Attr.ExStyle = 0; Attr.Id = 0; } } // /// Wrapper initialization of a default constructed TWindow. Is ignored if /// called more than once. // void TWindow::Init(HWND handle, TModule* module) { PRECONDITION(handle); if (!InstanceProc) { // Perform preliminary initialization // SetHandle(handle); SetCaption(LPCTSTR(0)); // If we've been given a module, then setup that and the app now if // possible so that GetWindowPtr below has some context. Otherwise at least // set it to 0. // Application = TYPESAFE_DOWNCAST(module,TApplication); // If the receiver's parent is an OWL window then pass the window to // PerformInit so the receiver can be added to the parent's list of children. // HWND hParent = GetParentH(); TWindow* parent = hParent ? GetWindowPtr(hParent) : 0; PerformInit(parent, module); // Install the instance window proc. // SubclassWindowFunction(); // Copy over the title, styles, the coordinates & the id // GetWindowTextTitle(); GetHWndState(true); //DLN now we force resysnc of style settings for non-owl windows. // Keep track that this is an alias object & that it is already created // SetFlag(wfAlias | wfFullyCreated); // Unique id may have been set inadvertantly to TWindow by the above // GetWindowTextTitle, et. al. Reset it just in case // SetUniqueId(); } } // // Private initializer function that does the bulk of the work for the // protected Init()s // void TWindow::PerformInit(TWindow* parent, TModule* module) { // Initialize members. // ZOrder = 0; ChildList = 0; Flags = wfDeleteOnClose; TransferBuffer = 0; TransferBufferSize = 0; Parent = parent; Attr.Param = 0; Attr.Menu = 0; Attr.AccelTable = 0; HAccel = 0; Scroller = 0; ContextPopupMenu = 0; Tooltip = 0; CursorModule = 0; CursorResId = 0; HCursor = 0; BkgndColor = TColor::None; // Set the window proc for this window instance. // InstanceProc = CreateInstanceProc(); // Link to parent. // if (Parent) Parent->AddChild(this); else SiblingList = 0; // Use passed module if one, else get parent's. If no parent, use app // if (Parent) { Application = Parent->GetApplication(); Module = module ? module : Parent->GetModule(); } else { Module = module ? module : 0; Application = TYPESAFE_DOWNCAST(Module,TApplication); if (!Application) { //Application = OWLGetAppDictionary().GetApplication(0); Application = GetApplicationObject(); if (!Module) Module = Application; } CHECK(Application); } SetUniqueId(); TRACEX(OwlWin, 1, _T("TWindow constructed @") << (void*)this << *this); } // // Helper function for TWindow destructor. // Shutdowns and deallocates the given window. // static void shutDown(TWindow* win, void*) { win->Destroy(); delete win; } // // Function prototype // void CacheFlush(uint32 id); // /// Destroys a still-associated interface element by calling Destroy. Deletes the /// window objects in the child list, then removes this from the parent window's /// child list. Deletes the Scroller if it is nonzero. Frees the cursor, if any /// exists, and the object instance (thunk). /// Destroys a still-associated Handle and frees the instance window proc used for /// linking the TWindow to the Handle. // TWindow::~TWindow() { // Clean up the instance window proc. // VH: Clean up the instance proc early. // We're in the destructor, we don't want to handle any more messages. // if (GetHandle()) { // // Restore original window proc, or set to default. // WARNX(OwlWin, GetWindowProc() != GetInstanceProc(), 0, _T("Restoring old WndProc after foreign subclass of:") << *this); SetWindowProc(DefaultProc ? DefaultProc : ::DefWindowProc); } FreeInstanceProc(); InstanceProc = 0; // Flush the cache so that messages dont get dispatched to a // already-destructed derived class // owl::CacheFlush(UniqueId); // ShutDown children first, so the Owl objects get a chance to clean up // ForEach(shutDown); // Destroy the window if the handle is still around, and this is not an alias. // if (GetHandle() && !IsFlagSet(wfAlias)) { WARNX(OwlWin, GetHandle(), 0, _T("Destroying from TWindow::~TWindow: ") << *this); Destroy(); } /* // If the Handle is still around, then destroy it or unlink from it as // appropriate. // if (GetHandle()) { // For aliases: // - we are destructing the C++ object but not destroying the MS window // - restore the original window function // if (IsFlagSet(wfAlias)) { // May want to check WNDPROC against InstanceProc to see if its still us // and not restore if it's not us... // WARNX(OwlWin, GetWindowProc() != GetInstanceProc(), 0, _T("Restoring old WndProc after foreign subclass of:") << *this); SetWindowProc(DefaultProc ? DefaultProc : ::DefWindowProc); } // For non-aliases: // - destroy the windows element // this is not a normal condition and is a safety net only // else { WARNX(OwlWin, GetHandle(), 0, _T("Destroying from TWindow::~TWindow: ") << *this); Destroy(); } } */ // Remove from parent's ChildList // if (Parent) Parent->RemoveChild(this); #if 0 // Clear TApplication's member to avoid dangling pointer // ///TH Moved to frame window's destructor // if (IsFlagSet(wfMainWindow)) GetApplication()->MainWindow = 0; #endif // Remove pointer from application's CondemnList // if (Application) Application->Uncondemn(this); // Delete menu id string. // if (Attr.Menu.IsString()) delete[] Attr.Menu.GetString(); // Get rid of our scroller, if any. // SetScroller(0); // Clean up title member // SetCaption(LPCTSTR(0)); // Cleanup cursor // if (HCursor && CursorModule) SetCursor(0, 0); // Clean up context menu object // delete ContextPopupMenu; TRACEX(OwlWin, 1, _T("TWindow destructed @") << (void*)this << *this); } #if defined(BI_MULTI_THREAD_RTL) // /// Cracks and dispatches a TWindow message. The info parameter is the /// event-handling function. The wp and lp parameters are the message parameters the /// dispatcher cracks. /// \note Overrides TEventHandler::Dispatch() to handle multi-thread synchronization // TResult TWindow::Dispatch(TEventInfo& info, TParam1 p1, TParam2 p2) { TApplication::TQueueLock lock(*GetApplication()); return TEventHandler::Dispatch(info, p1, p2); } #endif // /// Called from TApplication::ProcessAppMsg() to give the window an /// opportunity to perform preprocessing of the Windows message /// /// If you return true, further processing of the message is halted /// /// Allows preprocessing of queued messages prior to dispatching. If you override /// this method in a derived class, be sure to call the base class's PreProcessMsg /// because it handles the translation of accelerator keys. // bool TWindow::PreProcessMsg(MSG& msg) { PRECONDITION(GetHandle()); // Check if this message might be worth relaying to the tooltip window // TTooltip* tooltip = GetTooltip(); if (tooltip && tooltip->IsWindow()) { if (msg.hwnd == *this || IsChild(msg.hwnd)) { if (msg.message >= WM_MOUSEFIRST && msg.message <= WM_MOUSELAST) { tooltip->RelayEvent(msg); } } } return HAccel ? ::TranslateAccelerator(GetHandle(), HAccel, &msg) : false; } // /// Called when no messages are waiting to be processed, IdleAction performs idle /// processing as long as true is returned. idleCount specifies the number of times /// idleAction has been called between messages. /// /// Propagate idle action to all children if count==0, and to any children that /// previously said they wanted more time. // bool TWindow::IdleAction(long idleCount) { bool wantMore = false; TWindow* win = GetFirstChild(); if (win) { do { if (idleCount == 0 || win->IsFlagSet(wfPropagateIdle)) { if (win->IdleAction(idleCount)) { win->SetFlag(wfPropagateIdle); wantMore = true; } else { win->ClearFlag(wfPropagateIdle); } } win = win->Next(); } while (win && win != GetFirstChild()); } return wantMore; } // /// Respond to WM_SYSCOLORCHANGE by broadcasting it to all children // void TWindow::EvSysColorChange() { ChildBroadcastMessage(WM_SYSCOLORCHANGE); DefaultProcessing(); } // /// Removes a child window. Uses the ObjectWindows list of objects rather the /// Window's HWND list. // void TWindow::RemoveChild(TWindow* child) { if (child && ChildList) { TWindow* lastChild = ChildList; TWindow* nextChild = lastChild; while (nextChild->SiblingList != lastChild && nextChild->SiblingList != child) { nextChild = nextChild->SiblingList; } if (nextChild->SiblingList == child) { if (nextChild->SiblingList == nextChild) ChildList = 0; else { if (nextChild->SiblingList == ChildList) ChildList = nextChild; nextChild->SiblingList = nextChild->SiblingList->SiblingList; } } } } // /// Sets the parent for the specified window by setting Parent to the specified new /// Parent window object. Removes this window from the child list of the previous /// parent window, if any, and adds this window to the new parent's child list. // void TWindow::SetParent(TWindow* newParent) { if (Parent != newParent) { if (Parent) Parent->RemoveChild(this); SiblingList = 0; Parent = newParent; if (Parent) Parent->AddChild(this); } // Tell Windows about the change too, if appropriate // if (GetHandle() && Parent && GetParentH() != Parent->GetHandle()) { if (newParent) { if (newParent->GetHandle()) ::SetParent(GetHandle(), newParent->GetHandle()); } else ::SetParent(GetHandle(), 0); } } // /// Default behavior for updating document title is to pass it to parent frame /// /// Stores the title of the document (docname). index is the number of the view /// displayed in the document's caption bar. In order to determine what the view /// number should be, SetDocTitle makes two passes: the first pass checks to see if /// there's more than one view, and the second pass, if there is more than one view, /// assigns the next number to the view. If there is only one view, index is 0; /// therefore, the document does not display a view number. When TDocument is /// checking to see if more than one view exists, index is -1. In such cases, only /// the document's title is displayed in the caption bar. /// SetDocTitle returns true if there is more than one view and TDocument displays /// the number of the view passed in index. // bool TWindow::SetDocTitle(LPCTSTR docname, int index) { return Parent ? Parent->SetDocTitle(docname, index) : false; } // /// Sets the scroller object for this window. This window assumes ownership of the /// scroller object, and will delete it when done and on subsequent sets. // void TWindow::SetScroller(TScroller* scroller) { // This temporary variable is needed, because TScroller::~TScroller() calls TWindow::SetScroller(0) TScroller* temp = Scroller; Scroller = scroller; delete temp; } // // Wildcard check used for child id notifications // static bool wildcardCheck(TGenericTableEntry & entry, TEventHandler::TEventInfo& info) { return entry.Id == info.Id && (entry.Msg == UINT_MAX || entry.Msg == info.Msg); } // /// Handles default processing of events, which includes continued processing /// of menu/accelerators commands and enablers, as well as notifications // /// Serves as a general-purpose default processing function that handles a variety /// of messages. After being created and before calling DefaultProcessing, however, /// a window completes the following sequence of events (illustrated in the Default /// Message-Processing Flowchart). /// - If the window is already created, SubclassWindowFunction is used to /// install a thunk in place of the window's current procedure. The previous /// window procedure is saved in DefaultProc. /// - If the window has not been created, InitWndProc is set up as the /// window proc in the class. Then, when the window first receives a message, /// InitWndProc calls GetWindowProc to get the window's thunk (created by the /// constructor by calling CreateInstanceProc). InitWndProc then switches the /// the window procedure to the thunk. /// - After this point, the thunk responds to incoming messages by calling ReceiveMessage /// which calls the virtual function WindowProc to process the message. ObjectWindows uses /// the special registered message GetWindowPtrMsgId to get the this-pointer of an HWND. /// ReceiveMessage responds to this message by returning the this pointer obtained /// from the thunk. /// /// If the incoming message is not a command or command enable message, WindowProc /// immediately searches the window's response table for a matching entry. If the /// incoming message is a command or command enable message, WindowProc calls /// EvCommand or EvCommandEnable. EvCommand and EvCommandEnable begin searching for /// a matching entry in the focus window's response table. If an entry is found, the /// corresponding function is dispatched; otherwise ObjectWindows calls /// DefaultProcessing to finish the recursive walk back up the parent chain, /// searching for a match until the receiving window (the window that initially /// received the message) is reached. At this point, one of the following actions /// occurs: /// - If there is still no match and this is the MainWindow of the /// application, the window searches the application's response table. /// - If there are no matches and this is a command, DefWindowProc is /// called. /// - If this is a CommandEnable message, no further action is taken. /// - If this is not a command, and if a response table entry exists for /// the window, WindowProc dispatches the corresponding EvXxxx function to handle /// the message. /// - If this is the application's MainWindow, and the message is /// designed for the application, the message is forwarded to the application. /// - For any other cases, the window calls DefWindowProc. /// /// The following diagram illustrates this sequence of message-processing events: /// \image html bm282.BMP // TResult TWindow::DefaultProcessing() { TCurrentEvent& currentEvent = GetCurrentEvent(); if (currentEvent.Message == WM_COMMAND_ENABLE) { if (currentEvent.Win != this) { TWindow* receiver = Parent ? Parent : currentEvent.Win; TCommandEnabler& commandEnabler = *(TCommandEnabler*)currentEvent.Param2; TEventInfo eventInfo(WM_COMMAND_ENABLE, commandEnabler.GetId()); if (receiver->Find(eventInfo)) return receiver->Dispatch(eventInfo, 0, currentEvent.Param2); } return 0; } // Handle normal message default processing by routing directly to the // virtual DefWindowProc() for the window. // if (currentEvent.Message != WM_COMMAND && currentEvent.Message != WM_NOTIFY) return DefWindowProc(currentEvent.Message, currentEvent.Param1, currentEvent.Param2); // currentEvent.Message == WM_COMMAND or WM_NOTIFY // uint notifyCode; uint id; HWND hWndCtl; // Get notify code, control id and control handle from packed params. // Unpacking based on message & platform. // if (currentEvent.Message == WM_COMMAND) { notifyCode = HiUint16(currentEvent.Param1); id = LoUint16(currentEvent.Param1); hWndCtl = reinterpret_cast<HWND>(currentEvent.Param2); } else { TNotify& _not = *(TNotify*)currentEvent.Param2; notifyCode = _not.code; id = _not.idFrom; //currentEvent.Param1; // Y.B. In help written -> use not.idFrom. if (_not.code == (uint)TTN_NEEDTEXT && ((TTooltipText*)&_not)->uFlags&TTF_IDISHWND){ id = ::GetDlgCtrlID((HWND)_not.idFrom); } hWndCtl = _not.hwndFrom; } // If all special routing is done, then process the command/notify for this // window // if (currentEvent.Win == this) { // Menu command originally destined for the receiver, defer to the app. // if (hWndCtl == 0) { TEventInfo eventInfo(0, id); TApplication* app = GetApplication(); if (app->Find(eventInfo)) { app->Dispatch(eventInfo, eventInfo.Id); return 0; } WARNX(OwlMsg, notifyCode<=1, 0, _T("Unprocessed WM_COMMAND(id=") << id << _T(")")); } // Originally destined for the receiver and the receiver has called us so // default processing can occur. // Unpack the original parameters and call DefWindowProc() // return DefWindowProc(currentEvent.Message, currentEvent.Param1, currentEvent.Param2); } // Perform special routing for commands and notifications // else { TWindow* receiver; TEqualOperator equal = 0; if (hWndCtl == 0) { // Menu/accelerator/push button // Either give the message to the receiver's parent or the original // receiver of the message // receiver = Parent ? Parent : currentEvent.Win; // "notifyCode" is either 0 or 1 depending on whether this is from an // accelerator; however, we want to explicitly look for a 0... // notifyCode = 0; } else { // Child id notification (either WM_COMMAND or WM_NOTIFY) sent to the // child and the child has called us. // Offer the parent an opportunity to handle the notification // NOTE: use equal function that will do a wildcard search // equal = wildcardCheck; receiver = currentEvent.Win; // The child window identifier shouldn't be 0, but if it is then it will // look like we are searching for a WM_ message with value "notifyCode", // in that case just give up and call DefWindowProc() for the window. // if (receiver->IsFlagSet(wfAlias) || id == 0) return receiver->DefWindowProc(currentEvent.Message, currentEvent.Param1, currentEvent.Param2); } // Now dispatch the command or notification to the receiver window // TEventInfo eventInfo(notifyCode, id); // NOTE: The ResponseTableEntry of handlers which expect an id (e.g. // EV_COMMAND_AND_ID) have a zero in their first field. The // ResponseTableEntry of handlers which expect a notification code // (e.g. EV_CHILD_NOTIFY_AND_CODE and EV_NOTIFY_ALL_CODES) contain // either the notifyCode or UINT_MAX in that field. Hence, we can // dispatch the expected information based on the contents of that // field. // // However, this logic will fail to disambiguate cases where a // notification code is 0. The only standard control with such a // notification is BUTTON /w BN_CLICKED. So for button handlers // expecting the id, you can use EV_COMMAND_AND_ID. For handlers // expecting the notification code, you can use EV_NOTIFY_ALL_CODES, // (*NOT* EV_CHILD_NOTIFY_AND_CODE(Id, BN_CLICKED, xxxx,...)) // if (receiver->Find(eventInfo, equal)) { TParam1 param1 = eventInfo.Entry->NotifyCode ? notifyCode : id; return receiver->Dispatch(eventInfo, param1, currentEvent.Param2); } else return receiver->DefaultProcessing(); } } // /// WindowProc calls EvCommand to handle WM_COMMAND messages. id is the identifier /// of the menu item or control. hWndCtl holds a value that represents the control /// sending the message. If the message is not from a control, it is 0. notifyCode /// holds a value that represents the control's notification message. If the message /// is from an accelerator, notifyCode is 1; if the message is from a menu, /// notifyCode is 0. // TResult TWindow::EvCommand(uint id, HWND hWndCtl, uint notifyCode) { TRACEX(OwlCmd, 1, _T("TWindow::EvCommand - id(") << id << _T("), ctl(") <<\ hex << uint(hWndCtl) << _T("), code(") << notifyCode << _T(")")); TWindow* receiver = this; TEqualOperator equal = 0; // Menu/accelerator // if (hWndCtl == 0) { // "notifyCode" is either 0 or 1 depending on whether this is from an // accelerator; however, we want to explicitly look for a 0 in the tables // notifyCode = 0; } // Child id notification // else { TWindow* child = GetWindowPtr(hWndCtl); if (child) { // Give the child first crack at the event // receiver = child; id = UINT_MAX; // special designator for child Id notifications that are // handled at the child } else { // Offer the parent an opportunity to handle the notification // // NOTE: use equal function that will do a wildcard search // equal = wildcardCheck; // The child window identifier shouldn't be 0, but if it is then it will // look like we are searching for a WM_ message with value "notifyCode" // if (id == 0) return DefaultProcessing(); } } TEventInfo eventInfo(notifyCode, id); // NOTE: The ResponseTableEntry of handlers which expect an id // (e.g. EV_COMMAND_AND_ID) have a zero in their first field. // The ResponseTableEntry of handlers which expect a notification // code (e.g. EV_CHILD_NOTIFY_AND_CODE and EV_NOTIFY_ALL_CODES) // contain either the notifyCode or UINT_MAX in that field. // Hence, we can dispatch the expected information based on the // contents of that field. // // However, this logic will fail to disambiguate cases where // a notification code is 0. The only standard control with // such a notification is BUTTON /w BN_CLICKED. So for button // handlers expecting the id, you can use EV_COMMAND_AND_ID. // For handlers expecting the notification code, you can use // EV_NOTIFY_ALL_CODES. // // Do *NOT* use "EV_CHILD_NOTIFY_AND_CODE(Id, BN_CLICKED, xxxx,...)" // if (receiver->Find(eventInfo, equal)) return receiver->Dispatch(eventInfo, eventInfo.Entry->NotifyCode ? notifyCode : id); else return receiver->DefaultProcessing(); } // /// Handles WM_NOTIFY and subdispatch messages from child controls. This is the /// default message handler for WM_NOTIFY. // !CQ NOTE: similarity between EvCommand child notifies--merge? // TResult TWindow::EvNotify(uint ctlId, TNotify& notifyInfo) { // Intercept requests for tooltip texts and turn the request into // a 'CommandEnabler'. This mechanism allows use the route the request // the same way commands are routed in OWL. Therefore, the object that // handles a command is the object that get's first crack at providing // the tip text for that command. if (notifyInfo.code == (uint)TTN_NEEDTEXT) { TTooltipText& ttText = *(TTooltipText*)&notifyInfo; TTooltipEnabler enabler(ttText, *this); #if defined(__TRACE) || defined(__WARN) tchar text[50]; _stprintf(text, (ttText.uFlags & TTF_IDISHWND) ? _T("Tip for 0x%X not found") : _T("Text for %d not found"), enabler.GetId()); ttText.CopyText(text); //enabler.SetText(text); // Do not call SetText(), it will set Handled!!!! #endif #if 0 HandleMessage(WM_COMMAND_ENABLE, 0, TParam2(&enabler)); return 0; #else //RouteCommandEnable(*this, enabler); RouteCommandEnable(GetParentO() ? GetParentH() : (HWND)*this, enabler); if(enabler.GetHandled())//Y.B. return only if handled return !!!!!!!!!!!!!! return 0; #endif } TWindow* receiver = this; TEqualOperator equal = 0; TWindow* child = GetWindowPtr(notifyInfo.hwndFrom); if (child) { // Give the Owl child first crack at the event // receiver = child; ctlId = UINT_MAX;// special designator for child Id notifications that are // handled at the child // !CQ may need a different value } else { // Offer the parent an opportunity to handle the notification // NOTE: use equal function that will do a wildcard search // equal = wildcardCheck; // The child window identifier shouldn't be 0, but if it is then it will // look like we are searching for a WM_ message with value "notifyCode" // if (ctlId == 0) return DefaultProcessing(); } TEventInfo eventInfo(notifyInfo.code, ctlId); // Pass the "notifyCode" along in case the user wants it... // if (receiver->Find(eventInfo, equal)) return receiver->Dispatch(eventInfo, notifyInfo.code, TParam2(&notifyInfo)); else return receiver->DefaultProcessing(); } // /// Called by WindowProc to handle WM_COMMAND_ENABLE messages, EvCommandEnable calls /// the CmXxxx command-handling function or calls DefaultProcessing to handle the /// incoming message. // void TWindow::EvCommandEnable(TCommandEnabler& commandEnabler) { // code copied from old unix owl (JAM 04-16-01) //DLN test replace of DispatchMsg for CC 5.1 TEventInfo eventInfo(WM_COMMAND_ENABLE,commandEnabler.GetId()); if (Find(eventInfo)) Dispatch(eventInfo,0,TParam2(&commandEnabler)); // DispatchMsg(WM_COMMAND_ENABLE, commandEnabler.Id, 0, TParam2(&commandEnabler)); } // /// Walks the chain of windows from the initial target window to this window. If it /// finds a window to receive the message, RouteCommandEnable dispatches the command /// enabler to that window. hInitCmdTarget is the handle to the initial command /// target window, which can be focus window but does not need to be. ce is a /// reference to the command enabler. /// Other classes use this function to perform particular command enabling tasks: /// For example, TFrameWindow calls RouteCommandEnable to perform the majority of /// its menu command enabling tasks. When it is an embedded window, TOleWindow also /// uses RouteCommandEnable to perform command enabling. /// /// Don't process for windows out of our window tree (esp. other apps) // void TWindow::RouteCommandEnable(HWND hInitCmdTarget, TCommandEnabler& commandEnabler) { // Extra processing for commands & commandEnablers: send the command down the // command chain if we are the original receiver // if (commandEnabler.IsReceiver(*this)) { HWND hCmdTarget = hInitCmdTarget; while (hCmdTarget && hCmdTarget != *this) { TWindow* cmdTarget = GetWindowPtr(hCmdTarget); if (cmdTarget) { cmdTarget->EvCommandEnable(commandEnabler); if (commandEnabler.GetHandled()) return; } hCmdTarget = ::GetParent(hCmdTarget); } } // Always call base handler // TWindow::EvCommandEnable(commandEnabler); // No one explicitly enabled/disabled the command via the enabler, so run up // the command chain checking for any one who is going to handle the command // itself; if not then disable it... // Don't do this for command senders that don't actually generate commands, // like popup menu items. // if (commandEnabler.IsReceiver(*this) && !commandEnabler.GetHandled() && commandEnabler.SendsCommand()) { bool enable = false; TEventInfo eventInfo(0, commandEnabler.GetId()); HWND hCmdTarget = hInitCmdTarget; while (true) { TWindow* cmdTarget = GetWindowPtr(hCmdTarget); if (cmdTarget && cmdTarget->Find(eventInfo)) { enable = true; // command will be handled, leave sender alone break; } if (!hCmdTarget || hCmdTarget == *this) break; hCmdTarget = ::GetParent(hCmdTarget); } if (!enable) { // Check if the app wants to handle it // TEventInfo enableInfo(WM_COMMAND_ENABLE, commandEnabler.GetId()); TApplication* app = GetApplication(); if (app->Find(enableInfo)) { app->Dispatch(enableInfo, 0, TParam2(&commandEnabler)); if (commandEnabler.GetHandled()) return; } enable = app->Find(eventInfo); } commandEnabler.Enable(enable); } } // /// Virtual function provides final default processing for an incoming message /// Calls original window proc that was subclassed, using ::CallWindowProc to /// make sure that registers get setup correctly. // /// Performs default Windows processing and passes the incoming Windows message. You /// usually do not need to call this function directly. Classes such as TMDIFrame /// and TMDIChild override this function to perform specialized default processing. TResult TWindow::DefWindowProc(TMsgId message, TParam1 param1, TParam2 param2) { PRECONDITION(DefaultProc); bool priorException = Application && Application->HasSuspendedException(); TResult result = ::CallWindowProc(DefaultProc, GetHandle(), message, param1, param2); if (!priorException) // Don't rethrow exceptions if we are in a clean-up phase. GetApplication()->ResumeThrow(); return result; } //namespace owl { /// \addtogroup internal /// @{ // // Message cache // static const int msgCacheSize = 31; struct TCacheEntry{ uint32 UniqueId; TGenericTableEntry * Entry; TMsgId Msg; int Delta; // adjustment to "this" pointer //30.05.2007 - Submitted by Frank Rast: Initialization of TCacheEntry data members was missing. TCacheEntry() : UniqueId(0), Entry(0), Msg(0), Delta(0) {} void Set(uint32 uniqueId, TMsgId msg, TGenericTableEntry * entry, int delta = 0) { UniqueId = uniqueId; Entry = entry; Msg = msg; Delta = delta; } bool Hit(TMsgId msg, uint32 uniqueId) {return msg == Msg && uniqueId == UniqueId;} static uint Key(uint32 id, TMsgId msg) {return (uint(id) ^ msg) % msgCacheSize;} }; struct TCacheEntryStr #if defined(BI_MULTI_THREAD_RTL) : public TLocalObject #endif { TCacheEntryStr():Enabled(true) { } ~TCacheEntryStr() { } TCacheEntry Cache[msgCacheSize]; bool Enabled; void CacheFlush(uint32 id); void Set(int index, uint32 uniqueId, TMsgId, TGenericTableEntry * entry, int delta = 0); bool Check(int index, TMsgId, uint32 id); #if defined(BI_MULTI_THREAD_RTL) // TMRSWSection Lock; #endif }; uint32 TWindow::LastUniqueId = 0; static TCacheEntryStr& GetCache() { #if defined(BI_MULTI_THREAD_RTL) static TTlsContainer<TCacheEntryStr> cacheEntry; return cacheEntry.Get(); #else static TCacheEntryStr cacheEntry; return cacheEntry; #endif }; namespace { // // Ensure singleton initialization at start-up (single-threaded, safe). // TCacheEntryStr& InitCacheEntryStr = GetCache(); } #if defined(BI_MULTI_THREAD_RTL) #define LOCKCACHE //TMRSWSection::TLock Lock(GetCache().Lock); #else #define LOCKCACHE #endif // void TCacheEntryStr::CacheFlush(uint32 id) { LOCKCACHE for (int i = 0; i < msgCacheSize; i++) if (Cache[i].UniqueId == id) Cache[i].Msg = 0; } // void TCacheEntryStr::Set(int index, uint32 uniqueId, TMsgId msg, TGenericTableEntry * entry, int delta) { LOCKCACHE Cache[index].Set(uniqueId, msg, entry, delta); } // bool TCacheEntryStr::Check(int index, TMsgId msg, uint32 id) { LOCKCACHE return Enabled && Cache[index].Hit(msg, id); } // void CacheFlush(uint32 id) { GetCache().CacheFlush(id); } /// @} // // If rtti is available, then use it get an id for this window that is unique // on a per-class basis. // // Without rtti, use a per-instance unique id. Less efficient, but safe. // void TWindow::SetUniqueId() { #if defined(OWL_RTTI_MSGCACHE) UniqueId = 0; #else if (++LastUniqueId == 0) { // // numbers wrapped around. disable the cache to be safe... // LastUniqueId = 1; GetCache().Enabled = false; } UniqueId = LastUniqueId; #endif } // /// Dispatches the given message using the response table. Similar to SendMessage /// but goes directly to the OWL window, bypassing the Windows message queue. // TResult TWindow::HandleMessage(TMsgId msg, TParam1 p1, TParam2 p2) { // ReceiveMessage suspends any exception, so we need to rethrow it after the call. // TResult r = ReceiveMessage(Handle, msg, p1, p2); GetApplication()->ResumeThrow(); return r; } // /// First virtual function called to handling incoming messages to a TWindow // /// Processes incoming messages by calling EvCommand to handle WM_COMMAND messages, /// EvCommandEnable to handle WM_COMMAND_ENABLE messages, and dispatching for all /// other messages. // TResult TWindow::WindowProc(TMsgId msg, TParam1 param1, TParam2 param2) { PRECONDITION(GetHandle()); // Should never get here without a handle // Handle WM_COMMAND_ENABLE command enable msgs by directly calling the // virtual EvCommandEnable // if (msg == WM_COMMAND_ENABLE) { TRACEX(OwlMsg, 1, _T("WM_COMMAND_ENABLE") << _T("! => ") << *this); EvCommandEnable(*(TCommandEnabler*)param2); return 0; } // Handle WM_COMMAND command msgs by directly calling the // virtual EvCommand // else if (msg == WM_COMMAND) { TRACEX(OwlMsg, 1, _T("WM_COMMAND, ") << LoUint16(param1) << _T(" ! => ") << *this); return EvCommand(LoUint16(param1), reinterpret_cast<HWND>(param2), HiUint16(param1)); } // Handle WM_NOTIFY msgs by directly calling the virtual EvNotify // !CQ why not use response table dispatch? For above too? // else if (msg == WM_NOTIFY) { // We've received reports of some controls (out there) sending // WM_NOTIFY with a NULL LPARAM !! // TNotify dumbNMHDR; //DLN SET ID to 0 for these NULL LPARAM to avoid bad resource access dumbNMHDR.idFrom = static_cast<UINT>(-1); TNotify* notify = param2 ? (TNotify*)param2 : &dumbNMHDR; TRACEX(OwlMsg, 1, _T("WM_NOTIFY, ") << notify->idFrom << _T(", ")\ << notify->code << _T(", ")\ << hex << uint(notify->hwndFrom) << _T(", ")\ << _T(" ! => ") << *this); return EvNotify(param1, *notify); } // Handle all other messages by looking up and dispatching using the // response tables // else { #if defined(OWL_RTTI_MSGCACHE) if (!UniqueId) UniqueId = TYPE_UNIQUE_UINT32(*this); #endif uint key = TCacheEntry::Key(UniqueId, msg); TEventInfo eventInfo(msg); // Check the cache. A cache hit may be an RT handler, or an RT miss. // TCacheEntryStr& cache = GetCache(); if(cache.Check(key, msg, UniqueId)) { eventInfo.Entry = cache.Cache[key].Entry; if (eventInfo.Entry) { TRACEX(OwlMsg, 1, TMsgName(msg) << _T("* => ") << *this); eventInfo.Object = (TGeneric*)(((char*)this) + cache.Cache[key].Delta); return Dispatch(eventInfo, param1, param2); } // else fall out & do default below } // Perform the lookup on this window. // else if (this->Find(eventInfo)) { TRACEX(OwlMsg, 1, TMsgName(msg) << _T(" => ") << *this); cache.Set(key,UniqueId, msg, eventInfo.Entry, int(eventInfo.Object) - int(this)); return Dispatch(eventInfo, param1, param2); } else // not found cache.Set(key,UniqueId, msg, 0); // Cache no-handler entries too // Behavior for messages that have no handler. If this is the main window, // then give the app a chance to handle the message. If not the main // window, or if the app had no handler, just call DefWindowProc() to // pass the message back to whomever we subclassed // if (IsFlagSet(wfMainWindow)) { TEventInfo cmdEventInfo(msg, param1); if (GetApplication()->Find(cmdEventInfo)) return GetApplication()->Dispatch(cmdEventInfo, param1, param2); if (GetApplication()->Find(eventInfo)) return GetApplication()->Dispatch(eventInfo, param1, param2); } return DefWindowProc(msg, param1, param2); } } #if !defined(BI_COMP_GNUC) #pragma warn -par #endif // /// Handles messages sent to the window. /// May be called directly by the windows message dispatch mechanism, /// or manually via HandleMessage. /// If the message is a GetWindowPtr message, it is handled immediately, /// otherwise the current event is saved and the call forwarded to WindowProc. /// Any unhandled exception in WindowProc is suspended (see TApplication::SuspendThrow). // TResult TWindow::ReceiveMessage(HWND hwnd, TMsgId msg, TParam1 param1, TParam2 param2) throw() { // If it's a "GetWindowPtr" message, then return pointer to this window. // if (msg == GetWindowPtrMsgId && (!param2 || param2 == reinterpret_cast<TParam2>(Application))) return reinterpret_cast<TResult>(this); // Save away the current event to support nested calls. // TCurrentEvent& currentEvent = GetCurrentEvent(); TCurrentEvent saveEvent = currentEvent; currentEvent.Win = this; currentEvent.Message = msg; currentEvent.Param1 = param1; currentEvent.Param2 = param2; // Dispatch the message to the WindowProc virtual function. // Suspend any exception thrown. It will be rethrown in the message loop on the return from // this function. // TResult result = 0; try { PRECONDITIONX(hwnd == Handle, _T("ReceiveMessage: The passed handle does not match this window.")); InUse(hwnd); result = WindowProc(msg, param1, param2); } catch (const TXBase& x) { TRACEX(OwlWin, 0, _T("TWindow::ReceiveMessage: Suspending unhandled TXBase exception for message: ") << msg); GetApplication()->SuspendThrow(x); } catch (const TXEndSession& x) { TRACEX(OwlWin, 0, _T("TDialog::ReceiveMessage: Suspending unhandled TXEndSession for message: ") << msg); GetApplication()->SuspendThrow(x); } catch (const exception& x) { TRACEX(OwlWin, 0, _T("TWindow::ReceiveMessage: Suspending unhandled std::exception for message: ") << msg); GetApplication()->SuspendThrow(x); } catch (...) { TRACEX(OwlWin, 0, _T("TWindow::ReceiveMessage: Suspending unhandled unknown exception for message: ") << msg); GetApplication()->SuspendThrow(); } // Restore the current event; could have been changed by nested calls. // currentEvent = saveEvent; return result; } #if !defined(BI_COMP_GNUC) #pragma warn .par #endif // /// Determine the object pointer by sending a GetWindowPtrMsgId message to the window. /// When TWindow::ReceiveMessage receives this message it returns a pointer to the object. /// If app is non-zero, then the process makes sure that the corresponding /// TWindow is returned. // _OWLFUNC(TWindow*) GetWindowPtr(HWND hWnd, const TApplication* app) { if (!hWnd /* && ::IsWindow(hWnd) */) // Could also check handle validity return 0; TParam2 param2 = TParam2(app); // Avoid SendMessage to cutdown the overhead & message spy tool flooding // // Under Win32 don't even try if it is not our process. Some Win32's will // return a wndProc that crashes. // DWORD processId; ::GetWindowThreadProcessId(hWnd, &processId); if (processId != ::GetCurrentProcessId()) return 0; WNDPROC wndProc = (WNDPROC)::GetWindowLongPtr(hWnd, GWLP_WNDPROC); if (!wndProc) return 0; return (TWindow*)::CallWindowProc(wndProc, hWnd, GetWindowPtrMsgId, 0, param2); } // /// Response method for an incoming WM_CREATE message /// /// Performs setup and data transfer /// now that we are created & have a Handle // int TWindow::EvCreate(CREATESTRUCT &) { PerformSetupAndTransfer(); return (int)DefaultProcessing(); } // /// Responds to a request by a child window to hold its HWND when it is losing /// focus. Stores the child's HWND in HoldFocusHwnd. // /// \note Regular windows never hold focus child handles--just say no. // bool TWindow::HoldFocusHWnd(HWND /*hWndLose*/, HWND /*hWndGain*/) { return false; } // /// Handle WM_KILLFOCUS so that we can have a parent window hold onto our /// Handle and possibly restore focus later. // void TWindow::EvKillFocus(HWND getFocus) { // Follow the parent chain back until a window volunteers to hold our handle // if (IsFlagSet(wfFullyCreated)) { TWindow* holdWin = Parent; while (holdWin && !holdWin->HoldFocusHWnd(GetHandle(), getFocus)) holdWin = holdWin->Parent; } DefaultProcessing(); } // /// Response method for an incoming WM_SIZE message /// /// Saves the normal size of the window in Attr. /// Also calls the SetPageSize() and SetBarRange() methods of the TWindow's /// scroller, if it has been constructed. // void TWindow::EvSize(uint sizeType, const TSize&) { TraceWindowPlacement(); static bool inScroller = false; if (!inScroller && Scroller && sizeType != SIZE_MINIMIZED) { inScroller = true; Scroller->SetPageSize(); Scroller->SetSBarRange(); inScroller = false; } if (sizeType == SIZE_RESTORED) { TRect wndRect; GetWindowRect(wndRect); Attr.W = wndRect.Width(); Attr.H = wndRect.Height(); } // Added Owl functionality: notify parent of a resize in case it wants to // adjust accordingly // if (Parent && !(GetExStyle() & WS_EX_NOPARENTNOTIFY)) Parent->SendMessage(WM_PARENTNOTIFY, WM_SIZE, TParam2(GetHandle())); DefaultProcessing(); } // /// Save the normal position of the window. /// If IsIconic() or IsZoomed() ignore the position since it does not reflect /// the normal state // void TWindow::EvMove(const TPoint&) { if (!IsIconic() && !IsZoomed()) { TRect wndRect; GetWindowRect(wndRect); if ((GetWindowLong(GWL_STYLE) & WS_CHILD) == WS_CHILD && Parent && Parent->GetHandle()) Parent->ScreenToClient(wndRect.TopLeft()); Attr.X = wndRect.left; Attr.Y = wndRect.top; } DefaultProcessing(); } // /// Handles WM_COMPAREITEM message (for owner draw controls) by forwarding /// message to control itself // int TWindow::EvCompareItem(uint /*ctrlId*/, const COMPAREITEMSTRUCT& compareInfo) { TWindow* win = GetWindowPtr(compareInfo.hwndItem); if (win) return win->ForwardMessage(); return DefaultProcessing(); } // /// Handles WM_DELETEITEM message (for owner draw controls) by forwarding /// message to control itself // void TWindow::EvDeleteItem(uint /*ctrlId*/, const DELETEITEMSTRUCT& deleteInfo) { TWindow* win = GetWindowPtr(deleteInfo.hwndItem); if (deleteInfo.hwndItem != GetHandle() && win) win->ForwardMessage(); else DefaultProcessing(); } // /// Handles WM_DRAWITEM message (for owner draw controls & menus) by forwarding /// message to control itself // TDrawItem* ItemData2DrawItem(ULONG_PTR data); void TWindow::EvDrawItem(uint /*ctrlId*/, const DRAWITEMSTRUCT& drawInfo) { if (drawInfo.CtlType == ODT_MENU) { TDrawItem* item = ItemData2DrawItem(drawInfo.itemData); if(item){ DRAWITEMSTRUCT i(drawInfo); // Create copy to support legacy non-const virtual TDrawItem::Draw. item->Draw(i); return; } } else { TWindow* win = GetWindowPtr(drawInfo.hwndItem); if (drawInfo.hwndItem != GetHandle() && win) { win->ForwardMessage(); return; } } DefaultProcessing(); } // /// Handles WM_MEASUREITEM message (for owner draw controls & menus) by /// forwarding message to control itself // void TWindow::EvMeasureItem(uint ctrlId, MEASUREITEMSTRUCT & measureInfo) { if (measureInfo.CtlType == ODT_MENU) { TDrawItem* item = ItemData2DrawItem(measureInfo.itemData); if(item){ item->Measure(measureInfo); return; } } else { HWND hCtl = GetDlgItem(measureInfo.CtlID); // hWnd not in struct, get TWindow* win = GetWindowPtr(hCtl); // If the GetWindowPtr failed, & CreationWindow is non-zero, then this // WM_MEASUREITEM is probably for the ctrl which is not yet subclassed. // Route the message directly to creation window. // NOTE: Msg. may be sent before OWL has had a chance to subclass the ctrl. // if (!win) { TWindow* creationWindow = GetCreationWindow(); if (creationWindow) { if (creationWindow != this) // Don't cause a recursion loop win = creationWindow; } else win = ChildWithId(ctrlId); } if(win){ // 970921 MILI 11 The first WM_MEASUREITEM message for a control may // be is sent before OWL has had any chance to grab the handle for that // control. In that case we use Find+Dispatch instead of SendMessage to // forward the message to the control. if(win->GetHandle()){ // !CQ Handle causes bad behavior on DefWindowProc of control in some cases /// win->HandleMessage(WM_MEASUREITEM, ctrlId, TParam2(&measureInfo)); /// win->ForewardMessage(); win->SendMessage(WM_MEASUREITEM, ctrlId, TParam2(&measureInfo)); return; } else{ TEventInfo eventInfo(WM_MEASUREITEM); if (win->Find(eventInfo)){ win->Dispatch(eventInfo, ctrlId, TParam2(&measureInfo)); return; } } } } DefaultProcessing(); } // /// Processes Win32 control color messages (WM_CTLCOLOR*) by redispatching to the old-style /// handler for the Win16 WM_CTLCOLOR message. // TResult TWindow::EvWin32CtlColor(TParam1 param1, TParam2 param2) { int ctlType = GetCurrentEvent().Message - WM_CTLCOLORMSGBOX; CHECK(ctlType >= CTLCOLOR_MSGBOX && ctlType <= CTLCOLOR_STATIC); TEventInfo eventInfo(WM_CTLCOLOR); if (Find(eventInfo)) { typedef HBRUSH(TGeneric::*CTL_COLOR_PMF)(HDC, HWND, uint); CTL_COLOR_PMF& pmf = (CTL_COLOR_PMF&)(eventInfo.Entry->Pmf); return (TResult)(eventInfo.Object->*pmf)((HDC)param1, (HWND)param2, ctlType); } return DefWindowProc(GetCurrentEvent().Message, param1, param2); } // /// Called by EvHScroll and EvVScroll to dispatch messages from scroll bars. // void TWindow::DispatchScroll(uint scrollCode, uint /*thumbPos*/, HWND hWndCtrl) { if (hWndCtrl) { TWindow* win = GetWindowPtr(hWndCtrl); if (win) win->ForwardMessage(); // Adjust "CurrentEvent" to allow DefaultProcessing to work // uint16 id = (uint16)::GetDlgCtrlID(hWndCtrl); TCurrentEvent& currentEvent = GetCurrentEvent(); currentEvent.Message = WM_COMMAND; currentEvent.Param1 = MkParam1(id, scrollCode); currentEvent.Param2 = TParam2(hWndCtrl); EvCommand(id, hWndCtrl, scrollCode); return; } DefaultProcessing(); } // static bool _owlGotScrollLines = false; // static uint _OwlGetMouseScrollLines() { static uint uCachedScrollLines = 0; // if we've already got it and we're not refreshing, // return what we've already got if(_owlGotScrollLines) return uCachedScrollLines; // see if we can find the mouse window _owlGotScrollLines = true; static uint msgGetScrollLines = 0; static uint16 nRegisteredMessage = 0; if (nRegisteredMessage == 0){ msgGetScrollLines = ::RegisterWindowMessage(MSH_SCROLL_LINES); if (msgGetScrollLines == 0) nRegisteredMessage = 1; // couldn't register! never try again else nRegisteredMessage = 2; // it worked: use it } if (nRegisteredMessage == 2){ HWND hwMouseWheel = FindWindow(MSH_WHEELMODULE_CLASS, MSH_WHEELMODULE_TITLE); if (hwMouseWheel && msgGetScrollLines){ uCachedScrollLines = (uint) ::SendMessage(hwMouseWheel, msgGetScrollLines, 0, 0); return uCachedScrollLines; } } // couldn't use the window -- try system settings uCachedScrollLines = 3; // reasonable default ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &uCachedScrollLines, 0); return uCachedScrollLines; } // /// Respond to MouseWheel event if Scroller exist // bool TWindow::EvMouseWheel(uint modKeys, int zDelta, const TPoint& /*point*/) { // we don't handle anything but scrolling just now if (modKeys & (MK_SHIFT | MK_CONTROL)) return DefaultProcessing(); if (Scroller) { uint uWheelScrollLines = _OwlGetMouseScrollLines(); int scrollCnt; if (uWheelScrollLines == WHEEL_PAGESCROLL) { if (zDelta > 0) scrollCnt = -((int)Scroller->YPage); else scrollCnt = ((int)Scroller->YPage); } else { scrollCnt = ::MulDiv(-zDelta, uWheelScrollLines, WHEEL_DELTA) * (int)Scroller->YLine; } // int scrollCnt = ::MulDiv(-zDelta, uWheelScrollLines, WHEEL_DELTA); // scrollCnt = scrollCnt*(int)Scroller->YLine; // if (scrollCnt == -1 || uWheelScrollLines == WHEEL_PAGESCROLL){ // scrollCnt = (int)Scroller->YPage; // if (zDelta > 0) // scrollCnt = -((int)Scroller->YPage); // } Scroller->ScrollBy(0, scrollCnt); return true; } return DefaultProcessing(); } // /// Response method for an incoming WM_HSCROLL message /// /// If the message is from a scrollbar control, calls DispatchScroll() /// otherwise passes the message to the TWindow's scroller if it has been /// constructed, else calls DefaultProcessing() /// /// Assumes, because of a Windows bug, that if the window has the scrollbar /// style, it will not have scrollbar controls // void TWindow::EvHScroll(uint scrollCode, uint thumbPos, HWND hWndCtl) { if (!(GetWindowLong(GWL_STYLE) & WS_HSCROLL) && !Scroller) { DispatchScroll(scrollCode, thumbPos, hWndCtl); // from scrollbar control } else if (Scroller) { Scroller->HScroll(scrollCode, thumbPos); } else { DefaultProcessing(); } } // /// Response method for an incoming WM_VSCROLL message /// /// If the message is from a scrollbar control, calls DispatchScroll() /// otherwise passes the message to the TWindow's scroller if it has been /// constructed, else calls DefaultProcessing() /// /// Assumes, because of a Windows bug, that if the window has the scrollbar /// style, it will not have scrollbar controls // void TWindow::EvVScroll(uint scrollCode, uint thumbPos, HWND hWndCtl) { if (!(GetWindowLong(GWL_STYLE) & WS_VSCROLL) && !Scroller) DispatchScroll(scrollCode, thumbPos, hWndCtl); else if (Scroller) Scroller->VScroll(scrollCode, thumbPos); else DefaultProcessing(); } // /// Response method for an incoming WM_ERASEBKGND message /// If a background color is set, and is not transparent - paint the background. // bool TWindow::EvEraseBkgnd(HDC hDC) { // If color is set, we'll handle erasing (or doing nothing) here // if (BkgndColor != TColor::None) { // If a color is set, blt out a rectangle of it, else don't erase & let // paint handle background // if (BkgndColor != TColor::Transparent) { TDC dc(hDC); TBrush bkBrush(BkgndColor); dc.SelectObject(bkBrush); dc.SetBkColor(BkgndColor); dc.PatBlt(GetClientRect()); dc.RestoreBrush(); } return true; } // No color set, use default class brush // return (bool)DefaultProcessing(); } // /// Respond to WM_CTLCOLOR if we have a bkgnd color set & pass that to the /// control // HBRUSH TWindow::EvCtlColor(HDC hDC, HWND /*hWndChild*/, uint ctlType) { // If a bkgnd color is set, then setup the hdc's bkcolor and return a // brush for the child to use // if (BkgndColor != TColor::None && BkgndColor != TColor::Transparent && ctlType != CTLCOLOR_EDIT && ctlType != CTLCOLOR_LISTBOX) { ::SetBkColor(hDC, BkgndColor); return TBrush(BkgndColor); // HBRUSH will stay in cache } // No color set, use default windows behavior // return (HBRUSH)DefaultProcessing(); } // /// Response method for an incoming WM_PAINT message /// /// Calls Paint(), performing Windows-required paint setup and cleanup before /// and after. if the TWindow has a TScroller, also calls its BeginView() and /// EndView() methods before and after call to Paint() // void TWindow::EvPaint() { if (IsFlagSet(wfAlias)) DefaultProcessing(); // use application-defined wndproc else { TPaintDC dc(*this); TRect& rect = *(TRect*)&dc.Ps.rcPaint; if (Scroller) Scroller->BeginView(dc, rect); Paint(dc, dc.Ps.fErase, rect); if (Scroller) Scroller->EndView(); } } // /// Repaints the client area (the area you can use for drawing) of a window. Called /// by base classes when responding to a WM_PAINT message, Paint serves as a /// placeholder for derived types that define Paint member functions. Paint is /// called by EvPaint and requested automatically by Windows to redisplay the /// window's contents. dc is the paint display context supplied to text and graphics /// output functions. The supplied reference to the rect structure is the bounding /// rectangle of the area that requires painting. erase indicates whether the /// background needs erasing. // void TWindow::Paint(TDC&, bool /*erase*/, TRect&) { } // /// Response method for an incoming WM_SETCURSOR message /// /// If a cursor has been set for this window, & the mouse is over the /// client area, set the cursor // bool TWindow::EvSetCursor(HWND hWndCursor, uint hitTest, TMsgId /*mouseMsg*/) { if (hWndCursor == GetHandle() && hitTest == HTCLIENT && HCursor) { ::SetCursor(HCursor); return true; } return (bool)DefaultProcessing(); } // /// Response method for an incoming WM_LBUTTONDOWN message /// /// If the TWindow's Scroller has been constructed and if auto-scrolling /// has been requested, captures mouse input, loops until a WM_LBUTTONUP /// message comes in calling the Scroller's AutoScroll method, and then /// releases capture on mouse input. /// Will also break if a WM_MOUSEMOVE comes in without the left button down /// indicating a lost WM_LBUTTONUP // void TWindow::EvLButtonDown(uint /*modKeys*/, const TPoint& /*pt*/) { if (Scroller && Scroller->IsAutoMode()) { MSG loopMsg; loopMsg.message = 0; SetCapture(); while (loopMsg.message != WM_LBUTTONUP && Scroller->IsAutoMode() && (loopMsg.message != WM_MOUSEMOVE || (loopMsg.wParam&MK_LBUTTON))) { if (::PeekMessage(&loopMsg, 0, 0, 0, PM_REMOVE)) { ::TranslateMessage(&loopMsg); ::DispatchMessage(&loopMsg); // Rethrow any exception suspended in the handler, in which case we need to release // the mouse capture. // try { GetApplication()->ResumeThrow(); } catch (...) { ReleaseCapture(); throw; } } Scroller->AutoScroll(); } ReleaseCapture(); } DefaultProcessing(); } //namespace owl { // // // void DoEnableAutoCreate(TWindow* win, void* /*retVal*/) { if (win->GetHandle()) win->EnableAutoCreate(); } //} // OWL namespace // /// Destroys an MS-Windows element associated with the TWindow. // /// First, Destroy calls EnableAutoCreate for each window in the child list to /// ensure that windows in the child list will be re-created if this is re-created. /// Then, it destroys the associated interface element. /// If a derived window class expects to be destructed directly, it should call /// Destroy as the first step in its destruction so that any virtual functions and /// event handlers can be called during the destroy sequence. // void TWindow::Destroy(int ret) { if (GetHandle()) { ForEach(DoEnableAutoCreate, 0); if (IsFlagSet(wfModalWindow)) { GetApplication()->EndModal(ret); ClearFlag(wfModalWindow); if (Parent && Parent->GetHandle()) Parent->SetFocus(); } // For aliases: // - we are destructing the C++ object but not destroying the MS window // - restore the original window function // if (!IsFlagSet(wfAlias)) { if (::DestroyWindow(GetHandle())) SetHandle(0); } GetApplication()->ResumeThrow(); WARNX(OwlWin, GetHandle(), 0, _T("::DestroyWindow(") << (uint)GetHandle() << _T(") failed")); } } // /// Redefined by derived classes, GetWindowClass fills the supplied MS-Windows /// registration class structure with registration attributes, thus, allowing /// instances of TWindow to be registered. This function, along with GetClassName, /// allows Windows classes to be used for the specified ObjectWindows class and its /// derivatives. It sets the fields of the passed WNDCLASS parameter to the default /// attributes appropriate for a TWindow. The fields and their default attributes /// for the class are the following: /// - \c \b cbClsExtra 0 (the number of extra bytes to reserve after the Window class /// structure). This value is not used by ObjectWindows. /// - \c \b cbWndExtra 0 (the number of extra bytes to reserve after the Window instance). /// This value is not used by ObjectWindows. /// - \c \b hInstance The instance of the class in which the window procedure exists /// - \c \b hIcon 0 (Provides a handle to the class resource.) By default, the application /// must create an icon if the application's window is minimized. /// - \c \b hCursor IDC_ARROW (provides a handle to a cursor resource) /// - \c \b hbrBackground COLOR_WINDOW + 1 (the system background color) /// - \c \b lpszMenuName 0 (Points to a string that contains the name of the class's menu.) /// By default, the windows in this class have no assigned menus. /// - \c \b lpszClassName Points to a string that contains the name of the window class. /// - \c \b lpfnWndProc The address of the window procedure. This value is not used by /// ObjectWindows. /// - \c \b style Style field. /// /// The style field can contain one or more of the following values: /// - \c \b CS_BYTEALIGNCLIENT Aligns the window's client on a byte boundary in the x /// direction. This alignment, designed to improve performance, determines the width /// and horizontal position of the window. /// - \c \b CS_BYTEALIGNWINDOW Aligns a window on a byte boundary in the x direction. This /// alignment, designed to improve performance, determines the width and horizontal /// position of the window. /// - \c \b CS_CLASSDC Allocates a single device context (DC) that's going to be shared by /// all of the window in the class. This style controls how multi-threaded /// applications that have windows belonging to the same class share the same DC. /// - \c \b CS_DBLCLKS Sends a double-click mouse message to the window procedure when the /// mouse is double-clicked on a window belonging to this class. /// - \c \b CS_GLOBALCLASS Allows an application to create a window class regardless of the /// instance parameter. You can also create a global class by writing a DLL that /// contains the window class. /// - \c \b CS_HREDRAW If the size of the window changes as a result of some movement or /// resizing, redraws the entire window. /// - \c \b CS_NOCLOSE Disables the Close option on this window's system menu. /// - \c \b CS_OWNDC Enables each window in the class to have a different DC. /// - \c \b CS_PARENTDC Passes the parent window's DC to the child windows. /// - \c \b CS_SAVEBITS Saves the section of the screen as a bitmap if the screen is covered /// by another window. This bitmap is later used to recreate the window when it is /// no longer obscured by another window. /// - \c \b CS_VREDRAW If the height of the client area is changed, redraws the entire /// window. /// /// After the Windows class structure has been filled with default values by the /// base class, you can override this function to change the values of the Windows /// class structure. For example, you might want to change the window's colors or /// the cursor displayed. /// /// Register unique classes for windows that want system background colors so /// that full-drag erasing uses the right color (NT fails to let window erase /// itself) /// void TWindow::GetWindowClass(WNDCLASS& wndClass) { wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = *GetModule(); wndClass.hIcon = 0; wndClass.hCursor = ::LoadCursor(0, IDC_ARROW); if (BkgndColor.IsSysColor() && BkgndColor != TColor::None && BkgndColor != TColor::Transparent) wndClass.hbrBackground = HBRUSH(BkgndColor.Index()+1); else wndClass.hbrBackground = HBRUSH(COLOR_WINDOW+1); wndClass.lpszMenuName = 0; wndClass.lpszClassName = GetClassName(); wndClass.style = CS_DBLCLKS; wndClass.lpfnWndProc = InitWndProc; } // // Return the classname for a generic owl window. Assume instance private class // registration so that no instance mangling is needed. // // Register unique classnames for windows that want system background colors // TWindow::TGetClassNameReturnType TWindow::GetClassName() { static const tchar baseClassName[] = _T("OWL_Window"); if (BkgndColor.IsSysColor() && BkgndColor != TColor::None && BkgndColor != TColor::Transparent) { static tchar namebuff[COUNTOF(baseClassName) + 1 + 10 + 1 + 4]; // ?? How was this formula calculated _stprintf(namebuff, _T("%s:%X"), baseClassName, BkgndColor.Index()); // !CQ could hash in classStyle too. return namebuff; } return (TGetClassNameReturnType)baseClassName; // cast for old non-const type } // // Set this window's accelerator table, performing the load also if this window // is already created // void TWindow::SetAcceleratorTable(TResId resId) { Attr.AccelTable = resId; if (GetHandle()) LoadAcceleratorTable(); else HAccel = 0; } // /// Loads a handle to the window's accelerator table specified in the TWindowAttr /// structure (Attr.AccelTable). If the accelerator does not exist, /// LoadAcceleratorTable produces an "Unable to load accelerator table" diagnostic /// message. // void TWindow::LoadAcceleratorTable() { if (Attr.AccelTable) { HAccel = LoadAccelerators(Attr.AccelTable); WARNX(OwlWin, !HAccel, 0, _T("Unable to load accelerators ") << Attr.AccelTable << _T(" from ") << *GetModule()); } } // /// Utility function for either setting the passed handle or to just returning it, /// depending on build mode. See definition of TPerformCreateReturnType. /// This function is used by implementations of PerformCreate to write uniform /// code whatever the build mode. // TWindow::TPerformCreateReturnType TWindow::SetOrReturnHandle(THandle handle) { #if OWL_STRICT return handle; #else SetHandle(handle); #endif } // // Helper used by Create and PerformCreate to make a menu-or-id union parameter // for CreateWindowEx; see Windows SDK documentation. // HMENU TWindow::MakeMenuOrId() { PRECONDITION(GetModule()); HMENU m = (Attr.Menu ? LoadMenu(Attr.Menu) : reinterpret_cast<HMENU>(Attr.Id)); WARNX(OwlWin, Attr.Menu && !m, 0, _T("Unable to load menu: ") << Attr.Menu << _T(" from ") << *GetModule()); return m; } // /// Called from Create to perform the final step in creating an Windows interface /// element to be associated with a TWindow. PerformCreate can be overridden to /// provide alternate implementations. /// /// In strict mode we ignore the argument passed, and we build the menu-or-id /// parameter to CreateWindowEx purely based on TWindow data members. In old /// mode we treat the argument like before and assume that it is already a /// composed menu-or-id union. In case it represents a menu, we take ownership /// of the allocated menu (which should have been created by the caller). // TWindow::TPerformCreateReturnType TWindow::PerformCreate(int arg) { PRECONDITIONX(!(OWL_STRICT && arg), _T("The deprecated argument to PerformCreate is disallowed.")); InUse(arg); PRECONDITION(GetModule()); // // Use RAII to ensure the menu is released in case of failure. // struct TMenuGuard { HMENU m; bool is_mine; TMenuGuard(HMENU m_, bool is_mine_) : m(m_), is_mine(is_mine_) {} ~TMenuGuard() {if (is_mine) DestroyMenu(m);} operator HMENU() {return m;} HMENU RelinquishOwnership() {is_mine = false; return m;} } menuOrId(OWL_STRICT ? MakeMenuOrId() : reinterpret_cast<HMENU>(arg), Attr.Menu != 0); THandle h = CreateWindowEx( Attr.ExStyle, GetClassName(), Title, Attr.Style, Attr.X, Attr.Y, Attr.W, Attr.H, Parent ? Parent->GetHandle() : 0, menuOrId, *GetModule(), Attr.Param ); if (h) menuOrId.RelinquishOwnership(); // The menu belongs to the window now. OWL_SET_OR_RETURN_HANDLE(h); } // /// Creates the window interface element to be associated with this ObjectWindows /// interface element. Specifically, Create performs the following window creation /// tasks: /// - 1. If the HWND already exists, Create returns true. (It is perfectly valid to /// call Create even if the window currently exists.) /// - 2. If the wfFromResource flag is set, then Create grabs the HWND based on the /// window ID. Otherwise, Create registers the window, sets up the window thunk, /// loads accelerators and menus, and calls PerformCreate in the derived class to /// create the HWND. /// - 3. If class registration fails for the window, Create calls TXWindow with /// IDS_CLASSREGISTERFAIL. If the window creation fails, Create calls TXWindow with /// IDS_WINDOWCREATEFAIL. /// - 4. If the window is created for a predefined Window class (for example, a /// button or dialog class) registered outside of ObjectWindows, then ObjectWindows /// thunks the window so that it can intercept messages and obtains the state of the /// window (the window's attributes) from the HWND. /// /// \note Since this member function now throws an exception on error, it always /// returns true. // bool TWindow::Create() { if (GetHandle()) return true; DisableAutoCreate(); // If this is the main window, make sure it is treated as one by the shell. // if (IsFlagSet(wfMainWindow)) ModifyExStyle(0, WS_EX_APPWINDOW); if (IsFlagSet(wfFromResource)) SetHandle(Parent ? Parent->GetDlgItem(Attr.Id) : 0); // Windows already created it. else { // Make sure the window class is registered. // if (!Register()) TXWindow::Raise(this, IDS_CLASSREGISTERFAIL); // Perform necessary steps to create the window and attach the window procedure. // SetCreationWindow(this); LoadAcceleratorTable(); CHECK(!GetHandle()); // Ensure handle is NULL in case of exceptions. #if OWL_STRICT // In strict API mode, the argument til PerformCreate is no longer used. // Also PerformCreate now returns the handle instead of calling SetHandle, hence // we must do the latter here. // SetHandle(PerformCreate()); #else // In non-strict API mode (compatibility mode) we simulate the old behaviour and // construct the argument to PerformCreate as before. In non-strict mode // PerformCreate has the responsibility of calling SetHandle. // int menuOrId = reinterpret_cast<int>(MakeMenuOrId()); PerformCreate(menuOrId); #endif GetApplication()->ResumeThrow(); WARNX(OwlWin, !GetHandle(), 0, _T("PerformCreate failed: ") << _T("Class: \"") << tstring(GetClassName()).c_str() << _T("\", ") << _T("Title: \"") << tstring(Title).c_str() << _T("\", ") << _T("Style: ") << Attr.Style << _T(", ") << _T("Parent: ") << (Parent ? uint(Parent->GetHandle()) : 0) << _T(", ") << _T("Module: \"") << GetModule()->GetModuleFileName()); if (!GetHandle()) TXWindow::Raise(this, IDS_WINDOWCREATEFAIL); } // Here we deal with non-subclassed handles. This may be caused by two scenarios: // // 1. Predefined window class (non-owl) windows. // 2. OWL controls which were created from resource [Although these // are registered with InitWndProc, they did not get subclassed since // 'CreationWindow' was not set when they received their first messages]. // if (!GetWindowPtr(GetHandle())) { // If we have a title, then overwrite the current window text, if any. // Otherwise sync the title with the current window text. // if (Title) SetCaption(Title); else GetWindowTextTitle(); // Grab the state info. // GetHWndState(); // If it's a 'predefinedClass' window, subclass it. // if (GetWindowProc() != InitWndProc) { SubclassWindowFunction(); // Reset the 'CreationWindow' pointer [if necessary]. // if (GetCreationWindow() == this) SetCreationWindow(0); // Set status flag [since we missed EvCreate]. // SetFlag(wfPredefinedClass); } else { // This window's WNDPROC is 'InitWndProc' - However, it has not // been subclassed since 'CreationWindow' was not set when it received // its first messages [it was probably created from a resource but // registered by OWL]. We'll set 'CreationWindow' and send a dummy // message to allow subclassing to take place. // if (!GetCreationWindow()) SetCreationWindow(this); SendMessage(WM_USER+0x4000, 0, 0); } // Perform setup and transfer now, since 'EvCreate' was missed earlier. // PerformSetupAndTransfer(); } return true; } // /// Creates the underlying HWND and makes it modal with the help of TApplication's /// BeginModal support. // int TWindow::Execute() { return DoExecute(); } // /// Do actual modal execution using the Begin/End Modal support of TApplication. /// \note Defaults to 'TASKMODAL'. // int TWindow::DoExecute() { // Attempting to go modal when one's a child is indicative of // suicidal tendencies!! // PRECONDITION((GetStyle() & WS_CHILD) == 0); if (GetApplication()) { if (Create()) { SetFlag(wfModalWindow); return GetApplication()->BeginModal(this, MB_TASKMODAL); } } return -1; } // /// Ensures that the window is fully set up; then transfers data into the window. // void TWindow::PerformSetupAndTransfer() { SetupWindow(); SetFlag(wfFullyCreated); // Note that transfer has already happened in SetupWindow if the library is // built in backwards compatibility mode. See SetupWindow for details. // #if !defined(OWL5_COMPAT) TransferData(tdSetData); #endif } // /// Performs setup following creation of an associated MS-Windows window. /// /// The first virtual function called when the HWindow becomes valid. TWindow's /// implementation performs window setup by iterating through the child list, /// attempting to create an associated interface element for each child window /// object for which autocreation is enabled. (By default, autocreation is enabled /// for windows and controls, and disabled for dialog boxes.) /// If a child window cannot be created, SetupWindow calls TXWindow /// with an IDS_CHILDCREATEFAIL message. /// /// If the receiver has a TScroller object, calls the scroller's SetBarRange() /// method. /// /// SetupWindow can be redefined in derived classes to perform additional special /// initialization. Note that the HWindow is valid when the overridden SetupWindow /// is called, and that the children's HWindows are valid after calling the base /// classes' SetupWindow function. /// /// The following example from the sample program, APPWIN.CPP, illustrates the use /// of an overridden SetupWindow to setup a window, initialize .INI entries, and /// tell Windows that we want to accept drag and drop transactions: /// \code /// void TAppWindow::SetupWindow() /// { /// TFloatingFrame::SetupWindow(); /// InitEntries(); // Initialize .INI entries. /// RestoreFromINIFile(); // from APPLAUNC.INI in the startup directory /// UpdateAppButtons(); /// DragAcceptFiles(true); /// } /// \endcode // void TWindow::SetupWindow() { TRACEX(OwlWin, 1, _T("TWindow::SetupWindow() @") << (void*)this << *this); // Update scrollbar - if a scroller was attached to the window // if (Scroller){ Scroller->SetWindow(this); Scroller->SetSBarRange(); } // If this is main Window and GetAplication()->GetTooltip() != 0; create it. if (IsFlagSet(wfMainWindow)){ TTooltip* tooltip = GetApplication()->GetTooltip(); if(tooltip){ if(!tooltip->GetParentO()) tooltip->SetParent(this); if(!tooltip->GetHandle()){ // Make sure tooltip is disabled so it does not take input focus tooltip->ModifyStyle(0,WS_DISABLED); tooltip->Create(); } } } // NOTE: CreateChildren will throw a TXWindow exception if one of the // child objects could not be created. // CreateChildren(); // Transfer data here for legacy compatibility. // Note that this may be before any setup in a derived class has completed, // if that class overrides SetupWindow by calling this base version first, // as is the usual idiom. This problem has now been fixed, and TransferData // is now normally called from PerformSetupAndTransfer, thus ensuring that setup // has been fully completed before transfer. But we retain the old behaviour // here for compatibility modes to support legacy applications. // #if defined(OWL5_COMPAT) TransferData(tdSetData); #endif } // /// Always called immediately before the HWindow becomes invalid, CleanupWindow /// gives derived classes an opportunity to clean up HWND related resources. This /// function is the complement to SetupWindow. /// /// Override this function in your derived class to handle window cleanup. Derived /// classes should call the base class's version of CleanupWindow as the last step /// before returning. The following example from the sample program, APPWIN.CPP, /// illustrates this process: /// \code /// //Tell windows that we are not accepting drag and drop transactions any more and /// //perform other window cleanup. /// void /// TAppWindow::CleanupWindow() /// { /// AppLauncherCleanup(); /// DragAcceptFiles(false); /// TWindow::CleanupWindow(); /// } /// \endcode // void TWindow::CleanupWindow() { TRACEX(OwlWin, 1, _T("TWindow::CleanupWindow() @") << (void*)this << *this); } // // Transfer window 'data' to/from the passed data buffer. Used to initialize // windows and get data in or out of them. // // The direction passed specifies whether data is to be read from or written // to the passed buffer, or whether the data element size is simply to be // returned // // The return value is the size (in bytes) of the transfer data. this method // recursively calls transfer on all its children that have wfTransfer set. // #include <pshpack1.h> struct TTransferIterInfo { void* Data; TTransferDirection Direction; }; #include <poppack.h> static void transferDatchild(TWindow* child, TTransferIterInfo* info) { if (child->IsFlagSet(wfTransfer)) info->Data = (char*)info->Data + child->Transfer(info->Data, info->Direction); } // /// Transfers data to or from any window with or without children and returns the /// total size of the data transferred. Transfer is a general mechanism for data /// transfer that can be used with or without using TransferData. The direction /// supplied specifies whether data is to be read from or written to the supplied /// buffer, or whether the size of the transfer data is simply to be returned. Data /// is not transferred to or from any child windows whose wfTransfer flag is not /// set. The return value is the size (in bytes) of the transfer data. // uint TWindow::Transfer(void* buffer, TTransferDirection direction) { if (buffer) { TTransferIterInfo info = { buffer, direction }; ForEach((TActionFunc)transferDatchild, &info); return (char*)info.Data - (char*)buffer; } return 0; } // /// Transfers data between the TWindow's data buffer and the child /// windows in its ChildList (data is not transfered between any child /// windows whose wfTransfer flag is not set) /// /// A window usually calls TransferData during setup and closing of windows and /// relies on the constructor to set TransferBuffer to something meaningful. /// TransferData calls the Transfer member function of each participating child /// window, passing a pointer to TransferBuffer as well as the direction specified /// in direction (tdSetData, tdGetData, or tdSizeData). // void TWindow::TransferData(TTransferDirection direction) { if (!TransferBuffer) return; // nothing to do uint size = Transfer(TransferBuffer, tdSizeData); if (direction == tdSizeData) return; // done if (TransferBufferSize > 0 && size != TransferBufferSize) TXWindow::Raise(this, IDS_TRANSFERBUFFERSIZEMISMATCH); WARN(TransferBufferSize == 0, _T("TWindow::TransferData: Unsafe transfer is performed! ") _T("Use one of the safe overloads of SetTransferBuffer to enable buffer checks.")); Transfer(TransferBuffer, direction); } // // Checks whether the given HWND belongs to this process. // Internal function. // inline static bool BelongsToCurrentProcess (HWND h) { DWORD processId = 0; ::GetWindowThreadProcessId(h, &processId); return processId == ::GetCurrentProcessId(); } // /// Installs the instance thunk as the WindowProc and saves the old window function /// in DefaultProc. // void TWindow::SubclassWindowFunction() { PRECONDITION(GetHandle()); PRECONDITION(GetInstanceProc()); if (!BelongsToCurrentProcess(GetHandle())) return; // If the window already has the window proc we want, // then just ensure that it has a default proc and return. // if (GetInstanceProc() == GetWindowProc()) { if (!DefaultProc) DefaultProc = ::DefWindowProc; return; } // Initialize the instance proc and install it. // InitInstanceProc(); DefaultProc = SetWindowProc(GetInstanceProc()); } // /// Registers the Windows registration class of this window, if this window is not /// already registered. Calls GetClassName and GetWindowClass to retrieve the /// Windows registration class name and attributes of this window. Register returns /// true if this window is registered. // bool TWindow::Register() { WNDCLASS windowClass; // If the wndclass is not yet registered, call GetWindowClass() to let our // derived class fill in the appropriate info. If the class is still then not // registered, then make it so. // if (!GetModule()->GetClassInfo(GetClassName(), &windowClass)) { GetWindowClass(windowClass); WNDCLASS dummy; if (!GetModule()->GetClassInfo(GetClassName(), &dummy)) return ::RegisterClass(&windowClass); } return true; } // /// Use this function to determine if it is okay to close a window. Returns true if /// the associated interface element can be closed. Calls the CanClose member /// function of each of its child windows. Returns false if any of the CanClose /// calls returns false. /// In your application's main window, you can override TWindow's CanClose and call /// TWindow::MessageBox to display a YESNOCANCEL message prompting the user as /// follows: /// - \c \b YES Save the data /// - \c \b NO Do not save the data, but close the window /// - \c \b CANCEL Cancel the close operation and return to the edit window /// /// The following example shows how to write a CanClose function that displays a /// message box asking if the user wants to save a drawing that has changed. To save /// time, CanClose uses the IsDirty flag to see if the drawing has changed. If so, /// CanClose queries the user before closing the window. /// \code /// bool TMyWindow::CanClose() /// { /// if (IsDirty) /// switch(MessageBox("Do you want to save?", "Drawing has changed.", /// MB_YESNOCANCEL | MB_ICONQUESTION)) { /// case IDCANCEL: /// // Choosing Cancel means to abort the close -- return false. /// return false; /// /// case IDYES: /// // Choosing Yes means to save the drawing. /// CmFileSave(); /// } /// return true; /// } /// \endcode // bool TWindow::CanClose() { struct TLocal { static bool Compare(TWindow* w, void*) {return w->GetHandle() && !w->CanClose();} }; return !FirstThat(&TLocal::Compare); } // /// Determines if it is okay to close a window before actually closing the window. /// If this is the main window of the application, calls GetApplication->CanClose. /// Otherwise, calls this->CanClose to determine whether the window can be closed. /// After determining that it is okay to close the window, CloseWindow calls Destroy /// to destroy the HWND. // void TWindow::CloseWindow(int retVal) { bool willClose; if (IsFlagSet(wfMainWindow)) willClose = GetApplication()->CanClose(); else willClose = CanClose(); if (willClose) Destroy(retVal); } // /// The default response to a WM_CLOSE message is to call CloseWindow() /// and then have the window deleted if the Handle was really destroyed. // void TWindow::EvClose() { if (IsFlagSet(wfAlias)) DefaultProcessing(); else { CloseWindow(); if (!GetHandle() && IsFlagSet(wfDeleteOnClose)) GetApplication()->Condemn(this); // Assumes delete } } // /// Responds to an incoming WM_DESTROY message /// /// Calls CleanupWindow() to let derived classes cleanup /// Clears the wfFullyCreated flag since this window is no longer fully created /// /// If the TWindow is the application's main window posts a 'quit' message to /// end the application, unless already in ~TApplication() (MainWindow == 0) // void TWindow::EvDestroy() { ClearFlag(wfFullyCreated); CleanupWindow(); if (!IsFlagSet(wfAlias)) { if (IsFlagSet(wfMainWindow) && GetApplication()->IsRunning()) ::PostQuitMessage(0); } DefaultProcessing(); } // /// Responds to an incoming WM_NCDESTROY message, the last message /// sent to an MS-Windows interface element /// /// Sets the Handle data member of the TWindow to zero to indicate that an /// interface element is no longer associated with the object // void TWindow::EvNCDestroy() { DefaultProcessing(); SetHandle(0); } // /// Respond to Windows attempt to close down. Determines if this app or window /// is ready to close. // bool TWindow::EvQueryEndSession(uint /*flags*/) { if (IsFlagSet(wfAlias)) return (bool)DefaultProcessing(); else if (IsFlagSet(wfMainWindow)) return GetApplication()->CanClose(); else return CanClose(); } // /// Provides default handling for WM_ENDSESSION. /// If the session is ending, throws the exception TXEndSession, thus shutting down the /// entire applicaton. // void TWindow::EvEndSession(bool endSession, uint /*flags*/) { if (endSession) throw TXEndSession(); else DefaultProcessing(); } // /// Handle message posted to us by a control needing assistance in dealing with /// invalid inputs /// /// Responds to a WM_CHILDINVALID message posted by a child edit control. Indicates /// that the contents of the child window are invalid. // void TWindow::EvChildInvalid(HWND handle) { PRECONDITION(handle); ::SendMessage(handle, WM_CHILDINVALID, 0, 0); } //---------------------------------------------------------------------------- // Non-virtuals // void TWindow::AttachHandle(HWND handle) { ClearFlag(wfDetached); FreeInstanceProc(); InstanceProc = 0; Init(handle, GetModule()); } void TWindow::DetachHandle() { // NOTE: This is by no means a complete way of detaching the window... // The following is logic allows Delphi/OWL interaction.. // ClearFlag(wfFullyCreated); SetHandle(0); SetFlag(wfDetached); } // /// Returns the number of child windows of the window. // unsigned TWindow::NumChildren() const { return IndexOf(ChildList) + 1; } // // Walks over children and assigns a z-order index to the ZOrder member // void TWindow::AssignZOrder() { TWindow* wnd; HWND curWindow = GetHandle(); if (curWindow) { curWindow = ::GetWindow(curWindow, GW_CHILD); if (curWindow) { int i = 1; for (curWindow = ::GetWindow(curWindow, GW_HWNDLAST); curWindow; curWindow = ::GetWindow(curWindow, GW_HWNDPREV)) { wnd = GetWindowPtr(curWindow); if (wnd) wnd->ZOrder = (uint16)i++; } } } } // // The private field ZOrder is used to ensure the Z-order is // consistent through read and write of the object. // // When the object is written, parent->AssignZOrder will fill in this value // // ZOrder ranges from 1 to N where N is the number of objects and the top one. // A ZOrder value of 0 means that the Z-ordering has not be recoreded. // bool TWindow::OrderIsI(TWindow* win, void* position) { return win->ZOrder == *(int*)position; } // /// Creates the child windows in the child list whose auto-create flags (with /// wfAutoCreate mask) are set. If all of the child windows are created /// successfully, CreateChildren returns true. /// \note Throws an exception (TXWindow) if a child object could not be /// created. // bool TWindow::CreateChildren() { struct TLocal { // // Returns true if the child was supposed to be created but couldn't be. // static bool Create(TWindow* win, void*) { // If child is already created, then no need to re-create it. // if (win->GetHandle()) return false; bool autoCreate = win->IsFlagSet(owl::wfAutoCreate); WARNX(OwlWin, !autoCreate, 0, _T("Child window(Id=") << win->GetId() << _T(") not autocreated")); if (!autoCreate) return false; // This call will only fail if a user-defined Create returns false. // OWLNext's Create-implementations always throw exceptions. // if (!win->Create()) return true; // Get & set the window text for the child if it is iconic. // TODO: Review if this hack is still necessary. // if (win->IsIconic()) win->SetWindowText(win->GetWindowText()); return false; } }; // Create children first to restore creation order // TWindow* childFailed = FirstThat(&TLocal::Create); if (childFailed) TXWindow::Raise(childFailed, IDS_CHILDCREATEFAIL); // Restore Z-ordering for children that have Z-ordering recorded // HWND above = HWND_TOP; for (int top = NumChildren(); top; top--) { TWindow* wnd = FirstThat(&TWindow::OrderIsI, &top); if (wnd) { wnd->SetWindowPos(above, 0,0,0,0, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOSIZE); above = wnd->GetHandle(); } } return true; } // // adds the passed pointer to a child window to the linked list // of sibling windows which ChildList points to // void TWindow::AddChild(TWindow* child) { if (child) if (ChildList) { child->SiblingList = ChildList->SiblingList; ChildList->SiblingList = child; ChildList = child; } else { ChildList = child; child->SiblingList = child; } } // /// Returns a pointer to the TWindow's previous sibling (the window previous to /// the TWindow in its parent's child window list) /// /// If the TWindow was the first child added to the list, returns a pointer to /// the last child added // TWindow* TWindow::Previous() { if (!SiblingList) { return 0; } else { TWindow* CurrentIndex = this; while (CurrentIndex->Next() != this) CurrentIndex = CurrentIndex->Next(); return CurrentIndex; } } // /// Returns a pointer to the first TWindow in the ChildList that meets some /// specified criteria /// /// If no child in the list meets the criteria, 0 is returned /// /// The Test parameter which defines the criteria, is a pointer to a /// function that takes a TWindow pointer & a pointer to void /// /// The TWindow* will be used as the pointer to the child window and /// the void* as a pointer to the Test function's additional parameters /// /// The Test function must return a Boolean value indicating whether the /// child passed meets the criteria /// /// In the following example, GetFirstChecked calls FirstThat to obtain a pointer /// (p) to the first check box in the child list that is checked: /// \code /// bool IsThisBoxChecked(TWindow* p, void*) { /// return ((TCheckBox*)p)->GetCheck() == BF_CHECKED; /// } /// TCheckBox* TMyWindow::GetFirstChecked() { /// return FirstThat(IsThisBoxChecked); /// } /// \endcode // TWindow* TWindow::FirstThat(TCondFunc test, void* paramList) const { if (ChildList) { TWindow* nextChild = ChildList->Next(); TWindow* curChild; do { curChild = nextChild; nextChild = nextChild->Next(); // // Test curChild for okay // if (test(curChild, paramList)) return curChild; } while (curChild != ChildList && ChildList); } return 0; } // /// Iterates over each child window in the TWindow's ChildList, /// calling the procedure whose pointer is passed as the Action to be /// performed for each child /// /// A pointer to a child is passed as the first parameter to the iteration /// procedure /// /// In the following example, CheckAllBoxes calls ForEach, checking all the check /// boxes in the child list: /// \code /// void CheckTheBox(TWindow* p, void*) { /// ((TCheckBox*)p)->Check(); /// } /// void CheckAllBoxes() { /// ForEach(CheckTheBox); /// } /// \endcode // void TWindow::ForEach(TActionFunc action, void* paramList) { if (ChildList) { TWindow* curChild; TWindow* nextChild = ChildList->Next(); // Allows ForEach to delete children do { curChild = nextChild; nextChild = nextChild->Next(); action(curChild, paramList); } while (curChild != ChildList && ChildList); } } // /// Returns a pointer to the first TWindow in the ChildList that /// meets some specified criteria /// /// If no child in the list meets the criteria, 0 is returned /// /// The Test parameter which defines the criteria, is a pointer to a member /// function (this is how it's different from FirstThat above) that takes a /// pointer to a TWindow & a pointer to void /// /// The TWindow pointer will be used as the pointer to the child window and the /// void pointer as a pointer to the Test function's additional parameters /// /// The Test function must return a Boolean value indicating whether the child /// passed meets the criteria TWindow* TWindow::FirstThat(TCondMemFunc test, void* paramList) { if (ChildList) { TWindow* nextChild = ChildList->Next(); TWindow* curChild; do { curChild = nextChild; nextChild = nextChild->Next(); if ((this->*test)(curChild, paramList)) return curChild; } while (curChild != ChildList && ChildList); } return 0; } // /// Iterates over each child window in the TWindow's ChildList, /// calling the member function (unlike ForEach above which takes pointer /// to non-member function) whose pointer is passed as the Action to /// be performed for each child /// /// A pointer to a child is passed as the first parameter to the iteration /// procedure // void TWindow::ForEach(TActionMemFunc action, void* paramList) { if (ChildList) { TWindow* nextChild = ChildList->Next(); TWindow* curChild; do { curChild = nextChild; nextChild = nextChild->Next(); (this->*action)(curChild, paramList); } while (curChild != ChildList && ChildList); } } // // Returns the position at which the passed child window appears // in the TWindow's ChildList // // If the child does not appear in the list, -1 is returned. // The zero'th position is ChildList->Next. // int TWindow::IndexOf(TWindow* child) const { struct TLocal { int position; TWindow* child; static bool Compare(TWindow* w, void* p) { PRECONDITION(p); TLocal& a = *static_cast<TLocal*>(p); ++a.position; return w == a.child; } } a = {-1, child}; return FirstThat(&TLocal::Compare, &a) ? a.position : -1; } // // Returns the child at the passed position in the TWindow's // ChildList // // The ChildList is circularly-referent so that passing a position // larger than the number of children will cause the traversal of the // list to wrap // // Zero'th position is ChildList->Next // TWindow* TWindow::At(int position) { if (position == -1) return 0; else { TWindow* currentChild = ChildList; if (currentChild) { currentChild = ChildList->Next(); while (position > 0) { currentChild = currentChild->Next(); position--; } } return currentChild; } } // /// Returns a pointer to the window in the child window list that has the supplied /// id. Returns 0 if no child window has the indicated id. // TWindow* TWindow::ChildWithId(int id) const { struct TLocal { static bool Compare(TWindow* win, void* pid) {return win->GetId() == *reinterpret_cast<int*>(pid);} }; return FirstThat(&TLocal::Compare, &id); } // /// Sends a message (msg) to a specified window or windows. After it calls the /// window procedure, it waits until the window procedure has processed the message /// before returning. // TResult TWindow::SendMessage(TMsgId msg, TParam1 param1, TParam2 param2) const { PRECONDITION(GetHandle()); TResult result = ::SendMessage(GetHandle(), msg, param1, param2); GetApplication()->ResumeThrow(); return result; } // /// Forwards the window's current message. Calls SendMessage if send is true; /// otherwise calls PostMessage. // TResult TWindow::ForwardMessage(HWND handle, bool send) { if (!handle) return 0; TCurrentEvent& currentEvent = GetCurrentEvent(); if (send) { TResult result = ::SendMessage(handle, currentEvent.Message, currentEvent.Param1, currentEvent.Param2); GetApplication()->ResumeThrow(); return result; } else return ::PostMessage(handle, currentEvent.Message, currentEvent.Param1, currentEvent.Param2); } // /// Forwards the window's current message. Calls SendMessage if send is true; /// otherwise calls PostMessage. // TResult TWindow::ForwardMessage(bool send) { TCurrentEvent& currentEvent = GetCurrentEvent(); if (send) return HandleMessage(currentEvent.Message, currentEvent.Param1, currentEvent.Param2); return ForwardMessage(GetHandle(), send); } // /// Sends the specified message to all immediate children using SendMessage. /// \note Includes non-object windows // void TWindow::ChildBroadcastMessage(TMsgId msg, TParam1 param1, TParam2 param2) { for (HWND hWndChild = GetWindow(GW_CHILD); hWndChild; ) { HWND hWndNext = ::GetWindow(hWndChild, GW_HWNDNEXT); ::SendMessage(hWndChild, msg, param1, param2); GetApplication()->ResumeThrow(); hWndChild = hWndNext; } } // /// Posts messages when the mouse pointer leaves a window or hovers over a /// window for a specified amount of time. /// Encapsulates the eponymous Windows API function. /// http://msdn.microsoft.com/en-gb/library/windows/desktop/ms646265.aspx // bool TWindow::TrackMouseEvent(uint flags, int hoverTime) { TRACKMOUSEEVENT a = {sizeof(TRACKMOUSEEVENT), flags, GetHandle(), static_cast<DWORD>(hoverTime)}; return ::TrackMouseEvent(&a) == TRUE; } // /// Encapsulates a call to TrackMouseEvent, passing the TME_CANCEL flag. /// See TrackMouseEvent. // bool TWindow::CancelMouseEvent(uint flags) { return TrackMouseEvent(flags | TME_CANCEL); } // /// Returns the current state of mouse event tracking initiated by TrackMouseEvent. /// Encapsulates a call to ::TrackMouseEvent, passing the TME_QUERY flag. /// See TrackMouseEvent and Windows API structure TRACKMOUSEEVENT. /// http://msdn.microsoft.com/en-gb/library/windows/desktop/ms645604.aspx // TRACKMOUSEEVENT TWindow::QueryMouseEventTracking() const { TRACKMOUSEEVENT a = {sizeof(TRACKMOUSEEVENT), TME_QUERY, GetHandle()}; BOOL r = ::TrackMouseEvent(&a); CHECK(r); InUse(r); return a; } // /// This version of ShutDownWindow unconditionally shuts down a given window, calls /// Destroy on the interface element, and then deletes the interface object. Instead /// of using ShutDownWindow, you can call Destroy directly and then delete the /// interface object. /// /// \note This function is static to avoid side effects of deleting 'this'. // void TWindow::ShutDownWindow(TWindow* win, int retVal) { win->Destroy(retVal); delete win; } // /// Copies title to an allocated string pointed to by title. Sets the caption of the /// interface element to title. Deletes any previous title. /// If the given title is 0, then the internal caption is initialized to 0, and no update /// of the interface element is done. // void TWindow::SetCaption(LPCTSTR title) { if (Title != title) { if (Title) delete[] Title; Title = title ? strnewdup(title) : 0; } if (Title && GetHandle()) ::SetWindowText(GetHandle(), Title); } // /// Sets the window title to the resource string identified by the given id. // void TWindow::SetCaption(uint resourceStringId) { SetCaption(LoadString(resourceStringId)); } // /// Updates the TWindow internal caption (Title) from the current window's caption. /// GetWindowTextTitle is used to keep Title synchronized with the actual window /// state when there is a possibility that the state might have changed. // void TWindow::GetWindowTextTitle() { // NB! Previously (<= 6.30) Title was here checked against 0xXXXXFFFF; a flag for "don't-change". // See comment in TDialog::Init for more details. if (Title) delete[] Title; int titleLength = GetWindowTextLength(); if (titleLength < 0) { Title = strnewdup(_T("")); } else { Title = new tchar[titleLength + 1]; Title[0] = 0; Title[titleLength] = 0; GetWindowText(Title, titleLength + 1); } } // /// Copies the style, coordinate, and the resource id (but not the title) from the /// existing HWnd into the TWindow members. /// \note The title is not copied here, but in GetWindowTextTitle() // void TWindow::GetHWndState(bool forceStyleSync) { // Retrieve Attr.Style and Attr.ExStyle // // NOTE: some windows controls (e.g. EDIT) change the style bits // (e.g. WS_BORDER) from their original values. if we always reset // Attr.Style and Attr.ExStyle by extracting their values from // Windows, we will lose some of the style bits we supplied // in the CreateWindowEx call. in the case of the ResourceId // constructors, of course, we must retrieve these values. // if (IsFlagSet(wfFromResource) || forceStyleSync) { Attr.Style = GetWindowLong(GWL_STYLE); Attr.ExStyle = GetWindowLong(GWL_EXSTYLE); } // Retrieve Attr.X, Attr.Y, Attr.W and Attr.H // TRect wndRect; GetWindowRect(wndRect); Attr.H = wndRect.Height(); Attr.W = wndRect.Width(); HWND hParent = GetParentH(); if ((Attr.Style & WS_CHILD) && hParent) ::ScreenToClient(hParent, &wndRect.TopLeft()); Attr.X = wndRect.left; Attr.Y = wndRect.top; Attr.Id = GetWindowLong(GWL_ID); } // /// Translates the text of a specified control into an integer value and returns it. /// The parameter 'translated' points to a variable that is set to 'true' on success, 'false' otherwise. /// The parameter 'isSigned' indicates that the retrieved value is signed (the default). /// \note Wraps the corresponding function in the Windows API. // uint TWindow::GetDlgItemInt(int childId, bool* translated, bool isSigned) const { PRECONDITION(GetHandle()); BOOL tempTranslated; uint retVal = ::GetDlgItemInt(GetHandle(), childId, &tempTranslated, isSigned); if (translated) *translated = tempTranslated; return retVal; } // /// Gets the style bits of the underlying window or the 'Style' member of the /// attribute structure associated with this TWindow object. // uint32 TWindow::GetStyle() const { return GetHandle() ? GetWindowLong(GWL_STYLE) : Attr.Style; } // /// Sets the style bits of the underlying window or the 'Style' member of the /// attribute structure associated with this TWindow object. // uint32 TWindow::SetStyle(uint32 style) { if (!GetHandle()) { uint32 oldstyle = Attr.Style; Attr.Style = style; return oldstyle; } return SetWindowLong(GWL_STYLE, style); } // /// Gets the extra style bits of the window. // uint32 TWindow::GetExStyle() const { return GetHandle() ? GetWindowLong(GWL_EXSTYLE) : Attr.ExStyle; } // /// Sets the extra style bits of the window. // uint32 TWindow::SetExStyle(uint32 style) { if (!GetHandle()) { uint32 oldstyle = Attr.ExStyle; Attr.ExStyle = style; return oldstyle; } return SetWindowLong(GWL_EXSTYLE, style); } // /// Modifies the style bits of the window. // bool TWindow::ModifyStyle(uint32 offBits, uint32 onBits, uint swpFlags) { uint32 style = GetStyle(); uint32 newStyle = (style & ~offBits) | onBits; if (style == newStyle) return false; SetStyle(newStyle); if (swpFlags && GetHandle()) SetWindowPos(0, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|swpFlags); return true; } // /// Modifies the style bits of the window. // bool TWindow::ModifyExStyle(uint32 offBits, uint32 onBits, uint swpFlags) { uint32 style = GetExStyle(); uint32 newStyle = (style & ~offBits) | onBits; if (style == newStyle) return false; SetExStyle(newStyle); if (swpFlags) SetWindowPos(0, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|swpFlags); return true; } // /// Gets the screen coordinates of the window's rectangle and copies them into rect. /// \note Gets the window rectangle whether it has been created or not // void TWindow::GetWindowRect(TRect& rect) const { if (GetHandle()) { ::GetWindowRect(GetHandle(), &rect); } else { rect.SetWH(Attr.X, Attr.Y, Attr.W, Attr.H); } } // /// Gets the coordinates of the window's client area and then copies them into the /// object referred to by TRect. /// \note Gets the window's client rectangle whether it has been created or not // void TWindow::GetClientRect(TRect& rect) const { if (GetHandle()) { ::GetClientRect(GetHandle(), &rect); } else { rect.Set(0, 0, Attr.W, Attr.H); } } // /// Set the new window position. // /// Changes the size of the window pointed to by x, y, w, and h. flags contains one /// of the SWP_Xxxx Set Window Position constants that specify the size and /// position of the window. If flags is set to SWP_NOZORDER, SetWindowPos ignores /// the hWndInsertAfter parameter and retains the current ordering of the child, /// pop-up, or top-level windows. /// /// SWP_Xxxx Set Window Position Constants /// /// - \c \b SWP_DRAWFRAME Draws a frame around the window. /// - \c \b SWP_FRAMECHANGED Sends a message to the window to recalculate the window's /// size. If this flag is not set, a recalculate size message is sent only at the /// time the window's size is being changed. /// - \c \b SWP_HIDEWINDOW Hides the window. /// - \c \b SWP_NOACTIVATE Does not activate the window. If this flag is not set, the /// window is activated and moved to the top of the stack of windows. /// - \c \b SWP_NOCOPYBITS Discards the entire content area of the client area of the /// window. If this flag is not set, the valid contents are saved and copied into /// the window after the window is resized or positioned. /// - \c \b SWP_NOMOVE Remembers the window's current position. /// - \c \b SWP_NOSIZE Remembers the window's current size. /// - \c \b SWP_NOREDRAW Does not redraw any changes to the window. If this flag is set, no /// repainting of any window area (including client, nonclient, and any window part /// uncovered as a result of a move) occurs. When this flag is set, the application /// must explicitly indicate if any area of the window is invalid and needs to be /// redrawn. /// - \c \b SWP_NOZORDER Remembers the current Z-order (window stacking order). /// - \c \b SWP_SHOWWINDOW Displays the window. // bool TWindow::SetWindowPos(HWND hWndInsertAfter, int x, int y, int w, int h, uint flags) { if (GetHandle()) return ::SetWindowPos(GetHandle(), hWndInsertAfter, x, y, w, h, flags); if (!(flags & SWP_NOMOVE)) { Attr.X = x; Attr.Y = y; } if (!(flags & SWP_NOSIZE)) { Attr.W = w; Attr.H = h; } // !CQ Can't do much with Z-Order or owner Z-Order if (flags & SWP_SHOWWINDOW) Attr.Style |= WS_VISIBLE; else if (flags & SWP_HIDEWINDOW) Attr.Style &= ~WS_VISIBLE; return true; } // /// Displays this TWindow in a given state. Can be called either before or after /// the Window is created. If before, the show state is placed into Attr for use /// at creation /// /// After ensuring that the TWindow interface element has a valid handle, ShowWindow /// displays the TWindow on the screen in a manner specified by cmdShow, which can /// be one of the following SW_Xxxx Show Window constants: /// - \c \b SW_SHOWDEFAULT Show the window in its default configuration. Should be used at /// startup. /// - \c \b SW_HIDE Hide the window and activate another window. /// - \c \b SW_MINIMIZE Minimize the window and activate the top-level window in the list. /// - \c \b SW_RESTORE Same as SW_SHOWNORMAL. /// - \c \b SW_SHOW Show the window in the window's current size and position. /// - \c \b SW_SHOWMAXIMIZED Activate and maximize the window. /// - \c \b SW_SHOWMINIMIZED Activate window as an icon. /// - \c \b SW_SHOWNA Display the window as it is currently. /// - \c \b SW_SHOWMINNOACTIVE Display the window as an icon. /// - \c \b SW_SHOWNORMAL Activate and display the window in its original size and position. /// - \c \b SW_SHOWSMOOTH Show the window after updating it in a bitmap. // bool TWindow::ShowWindow(int cmdShow) { // If the window is being minimzed send a WM_SYSCOMMAND; this way the // frame window focus saving works properly // !CQ do we still need this with final owl2 focus saving? // if (gBatchMode) return true; if (GetHandle()) { if (cmdShow == SW_MINIMIZE) return HandleMessage(WM_SYSCOMMAND, SC_MINIMIZE); else return ::ShowWindow(GetHandle(), cmdShow); } switch (cmdShow) { case SW_HIDE: Attr.Style &= ~WS_VISIBLE; break; case SW_SHOWNORMAL: case SW_RESTORE: Attr.Style |= WS_VISIBLE; Attr.Style &= ~(WS_MINIMIZE | WS_MAXIMIZE); break; case SW_SHOWMINIMIZED: case SW_MINIMIZE: case SW_SHOWMINNOACTIVE: Attr.Style |= WS_VISIBLE; Attr.Style |= WS_MINIMIZE; break; case SW_SHOWMAXIMIZED: Attr.Style |= WS_VISIBLE; Attr.Style |= WS_MAXIMIZE; break; case SW_SHOWNOACTIVATE: case SW_SHOW: case SW_SHOWNA: Attr.Style |= WS_VISIBLE; break; } return true; } // /// Sets the cursor position for the window using the given module and ResId. If the /// module parameter is 0, CursorResId can be one of the IDC_xxxx constants that /// represent different kinds of cursors. See the data member for a list of these /// cursor values. If the mouse is over the client area, SetCursor changes the /// cursor that is displayed. // bool TWindow::SetCursor(TModule* module, TResId resId) { if (module == CursorModule && resId == CursorResId) return false; HCURSOR hOldCursor = (HCursor && CursorModule) ? HCursor : 0; CursorModule = module; CursorResId = resId; if (CursorResId) if (CursorModule) HCursor = CursorModule->LoadCursor(CursorResId); else HCursor = ::LoadCursor(0, CursorResId); else HCursor = 0; // If the cursor is in our client window then set it now // if (GetHandle()) { TPoint p; GetCursorPos(p); ScreenToClient(p); if (GetClientRect().Contains(p)) ::SetCursor(HCursor); } // Destroy old cursor if there was one & it was not loaded from USER // if (hOldCursor) ::DestroyCursor(hOldCursor); return true; } // /// Handle WM_INITMENUPOPUP while embeded to generate command enable messages /// for our server menu items. Very similar to TFrameWindow::EvInitMenuPopup; /// could rearrange code to share better. // void TWindow::EvInitMenuPopup(HMENU hPopupMenu, uint /*index*/, bool sysMenu) { if (IsFlagSet(wfAlias)) DefaultProcessing(); else if (!sysMenu && hPopupMenu) { const int count = ::GetMenuItemCount(hPopupMenu); for (int pos = 0; pos < count; pos++) { uint id; if (hPopupMenu == GetMenu()) // top level menu id = ::GetMenuItemID(hPopupMenu, pos); else { // For second level and below menus, return the implied id for popup // sub-menus. The implied id for a sub-menu is the id of the first item // in the popup sub-menu less 1. If there are more than one level of // popup menus, it will recursively look into those sub-menus as well. // TMenu popupMenu(hPopupMenu); id = popupMenu.GetMenuItemID(pos); } // Ignore separators // if (id == 0 || uint16(id) == uint16(-1)) continue; // Skip the rest if it is the mdi child list, or system commands // if (id == (uint)IDW_FIRSTMDICHILD || id > 0xF000) break; TMenuItemEnabler mie(hPopupMenu, id, GetHandle(), pos); EvCommandEnable(mie); } } } // /// Associates a pop-up menu with the window so that it can automatically handle a /// WM_CONTEXTMENU message. // // !CQ Is this unusual/confusing to take the pointer & own it, & not a ref // !CQ & copy it??? // void TWindow::AssignContextMenu(TPopupMenu* popupMenu) { delete ContextPopupMenu; ContextPopupMenu = popupMenu; } // /// The default message handler for WM_CONTEXTMENU. /// Respond to a right button click or VK_APPS key press in the window. /// If a context menu is set, display it. // void TWindow::EvContextMenu(HWND child, int x, int y) { TPopupMenu* m = GetContextMenu(); if (!m) { DefaultProcessing(); return; } TPoint p(x, y); bool invalidPos = (x < 0 || y < 0); if (invalidPos) { // The message was probably generated by the VK_APPS key (sets x = y = -1). // See the Windows API documentation for WM_CONTEXTMENU. // http://msdn.microsoft.com/en-us/library/windows/desktop/ms647592.aspx // In this case, we open the menu in the upper left corner of the given window. // p = TPoint(0, 0); ::ClientToScreen(child, &p); } else { // Provide additional help support by reporting the click position to the main window. // THelpHitInfo hit(p, this); GetApplication()->GetMainWindow()->HandleMessage(WM_OWLHELPHIT, 0, reinterpret_cast<TParam2>(&hit)); } m->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, p, 0, GetHandle()); } // /// The default message handler for WM_ENTERIDLE. // void TWindow::EvEnterIdle(uint source, HWND hWndDlg) { // If we're the main window, let it rip from the receiver // if (source == MSGF_DIALOGBOX) { if (IsFlagSet(wfMainWindow)) IdleAction(0); else { TWindow* win = GetWindowPtr(hWndDlg); if (win) win->IdleAction(0); } } // Let original proc. have a crack at msg. // DefaultProcessing(); } // /// Retrieves the properties of the given scroll bar. /// The 'scrollInfo' parameter must be properly initialized according /// to the Windows API documentation for SCROLLINFO. /// Returns true on success. /// \note Wrapper for Windows API. // bool TWindow::GetScrollInfo(int bar, SCROLLINFO* scrollInfo) const { PRECONDITION(GetHandle()); return ::GetScrollInfo(GetHandle(), bar, scrollInfo); } // /// Function-style overload /// Returns selected properties of the given scroll bar. /// Valid values for the 'mask' parameter are the same as for the /// SCROLLINFO::fMask member documented by the Windows API. /// \note On failure, SCROLLINFO::nMin, nMax, nPage, nPos and nTrackPos /// are all left value-initialized (0). // SCROLLINFO TWindow::GetScrollInfo(int bar, uint mask) const { SCROLLINFO i = {sizeof(SCROLLINFO), mask}; bool r = GetScrollInfo(bar, &i); WARNX(OwlWin, !r, 0, _T("GetScrollInfo failed.")); InUse(r); return i; } // /// Sets the properties of the given scroll bar. /// Returns the current position of the scroll bar thumb. /// \note Wrapper for Windows API. // int TWindow::SetScrollInfo(int bar, SCROLLINFO* scrollInfo, bool redraw) { PRECONDITION(GetHandle()); return ::SetScrollInfo(GetHandle(), bar, scrollInfo, redraw); } // /// Returns the thumb position in the scroll bar. The position returned is relative /// to the scrolling range. If bar is SB_CTL, it returns the position of a control /// in the scroll bar. If bar is SB_HORZ, it returns the position of a horizontal /// scroll bar. If bar is SB_VERT, it returns the position of a vertical scroll bar. // int TWindow::GetScrollPos(int bar) const { return GetScrollInfo(bar, SIF_POS).nPos; } // /// Sets the thumb position in the scroll bar. Parameter 'bar' identifies the position /// (horizontal, vertical, or scroll bar control) to return and can be one of the /// SB_Xxxx scroll bar constants. /// Returns the current position of the scroll bar thumb. // int TWindow::SetScrollPos(int bar, int pos, bool redraw) { SCROLLINFO i = {sizeof(SCROLLINFO), SIF_POS, 0, 0, 0, pos}; return SetScrollInfo(bar, &i, redraw); } // /// Returns the thumb track position in the scroll bar. Call this function only during /// the processing of a scroll message with the SB_THUMBTRACK or SB_THUMBPOSITION code. /// See GetScrollPos for valid values for the 'bar' parameter. // int TWindow::GetScrollTrackPos(int bar) const { return GetScrollInfo(bar, SIF_TRACKPOS).nTrackPos; } // /// Returns the minimum and maximum positions in the scroll bar. If bar is SB_CTL, /// it returns the position of a control in the scroll bar. If bar is SB_HORZ, it /// returns the position of a horizontal scroll bar. If bar is SB_VERT, it returns /// the position of a vertical scroll bar. minPos and maxPos hold the lower and /// upper range, respectively, of the scroll bar positions. If there are no scroll /// bar controls, or if the scrolls are non-standard, minPos and maxPos are zero. // void TWindow::GetScrollRange(int bar, int& minPos, int& maxPos) const { SCROLLINFO i = GetScrollInfo(bar, SIF_RANGE); minPos = i.nMin; maxPos = i.nMax; } // /// Function-style overload // TWindow::TScrollRange TWindow::GetScrollRange(int bar) const { SCROLLINFO i = GetScrollInfo(bar, SIF_RANGE); return TScrollRange(i.nMin, i.nMax); } // /// Sets the thumb position in the scroll bar. bar identifies the position /// (horizontal, vertical, or scroll bar control) to set and can be one of the /// SB_Xxxx scroll bar constants. minPos and maxPos specify the lower and upper /// range, respectively, of the scroll bar positions. // void TWindow::SetScrollRange(int bar, int minPos, int maxPos, bool redraw) { SCROLLINFO i = {sizeof(SCROLLINFO), SIF_RANGE, minPos, maxPos}; SetScrollInfo(bar, &i, redraw); } // /// Overload taking the range as a pair // void TWindow::SetScrollRange(int bar, const TScrollRange& r, bool redraw) { SetScrollRange(bar, r.first, r.second, redraw); } // /// Returns the page property (SCROLLINFO::nPage) of the given scroll bar. // int TWindow::GetScrollPage(int bar) const { return GetScrollInfo(bar, SIF_PAGE).nPage; } // /// Sets the page property (SCROLLINFO::nPage) of the given scroll bar. // void TWindow::SetScrollPage(int bar, int page, bool redraw) { SCROLLINFO i = {sizeof(SCROLLINFO), SIF_PAGE, 0, 0, page}; SetScrollInfo(bar, &i, redraw); } // // // void TWindow::EnableTooltip(bool enable) { if (!Tooltip) { // To circumvent this scenario, we'll look for a window which is fairly // stable/rooted as owner of the tooltip. Ideally, we'll get the // application's main window. // TWindow* tipParent = this; /* // check it what if window -> is closed but tooltip live????????? // it is for gastget only ???????????????????? while (tipParent->GetParentO()){ tipParent = tipParent->GetParentO(); if (tipParent->IsFlagSet(wfMainWindow)) break; } */ // Create and initialize tooltip // SetTooltip(new TTooltip(tipParent)); } else { if (Tooltip->GetHandle()) Tooltip->Activate(enable); } } // // Set a specific tooltip for this window. Assume we now own the ToolTip // void TWindow::SetTooltip(TTooltip* tooltip) { // Cleanup; via Condemned list if tooltip was created // if (Tooltip) { if (Tooltip->GetHandle()) Tooltip->SendMessage(WM_CLOSE); else delete Tooltip; } // Store new tooltip and create if necessary // Tooltip = tooltip; if (Tooltip) { if (!Tooltip->GetHandle()) { // Make sure tooltip is disabled so it does not take input focus Tooltip->Attr.Style |= WS_DISABLED; Tooltip->Create(); } } } // /// Copies a window's update region into a region specified by region. If erase is /// true, GetUpdateRgn erases the background of the updated region and redraws /// nonclient regions of any child windows. If erase is false, no redrawing occurs. /// If the call is successful, GetUpdateRgn returns a value indicating the kind of /// region that was updated. If the region has no overlapping borders, it returns /// SIMPLEREGION; if the region has overlapping borders, it returns COMPLEXREGION; /// if the region is empty, it returns NULLREGION; if an error occurs, it returns /// ERROR. /// /// \note Not inline to avoid requiring gdiobjec.h by window.h just to get TRegion's /// conversion operator // int TWindow::GetUpdateRgn(TRegion& region, bool erase) const { PRECONDITION(GetHandle()); return ::GetUpdateRgn(GetHandle(), region, erase); } // /// If a window can process dropped files, DragAcceptFiles sets accept to true. /// \note Wrapper for Windows API. // void TWindow::DragAcceptFiles(bool accept) { PRECONDITION(GetHandle()); TShell::DragAcceptFiles(GetHandle(), accept); } // /// Creates and displays a message box that contains a message (text), a title /// (caption), and icons or push buttons (type). If caption is 0, the default title /// is displayed. Although flags is set to one push button by default, it can contain /// a combination of the MB_Xxxx message constants. This function returns one of /// the following constants: /// - \c \b IDABORT User selected the abort button. /// - \c \b IDCANCEL User selected the cancel button. /// - \c \b IDIGNORE User selected the ignore button. /// - \c \b IDNO User selected the no button. /// - \c \b IDOK User selected the OK button /// - \c \b IDRETRY User selected the retry button. /// - \c \b IDYES User selected the yes button. // int TWindow::MessageBox(LPCTSTR text, LPCTSTR caption, uint flags) { PRECONDITION(GetApplication()); PRECONDITION(GetHandle()); return GetApplication()->MessageBox(*this, text, caption, flags); } const int FORMATMESSAGEBOXBUFFERSIZE = 1024; int TWindow::FormatMessageBox(LPCTSTR text, LPCTSTR caption, uint flags, va_list argp) { tchar buffer[FORMATMESSAGEBOXBUFFERSIZE]; int r = _vsntprintf(buffer, FORMATMESSAGEBOXBUFFERSIZE, text, argp); if (r== -1) { buffer[FORMATMESSAGEBOXBUFFERSIZE - 1] = _T('\0'); WARNX(OwlWin, r == -1, 0, _T("TWindow::FormatMessageBox: Message was truncated.")); } return MessageBox(buffer, caption, flags); } int TWindow::FormatMessageBox(LPCTSTR text, LPCTSTR caption, uint flags, ...) { va_list argp; va_start(argp, flags); int r = 0; try { r = FormatMessageBox(text, caption, flags, argp); } catch (...) { WARNX(OwlWin, true, 0, _T("Variadic TWindow::FormatMessageBox failed.")); } va_end(argp); return r; } int TWindow::FormatMessageBox(const tstring& text, const tstring& caption, uint flags, ...) { va_list argp; va_start(argp, flags); int r = 0; try { r = FormatMessageBox(text.c_str(), caption.c_str(), flags, argp); } catch (...) { WARNX(OwlWin, true, 0, _T("Variadic TWindow::FormatMessageBox failed.")); } va_end(argp); return r; } int TWindow::MessageBox(uint resId, LPCTSTR caption, uint flags) { PRECONDITION(GetApplication()); PRECONDITION(GetHandle()); PRECONDITION(resId); tstring text = LoadString(resId); return MessageBox(text.c_str(), caption, flags); } int TWindow::MessageBox(uint resId, const tstring& caption, uint flags) { PRECONDITION(GetApplication()); PRECONDITION(GetHandle()); PRECONDITION(resId); tstring text = LoadString(resId); return MessageBox(text.c_str(), caption.c_str(), flags); } int TWindow::FormatMessageBox(uint resId, LPCTSTR caption, uint flags, va_list argp) { PRECONDITION(resId); tstring text = LoadString(resId); return FormatMessageBox(text.c_str(), caption, flags, argp); } int TWindow::FormatMessageBox(uint resId, LPCTSTR caption, uint flags, ...) { va_list argp; va_start(argp, flags); int r = 0; try { r = FormatMessageBox(resId, caption, flags, argp); } catch (...) { WARNX(OwlWin, true, 0, _T("Variadic TWindow::FormatMessageBox failed.")); } va_end(argp); return r; } int TWindow::FormatMessageBox(uint resId, const tstring& caption, uint flags, ...) { va_list argp; va_start(argp, flags); int r = 0; try { FormatMessageBox(resId, caption.c_str(), flags, argp); } catch (...) { WARNX(OwlWin, true, 0, _T("Variadic TWindow::FormatMessageBox failed.")); } va_end(argp); return r; } int TWindow::FormatMessageBox(uint resId, const tstring& caption, uint flags, va_list argp) { tstring text = LoadString(resId); return FormatMessageBox(text.c_str(), caption.c_str(), flags, argp); } // // // void TWindow::SethAccel(HACCEL _hAccel) { HAccel = _hAccel; } // /// For use with CopyText. // struct TWindowGetWindowText { const TWindow& win; TWindowGetWindowText(const TWindow& w) : win(w) {} int operator()(LPTSTR buf, int buf_size) {return win.GetWindowText(buf, buf_size);} }; // /// String-aware overload // tstring TWindow::GetWindowText() const { return CopyText(GetWindowTextLength(), TWindowGetWindowText(*this)); } // /// For use with CopyText. // struct TWindowGetDlgItemText { const TWindow& win; int id; TWindowGetDlgItemText(const TWindow& w, int id_) : win(w), id(id_) {} int operator()(LPTSTR buf, int buf_size) {return win.GetDlgItemText(id, buf, buf_size);} }; // /// String-aware overload // tstring TWindow::GetDlgItemText(int childId) const { return CopyText(::GetWindowTextLength(GetDlgItem(childId)), TWindowGetDlgItemText(*this, childId)); } // // // #if defined(__TRACE) || defined(__WARN) //namespace owl { ostream& operator <<(ostream& os, const TWindow& w) { os << '('; os << _OBJ_FULLTYPENAME(&w) << ','; os << "0x" << hex << uint(w.GetHandle()) << ','; if (w.GetCaption()) os << '\'' << w.GetCaption() << '\'' << ','; if (w.GetParentO()) os << "id=" << w.GetId(); os << ')'; return os; } //} // OWL namespace #endif /////////////////////////////////////////////////////////////////////////////////////// // TDrawItem* ItemData2DrawItem(ULONG_PTR data) { // 0. If 0 if(data==0) return 0; // 1. check to make sure the pointer is valid if(IsBadReadPtr((void*)data, sizeof(TDrawItem))) return 0; // quick escape // 2. check signature -> starting from 5's byte uint32* itemId = (uint32*)((uint8*)data+4); if(*itemId != TDrawItemBase::drawId) return 0; // 3. check to make sure the VTable pointer is valid if(IsBadReadPtr(*(void**)data, sizeof(void*))) return 0; // quick escape #if 0 //?? maby simple casting enauph after checking itemId?? TDrawItem* item; try{ item = localTryCatchBlock(data); } catch(...){ return 0; } return item; #else return (TDrawItem*)(void*)data; #endif } /////////////////////////////////////////////////////////////////////////////////////// // // Converts the given integer to a string. // TODO: Relocate somewhere else more convenient for reuse. // static tstring ToString(int v) { tchar buf[64]; _stprintf(buf, _T("%d"), v); return tstring(buf); } // // Returns a string which kind-of identifies the window (used during autopsy // and vivisection of dead/dying window). // static tstring GetSuspectDescription(TWindow* w) { _USES_CONVERSION; if (!w) return _T(""); tstring caption = w->GetCaption() ? w->GetCaption() : _T(""); tstring id = ToString(w->GetWindowAttr().Id); tstring type = _A2W(_OBJ_FULLTYPENAME(w)); tstring s; s += _T("\"") + caption + _T("\""); s += _T(", ID: ") + id; s += _T(", window ") + type; s += _T("."); return s; } // // Formats an error message defined by the given resource id. // Appends the last system error message if any. // // NB! Note that the TSystemMessage probably is too far from the problem site to give a // meaningful error message; intermediate system calls have probably happened since // the exception was thrown. // static tstring MakeTXWindowMessage(TWindow* win, uint resId) { TSystemMessage m; tstring s = TXOwl::MakeMessage(resId, GetSuspectDescription(win).c_str()); if (m.SysError() != ERROR_SUCCESS) s += _T("\n\nSystem error: ") + m.SysMessage(); return s; } // /// Constructs a TXWindow object with a default resource ID of IDS_INVALIDWINDOW. // TXWindow::TXWindow(TWindow* win, uint resId) : TXOwl(MakeTXWindowMessage(win, resId), resId), Window(win) { } // /// Copy the exception object. // TXWindow::TXWindow(const TXWindow& src) : TXOwl(src), Window(src.Window) { } // /// Unhandled exception. /// /// Called if an exception caught in the window's message loop has not been handled. /// Unhandled() deletes the window. This type of exception can occur if a window /// cannot be created. // int TXWindow::Unhandled(TModule* app, uint promptResId) { Window = 0; return TXOwl::Unhandled(app, promptResId); } // /// Clone the exception object for safe-throwing. // TXWindow* TXWindow::Clone() const { return new TXWindow(*this); } // /// Throws the exception object. Throw() must be implemented in any class derived /// from TXOwl. // void TXWindow::Throw() { throw *this; } // /// Creates the TXWindow exception and throws it. // void TXWindow::Raise(TWindow* win, uint resourceId) { TXWindow(win, resourceId).Throw(); } // // Returns the window causing the exception. // TWindow* TXWindow::GetWindow() const { return Window; } } // OWL namespace /* ========================================================================== */
30.361862
292
0.6871
[ "object" ]
6ac19be6320ccd1c24589ee68908e0e5b35e6e2d
5,679
hh
C++
Include/OpenMesh/Tools/VDPM/MeshTraits.hh
565353780/peeling-art
7427321c8cbf076361c8de2281a0f0cde7fd38bb
[ "MIT" ]
null
null
null
Include/OpenMesh/Tools/VDPM/MeshTraits.hh
565353780/peeling-art
7427321c8cbf076361c8de2281a0f0cde7fd38bb
[ "MIT" ]
null
null
null
Include/OpenMesh/Tools/VDPM/MeshTraits.hh
565353780/peeling-art
7427321c8cbf076361c8de2281a0f0cde7fd38bb
[ "MIT" ]
null
null
null
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2015, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * 3. Neither the name of the copyright holder nor the names of its * * contributors may be used to endorse or promote products derived from * * this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * ========================================================================= */ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ //============================================================================= // // CLASS VDPMTraits // //============================================================================= #ifndef OPENMESH_VDPM_TRAITS_HH #define OPENMESH_VDPM_TRAITS_HH //== INCLUDES ================================================================= #include <OpenMesh/Core/System/config.h> #include <OpenMesh/Core/Mesh/Traits.hh> #include <OpenMesh/Tools/VDPM/VHierarchy.hh> //== FORWARDDECLARATIONS ====================================================== //== NAMESPACES =============================================================== namespace OpenMesh { namespace VDPM { //== CLASS DEFINITION ========================================================= /** \class MeshTraits MeshTraits.hh <OpenMesh/Tools/VDPM/MeshTraits.hh> Mesh traits for View Dependent Progressive Meshes */ struct OPENMESHDLLEXPORT MeshTraits : public DefaultTraits { VertexTraits { public: VHierarchyNodeHandle vhierarchy_node_handle() { return node_handle_; } void set_vhierarchy_node_handle(VHierarchyNodeHandle _node_handle) { node_handle_ = _node_handle; } bool is_ancestor(const VHierarchyNodeIndex &_other) { return false; } private: VHierarchyNodeHandle node_handle_; }; VertexAttributes(OpenMesh::Attributes::Status | OpenMesh::Attributes::Normal); HalfedgeAttributes(OpenMesh::Attributes::PrevHalfedge); EdgeAttributes(OpenMesh::Attributes::Status); FaceAttributes(OpenMesh::Attributes::Status | OpenMesh::Attributes::Normal); }; //============================================================================= } // namespace VDPM } // namespace OpenMesh //============================================================================= #endif // OPENMESH_VDPM_TRAITS_HH defined //=============================================================================
45.071429
92
0.398838
[ "mesh" ]
6ac2ee186c63a8a9c32c06751b1f70477d3e4232
5,387
cc
C++
src/wm/manage/workspace.cc
kkspeed/NaiveWM
5da1e816ae3b9ec7a5a8c0b73b569615e231a215
[ "BSD-3-Clause" ]
null
null
null
src/wm/manage/workspace.cc
kkspeed/NaiveWM
5da1e816ae3b9ec7a5a8c0b73b569615e231a215
[ "BSD-3-Clause" ]
1
2017-07-12T06:22:10.000Z
2017-07-16T17:27:09.000Z
src/wm/manage/workspace.cc
kkspeed/NaiveWM
5da1e816ae3b9ec7a5a8c0b73b569615e231a215
[ "BSD-3-Clause" ]
1
2018-07-22T02:02:11.000Z
2018-07-22T02:02:11.000Z
#include "wm/manage/workspace.h" #include <algorithm> #include <cassert> #include <deque> #include "config.h" #include "wm/manage/split_exec.h" namespace naive { namespace wm { namespace { void ArrangeNonFloatingWindows(std::deque<ManageWindow*>& candidates, int32_t x, int32_t y, int32_t width, int32_t height, int32_t screen_width_, int32_t screen_height_, int32_t tag, int32_t inset_y) { SplitExec exec(config::kLayouts[tag], base::geometry::Rect(x, y, width, height), candidates.size()); for (int32_t i = 0; i < candidates.size(); i++) { auto* front = candidates[i]; auto rect = exec.NextRect(i); if (front->is_maximized()) front->MoveResize(0, inset_y, screen_width_, screen_height_); else front->MoveResize(rect.x(), rect.y(), rect.width(), rect.height()); } } } // namespace ManageWindow::ManageWindow(Window* window, WMPrimitives* primitives) : window_(window), primitives_(primitives), is_floating_(window->has_manage_floating_hint() || window->is_transient() || window->is_popup()) {} Workspace::Workspace(uint32_t tag, uint32_t workspace_inset_y) : tag_(tag), workspace_inset_y_(workspace_inset_y) {} ManageWindow* Workspace::AddWindow(std::unique_ptr<ManageWindow> window) { auto* result = window.get(); windows_.push_back(std::move(window)); current_window_ = windows_.size() - 1; return result; } ManageWindow* Workspace::CurrentWindow() { assert(current_window_ <= windows_.size()); if (windows_.size() == 0) return nullptr; return windows_[current_window_].get(); } std::unique_ptr<ManageWindow> Workspace::PopWindow(Window* window) { if (current_window_ >= windows_.size() - 1) current_window_ = 0; auto it = std::find_if(windows_.begin(), windows_.end(), [window](auto& mw) { return mw->window() == window; }); if (it != windows_.end()) { while (it + 1 != windows_.end()) { std::iter_swap(it, it + 1); it++; } auto* mw = windows_.back().release(); windows_.pop_back(); auto* current = CurrentWindow(); if (current && !current->window()->is_visible()) NextVisibleWindow(); return std::unique_ptr<ManageWindow>(mw); } return nullptr; } ManageWindow* Workspace::NextWindow() { if (windows_.size() == 0) return nullptr; size_t next_index = (current_window_ + 1) % windows_.size(); current_window_ = next_index; return windows_[next_index].get(); } ManageWindow* Workspace::PrevWindow() { if (windows_.size() == 0) return nullptr; size_t next_index = (current_window_ - 1 + windows_.size()) % windows_.size(); current_window_ = next_index; return windows_[next_index].get(); } ManageWindow* Workspace::NextVisibleWindow() { return WindowWithCondition( [](auto* mw) { return mw->window()->is_visible(); }, [this]() { return this->NextWindow(); }); } ManageWindow* Workspace::PrevVisibleWindow() { return WindowWithCondition( [](auto* mw) { return mw->window()->is_visible(); }, [this]() { return this->PrevWindow(); }); } ManageWindow* Workspace::WindowWithCondition( std::function<bool(ManageWindow* mw)> predicate, std::function<ManageWindow*()> advance_proc) { ManageWindow* current = advance_proc(); ManageWindow* start = current; while (current && !predicate(current)) { current = advance_proc(); if (start == current) { current = nullptr; break; } } return current; } void Workspace::Show(bool show) { for (auto& window : windows_) window->Show(show, ManageWindowShowReason::SHOW_WORKSPACE_CHANGE); } void Workspace::SetCurrentWindow(Window* window) { for (size_t i = 0; i < windows_.size(); i++) { if (windows_[i]->window() == window) current_window_ = i; } } void Workspace::ArrangeWindows(int32_t x, int32_t y, int32_t width, int32_t height) { std::vector<ManageWindow*> floating_windows; std::deque<ManageWindow*> normal_windows; for (auto& mw : windows_) { if (mw->window()->is_visible()) { if (mw->is_floating()) floating_windows.push_back(mw.get()); else normal_windows.push_back(mw.get()); } } ArrangeNonFloatingWindows(normal_windows, x, y, width, height, width, height, tag_, workspace_inset_y_); for (auto* window : floating_windows) window->window()->Raise(); } void Workspace::AddWindowToHead(std::unique_ptr<ManageWindow> window) { windows_.insert(windows_.begin(), std::move(window)); current_window_ = 0; } bool Workspace::HasWindow(Window* window) { return std::find_if(windows_.begin(), windows_.end(), [window](auto& mw) { return mw->window() == window; }) != windows_.end(); } ManageWindow* Workspace::FindWindowByPid(pid_t pid) { auto result = std::find_if(windows_.begin(), windows_.end(), [pid](auto& mw) { return mw->window()->GetPid() == pid; }); return (result == windows_.end()) ? nullptr : (*result).get(); } } // namespace wm } // namespace naive
30.094972
80
0.617041
[ "geometry", "vector" ]
6ac69c0e8de96e33a599017336a7d4bd5d5f3361
2,658
cc
C++
decision_service/test/ds_test_action_probabilities.cc
eisber/vowpal_wabbit
a6637cbf5e0bb9774d24dd2bb0eb240e98b8c79e
[ "BSD-3-Clause" ]
27
2016-06-15T15:49:03.000Z
2019-11-12T06:52:49.000Z
decision_service/test/ds_test_action_probabilities.cc
eisber/vowpal_wabbit
a6637cbf5e0bb9774d24dd2bb0eb240e98b8c79e
[ "BSD-3-Clause" ]
null
null
null
decision_service/test/ds_test_action_probabilities.cc
eisber/vowpal_wabbit
a6637cbf5e0bb9774d24dd2bb0eb240e98b8c79e
[ "BSD-3-Clause" ]
14
2016-07-15T19:47:12.000Z
2020-01-09T03:38:40.000Z
/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include <boost/test/unit_test.hpp> #include <vector> #include "ds_explore.h" using namespace std; #include "utility.h" using namespace boost::unit_test; using namespace Microsoft::DecisionService; using namespace MultiWorldTesting; BOOST_AUTO_TEST_SUITE( DecisionServiceActionProbabilities ) BOOST_AUTO_TEST_CASE( ActionProbabilities_init ) { ActionProbabilities actionProbs(3); BOOST_CHECK_EQUAL(actionProbs[0].action, 0); BOOST_CHECK_EQUAL(actionProbs[1].action, 1); BOOST_CHECK_EQUAL(actionProbs[2].action, 2); } BOOST_AUTO_TEST_CASE( ActionProbabilities_swap_first ) { ActionProbabilities actionProbs(3); actionProbs[0].probability = 0.8f; actionProbs[1].probability = 0.1f; actionProbs[2].probability = 0.1f; actionProbs.swap_first(2); BOOST_CHECK_EQUAL(actionProbs[0].action, 2); BOOST_CHECK_EQUAL(actionProbs[1].action, 1); BOOST_CHECK_EQUAL(actionProbs[2].action, 0); BOOST_CHECK_CLOSE(actionProbs[0].probability, 0.1, 0.00001); BOOST_CHECK_CLOSE(actionProbs[1].probability, 0.1, 0.00001); BOOST_CHECK_CLOSE(actionProbs[2].probability, 0.8, 0.00001); } BOOST_AUTO_TEST_CASE( ActionProbabilities_sort_by_probabilities_desc ) { ActionProbabilities actionProbs(3); actionProbs[0].probability = 0.1f; actionProbs[1].probability = 0.1f; actionProbs[2].probability = 0.8f; actionProbs.sort_by_probabilities_desc(); BOOST_CHECK_EQUAL(actionProbs[0].action, 2); BOOST_CHECK_EQUAL(actionProbs[1].action, 0); BOOST_CHECK_EQUAL(actionProbs[2].action, 1); BOOST_CHECK_CLOSE(actionProbs[0].probability, 0.8, 0.00001); BOOST_CHECK_CLOSE(actionProbs[1].probability, 0.1, 0.00001); BOOST_CHECK_CLOSE(actionProbs[2].probability, 0.1, 0.00001); } BOOST_AUTO_TEST_CASE( ActionProbabilities_sample ) { ActionProbabilities actionProbs(3); actionProbs[0].probability = 0.7f; actionProbs[1].probability = 0.2f; actionProbs[2].probability = 0.1f; PRG::prg random_generator(123); double counts[3] = { 0, 0, 0}; int n = 10000; for(int i=0;i<10000;i++) { float draw = random_generator.Uniform_Unit_Interval(); counts[actionProbs.sample(draw)]++; } for (int i=0;i<3;i++) counts[i] /= n; BOOST_CHECK_CLOSE(counts[0], 0.7, 2.f); BOOST_CHECK_CLOSE(counts[1], 0.2, 2.f); BOOST_CHECK_CLOSE(counts[2], 0.1, 2.f); } // TODO: probabilities, actions, saftey BOOST_AUTO_TEST_SUITE_END()
28.276596
77
0.724229
[ "vector" ]
6ac6b9e7157684805a7faf5a45ce9be169ba2af3
6,947
cc
C++
mace/ops/resize_nearest_neighbor.cc
oneTaken/mace
be149a74789cb5e3b9394b004f7a6ddb42624a87
[ "Apache-2.0" ]
null
null
null
mace/ops/resize_nearest_neighbor.cc
oneTaken/mace
be149a74789cb5e3b9394b004f7a6ddb42624a87
[ "Apache-2.0" ]
null
null
null
mace/ops/resize_nearest_neighbor.cc
oneTaken/mace
be149a74789cb5e3b9394b004f7a6ddb42624a87
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The MACE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <memory> #include <vector> #include "mace/core/operator.h" #include "mace/ops/common/utils.h" #ifdef MACE_ENABLE_OPENCL #include "mace/ops/opencl/image/resize_nearest_neighbor.h" #endif // MACE_ENABLE_OPENCL #include "mace/utils/memory.h" namespace mace { namespace ops { template<typename T> inline void ResizeImageNCHW(const OpContext *context, const T *images, const index_t batch_size, const index_t in_height, const index_t in_width, const index_t out_height, const index_t out_width, const index_t channels, const float height_scale, const float width_scale, bool align_corners, T *output) { utils::ThreadPool &thread_pool = context->device()->cpu_runtime()->thread_pool(); thread_pool.Compute2D([=](index_t start0, index_t end0, index_t step0, index_t start1, index_t end1, index_t step1) { for (index_t b = start0; b < end0; b += step0) { for (index_t c = start1; c < end1; c += step1) { const T *channel_input_ptr = images + (b * channels + c) * in_height * in_width; T *channel_output_ptr = output + (b * channels + c) * out_height * out_width; for (index_t y = 0; y < out_height; ++y) { const index_t in_y = std::min( (align_corners) ? static_cast<index_t>(roundf(y * height_scale)) : static_cast<index_t>(floorf(y * height_scale)), in_height - 1); for (int x = 0; x < out_width; ++x) { const index_t in_x = std::min( (align_corners) ? static_cast<index_t>(roundf(x * width_scale)) : static_cast<index_t>(floorf(x * width_scale)), in_width - 1); channel_output_ptr[y * out_width + x] = channel_input_ptr[in_y * in_width + in_x]; } } } } }, 0, batch_size, 1, 0, channels, 1); } template<DeviceType D, typename T> class ResizeNearestNeighborOp; template<typename T> class ResizeNearestNeighborOp<DeviceType::CPU, T> : public Operation { public: explicit ResizeNearestNeighborOp(OpConstructContext *context) : Operation(context), align_corners_(Operation::GetOptionalArg<bool>("align_corners", false)) {} MaceStatus Run(OpContext *context) override { MACE_UNUSED(context); const Tensor *input = this->Input(0); const Tensor *size = this->Input(1); Tensor::MappingGuard size_mapper(size); Tensor *output = this->Output(0); MACE_CHECK(input->dim_size() == 4 && size->dim_size() == 1, "input must be 4-dimensional and size must be 1-dimensional. ", input->dim_size(), size->dim_size()); const index_t batch = input->dim(0); const index_t channels = input->dim(1); const index_t in_height = input->dim(2); const index_t in_width = input->dim(3); const index_t out_height = size->data<int32_t>()[0]; const index_t out_width = size->data<int32_t>()[1]; MACE_CHECK(out_height > 0 && out_width > 0, out_height, out_width); std::vector<index_t> out_shape{batch, channels, out_height, out_width}; MACE_RETURN_IF_ERROR(output->Resize(out_shape)); Tensor::MappingGuard input_mapper(input); Tensor::MappingGuard output_mapper(output); const T *input_data = input->data<T>(); T *output_data = output->mutable_data<T>(); if (out_height == in_height && out_width == in_width) { std::copy(input_data, input_data + batch * channels * in_height * in_width, output_data); return MaceStatus::MACE_SUCCESS; } float height_scale = common::utils::CalculateResizeScale(in_height, out_height, align_corners_); float width_scale = common::utils::CalculateResizeScale(in_width, out_width, align_corners_); ResizeImageNCHW(context, input_data, batch, in_height, in_width, out_height, out_width, channels, height_scale, width_scale, align_corners_, output_data); return MaceStatus::MACE_SUCCESS; } private: bool align_corners_; }; #ifdef MACE_ENABLE_OPENCL template<> class ResizeNearestNeighborOp<DeviceType::GPU, float> : public Operation { public: explicit ResizeNearestNeighborOp(OpConstructContext *context) : Operation(context), dim_(Operation::GetRepeatedArgs<index_t>("dim")) { bool align_corners = Operation::GetOptionalArg<bool>( "align_corners", false); if (context->GetOpMemoryType() == MemoryType::GPU_IMAGE) { kernel_ = make_unique<opencl::image::ResizeNearestNeighborKernel>( align_corners); } else { MACE_NOT_IMPLEMENTED; } } MaceStatus Run(OpContext *context) override { const Tensor *input = this->Input(0); const Tensor *size = this->Input(1); Tensor *output = this->Output(0); MACE_CHECK(input->dim_size() == 4 && size->dim_size() == 1, "input must be 4-dimensional and size must be 1-dimensional.", input->dim_size(), size->dim_size()); return kernel_->Compute(context, input, size, dim_, output); } private: std::vector<index_t> dim_; std::unique_ptr<OpenCLResizeNearestNeighborKernel> kernel_; }; #endif // MACE_ENABLE_OPENCL void RegisterResizeNearestNeighbor(OpRegistryBase *op_registry) { MACE_REGISTER_OP(op_registry, "ResizeNearestNeighbor", ResizeNearestNeighborOp, DeviceType::CPU, float); MACE_REGISTER_GPU_OP(op_registry, "ResizeNearestNeighbor", ResizeNearestNeighborOp); } } // namespace ops } // namespace mace
37.551351
80
0.596948
[ "vector" ]
6acac8f6fd5bdfc3d50fedd25d9e440e1b3e7e50
9,981
cpp
C++
Compressonator/Applications/CompressonatorGUI/Components/acProgressDlg.cpp
thaeseler-amd/compressonator
414296d1c62a8b6950aae7db741ab6a3efca69e3
[ "MIT" ]
null
null
null
Compressonator/Applications/CompressonatorGUI/Components/acProgressDlg.cpp
thaeseler-amd/compressonator
414296d1c62a8b6950aae7db741ab6a3efca69e3
[ "MIT" ]
null
null
null
Compressonator/Applications/CompressonatorGUI/Components/acProgressDlg.cpp
thaeseler-amd/compressonator
414296d1c62a8b6950aae7db741ab6a3efca69e3
[ "MIT" ]
null
null
null
//================================================================================== // Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved. // /// \author AMD Developer Tools Team /// \file acProgressDlg.cpp /// //================================================================================== //#include <acDisplay.h> #include "acProgressDlg.h" #include "acProgressAnimationWidget.h" #include <QtWidgets> // Infra: #include <assert.h> #define AC_PROGRESSDLG_DEAFULT_HRADER "Loading" #define AC_PROGRESSDLG_DEAFULT_MSG "Please wait..." #define AC_PROGRESSBAR_REFRESH_RATE_WITH_CANCEL 50 #define AC_PROGRESSBAR_REFRESH_RATE_NO_CANCEL 200 #define AC_PROGRESSBAR_MIN_WIDTH 520 #define AC_PROGRESSBAR_MIN_HEIGHT 150 #define AC_PROGRESSBAR_MAX_WIDTH 620 #define AC_SOURCE_CODE_EDITOR_MARGIN_BG_COLOR QColor(240, 240, 240, 255) acProgressDlg::acProgressDlg(QWidget* parent) : QDialog(parent, Qt::SubWindow), m_pPercentageLabel(nullptr), m_pHeaderLabel(nullptr), m_pMsgLabel(nullptr), m_pCancelButton(nullptr), m_pProgressAnimationWidget(nullptr), m_showPercentage(false), m_lastTimeMsec(0), m_forceDraw(false), m_mouseDown(false) { Init(); } acProgressDlg::~acProgressDlg() { Cleanup(); } void acProgressDlg::Init() { // logical members m_minimum = 0; m_maximum = 100; m_currentProgress = 0; m_currentPercentageProgress = 0; m_cancellationFlag = false; m_showCancelButton = false; // GUI //setMinimumHeight(acScaleSignedPixelSizeToDisplayDPI(AC_PROGRESSBAR_MIN_HEIGHT)); //150 //setMinimumWidth(acScaleSignedPixelSizeToDisplayDPI(AC_PROGRESSBAR_MIN_WIDTH)); //520 //setMaximumWidth(acScaleSignedPixelSizeToDisplayDPI(AC_PROGRESSBAR_MAX_WIDTH)); //620 setMinimumHeight(150); setMinimumWidth(520); setMaximumWidth(620); setStyleSheet(QString("QDialog{border:1px solid gray; background-color: %1;}").arg(AC_SOURCE_CODE_EDITOR_MARGIN_BG_COLOR.name())); m_pPercentageLabel = new QLabel; m_pHeaderLabel = new QLabel; QFont font; font.setPointSize(12); font.setBold(true); font.setWeight(75); m_pHeaderLabel->setFont(font); m_pMsgLabel = new QLabel; m_pCancelButton = new QPushButton; QFont fontNumbers; fontNumbers.setPointSize(11); fontNumbers.setBold(true); m_pPercentageLabel->setFont(fontNumbers); m_pPercentageLabel->setVisible(m_showPercentage); m_pPercentageLabel->setAlignment(Qt::AlignCenter | Qt::AlignVCenter); m_pPercentageLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); m_pHeaderLabel->setText(QApplication::translate("acProgressDlg", AC_PROGRESSDLG_DEAFULT_HRADER, 0)); m_pHeaderLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_pMsgLabel->setText(QApplication::translate("acProgressDlg", AC_PROGRESSDLG_DEAFULT_MSG, 0)); m_pMsgLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_pMsgLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); m_pCancelButton->setText(QApplication::translate("acProgressDlg", "&Cancel", 0)); m_pCancelButton->setStyleSheet("QPushButton{ border:1px solid gray; border-radius: 2px; width: 75px; height: 20px;} QPushButton::hover{ border:1px solid gray; border-radius: 2px; background-color: lightgray;}"); m_pProgressAnimationWidget = new acProgressAnimationWidget(this); m_pProgressAnimationWidget->setMinimumSize(QSize(80, 80)); m_pProgressAnimationWidget->SetColor(QColor(99, 100, 102, 0xff)); QHBoxLayout* pHLayout = new QHBoxLayout; QVBoxLayout* pLeftVLayout = new QVBoxLayout; QVBoxLayout* pRightVLayout = new QVBoxLayout; pLeftVLayout->addSpacing(15); pLeftVLayout->addWidget(m_pProgressAnimationWidget, 0, Qt::AlignCenter); pLeftVLayout->addWidget(m_pPercentageLabel, 0, Qt::AlignCenter); pLeftVLayout->addSpacing(15); pRightVLayout->addSpacing(15); pRightVLayout->addWidget(m_pHeaderLabel); pRightVLayout->addWidget(m_pMsgLabel, 1, Qt::AlignTop); pRightVLayout->addStretch(); pHLayout->addLayout(pLeftVLayout); pHLayout->addSpacing(15); pHLayout->addLayout(pRightVLayout); pHLayout->addStretch(); pHLayout->addWidget(m_pCancelButton, 0, Qt::AlignBottom); setLayout(pHLayout); Qt::WindowFlags flags = windowFlags(); setWindowFlags(flags | Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); m_pCancelButton->setVisible(false); m_refreshRateMsec = AC_PROGRESSBAR_REFRESH_RATE_NO_CANCEL; QMetaObject::connectSlotsByName(this); } void acProgressDlg::Cleanup() { if (m_showCancelButton) { DisconnectCancelEvents(); } if (m_pProgressAnimationWidget) { delete m_pProgressAnimationWidget; m_pProgressAnimationWidget = nullptr; } } void acProgressDlg::Increment(unsigned int numSteps) { SetValue(m_currentProgress + numSteps); } void acProgressDlg::SetValue(unsigned int value) { m_currentProgress = qMin(m_maximum, value); int elapsedMsecs = m_refreshTimer.elapsed(); unsigned int percentageProgress = (m_maximum) ? (int)(100.f * ((float)m_currentProgress / (float)m_maximum)) : 0; if (m_forceDraw || ( (elapsedMsecs >= m_refreshRateMsec) && (m_currentPercentageProgress != percentageProgress) ) ) { m_forceDraw = false; m_refreshTimer.restart(); if(m_pPercentageLabel != nullptr && m_pProgressAnimationWidget != nullptr) { if (percentageProgress > 0) { QString percentage = " " + (QString::number(percentageProgress)) + "% "; m_pPercentageLabel->setText(QApplication::translate("acProgressDlg", percentage.toStdString().c_str(), 0)); } else m_pPercentageLabel->setText(""); m_currentPercentageProgress = percentageProgress; m_pProgressAnimationWidget->SetProgressValue(percentageProgress); } repaint(); qApp->processEvents(); // keep UI responsive } } unsigned int acProgressDlg::Value()const { return m_currentProgress; } unsigned int acProgressDlg::RangeMax()const { return m_maximum; } void acProgressDlg::SetLabelText(const QString& text) { if (m_pMsgLabel != nullptr) { m_pMsgLabel->setText(text); } } void acProgressDlg::GetLabelText(QString& text) const { if (m_pMsgLabel != nullptr) { text = m_pMsgLabel->text(); } else { text.clear(); } } void acProgressDlg::SetHeader(const QString& text) { if(m_pHeaderLabel != nullptr) { m_pHeaderLabel->setText(text); } } void acProgressDlg::ShowCancelButton(bool showCancel, funcPtr func) { if(m_pCancelButton != nullptr) { m_pCancelButton->setVisible(showCancel); if (showCancel) { m_cancel_callbackfunc = func; ConnectCancelEvents(); } else { DisconnectCancelEvents(); m_cancel_callbackfunc = nullptr; } m_showCancelButton = showCancel; } m_refreshRateMsec = (m_showCancelButton ? AC_PROGRESSBAR_REFRESH_RATE_WITH_CANCEL : AC_PROGRESSBAR_REFRESH_RATE_NO_CANCEL); } void acProgressDlg::SetRange(unsigned int min, unsigned int max) { m_minimum = min; m_maximum = max; if(m_pPercentageLabel != nullptr) { m_pPercentageLabel->setVisible(true); } } void acProgressDlg::DisconnectCancelEvents() { if((m_pCancelButton != nullptr) && (m_pProgressAnimationWidget != nullptr)) { QObject::disconnect(m_pCancelButton, SIGNAL(clicked(bool)), m_pProgressAnimationWidget, SLOT(StopAnimation())); QObject::disconnect(m_pCancelButton, SIGNAL(clicked(bool)), this, SLOT(cancel())); QObject::disconnect(m_pCancelButton, SIGNAL(released()), this, SLOT(cancel())); QObject::disconnect(m_pCancelButton, SIGNAL(clicked(bool)), this, SIGNAL(canceled())); } } void acProgressDlg::ConnectCancelEvents() { if((m_pCancelButton != nullptr) && (m_pProgressAnimationWidget != nullptr)) { bool rc = QObject::connect(m_pCancelButton, SIGNAL(clicked(bool)), m_pProgressAnimationWidget, SLOT(StopAnimation())); assert(rc); rc = QObject::connect(m_pCancelButton, SIGNAL(clicked(bool)), this, SLOT(cancel())); assert(rc); rc = QObject::connect(m_pCancelButton, SIGNAL(released()), this, SLOT(cancel())); assert(rc); rc = QObject::connect(m_pCancelButton, SIGNAL(clicked(bool)), this, SIGNAL(canceled())); assert(rc); } } void acProgressDlg::mousePressEvent(QMouseEvent* e) { Q_UNUSED(e); m_mouseDown = true; } void acProgressDlg::mouseMoveEvent(QMouseEvent* pEvent) { if (m_mouseDown && (pEvent != nullptr)) { QPoint clickPos = pEvent->globalPos(); move(clickPos); } } void acProgressDlg::mouseReleaseEvent(QMouseEvent* e) { Q_UNUSED(e) m_mouseDown = false; } void acProgressDlg::cancel() { if (m_cancel_callbackfunc != nullptr) { m_cancel_callbackfunc(); } m_cancellationFlag = true; close(); } void acProgressDlg::reset() { m_currentProgress = m_minimum; m_currentPercentageProgress = 0; m_cancellationFlag = false; show(); } bool acProgressDlg::WasCanceled() const { return m_cancellationFlag; } void acProgressDlg::closeEvent(QCloseEvent* e) { emit canceled(); QDialog::closeEvent(e); } void acProgressDlg::show() { if(m_pProgressAnimationWidget != nullptr) { if (m_pProgressAnimationWidget->IsAnimationStarted() == false) { m_pProgressAnimationWidget->StartAnimation(); m_refreshTimer.start(); m_forceDraw = true; } } QDialog::show(); } void acProgressDlg::hide() { if(m_pProgressAnimationWidget != nullptr) { m_pProgressAnimationWidget->StopAnimation(); } QDialog::hide(); }
28.681034
259
0.682397
[ "solid" ]