hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
6adecafe2b758935fe01c35eb3c3f679b3d86ebe
3,146
cpp
C++
catboost/cuda/cuda_lib/cuda_manager.cpp
mityada/test2
00df18ecbac8fb724c06b68474df067e81a3d7dd
[ "Apache-2.0" ]
null
null
null
catboost/cuda/cuda_lib/cuda_manager.cpp
mityada/test2
00df18ecbac8fb724c06b68474df067e81a3d7dd
[ "Apache-2.0" ]
null
null
null
catboost/cuda/cuda_lib/cuda_manager.cpp
mityada/test2
00df18ecbac8fb724c06b68474df067e81a3d7dd
[ "Apache-2.0" ]
1
2018-08-06T14:13:12.000Z
2018-08-06T14:13:12.000Z
#include "cuda_manager.h" #include "cuda_profiler.h" #include <catboost/cuda/cuda_lib/tasks_impl/single_host_memory_copy_tasks.h> using namespace NCudaLib; void TCudaManager::CreateProfiler() { Profiler = new TCudaProfiler; } TCudaManager::~TCudaManager() { Y_VERIFY(Profiler == nullptr, "Reset profile before stopping cuda manager"); } void TCudaManager::ResetProfiler(bool printInfo) { if (Profiler) { if (printInfo) { Profiler->PrintInfo(); } delete Profiler; Profiler = nullptr; } } void TCudaManager::SyncStream(ui32 stream) { TSingleHostStreamSync streamSync(stream); for (auto dev : DevicesList) { streamSync.AddDevice(GetState().Devices[dev]); } streamSync(); } void TCudaManager::DumpFreeMemory(TString message) const { GetCudaManager().WaitComplete(); MATRIXNET_INFO_LOG << message << Endl; for (ui32 dev = 0; dev < GetDeviceCount(); ++dev) { auto devPtr = GetState().Devices[dev]; const double totalMb = devPtr->GetGpuRamSize() * 1.0 / 1024 / 1024; const double freeMb = devPtr->GetFreeMemorySize() * 1.0 / 1024 / 1024; MATRIXNET_INFO_LOG << " Device memory #" << dev << " " << freeMb << " / " << totalMb << Endl; } } double TCudaManager::TotalMemoryMb(ui32 devId) const { auto devPtr = GetState().Devices[devId]; return devPtr->GetGpuRamSize() * 1.0 / 1024 / 1024; } double TCudaManager::MinFreeMemoryFraction() const { GetCudaManager().WaitComplete(); double min = 1.0; for (ui32 dev = 0; dev < GetDeviceCount(); ++dev) { auto devPtr = GetState().Devices[dev]; const double totalMb = devPtr->GetGpuRamSize() * 1.0 / 1024 / 1024; const double freeMb = devPtr->GetFreeMemorySize() * 1.0 / 1024 / 1024; min = Min<double>(min, freeMb / totalMb); } return min; } double TCudaManager::FreeMemoryMb(ui32 deviceId, bool waitComplete) const { if (waitComplete) { GetCudaManager().WaitComplete(); } auto devPtr = GetState().Devices[deviceId]; return devPtr->GetFreeMemorySize() * 1.0 / 1024 / 1024; } void TCudaManager::StopChild() { CB_ENSURE(IsChildManager); CB_ENSURE(ParentProfiler != nullptr); WaitComplete(); //add stats from child to parent { TGuard<TAdaptiveLock> guard(GetState().Lock); ParentProfiler->Add(*Profiler); } ResetProfiler(false); State = nullptr; OnStopChildEvent.Signal(); } void TCudaManager::StartChild(TCudaManager& parent, const TDevicesList& devices, TAutoEvent& stopEvent) { CB_ENSURE(!State, "Error: can't start, state already exists"); State = parent.State; IsChildManager = true; DevicesList = devices; OnStopChildEvent = stopEvent; IsActiveDevice.resize(GetDeviceCount(), false); for (auto& dev : devices) { IsActiveDevice[dev] = true; } CreateProfiler(); GetProfiler().SetDefaultProfileMode(parent.GetProfiler().GetDefaultProfileMode()); ParentProfiler = &parent.GetProfiler(); }
31.148515
104
0.641132
mityada
6adf152f2f8e2fc78e4b5a2d28a2b547d5c487dd
2,602
cpp
C++
src/runtime_src/core/pcie/common/system_pcie.cpp
cellery/XRT
a5c908d18dd8cd99d922ec8c847f869477d21079
[ "Apache-2.0" ]
null
null
null
src/runtime_src/core/pcie/common/system_pcie.cpp
cellery/XRT
a5c908d18dd8cd99d922ec8c847f869477d21079
[ "Apache-2.0" ]
null
null
null
src/runtime_src/core/pcie/common/system_pcie.cpp
cellery/XRT
a5c908d18dd8cd99d922ec8c847f869477d21079
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2019 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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 "system_pcie.h" namespace xrt_core { void system_pcie:: get_devices(boost::property_tree::ptree& pt) const { auto cards = get_total_devices(); using index_type = decltype(cards.first); boost::property_tree::ptree pt_devices; for (index_type device_id = 0; device_id < cards.first; ++device_id) { boost::property_tree::ptree pt_device; // Key: device_id pt_device.put("device_id", std::to_string(device_id)); // Key: pcie auto device = get_userpf_device(device_id); boost::property_tree::ptree pt_pcie; device->get_info(pt_pcie); pt_device.add_child("pcie", pt_pcie); // Create our array of data pt_devices.push_back(std::make_pair("", pt_device)); } pt.add_child("devices", pt_devices); } uint16_t system_pcie:: bdf2index(const std::string& bdfStr) const { // Extract bdf from bdfStr. int dom = 0, b= 0, d = 0, f = 0; char dummy; std::stringstream s(bdfStr); size_t n = std::count(bdfStr.begin(), bdfStr.end(), ':'); if (n == 1) s >> std::hex >> b >> dummy >> d >> dummy >> f; else if (n == 2) s >> std::hex >> dom >> dummy >> b >> dummy >> d >> dummy >> f; if ((n != 1 && n != 2) || s.fail()) { std::string errMsg = boost::str( boost::format("Can't extract BDF from '%s'") % bdfStr); throw error(errMsg); } for (uint16_t i = 0; i < get_total_devices(false).first; i++) { auto device = get_mgmtpf_device(i); boost::any bus, dev, func; device->query(xrt_core::device::QR_PCIE_BDF_BUS, typeid(b), bus); if (b != boost::any_cast<uint16_t>(bus)) continue; device->query(xrt_core::device::QR_PCIE_BDF_DEVICE, typeid(d), dev); if (d != boost::any_cast<uint16_t>(dev)) continue; device->query(xrt_core::device::QR_PCIE_BDF_FUNCTION, typeid(f), func); if (f != boost::any_cast<uint16_t>(func)) continue; return i; } std::string errMsg = boost::str( boost::format("No mgmt PF found for '%s'") % bdfStr); throw error(errMsg); } } // xrt_core
28.911111
92
0.656034
cellery
6ae0da4e82f7f4bbb6f49165dad6999532ebeea9
211
hpp
C++
include/generic/math/algorithm.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
4
2022-01-06T14:06:03.000Z
2022-01-07T01:13:58.000Z
include/generic/math/algorithm.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
null
null
null
include/generic/math/algorithm.hpp
shikanle/gfx
772db3ddd66c294beaf17319f6b3803abe3ce0df
[ "Apache-2.0" ]
null
null
null
#pragma once namespace gfx { namespace generic { template <typename float_system> class algorithm { public: typedef float_system float_system_t; typedef typename float_system::float_t float_t; }; } }
14.066667
51
0.758294
shikanle
6ae1a9022737b064b4d83fedb92ce2e5ee877405
852
cpp
C++
ONLINE JUDGE/LeetCode/#84-Largest_area_Histogram.cpp
theneek14/C-plus-plus-Algorithms
ee265db0f24fcc91c8df0c5c584b651e07c4886e
[ "MIT" ]
21
2020-10-03T03:57:19.000Z
2022-03-25T22:41:05.000Z
ONLINE JUDGE/LeetCode/#84-Largest_area_Histogram.cpp
theneek14/C-plus-plus-Algorithms
ee265db0f24fcc91c8df0c5c584b651e07c4886e
[ "MIT" ]
40
2020-10-02T07:02:34.000Z
2021-10-30T16:00:07.000Z
ONLINE JUDGE/LeetCode/#84-Largest_area_Histogram.cpp
theneek14/C-plus-plus-Algorithms
ee265db0f24fcc91c8df0c5c584b651e07c4886e
[ "MIT" ]
90
2020-10-02T07:06:22.000Z
2022-03-25T22:41:17.000Z
//https://leetcode.com/problems/largest-rectangle-in-histogram/ class Solution { public: int largestRectangleArea(vector<int>& heights) { stack<int>s; int area_with_top=0; int area=0; int i=0; int n=heights.size(); while(i<n){ if(s.empty() || heights[s.top()]<=heights[i]){ s.push(i++); } else{ int tp=s.top(); s.pop(); area_with_top=heights[tp]*(s.empty()?i:i-s.top()-1); if(area<area_with_top) area=area_with_top; } } while(!s.empty()){ int tp=s.top(); s.pop(); area_with_top=heights[tp]*(s.empty()?i:i-s.top()-1); area=max(area,area_with_top); } return area; } };
26.625
68
0.450704
theneek14
6aebe6525be97d55d023b8dcf1e00f5e12668c45
3,278
cpp
C++
Source/bin/opennwa/print-stats.cpp
jusito/WALi-OpenNWA
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
[ "MIT" ]
15
2015-03-07T17:25:57.000Z
2022-02-04T20:17:00.000Z
src/wpds/Source/bin/opennwa/print-stats.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
1
2018-03-03T05:58:55.000Z
2018-03-03T12:26:10.000Z
src/wpds/Source/bin/opennwa/print-stats.cpp
ucd-plse/mpi-error-prop
4367df88bcdc4d82c9a65b181d0e639d04962503
[ "BSD-3-Clause" ]
15
2015-09-25T17:44:35.000Z
2021-07-18T18:25:38.000Z
#include <iostream> #include <vector> #include <string> #include <cstdlib> #include <fstream> #include "opennwa/Nwa.hpp" #include "opennwa/NwaParser.hpp" #include "opennwa/query/automaton.hpp" using std::string; using std::ifstream; using std::ofstream; using std::cout; using std::cerr; using std::endl; using std::exit; using namespace opennwa::query; int main(int argc, char** argv) { if (argc != 2 && argc != 3) { cerr << "Syntax: " << argv[0] << " [--json] nwafilename\n"; exit(1); } if (argc == 3 && argv[1] != string("--json")) { cerr << "Syntax: " << argv[0] << " [--json] nwafilename\n"; exit(1); } // Open the file ifstream infile(argv[argc-1]); if (!infile.good()) { cerr << "Error opening input file " << argv[argc-1] << "\n"; exit(2); } opennwa::NwaRefPtr nwa = opennwa::read_nwa(infile); if (argc == 2) { // Print "human readable" std::cout << "Number of states: " << nwa->sizeStates() << "\n"; std::cout << " initials: " << nwa->sizeInitialStates() << "\n"; std::cout << " accepting: " << nwa->sizeFinalStates() << "\n"; std::cout << " call sites: " << numCallSites(*nwa) << "\n"; std::cout << " entry sites: " << numEntrySites(*nwa) << "\n"; std::cout << " exit sites: " << numExitSites(*nwa) << "\n"; std::cout << " return sites: " << numReturnSites(*nwa) << "\n"; std::cout << "\n"; std::cout << "Number of symbols: " << nwa->sizeSymbols() << "\n"; std::cout << "\n"; std::cout << "Number of transitions: " << nwa->sizeTrans() << "\n"; std::cout << " internals: " << nwa->sizeInternalTrans() << "\n"; std::cout << " calls: " << nwa->sizeCallTrans() << "\n"; std::cout << " returns: " << nwa->sizeReturnTrans() << "\n"; } else { // Print JSON std::cout << "{\n"; std::cout << " \"count_states\": " << nwa->sizeStates() << "\n"; std::cout << " \"count_initial_states\": " << nwa->sizeInitialStates() << "\n"; std::cout << " \"count_accepting_states\": " << nwa->sizeFinalStates() << "\n"; std::cout << " \"count_call_sites\": " << numCallSites(*nwa) << "\n"; std::cout << " \"count_entry_sites\": " << numEntrySites(*nwa) << "\n"; std::cout << " \"count_exit_sites\": " << numExitSites(*nwa) << "\n"; std::cout << " \"count_return_sites\": " << numReturnSites(*nwa) << "\n"; std::cout << " \"count_symbols\": " << nwa->sizeSymbols() << "\n"; std::cout << " \"count_internals\": " << nwa->sizeInternalTrans() << "\n"; std::cout << " \"count_calls\": " << nwa->sizeCallTrans() << "\n"; std::cout << " \"count_returns\": " << nwa->sizeReturnTrans() << "\n"; std::cout << "}\n"; } } // Yo emacs! // Local Variables: // c-basic-offset: 4 // indent-tabs-mode: nil // End:
38.116279
97
0.458206
jusito
6aedd8614c34c50d9a153f367f5d6875ff09208c
7,512
cpp
C++
tests/envelope/envelope_segment_tests.cpp
Frank-Krick/fr-musp
4f8f8e4764fd411158e63e4b37d6285d8e1a2885
[ "MIT" ]
null
null
null
tests/envelope/envelope_segment_tests.cpp
Frank-Krick/fr-musp
4f8f8e4764fd411158e63e4b37d6285d8e1a2885
[ "MIT" ]
null
null
null
tests/envelope/envelope_segment_tests.cpp
Frank-Krick/fr-musp
4f8f8e4764fd411158e63e4b37d6285d8e1a2885
[ "MIT" ]
null
null
null
#include <catch2/catch_test_macros.hpp> #include <fr_musp/envelope/envelope_segment.h> using namespace fr_musp::envelope; using namespace std::chrono; using namespace Catch; TEST_CASE("The empty envelope segment") { EnvelopeSegment envelopeSegment; SECTION("Should be size 0") { REQUIRE(envelopeSegment.size() == 0); } SECTION("Should signal if it's empty") { REQUIRE(envelopeSegment.empty()); } } TEST_CASE("The envelope segment containing a constant") { milliseconds length(1000); unsigned int sampleRate(40000); Constant constant(length, sampleRate); SECTION("Should not be empty") { EnvelopeSegment envelopeSegment(constant, 0.0f, 0.0f); REQUIRE_FALSE(envelopeSegment.empty()); } SECTION("Should scale an envelope") { float scale(0.5f); EnvelopeSegment envelopeSegment(constant, scale, 0.0f); for (int i = 0; i < sampleRate; i++) { REQUIRE(envelopeSegment[i] == 0.5f); } } SECTION("Should offset an envelope") { float scale(1.0f); float offset(0.5f); EnvelopeSegment envelopeSegment(constant, scale, offset); for (int i = 0; i < sampleRate; i++) { REQUIRE(envelopeSegment[i] == 1.5f); } } SECTION("Should do both") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(constant, scale, offset); for (int i = 0; i < sampleRate; i++) { REQUIRE(envelopeSegment[i] == 4.5f); } } SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(constant, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(constant[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the exponential fall") { milliseconds length(1000); unsigned int sampleRate(40000); float curvature(4); ExponentialFall exponentialFall(length, curvature, sampleRate); SECTION("Should scale and offset the envelope") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(exponentialFall, scale, offset); REQUIRE(envelopeSegment[0] == 4.5f); } SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(exponentialFall, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(exponentialFall[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the exponential rise") { milliseconds length(1000); unsigned int sampleRate(40000); float curvature(4); ExponentialRise exponentialRise(length, curvature, sampleRate); SECTION("Should scale and offset the envelope") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(exponentialRise, scale, offset); REQUIRE(envelopeSegment[39999] == 4.5f); } SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(exponentialRise, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(exponentialRise[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the inverted ramp") { milliseconds length(1000); unsigned int sampleRate(40000); InvertedRamp invertedRamp(length, sampleRate); SECTION("Should scale and offset the envelope") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(invertedRamp, scale, offset); REQUIRE(envelopeSegment[39999] == 0.5f); } SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(invertedRamp, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(invertedRamp[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the logarithmic fall") { milliseconds length(1000); unsigned int sampleRate(40000); float curvature(2.0f); LogarithmicFall logarithmicFall(length, curvature, sampleRate); SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(logarithmicFall, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(logarithmicFall[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the logarithmic rise") { milliseconds length(1000); unsigned int sampleRate(40000); float curvature(2.0f); LogarithmicRise logarithmicRise(length, curvature, sampleRate); SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(logarithmicRise, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(logarithmicRise[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the pulse") { milliseconds length(1000); unsigned int sampleRate(40000); float curvature(2.0f); Pulse pulse(length, curvature, sampleRate); SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(pulse, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(pulse[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the ramp") { milliseconds length(1000); unsigned int sampleRate(40000); Ramp ramp(length, sampleRate); SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(ramp, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(ramp[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the triangle") { milliseconds length(1000); unsigned int sampleRate(40000); Triangle triangle(length, sampleRate); SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(triangle, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(triangle[index] * scale + offset == value); index++; } } } TEST_CASE("The envelope segment containing the inverted triangle") { milliseconds length(1000); unsigned int sampleRate(40000); InvertedTriangle invertedTriangle(length, sampleRate); SECTION("Should be iterable") { float offset(0.5f); float scale(4.0f); EnvelopeSegment envelopeSegment(invertedTriangle, scale, offset); unsigned int index{}; for (auto value : envelopeSegment) { REQUIRE(invertedTriangle[index] * scale + offset == value); index++; } } }
30.536585
73
0.622737
Frank-Krick
6aeec1f47e524c8b0b28f947348e2e59f4cd7de3
1,177
cpp
C++
tests/utils/test_partitioning.cpp
FreshDISKANN/FreshDISKANN
c7750ed7ae2df202b3f3a98477199963245c8ba7
[ "MIT" ]
6
2020-10-13T11:30:53.000Z
2021-12-03T15:50:15.000Z
tests/utils/test_partitioning.cpp
FreshDISKANN/FreshDISKANN
c7750ed7ae2df202b3f3a98477199963245c8ba7
[ "MIT" ]
null
null
null
tests/utils/test_partitioning.cpp
FreshDISKANN/FreshDISKANN
c7750ed7ae2df202b3f3a98477199963245c8ba7
[ "MIT" ]
3
2020-10-13T11:30:55.000Z
2021-12-02T14:29:42.000Z
//#include <distances.h> //#include <indexing.h> #include <index.h> #include <math_utils.h> #include "partition_and_pq.h" // DEPRECATED: NEED TO REPROGRAM int main(int argc, char** argv) { auto s = std::chrono::high_resolution_clock::now(); if (argc != 8) { std::cout << argv[0] << " format: data type <int8/uint8/float> base_set train_set " "num_clusters " "max_reps prefix_for_working_directory k_base " << std::endl; exit(-1); } size_t num_clusters = std::atoi(argv[4]); size_t max_reps = std::atoi(argv[5]); size_t k_base = std::atoi(argv[7]); if (std::string(argv[1]) == std::string("float")) partition<float>(argv[2], argv[3], num_clusters, max_reps, argv[6], k_base); else if (std::string(argv[1]) == std::string("int8")) partition<int8_t>(argv[2], argv[3], num_clusters, max_reps, argv[6], k_base); else if (std::string(argv[1]) == std::string("uint8")) partition<uint8_t>(argv[2], argv[3], num_clusters, max_reps, argv[6], k_base); else std::cout << "unsupported data format. use float/int8/uint8" << std::endl; }
34.617647
80
0.598131
FreshDISKANN
6aef1dd615b2fcaa3338b0757aeccf81676b8146
845
cpp
C++
Aoba/src/Constraint/Constraint.cpp
KondoA9/OpenSiv3d-GUIKit
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
null
null
null
Aoba/src/Constraint/Constraint.cpp
KondoA9/OpenSiv3d-GUIKit
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
32
2021-10-09T10:04:11.000Z
2022-02-25T06:10:13.000Z
Aoba/src/Constraint/Constraint.cpp
athnomedical/Aoba
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
null
null
null
#include "Aoba/Constraint.hpp" namespace s3d::aoba { void Constraint::setConstraint(double constant, double multiplier) { m_constant = constant; m_multiplier = multiplier; m_exists = true; } void Constraint::setConstraint(double* const watchingValue, double constant, double multiplier) { m_watchingValue = watchingValue; setConstraint(constant, multiplier); } void Constraint::setConstraint(const std::function<double()>& func, double constant, double multiplier) { m_func = func; setConstraint(constant, multiplier); } void Constraint::removeConstraint() { m_exists = false; m_func = std::function<double()>(); m_watchingValue = nullptr; m_constant = 0.0; m_multiplier = 1.0; } }
30.178571
109
0.623669
KondoA9
6af04d8ebae37eb836509402d8cec780054ef609
6,081
cpp
C++
test/test_parallel.cpp
melven/pitts
491f503a99a7d1161a27672955ae53ca6b5d3412
[ "BSD-3-Clause" ]
2
2021-12-31T08:28:17.000Z
2022-01-12T14:48:49.000Z
test/test_parallel.cpp
melven/pitts
491f503a99a7d1161a27672955ae53ca6b5d3412
[ "BSD-3-Clause" ]
null
null
null
test/test_parallel.cpp
melven/pitts
491f503a99a7d1161a27672955ae53ca6b5d3412
[ "BSD-3-Clause" ]
null
null
null
#include <gtest/gtest.h> #include "pitts_parallel.hpp" namespace { // helper function to determine the currently default number of threads in a parallel region int get_default_num_threads() { int numThreads = 1; #pragma omp parallel { #pragma omp critical (PITTS_TEST_PARALLEL) numThreads = omp_get_num_threads(); } return numThreads; } } TEST(PITTS_Parallel, ompThreadInfo_serial) { ASSERT_LE(4, omp_get_max_threads()); const auto& [iThread,nThreads] = PITTS::internal::parallel::ompThreadInfo(); EXPECT_EQ(0, iThread); EXPECT_EQ(1, nThreads); } TEST(PITTS_Parallel, ompThreadInfo) { ASSERT_LE(4, omp_get_max_threads()); const auto nThreadsDefault = get_default_num_threads(); ASSERT_LE(4, nThreadsDefault); std::vector<int> iThreads(nThreadsDefault); std::vector<int> nThreads(nThreadsDefault); #pragma omp parallel for schedule(static) for(int i = 0; i < nThreadsDefault; i++) { const auto& [iT,nT] = PITTS::internal::parallel::ompThreadInfo(); iThreads[i] = iT; nThreads[i] = nT; } std::vector<int> iThreads_ref(nThreadsDefault); std::vector<int> nThreads_ref(nThreadsDefault); for(int i = 0; i < nThreadsDefault; i++) { iThreads_ref[i] = i; nThreads_ref[i] = nThreadsDefault; } EXPECT_EQ(iThreads_ref, iThreads); EXPECT_EQ(nThreads_ref, nThreads); } TEST(PITTS_Parallel, mpiProcInfo_self) { const auto& [iProc,nProcs] = PITTS::internal::parallel::mpiProcInfo(MPI_COMM_SELF); EXPECT_EQ(0, iProc); EXPECT_EQ(1, nProcs); } TEST(PITTS_Parallel, mpiProcInfo) { const auto& [iProc,nProcs] = PITTS::internal::parallel::mpiProcInfo(); int iProc_ref = 0, nProcs_ref = 1; ASSERT_EQ(MPI_SUCCESS, MPI_Comm_rank(MPI_COMM_WORLD, &iProc_ref)); ASSERT_EQ(MPI_SUCCESS, MPI_Comm_size(MPI_COMM_WORLD, &nProcs_ref)); EXPECT_EQ(iProc_ref, iProc); EXPECT_EQ(nProcs_ref, nProcs); } // depending on the MPI vendor, this just kills the process with an error message - so disable it per default... TEST(DISABLED_PITTS_Parallel, mpiProcInfo_error) { ASSERT_THROW(PITTS::internal::parallel::mpiProcInfo(MPI_COMM_NULL), std::runtime_error); } TEST(PITTS_Parallel, distribute_zeroElems) { for(int i = 0; i < 15; i++) { const auto& [firstElem,lastElem] = PITTS::internal::parallel::distribute(0, {i,15}); EXPECT_EQ(0, firstElem); EXPECT_EQ(-1, lastElem); } } TEST(PITTS_Parallel, distribute_trivial) { for(int i = 0; i < 5; i++) { const auto& [firstElem,lastElem] = PITTS::internal::parallel::distribute(15, {i,5}); EXPECT_EQ(i*3, firstElem); EXPECT_EQ((i+1)*3-1, lastElem); } } TEST(PITTS_Parallel, distribute_withRemainder) { const std::array<long long,5> nLocal = {7,7,6,6,6}; const std::array<long long,5> offsets = {0,7,14,20,26}; const long long nTotal = 7+7+6+6+6; for(int i = 0; i < 5; i++) { const auto& [firstElem,lastElem] = PITTS::internal::parallel::distribute(nTotal, {i,5}); EXPECT_EQ(offsets[i], firstElem); EXPECT_EQ(offsets[i]+nLocal[i]-1, lastElem); } } TEST(PITTS_Parallel, distribute_tooManyProcs) { for(int i = 0; i < 20; i++) { const auto& [firstElem,lastElem] = PITTS::internal::parallel::distribute(7, {i,20}); if( i < 7 ) { EXPECT_EQ(i, firstElem); EXPECT_EQ(i, lastElem); } else { EXPECT_EQ(7, firstElem); EXPECT_EQ(6, lastElem); } } } TEST(PITTS_Parallel, mpiType) { ASSERT_EQ(MPI_DOUBLE, PITTS::internal::parallel::mpiType<double>()); ASSERT_EQ(MPI_FLOAT, PITTS::internal::parallel::mpiType<float>()); ASSERT_EQ(MPI_C_DOUBLE_COMPLEX, PITTS::internal::parallel::mpiType<std::complex<double>>()); ASSERT_EQ(MPI_C_FLOAT_COMPLEX, PITTS::internal::parallel::mpiType<std::complex<float>>()); // generates a compilation error: // PITTS::internal::parallel::mpiType<int>(); } TEST(PITTS_Parallel, mpiGather) { const auto& [iProc,nProcs] = PITTS::internal::parallel::mpiProcInfo(); const std::string localData = "Hello from process " + std::to_string(iProc) + ".\n"; const int root = nProcs - 1; const auto& [globalData,offsets] = PITTS::internal::parallel::mpiGather(localData, root); std::string globalData_ref(0, '\0'); std::vector<int> offsets_ref(nProcs+1, 0); if( iProc == root ) { for(int i = 0; i < nProcs; i++) { globalData_ref += "Hello from process " + std::to_string(i) + ".\n"; offsets_ref[i+1] = globalData_ref.size(); } } EXPECT_EQ(globalData_ref, globalData); EXPECT_EQ(offsets_ref, offsets); } TEST(PITTS_Parallel, mpiCombineMaps) { using StringMap = std::unordered_map<std::string,std::string>; StringMap localMap; localMap["hello"] = "world"; const auto op = [](const std::string& s1, const std::string& s2){return s1 + " | " + s2;}; int nProcs = 1, iProc = 0; ASSERT_EQ(0, MPI_Comm_size(MPI_COMM_WORLD, &nProcs)); ASSERT_EQ(0, MPI_Comm_rank(MPI_COMM_WORLD, &iProc)); StringMap globalMap = PITTS::internal::parallel::mpiCombineMaps(localMap, op); if( iProc == 0 ) { ASSERT_EQ(1, globalMap.size()); std::string str_ref = "world"; for(int i = 1; i < nProcs; i++) str_ref = str_ref + " | world"; ASSERT_EQ(str_ref, globalMap["hello"]); } else { ASSERT_EQ(0, globalMap.size()); ASSERT_EQ(0, 0); } localMap.clear(); localMap["proc"] = std::to_string(iProc); localMap["only_local: "+std::to_string(iProc)] = "I'm here"; globalMap = PITTS::internal::parallel::mpiCombineMaps(localMap); if( iProc == 0 ) { ASSERT_EQ(1+nProcs, globalMap.size()); std::string str_ref = ""; for(int i = 0; i < nProcs; i++) str_ref = str_ref + std::to_string(i); ASSERT_EQ(str_ref, globalMap["proc"]); for(int i = 0; i < nProcs; i++) { std::string key = "only_local: " + std::to_string(i); ASSERT_EQ("I'm here", globalMap[key]); } } else { // dummy checks as all checks are global ASSERT_EQ(0, globalMap.size()); ASSERT_EQ(0, 0); for(int i = 0; i < nProcs; i++) { ASSERT_EQ(0, 0); } } }
25.766949
112
0.659924
melven
6af5230f6d4614cdc323851415a78e41522b15c9
1,431
cpp
C++
stm32f429-ram/Src/PAW_3D_Projection.cpp
sterowniki-robotow-projekt/main-repo
744252ffa1cc05c18705d3ea5ec0b725f4b62759
[ "MIT" ]
null
null
null
stm32f429-ram/Src/PAW_3D_Projection.cpp
sterowniki-robotow-projekt/main-repo
744252ffa1cc05c18705d3ea5ec0b725f4b62759
[ "MIT" ]
null
null
null
stm32f429-ram/Src/PAW_3D_Projection.cpp
sterowniki-robotow-projekt/main-repo
744252ffa1cc05c18705d3ea5ec0b725f4b62759
[ "MIT" ]
null
null
null
#include "PAW_3D_Projection.h" PAW_Vector project_3D_to_2D(const PAW_Vector point_position) { PAW_Vector r_value(4); PAW_Matrix P(4); P = projection_matrix(0.0f, 239.0f, 0.0f, 319.0f, 160.0f, 0.0f); PAW_Matrix Rx(4, 1.0f), Ry(4, 1.0f), Rz(4, 1.0f), Rx2(4, 1.0f); Rx.to_rotation_matrix(y, z, 0 * 0.0f); //x rot Ry.to_rotation_matrix(z, x, 2 * 0.0f); //y rot Rz.to_rotation_matrix(y, x, 2 * 90.0f); //z rot Rx2.to_rotation_matrix(y, z, 2 * 0.0f); //x rot PAW_Vector point_position2; point_position2 = point_position; point_position2[y] *= -1; point_position2[z] *= -1; r_value = Rz * point_position2; point_position2[y] *= -1; point_position2[z] *= -1; point_position2[y] *= -1; point_position2[z] *= -1; r_value = P * r_value; r_value += PAW_Vector(540.0f, 290.0f, 0.0f, 0.0f); r_value /= 2; std::cout << r_value; return r_value; } PAW_Matrix projection_matrix(const float left, const float right, const float top, const float bottom, const float near, const float far) { PAW_Matrix projection_matrix(4); projection_matrix[0][0] = 2 * near / (right - left); projection_matrix[0][2] = (right + left) / (right - left); projection_matrix[1][1] = 2 * near / (top - bottom); projection_matrix[1][2] = (top + bottom) / (top - bottom); projection_matrix[2][2] = -(far + near) / (far - near); projection_matrix[2][3] = -2 * far * near / (far - near); return projection_matrix; }
30.446809
137
0.658281
sterowniki-robotow-projekt
6af6955d87d82480808275c49a9b88a2f00ee55e
585
hpp
C++
include/ActuationSystem.hpp
AhmedHumais/flight_controller_temp
2836b4f99b76e856ef0ba0e7ee673669c1c3db7b
[ "BSD-3-Clause" ]
null
null
null
include/ActuationSystem.hpp
AhmedHumais/flight_controller_temp
2836b4f99b76e856ef0ba0e7ee673669c1c3db7b
[ "BSD-3-Clause" ]
null
null
null
include/ActuationSystem.hpp
AhmedHumais/flight_controller_temp
2836b4f99b76e856ef0ba0e7ee673669c1c3db7b
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "common_srv/MsgEmitter.hpp" #include "common_srv/MsgReceiver.hpp" #include "Actuator.hpp" #include <vector> #include "common_srv/Block.hpp" class ActuationSystem : public MsgEmitter, public Block{ public: virtual void receiveMsgData(DataMessage* t_msg) = 0; ActuationSystem(std::vector<Actuator*>) {}; //TODO Refactor below block_id getID() {} block_type getType() {} void switchIn(DataMessage*) {} DataMessage* switchOut() {} DataMessage* runTask(DataMessage*) {} void process(DataMessage* t_msg, Port* t_port) {} };
24.375
56
0.700855
AhmedHumais
6af9d02de8b6d27999b35e9b533fbd051c38b7b2
114
cpp
C++
unit_test/cuda/Test_Cuda_Batched_SerialMatUtil_Real.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
156
2017-03-01T23:38:10.000Z
2022-03-27T21:28:03.000Z
unit_test/cuda/Test_Cuda_Batched_SerialMatUtil_Real.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
1,257
2017-03-03T15:25:16.000Z
2022-03-31T19:46:09.000Z
unit_test/cuda/Test_Cuda_Batched_SerialMatUtil_Real.cpp
dialecticDolt/kokkos-kernels
00189c0be23a70979aeaa162f0abd4c0e4d1c479
[ "BSD-3-Clause" ]
76
2017-03-01T17:03:59.000Z
2022-03-03T21:04:41.000Z
#include "Test_Cuda.hpp" #include "Test_Batched_SerialMatUtil.hpp" #include "Test_Batched_SerialMatUtil_Real.hpp"
28.5
46
0.842105
dialecticDolt
1390a4ac5c31a33c204aaee203b53eca5dbe0338
2,539
hpp
C++
Includes/Rosetta/Battlegrounds/Cards/Card.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Includes/Rosetta/Battlegrounds/Cards/Card.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Includes/Rosetta/Battlegrounds/Cards/Card.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef ROSETTASTONE_BATTLEGROUNDS_CARD_HPP #define ROSETTASTONE_BATTLEGROUNDS_CARD_HPP #include <Rosetta/Battlegrounds/Cards/TargetingPredicates.hpp> #include <Rosetta/Battlegrounds/Enchants/Power.hpp> #include <Rosetta/Common/Enums/CardEnums.hpp> #include <Rosetta/Common/Enums/TargetingEnums.hpp> #include <map> #include <string> namespace RosettaStone::Battlegrounds { //! //! \brief Card class. //! //! This class stores card information such as attack, health and cost. //! class Card { public: //! Initializes card data. void Initialize(); //! Returns the value of card set. //! \return The value of card set. CardSet GetCardSet() const; //! Returns the value of card type. //! \return The value of card type. CardType GetCardType() const; //! Returns the value of race. //! \return The value of race. Race GetRace() const; //! Returns the value of attack. //! \return The value of attack. int GetAttack() const; //! Returns the value of health. //! \return The value of health. int GetHealth() const; //! Returns the value of tier. //! \return The value of tier. int GetTier() const; //! Gets a value indicating whether source entity is playable by card //! requirements. Static requirements are checked. //! \param player The player of the source. //! \return true if it is playable by card requirements, false otherwise. bool IsPlayableByCardReq(Player& player) const; //! Calculates if a target is valid by testing the game state //! for each hardcoded requirement. //! \param target The proposed target. //! \return true if the proposed target is valid, false otherwise. bool TargetingRequirements(Minion& target) const; std::string id; int dbfID; int normalDbfID; int premiumDbfID; std::string name; std::string text; std::map<GameTag, int> gameTags; std::map<PlayReq, int> playRequirements; std::vector<TargetingPredicate> targetingPredicate; TargetingType targetingType; Power power; bool isCurHero = false; bool isBattlegroundsPoolMinion = false; bool mustHaveToTargetToPlay = false; }; } // namespace RosettaStone::Battlegrounds #endif // ROSETTASTONE_BATTLEGROUNDS_CARD_HPP
28.211111
77
0.704608
Hearthstonepp
1392513fd74497e6282b84bbde11025458e2c6b8
8,437
cpp
C++
ui/src/audiobar.cpp
hveld/qlcplus
1dd61a5a3a2c93d7fe88cd2a90574c4849b64829
[ "Apache-2.0" ]
1
2015-03-03T17:30:10.000Z
2015-03-03T17:30:10.000Z
ui/src/audiobar.cpp
bjlupo/rcva_qlcplus
d367d33f5446c30d5201625e72946cc27f55ae5d
[ "Apache-2.0" ]
null
null
null
ui/src/audiobar.cpp
bjlupo/rcva_qlcplus
d367d33f5446c30d5201625e72946cc27f55ae5d
[ "Apache-2.0" ]
null
null
null
/* Q Light Controller Plus audiobar.cpp Copyright (c) Massimo Callegari Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QtXml> #include "audiobar.h" #include "vcbutton.h" #include "vcslider.h" #include "vcspeeddial.h" #include "vccuelist.h" #include "virtualconsole.h" AudioBar::AudioBar(int t, uchar v) { m_type = t; m_value = v; m_tapped = false; m_dmxChannels.clear(); m_absDmxChannels.clear(); m_function = NULL; m_widget = NULL; m_widgetID = VCWidget::invalidId(); m_minThreshold = 51; // 20% m_maxThreshold = 204; // 80% m_divisor = 1; m_skippedBeats = 0; } AudioBar *AudioBar::createCopy() { AudioBar *copy = new AudioBar(); copy->m_type = m_type; copy->m_value = m_value; copy->m_name = m_name; copy->m_tapped = m_tapped; copy->m_dmxChannels = m_dmxChannels; copy->m_absDmxChannels = m_absDmxChannels; copy->m_function = m_function; copy->m_widget = m_widget; copy->m_minThreshold = m_minThreshold; copy->m_maxThreshold = m_maxThreshold; copy->m_divisor = m_divisor; copy->m_skippedBeats = m_skippedBeats; return copy; } void AudioBar::setName(QString nme) { m_name = nme; } void AudioBar::setType(int type) { m_type = type; if (m_type == None) { m_value = 0; m_tapped = false; m_dmxChannels.clear(); m_absDmxChannels.clear(); m_function = NULL; m_widget = NULL; m_widgetID = VCWidget::invalidId(); m_minThreshold = 51; // 20% m_maxThreshold = 204; // 80% m_divisor = 1; m_skippedBeats = 0; } } void AudioBar::setMinThreshold(uchar value) { m_minThreshold = value; } void AudioBar::setMaxThreshold(uchar value) { m_maxThreshold = value; } void AudioBar::setDivisor(int value) { m_divisor = value; if (m_skippedBeats >= m_divisor) m_skippedBeats = 0; } void AudioBar::attachDmxChannels(Doc *doc, QList<SceneValue> list) { m_dmxChannels.clear(); m_dmxChannels = list; m_absDmxChannels.clear(); foreach(SceneValue scv, m_dmxChannels) { Fixture *fx = doc->fixture(scv.fxi); if (fx != NULL) { quint32 absAddr = fx->universeAddress() + scv.channel; m_absDmxChannels.append(absAddr); } } } void AudioBar::attachFunction(Function *func) { if (func != NULL) { qDebug() << Q_FUNC_INFO << "Attaching function:" << func->name(); m_function = func; } } void AudioBar::attachWidget(quint32 wID) { if (wID == VCWidget::invalidId()) return; qDebug() << Q_FUNC_INFO << "Attaching widget with ID" << wID; m_widgetID = wID; m_widget = NULL; m_tapped = false; } VCWidget * AudioBar::widget() { if (m_widget == NULL) m_widget = VirtualConsole::instance()->widget(m_widgetID); return m_widget; } void AudioBar::checkFunctionThresholds(Doc *doc) { if (m_function == NULL) return; if (m_value >= m_maxThreshold && m_function->isRunning() == false) m_function->start(doc->masterTimer()); else if (m_value < m_minThreshold && m_function->isRunning() == true) m_function->stop(); } void AudioBar::checkWidgetFunctionality() { if (m_widgetID == VCWidget::invalidId()) return; if (widget() == NULL) // fills m_widget if needed return; if (m_widget->type() == VCWidget::ButtonWidget) { VCButton *btn = (VCButton *)m_widget; if (m_value >= m_maxThreshold && btn->isOn() == false) btn->setOn(true); else if (m_value < m_minThreshold && btn->isOn() == true) btn->setOn(false); } else if (m_widget->type() == VCWidget::SliderWidget) { VCSlider *slider = (VCSlider *)m_widget; slider->setSliderValue(m_value); } else if (m_widget->type() == VCWidget::SpeedDialWidget) { VCSpeedDial *speedDial = (VCSpeedDial *)m_widget; if (m_value >= m_maxThreshold && !m_tapped) { if (m_skippedBeats == 0) speedDial->tap(); m_tapped = true; m_skippedBeats = (m_skippedBeats + 1) % m_divisor; } else if (m_value < m_minThreshold) { m_tapped = false; } } else if (m_widget->type() == VCWidget::CueListWidget) { VCCueList *cueList = (VCCueList *)m_widget; if (m_value >= m_maxThreshold && !m_tapped) { if (m_skippedBeats == 0) cueList->slotNextCue(); m_tapped = true; m_skippedBeats = (m_skippedBeats + 1) % m_divisor; } else if (m_value < m_minThreshold) m_tapped = false; } } void AudioBar::debugInfo() { qDebug() << "[AudioBar] " << m_name; qDebug() << " type:" << m_type << ", value:" << m_value; } bool AudioBar::loadXML(const QDomElement &root, Doc *doc) { if (root.hasAttribute(KXMLQLCAudioBarName)) m_name = root.attribute(KXMLQLCAudioBarName); if (root.hasAttribute(KXMLQLCAudioBarType)) { m_type = root.attribute(KXMLQLCAudioBarType).toInt(); m_minThreshold = root.attribute(KXMLQLCAudioBarMinThreshold).toInt(); m_maxThreshold = root.attribute(KXMLQLCAudioBarMaxThreshold).toInt(); m_divisor = root.attribute(KXMLQLCAudioBarDivisor).toInt(); if (m_type == AudioBar::DMXBar) { QDomNode node = root.firstChild(); if (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == KXMLQLCAudioBarDMXChannels) { QString dmxValues = tag.text(); if (dmxValues.isEmpty() == false) { QList<SceneValue> channels; QStringList varray = dmxValues.split(","); for (int i = 0; i < varray.count(); i+=2) { channels.append(SceneValue(QString(varray.at(i)).toUInt(), QString(varray.at(i + 1)).toUInt(), 0)); } attachDmxChannels(doc, channels); } } } } } return true; } bool AudioBar::saveXML(QDomDocument *doc, QDomElement *atf_root, QString tagName, int index) { Q_ASSERT(doc != NULL); Q_ASSERT(atf_root != NULL); qDebug() << Q_FUNC_INFO; QDomElement ab_tag = doc->createElement(tagName); ab_tag.setAttribute(KXMLQLCAudioBarName, m_name); ab_tag.setAttribute(KXMLQLCAudioBarType, m_type); ab_tag.setAttribute(KXMLQLCAudioBarMinThreshold, m_minThreshold); ab_tag.setAttribute(KXMLQLCAudioBarMaxThreshold, m_maxThreshold); ab_tag.setAttribute(KXMLQLCAudioBarDivisor, m_divisor); ab_tag.setAttribute(KXMLQLCAudioBarIndex, index); if (m_type == AudioBar::DMXBar && m_dmxChannels.count() > 0) { QDomElement dmx_tag = doc->createElement(KXMLQLCAudioBarDMXChannels); QString chans; foreach (SceneValue scv, m_dmxChannels) { if (chans.isEmpty() == false) chans.append(","); chans.append(QString("%1,%2").arg(scv.fxi).arg(scv.channel)); } if (chans.isEmpty() == false) { QDomText text = doc->createTextNode(chans); dmx_tag.appendChild(text); } ab_tag.appendChild(dmx_tag); } else if (m_type == AudioBar::FunctionBar && m_function != NULL) { ab_tag.setAttribute(KXMLQLCAudioBarFunction, m_function->id()); } else if (m_type == AudioBar::VCWidgetBar && m_widget != NULL) { ab_tag.setAttribute(KXMLQLCAudioBarWidget, m_widget->id()); } atf_root->appendChild(ab_tag); return true; }
27.937086
97
0.596065
hveld
139370d3d074b2d45342eca6ee94d72757b4e0ec
3,654
cpp
C++
src/jc/JMap.cpp
andrelo1/gotobed-ae
9b2001e89de0ac479e9b979f01fa3a6475c8cd79
[ "MIT" ]
1
2022-03-03T17:01:38.000Z
2022-03-03T17:01:38.000Z
src/jc/JMap.cpp
andrelo1/gotobed-ae
9b2001e89de0ac479e9b979f01fa3a6475c8cd79
[ "MIT" ]
null
null
null
src/jc/JMap.cpp
andrelo1/gotobed-ae
9b2001e89de0ac479e9b979f01fa3a6475c8cd79
[ "MIT" ]
null
null
null
#include "JMap.h" #include "jcapistorage.h" namespace jc::JMap { using ApiStorage = jc::api::detail::Storage; std::int32_t object(void* a_domain) { return ApiStorage::get().JMap_object(a_domain); } std::int32_t getInt(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, std::int32_t a_default) { return ApiStorage::get().JMap_getInt(a_domain, a_obj, a_key, a_default); } float getFlt(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, float a_default) { return ApiStorage::get().JMap_getFlt(a_domain, a_obj, a_key, a_default); } RE::BSFixedString getStr(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, RE::BSFixedString a_default) { return ApiStorage::get().JMap_getStr(a_domain, a_obj, a_key, a_default); } std::int32_t getObj(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, std::int32_t a_default) { return ApiStorage::get().JMap_getObj(a_domain, a_obj, a_key, a_default); } RE::TESForm* getForm(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, RE::TESForm* a_default) { return ApiStorage::get().JMap_getForm(a_domain, a_obj, a_key, a_default); } void setInt(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, std::int32_t a_value) { ApiStorage::get().JMap_setInt(a_domain, a_obj, a_key, a_value); } void setFlt(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, float a_value) { ApiStorage::get().JMap_setFlt(a_domain, a_obj, a_key, a_value); } void setStr(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, RE::BSFixedString a_value) { ApiStorage::get().JMap_setStr(a_domain, a_obj, a_key, a_value); } void setObj(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, std::int32_t a_container) { ApiStorage::get().JMap_setObj(a_domain, a_obj, a_key, a_container); } void setForm(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key, RE::TESForm* a_value) { ApiStorage::get().JMap_setForm(a_domain, a_obj, a_key, a_value); } bool hasKey(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key) { return ApiStorage::get().JMap_hasKey(a_domain, a_obj, a_key); } std::int32_t valueType(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key) { return ApiStorage::get().JMap_valueType(a_domain, a_obj, a_key); } std::int32_t allKeys(void* a_domain, std::int32_t a_obj) { return ApiStorage::get().JMap_allKeys(a_domain, a_obj); } std::vector<RE::BSFixedString> allKeysPArray(void* a_domain, std::int32_t a_obj) { return ApiStorage::get().JMap_allKeysPArray(a_domain, a_obj); } std::int32_t allValues(void* a_domain, std::int32_t a_obj) { return ApiStorage::get().JMap_allValues(a_domain, a_obj); } bool removeKey(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_key) { return ApiStorage::get().JMap_removeKey(a_domain, a_obj, a_key); } std::int32_t count(void* a_domain, std::int32_t a_obj) { return ApiStorage::get().JMap_count(a_domain, a_obj); } void clear(void* a_domain, std::int32_t a_obj) { ApiStorage::get().JMap_clear(a_domain, a_obj); } void addPairs(void* a_domain, std::int32_t a_obj, std::int32_t a_source, bool a_overrideDuplicates) { ApiStorage::get().JMap_addPairs(a_domain, a_obj, a_source, a_overrideDuplicates); } RE::BSFixedString nextKey(void* a_domain, std::int32_t a_obj, RE::BSFixedString a_previousKey, RE::BSFixedString a_endKey) { return ApiStorage::get().JMap_nextKey(a_domain, a_obj, a_previousKey, a_endKey); } RE::BSFixedString getNthKey(void* a_domain, std::int32_t a_obj, std::int32_t a_keyIndex) { return ApiStorage::get().JMap_getNthKey(a_domain, a_obj, a_keyIndex); } }
31.230769
123
0.735632
andrelo1
139880d9c286eb56c01c125e9c8f234ee9328a71
1,632
hpp
C++
module-utils/log/api/log/debug.hpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
module-utils/log/api/log/debug.hpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
module-utils/log/api/log/debug.hpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #define DEBUG_APPLICATION_MANAGEMENT 0 /// show verbose logs in ApplicationManager #define DEBUG_SCOPED_TIMINGS 0 /// show timings in measured functions #define DEBUG_CELLULAR_UART 0 /// show full modem uart communication #define DEBUG_BLUETOOTH_HCI_COMS 0 /// show communication with BT module - transactions #define DEBUG_BLUETOOTH_HCI_BYTES 0 /// show communication with BT module - all the HCI bytes #define DEBUG_SERVICE_MESSAGES 0 /// show messages prior to handling in service #define DEBUG_DB_MODEL_DATA 0 /// show messages prior to handling in service #define DEBUG_SIM_IMPORT_DATA 0 /// show messages connected to sim data imports #define DEBUG_FONT 0 /// show Font debug messages #define DEBUG_GUI_TEXT 0 /// show basic debug messages for gui::Text - warning this can be hard on cpu #define DEBUG_GUI_TEXT_LINES 0 /// show extended debug messages for gui::Text - lines building #define DEBUG_GUI_TEXT_CURSOR 0 /// show extended debug messages for gui::Text - cursor handling #define DEBUG_INPUT_EVENTS 0 /// show input events prints in system #define DEBUG_TIMER 0 /// debug timers system utility #define DEBUG_SETTINGS_DB 0 /// show extensive settings logs for all applications #define DEBUG_SERVICE_CELLULAR 0 /// show various logs in cellular service #define DEBUG_MISSING_ASSETS 0 /// show debug concerning missing assets
70.956522
116
0.723652
GravisZro
139e6c379b1a3be486138727e769472c69ff126c
998
hpp
C++
include/XP++/Exceptions/XPException.hpp
Andy260/xp-plus-plus
48f469d333eb50c0d7a4c914644217639084fda6
[ "MIT" ]
null
null
null
include/XP++/Exceptions/XPException.hpp
Andy260/xp-plus-plus
48f469d333eb50c0d7a4c914644217639084fda6
[ "MIT" ]
null
null
null
include/XP++/Exceptions/XPException.hpp
Andy260/xp-plus-plus
48f469d333eb50c0d7a4c914644217639084fda6
[ "MIT" ]
null
null
null
#pragma once // STL includes #include <exception> #include <string> namespace XP { /// <summary> /// Thrown when an error was encountered while calling X-Plane SDK functions /// </summary> class XPException : public std::exception { public: /// <summary> /// Constructs new a XPException /// </summary> /// <param name="message">Message to give to this exception</param> XPException(std::string message) : std::exception(), m_message(message) { } /// <summary> /// Returns the explanatory string. /// </summary> /// <returns>Pointer to a null-terminated string with explanatory information. /// The pointer is guaranteed to be valid at least until the exception object /// from which it is obtained is destroyed, or until a non-const member function /// on the exception object is called.</returns> virtual const char* what() const noexcept override { return m_message.c_str(); } private: // Message of this exception std::string m_message; }; }
26.263158
83
0.690381
Andy260
13aa76b5e45608ad84cea2bdfb10da10f39159d2
6,280
cpp
C++
src/reyes/reyes_virtual_machine/not_equal.cpp
cwbaker/sweet_render
259830adba09fabe4de2eef3537f4a95828965d3
[ "MIT" ]
9
2019-01-10T21:37:24.000Z
2021-05-26T23:59:05.000Z
src/reyes/reyes_virtual_machine/not_equal.cpp
cwbaker/sweet_render
259830adba09fabe4de2eef3537f4a95828965d3
[ "MIT" ]
null
null
null
src/reyes/reyes_virtual_machine/not_equal.cpp
cwbaker/sweet_render
259830adba09fabe4de2eef3537f4a95828965d3
[ "MIT" ]
1
2018-09-05T01:40:09.000Z
2018-09-05T01:40:09.000Z
// // not_equal.cpp // Copyright (c) Charles Baker. All rights reserved. // #include "not_equal.hpp" #include "Dispatch.hpp" #include "Instruction.hpp" #include <reyes/assert.hpp> namespace reyes { void not_equal_u1u1( int* result, const float* lhs, const float* rhs, unsigned int /*length*/ ) { result[0] = lhs[0] != rhs[0]; } void not_equal_u2u2( int* result, const float* lhs, const float* rhs, unsigned int /*length*/ ) { result[0 + 0] = lhs[0 + 0] != rhs[0 + 0]; result[0 + 1] = lhs[0 + 1] != rhs[0 + 1]; } void not_equal_u3u3( int* result, const float* lhs, const float* rhs, unsigned int /*length*/ ) { result[0 + 0] = lhs[0 + 0] != rhs[0 + 0]; result[0 + 1] = lhs[0 + 1] != rhs[0 + 1]; result[0 + 2] = lhs[0 + 2] != rhs[0 + 2]; } void not_equal_u4u4( int* result, const float* lhs, const float* rhs, unsigned int /*length*/ ) { result[0 + 0] = lhs[0 + 0] != rhs[0 + 0]; result[0 + 1] = lhs[0 + 1] != rhs[0 + 1]; result[0 + 2] = lhs[0 + 2] != rhs[0 + 2]; result[0 + 3] = lhs[0 + 3] != rhs[0 + 3]; } void not_equal_u1v1( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i] = lhs[0] != rhs[i]; } } void not_equal_u2v2( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[0 + 0] != rhs[i + 0]; result[i + 1] = lhs[0 + 1] != rhs[i + 1]; } } void not_equal_u3v3( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[0 + 0] != rhs[i + 0]; result[i + 1] = lhs[0 + 1] != rhs[i + 1]; result[i + 2] = lhs[0 + 2] != rhs[i + 2]; } } void not_equal_u4v4( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[0 + 0] != rhs[i + 0]; result[i + 1] = lhs[0 + 1] != rhs[i + 1]; result[i + 2] = lhs[0 + 2] != rhs[i + 2]; result[i + 3] = lhs[0 + 3] != rhs[i + 3]; } } void not_equal_v1u1( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i] = lhs[i] != rhs[0]; } } void not_equal_v2u2( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[i + 0] != rhs[0 + 0]; result[i + 1] = lhs[i + 1] != rhs[0 + 1]; } } void not_equal_v3u3( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[i + 0] != rhs[0 + 0]; result[i + 1] = lhs[i + 1] != rhs[0 + 1]; result[i + 2] = lhs[i + 2] != rhs[0 + 2]; } } void not_equal_v4u4( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[i + 0] != rhs[0 + 0]; result[i + 1] = lhs[i + 1] != rhs[0 + 1]; result[i + 2] = lhs[i + 2] != rhs[0 + 2]; result[i + 3] = lhs[i + 3] != rhs[0 + 3]; } } void not_equal_v1v1( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i] = lhs[i] != rhs[i]; } } void not_equal_v2v2( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[i + 0] != rhs[i + 0]; result[i + 1] = lhs[i + 1] != rhs[i + 1]; } } void not_equal_v3v3( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[i + 0] != rhs[i + 0]; result[i + 1] = lhs[i + 1] != rhs[i + 1]; result[i + 2] = lhs[i + 2] != rhs[i + 2]; } } void not_equal_v4v4( int* result, const float* lhs, const float* rhs, unsigned int length ) { for ( unsigned int i = 0; i < length; ++i ) { result[i + 0] = lhs[i + 0] != rhs[i + 0]; result[i + 1] = lhs[i + 1] != rhs[i + 1]; result[i + 2] = lhs[i + 2] != rhs[i + 2]; result[i + 3] = lhs[i + 3] != rhs[i + 3]; } } void not_equal( int dispatch, int* result, const float* lhs, const float* rhs, unsigned int length ) { switch ( dispatch ) { case DISPATCH_U1U1: not_equal_u1u1( result, lhs, rhs, length ); break; case DISPATCH_U2U2: not_equal_u2u2( result, lhs, rhs, length ); break; case DISPATCH_U3U3: not_equal_u3u3( result, lhs, rhs, length ); break; case DISPATCH_U4U4: not_equal_u4u4( result, lhs, rhs, length ); break; case DISPATCH_U1V1: not_equal_u1v1( result, lhs, rhs, length ); break; case DISPATCH_U2V2: not_equal_u2v2( result, lhs, rhs, length ); break; case DISPATCH_U3V3: not_equal_u3v3( result, lhs, rhs, length ); break; case DISPATCH_U4V4: not_equal_u4v4( result, lhs, rhs, length ); break; case DISPATCH_V1U1: not_equal_v1u1( result, lhs, rhs, length ); break; case DISPATCH_V2U2: not_equal_v2u2( result, lhs, rhs, length ); break; case DISPATCH_V3U3: not_equal_v3u3( result, lhs, rhs, length ); break; case DISPATCH_V4U4: not_equal_v4u4( result, lhs, rhs, length ); break; case DISPATCH_V1V1: not_equal_v1v1( result, lhs, rhs, length ); break; case DISPATCH_V2V2: not_equal_v2v2( result, lhs, rhs, length ); break; case DISPATCH_V3V3: not_equal_v3v3( result, lhs, rhs, length ); break; case DISPATCH_V4V4: not_equal_v4v4( result, lhs, rhs, length ); break; default: REYES_ASSERT( false ); break; } } }
27.423581
100
0.516401
cwbaker
13aac82aaf1ba28bd4dcdb9f906f134ccc9a9eac
314
hpp
C++
framework/MatrixInterpolation.hpp
aosterthun/rgbdri
8e513172f512c902f7d6d8631c7580b5b62277c4
[ "MIT" ]
null
null
null
framework/MatrixInterpolation.hpp
aosterthun/rgbdri
8e513172f512c902f7d6d8631c7580b5b62277c4
[ "MIT" ]
null
null
null
framework/MatrixInterpolation.hpp
aosterthun/rgbdri
8e513172f512c902f7d6d8631c7580b5b62277c4
[ "MIT" ]
null
null
null
#ifndef GLM_MATRIXINTERPOLATION_H #define GLM_MATRIXINTERPOLATION_H #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtc/matrix_transform.hpp> glm::mat4 interpolate(const glm::mat4& a, const glm::mat4& b, float t); #endif // #ifndef GLM_MATRIXINTERPOLATION_H
19.625
71
0.780255
aosterthun
13ac348230a5f4c53e58a86c9009f598b0734dc6
690
cpp
C++
source/mazegenerator/DistanceGrid.cpp
danielplawrence/MazeGeneration
d9d0e878c94226aa379e6ee2a2681f1c99b2f792
[ "Unlicense" ]
null
null
null
source/mazegenerator/DistanceGrid.cpp
danielplawrence/MazeGeneration
d9d0e878c94226aa379e6ee2a2681f1c99b2f792
[ "Unlicense" ]
null
null
null
source/mazegenerator/DistanceGrid.cpp
danielplawrence/MazeGeneration
d9d0e878c94226aa379e6ee2a2681f1c99b2f792
[ "Unlicense" ]
null
null
null
#include <mazegenerator/DistanceGrid.h> #include <algorithm> std::tuple<int, int, int, int, Color> DistanceGrid::contentsOf(CellPtr cell, int cellSize) { if (distances == nullptr) { return {}; } auto location = cell->getLocation(); auto x1 = location.second * cellSize; auto y1 = location.first * cellSize; auto x2 = (location.second + 1) * cellSize; auto y2 = (location.first + 1) * cellSize; auto distance = distances->get(cell); if (!distance.has_value()) { return {}; } auto max = std::max({distances->max().first, 1}); auto intensity = (float(max) - float(distance.value())) / float(max); auto c = color * intensity; return {x1, y1, x2, y2, c}; }
30
92
0.646377
danielplawrence
13ad1f3cb8a403eddb1d3563f437812f2230cb6c
3,188
cpp
C++
Ouroboros/Source/oLauncher/oLauncher.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
Ouroboros/Source/oLauncher/oLauncher.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
Ouroboros/Source/oLauncher/oLauncher.cpp
jiangzhu1212/oooii
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
[ "MIT" ]
null
null
null
// Copyright (c) 2014 Antony Arciuolo. See License.txt regarding use. #include <oBase/throw.h> #include <oString/opttok.h> #include <oGUI/msgbox.h> //#include <oPlatform/oVersionUpdate.h> using namespace ouro; static option sCmdOptions[] = { { 'w', "launcher-wait", "process-id", "Wait for process to terminate before launching" }, { 't', "wait-timeout", "milliseconds", "Try to forcibly terminate the -w process after\nthis amount of time" }, { 'v', "version", "Maj.Min.Build.Rev", "Force execution of the specified version" }, { 'e', "exe-name-override", "exe-name", "Override the default of <version>/launcher-name\nwith an explicit exe name" }, { 'c', "command-line", "options", "The command line to pass to the actual executable" }, { 'p', "prefix", "prefix", "A prefix to differentiatethe actual exe from the\nlauncher exe" }, { 'h', "help", 0, "Displays this message" }, }; namespace ouro { bool from_string(const char** _ppConstStr, const char* _Value) { *_ppConstStr = _Value; return true; } } #define oOPT_CASE(_ShortNameConstant, _Value, _Dest) case _ShortNameConstant: { if (!from_string(&(_Dest), value)) { return oErrorSetLast(std::errc::invalid_argument, "-%c %s cannot be interpreted as a(n) %s", (_ShortNameConstant), (_Value), typeid(_Dest).name()); } break; } #define oOPT_CASE_DEFAULT(_ShortNameVariable, _Value, _NthOption) \ case ' ': { oTHROW_INVARG("There should be no parameters that aren't switches passed"); break; } \ case '?': { oTHROW_INVARG("Parameter %d is not recognized", (_NthOption)); break; } \ case ':': { oTHROW_INVARG("Parameter %d is missing a value", (_NthOption)); break; } \ default: { oTRACE("Unhandled option -%c %s", (_ShortNameVariable), oSAFESTR(_Value)); break; } #if 0 void oParseCmdLine(int argc, const char* argv[], oVERSIONED_LAUNCH_DESC* _pDesc, bool* _pShowHelp) { *_pShowHelp = false; const char* value = 0; char ch = opttok(&value, argc, argv, sCmdOptions); int count = 1; while (ch) { switch (ch) { oOPT_CASE('w', value, _pDesc->WaitForPID); oOPT_CASE('t', value, _pDesc->WaitForPIDTimeout); oOPT_CASE('v', value, _pDesc->SpecificVersion); oOPT_CASE('e', value, _pDesc->SpecificModuleName); oOPT_CASE('c', value, _pDesc->PassThroughCommandLine); oOPT_CASE('p', value, _pDesc->ModuleNamePrefix); oOPT_CASE_DEFAULT(ch, value, count); case 'h': *_pShowHelp = true; break; } ch = opttok(&value); count++; } } static void oLauncherMain(int argc, const char* argv[]) { oVERSIONED_LAUNCH_DESC vld; bool ShowHelp = false; oParseCmdLine(argc, argv, &vld, &ShowHelp); if (ShowHelp) { char help[1024]; if (optdoc(help, path(argv[0]).filename().c_str(), sCmdOptions)) printf(help); return; } oVURelaunch(vld); } #endif int main(int argc, const char* argv[]) { oTHROW(not_supported, "Disabled until version update is resurrected"); #if 0 try { oLauncherMain(argc, argv); } catch (std::exception& e) { path ModuleName = this_module::get_path(); msgbox(msg_type::error, nullptr, ModuleName.filename(), "%s", e.what()); return -1; } return 0; #endif }
33.557895
276
0.668758
jiangzhu1212
13ae6c1d193c6b9c313226f1722ce9b72f6f5b0e
1,625
cpp
C++
CF/contests/670d2/d.cpp
death-shadow/Competitive-Coding-Solutions
fc4f7cbcac275d263f3356e2cc901e676b97c257
[ "MIT" ]
2
2019-07-12T14:56:19.000Z
2020-05-01T20:04:41.000Z
CF/contests/670d2/d.cpp
death-shadow/Competitive-Coding-Solutions
fc4f7cbcac275d263f3356e2cc901e676b97c257
[ "MIT" ]
7
2020-09-21T16:52:23.000Z
2020-11-07T09:12:24.000Z
CF/contests/670d2/d.cpp
death-shadow/Competitive-Coding-Solutions
fc4f7cbcac275d263f3356e2cc901e676b97c257
[ "MIT" ]
5
2020-10-01T16:51:49.000Z
2020-10-02T06:00:56.000Z
#include <bits/stdc++.h> #define FAST_IO ios_base::sync_with_stdio(false); cin.tie(NULL) #define endl "\n" #define CPrint(c) for(auto i:(c)) { cout<<i<<" "; } nl #define eb emplace_back #define ef emplace_front #define pb push_back #define pf push_front #define popb pop_back #define popf pop_front #define mp make_pair #define f first #define s second #define present(c,x) ((c).find(x) != (c).end()) #define cpresent(c,x) (find(all(c),x) != (c).end()) typedef long long ll; using namespace std; typedef long long ll; int subtractTime(int land, int fly) { ll minLand = land % 100; ll hourLand = (land / 100) % 100; ll minFly = (fly) % 100; ll hourFly = (fly / 100) % 100; ll min, hour; if (minFly < minLand) { min = minFly - minLand + 60; hourFly--; } else { min = minFly - minLand; } hour = hourFly - hourLand; return hour * 100 + min; } int getMinGates(vector<int> landingTimes, vector<int> takeOffTimes, int maxWaitTime, int initialPlanes) { ll ans = initialPlanes, curr = initialPlanes; ll x = 0, y = 0; while (y < takeOffTimes.size() or x < landingTimes.size() ) { if (x == landingTimes.size()) break; if (y == takeOffTimes.size()) { curr += landingTimes.size() - x; ans = max(ans, curr); break; } if (landingTimes[x] < takeOffTimes[y]) { if (subtractTime(landingTimes[x], takeOffTimes[y]) > maxWaitTime) { curr++; ans = max(ans, curr); } else y++; x++; } else { if (curr > 0) curr--; y++; } } return ans; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif }
22.260274
105
0.626462
death-shadow
13affb5f7fd1824bbfae9033c7b7dd8f3a4c2865
82,300
cpp
C++
external/openglcts/modules/common/glcPackedDepthStencilTests.cpp
tarceri/VK-GL-CTS
22389a0e44f458492f594ca0553a5a67cf6c7ada
[ "Apache-2.0" ]
20
2019-04-18T07:37:34.000Z
2022-02-02T21:43:47.000Z
external/openglcts/modules/common/glcPackedDepthStencilTests.cpp
tarceri/VK-GL-CTS
22389a0e44f458492f594ca0553a5a67cf6c7ada
[ "Apache-2.0" ]
11
2019-10-21T13:39:41.000Z
2021-11-05T08:11:54.000Z
external/openglcts/modules/common/glcPackedDepthStencilTests.cpp
tarceri/VK-GL-CTS
22389a0e44f458492f594ca0553a5a67cf6c7ada
[ "Apache-2.0" ]
1
2021-12-03T18:11:36.000Z
2021-12-03T18:11:36.000Z
/*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2017 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file glcPackedDepthStencilTests.cpp * \brief */ /*-------------------------------------------------------------------*/ #include "glcPackedDepthStencilTests.hpp" #include "deMath.h" #include "gluContextInfo.hpp" #include "gluDrawUtil.hpp" #include "gluRenderContext.hpp" #include "gluShaderProgram.hpp" #include "gluStrUtil.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuRenderTarget.hpp" #include "tcuTestLog.hpp" #include <algorithm> #include <cstring> #include <stdio.h> using namespace glw; using namespace glu; namespace glcts { #define TEX_SIZE 256 #define TOLERANCE_LOW 0.48 #define TOLERANCE_HIGH 0.52 #define EPSILON 0.01 enum DrawMode { DEFAULT, DEPTH_SPAN1, DEPTH_SPAN2, }; struct D32F_S8 { GLfloat d; GLuint s; }; // Reference texture names for the described 5 textures and framebuffers // and also for identifying other cases' reference textures enum TextureNames { packedTexImage, packedTexRender, packedTexRenderInitStencil, packedTexRenderDepthStep, packedTexRenderStencilStep, NUM_TEXTURES, verifyCopyTexImage, verifyPartialAttachments, verifyMixedAttachments, verifyClearBufferDepth, verifyClearBufferStencil, verifyClearBufferDepthStencil, verifyBlit, }; struct TypeFormat { GLenum type; GLenum format; const char* formatName; int size; int d; int s; }; #define NUM_TEXTURE_TYPES 2 static const TypeFormat TextureTypes[NUM_TEXTURE_TYPES] = { { GL_UNSIGNED_INT_24_8, GL_DEPTH24_STENCIL8, "depth24_stencil8", sizeof(GLuint), 24, 8 }, { GL_FLOAT_32_UNSIGNED_INT_24_8_REV, GL_DEPTH32F_STENCIL8, "depth32f_stencil8", sizeof(GLuint) + sizeof(GLfloat), 32, 8 }, }; // Texture targets for initial state checking static const GLenum coreTexTargets[] = { GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_1D, GL_TEXTURE_1D_ARRAY, GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_RECTANGLE, GL_TEXTURE_2D_MULTISAMPLE, GL_TEXTURE_2D_MULTISAMPLE_ARRAY, GL_PROXY_TEXTURE_1D, GL_PROXY_TEXTURE_2D, GL_PROXY_TEXTURE_3D, GL_PROXY_TEXTURE_1D_ARRAY, GL_PROXY_TEXTURE_2D_ARRAY, GL_PROXY_TEXTURE_CUBE_MAP_ARRAY, GL_PROXY_TEXTURE_RECTANGLE, GL_PROXY_TEXTURE_CUBE_MAP, GL_PROXY_TEXTURE_2D_MULTISAMPLE, GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY, }; static const GLenum esTexTargets[] = { GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, }; // Listing of non-depth_stencil types for error tests static const GLenum coreNonDepthStencilTypes[] = { GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, GL_UNSIGNED_INT, GL_INT, GL_HALF_FLOAT, GL_FLOAT, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV, GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, GL_UNSIGNED_SHORT_5_6_5_REV, GL_UNSIGNED_SHORT_4_4_4_4_REV, GL_UNSIGNED_SHORT_1_5_5_5_REV, GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2, }; static const GLenum esNonDepthStencilTypes[] = { GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, GL_UNSIGNED_INT, GL_INT, GL_HALF_FLOAT, GL_FLOAT, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_10F_11F_11F_REV, GL_UNSIGNED_INT_5_9_9_9_REV, }; // Listing of non-depth_stencil formats for error tests static const GLenum coreNonDepthStencilFormats[] = { GL_STENCIL_INDEX, GL_RED, GL_GREEN, GL_BLUE, GL_RG, GL_RGB, GL_RGBA, GL_BGR, GL_BGRA, GL_RED_INTEGER, GL_GREEN_INTEGER, GL_BLUE_INTEGER, GL_RG_INTEGER, GL_RGB_INTEGER, GL_RGBA_INTEGER, GL_BGR_INTEGER, GL_BGRA_INTEGER, }; static const GLenum esNonDepthStencilFormats[] = { GL_RED, GL_RG, GL_RGB, GL_RGBA, GL_LUMINANCE, // for es3+ GL_ALPHA, // for es3+ GL_LUMINANCE_ALPHA, // for es3+ GL_RED_INTEGER, GL_RG_INTEGER, GL_RGB_INTEGER, GL_RGBA_INTEGER, }; // Listing of non-depth_stencil base formats for error tests static const GLenum coreOtherBaseFormats[] = { GL_RED, GL_RG, GL_RGB, GL_RGBA, }; static const GLenum esOtherBaseFormats[] = { GL_RED, GL_RG, GL_RGB, GL_RGBA, GL_LUMINANCE, GL_ALPHA, GL_LUMINANCE_ALPHA, }; struct AttachmentParam { GLenum pname; GLint value; }; #define NUM_ATTACHMENT_PARAMS_CORE 13 #define NUM_ATTACHMENT_PARAMS_ES 12 static const AttachmentParam coreAttachmentParams[NUM_TEXTURE_TYPES][NUM_ATTACHMENT_PARAMS_CORE] = { { { GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, 24 }, { GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, 8 }, { GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, GL_UNSIGNED_NORMALIZED }, { GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, GL_LINEAR }, { GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, -1 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_LAYERED, 0 }, }, { { GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, 32 }, { GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, 8 }, { GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, GL_FLOAT }, { GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, GL_LINEAR }, { GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, -1 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_LAYERED, 0 }, }, }; static const AttachmentParam esAttachmentParams[NUM_TEXTURE_TYPES][NUM_ATTACHMENT_PARAMS_ES] = { { { GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, 24 }, { GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, 8 }, { GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, GL_UNSIGNED_NORMALIZED }, { GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, GL_LINEAR }, { GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, -1 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, 0 }, }, { { GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, 32 }, { GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, 8 }, { GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE, GL_FLOAT }, { GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, GL_LINEAR }, { GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, -1 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, 0 }, { GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, 0 }, }, }; enum ColorFunction { COLOR_CHECK_DEFAULT, COLOR_CHECK_DEPTH, COLOR_CHECK_STENCIL, }; class BaseTest : public deqp::TestCase { public: BaseTest(deqp::Context& context, const TypeFormat& tf); virtual ~BaseTest(); void init(void); virtual tcu::TestNode::IterateResult iterate(void); const AttachmentParam* getAttachmentParams() const; void createGradient(std::vector<GLbyte>& data); void setDrawReadBuffer(GLenum draw, GLenum read); void restoreDrawReadBuffer(); void createTextures(); void setupTexture(); void destroyTextures(); GLuint createProgram(const char* vsCode, const char* fsCode); void setupColorProgram(GLint& uColor); bool setupTextureProgram(); bool setupStencilProgram(); bool setTextureUniform(GLuint programId); void drawQuad(DrawMode drawMode, GLuint program); void renderToTextures(); bool verifyDepthStencilGradient(GLvoid* data, unsigned int texIndex, int width, int height); bool verifyColorGradient(GLvoid* data, unsigned int texIndex, int function, int width, int height); bool doReadPixels(GLuint texture, int function); protected: GLuint m_defaultFBO; GLuint m_drawBuffer; GLuint m_readBuffer; const GLenum* m_textureTargets; GLuint m_textureTargetsCount; const GLenum* m_nonDepthStencilTypes; GLuint m_nonDepthStencilTypesCount; const GLenum* m_nonDepthStencilFormats; GLuint m_nonDepthStencilFormatsCount; const GLenum* m_otherBaseFormats; GLuint m_otherBaseFormatsCount; const AttachmentParam* m_attachmentParams[NUM_TEXTURE_TYPES]; GLuint m_attachmentParamsCount; const TypeFormat& m_typeFormat; GLuint m_textureProgram; GLuint m_colorProgram; GLuint m_stencilProgram; GLuint m_textures[NUM_TEXTURES]; GLuint m_framebuffers[NUM_TEXTURES]; }; BaseTest::BaseTest(deqp::Context& context, const TypeFormat& tf) : deqp::TestCase(context, tf.formatName, "") , m_defaultFBO(0) , m_drawBuffer(GL_COLOR_ATTACHMENT0) , m_readBuffer(GL_COLOR_ATTACHMENT0) , m_textureTargets(coreTexTargets) , m_textureTargetsCount(DE_LENGTH_OF_ARRAY(coreTexTargets)) , m_nonDepthStencilTypes(coreNonDepthStencilTypes) , m_nonDepthStencilTypesCount(DE_LENGTH_OF_ARRAY(coreNonDepthStencilTypes)) , m_nonDepthStencilFormats(coreNonDepthStencilFormats) , m_nonDepthStencilFormatsCount(DE_LENGTH_OF_ARRAY(coreNonDepthStencilFormats)) , m_otherBaseFormats(coreOtherBaseFormats) , m_otherBaseFormatsCount(DE_LENGTH_OF_ARRAY(coreOtherBaseFormats)) , m_typeFormat(tf) , m_textureProgram(0) , m_colorProgram(0) , m_stencilProgram(0) { } BaseTest::~BaseTest() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); if (m_textureProgram) gl.deleteProgram(m_textureProgram); if (m_colorProgram) gl.deleteProgram(m_colorProgram); if (m_stencilProgram) gl.deleteProgram(m_stencilProgram); } void BaseTest::init(void) { if (glu::isContextTypeES(m_context.getRenderContext().getType())) { m_textureTargets = esTexTargets; m_textureTargetsCount = DE_LENGTH_OF_ARRAY(esTexTargets); m_nonDepthStencilTypes = esNonDepthStencilTypes; m_nonDepthStencilTypesCount = DE_LENGTH_OF_ARRAY(esNonDepthStencilTypes); m_nonDepthStencilFormats = esNonDepthStencilFormats; m_nonDepthStencilFormatsCount = DE_LENGTH_OF_ARRAY(esNonDepthStencilFormats); m_otherBaseFormats = esOtherBaseFormats; m_otherBaseFormatsCount = DE_LENGTH_OF_ARRAY(esOtherBaseFormats); for (int i = 0; i < NUM_TEXTURE_TYPES; i++) m_attachmentParams[i] = esAttachmentParams[i]; m_attachmentParamsCount = NUM_ATTACHMENT_PARAMS_ES; } else { for (int i = 0; i < NUM_TEXTURE_TYPES; i++) m_attachmentParams[i] = coreAttachmentParams[i]; m_attachmentParamsCount = NUM_ATTACHMENT_PARAMS_CORE; } } tcu::TestNode::IterateResult BaseTest::iterate(void) { m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } const AttachmentParam* BaseTest::getAttachmentParams() const { // find type index int index = 0; for (; index < NUM_TEXTURE_TYPES; index++) { if (TextureTypes[index].format == m_typeFormat.format) break; } if (index >= NUM_TEXTURE_TYPES) TCU_FAIL("Missing attachment definition"); return m_attachmentParams[index]; } // Creates a gradient texture data in the given type parameter format void BaseTest::createGradient(std::vector<GLbyte>& data) { switch (m_typeFormat.type) { case GL_UNSIGNED_INT_24_8: { data.resize(TEX_SIZE * TEX_SIZE * sizeof(GLuint)); GLuint* dataPtr = reinterpret_cast<GLuint*>(&data[0]); for (int j = 0; j < TEX_SIZE; j++) { for (int i = 0; i < TEX_SIZE; i++) { GLuint d = static_cast<GLuint>(static_cast<float>(i) / (TEX_SIZE - 1) * 0x00ffffff); GLubyte s = i & 0xff; dataPtr[TEX_SIZE * j + i] = (d << 8) + s; } } return; } case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: { data.resize(TEX_SIZE * TEX_SIZE * sizeof(D32F_S8)); D32F_S8* dataPtr = reinterpret_cast<D32F_S8*>(&data[0]); for (int j = 0; j < TEX_SIZE; j++) { for (int i = 0; i < TEX_SIZE; i++) { D32F_S8 v = { static_cast<float>(i) / (TEX_SIZE - 1), static_cast<GLuint>(i & 0xff) }; dataPtr[TEX_SIZE * j + i] = v; } } return; } default: TCU_FAIL("Unsuported type"); } } void BaseTest::setDrawReadBuffer(GLenum draw, GLenum read) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); GLint drawBuffer; gl.getIntegerv(GL_DRAW_BUFFER0, &drawBuffer); m_drawBuffer = static_cast<GLuint>(drawBuffer); GLint readBuffer; gl.getIntegerv(GL_READ_BUFFER, &readBuffer); m_readBuffer = static_cast<GLuint>(readBuffer); gl.drawBuffers(1, &draw); gl.readBuffer(read); GLU_EXPECT_NO_ERROR(gl.getError(), "glReadBuffer"); } void BaseTest::restoreDrawReadBuffer() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.drawBuffers(1, &m_drawBuffer); gl.readBuffer(m_readBuffer); GLU_EXPECT_NO_ERROR(gl.getError(), "glReadBuffer"); } void BaseTest::createTextures() { // Creates all the textures and framebuffers const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.genTextures(NUM_TEXTURES, m_textures); gl.genFramebuffers(NUM_TEXTURES, m_framebuffers); // packedTexImage gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexImage]); gl.bindTexture(GL_TEXTURE_2D, m_textures[packedTexImage]); setupTexture(); std::vector<GLbyte> data; createGradient(data); gl.texImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexImage], 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexImage], 0); // packedTexRender gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRender]); gl.bindTexture(GL_TEXTURE_2D, m_textures[packedTexRender]); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_STENCIL, m_typeFormat.type, NULL); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexRender], 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexRender], 0); // packedTexRenderInitStencil gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRenderInitStencil]); gl.bindTexture(GL_TEXTURE_2D, m_textures[packedTexRenderInitStencil]); setupTexture(); createGradient(data); gl.texImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexRenderInitStencil], 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexRenderInitStencil], 0); // packedTexRenderDepthStep gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRenderDepthStep]); gl.bindTexture(GL_TEXTURE_2D, m_textures[packedTexRenderDepthStep]); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_STENCIL, m_typeFormat.type, NULL); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexRenderDepthStep], 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexRenderDepthStep], 0); // packedTexRenderStencilStep gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRenderStencilStep]); gl.bindTexture(GL_TEXTURE_2D, m_textures[packedTexRenderStencilStep]); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_STENCIL, m_typeFormat.type, NULL); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexRenderStencilStep], 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexRenderStencilStep], 0); gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindFramebuffer"); } void BaseTest::setupTexture() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); GLU_EXPECT_NO_ERROR(gl.getError(), "glTexParameteri"); } // Destroys all the textures and framebuffers void BaseTest::destroyTextures() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.deleteFramebuffers(NUM_TEXTURES, m_framebuffers); gl.deleteTextures(NUM_TEXTURES, m_textures); } GLuint BaseTest::createProgram(const char* vsCode, const char* fsCode) { glu::RenderContext& renderContext = m_context.getRenderContext(); glu::ContextType contextType = renderContext.getType(); const glw::Functions& gl = m_context.getRenderContext().getFunctions(); glu::GLSLVersion glslVersion = glu::getContextTypeGLSLVersion(contextType); const char* version = glu::getGLSLVersionDeclaration(glslVersion); glu::Shader vs(gl, glu::SHADERTYPE_VERTEX); const char* vSources[] = { version, vsCode }; const int vLengths[] = { int(strlen(version)), int(strlen(vsCode)) }; vs.setSources(2, vSources, vLengths); vs.compile(); if (!vs.getCompileStatus()) TCU_FAIL("Vertex shader compilation failed"); glu::Shader fs(gl, glu::SHADERTYPE_FRAGMENT); const char* fSources[] = { version, fsCode }; const int fLengths[] = { int(strlen(version)), int(strlen(fsCode)) }; fs.setSources(2, fSources, fLengths); fs.compile(); if (!fs.getCompileStatus()) TCU_FAIL("Fragment shader compilation failed"); GLuint p = gl.createProgram(); gl.attachShader(p, vs.getShader()); gl.attachShader(p, fs.getShader()); gl.linkProgram(p); return p; } void BaseTest::setupColorProgram(GLint& uColor) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); const char* vs = "\n" "precision highp float;\n" "in vec4 pos;\n" "void main() {\n" " gl_Position = pos;\n" "}\n"; const char* fs = "\n" "precision highp float;\n" "out vec4 color;\n" "uniform vec4 uColor;\n" "void main() {\n" " color = uColor;\n" "}\n"; // setup shader program if (!m_colorProgram) m_colorProgram = createProgram(vs, fs); if (!m_colorProgram) TCU_FAIL("Error while loading shader program"); gl.useProgram(m_colorProgram); // Setup program uniforms uColor = gl.getUniformLocation(m_colorProgram, "uColor"); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetUniformLocation"); if (uColor == -1) TCU_FAIL("Error getting uniform uColor"); gl.uniform4f(uColor, 1.0f, 1.0f, 1.0f, 1.0f); } // Common code for default and stencil texture rendering shaders bool BaseTest::setTextureUniform(GLuint programId) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.useProgram(programId); GLint uniformTex = gl.getUniformLocation(programId, "tex"); GLU_EXPECT_NO_ERROR(gl.getError(), "glGetUniformLocation"); if (uniformTex == -1) { m_testCtx.getLog() << tcu::TestLog::Message << "Error getting uniform tex" << tcu::TestLog::EndMessage; return false; } gl.uniform1i(uniformTex, 0); return true; } // Loads texture rendering shader bool BaseTest::setupTextureProgram() { const char* vs = "\n" "precision highp float;\n" "in vec4 pos;\n" "in vec2 UV;\n" "out vec2 vUV;\n" "void main() {\n" " gl_Position = pos;\n" " vUV = UV;\n" "}\n"; const char* fs = "\n" "precision highp float;\n" "in vec2 vUV;\n" "out vec4 color;\n" "uniform sampler2D tex;\n" "void main() {\n" " color = texture(tex, vUV).rrra;\n" "}\n"; if (!m_textureProgram) m_textureProgram = createProgram(vs, fs); if (!m_textureProgram) return false; return setTextureUniform(m_textureProgram); } // Loads texture stencil rendering shader bool BaseTest::setupStencilProgram() { const char* vs = "\n" "precision highp float;\n" "in vec4 pos;\n" "in vec2 UV;\n" "out vec2 vUV;\n" "void main() {\n" " gl_Position = pos;\n" " vUV = UV;\n" "}\n"; const char* fs = "\n" "precision highp float;\n" "in vec2 vUV;\n" "out vec4 color;\n" "uniform highp usampler2D tex;\n" "void main() {\n" " float s = float(texture(tex, vUV).r);\n" " s /= 255.0;\n" " color = vec4(s, s, s, 1);\n" "}\n"; if (!m_stencilProgram) m_stencilProgram = createProgram(vs, fs); if (!m_stencilProgram) return false; return setTextureUniform(m_stencilProgram); } void BaseTest::drawQuad(DrawMode drawMode, GLuint program) { static const GLfloat verticesDefault[] = { -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, }; static const GLfloat verticesDepthSpan1[] = { -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; static const GLfloat verticesDepthSpan2[] = { -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, }; static const GLfloat texCoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; static const deUint16 quadIndices[] = { 0, 1, 2, 2, 1, 3 }; static PrimitiveList quadPrimitive = glu::pr::TriangleStrip(DE_LENGTH_OF_ARRAY(quadIndices), quadIndices); static const glu::VertexArrayBinding depthSpanVA1[] = { glu::va::Float("pos", 4, 4, 0, verticesDepthSpan1) }; static const glu::VertexArrayBinding depthSpanVA2[] = { glu::va::Float("pos", 4, 4, 0, verticesDepthSpan2) }; static const glu::VertexArrayBinding defaultVA[] = { glu::va::Float("pos", 4, 4, 0, verticesDefault), glu::va::Float("UV", 2, 4, 0, texCoords) }; const glu::RenderContext& renderContext = m_context.getRenderContext(); if (drawMode == DEPTH_SPAN1) glu::draw(renderContext, program, 1, depthSpanVA1, quadPrimitive); else if (drawMode == DEPTH_SPAN2) glu::draw(renderContext, program, 1, depthSpanVA2, quadPrimitive); else glu::draw(renderContext, program, 2, defaultVA, quadPrimitive); } // Renders all non-trivial startup textures void BaseTest::renderToTextures() { const glu::RenderContext& renderContext = m_context.getRenderContext(); const glw::Functions& gl = renderContext.getFunctions(); GLint uColor; setupColorProgram(uColor); gl.enable(GL_DEPTH_TEST); // depth writing must be enabled as it is disabled in places like doReadPixels gl.depthMask(GL_TRUE); if (glu::isContextTypeES(renderContext.getType())) gl.clearDepthf(1.0f); else gl.clearDepth(1.0); gl.depthFunc(GL_LEQUAL); gl.viewport(0, 0, TEX_SIZE, TEX_SIZE); drawQuad(DEPTH_SPAN1, m_colorProgram); // packedTexRender gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRender]); setDrawReadBuffer(GL_NONE, GL_NONE); gl.enable(GL_STENCIL_TEST); gl.stencilFunc(GL_ALWAYS, 0x0, 0xFF); gl.stencilOp(GL_ZERO, GL_INCR, GL_INCR); gl.clear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); drawQuad(DEPTH_SPAN1, m_colorProgram); gl.disable(GL_STENCIL_TEST); restoreDrawReadBuffer(); // packedTexRenderInitStencil gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRenderInitStencil]); setDrawReadBuffer(GL_NONE, GL_NONE); gl.clear(GL_DEPTH_BUFFER_BIT); drawQuad(DEPTH_SPAN1, m_colorProgram); restoreDrawReadBuffer(); // packedTexRenderDepthStep gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRenderDepthStep]); setDrawReadBuffer(GL_NONE, GL_NONE); gl.clear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); drawQuad(DEPTH_SPAN2, m_colorProgram); drawQuad(DEPTH_SPAN1, m_colorProgram); restoreDrawReadBuffer(); // packedTexRenderStencilStep gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRenderStencilStep]); setDrawReadBuffer(GL_NONE, GL_NONE); gl.clear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); gl.enable(GL_SCISSOR_TEST); gl.scissor(0, 0, TEX_SIZE, TEX_SIZE / 2); gl.enable(GL_STENCIL_TEST); gl.stencilFunc(GL_ALWAYS, 0x0, 0xFF); gl.stencilOp(GL_ZERO, GL_INCR, GL_INCR); for (int i = 0; i < 256; i++) drawQuad(DEPTH_SPAN2, m_colorProgram); gl.disable(GL_SCISSOR_TEST); gl.stencilFunc(GL_EQUAL, 0xFF, 0xFF); gl.clear(GL_DEPTH_BUFFER_BIT); drawQuad(DEPTH_SPAN1, m_colorProgram); gl.disable(GL_STENCIL_TEST); GLU_EXPECT_NO_ERROR(gl.getError(), "glDisable"); restoreDrawReadBuffer(); // end gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindFramebuffer"); } // Verifies DepthStencil buffer data against reference values bool BaseTest::verifyDepthStencilGradient(GLvoid* data, unsigned int texIndex, int width, int height) { bool result = true; int index, skip; int countD, countS; index = 0; countD = 0; countS = 0; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { float d, dref = 0.0; int s, sref = 0; skip = 0; switch (m_typeFormat.type) { case GL_UNSIGNED_INT_24_8: { GLuint v = ((GLuint*)data)[index]; d = ((float)(v >> 8)) / 0xffffff; s = v & 0xff; break; } case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: { D32F_S8 v = ((D32F_S8*)data)[index]; d = v.d; s = v.s & 0xff; break; } default: d = -1; s = -1; break; } switch (texIndex) { case packedTexImage: dref = ((float)i) / (width - 1); sref = (int)(dref * 255); break; case packedTexRender: dref = ((float)j) / (height - 1); sref = 1; break; case packedTexRenderInitStencil: dref = ((float)j) / (height - 1); sref = (int)(((float)i) / (width - 1) * 255); break; case packedTexRenderDepthStep: if (j < height * TOLERANCE_LOW) { dref = ((float)j) / (height - 1); sref = 0; } else if (j > height * TOLERANCE_HIGH) { dref = 1.0f - ((float)j) / (height - 1); sref = 0; } else { skip = 1; // give some tolerance to pixels in the middle } break; case packedTexRenderStencilStep: if (j < height * TOLERANCE_LOW) { dref = ((float)j) / (height - 1); sref = 255; } else if (j > height * TOLERANCE_HIGH) { dref = 1; sref = 0; } else { skip = 1; // give some tolerance to pixels in the middle } break; case verifyCopyTexImage: if (j < height * TOLERANCE_LOW) { dref = ((float)j) / (height - 1); sref = 1; } else if (j > height * TOLERANCE_HIGH) { dref = 0.5; sref = 1; } else { skip = 1; // give some tolerance to pixels in the middle } break; default: dref = -2; sref = -2; break; } if (!skip) { if (deFloatAbs(d - dref) > EPSILON) { result = false; countD++; } if (s != sref) { result = false; countS++; } } else { skip = 0; } index++; } } if (countD || countS) { m_testCtx.getLog() << tcu::TestLog::Message << "DEPTH_STENCIL comparison failed" << tcu::TestLog::EndMessage; } return result; } // Verifies Color buffer data against reference values bool BaseTest::verifyColorGradient(GLvoid* data, unsigned int texIndex, int function, int width, int height) { bool result = true; int index = 0, skip; int channel = 0; int count = 0; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { skip = 0; GLuint color = ((GLuint*)data)[index]; GLuint colorref = 0; switch (texIndex) { case packedTexImage: channel = (int)(((float)i) / (width - 1) * 255); colorref = 0xff000000 + channel * 0x00010101; break; case packedTexRender: if (function == COLOR_CHECK_DEPTH) channel = (int)(((float)j) / (height - 1) * 255); else channel = 1; colorref = 0xff000000 + channel * 0x00010101; break; case packedTexRenderInitStencil: if (function == COLOR_CHECK_DEPTH) channel = (int)(((float)j) / (height - 1) * 255); else channel = (int)(((float)i) / (width - 1) * 255); colorref = 0xff000000 + channel * 0x00010101; break; case packedTexRenderDepthStep: if (function == COLOR_CHECK_DEPTH) { if (j < height * TOLERANCE_LOW) channel = (int)(((float)j) / (height - 1) * 255); else if (j > height * TOLERANCE_HIGH) channel = 255 - (int)(((float)j) / (height - 1) * 255); else skip = 1; // give some tolerance to pixels in the middle } else channel = 0; colorref = 0xff000000 + channel * 0x00010101; break; case packedTexRenderStencilStep: if (j < height * TOLERANCE_LOW) { if (function == COLOR_CHECK_DEPTH) channel = (int)(((float)j) / (height - 1) * 255); else channel = 255; } else if (j > height * TOLERANCE_HIGH) channel = (function == COLOR_CHECK_DEPTH) ? 255 : 0; else skip = 1; // give some tolerance to pixels in the middle colorref = 0xff000000 + channel * 0x00010101; break; case verifyCopyTexImage: if (j < height * TOLERANCE_LOW) { if (function == COLOR_CHECK_DEPTH) channel = (int)(((float)j) / (height - 1) * 255); else channel = 1; } else if (j > height * TOLERANCE_HIGH) { channel = (function == COLOR_CHECK_DEPTH) ? 127 : 1; } else { skip = 1; // give some tolerance to pixels in the middle } colorref = 0xff000000 + channel * 0x00010101; break; case verifyPartialAttachments: colorref = 0xffffffff; break; case verifyMixedAttachments: if (j > height * TOLERANCE_HIGH) colorref = 0xffffffff; else if (j < height * TOLERANCE_LOW) colorref = 0xcccccccc; else skip = 1; break; case verifyClearBufferDepth: if ((i & 0xff) == 0xff) colorref = 0xffffffff; else colorref = 0xcccccccc; break; case verifyClearBufferStencil: if (i > width * TOLERANCE_HIGH) colorref = 0xffffffff; else if (i < width * TOLERANCE_LOW) colorref = 0xcccccccc; else skip = 1; break; case verifyClearBufferDepthStencil: colorref = 0xffffffff; break; case verifyBlit: if (j > height * TOLERANCE_HIGH) colorref = 0xffffffff; else if (j < height * TOLERANCE_LOW) colorref = 0xcccccccc; else skip = 1; break; default: colorref = 0xdeadbeef; break; } if (skip) skip = 0; else if (color != colorref) { float d = (float)(color & 0xff) / 0xff; float dref = (float)(colorref & 0xff) / 0xff; if (!((function == COLOR_CHECK_DEPTH) && (deFloatAbs(d - dref) < EPSILON))) { result = false; count++; } } index++; } } if (count) { m_testCtx.getLog() << tcu::TestLog::Message << "*** Color comparison failed" << tcu::TestLog::EndMessage; result = false; } return result; } // Verify DepthStencil texture by replicating it to color channels // so it can be read using ReadPixels in Halti. bool BaseTest::doReadPixels(GLuint texture, int function) { bool result = true; const glw::Functions& gl = m_context.getRenderContext().getFunctions(); GLuint fbo; gl.genFramebuffers(1, &fbo); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); GLuint texColor; gl.genTextures(1, &texColor); gl.bindTexture(GL_TEXTURE_2D, texColor); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, TEX_SIZE, TEX_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColor, 0); setDrawReadBuffer(GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT0); // Step 1: Verify depth values GLenum status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { m_testCtx.getLog() << tcu::TestLog::Message << "Framebuffer is incomplete: " << status << tcu::TestLog::EndMessage; result = false; } else { setupTextureProgram(); gl.bindTexture(GL_TEXTURE_2D, texture); gl.disable(GL_DEPTH_TEST); gl.depthMask(GL_FALSE); gl.disable(GL_STENCIL_TEST); gl.viewport(0, 0, TEX_SIZE, TEX_SIZE); gl.clearColor(0.8f, 0.8f, 0.8f, 0.8f); gl.clear(GL_COLOR_BUFFER_BIT); drawQuad(DEFAULT, m_textureProgram); std::vector<GLuint> dataColor(TEX_SIZE * TEX_SIZE, 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, &dataColor[0]); result &= verifyColorGradient(&dataColor[0], function, COLOR_CHECK_DEPTH, TEX_SIZE, TEX_SIZE); // Step 2: Verify stencil values gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texture, 0); status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { m_testCtx.getLog() << tcu::TestLog::Message << "Framebuffer is incomplete: " << status << tcu::TestLog::EndMessage; result = false; } else { GLint uColor; setupColorProgram(uColor); gl.clearColor(0.8f, 0.8f, 0.8f, 0.8f); gl.clear(GL_COLOR_BUFFER_BIT); gl.enable(GL_STENCIL_TEST); for (int i = 0; i < 256; i++) { float v = i / 255.0f; gl.uniform4f(uColor, v, v, v, 1.0f); gl.stencilFunc(GL_EQUAL, i, 0xFF); gl.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); drawQuad(DEFAULT, m_colorProgram); } gl.disable(GL_STENCIL_TEST); dataColor.assign(dataColor.size(), 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, &dataColor[0]); result &= verifyColorGradient(&dataColor[0], function, COLOR_CHECK_STENCIL, TEX_SIZE, TEX_SIZE); } } // clean up restoreDrawReadBuffer(); gl.deleteFramebuffers(1, &fbo); gl.deleteTextures(1, &texColor); return result; } class InitialStateTest : public deqp::TestCase { public: InitialStateTest(deqp::Context& context); virtual ~InitialStateTest(); virtual tcu::TestNode::IterateResult iterate(void); }; InitialStateTest::InitialStateTest(deqp::Context& context) : deqp::TestCase(context, "initial_state", "TEXTURE_STENCIL_SIZE for the default texture objects should be 0") { } InitialStateTest::~InitialStateTest() { } tcu::TestNode::IterateResult InitialStateTest::iterate(void) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); for (int i = 0; i < DE_LENGTH_OF_ARRAY(coreTexTargets); i++) { GLenum target = coreTexTargets[i]; GLfloat fp; gl.getTexLevelParameterfv(target, 0, GL_TEXTURE_STENCIL_SIZE, &fp); if (deFloatCmpNE(fp, 0.0f)) { m_testCtx.getLog() << tcu::TestLog::Message << "gl.getTexLevelParameterfv: Parameter is not 0" << tcu::TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } GLint ip; gl.getTexLevelParameteriv(target, 0, GL_TEXTURE_STENCIL_SIZE, &ip); if (deFloatCmpNE((float)ip, 0.0f)) { m_testCtx.getLog() << tcu::TestLog::Message << "gl.getTexLevelParameteriv: Parameter is not 0" << tcu::TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } } return STOP; } class ValidateErrorsTest : public BaseTest { public: ValidateErrorsTest(deqp::Context& context, const TypeFormat& tf); virtual ~ValidateErrorsTest(); virtual tcu::TestNode::IterateResult iterate(void); protected: bool checkErrors(); }; ValidateErrorsTest::ValidateErrorsTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } ValidateErrorsTest::~ValidateErrorsTest() { } tcu::TestNode::IterateResult ValidateErrorsTest::iterate(void) { createTextures(); if (checkErrors()) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); destroyTextures(); return STOP; } // Error tests [desktop only]: // - The error INVALID_ENUM is generated if ReadPixels is // called where format is DEPTH_STENCIL and type is not // UNSIGNED_INT_24_8, or FLOAT_32_UNSIGNED_INT_24_8_REV. // - The error INVALID_OPERATION is generated if ReadPixels // is called where type is UNSIGNED_INT_24_8 or // FLOAT_32_UNSIGNED_INT_24_8_REV and format is not DEPTH_STENCIL. // - The error INVALID_OPERATION is generated if ReadPixels // is called where format is DEPTH_STENCIL and there is not both a // depth buffer and a stencil buffer. // - Calling GetTexImage with a <format> of DEPTH_COMPONENT when the // base internal format of the texture image is not DEPTH_COMPONENT // or DEPTH_STENCIL causes the error INVALID_OPERATION. // - Calling GetTexImage with a <format> of DEPTH_STENCIL when // the base internal format of the texture image is not // DEPTH_STENCIL causes the error INVALID_OPERATION. // Error tests [Halti only]: // - The error INVALID_ENUM is generated if ReadPixels is // called where format is DEPTH_STENCIL. // Error tests [desktop and Halti]: // - TexImage generates INVALID_OPERATION if one of the base internal format // and format is DEPTH_COMPONENT or DEPTH_STENCIL, and the other is neither // of these values. // - The error INVALID_OPERATION is generated if CopyTexImage // is called where format is DEPTH_STENCIL and there is not both a // depth buffer and a stencil buffer. bool ValidateErrorsTest::checkErrors() { bool result = true; GLuint fbo, fbo2; GLuint texColor; std::vector<GLfloat> data(4 * TEX_SIZE * TEX_SIZE, 0.0f); const glu::RenderContext& renderContext = m_context.getRenderContext(); const glw::Functions& gl = renderContext.getFunctions(); bool isContextES = glu::isContextTypeES(renderContext.getType()); if (isContextES) { gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexImage]); setDrawReadBuffer(GL_NONE, GL_NONE); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); GLenum error = gl.getError(); if (((GL_INVALID_OPERATION != error) && (GL_INVALID_ENUM != error)) && !((GL_NO_ERROR == error) && m_context.getContextInfo().isExtensionSupported("GL_NV_read_depth_stencil"))) { gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); if (gl.getError() != GL_INVALID_OPERATION) result = false; } restoreDrawReadBuffer(); gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); } else { gl.bindTexture(GL_TEXTURE_2D, m_textures[packedTexImage]); gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexImage]); setDrawReadBuffer(GL_NONE, GL_NONE); for (unsigned int i = 0; i < m_nonDepthStencilTypesCount; i++) { gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_DEPTH_STENCIL, m_nonDepthStencilTypes[i], &data[0]); if (gl.getError() != GL_INVALID_ENUM) result = false; } for (unsigned int i = 0; i < m_nonDepthStencilFormatsCount; i++) { gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, m_nonDepthStencilFormats[i], m_typeFormat.type, &data[0]); if (gl.getError() != GL_INVALID_OPERATION) result = false; } for (int i = 0; i < 2; i++) { // setup texture/fbo gl.genTextures(1, &texColor); gl.genFramebuffers(1, &fbo); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); GLenum attachmentType = (i == 0) ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT; gl.framebufferTexture2D(GL_FRAMEBUFFER, attachmentType, GL_TEXTURE_2D, m_textures[packedTexImage], 0); gl.bindTexture(GL_TEXTURE_2D, texColor); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, TEX_SIZE, TEX_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColor, 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); if (gl.getError() != GL_INVALID_OPERATION) result = false; gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); gl.bindTexture(GL_TEXTURE_2D, 0); gl.deleteFramebuffers(1, &fbo); gl.deleteTextures(1, &texColor); } for (unsigned int i = 0; i < m_otherBaseFormatsCount; i++) { GLenum format = m_otherBaseFormats[i]; gl.genTextures(1, &texColor); gl.bindTexture(GL_TEXTURE_2D, texColor); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, format, TEX_SIZE, TEX_SIZE, 0, format, GL_UNSIGNED_BYTE, 0); if (format != GL_DEPTH_COMPONENT) { gl.getTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, &data[0]); if (gl.getError() != GL_INVALID_OPERATION) result = false; } gl.getTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, &data[0]); if (gl.getError() != GL_INVALID_OPERATION) result = false; gl.deleteTextures(1, &texColor); } } bool coreGL = !glu::isContextTypeES(m_context.getRenderContext().getType()); for (int i = 0; i < 4; i++) { int limit; if (i < 2) limit = m_nonDepthStencilFormatsCount; else limit = m_otherBaseFormatsCount; for (int j = 0; j < limit; j++) { GLint internalFormat = 0; GLint format = 0; gl.genTextures(1, &texColor); gl.bindTexture(GL_TEXTURE_2D, texColor); setupTexture(); switch (i) { case 0: internalFormat = GL_DEPTH_COMPONENT; format = m_nonDepthStencilFormats[j]; break; case 1: internalFormat = GL_DEPTH_STENCIL; format = m_nonDepthStencilFormats[j]; break; case 2: internalFormat = m_otherBaseFormats[j]; format = GL_DEPTH_COMPONENT; break; case 3: internalFormat = m_otherBaseFormats[j]; format = GL_DEPTH_STENCIL; break; } gl.texImage2D(GL_TEXTURE_2D, 0, internalFormat, TEX_SIZE, TEX_SIZE, 0, format, (format == GL_DEPTH_STENCIL) ? GL_UNSIGNED_INT_24_8 : GL_UNSIGNED_BYTE, 0); GLenum expectedError = GL_INVALID_OPERATION; if (coreGL && (format == GL_STENCIL_INDEX)) { // The OpenGL 4.3 spec is imprecise about what error this should generate // see Bugzilla 10134: TexImage with a <format> of STENCIL_INDEX // 4.3 core (Feb 14 2013) p. 174: // (describing TexImage3D) // The format STENCIL_INDEX is not allowed. // The new OpenGL 4.4 feature ARB_texture_stencil8 removes this error. So // the best we can do for OpenGL is to just allow any error, or no error, // for this specific case. gl.getError(); } else if (gl.getError() != expectedError) result = false; gl.bindTexture(GL_TEXTURE_2D, 0); gl.deleteTextures(1, &texColor); } } gl.genFramebuffers(1, &fbo); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexImage], 0); gl.genFramebuffers(1, &fbo2); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo2); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_textures[packedTexImage], 0); GLuint tex; gl.genTextures(1, &tex); gl.bindTexture(GL_TEXTURE_2D, tex); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_STENCIL, m_typeFormat.type, 0); for (int i = 0; i < 2; i++) { switch (i) { case 0: gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); gl.bindTexture(GL_TEXTURE_2D, tex); break; case 1: gl.bindFramebuffer(GL_FRAMEBUFFER, fbo2); gl.bindTexture(GL_TEXTURE_2D, tex); break; } setDrawReadBuffer(GL_NONE, GL_NONE); gl.copyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL, 0, 0, TEX_SIZE, TEX_SIZE, 0); GLenum error = gl.getError(); if ((GL_INVALID_OPERATION != error) && (GL_INVALID_ENUM != error)) { gl.copyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL, 0, 0, TEX_SIZE, TEX_SIZE, 0); if (gl.getError() != GL_INVALID_OPERATION) result = false; } restoreDrawReadBuffer(); gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); } gl.bindTexture(GL_TEXTURE_2D, 0); gl.deleteTextures(1, &tex); gl.deleteFramebuffers(1, &fbo); gl.deleteFramebuffers(1, &fbo2); return result; } class VerifyReadPixelsTest : public BaseTest { public: VerifyReadPixelsTest(deqp::Context& context, const TypeFormat& tf); virtual ~VerifyReadPixelsTest(); virtual tcu::TestNode::IterateResult iterate(void); }; VerifyReadPixelsTest::VerifyReadPixelsTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } VerifyReadPixelsTest::~VerifyReadPixelsTest() { } tcu::TestNode::IterateResult VerifyReadPixelsTest::iterate(void) { // Use readpixels to verify the results for the 5 textures above are correct. // Note that in ES you can only use gl.readpixels on color buffers. // Test method: // - on desktop: ReadPixel DEPTH_STENCIL value to buffer. Verify gradient. // - on desktop/Halti: Create FBO with color/depth/stencil attachment. // Draw a quad with depth texture bound. Verify gradient. // Draw 256 times using stencil test and gradient color. Verify gradient. const glu::RenderContext& renderContext = m_context.getRenderContext(); const glw::Functions& gl = renderContext.getFunctions(); std::size_t dataSize = static_cast<std::size_t>(TEX_SIZE * TEX_SIZE * m_typeFormat.size); std::vector<GLubyte> data(dataSize); createTextures(); renderToTextures(); bool result = true; for (int i = 0; i < NUM_TEXTURES; i++) { // Read DEPTH_STENCIL value, applies only to desktop if (!glu::isContextTypeES(renderContext.getType())) { gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[i]); setDrawReadBuffer(GL_NONE, GL_NONE); data.assign(TEX_SIZE * TEX_SIZE * m_typeFormat.size, 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); result &= verifyDepthStencilGradient(&data[0], i, TEX_SIZE, TEX_SIZE); restoreDrawReadBuffer(); } // On ES3.2 we have to render to color buffer to verify. // We can run this also on desktop. result &= doReadPixels(m_textures[i], i); } gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class VerifyGetTexImageTest : public BaseTest { public: VerifyGetTexImageTest(deqp::Context& context, const TypeFormat& tf); virtual ~VerifyGetTexImageTest(); virtual tcu::TestNode::IterateResult iterate(void); }; VerifyGetTexImageTest::VerifyGetTexImageTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } VerifyGetTexImageTest::~VerifyGetTexImageTest() { } tcu::TestNode::IterateResult VerifyGetTexImageTest::iterate(void) { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); std::vector<GLubyte> data(TEX_SIZE * TEX_SIZE * m_typeFormat.size); createTextures(); renderToTextures(); bool result = true; for (int i = 0; i < NUM_TEXTURES; i++) { data.assign(TEX_SIZE * TEX_SIZE * m_typeFormat.size, 0); gl.bindTexture(GL_TEXTURE_2D, m_textures[i]); gl.getTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); result &= verifyDepthStencilGradient(&data[0], i, TEX_SIZE, TEX_SIZE); } destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class VerifyCopyTexImageTest : public BaseTest { public: VerifyCopyTexImageTest(deqp::Context& context, const TypeFormat& tf); virtual ~VerifyCopyTexImageTest(); virtual tcu::TestNode::IterateResult iterate(void); }; VerifyCopyTexImageTest::VerifyCopyTexImageTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } VerifyCopyTexImageTest::~VerifyCopyTexImageTest() { } tcu::TestNode::IterateResult VerifyCopyTexImageTest::iterate(void) { // After rendering to depth and stencil, CopyTexImage the results to a new // DEPTH_STENCIL texture. Attach this texture to a new FBO. Verify that // depth and stencil tests work with the copied data. createTextures(); renderToTextures(); bool result = true; const glw::Functions& gl = m_context.getRenderContext().getFunctions(); // setup shader GLint uColor; setupColorProgram(uColor); // setup and copy texture/fbo GLuint tex; gl.genTextures(1, &tex); GLuint fbo; gl.genFramebuffers(1, &fbo); gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexRender]); gl.bindTexture(GL_TEXTURE_2D, tex); setupTexture(); setDrawReadBuffer(GL_NONE, GL_NONE); gl.texImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_STENCIL, m_typeFormat.type, NULL); gl.copyTexImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, 0, 0, TEX_SIZE, TEX_SIZE, 0); restoreDrawReadBuffer(); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, tex, 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, tex, 0); setDrawReadBuffer(GL_NONE, GL_NONE); int status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { m_testCtx.getLog() << tcu::TestLog::Message << "Framebuffer is incomplete: " << status << tcu::TestLog::EndMessage; result = false; restoreDrawReadBuffer(); } else { // render gl.enable(GL_DEPTH_TEST); gl.depthFunc(GL_LEQUAL); gl.viewport(0, 0, TEX_SIZE, TEX_SIZE); gl.enable(GL_STENCIL_TEST); gl.stencilFunc(GL_EQUAL, 0x1, 0xFF); gl.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); drawQuad(DEFAULT, m_colorProgram); gl.disable(GL_STENCIL_TEST); // verify std::vector<GLubyte> data(TEX_SIZE * TEX_SIZE * m_typeFormat.size, 0); gl.getTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); result &= verifyDepthStencilGradient(&data[0], verifyCopyTexImage, TEX_SIZE, TEX_SIZE); restoreDrawReadBuffer(); result &= doReadPixels(tex, verifyCopyTexImage); } // clean up gl.deleteFramebuffers(1, &fbo); gl.deleteTextures(1, &tex); destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class VerifyPartialAttachmentsTest : public BaseTest { public: VerifyPartialAttachmentsTest(deqp::Context& context, const TypeFormat& tf); virtual ~VerifyPartialAttachmentsTest(); virtual tcu::TestNode::IterateResult iterate(void); }; VerifyPartialAttachmentsTest::VerifyPartialAttachmentsTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } VerifyPartialAttachmentsTest::~VerifyPartialAttachmentsTest() { } tcu::TestNode::IterateResult VerifyPartialAttachmentsTest::iterate(void) { createTextures(); renderToTextures(); bool result = true; // - Create an FBO with a packed depth stencil renderbuffer attached to // DEPTH_ATTACHMENT only. If this FBO is complete, stencil test must act as // if there is no stencil buffer (always pass.) // - Create an FBO with a packed depth stencil renderbuffer attached to // STENCIL_ATTACHMENT only. If this FBO is complete, depth test must act as // if there is no depth buffer (always pass.) // - Create an FBO with a packed depth stencil renderbuffer attached to // STENCIL_ATTACHMENT only. If this FBO is complete, occlusion query must // act as if there is no depth buffer (always pass.) const glu::RenderContext& renderContext = m_context.getRenderContext(); const glw::Functions& gl = renderContext.getFunctions(); bool isContextES = glu::isContextTypeES(renderContext.getType()); // setup shader GLint uColor; setupColorProgram(uColor); GLuint occ; gl.genQueries(1, &occ); for (int i = 0; i < 3; i++) { // setup fbo GLuint fbo; gl.genFramebuffers(1, &fbo); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); GLuint rbo[2]; // color, D/S gl.genRenderbuffers(2, rbo); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[0]); gl.renderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, TEX_SIZE, TEX_SIZE); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[1]); gl.renderbufferStorage(GL_RENDERBUFFER, m_typeFormat.format, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[0]); setDrawReadBuffer(GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT0); switch (i) { case 0: gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo[1]); break; case 1: case 2: gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[1]); break; default: result = false; } if (!result) break; int status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { m_testCtx.getLog() << tcu::TestLog::Message << "Framebuffer is incomplete: " << status << tcu::TestLog::EndMessage; result = false; } else { // render gl.viewport(0, 0, TEX_SIZE, TEX_SIZE); if (isContextES) gl.clearDepthf(1.0f); else gl.clearDepth(1.0); gl.clearStencil(0); gl.clearColor(0.8f, 0.8f, 0.8f, 0.8f); gl.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); switch (i) { case 0: gl.disable(GL_DEPTH_TEST); gl.enable(GL_STENCIL_TEST); gl.stencilFunc(GL_NEVER, 0xFF, 0xFF); gl.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); break; case 1: gl.enable(GL_DEPTH_TEST); gl.depthFunc(GL_NEVER); gl.disable(GL_STENCIL_TEST); break; case 2: gl.enable(GL_DEPTH_TEST); gl.depthFunc(GL_NEVER); gl.disable(GL_STENCIL_TEST); gl.beginQuery(GL_ANY_SAMPLES_PASSED, occ); break; default: break; } drawQuad(DEFAULT, m_colorProgram); if (i == 2) { GLuint n; gl.endQuery(GL_ANY_SAMPLES_PASSED); gl.getQueryObjectuiv(occ, GL_QUERY_RESULT, &n); if (n > 0) { drawQuad(DEFAULT, m_colorProgram); } } std::vector<GLuint> data(TEX_SIZE * TEX_SIZE, 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]); result &= verifyColorGradient(&data[0], verifyPartialAttachments, COLOR_CHECK_DEFAULT, TEX_SIZE, TEX_SIZE); } restoreDrawReadBuffer(); gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); // clean up gl.deleteFramebuffers(1, &fbo); gl.deleteRenderbuffers(2, rbo); } gl.deleteQueries(1, &occ); destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class VerifyMixedAttachmentsTest : public BaseTest { public: VerifyMixedAttachmentsTest(deqp::Context& context, const TypeFormat& tf); virtual ~VerifyMixedAttachmentsTest(); virtual tcu::TestNode::IterateResult iterate(void); }; VerifyMixedAttachmentsTest::VerifyMixedAttachmentsTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } VerifyMixedAttachmentsTest::~VerifyMixedAttachmentsTest() { } tcu::TestNode::IterateResult VerifyMixedAttachmentsTest::iterate(void) { // Create FBOs that mix DEPTH_STENCIL renderbuffers with DEPTH or STENCIL // renderbuffers. If these FBOs are complete, depth and stencil test // must work properly. // Create an FBO with two different packed depth stencil renderbuffers, one // attached to DEPTH_ATTACHMENT and the other attached to STENCIL_ATTACHMENT. // Querying DEPTH_STENCIL_ATTACHMENT must fail with INVALID_OPERATION. If // this FBO is complete, depth and stencil tests must work properly. createTextures(); renderToTextures(); bool result = true; const glu::RenderContext& renderContext = m_context.getRenderContext(); const glw::Functions& gl = renderContext.getFunctions(); bool isContextES = glu::isContextTypeES(renderContext.getType()); GLint uColor; setupColorProgram(uColor); for (int i = 0; i < 3; i++) { // set up FBO/RBOs GLuint fbo; gl.genFramebuffers(1, &fbo); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); GLuint rbo[3]; // color, DEPTH_STENCIL, DEPTH/STENCIL gl.genRenderbuffers(3, rbo); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[0]); gl.renderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[0]); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[1]); gl.renderbufferStorage(GL_RENDERBUFFER, m_typeFormat.format, TEX_SIZE, TEX_SIZE); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[2]); switch (i) { case 0: gl.renderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[1]); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo[2]); break; case 1: gl.renderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo[1]); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[2]); break; case 2: gl.renderbufferStorage(GL_RENDERBUFFER, m_typeFormat.format, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo[1]); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[2]); GLint param; gl.getFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &param); if (gl.getError() != GL_INVALID_OPERATION) { m_testCtx.getLog() << tcu::TestLog::Message << "Expected INVALID_OPERATION for DEPTH_STENCIL_ATTACHMENT query" << tcu::TestLog::EndMessage; result = false; } break; } GLenum status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { if (status == GL_FRAMEBUFFER_UNSUPPORTED) { /* The spec only requires "when both depth and stencil attachments are present, implementations are only required to support framebuffer objects where both attachments refer to the same image." Thus, it is accepatable for an implementation returning GL_FRAMEBUFFER_UNSUPPORTED. And the test can NOT be marked as fail. */ } else { m_testCtx.getLog() << tcu::TestLog::Message << "Framebuffer is incomplete" << tcu::TestLog::EndMessage; result = false; } } else { // render // step 1 gl.viewport(0, 0, TEX_SIZE, TEX_SIZE); gl.enable(GL_DEPTH_TEST); gl.depthFunc(GL_LEQUAL); if (isContextES) gl.clearDepthf(1.0f); else gl.clearDepth(1.0); gl.enable(GL_STENCIL_TEST); gl.stencilFunc(GL_ALWAYS, 0x1, 0xFF); gl.stencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); gl.clearStencil(0); gl.clearColor(0.8f, 0.8f, 0.8f, 0.8f); gl.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); drawQuad(DEPTH_SPAN1, m_colorProgram); // step 2 gl.stencilFunc(GL_EQUAL, 0x1, 0xFF); gl.stencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); gl.clearColor(0.8f, 0.8f, 0.8f, 0.8f); gl.clear(GL_COLOR_BUFFER_BIT); drawQuad(DEFAULT, m_colorProgram); std::vector<GLuint> data(TEX_SIZE * TEX_SIZE, 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]); result &= verifyColorGradient(&data[0], verifyMixedAttachments, COLOR_CHECK_DEFAULT, TEX_SIZE, TEX_SIZE); } // clean up gl.deleteRenderbuffers(3, rbo); gl.deleteFramebuffers(1, &fbo); } destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class VerifyParametersTest : public BaseTest { public: VerifyParametersTest(deqp::Context& context, const TypeFormat& tf); virtual ~VerifyParametersTest(); virtual tcu::TestNode::IterateResult iterate(void); }; VerifyParametersTest::VerifyParametersTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } VerifyParametersTest::~VerifyParametersTest() { } tcu::TestNode::IterateResult VerifyParametersTest::iterate(void) { // Verify GetFramebufferAttachmentParameter queries of each <pname> on // DEPTH_STENCIL_ATTACHMENT work correctly if both attachments are populated // with the same object. createTextures(); renderToTextures(); bool result = true; const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexImage]); GLint param; gl.getFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &param); if (param != GL_TEXTURE) { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid value for GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: " << param << tcu::TestLog::EndMessage; m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } const AttachmentParam* attachmentParams = getAttachmentParams(); for (GLuint i = 0; i < m_attachmentParamsCount; i++) { int ref; GLenum pname = attachmentParams[i].pname; if (GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE == pname) { gl.getFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, pname, &param); if (gl.getError() != GL_INVALID_OPERATION) result = false; continue; } gl.getFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, pname, &param); ref = attachmentParams[i].value; if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME) ref = m_textures[packedTexImage]; if (param != ref) { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid value for pname " << attachmentParams[i].pname << ": " << param << " ( expected " << ref << ")" << tcu::TestLog::EndMessage; result = false; } } destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class RenderbuffersTest : public BaseTest { public: RenderbuffersTest(deqp::Context& context, const TypeFormat& tf); virtual ~RenderbuffersTest(); virtual tcu::TestNode::IterateResult iterate(void); }; RenderbuffersTest::RenderbuffersTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } RenderbuffersTest::~RenderbuffersTest() { } tcu::TestNode::IterateResult RenderbuffersTest::iterate(void) { createTextures(); renderToTextures(); bool result = true; // Verify RENDERBUFFER_DEPTH_SIZE and RENDERBUFFER_STENCIL_SIZE report // appropriate values for for DEPTH_STENCIL renderbuffers. const glw::Functions& gl = m_context.getRenderContext().getFunctions(); gl.bindFramebuffer(GL_FRAMEBUFFER, m_framebuffers[packedTexImage]); GLuint rbo; gl.genRenderbuffers(1, &rbo); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo); gl.renderbufferStorage(GL_RENDERBUFFER, m_typeFormat.format, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); GLint param; gl.getRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_DEPTH_SIZE, &param); if (param != m_typeFormat.d) { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid depth: " << param << ", expected: " << m_typeFormat.d << tcu::TestLog::EndMessage; result = false; } gl.getRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_STENCIL_SIZE, &param); if (param != m_typeFormat.s) { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid stencil: " << param << ", expected: " << m_typeFormat.s << tcu::TestLog::EndMessage; result = false; } gl.bindRenderbuffer(GL_RENDERBUFFER, 0); gl.deleteRenderbuffers(1, &rbo); gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class StencilSizeTest : public BaseTest { public: StencilSizeTest(deqp::Context& context, const TypeFormat& tf); virtual ~StencilSizeTest(); virtual tcu::TestNode::IterateResult iterate(void); }; StencilSizeTest::StencilSizeTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } StencilSizeTest::~StencilSizeTest() { } tcu::TestNode::IterateResult StencilSizeTest::iterate(void) { // [desktop only] Verify TEXTURE_STENCIL_SIZE reports 8 for DEPTH_STENCIL // textures, and 0 for RGBA and DEPTH_COMPONENT textures. createTextures(); renderToTextures(); const glw::Functions& gl = m_context.getRenderContext().getFunctions(); bool result = true; GLint param; gl.bindTexture(GL_TEXTURE_2D, m_textures[packedTexImage]); gl.getTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_STENCIL_SIZE, &param); if (param != 8) { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid value for DEPTH_STENCIL stencil size: " << param << tcu::TestLog::EndMessage; result = false; } GLuint texRGBA; gl.genTextures(1, &texRGBA); gl.bindTexture(GL_TEXTURE_2D, texRGBA); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, TEX_SIZE, TEX_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); gl.getTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_STENCIL_SIZE, &param); if (param != 0) { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid value for RGBA stencil size: " << param << tcu::TestLog::EndMessage; result = false; } gl.deleteTextures(1, &texRGBA); GLuint texDepth; gl.genTextures(1, &texDepth); gl.bindTexture(GL_TEXTURE_2D, texDepth); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 0); gl.getTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_STENCIL_SIZE, &param); if (param != 0) { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid value for DEPTH_COMPONENT stencil size: " << param << tcu::TestLog::EndMessage; result = false; } gl.deleteTextures(1, &texDepth); destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class ClearBufferTest : public BaseTest { public: ClearBufferTest(deqp::Context& context, const TypeFormat& tf); virtual ~ClearBufferTest(); virtual tcu::TestNode::IterateResult iterate(void); }; ClearBufferTest::ClearBufferTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } ClearBufferTest::~ClearBufferTest() { } tcu::TestNode::IterateResult ClearBufferTest::iterate(void) { // Verify ClearBufferfv correctly clears the depth channel of a DEPTH_STENCIL // FBO attachment (and does not touch the stencil channel.) // Verify ClearBufferiv correctly clears the stencil channel of a // DEPTH_STENCIL FBO attachment (and does not touch the depth channel.) // Verify ClearBufferfi correctly clears the depth and stencil channels of a // DEPTH_STENCIL FBO attachment. createTextures(); renderToTextures(); bool result = true; GLfloat valuef; GLint valuei; GLenum status; const glw::Functions& gl = m_context.getRenderContext().getFunctions(); // setup shader GLint uColor; setupColorProgram(uColor); for (int i = 0; i < 3; i++) { // setup texture/fbo GLuint tex; GLuint texColor; GLuint fbo; gl.genTextures(1, &tex); gl.genTextures(1, &texColor); gl.genFramebuffers(1, &fbo); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); gl.bindTexture(GL_TEXTURE_2D, tex); setupTexture(); std::vector<GLbyte> data; createGradient(data); gl.texImage2D(GL_TEXTURE_2D, 0, m_typeFormat.format, TEX_SIZE, TEX_SIZE, 0, GL_DEPTH_STENCIL, m_typeFormat.type, &data[0]); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, tex, 0); gl.bindTexture(GL_TEXTURE_2D, texColor); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, TEX_SIZE, TEX_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColor, 0); setDrawReadBuffer(GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT0); status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { m_testCtx.getLog() << tcu::TestLog::Message << "Framebuffer is incomplete: " << status << tcu::TestLog::EndMessage; result = false; } else { // clear relevant buffers switch (i) { case 0: valuef = 1.0f; gl.clearBufferfv(GL_DEPTH, 0, &valuef); break; case 1: valuei = 0xff; gl.clearBufferiv(GL_STENCIL, 0, &valuei); break; case 2: valuef = 1.0f; valuei = 0xff; gl.clearBufferfi(GL_DEPTH_STENCIL, 0, valuef, valuei); break; } // render reference image gl.viewport(0, 0, TEX_SIZE, TEX_SIZE); gl.enable(GL_DEPTH_TEST); gl.depthFunc(GL_LEQUAL); gl.enable(GL_STENCIL_TEST); gl.stencilFunc(GL_EQUAL, 0xFF, 0xFF); gl.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); gl.clearColor(0.8f, 0.8f, 0.8f, 0.8f); gl.clear(GL_COLOR_BUFFER_BIT); drawQuad(DEFAULT, m_colorProgram); // verify std::vector<GLubyte> readData(TEX_SIZE * TEX_SIZE * 4, 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, &readData[0]); result &= verifyColorGradient(&readData[0], verifyClearBufferDepth + i, COLOR_CHECK_DEFAULT, TEX_SIZE, TEX_SIZE); } // destroy texture/fbo restoreDrawReadBuffer(); gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); gl.bindTexture(GL_TEXTURE_2D, 0); gl.deleteFramebuffers(1, &fbo); gl.deleteTextures(1, &tex); gl.deleteTextures(1, &texColor); } destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class BlitTest : public BaseTest { public: BlitTest(deqp::Context& context, const TypeFormat& tf); virtual ~BlitTest(); virtual tcu::TestNode::IterateResult iterate(void); }; BlitTest::BlitTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } BlitTest::~BlitTest() { } tcu::TestNode::IterateResult BlitTest::iterate(void) { // Verify that NEAREST filtered blits of DEPTH and/or STENCIL between two // FBOs with the same format packed depth stencil attachment work. Test // non-multisample [1->1], multisample resolve [N->1], and multisample // replicate [1->N] blits, for each supported value of N up to MAX_SAMPLES. createTextures(); renderToTextures(); GLuint fbo[3]; // Framebuffers: source, dest, downsample GLuint rbo[4]; // Renderbuffers: source D/S, dest D/S, dest color, downsample color GLint maxSamples; int srcSamples, destSamples; bool result = true; const glu::RenderContext& renderContext = m_context.getRenderContext(); const glw::Functions& gl = renderContext.getFunctions(); bool isContextES = glu::isContextTypeES(renderContext.getType()); std::vector<GLuint> data(TEX_SIZE * TEX_SIZE); GLint uColor; setupColorProgram(uColor); gl.getIntegerv(GL_MAX_SAMPLES, &maxSamples); // ES does not allow SAMPLE_BUFFERS for the draw frame // buffer is greater than zero when doing a blit. int loopCount = isContextES ? 1 : 2; for (int j = 0; j < loopCount; j++) { for (int i = 0; i <= maxSamples; i++) { // Create FBO/RBO gl.genFramebuffers(3, fbo); gl.genRenderbuffers(4, rbo); if (j == 0) { srcSamples = i; destSamples = 0; } else { srcSamples = 0; destSamples = i; } gl.bindFramebuffer(GL_FRAMEBUFFER, fbo[0]); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[0]); gl.renderbufferStorageMultisample(GL_RENDERBUFFER, srcSamples, m_typeFormat.format, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[0]); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo[1]); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[1]); gl.renderbufferStorageMultisample(GL_RENDERBUFFER, destSamples, m_typeFormat.format, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo[1]); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[2]); gl.renderbufferStorageMultisample(GL_RENDERBUFFER, destSamples, GL_RGBA8, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[2]); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo[2]); gl.bindRenderbuffer(GL_RENDERBUFFER, rbo[3]); gl.renderbufferStorageMultisample(GL_RENDERBUFFER, 0, GL_RGBA8, TEX_SIZE, TEX_SIZE); gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[3]); // Render gl.bindFramebuffer(GL_FRAMEBUFFER, fbo[0]); setDrawReadBuffer(GL_NONE, GL_NONE); gl.viewport(0, 0, TEX_SIZE, TEX_SIZE); gl.enable(GL_DEPTH_TEST); gl.depthFunc(GL_LEQUAL); if (isContextES) gl.clearDepthf(1.0f); else gl.clearDepth(1.0); gl.enable(GL_STENCIL_TEST); gl.stencilFunc(GL_ALWAYS, 0x1, 0xFF); gl.stencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); gl.clearStencil(0); gl.clearColor(0.8f, 0.8f, 0.8f, 0.8f); gl.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); drawQuad(DEPTH_SPAN1, m_colorProgram); restoreDrawReadBuffer(); // Blit gl.bindFramebuffer(GL_READ_FRAMEBUFFER, fbo[0]); gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[1]); setDrawReadBuffer(GL_NONE, GL_NONE); gl.blitFramebuffer(0, 0, TEX_SIZE, TEX_SIZE, 0, 0, TEX_SIZE, TEX_SIZE, GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST); restoreDrawReadBuffer(); // Verify gl.bindFramebuffer(GL_FRAMEBUFFER, fbo[1]); setDrawReadBuffer(GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT0); gl.stencilFunc(GL_EQUAL, 0x1, 0xFF); gl.stencilOp(GL_KEEP, GL_KEEP, GL_KEEP); gl.clear(GL_COLOR_BUFFER_BIT); drawQuad(DEFAULT, m_colorProgram); restoreDrawReadBuffer(); // Downsample blit gl.bindFramebuffer(GL_READ_FRAMEBUFFER, fbo[1]); gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[2]); setDrawReadBuffer(GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT0); gl.blitFramebuffer(0, 0, TEX_SIZE, TEX_SIZE, 0, 0, TEX_SIZE, TEX_SIZE, GL_COLOR_BUFFER_BIT, GL_NEAREST); restoreDrawReadBuffer(); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo[2]); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]); result &= verifyColorGradient(&data[0], verifyBlit, COLOR_CHECK_DEFAULT, TEX_SIZE, TEX_SIZE); // Clean up gl.bindFramebuffer(GL_FRAMEBUFFER, m_defaultFBO); gl.bindRenderbuffer(GL_RENDERBUFFER, 0); gl.deleteRenderbuffers(4, rbo); gl.deleteFramebuffers(3, fbo); } } destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class StencilTexturingTest : public BaseTest { public: StencilTexturingTest(deqp::Context& context, const TypeFormat& tf); virtual ~StencilTexturingTest(); virtual tcu::TestNode::IterateResult iterate(void); }; StencilTexturingTest::StencilTexturingTest(deqp::Context& context, const TypeFormat& tf) : BaseTest(context, tf) { } StencilTexturingTest::~StencilTexturingTest() { } tcu::TestNode::IterateResult StencilTexturingTest::iterate(void) { // Verifies that either depth or stencil can be sampled depending on // GL_DEPTH_STENCIL_TEXTURE_MODE const glu::RenderContext& renderContext = m_context.getRenderContext(); glu::ContextType contextType = renderContext.getType(); const glw::Functions& gl = renderContext.getFunctions(); bool notSupported = false; if (glu::isContextTypeES(contextType)) notSupported = !glu::contextSupports(contextType, glu::ApiType::es(3, 1)); else notSupported = !glu::contextSupports(contextType, glu::ApiType::core(4, 3)); if (notSupported) { m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "stencil_texturing extension is not supported"); return STOP; } createTextures(); renderToTextures(); bool result = true; GLuint fbo; gl.genFramebuffers(1, &fbo); gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); GLuint texColor; gl.genTextures(1, &texColor); gl.bindTexture(GL_TEXTURE_2D, texColor); setupTexture(); gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, TEX_SIZE, TEX_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColor, 0); setDrawReadBuffer(GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT0); // Step 1: Verify depth values GLenum status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { m_testCtx.getLog() << tcu::TestLog::Message << "Framebuffer is incomplete: " << status << tcu::TestLog::EndMessage; result = false; } else { gl.bindTexture(GL_TEXTURE_2D, m_textures[packedTexImage]); gl.disable(GL_DEPTH_TEST); gl.depthMask(GL_FALSE); gl.disable(GL_STENCIL_TEST); gl.viewport(0, 0, TEX_SIZE, TEX_SIZE); gl.clearColor(0.8f, 0.8f, 0.8f, 0.8f); gl.clear(GL_COLOR_BUFFER_BIT); gl.texParameteri(GL_TEXTURE_2D, GL_DEPTH_STENCIL_TEXTURE_MODE, GL_DEPTH_COMPONENT); setupTextureProgram(); drawQuad(DEFAULT, m_textureProgram); std::vector<GLuint> dataColor(TEX_SIZE * TEX_SIZE, 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, &dataColor[0]); result &= verifyColorGradient(&dataColor[0], packedTexImage, COLOR_CHECK_DEPTH, TEX_SIZE, TEX_SIZE); // Step 2: Verify stencil values gl.texParameteri(GL_TEXTURE_2D, GL_DEPTH_STENCIL_TEXTURE_MODE, GL_STENCIL_INDEX); setupStencilProgram(); drawQuad(DEFAULT, m_stencilProgram); dataColor.assign(TEX_SIZE * TEX_SIZE, 0); gl.readPixels(0, 0, TEX_SIZE, TEX_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, &dataColor[0]); result &= verifyColorGradient(&dataColor[0], packedTexImage, COLOR_CHECK_DEFAULT, TEX_SIZE, TEX_SIZE); } restoreDrawReadBuffer(); gl.deleteFramebuffers(1, &fbo); gl.deleteTextures(1, &texColor); destroyTextures(); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } PackedDepthStencilTests::PackedDepthStencilTests(deqp::Context& context) : TestCaseGroup(context, "packed_depth_stencil", "") { } PackedDepthStencilTests::~PackedDepthStencilTests(void) { } void PackedDepthStencilTests::init(void) { TestCaseGroup* validateErrorsGroup = new deqp::TestCaseGroup(m_context, "validate_errors", ""); TestCaseGroup* verifyReadPixelsGroup = new deqp::TestCaseGroup(m_context, "verify_read_pixels", ""); TestCaseGroup* verifyGetTexImageGroup = new deqp::TestCaseGroup(m_context, "verify_get_tex_image", ""); TestCaseGroup* verifyCopyTexImageGroup = new deqp::TestCaseGroup(m_context, "verify_copy_tex_image", ""); TestCaseGroup* verifyPartialAttachmentsGroup = new deqp::TestCaseGroup(m_context, "verify_partial_attachments", ""); TestCaseGroup* verifyMixedAttachmentsGroup = new deqp::TestCaseGroup(m_context, "verify_mixed_attachments", ""); TestCaseGroup* verifyParametersGroup = new deqp::TestCaseGroup(m_context, "verify_parameters", ""); TestCaseGroup* renderbuffersGroup = new deqp::TestCaseGroup(m_context, "renderbuffers", ""); TestCaseGroup* clearBufferGroup = new deqp::TestCaseGroup(m_context, "clear_buffer", ""); TestCaseGroup* blitGroup = new deqp::TestCaseGroup(m_context, "blit", ""); TestCaseGroup* stencilTexturingGroup = new deqp::TestCaseGroup(m_context, "stencil_texturing", ""); TestCaseGroup* stencilSizeGroup = new deqp::TestCaseGroup(m_context, "stencil_size", ""); bool isContextCoreGL = !glu::isContextTypeES(m_context.getRenderContext().getType()); if (isContextCoreGL) validateErrorsGroup->addChild(new InitialStateTest(m_context)); for (int i = 0; i < NUM_TEXTURE_TYPES; i++) { const TypeFormat& typeFormat = TextureTypes[i]; validateErrorsGroup->addChild(new ValidateErrorsTest(m_context, typeFormat)); verifyReadPixelsGroup->addChild(new VerifyReadPixelsTest(m_context, typeFormat)); verifyPartialAttachmentsGroup->addChild(new VerifyPartialAttachmentsTest(m_context, typeFormat)); verifyMixedAttachmentsGroup->addChild(new VerifyMixedAttachmentsTest(m_context, typeFormat)); verifyParametersGroup->addChild(new VerifyParametersTest(m_context, typeFormat)); renderbuffersGroup->addChild(new RenderbuffersTest(m_context, typeFormat)); clearBufferGroup->addChild(new ClearBufferTest(m_context, typeFormat)); blitGroup->addChild(new BlitTest(m_context, typeFormat)); stencilTexturingGroup->addChild(new StencilTexturingTest(m_context, typeFormat)); if (isContextCoreGL) { verifyGetTexImageGroup->addChild(new VerifyGetTexImageTest(m_context, typeFormat)); verifyCopyTexImageGroup->addChild(new VerifyCopyTexImageTest(m_context, typeFormat)); stencilSizeGroup->addChild(new StencilSizeTest(m_context, typeFormat)); } } addChild(validateErrorsGroup); addChild(verifyReadPixelsGroup); addChild(verifyGetTexImageGroup); addChild(verifyCopyTexImageGroup); addChild(verifyPartialAttachmentsGroup); addChild(verifyMixedAttachmentsGroup); addChild(verifyParametersGroup); addChild(renderbuffersGroup); addChild(clearBufferGroup); addChild(blitGroup); addChild(stencilTexturingGroup); addChild(stencilSizeGroup); } } /* glcts namespace */
29.721921
117
0.728493
tarceri
13b2390b822b62ab1474de3490808be550991b84
1,550
cpp
C++
ipc/src/platform/win32/win_semaphore.cpp
c-liang/inter-process-communication
3ce322a425808f6c7ab180b335cbf4cdc02f121a
[ "MIT" ]
1
2021-01-05T08:50:57.000Z
2021-01-05T08:50:57.000Z
ipc/src/platform/win32/win_semaphore.cpp
c-liang/inter-process-communication
3ce322a425808f6c7ab180b335cbf4cdc02f121a
[ "MIT" ]
null
null
null
ipc/src/platform/win32/win_semaphore.cpp
c-liang/inter-process-communication
3ce322a425808f6c7ab180b335cbf4cdc02f121a
[ "MIT" ]
null
null
null
#include "win_semaphore.h" #include "pch.h" _IPC_BEGIN Semaphore::Semaphore(std::wstring const& const name) : semaphore_name(name) {} Semaphore::~Semaphore() { this->close(); } auto Semaphore::create() -> HRESULT { // disable security SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sd; InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE); sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = &sd; this->semaphore = CreateSemaphoreW(&sa, 0, _IPC_SEMAPHORE_MAX, this->semaphore_name.c_str()); if (this->semaphore == nullptr) { return HRESULT_FROM_WIN32(GetLastError()); } return S_OK; } auto Semaphore::open() -> HRESULT { this->semaphore = OpenSemaphoreW(SEMAPHORE_ALL_ACCESS, FALSE, this->semaphore_name.c_str()); if (this->semaphore == nullptr) { return HRESULT_FROM_WIN32(GetLastError()); } return S_OK; } auto Semaphore::wait() -> HRESULT { WaitForSingleObject(this->semaphore, INFINITE); return S_OK; } auto Semaphore::wait_timeout(const uint32_t timeout) -> HRESULT { if (WaitForSingleObject(this->semaphore, timeout) == WAIT_OBJECT_0) { return S_OK; } else { return HRESULT_FROM_WIN32(ERROR_TIMEOUT); } } auto Semaphore::release() -> void { ReleaseSemaphore(this->semaphore, 1, nullptr); } auto Semaphore::close() -> void { if (this->semaphore) { CloseHandle(this->semaphore); this->semaphore = nullptr; } } _IPC_END
25
80
0.694839
c-liang
13b43e0aea82e83147f200372dead373675e5bfa
9,048
cpp
C++
VS2005/GeneralCtrl/DxButton.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
null
null
null
VS2005/GeneralCtrl/DxButton.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
null
null
null
VS2005/GeneralCtrl/DxButton.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
1
2020-06-13T08:34:26.000Z
2020-06-13T08:34:26.000Z
// DxButton.cpp : implementation file // #include "stdafx.h" #include "DxButton.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDxButton CDxButton::CDxButton() { m_bColorStyle = FALSE; m_bHighlight = FALSE; m_hFace = NULL; m_hHighlight = NULL; m_clrText = RGB(0,0,0); m_clrTextHighlight = RGB(0,0,0); m_bPressing = FALSE; } CDxButton::~CDxButton() { } BEGIN_MESSAGE_MAP(CDxButton, CButton) //{{AFX_MSG_MAP(CDxButton) ON_WM_MOUSEMOVE() ON_WM_KILLFOCUS() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDxButton message handlers void CDxButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { // This code only works with buttons. ASSERT(lpDrawItemStruct->CtlType == ODT_BUTTON); CRect rcDefault = lpDrawItemStruct->rcItem; CRect rcText = rcDefault; CPoint iconPos((rcDefault.Height()-32)/2,(rcDefault.Height()-32)/2); CDC *pdc = CDC::FromHandle(lpDrawItemStruct->hDC); // Get the button's text. CString strText; GetWindowText(strText); pdc->SetBkMode(TRANSPARENT); // Change text color COLORREF clrOld = ::SetTextColor(lpDrawItemStruct->hDC,m_clrText); // Setting the text font CFont *pOldFont = pdc->SelectObject(&m_Font); // Create the brushes for painting CBrush brFace; CBrush brPushed; CBrush *pbrOld; brFace.CreateSolidBrush(::GetSysColor(COLOR_3DFACE)); brPushed.CreateSolidBrush(RGB(240,240,240)); pbrOld = pdc->SelectObject(&brFace); UINT state = lpDrawItemStruct->itemState; COLORREF clrTopLeft = RGB(255,255,255); COLORREF clrBottomRight = ::GetSysColor(COLOR_3DSHADOW); HICON hIcon = m_hFace; if ((state& ODS_DEFAULT)) { hIcon = m_hFace; clrTopLeft = RGB(255,255,255); // normal state clrBottomRight = ::GetSysColor(COLOR_3DSHADOW); } else if ((state & ODS_SELECTED)) { hIcon = m_hHighlight; pdc->SelectObject(&brPushed); clrTopLeft = ::GetSysColor(COLOR_3DSHADOW); // button pushed clrBottomRight = RGB(255,255,255); ::SetTextColor(lpDrawItemStruct->hDC,m_clrTextHighlight); } else if ((state & ODS_DISABLED)) { hIcon = m_hFace; clrTopLeft = ::GetSysColor(COLOR_3DFACE); // button pushed clrBottomRight = ::GetSysColor(COLOR_3DFACE); } else if ((m_bHighlight) ) { hIcon = m_hHighlight; clrTopLeft = RGB(255,255,255); // highlight state clrBottomRight = ::GetSysColor(COLOR_3DSHADOW); ::SetTextColor(lpDrawItemStruct->hDC,m_clrTextHighlight); } // Draw the buttons pdc->Rectangle(&rcDefault); pdc->Draw3dRect(&rcDefault,clrTopLeft,clrBottomRight); if(m_bHighlight && !(state & ODS_SELECTED)) { rcDefault.DeflateRect(1,1); pdc->Draw3dRect(&rcDefault,clrTopLeft,clrBottomRight); } // Draw the icons if(pdc->DrawIcon(iconPos,hIcon)) { rcText.left +=32; } pdc->DrawText(strText,&rcText, DT_SINGLELINE|DT_VCENTER|DT_CENTER); // draw clor fase for button color style if (m_bColorStyle) { CBrush brFace(m_clrFace); CBrush*pbrOld = pdc->SelectObject(&brFace); CPen Pen(PS_SOLID,0,m_clrFace); CPen* pPen = pdc->SelectObject(&Pen); rcDefault.DeflateRect(1,1); pdc->Rectangle(&rcDefault); pdc->SelectObject(pbrOld); pdc->SelectObject(pPen); } // Reset text color ::SetTextColor(lpDrawItemStruct->hDC, clrOld); // Reset objects pdc->SelectObject(pOldFont); pdc->SelectObject(pbrOld); pdc->SetBkMode(OPAQUE); } void CDxButton::OnMouseMove(UINT nFlags, CPoint point) { if(nFlags!=MK_LBUTTON) { if(GetCapture()!=this) SetCapture(); CRect rc ; this->GetClientRect(&rc); if(rc.PtInRect(point)) { if(m_bHighlight==FALSE) Invalidate(); m_bHighlight = TRUE; } else { if(m_bHighlight==TRUE) Invalidate(); m_bHighlight = FALSE; if(GetCapture()==this) ::ReleaseCapture(); } } CButton::OnMouseMove(nFlags, point); } void CDxButton::SetTextColor(COLORREF clrText, COLORREF clrTextHighlight) { m_clrText = clrText; m_clrTextHighlight = clrTextHighlight; } void CDxButton::SetWindowText(LPCTSTR lpszString) { Invalidate(TRUE); CButton::SetWindowText(lpszString ); } void CDxButton::OnKillFocus(CWnd* pNewWnd) { m_bHighlight = FALSE; CButton::OnKillFocus(pNewWnd); } HICON CDxButton::SetIcon(HICON hIcon) { m_hFace = hIcon; m_hHighlight = hIcon; return CButton::SetIcon(hIcon); } void CDxButton::SetIcon(HICON hFace, HICON hHighlight) { m_hFace = hFace; m_hHighlight = hHighlight; } HCURSOR CDxButton::SetCursor(HCURSOR hCursor) { return (HCURSOR)SetClassLong(m_hWnd,GCL_HCURSOR,(LONG)hCursor); } void CDxButton::SetFont(LOGFONT lfont) { VERIFY(m_Font.CreateFontIndirect(&lfont)); // create the font } void CDxButton::SetFont(LPCTSTR lpszFontFace,UINT nHeigh,UINT nStyle,BOOL bItalic,BOOL bUnderline) { LOGFONT lf; memset(&lf, 0, sizeof(LOGFONT)); // zero out structure lf.lfHeight = nHeigh; // size lf.lfWeight = nStyle; lf.lfItalic = bItalic; lf.lfUnderline = bUnderline; lf.lfQuality= ANTIALIASED_QUALITY; lf.lfPitchAndFamily = FF_SCRIPT|FF_SWISS; #ifdef _UNICODE wcscpy_s(lf.lfFaceName, LF_FACESIZE, lpszFontFace); // request a face name #else strcpy_s(lf.lfFaceName, LF_FACESIZE, lpszFontFace); // request a face name #endif VERIFY(m_Font.CreateFontIndirect(&lf)); // create the font } BOOL CDxButton::PreTranslateMessage(MSG* pMsg) { return CButton::PreTranslateMessage(pMsg); } void CDxButton::ButtonPress() { m_bPressing = TRUE; CRect rcDefault; GetClientRect(&rcDefault); CRect rcText = rcDefault; CClientDC *pdc = new CClientDC(this); // Get the button's text. CString strText; GetWindowText(strText); pdc->SetBkMode(TRANSPARENT); // Change text color COLORREF clrOld = pdc->SetTextColor(m_clrText); // Setting the text font CFont *pOldFont = pdc->SelectObject(&m_Font); // Create the brushes for painting CBrush brFace; CBrush brPushed; CBrush *pbrOld; brFace.CreateSolidBrush(::GetSysColor(COLOR_3DFACE)); brPushed.CreateSolidBrush(RGB(240,240,240)); pbrOld = pdc->SelectObject(&brFace); COLORREF clrTopLeft = RGB(255,255,255); COLORREF clrBottomRight = ::GetSysColor(COLOR_3DSHADOW); // pressed state pdc->SelectObject(&brPushed); clrTopLeft = ::GetSysColor(COLOR_3DSHADOW); // button pushed clrBottomRight = RGB(255,255,255); pdc->SetTextColor(m_clrTextHighlight); // Draw the buttons pdc->Rectangle(&rcDefault); pdc->Draw3dRect(&rcDefault,clrTopLeft,clrBottomRight); pdc->DrawText(strText,&rcText, DT_SINGLELINE|DT_VCENTER|DT_CENTER); // Reset text color pdc->SetTextColor(clrOld); // Reset objects pdc->SelectObject(pOldFont); pdc->SelectObject(pbrOld); pdc->SetBkMode(OPAQUE); delete pdc; } void CDxButton::ButtonRelease() { m_bPressing = FALSE; CRect rcDefault; GetClientRect(&rcDefault); CRect rcText = rcDefault; CClientDC *pdc = new CClientDC(this); // Get the button's text. CString strText; GetWindowText(strText); pdc->SetBkMode(TRANSPARENT); // Change text color COLORREF clrOld = pdc->SetTextColor(m_clrText); // Setting the text font CFont *pOldFont = pdc->SelectObject(&m_Font); // Create the brushes for painting CBrush brFace; CBrush brPushed; CBrush *pbrOld; brFace.CreateSolidBrush(::GetSysColor(COLOR_3DFACE)); brPushed.CreateSolidBrush(RGB(240,240,240)); pbrOld = pdc->SelectObject(&brFace); COLORREF clrTopLeft = RGB(255,255,255); COLORREF clrBottomRight = ::GetSysColor(COLOR_3DSHADOW); // normal state // pdc->SelectObject(&brPushed); // clrTopLeft = RGB(255,255,255); // normal state // clrBottomRight = ::GetSysColor(COLOR_3DSHADOW); // pdc->SetTextColor(m_clrTextHighlight); // Draw the buttons pdc->Rectangle(&rcDefault); pdc->Draw3dRect(&rcDefault,clrTopLeft,clrBottomRight); pdc->DrawText(strText,&rcText, DT_SINGLELINE|DT_VCENTER|DT_CENTER); // Reset text color pdc->SetTextColor(clrOld); // Reset objects pdc->SelectObject(pOldFont); pdc->SelectObject(pbrOld); pdc->SetBkMode(OPAQUE); delete pdc; } void CDxButton::ButtonRefresh() { Invalidate(); } void CDxButton::SetColorFace(COLORREF clrFace, BOOL bReraw) { m_clrFace = clrFace; if (bReraw) Invalidate(); } void CDxButton::SetColorButtonStyle(BOOL bStyle) { m_bColorStyle = bStyle; }
22.790932
99
0.65252
cuongquay
13b785434c604bb265b59a736c395c088dbb5539
5,658
cpp
C++
recolumn.cpp
shawnw/unicode-text-utils
9bf33bfe367c0bf81f1574bb632fe38747af6668
[ "MIT" ]
null
null
null
recolumn.cpp
shawnw/unicode-text-utils
9bf33bfe367c0bf81f1574bb632fe38747af6668
[ "MIT" ]
null
null
null
recolumn.cpp
shawnw/unicode-text-utils
9bf33bfe367c0bf81f1574bb632fe38747af6668
[ "MIT" ]
null
null
null
/* * Copyright © 2021 Shawn Wagner * * 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 <memory> #include <iostream> #include <stdexcept> #include <string> #include <vector> #include <cstring> #include <unicode/regex.h> #include <unicode/ucnv.h> #include <unicode/unistr.h> #include <unicode/ustdio.h> #include <getopt.h> #include "formatter.h" #include "util.h" using namespace std::literals::string_literals; const char *version = "0.1"; void print_usage(const char *name) { std::cout << name << " [ARGS] [FILE ...]\n\n" << "ARGS:\n" << " -h/--help\t\tDisplay this information.\n" << " -v/--version\t\tDisplay version.\n" << " -d/--delimiter=RE\tSet the column separator regular expression.\n" << " -c/--colspec=SPEC\tSet the column specification.\n" << " -l/--list\t\tUse list mode output.\n"; } using colvector = std::vector<icu::UnicodeString>; using ufp = std::unique_ptr<UFILE, decltype(&u_fclose)>; class line_breaker { private: std::unique_ptr<icu::RegexPattern> pattern; std::unique_ptr<icu::RegexMatcher> splitter; colvector fields; public: line_breaker(const icu::UnicodeString &re); bool split(UFILE *, colvector *out); }; line_breaker::line_breaker(const icu::UnicodeString &re) { UParseError pe; UErrorCode err = U_ZERO_ERROR; pattern = std::unique_ptr<icu::RegexPattern>( icu::RegexPattern::compile(re, pe, err)); if (U_FAILURE(err)) { throw std::invalid_argument{"Invalid regular expression: "s + u_errorName(err)}; } splitter = std::unique_ptr<icu::RegexMatcher>(pattern->matcher(err)); if (U_FAILURE(err)) { throw std::runtime_error{"Couldn't create RegexMatcher: "s + u_errorName(err)}; } } bool line_breaker::split(UFILE *uf, colvector *out) { icu::UnicodeString line; UErrorCode err = U_ZERO_ERROR; if (!uu::getline(uf, &line)) { return false; } if (fields.size() < line.length()) { fields.resize(line.length()); } auto nfields = splitter->split(line, &fields[0], fields.size(), err); if (U_FAILURE(err)) { return false; } out->assign(fields.begin(), fields.begin() + nfields); return true; } int main(int argc, char **argv) { enum output_type { OUT_COLUMN, OUT_LIST } out_type = OUT_COLUMN; struct option opts[] = { {"version", 0, nullptr, 'v'}, {"help", 0, nullptr, 'h'}, {"delimiter", 1, nullptr, 'd'}, {"colspec", 1, nullptr, 'c'}, {"list", 0, nullptr, 'l'}, {nullptr, 0, nullptr, 0}}; const char *split_re = "\\s+"; const char *colspec = nullptr; for (int val; (val = getopt_long(argc, argv, "vhd:c:l", opts, nullptr)) != -1;) { switch (val) { case 'v': std::cout << argv[0] << " version " << version << '\n'; return 0; case 'h': print_usage(argv[0]); return 0; case 'd': split_re = optarg; break; case 'c': colspec = optarg; break; case 'l': out_type = OUT_LIST; break; case '?': default: return 1; } } try { UErrorCode err = U_ZERO_ERROR; icu::UnicodeString usplit_re{split_re, -1, nullptr, err}; if (U_FAILURE(err)) { throw std::runtime_error{"Couldn't convert '"s + split_re + "' to unicode: "s + u_errorName(err)}; } line_breaker breaker{usplit_re}; colvector fields; uformatter fmt; if (out_type == OUT_LIST) { fmt = std::move(make_list_formatter()); } else { fmt = std::move(make_column_formatter()); } auto process = [&fmt, &breaker](UFILE *uf) { colvector fields; while (breaker.split(uf, &fields)) { fmt->format_line(fields); } }; if (optind == argc) { ufp ustdin{u_fadopt(stdin, nullptr, nullptr), &u_fclose}; if (!ustdin) { throw std::runtime_error{"Unable to read from standard input"}; } process(ustdin.get()); } else { for (int i = optind; i < argc; i += 1) { ufp uf = [&]() { if (std::strcmp(argv[i], "/dev/stdin") == 0 || std::strcmp(argv[i], "-")) { return ufp{u_fadopt(stdin, nullptr, nullptr), &u_fclose}; } else { return ufp{u_fopen(argv[i], "r", nullptr, nullptr), &u_fclose}; } }(); if (!uf) { throw std::runtime_error{"Unable to read from '"s + argv[i] + "' "s}; } process(uf.get()); } fmt->flush(); } } catch (std::exception &e) { std::cerr << "Error: " << e.what() << '\n'; return 1; } return 0; }
29.015385
80
0.610817
shawnw
13b7896a8048225540c73ee7b5c88a6c9598b4c5
2,874
hpp
C++
source/nth_fibonacci_number.hpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
source/nth_fibonacci_number.hpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
source/nth_fibonacci_number.hpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
#ifndef PK_NTHFIBONACCINUMBER_HPP #define PK_NTHFIBONACCINUMBER_HPP #include <algorithm> namespace pk { int nth_fibonacci_number(int n) { if(n == 0) return 0; int m_prev[2][2] = {{1, 0}, {0, 1}}; int m_next[2][2]; int (*m_prev_p)[2] = m_prev; int (*m_next_p)[2] = m_next; int c_next[2][2] = {{1, 1}, {1, 0}}; int c_prev[2][2]; int (*c_next_p)[2] = c_next; int (*c_prev_p)[2] = c_prev; --n; while(n > 0) { if(n % 2 == 1) { m_next_p[0][0] = m_prev_p[0][0] * c_next_p[0][0] + m_prev_p[0][1] * c_next_p[1][0]; m_next_p[0][1] = m_prev_p[0][0] * c_next_p[0][1] + m_prev_p[0][1] * c_next_p[1][1]; m_next_p[1][0] = m_prev_p[1][0] * c_next_p[0][0] + m_prev_p[1][1] * c_next_p[1][0]; m_next_p[1][1] = m_prev_p[1][0] * c_next_p[0][1] + m_prev_p[1][1] * c_next_p[1][1]; std::swap(m_prev_p, m_next_p); } c_prev_p[0][0] = c_next_p[0][0] * c_next_p[0][0] + c_next_p[0][1] * c_next_p[1][0]; c_prev_p[0][1] = c_next_p[0][0] * c_next_p[0][1] + c_next_p[0][1] * c_next_p[1][1]; c_prev_p[1][0] = c_next_p[1][0] * c_next_p[0][0] + c_next_p[1][1] * c_next_p[1][0]; c_prev_p[1][1] = c_next_p[1][0] * c_next_p[0][1] + c_next_p[1][1] * c_next_p[1][1]; std::swap(c_prev_p, c_next_p); n /= 2; } return m_prev_p[0][0]; } template<class T> T nth_fibonacci_number(int n, const T& mod) { if(n == 0) return T(0); T m_prev[2][2] = {{T(1), T(0)}, {T(0), T(1)}}; T m_next[2][2]; T (*m_prev_p)[2] = m_prev; T (*m_next_p)[2] = m_next; T c_next[2][2] = {{T(1), T(1)}, {T(1), T(0)}}; T c_prev[2][2]; T (*c_next_p)[2] = c_next; T (*c_prev_p)[2] = c_prev; --n; while(n > 0) { if(n % T(2) == T(1)) { m_next_p[0][0] = (m_prev_p[0][0] * c_next_p[0][0] + m_prev_p[0][1] * c_next_p[1][0]) % mod; m_next_p[0][1] = (m_prev_p[0][0] * c_next_p[0][1] + m_prev_p[0][1] * c_next_p[1][1]) % mod; m_next_p[1][0] = (m_prev_p[1][0] * c_next_p[0][0] + m_prev_p[1][1] * c_next_p[1][0]) % mod; m_next_p[1][1] = (m_prev_p[1][0] * c_next_p[0][1] + m_prev_p[1][1] * c_next_p[1][1]) % mod; std::swap(m_prev_p, m_next_p); } c_prev_p[0][0] = (c_next_p[0][0] * c_next_p[0][0] + c_next_p[0][1] * c_next_p[1][0]) % mod; c_prev_p[0][1] = (c_next_p[0][0] * c_next_p[0][1] + c_next_p[0][1] * c_next_p[1][1]) % mod; c_prev_p[1][0] = (c_next_p[1][0] * c_next_p[0][0] + c_next_p[1][1] * c_next_p[1][0]) % mod; c_prev_p[1][1] = (c_next_p[1][0] * c_next_p[0][1] + c_next_p[1][1] * c_next_p[1][1]) % mod; std::swap(c_prev_p, c_next_p); n /= T(2); } return m_prev_p[0][0]; } } // namespace pk #endif // PK_NTHFIBONACCINUMBER_HPP
27.371429
103
0.504175
pawel-kieliszczyk
13b81957e3c23335c4e4f5dfeae6f4c204624eb5
10,759
cpp
C++
project/source/game/panels/SaveLoadPanel.cpp
ntnt/carpg
f26c43c76d39f2ec2c51bd929f1b85f3c5197337
[ "MIT" ]
1
2016-04-30T15:34:11.000Z
2016-04-30T15:34:11.000Z
project/source/game/panels/SaveLoadPanel.cpp
ntnt/carpg
f26c43c76d39f2ec2c51bd929f1b85f3c5197337
[ "MIT" ]
null
null
null
project/source/game/panels/SaveLoadPanel.cpp
ntnt/carpg
f26c43c76d39f2ec2c51bd929f1b85f3c5197337
[ "MIT" ]
1
2018-11-30T23:32:58.000Z
2018-11-30T23:32:58.000Z
#include "Pch.h" #include "GameCore.h" #include "SaveLoadPanel.h" #include "SaveState.h" #include "Language.h" #include "KeyStates.h" #include "Class.h" #include "Scrollbar.h" #include "Net.h" #include "World.h" #include "Level.h" #include "Game.h" #include "GlobalGui.h" #include "GetTextDialog.h" #include "GameMenu.h" #include "CreateServerPanel.h" #include "Unit.h" #include "GameFile.h" #include "DirectX.h" //================================================================================================= SaveLoad::SaveLoad(const DialogInfo& info) : GameDialogBox(info), choice(0), tMiniSave(nullptr) { size = Int2(610, 400); bt[0].pos = Int2(238, 344); bt[0].parent = this; bt[0].id = IdOk; bt[0].size = Int2(160, 50); bt[1].pos = Int2(238 + 160 + 16, 344); bt[1].parent = this; bt[1].id = IdCancel; bt[1].size = Int2(160, 50); textbox.pos = Int2(265, 52); textbox.size = Int2(297, 88); textbox.parent = this; textbox.SetMultiline(true); textbox.SetReadonly(true); textbox.AddScrollbar(); } //================================================================================================= void SaveLoad::LoadLanguage() { Language::Section s = Language::GetSection("SaveLoad"); txSaving = s.Get("SAVINGGAME"); txLoading = s.Get("LOADINGGAME"); txSave = s.Get("save"); txLoad = s.Get("load"); txSaveN = s.Get("saveN"); txQuickSave = s.Get("quickSave"); txEmptySlot = s.Get("emptySlot"); txSaveDate = s.Get("saveDate"); txSaveTime = s.Get("saveTime"); txSavePlayers = s.Get("savePlayers"); txSaveName = s.Get("saveName"); txSavedGameN = s.Get("savedGameN"); bt[1].text = GUI.txCancel; } //================================================================================================= void SaveLoad::Draw(ControlDrawData*) { GUI.DrawSpriteFull(tBackground, Color::Alpha(128)); GUI.DrawItem(tDialog, global_pos, size, Color::Alpha(222), 16); Rect r = { global_pos.x, global_pos.y + 8, global_pos.x + size.x, global_pos.y + size.y }; GUI.DrawText(GUI.fBig, save_mode ? txSaving : txLoading, DTF_CENTER, Color::Black, r); for(int i = 0; i < 2; ++i) bt[i].Draw(); textbox.Draw(); // slot names r = Rect::Create(global_pos + Int2(12, 76), Int2(256, 20)); for(int i = 0; i < SaveSlot::MAX_SLOTS; ++i) { cstring text; if(slots[i].valid) { if(slots[i].text.empty()) text = Format(txSaveN, i + 1); else text = slots[i].text.c_str(); } else { if(i == SaveSlot::MAX_SLOTS - 1) text = txQuickSave; else text = Format(txEmptySlot, i + 1); } GUI.DrawText(GUI.default_font, text, DTF_SINGLELINE | DTF_VCENTER, choice == i ? Color::Green : Color::Black, r); r.Top() = r.Bottom() + 4; r.Bottom() = r.Top() + 20; } // image if(tMiniSave) { Rect r2 = Rect::Create(Int2(global_pos.x + 400 - 81, global_pos.y + 42 + 103), Int2(256, 192)); GUI.DrawSpriteRect(tMiniSave, r2); } } //================================================================================================= void SaveLoad::Update(float dt) { textbox.mouse_focus = focus; textbox.Update(dt); if(focus && Key.Focus()) { Rect rect = Rect::Create(Int2(global_pos.x + 12, global_pos.y + 76), Int2(256, 20)); for(int i = 0; i < SaveSlot::MAX_SLOTS; ++i) { if(rect.IsInside(GUI.cursor_pos)) { GUI.cursor_mode = CURSOR_HAND; if(Key.PressedRelease(VK_LBUTTON) && choice != i) { choice = i; if(!save_mode) bt[0].state = slots[i].valid ? Button::NONE : Button::DISABLED; SetSaveImage(); SetText(); } } rect.Top() = rect.Bottom() + 4; rect.Bottom() = rect.Top() + 20; } if(Key.PressedRelease(VK_ESCAPE)) Event((GuiEvent)IdCancel); } for(int i = 0; i < 2; ++i) { bt[i].mouse_focus = focus; bt[i].Update(dt); } } //================================================================================================= void SaveLoad::Event(GuiEvent e) { if(e == GuiEvent_Show || e == GuiEvent_WindowResize) { global_pos = pos = (GUI.wnd_size - size) / 2; for(int i = 0; i < 2; ++i) bt[i].global_pos = bt[i].pos + global_pos; textbox.global_pos = textbox.pos + global_pos; textbox.scrollbar->global_pos = textbox.scrollbar->pos + textbox.global_pos; if(e == GuiEvent_Show) SetText(); } else if(e >= GuiEvent_Custom) { if(e == IdCancel) { N.mp_load = false; GUI.CloseDialog(this); return; } if(save_mode) { // saving SaveSlot& slot = slots[choice]; if(choice == SaveSlot::MAX_SLOTS - 1) { // quicksave GUI.CloseDialog(this); game->SaveGameSlot(choice + 1, txQuickSave); } else { // enter save title cstring names[] = { nullptr, txSave }; if(slot.valid) save_input_text = slot.text; else if(game->hardcore_mode) save_input_text = hardcore_savename; else save_input_text.clear(); GetTextDialogParams params(txSaveName, save_input_text); params.custom_names = names; params.event = [this](int id) { if(id == BUTTON_OK && game->SaveGameSlot(choice + 1, save_input_text.c_str())) { GUI.CloseDialog(this); } }; params.parent = this; GetTextDialog::Show(params); } } else { // load CloseDialog(); game->TryLoadGame(choice + 1, false, false); } } } //================================================================================================= void SaveLoad::SetSaveMode(bool save_mode, bool online, SaveSlot* slots) { this->save_mode = save_mode; this->online = online; this->slots = slots; SaveSlot& slot = slots[choice]; // setup buttons if(save_mode) { bt[0].state = Button::NONE; bt[0].text = txSave; } else { bt[0].state = slot.valid ? Button::NONE : Button::DISABLED; bt[0].text = txLoad; } SetSaveImage(); } //================================================================================================= void SaveLoad::SetSaveImage() { SaveSlot& slot = slots[choice]; SafeRelease(tMiniSave); if(slot.valid) { if(slot.img_size == 0) { cstring filename = Format("saves/%s/%d.jpg", online ? "multi" : "single", choice + 1); if(io::FileExists(filename)) V(D3DXCreateTextureFromFile(GUI.GetDevice(), filename, &tMiniSave)); } else { cstring filename = Format("saves/%s/%d.sav", online ? "multi" : "single", choice + 1); Buffer* buf = FileReader::ReadToBuffer(filename, slot.img_offset, slot.img_size); V(D3DXCreateTextureFromFileInMemory(GUI.GetDevice(), buf->Data(), buf->Size(), &tMiniSave)); buf->Free(); } } } //================================================================================================= void SaveLoad::SetText() { textbox.Reset(); if(choice == -1 || !slots[choice].valid) return; LocalString s; SaveSlot& slot = slots[choice]; bool exists = false; if(!slot.player_name.empty()) { s += slot.player_name; exists = true; } if(slot.player_class != Class::INVALID) { if(exists) s += " "; s += ClassInfo::classes[(int)slot.player_class].name; exists = true; } if(slot.hardcore) { if(exists) s += " "; s += "(hardcore)"; exists = true; } if(exists) s += "\n"; if(online && !slot.mp_players.empty()) { s += txSavePlayers; bool first = true; for(string& str : slot.mp_players) { if(first) first = false; else s += ", "; s += str; } s += "\n"; } if(slot.save_date != 0) { tm t; localtime_s(&t, &slot.save_date); s += Format(txSaveDate, t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); } if(slot.game_year != -1 && slot.game_month != -1 && slot.game_day != -1) s += Format(txSaveTime, W.GetDate(slot.game_year, slot.game_month, slot.game_day)); if(!slot.location.empty()) s += slot.location; textbox.SetText(s); textbox.UpdateScrollbar(); } //================================================================================================= void SaveLoad::RemoveHardcoreSave(int slot) { SaveSlot& s = single_saves[slot - 1]; s.valid = false; hardcore_savename = s.text; } //================================================================================================= void SaveLoad::LoadSaveSlots() { for(int multi = 0; multi < 2; ++multi) { for(int i = 1; i <= SaveSlot::MAX_SLOTS; ++i) { SaveSlot& slot = (multi == 0 ? single_saves : multi_saves)[i - 1]; cstring filename = Format("saves/%s/%d.sav", multi == 0 ? "single" : "multi", i); GameReader f(filename); if(!game->LoadGameHeader(f, slot)) { if(i == SaveSlot::MAX_SLOTS) slot.text = txQuickSave; continue; } slot.valid = true; if(slot.load_version < V_0_9) { filename = Format("saves/%s/%d.txt", multi == 0 ? "single" : "multi", i); if(io::FileExists(filename)) { Config cfg; cfg.Load(filename); slot.player_name = cfg.GetString("player_name", ""); slot.location = cfg.GetString("location", ""); slot.text = cfg.GetString("text", ""); slot.game_day = cfg.GetInt("game_day"); slot.game_month = cfg.GetInt("game_month"); slot.game_year = cfg.GetInt("game_year"); slot.hardcore = cfg.GetBool("hardcore"); slot.mp_players.clear(); slot.save_date = cfg.GetInt64("save_date"); const string& str = cfg.GetString("player_class"); if(str == "0") slot.player_class = Class::WARRIOR; else if(str == "1") slot.player_class = Class::HUNTER; else if(str == "2") slot.player_class = Class::ROGUE; else { ClassInfo* ci = ClassInfo::Find(str); if(ci && ci->pickable) slot.player_class = ci->class_id; else slot.player_class = Class::INVALID; } } else { slot.player_name.clear(); slot.text.clear(); slot.location.clear(); slot.game_day = -1; slot.game_month = -1; slot.game_year = -1; slot.player_class = Class::INVALID; slot.mp_players.clear(); slot.save_date = 0; slot.hardcore = false; } slot.img_size = 0; } if(i == SaveSlot::MAX_SLOTS) slot.text = txQuickSave; } } } //================================================================================================= void SaveLoad::ShowSavePanel() { SetSaveMode(true, Net::IsOnline(), Net::IsOnline() ? multi_saves : single_saves); GUI.ShowDialog(this); } //================================================================================================= void SaveLoad::ShowLoadPanel() { bool online = (N.mp_load || Net::IsServer()); SetSaveMode(false, online, online ? multi_saves : single_saves); GUI.ShowDialog(this); } //================================================================================================= SaveSlot& SaveLoad::GetSaveSlot(int slot) { return (Net::IsOnline() ? multi_saves[slot - 1] : single_saves[slot - 1]); }
25.555819
115
0.549215
ntnt
13b822e2ff9202767f156fd5308495b394ca2378
241
hpp
C++
src/adjustment/rotate.hpp
corneliusyan/Protoshop
66fb204554822e6da6416f495622a2b7d5be73ec
[ "MIT" ]
1
2020-09-23T19:18:23.000Z
2020-09-23T19:18:23.000Z
src/adjustment/rotate.hpp
corneliusyan/Protoshop
66fb204554822e6da6416f495622a2b7d5be73ec
[ "MIT" ]
null
null
null
src/adjustment/rotate.hpp
corneliusyan/Protoshop
66fb204554822e6da6416f495622a2b7d5be73ec
[ "MIT" ]
2
2020-09-15T13:52:59.000Z
2021-12-15T02:44:36.000Z
#ifndef PROTOSHOP_ADJUSTMENT_ROTATE #define PROTOSHOP_ADJUSTMENT_ROTATE #include "base.hpp" class AdjustmentRotate : public Adjustment { public: static void rotate90CCW(Image* target); static void rotate90CW(Image* target); }; #endif
18.538462
44
0.792531
corneliusyan
13ba4210c70a9164a07606e01c1b43e3e9a45206
10,144
cpp
C++
Chapter16/FDMCPPBOOK2004/ParabolicFDM.cpp
alamlam1982/fincpp
470469d35d90fc0fde96f119e329aedbc5f68f89
[ "CECILL-B" ]
null
null
null
Chapter16/FDMCPPBOOK2004/ParabolicFDM.cpp
alamlam1982/fincpp
470469d35d90fc0fde96f119e329aedbc5f68f89
[ "CECILL-B" ]
null
null
null
Chapter16/FDMCPPBOOK2004/ParabolicFDM.cpp
alamlam1982/fincpp
470469d35d90fc0fde96f119e329aedbc5f68f89
[ "CECILL-B" ]
null
null
null
// parabolicFDM.cpp // // Finite difference method for Parabolic PDE. // // Last modification dates: // // 2000-7-30 DD kick-off code. The member 'theta' is for a future version // 2000-8-1 DD more improvements, specific use of Array code // 2000-8-2 DD getting ready for Robert and Jasmin // 2001-1-30 DD debugging and checking (heavy overhaul) // 2001-2-10 DD 'improvements' // 2002-1-8 DD Cleaning up mostly // 2002-4-9 DD Later on the discrete A, B, C and F can be replaced by one generic function // 2002-17-5 RM coth added to ParabolicFDM class (RM = R. Mirani) // 2002-17-5 RM functions ::A, ::B and ::C changed to internal note 1 format // 2002-17-5 RM some small errors in ::init() // 2002-21-5 RM current now initialized (to 0) in constructor // 2002-21-5 RM Completely new advance() function // 2002-21-5 RM initial condition IC() added // 2002-21-5 RM function start() now computes the complete result // 2002-22-5 RM pde is not a pointer! All calls pde->function() changed to pde.function() // 2002-23-5 RM factor 0.5*k added in finished to prevent roundof errors screwing up stopping condition // 2002-16-6 RM bug in advance: stock price domain assumed to start at 0 // 2006-1-9 DD New structure and more in line with othe C++ code // 2006-1-9 DD Major redesign // 2006-1-13 DD BUG FIX BAH, it was an error in Unary - in Vector, don't // ask how much good drinking time lost // 2006-1-16 DD incorporate American exercise feature // // (C) Datasim Component Technology BV 2000-2006 // #ifndef FDM_CPP #define FDM_CPP #include "ParabolicFDM.hpp" #include <math.h> template <class X, class T, class V> void ParabolicFDM<X,T,V>::CheckAmericanConstraintPut(Vector<V, long>& fullSolution) { //========********** AMERICAN OPTION PUT ************* for (long mj = fullSolution.MinIndex(); mj <= fullSolution.MaxIndex(); mj++) { fullSolution[mj] =(fullSolution[mj] > Strike - XARR[mj+1]) ? fullSolution[mj] : Strike - XARR[mj+1]; } } template <class X, class T, class V> void ParabolicFDM<X,T,V>::CheckAmericanConstraintCall(Vector<V, long>& fullSolution) { //========********** AMERICAN OPTION CALL************* for (long mj = fullSolution.MinIndex() + 1; mj <= fullSolution.MaxIndex(); mj++) { fullSolution[mj] =(fullSolution[mj]>XARR[mj] - Strike) ? fullSolution[mj] : XARR[mj] - Strike; } } template <class X, class T, class V> V ParabolicFDM<X,T,V>::coth(const V& x) const { // Hyperbolic cotangent function V tmp=::exp(-2*x); return (1.0 + tmp)/(1.0 - tmp); } template <class X, class T, class V> V ParabolicFDM<X,T,V>::A(const X& x, const T& t) const { // Sub-diagonal term in matrix in semi-discrete scheme // alpha - beta return (fitting_factor(x,t)/(h*h) - (0.5 * pde.convection(x,t))/(h)); } template <class X, class T, class V> V ParabolicFDM<X,T,V>::B(const X& x, const T& t) const { // Main diagonal term in matrix in semi-discrete scheme // - 2 * alpha + b return - 2.0 * (fitting_factor(x,t)/(h*h)) + pde.zeroterm(x,t); } template <class X, class T, class V>V ParabolicFDM<X,T,V>::C(const X& x, const T& t) const { // Super-diagonal term in matrix in semi-discrete scheme // alpha + beta return (fitting_factor(x,t)/(h*h)) + (0.5 * pde.convection(x,t))/(h); } template <class X, class T, class V>V ParabolicFDM<X,T,V>::F(const X& x, const T& t) const { // Right-hand side of matrix equation in semi-discrete scheme return (pde.RHS(x,t)); } template <class X, class T, class V> V ParabolicFDM<X,T,V>::fitting_factor(const X& x, const T& t) const { // Il'in fitting function V tmp = pde.convection(x,t) * h * 0.5; return tmp * coth(tmp/(pde.diffusion(x,t))); // Uses hyperbolic cotangent } // Fully-discrete coefficients template <class X, class T, class V> Vector<V,long> ParabolicFDM<X,T,V>::Adiscrete(const T& t) const { // Array of A's in semi-discrete scheme // Create an array a[1..J-1] Vector<V,long> result(J-1, 1); for (long j = result.MinIndex(); j <= result.MaxIndex(); j++) { result[j] = A(XARR[j+1], t); } return result; } template <class X, class T, class V> Vector<V,long > ParabolicFDM<X,T,V>::Bdiscrete(const T& t) const { // Array of B's in semi-discrete scheme // Create an array b[1..J-1] Vector<V,long > result(J-1, 1); for (long j = result.MinIndex(); j <= result.MaxIndex(); j++) { result[j] = B(XARR[j+1], t); } return result; } template <class X, class T, class V> Vector<V,long > ParabolicFDM<X,T,V>::Cdiscrete(const T& t) const { // Array of C's in semi-discrete scheme // Create an array c[1..J-1] Vector<V,long > result(J-1, 1); for (long j = result.MinIndex(); j <= result.MaxIndex(); j++) { result[j] = C(XARR[j+1], t); } return result; } template <class X, class T, class V> Vector<V,long > ParabolicFDM<X,T,V>::Fdiscrete(const T& t) const { // Right-hand side in semi-discrete scheme // Create an array f[1..J-1] Vector<V,long > result (J-1, 1); for (long j = result.MinIndex(); j <= result.MaxIndex(); j++) { result[j] = F(XARR[j+1], t); } return result; } template <class X, class T, class V> void ParabolicFDM<X,T,V>::init() { // Initialise all variables, arrays and matrices // 1. Mesh stuff h = X(pde.first().spread()) / V(J); k = T(pde.second().spread())/ V(N); // Make 2 arrays of in range [1..J+1] and [1..N+1] XARR = pde.first().mesh(J); TARR = pde.second().mesh(N); vecOld = Vector<V, long> (XARR.Size(), XARR.MinIndex()); vecNew = Vector<V, long> (XARR.Size(), XARR.MinIndex()); meshValues = NumericMatrix<V, long>(N+1, J+1); solution = Vector<V, long>(XARR.Size()- 2, 1); } template <class X, class T, class V> ParabolicFDM<X,T,V>::ParabolicFDM (const ParabolicPDE<X,T,V>& context, long Xintervals, long Tintervals, int choice, OptionType otype) { pde = context; current = pde.second().low(); // Number of intervals in spatial axis J = Xintervals; // Number of intervals in temporal axis N = Tintervals; // Ratio between explicit and implicit theta = 0.5; // default is CN if (choice == 1) theta = 0.0; if (choice == 2) theta = 1.0; // Early exercise exerciseType = otype; // Initialize the run init(); } // The computational scenario template <class X, class T, class V> void ParabolicFDM<X,T,V>::start() { // Fill in initial data // Initialise at the boundaries vecOld[vecOld.MinIndex()] = pde.BCL(current); vecOld[vecOld.MaxIndex()] = pde.BCR(current); // Set initial condition for (long j = vecOld.MinIndex()+1; j <= vecOld.MaxIndex()-1; j++) { vecOld[j] = pde.IC(XARR[j]); } // print(vecOld); // int t; cin >> t; // Add initial vector to matrix currentRow = 1; meshValues.Row(currentRow, vecOld); // Compute the results while(!finished()) { advance(); // vecOld = vecNew; } } template <class X, class T, class V> void ParabolicFDM<X,T,V>::advance() { // Go to the next time stage and calculate. This is where all the action // takes place. // Set the time T t = current; // Calculate BC for new Vector vecNew[vecNew.MinIndex()] = pde.BCL(t+k); vecNew[vecNew.MaxIndex()] = pde.BCR(t+k); // Candidate for optimisation // Build up Matrix vectors Vector<V, long> A_now(J-1, 1); // Start index 1, size J-1 Vector<V, long> B_now(J-1, 1); Vector<V, long> C_now(J-1, 1); Vector<V, long> F_now(J-1, 1); // forcing term at time current Vector<V,long> RHS(J-1, 1); Vector<V, long> A_next(J-1, 1); // Start index 1, size J-1 Vector<V, long> B_next(J-1, 1); Vector<V, long> C_next(J-1, 1); Vector<V, long> F_next(J-1, 1); // forcing term at time current + k Vector<V, long> unit(J-1, 1, 1.0); // All elements == 1.0 // Determine matrix- and vector-values at time current i.e. n V coeff_now = k * (1.0 - theta); A_now = Adiscrete(t)*coeff_now; B_now = unit + (Bdiscrete(t) * coeff_now); C_now = Cdiscrete(t) * coeff_now; F_now = - Fdiscrete(t) * coeff_now; // Determine matrix- and vector-values at time current + k V coeff_next = k * theta; A_next = - (Adiscrete(t+k) * coeff_next); B_next = unit - (Bdiscrete(t+k) * coeff_next); C_next = - Cdiscrete(t+k) * coeff_next; F_next = - Fdiscrete(t+k) * coeff_next; // Calculate the RHS in AU = RHS for(long q=RHS.MinIndex(); q<= RHS.MaxIndex(); q++) { RHS[q] = A_now[q]*vecOld[q]+B_now[q]*vecOld[q+1]+C_now[q]*vecOld[q+2]; + F_now[q] + F_next[q]; } // Corrections RHS[1] += coeff_next * A(XARR[2],t+k) * vecNew[vecNew.MinIndex()]; RHS[J-1] += coeff_next * C(XARR[J],t+k) * vecNew[vecNew.MaxIndex()]; // The objective is to calculate the 'next' vector (BALAYAGE) // DoubleSweep<V, long> ss( A_next, B_next, C_next, RHS, // vecNew[vecNew.MinIndex()], vecNew[vecNew.MaxIndex()]); // Now solve the system of equations LUTridiagonalSolver<double, long> ss(A_next, B_next, C_next, RHS); solution = ss.solve(); // [1,J-1] ==> length J - 1 // Test if American constraint has been satisfied if (exerciseType == AmericanCallType || exerciseType == AmericanPutType) { if (exerciseType == AmericanCallType) { CheckAmericanConstraintCall(solution); } else { CheckAmericanConstraintPut(solution); } } for (long ii = vecNew.MinIndex()+1; ii <= vecNew.MaxIndex()-1; ii++) { vecNew[ii] = solution[ii-1]; } current += k; // Next floor (I mean time level) vecOld = vecNew; currentRow++; meshValues.Row(currentRow, vecNew); } template <class X, class T, class V> bool ParabolicFDM<X,T,V>::finished() { // Have we calculated the last vector? // Determine if time t = T //if (current > pde.second().high() - 0.5*k) if (currentRow <= N) { return false; //true; } cout << "time " << current << endl; return true; //false; } // Results template <class X, class T, class V> Vector<V,long >& ParabolicFDM<X,T,V>::line() { // Current vector output // Return the result of the run return vecNew; } template <class X, class T, class V> Vector<V,long >& ParabolicFDM<X,T,V>::linePrevious() { // Current vector output // Return the result of the run return vecOld; } template <class X, class T, class V> NumericMatrix<V,long>& ParabolicFDM<X,T,V>::result() { // Solution so far return meshValues; } #endif
26.554974
121
0.651518
alamlam1982
13bc7c9db02a800bd632b458194e37aabdeca05f
3,760
cpp
C++
VST3 SDK/public.sdk/samples/vst/mda-vst3/source/mdaRingModProcessor.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
2
2020-10-25T09:03:03.000Z
2021-06-24T13:20:01.000Z
VST3 SDK/public.sdk/samples/vst/mda-vst3/source/mdaRingModProcessor.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
null
null
null
VST3 SDK/public.sdk/samples/vst/mda-vst3/source/mdaRingModProcessor.cpp
jagilley/MrsWatson
dd00b6a3740cce4bf7c10d3342d4742c7d1b4836
[ "BSD-2-Clause" ]
1
2021-12-18T06:30:51.000Z
2021-12-18T06:30:51.000Z
/* * mdaRingModProcessor.cpp * mda-vst3 * * Created by Arne Scheffler on 6/14/08. * * mda VST Plug-ins * * Copyright (c) 2008 Paul Kellett * * 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 "mdaRingModProcessor.h" #include "mdaRingModController.h" #include <math.h> namespace Steinberg { namespace Vst { namespace mda { //----------------------------------------------------------------------------- FUID RingModProcessor::uid (0x935CB08D, 0xFE614CF5, 0xA3927AAA, 0x21B25D95); //----------------------------------------------------------------------------- RingModProcessor::RingModProcessor () { setControllerClass (RingModController::uid); allocParameters (4); } //----------------------------------------------------------------------------- RingModProcessor::~RingModProcessor () { } //----------------------------------------------------------------------------- tresult PLUGIN_API RingModProcessor::initialize (FUnknown* context) { tresult res = BaseProcessor::initialize (context); if (res == kResultTrue) { addAudioInput (USTRING("Stereo In"), SpeakerArr::kStereo); addAudioOutput (USTRING("Stereo Out"), SpeakerArr::kStereo); params[0] = (float)0.0625; //1kHz params[1] = (float)0.0; params[2] = (float)0.0; fPhi = 0.0; twoPi = (float)6.2831853; fprev = 0.f; recalculate (); } return res; } //----------------------------------------------------------------------------- tresult PLUGIN_API RingModProcessor::terminate () { return BaseProcessor::terminate (); } //----------------------------------------------------------------------------- tresult PLUGIN_API RingModProcessor::setActive (TBool state) { return BaseProcessor::setActive (state); } //----------------------------------------------------------------------------- void RingModProcessor::doProcessing (ProcessData& data) { int32 sampleFrames = data.numSamples; float* in1 = data.inputs[0].channelBuffers32[0]; float* in2 = data.inputs[0].channelBuffers32[1]; float* out1 = data.outputs[0].channelBuffers32[0]; float* out2 = data.outputs[0].channelBuffers32[1]; float a, b, c, d, g; float p, dp, tp = twoPi, fb, fp, fp2; p = fPhi; dp = fdPhi; fb = ffb; fp = fprev; --in1; --in2; --out1; --out2; while (--sampleFrames >= 0) { a = *++in1; b = *++in2; g = (float)sin(p); p = (float)fmod( p + dp, tp ); fp = (fb * fp + a) * g; fp2 = (fb * fp + b) * g; c = fp; d = fp2; *++out1 = c; *++out2 = d; } fPhi = p; fprev = fp; } //----------------------------------------------------------------------------- void RingModProcessor::recalculate () { fdPhi = (float) (twoPi * 100.0 * (params[1] + (160.0 * params[0]))/ getSampleRate ()); ffb = 0.95f * params[2]; } }}} // namespaces
29.606299
464
0.577394
jagilley
13c0bf59bb43fd5df9396767cca156db76a4f24a
793
cpp
C++
src/SFECS/TagManager.cpp
allindevelopers/sfecs
f6ce97dbd5e3bcf90475c3d68bf33211db7a2fbe
[ "Zlib" ]
1
2022-03-19T14:00:38.000Z
2022-03-19T14:00:38.000Z
src/SFECS/TagManager.cpp
iamandrewluca/sfecs
f6ce97dbd5e3bcf90475c3d68bf33211db7a2fbe
[ "Zlib" ]
null
null
null
src/SFECS/TagManager.cpp
iamandrewluca/sfecs
f6ce97dbd5e3bcf90475c3d68bf33211db7a2fbe
[ "Zlib" ]
1
2020-09-23T20:12:30.000Z
2020-09-23T20:12:30.000Z
#include "SFECS/TagManager.hpp" //#include "Manager.hpp" #include "SFECS/Entity.hpp" namespace sfecs { TagManager::TagManager() { //this->world = &world; } Entity& TagManager::getEntity(const std::string tag) { return *tagByEntity[tag]; } bool TagManager::isSubscribed(const std::string tag) { return (tagByEntity[tag] != nullptr); } void TagManager::remove(Entity &e) { //TODO find cleaner way to remove by value Entity * ent = &e; for(auto& it: tagByEntity){ if(it.second == ent){ tagByEntity.erase(it.first); return; } } } void TagManager::unSubscribe(const std::string tag) { //tagByEntity[tag] = nullptr; tagByEntity.erase(tag); } void TagManager::subscribe(std::string tag, Entity &e){ remove(e); tagByEntity[tag] = &e; } }
18.44186
56
0.656999
allindevelopers
13c6d47b53ee75816edaac3d4ad9dd683851b300
6,770
cc
C++
bootid-logger/bootid_logger.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
bootid-logger/bootid_logger.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
bootid-logger/bootid_logger.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium OS 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 <deque> #include <fstream> #include <sstream> #include <string> #include <utility> #include <fcntl.h> #include <stdio.h> #include <sys/file.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "base/files/file_util.h" #include "base/files/scoped_file.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/time/time.h" #include "bootid-logger/bootid_logger.h" namespace { constexpr char kBootIdProcPath[] = "/proc/sys/kernel/random/boot_id"; // 47 bytes = timestamp 31bytes + space + fixed message 15 bytes. constexpr size_t kBootEntryLength = 47u + kBootIdLength; // Generate an entry in the boot entry format. std::string GenerateBootEntryString(const std::string current_boot_id, const base::Time boot_time) { // Boot id must be 32 hexadecimal digits. CHECK_EQ(32u, current_boot_id.length()); // TODO(crbug.com): Change the timezone from local to UTC. base::Time::Exploded exploded; boot_time.LocalExplode(&exploded); struct tm lt = {0}; time_t milliseconds = boot_time.ToTimeT(); localtime_r(&milliseconds, &lt); int32_t timezone_offset_sec = lt.tm_gmtoff; const std::string boot_time_str(base::StringPrintf( "%04d-%02d-%02dT%02d:%02d:%02d.%03d000%+03d:%02d", exploded.year, exploded.month, exploded.day_of_month, exploded.hour, exploded.minute, exploded.second, exploded.millisecond, (timezone_offset_sec / 3600), ((std::abs(timezone_offset_sec) / 60) % 60))); const std::string boot_id_entry = boot_time_str + " INFO boot_id: " + base::ToLowerASCII(current_boot_id); CHECK_EQ(kBootEntryLength, boot_id_entry.length()); return boot_id_entry; } // Read previous entries from the log file (FD). base::Optional<std::deque<std::string>> ReadPreviousBootEntries( const int fd, int boot_log_max_entries) { std::deque<std::string> previous_boot_entries; struct stat st; fstat(fd, &st); const off_t length = st.st_size; if (length > 0) { // Here, we do mmap and stringstream to read lines. // We can't use ifstream here because we want to use fd for keeping locking // on the file. char* buffer = static_cast<char*>(mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0)); if (buffer == NULL) { PLOG(FATAL) << "mmap failed"; return base::nullopt; } // Set the buffer to the stream. std::istringstream ss(std::string(buffer, length)); std::string s; while (std::getline(ss, s)) { // Skip an empty log. if (s.empty()) continue; // Skip a duplicated entry. if (!previous_boot_entries.empty() && previous_boot_entries.back() == s) continue; // Skip an invalid entry. if (!ValidateBootEntry(s)) continue; previous_boot_entries.push_back(s); } munmap(buffer, length); // Truncate if the logs are overflown. while (previous_boot_entries.size() > (boot_log_max_entries - 1)) { previous_boot_entries.pop_front(); } } return previous_boot_entries; } base::Time GetCurrentBootTime() { struct timespec boot_timespec; if (clock_gettime(CLOCK_BOOTTIME, &boot_timespec) == -1) { PLOG(FATAL) << "clock_gettime failed"; exit(EXIT_FAILURE); } return base::Time::Now() - base::TimeDelta::FromTimeSpec(boot_timespec); } } // anonymous namespace // Extracts the boot ID from the givin boot ID entry. bool ValidateBootEntry(const std::string& boot_id_entry) { if (boot_id_entry.length() != kBootEntryLength) return false; if (boot_id_entry[32] != ' ' || boot_id_entry[37] != ' ' || boot_id_entry[46] != ' ') return false; return true; } // Extracts the boot ID from the givin boot ID entry. std::string ExtractBootId(const std::string& boot_id_entry) { if (boot_id_entry.length() != kBootEntryLength) return ""; return boot_id_entry.substr(32u + 15u, kBootIdLength); } std::string GetCurrentBootId() { std::string boot_id; if (!base::ReadFileToString(base::FilePath(kBootIdProcPath), &boot_id)) { LOG(FATAL) << "Reading the log file failed"; exit(EXIT_FAILURE); } base::RemoveChars(boot_id, "-\r\n", &boot_id); CHECK_EQ(kBootIdLength, boot_id.length()); return boot_id; } bool WriteCurrentBootEntry(const base::FilePath& bootid_log_path, const int max_entries) { std::string boot_id = GetCurrentBootId(); base::Time boot_time = GetCurrentBootTime(); return WriteBootEntry(bootid_log_path, boot_id, boot_time, max_entries); } bool WriteBootEntry(const base::FilePath& bootid_log_path, const std::string& current_boot_id, const base::Time boot_time, const int max_entries) { // Open the log file. base::ScopedFD fd(HANDLE_EINTR( open(bootid_log_path.value().c_str(), O_RDWR | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP /* 0644 */))); if (fd.get() == -1) { PLOG(FATAL) << "open failed"; return false; } if (HANDLE_EINTR(flock(fd.get(), LOCK_EX)) == -1) { PLOG(FATAL) << "flock failed"; return false; } auto ret = ReadPreviousBootEntries(fd.get(), max_entries); if (!ret.has_value()) { LOG(FATAL) << "Reading the log file failed"; return false; } std::deque<std::string> previous_boot_entries = std::move(*ret); if (!previous_boot_entries.empty() && ExtractBootId(previous_boot_entries.back()) == current_boot_id) { LOG(INFO) << "The current Boot ID does already exists in the log. New " "entry is not added to prevent duplication."; // Returning true, since it is not an issue. return true; } const std::string boot_entry_str = GenerateBootEntryString(current_boot_id, boot_time); previous_boot_entries.push_back(boot_entry_str); // Update the current pos to the beginning of the file. if (lseek(fd.get(), 0, SEEK_SET) != 0) { PLOG(FATAL) << "lseek failed"; return false; } // Shrink the file to zero. if (HANDLE_EINTR(ftruncate(fd.get(), 0)) != 0) { PLOG(FATAL) << "ftruncate failed"; return false; } // Rewrite the existing entries. for (std::string boot_entry : previous_boot_entries) { boot_entry.append(1, '\n'); if (!base::WriteFileDescriptor(fd.get(), boot_entry.c_str(), boot_entry.size())) { PLOG(FATAL) << "Writing to the file failed"; return false; } } // Automatically the file is closed and unlocked at the end of process. return true; }
29.692982
79
0.666765
dgreid
13c88010fdb10ed41197f7db26bbc1c62f2434b7
1,522
hpp
C++
src/jadx/api/JadxArgs.hpp
oyamoh-brian/pyjadx
ecdd9f9e5e70de7fe4168ed028a27b667170ef32
[ "Apache-2.0" ]
3
2021-06-17T03:07:33.000Z
2022-02-12T14:12:12.000Z
src/jadx/api/JadxArgs.hpp
oyamoh-brian/pyjadx
ecdd9f9e5e70de7fe4168ed028a27b667170ef32
[ "Apache-2.0" ]
null
null
null
src/jadx/api/JadxArgs.hpp
oyamoh-brian/pyjadx
ecdd9f9e5e70de7fe4168ed028a27b667170ef32
[ "Apache-2.0" ]
5
2020-09-24T09:42:30.000Z
2021-06-04T12:03:20.000Z
/* Copyright 2018 R. Thomas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef JADX_API_JADXARGS_H_ #define JADX_API_JADXARGS_H_ #include <jni/jni.hpp> #include <string> namespace jni::jadx::api { class JadxArgs { public: struct Tag { static constexpr auto Name() { return "jadx/api/JadxArgs"; } }; using Object_t = Object<Tag>; using Class_t = Class<Tag>; JadxArgs(JNIEnv& env); const Class_t& clazz(void) const; Local<Object_t> get(void); void setInputFiles(const std::vector<std::string>& inputs); void show_inconsistent_code(bool value); void escape_unicode(bool value); void deobfuscation_on(bool value); void use_source_name_as_class_alias(bool value); void deobfuscation_min_length(size_t value); void deobfuscation_max_length(size_t value); private: inline JNIEnv& env(void) { return *(this->env_); } inline JNIEnv& env(void) const { return *(this->env_); } mutable JNIEnv* env_{nullptr}; Local<Object_t> obj_{nullptr}; }; } #endif
25.79661
78
0.724047
oyamoh-brian
13c8d65fb112b1531bb586ac9d78aad167bb2c1b
73,447
cpp
C++
smallvm/runtime/builtinmethods.cpp
mobadarah/kalimat-lang
9eb6c64dd5380efaf863b619a506ebf000be7fd9
[ "Apache-2.0" ]
6
2021-07-05T15:35:33.000Z
2022-03-25T21:21:43.000Z
smallvm/runtime/builtinmethods.cpp
anasawad/kalimat
830cbe9ddde13865bc1f77a2f74efd3dac3b58cc
[ "Apache-2.0" ]
null
null
null
smallvm/runtime/builtinmethods.cpp
anasawad/kalimat
830cbe9ddde13865bc1f77a2f74efd3dac3b58cc
[ "Apache-2.0" ]
1
2022-03-25T21:15:33.000Z
2022-03-25T21:15:33.000Z
/************************************************************************** ** The Kalimat programming language ** Copyright 2010 Mohamed Samy Ali - samy2004@gmail.com ** This project is released under the Apache License version 2.0 ** as described in the included license.txt file **************************************************************************/ #include "runwindow.h" #include "builtinmethods.h" #include "guieditwidgethandler.h" #include "parserengine.h" #include "../runtime_identifiers.h" #include "guicontrols.h" // for ButtonGroupForeignClass #include <QApplication> #include <QDialog> #include <QPushButton> #include <QLineEdit> #include <QCheckBox> #include <QLabel> #include <QFrame> #include <QScrollArea> #include <QGroupBox> #include <QVBoxLayout> #include <QListWidget> #include <QComboBox> #include <QRadioButton> #include <QButtonGroup> #include <QString> #include <QMap> #include <QPainter> #include <QFile> #include <QTextStream> #include <QLibrary> #include <math.h> #include <algorithm> #include <QPushButton> #include <QVariant> #include <QRgb> #include <QtDebug> //#include <QtConcurrentRun> #include <QMessageBox> #include <iostream> #include "../smallvm/vm_ffi.h" using namespace std; #define _ws(s) QString::fromStdWString(s) void PrintProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *) { if(stack.empty()) proc->signal(InternalError1, "Empty operand stack when reading value to in 'print'"); Value *v = stack.pop(); QString str = v->toString(); w->textLayer.print(str); w->redrawWindow(); } void PushReadChanProc(VOperandStack &stack, Process *, RunWindow *w, VM *) { stack.push(w->readChannel); } void MouseEventChanProc(VOperandStack &stack, Process *, RunWindow *w, VM *vm) { stack.push(w->realmouseEventChannel); } void MouseDownEventChanProc(VOperandStack &stack, Process *, RunWindow *w, VM *vm) { stack.push(w->realmouseDownEventChannel); } void MouseUpEventChanProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { stack.push(w->realmouseUpEventChannel); } void MouseMoveEventChanProc(VOperandStack &stack, Process *, RunWindow *w, VM *) { stack.push(w->realmouseMoveEventChannel); } void KbEventChanProc(VOperandStack &stack, Process *, RunWindow *w, VM *) { stack.push(w->realkbEventChannel); } void EnableMouseEventChanProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { bool enable = popBool(stack, proc, w, vm); if(enable) { w->mouseEventChannel = w->realmouseEventChannel; } else { w->mouseEventChannel = NULL; } } void EnableMouseDownEventChanProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { bool enable = popBool(stack, proc, w, vm); if(enable) { w->mouseDownEventChannel = w->realmouseDownEventChannel; } else { w->mouseDownEventChannel = NULL; } } void EnableMouseUpEventChanProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { bool enable = popBool(stack, proc, w, vm); if(enable) { w->mouseUpEventChannel = w->realmouseUpEventChannel; } else { w->mouseUpEventChannel = NULL; } } void EnableMouseMoveEventChanProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { bool enable = popBool(stack, proc, w, vm); if(enable) { w->mouseMoveEventChannel = w->realmouseMoveEventChannel; } else { w->mouseMoveEventChannel = NULL; } } void EnableKbEventChanProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { bool enable = popBool(stack, proc, w, vm); if(enable) { w->kbEventChannel = w->realkbEventChannel; } else { w->kbEventChannel = NULL; } } WindowReadMethod::WindowReadMethod(RunWindow *parent, VM *vm) { this->parent = parent; this->vm = vm; this->readNum = false; } void WindowReadMethod::operator ()(VOperandStack &operandStack, Process *proc) { readNum = popInt(operandStack, proc, parent, vm); parent->beginInput(); parent->update(); // We must do this, because normal updating is done // by calling redrawWindow() in the instruction loop, and // here we suspend the instruction loop... } void SetCursorPosProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int line = popInt(stack, proc, w, vm); int col = popInt(stack, proc, w, vm); bool result = w->textLayer.setCursorPos(line, col); proc->assert(result, ArgumentError, VM::argumentErrors[ArgErr::InvalidCursorPosition]); } void GetCursorRowProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int r = w->textLayer.getCursorRow(); stack.push(vm->GetAllocator().newInt(r)); } void GetCursorColProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int c = w->textLayer.getCursorCol(); stack.push(vm->GetAllocator().newInt(c)); } void PrintUsingWidthProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *) { Value *v = stack.pop(); w->typeCheck(proc, stack.top(), BuiltInTypes::IntType); int wid = unboxInt(stack.pop()); QString str = v->toString(); w->textLayer.print(str, wid); } void DrawPixelProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int x = popIntOrCoercable(stack, proc, w, vm); int y = popIntOrCoercable(stack, proc, w, vm); int color = popInt(stack, proc, w, vm); if(color == -1) color = 0; QColor clr = w->paintSurface->GetColor(color); w->paintSurface->TX(x); QPainter p(w->paintSurface->GetImageForWriting()); p.fillRect(x, y, 1, 1, clr); w->redrawWindow(); } void DrawLineProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int x1 = popIntOrCoercable(stack, proc, w, vm); int y1 = popIntOrCoercable(stack, proc, w, vm); int x2 = popIntOrCoercable(stack, proc, w, vm); int y2 = popIntOrCoercable(stack, proc, w, vm); w->paintSurface->TX(x1); w->paintSurface->TX(x2); int color = popInt(stack, proc, w, vm); if(color ==-1) color = 0; QColor clr = w->paintSurface->GetColor(color); QPainter p(w->paintSurface->GetImageForWriting()); QColor oldcolor = p.pen().color(); QPen pen = p.pen(); pen.setColor(clr); p.setPen(pen); p.drawLine(x1, y1, x2, y2); pen.setColor(oldcolor); p.setPen(pen); w->redrawWindow(); } void DrawRectProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int x1 = popIntOrCoercable(stack, proc, w, vm); int y1 = popIntOrCoercable(stack, proc, w, vm); int x2 = popIntOrCoercable(stack, proc, w, vm); int y2 = popIntOrCoercable(stack, proc, w, vm); w->paintSurface->TX(x1); w->paintSurface->TX(x2); int color = popInt(stack, proc, w, vm); bool filled = popBool(stack, proc, w, vm); if(color ==-1) color = 0; QPainter p(w->paintSurface->GetImageForWriting()); int top = min(y1, y2); int left = min(x1, x2); int wid = abs(x2-x1); int hei = abs(y2-y1); QColor clr = w->paintSurface->GetColor(color); QColor oldcolor = p.pen().color(); QPen pen = p.pen(); pen.setColor(clr); p.setPen(pen); if(filled) { QBrush oldBrush = p.brush(); p.setBrush(QBrush(clr,Qt::SolidPattern)); p.drawRect(left, top, wid, hei); p.setBrush(oldBrush); } else { p.setBrush(Qt::NoBrush); p.drawRect(left, top, wid, hei); } pen.setColor(oldcolor); p.setPen(pen); w->redrawWindow(); } void DrawCircleProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int cx = popIntOrCoercable(stack, proc, w, vm); int cy = popIntOrCoercable(stack, proc, w, vm); int radius = popIntOrCoercable(stack, proc, w, vm); int color = popInt(stack, proc, w, vm); bool filled = popBool(stack, proc, w, vm); w->paintSurface->TX(cx); QPainter p(w->paintSurface->GetImageForWriting()); if(color ==-1) color = 0; QColor clr = w->paintSurface->GetColor(color); QColor oldcolor = p.pen().color(); QPen pen = p.pen(); pen.setColor(clr); p.setPen(pen); if(filled) { QBrush oldBrush = p.brush(); p.setBrush(QBrush(clr,Qt::SolidPattern)); p.drawEllipse(cx-radius, cy-radius, radius*2, radius*2); p.setBrush(oldBrush); } else { p.setBrush(Qt::NoBrush); p.drawEllipse(cx-radius, cy-radius, radius*2, radius*2); } pen.setColor(oldcolor); p.setPen(pen); w->redrawWindow(); } void RandomProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int max = popIntOrCoercable(stack, proc, w, vm); vm->assert(proc, max >0, ArgumentError, VM::argumentErrors[ArgErr::RandTakesPositiveValues]); int ret = rand()%max; stack.push(vm->GetAllocator().newInt(ret)); } Value *ConvertStringToNumber(QString str, VM *vm) { bool ok; QLocale loc(QLocale::Arabic, QLocale::Egypt); int i = loc.toInt(str, &ok,10); if(ok) { return vm->GetAllocator().newInt(i); } long lng = loc.toLongLong(str, &ok, 10); if(ok) { return vm->GetAllocator().newLong(lng); } i = str.toInt(&ok, 10); if(ok) { return vm->GetAllocator().newInt(i); } double d = str.toDouble(&ok); if(ok) { return vm->GetAllocator().newDouble(d); } return NULL; } void ToNumProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str = popString(stack, proc, w, vm); Value * v = ConvertStringToNumber(str, vm); if(v != NULL) stack.push(v); else { proc->signal(ArgumentError, VM::argumentErrors.get(ArgErr::CannotConvertStrToInt1, str)); } } void ConcatProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str1 = popString(stack, proc, w, vm); QString str2 = popString(stack, proc, w, vm); QString ret = str1 + str2; stack.push(vm->GetAllocator().newString(ret)); } void StrLenProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str = popString(stack, proc, w, vm); int ret = str.length(); stack.push(vm->GetAllocator().newInt(ret)); } void StrFirstProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str = popString(stack, proc, w, vm); int n = popInt(stack, proc, w, vm); QString ret = str.left(n); stack.push(vm->GetAllocator().newString(ret)); } void StrLastProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str = popString(stack, proc, w, vm); int n = popInt(stack, proc, w, vm); QString ret = str.right(n); stack.push(vm->GetAllocator().newString(ret)); } void StrMidProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str = popString(stack, proc, w, vm); int i = popInt(stack, proc, w, vm); int n = popInt(stack, proc, w, vm); // We make indexing one-based instead of QT's zero-based // todo: range checking in StrMidProc() QString ret = str.mid(i -1 ,n); stack.push(vm->GetAllocator().newString(ret)); } void StrBeginsWithProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString strMain = popString(stack, proc, w, vm); QString strSub = popString(stack, proc, w, vm); bool ret = strMain.startsWith(strSub, Qt::CaseSensitive); stack.push(vm->GetAllocator().newBool(ret)); } void StrEndsWithProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString strMain = popString(stack, proc, w, vm); QString strSub = popString(stack, proc, w, vm); bool ret = strMain.endsWith(strSub, Qt::CaseSensitive); stack.push(vm->GetAllocator().newBool(ret)); } void StrContainsProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString strMain = popString(stack, proc, w, vm); QString strSub = popString(stack, proc, w, vm); bool ret = strMain.contains(strSub, Qt::CaseSensitive); stack.push(vm->GetAllocator().newBool(ret)); } void StrSplitProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str = popString(stack, proc, w, vm); QString separator = popString(stack, proc, w, vm); QStringList result = str.split(separator, QString::KeepEmptyParts); Value *ret = vm->GetAllocator().newArray(result.count()); for(int i=0; i<result.count(); i++) { unboxArray(ret)->Elements[i] = vm->GetAllocator().newString(result[i]); } stack.push(ret); } void StrTrimProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str = popString(stack, proc, w, vm); QString str2 = str.trimmed(); Value *ret = vm->GetAllocator().newString(str2); stack.push(ret); } void StrReplaceProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString str = popString(stack, proc, w, vm); QString str2 = popString(stack, proc, w, vm); QString str3 = popString(stack, proc, w, vm); str = str.replace(str2, str3); Value *ret = vm->GetAllocator().newString(str); stack.push(ret); } void ToStringProc(VOperandStack &stack, Process *proc, RunWindow *, VM *vm) { verifyStackNotEmpty(stack, proc, vm); Value *v = stack.pop(); QString ret = v->toString(); stack.push(vm->GetAllocator().newString(ret)); } void RoundProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double d = popDoubleOrCoercable(stack, proc, w, vm); int i = (int) d; stack.push(vm->GetAllocator().newInt(i)); } void RemainderProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int n1 = popInt(stack, proc, w, vm); int n2 = popInt(stack, proc, w, vm); if(n2 == 0) proc->signal(DivisionByZero); int i = n1 % n2; stack.push(vm->GetAllocator().newInt(i)); } int popIntOrCoercable(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { if(stack.empty()) { proc->signal(InternalError1, "Empty operand stack when reading value"); } Value *v = stack.pop(); if(v->type != BuiltInTypes::IntType && v->type != BuiltInTypes::DoubleType && v->type != BuiltInTypes::LongType) { w->typeError(proc, BuiltInTypes::NumericType, v->type); } if(v->type == BuiltInTypes::DoubleType) v = vm->GetAllocator().newInt((int) unboxDouble(v)); if(v->type == BuiltInTypes::LongType) v = vm->GetAllocator().newInt((int) unboxLong(v)); return unboxInt(v); } double popDoubleOrCoercable(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { if(stack.empty()) { proc->signal(InternalError1, "Empty operand stack when reading double or double-coercible value"); } Value *v = stack.pop(); if(v->type != BuiltInTypes::IntType && v->type != BuiltInTypes::DoubleType && v->type != BuiltInTypes::LongType) { w->typeError(proc, BuiltInTypes::NumericType, v->type); } if(v->type == BuiltInTypes::IntType) v = vm->GetAllocator().newDouble(unboxInt(v)); if(v->type == BuiltInTypes::LongType) v = vm->GetAllocator().newDouble(unboxLong(v)); return unboxDouble(v); } void verifyStackNotEmpty(VOperandStack &stack, Process *proc, VM *) { if(stack.empty()) { proc->signal(InternalError1, "Empty operand stack"); } } void SinProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = sin(theta); stack.push(vm->GetAllocator().newDouble(result)); } void CosProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = cos(theta); stack.push(vm->GetAllocator().newDouble(result)); } void TanProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = tan(theta); stack.push(vm->GetAllocator().newDouble(result)); } void ASinProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = asin(theta); stack.push(vm->GetAllocator().newDouble(result)); } void ACosProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = acos(theta); stack.push(vm->GetAllocator().newDouble(result)); } void ATanProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = atan(theta); stack.push(vm->GetAllocator().newDouble(result)); } void SqrtProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = sqrt(theta); stack.push(vm->GetAllocator().newDouble(result)); } void PowProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double base = popDoubleOrCoercable(stack, proc, w, vm); double power = popDoubleOrCoercable(stack, proc, w, vm); double result = pow(base, power); stack.push(vm->GetAllocator().newDouble(result)); } void Log10Proc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = log10(theta); stack.push(vm->GetAllocator().newDouble(result)); } void LnProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { double theta = popDoubleOrCoercable(stack, proc, w, vm); double result = log(theta); stack.push(vm->GetAllocator().newDouble(result)); } void LoadImageProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); QString fname = popString(stack, proc, w, vm); fname = w->ensureCompletePath(proc, fname); if(!QFile::exists(fname)) { w->assert(proc, false, ArgumentError, VM::argumentErrors.get(ArgErr::NonExistingImageFile1,fname)); } IClass *imgClass = dynamic_cast<IClass *>(unboxObj(vm->GetType(VMId::get(RId::Image)))); QImage *img = new QImage(fname); IObject *obj = imgClass->newValue(&vm->GetAllocator()); obj->setSlotValue("handle", vm->GetAllocator().newRaw(img, BuiltInTypes::RawType)); stack.push(vm->GetAllocator().newObject(obj, imgClass)); } void LoadSpriteProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); QString fname = popString(stack, proc, w, vm); fname = w->ensureCompletePath(proc, fname); if(!QFile::exists(fname)) { w->assert(proc, false, ArgumentError, VM::argumentErrors.get(ArgErr::NonExistingSpriteFile1, fname)); } Sprite *sprite = new Sprite(fname); w->spriteLayer.AddSprite(sprite); stack.push(MakeSpriteValue(sprite, &vm->GetAllocator())); } void SpriteFromImageProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *imgClass = dynamic_cast<IClass *>(unboxObj(vm->GetType(VMId::get(RId::Image)))); verifyStackNotEmpty(stack, proc, vm); w->typeCheck(proc, stack.top(), imgClass); IObject *obj = unboxObj(stack.pop()); QImage *handle = reinterpret_cast<QImage*> (unboxRaw((obj->getSlotValue("handle")))); Sprite *sprite = new Sprite(QPixmap::fromImage(*handle)); w->spriteLayer.AddSprite(sprite); stack.push(MakeSpriteValue(sprite, &vm->GetAllocator())); } Sprite *GetSpriteFromValue(Value * v) { IObject *obj = unboxObj(v); Value *rawSpr = obj->getSlotValue("_handle"); Sprite *spr = (Sprite *) unboxRaw(rawSpr); return spr; } Value *MakeSpriteValue(Sprite *sprite, Allocator *alloc) { Value *spriteHandle = alloc->newRaw(sprite, BuiltInTypes::RawType); alloc->stopGcMonitoring(spriteHandle); //todo: we stopGcMonitoring each thing we allocate since // possible GC in the next allocation could erase it // the return GcMonitoring after each allocation. // but the problem is we don't have access to whatever objects // allocated internally by SpriteType.newValue (luckily // nothing is actually allocated there now), so we can't do this // we really need atomic allocation of multiple values IObject *spriteObj = BuiltInTypes::SpriteType->newValue(alloc); spriteObj->setSlotValue("_handle", spriteHandle); Value *spriteVal = alloc->newObject( spriteObj, BuiltInTypes::SpriteType); alloc->makeGcMonitored(spriteHandle); sprite->extraValue = spriteVal; return spriteVal; } void DrawImageProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *imgClass = dynamic_cast<IClass *>(unboxObj(vm->GetType(VMId::get(RId::Image)))); w->typeCheck(proc, stack.top(), imgClass); IObject *obj = unboxObj(stack.pop()); QImage *handle = reinterpret_cast<QImage*> (unboxRaw((obj->getSlotValue("handle")))); int x = popIntOrCoercable(stack, proc, w , vm); int y = popIntOrCoercable(stack, proc, w , vm); w->paintSurface->TX(x, handle->width()); x-= handle->width(); QPainter p(w->paintSurface->GetImageForWriting()); p.drawImage(x, y, *handle); w->redrawWindow(); } void DrawSpriteProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Value *spriteVal =stack.pop(); Sprite *sprite = GetSpriteFromValue(spriteVal); int x = popIntOrCoercable(stack, proc, w , vm); int y = popIntOrCoercable(stack, proc, w , vm); sprite->location = QPoint(x,y); sprite->visible = true; vm->GetAllocator().stopGcMonitoring(spriteVal); w->spriteLayer.showSprite(sprite); // If a sprite is visible on the screen, we don't want to GC // it, since a collision function that might use it // could be called. A sprite can be GC'd only if it is // both unreachable and invisible w->checkCollision(sprite); w->redrawWindow(); } void ShowSpriteProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Value *spriteVal = stack.pop(); Sprite *sprite = GetSpriteFromValue(spriteVal); sprite->visible = true; vm->GetAllocator().stopGcMonitoring(spriteVal); w->spriteLayer.showSprite(sprite); // If a sprite is visible on the screen, we don't want to GC // it, since a collision function that might use it // could be called. A sprite can be GC'd only if it is // both unreachable and invisible w->checkCollision(sprite); w->redrawWindow(); } void HideSpriteProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Value *spriteVal = stack.pop(); Sprite *sprite = GetSpriteFromValue(spriteVal); sprite->visible = false; w->spriteLayer.hideSprite(sprite); // See ShowSpriteProc and DrawSpriteProc // for why the sprite was not GC monitored when visible //vm->GetAllocator().makeGcMonitored(spriteVal); w->redrawWindow(); } void GetSpriteLeftProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Sprite *sprite = GetSpriteFromValue(stack.pop()); #ifdef ENGLISH_PL int ret = sprite->location.x(); #else int ret = sprite->location.x() + sprite->image.width(); #endif stack.push(vm->GetAllocator().newInt(ret)); } void GetSpriteRightProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Sprite *sprite = GetSpriteFromValue(stack.pop()); #ifdef ENGLISH_PL int ret = sprite->location.x() + sprite->image.width(); #else int ret = sprite->location.x(); #endif stack.push(vm->GetAllocator().newInt(ret)); } void GetSpriteTopProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Sprite *sprite = GetSpriteFromValue(stack.pop()); int ret = sprite->boundingRect().top(); stack.push(vm->GetAllocator().newInt(ret)); } void GetSpriteBottomProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Sprite *sprite = GetSpriteFromValue(stack.pop()); int ret = sprite->boundingRect().bottom(); stack.push(vm->GetAllocator().newInt(ret)); } void GetSpriteWidthProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Value *spriteVal = stack.pop(); Sprite *sprite = GetSpriteFromValue(spriteVal); int ret = sprite->boundingRect().width(); stack.push(vm->GetAllocator().newInt(ret)); } void GetSpriteHeightProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Sprite *sprite = GetSpriteFromValue(stack.pop()); int ret = sprite->boundingRect().height(); stack.push(vm->GetAllocator().newInt(ret)); } void GetSpriteImageProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Sprite *sprite = GetSpriteFromValue(stack.pop()); QString clsName = VMId::get(RId::Image); QImage *img = new QImage(sprite->image.toImage()); IClass *imgClass = dynamic_cast<IClass *> (unboxObj(vm->GetType(clsName))); IObject *imgObj = imgClass->newValue(&vm->GetAllocator()); imgObj->setSlotValue("handle", vm->GetAllocator().newRaw(img, BuiltInTypes::RawType)); stack.push(vm->GetAllocator().newObject(imgObj, imgClass)); } void SetSpriteImageProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString clsName = VMId::get(RId::Image); IClass *imgClass = dynamic_cast<IClass *> (unboxObj(vm->GetType(clsName))); w->typeCheck(proc, stack.top(), BuiltInTypes::SpriteType); Sprite *sprite = GetSpriteFromValue(stack.pop()); w->typeCheck(proc, stack.top(), imgClass); IObject *imgObj = unboxObj(stack.pop()); QImage *img = reinterpret_cast<QImage *> (unboxRaw((imgObj->getSlotValue("handle")))); sprite->setImage(QPixmap::fromImage(*img)); w->spriteLayer.changing(); w->redrawWindow(); } void WaitProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { /* int ms = stack.pop()->unboxNumeric(); // The GC could collect the channel // even when the RunWindow is still to send it a message // therefore in the wait() builtin // we shall store a reference to it // in a local variable Value *channel = vm->GetAllocator().newChannel(false); //w->suspend(); int cookie = w->startTimer(ms); w->setAsleep(cookie, channel, ms); stack.push(channel); */ int ms = unboxNumeric(stack.pop()); proc->owner->makeItWaitTimer(proc, ms); } void ZoomProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int x1 = popIntOrCoercable(stack, proc, w , vm); int y1 = popIntOrCoercable(stack, proc, w , vm); int x2 = popIntOrCoercable(stack, proc, w , vm); int y2 = popIntOrCoercable(stack, proc, w , vm); //w->TX(x1); //w->TX(x2); w->paintSurface->zoom(x1, y1, x2, y2); } void ClsProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->cls(); } void ClearTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->clearAllText(); } void SetTextColorProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int color = popInt(stack, proc, w, vm); w->assert(proc, color>=0 && color <=15, ArgumentError, "Color value must be from 0 to 15"); //w->paintSurface->setTextColor(w->paintSurface->GetColor(color)); w->textLayer.setColor(w->paintSurface->GetColor(color)); w->redrawWindow(); } void PointAtProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int x = popIntOrCoercable(stack, proc, w, vm); int y = popIntOrCoercable(stack, proc, w, vm); w->paintSurface->TX(x); int color = 15; /* w->assert(x>=0 && x <w->paintSurface->GetImage()->width(), ArgumentError, VM::argumentErrors.get(ArgErr::InvalidArgRange3, VM::argumentErrors.get(ArgErr::X, "0", str(w->paintSurface->GetImage()->width()))) ); w->assert(y>=0 && y <w->paintSurface->GetImage()->height(), ArgumentError, VM::argumentErrors.get(ArgErr::InvalidArgRange3, VM::argumentErrors.get(ArgErr::Y, "0", str(w->paintSurface->GetImage()->height()))) ); //*/ if(x>=0 && y >=0 && x<w->paintSurface->GetImage()->width() && y < w->paintSurface->GetImage()->height()) { // todo: implement colorConstant that takes // QRgb to save time converting QRgb->QColor color = w->paintSurface->colorConstant(QColor(w->paintSurface->GetImage()->pixel(x, y))); } stack.push(vm->GetAllocator().newInt(color)); } void PointRgbAtProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int x = popIntOrCoercable(stack, proc, w, vm); int y = popIntOrCoercable(stack, proc, w, vm); w->paintSurface->TX(x); QRgb color = qRgb(255,255,255); /* w->assert(x>=0 && x <w->paintSurface->GetImage()->width(), ArgumentError, VM::argumentErrors.get(ArgErr::InvalidArgRange3, VM::argumentErrors.get(ArgErr::X, "0", str(w->paintSurface->GetImage()->width()))) ); w->assert(y>=0 && y <w->paintSurface->GetImage()->height(), ArgumentError, VM::argumentErrors.get(ArgErr::InvalidArgRange3, VM::argumentErrors.get(ArgErr::Y, "0", str(w->paintSurface->GetImage()->height()))) ); */ if(x>=0 && y >=0 && x<w->paintSurface->GetImage()->width() && y < w->paintSurface->GetImage()->height()) { color = w->paintSurface->GetImage()->pixel(x, y); } Allocator &a = vm->GetAllocator(); Value *arr = a.newArray(3); unboxArray(arr)->set(a.newInt(1), a.newInt(qRed(color))); unboxArray(arr)->set(a.newInt(2), a.newInt(qGreen(color))); unboxArray(arr)->set(a.newInt(3), a.newInt(qBlue(color))); stack.push(arr); } void BuiltInConstantProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString constName = popString(stack, proc, w, vm); if(constName == VMId::get(RId::NewLine)) { stack.push(vm->GetAllocator().newString("\n")); return; } if(constName ==QString::fromStdWString(L"c_int")) { stack.push(vm->GetAllocator().newObject(BuiltInTypes::c_int, BuiltInTypes::ClassType, false)); return; } if(constName == QString::fromStdWString(L"c_long")) { stack.push(vm->GetAllocator().newObject(BuiltInTypes::c_long, BuiltInTypes::ClassType, false)); return; } if(constName == QString::fromStdWString(L"c_float")) { stack.push(vm->GetAllocator().newObject(BuiltInTypes::c_float, BuiltInTypes::ClassType, false)); return; } if(constName == QString::fromStdWString(L"c_double")) { stack.push(vm->GetAllocator().newObject(BuiltInTypes::c_double, BuiltInTypes::ClassType, false)); return; } if(constName== QString::fromStdWString(L"c_char")) { stack.push(vm->GetAllocator().newObject(BuiltInTypes::c_char, BuiltInTypes::ClassType, false)); return; } if(constName == QString::fromStdWString(L"c_asciiz")) { stack.push(vm->GetAllocator().newObject(BuiltInTypes::c_asciiz, BuiltInTypes::ClassType, false)); return; } if(constName == QString::fromStdWString(L"c_wstr")) { stack.push(vm->GetAllocator().newObject(BuiltInTypes::c_wstr, BuiltInTypes::ClassType, false)); return; } if(constName == QString::fromStdWString(L"c_ptr")) { stack.push(vm->GetAllocator().newObject(BuiltInTypes::c_ptr, BuiltInTypes::ClassType, false)); return; } w->assert(proc, false, ArgumentError, VM::argumentErrors.get(ArgErr::InvalidConstantName1, constName)); } void StringIsNumericProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString s = popString(stack, proc, w, vm); bool yep = true; for(int i=0; i<s.length(); i++) { QChar c = s[i]; if(!c.isDigit()) yep = false; } stack.push(vm->GetAllocator().newBool(yep)); } void StringIsAlphabeticProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString s = popString(stack, proc, w, vm); bool yep = true; for(int i=0; i<s.length(); i++) { QChar c = s[i]; if(!c.isLetter()) yep = false; } stack.push(vm->GetAllocator().newBool(yep)); } void TypeOfProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { Value *v = popValue(stack, proc, w, vm); // We use a gcMonitor value of false since we don't want the GC // to collect class objects stack.push(vm->GetAllocator().newObject(v->type, BuiltInTypes::ClassType, false)); } void TypeFromIdProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString typeId = popString(stack, proc, w, vm); Value *type = vm->GetType(typeId); stack.push(type); } void AddressOfProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { Value *v = popValue(stack, proc, w, vm); ffi_type *type; IClass *guessedType; default_C_Type_Of(v->type, guessedType); kalimat_to_ffi_type(guessedType, type, vm); if(type == NULL) { proc->signal(InternalError1, QString("Cannot take address of value of type: '%1'").arg(v->type->toString())); } void *ptr = malloc(type->size); kalimat_to_ffi_value(v->type, v, type, ptr, proc, vm); //todo: stack.push(vm->GetAllocator().newRaw(ptr, new PointerClass(v->type))); } void NewMapProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { stack.push(vm->GetAllocator().newMap()); } void HasKeyProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::MapType); Value *v = popValue(stack, proc, w, vm); Value *key = popValue(stack, proc, w, vm); VMap *m = unboxMap(v); VMError err; if(!m->keyCheck(key, err)) throw err; bool result = (m->get(key) != NULL); stack.push(vm->GetAllocator().newBool(result)); } void KeysOfProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::MapType); Value *v = popValue(stack, proc, w, vm); VMap *m = unboxMap(v); const int keyCount = m->Elements.keys().count(); Value *k = vm->GetAllocator().newArray(keyCount); for(int i=0; i<keyCount; i++) unboxArray(k)->Elements[i] = m->Elements.keys()[i].v; stack.push(k); } void MapKeyProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { w->typeCheck(proc, stack.top(), BuiltInTypes::MapType); Value *v = popValue(stack, proc, w, vm); VMap *m = unboxMap(v); int keyIndex = popInt(stack, proc, w, vm); const int keyCount = m->Elements.keys().count(); if(keyIndex < 1 || keyIndex > keyCount) throw VMError(SubscriptOutOfRange2, proc, proc->owner, proc->currentFrame()).arg(str(keyIndex)).arg(str(keyCount)); Value *ret = m->Elements.keys()[keyIndex-1].v; stack.push(ret); } struct FileBlob { QFile *file; QTextStream *stream; ~FileBlob() { file->close(); delete file; delete stream;} }; // TODO: use the helpers popXXX(...) functions instead of manually calling // typecheck() and pop() in all external methods. FileBlob *popFileBlob(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); w->typeCheck(proc, stack.top(), BuiltInTypes::FileType); IObject *ob = unboxObj(stack.pop()); Value *rawFile = ob->getSlotValue("file_handle"); w->typeCheck(proc, rawFile, BuiltInTypes::RawFileType); void *fileObj = unboxRaw(rawFile); FileBlob *f = (FileBlob *) fileObj; return f; } Value *popValue(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); Value *v = stack.pop(); return v; } Value *newGuiObject(void *ptr, IClass *type, VM *vm) { IObject *obj = type->newValue(&vm->GetAllocator()); obj->setSlotValue("handle", vm->GetAllocator().newRaw(ptr, BuiltInTypes::RawType)); return vm->GetAllocator().newObject(obj, type); } QString popString(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); w->typeCheck(proc, stack.top(), BuiltInTypes::StringType); QString s = unboxStr(stack.pop()); return s; } int popInt(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); w->typeCheck(proc, stack.top(), BuiltInTypes::IntType); int i = unboxInt(stack.pop()); return i; } void *popRaw(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm, IClass *type) { verifyStackNotEmpty(stack, proc, vm); w->typeCheck(proc, stack.top(), type); void *ret = unboxRaw(stack.pop()); return ret; } Channel *popChannel(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); w->typeCheck(proc, stack.top(), BuiltInTypes::ChannelType); Channel *ret = unboxChan(stack.pop()); return ret; } bool popBool(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); w->typeCheck(proc, stack.top(), BuiltInTypes::BoolType); bool b = unboxBool(stack.pop()); return b; } VArray *popArray(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { verifyStackNotEmpty(stack, proc, vm); w->typeCheck(proc, stack.top(), BuiltInTypes::ArrayType); VArray *arr = unboxArray(stack.pop()); return arr; } void DoFileWrite(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm, bool newLine) { FileBlob *f = popFileBlob(stack, proc, w, vm); QString s = popValue(stack, proc, w, vm)->toString(); if(f->file == NULL) w->assert(proc, false, ArgumentError, VM::argumentErrors[ArgErr::CannotWriteToClosedFile]); if(newLine) *(f->stream) << s << endl; else *(f->stream) << s; } void FileWriteProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { DoFileWrite(stack, proc, w, vm, false); } void FileWriteUsingWidthProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { FileBlob *f = popFileBlob(stack, proc, w, vm); if(f->file == NULL) w->assert(proc, false, ArgumentError, VM::argumentErrors[ArgErr::CannotWriteToClosedFile]); QString s = popValue(stack, proc, w, vm)->toString(); int width = popInt(stack, proc, w, vm); QString s2 = w->textLayer.formatStringUsingWidth(s, width); *(f->stream) << s2; } void FileWriteLineProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { DoFileWrite(stack, proc, w, vm, true); } void FileReadLineProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { FileBlob *f = popFileBlob(stack, proc, w, vm); if(f->file == NULL) w->assert(proc, false, ArgumentError, VM::argumentErrors[ArgErr::CannotReadFromClosedFile]); QString s = f->stream->readLine(); Value *v = vm->GetAllocator().newString(s); stack.push(v); } void FileEofProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { FileBlob *f = popFileBlob(stack, proc, w, vm); if(f->file == NULL) w->assert(proc, false, ArgumentError, VM::argumentErrors[ArgErr::CannotReadFromClosedFile]); bool ret = f->stream->atEnd(); Value *v = vm->GetAllocator().newBool(ret); stack.push(v); } void FileOpenProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString fname = popString(stack, proc, w, vm); fname = w->ensureCompletePath(proc, fname); w->assert(proc, QFile::exists(fname), ArgumentError, VM::argumentErrors.get(ArgErr::TryingToOpenMissingFile1, fname)); QFile *f = new QFile(fname); bool ret = f->open(QIODevice::ReadOnly | QIODevice::Text); w->assert(proc, ret, RuntimeError, VM::argumentErrors.get(ArgErr::FailedToOpenFile1,fname)); QTextStream *stream = new QTextStream(f); FileBlob *blob = new FileBlob(); blob->file = f; blob->stream = stream; Value *v = vm->GetAllocator().newObject(BuiltInTypes::FileType); unboxObj(v)->setSlotValue("file_handle", vm->GetAllocator().newRaw(blob, BuiltInTypes::RawFileType)); stack.push(v); } void FileCreateProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString fname = popString(stack, proc, w, vm); fname = w->ensureCompletePath(proc, fname); QFile *f = new QFile(fname); bool ret = f->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate); w->assert(proc, ret, RuntimeError, VM::argumentErrors.get(ArgErr::FailedToOpenFile1,fname)); QTextStream *stream = new QTextStream(f); FileBlob *blob = new FileBlob(); blob->file = f; blob->stream = stream; Value *v = vm->GetAllocator().newObject(BuiltInTypes::FileType); unboxObj(v)->setSlotValue("file_handle", vm->GetAllocator().newRaw(blob, BuiltInTypes::RawFileType)); stack.push(v); } void FileAppendProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString fname = popString(stack, proc, w, vm); fname = w->ensureCompletePath(proc, fname); QFile *f = new QFile(fname); bool ret = f->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append); w->assert(proc, ret, ArgumentError, VM::argumentErrors.get(ArgErr::FailedToOpenFile1,fname)); Value *v = vm->GetAllocator().newObject(BuiltInTypes::FileType); QTextStream *stream = new QTextStream(f); FileBlob *blob = new FileBlob(); blob->file = f; blob->stream = stream; unboxObj(v)->setSlotValue("file_handle", vm->GetAllocator().newRaw(blob, BuiltInTypes::RawFileType)); stack.push(v); } void FileCloseProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { // TODO: use popFileblob w->typeCheck(proc, stack.top(), BuiltInTypes::FileType); IObject *ob = unboxObj(stack.pop()); Value *rawFile = ob->getSlotValue("file_handle"); w->typeCheck(proc, rawFile, BuiltInTypes::RawFileType); void *fileObj = unboxRaw(rawFile); FileBlob *f = (FileBlob *) fileObj; f->file->close(); // TODO: memory leak if we comment the following line // but a segfault if we delete 'f' and the the kalimat code // tries to do some operation on the file :( delete f->file; delete f->stream; f->file = NULL; } Value *editAndReturn(Value *v, RunWindow *w, VM *vm); void EditProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { Value *v = stack.pop(); w->assert(proc, v->isObject(), ArgumentError, VM::argumentErrors.get(ArgErr::SentValueHasToBeAnObject1, v->toString())); v = editAndReturn(v, w, vm); stack.push(v); } void GetMainWindowProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { stack.push(vm->GetAllocator().newQObject(w)); } void NewChannelProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { stack.push(vm->GetAllocator().newChannel()); } void LoadLibraryProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString libName = popString(stack, proc, w, vm); // todo: will this leak? QLibrary *lib = new QLibrary(libName); if(!lib->load()) proc->signal(InternalError1, QString("Failed to load library '%1'").arg(libName)); Value *ret = vm->GetAllocator().newRaw(lib, BuiltInTypes::ExternalLibrary); stack.push(ret); } void GetProcAddressProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { void *libRaw = popRaw(stack, proc, w, vm, BuiltInTypes::ExternalLibrary); QString funcName = popString(stack, proc, w, vm); // todo: invalid casts here will crash the VM QLibrary *lib = (QLibrary *) libRaw; // todo: all those conversion might be slow void * func = lib->resolve(funcName.toStdString().c_str()); if(func == NULL) { proc->signal(InternalError1, QString("Cannot find function called '%1' in external library %2") .arg(funcName).arg(lib->fileName())); } Value *ret = vm->GetAllocator().newRaw(func, BuiltInTypes::ExternalMethodType); stack.push(ret); } void TestMakeCArrayProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int *a = new int[5]; for(int i=0; i<5; i++) a[i] = 10 - i; stack.push(vm->GetAllocator().newRaw(a, BuiltInTypes::c_ptr)); } void InvokeForeignProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { void *funcPtr = popRaw(stack, proc, w, vm, BuiltInTypes::ExternalMethodType); VArray *args = popArray(stack, proc, w, vm); VArray *argTypes = NULL; bool guessArgTypes = false; if(stack.top()->type == BuiltInTypes::NullType) { guessArgTypes = true; stack.pop(); } else { argTypes = popArray(stack, proc, w, vm); } IClass *retType = unboxClass(stack.pop()); QVector<Value *> argz; QVector<IClass *> kargTypes; for(int i=0; i<args->count(); i++) { argz.append(args->Elements[i]); if(!guessArgTypes) { IClass *type = unboxClass(argTypes->Elements[i]); if(!type) { proc->signal(TypeError2, BuiltInTypes::ClassType->toString(), argTypes->Elements[i]->type->toString()); } kargTypes.append(type); } } Value *ret = CallForeign(funcPtr, argz, retType, kargTypes, guessArgTypes, proc, vm); if(ret) stack.push(ret); else stack.push(vm->GetAllocator().null()); } void CurrentParseTreeProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { Value *v = vm->GetGlobal("%parseTree"); stack.push(v); } void MakeParserProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { QString datum = popString(stack, proc, w, vm); IClass *parserClass = unboxClass(vm->GetType(VMId::get(RId::Parser))); IObject *parser = parserClass->newValue(&vm->GetAllocator()); parser->setSlotValue(VMId::get(RId::InputPos), vm->GetAllocator().newInt(0)); parser->setSlotValue(VMId::get(RId::Data), vm->GetAllocator().newString( datum)); stack.push(vm->GetAllocator().newObject(parser, parserClass)); } void PushParserBacktrackPointProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IObject *receiver = unboxObj(popValue(stack, proc, w, vm)); int arg1 = popInt(stack, proc, w, vm); ParserObj *parser = dynamic_cast<ParserObj *>(receiver); parser->stack.push(ParseFrame(arg1, parser->pos, true)); } void IgnoreParserBacktrackPointProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IObject *receiver = unboxObj(popValue(stack, proc, w, vm)); ParserObj *parser = dynamic_cast<ParserObj *>(receiver); ParseFrame f = parser->stack.pop(); if(!f.backTrack) w->assert(proc, false, InternalError1, VM::argumentErrors.get(ArgErr::StackTopNotBacktrackPointToIgnore1, str(f.continuationLabel))); } void ActivationFrameProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { int n = popIntOrCoercable(stack, proc, w, vm); Frame *s = proc->stack; n++; // skip the frame of this very function, 'activation_frame' // we used n > 0 instead of n!=0 to avoid problems with negative arguments // todo: this slows down things since we still search the entire frame list before // discovering the problem while(n > 0 && s != NULL) { s = s->next; n--; } if(n == 0) { // todo: not garbage collected? // we need not only a GCMonitor flag // but "heap objec owns real object" flag // for deletion upon destruction stack.push(vm->GetAllocator().newObject(s, BuiltInTypes::ActivationFrameType, false)); } else { throw VMError(InternalError1).arg(VM::argumentErrors.get(ArgErr::BadFrameNumber1, str(n))); } } void MigrateToGuiThreadProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { //proc->migrateTo(&vm->guiScheduler); //emit w->EmitGuiSchedule(); proc->wannaMigrateTo = &vm->guiScheduler; proc->exitTimeSlice(); } void MigrateBackFromGuiThreadProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { //proc->migrateTo(&vm->mainScheduler); proc->wannaMigrateTo = &vm->mainScheduler; proc->exitTimeSlice(); } void CloseChannelProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { Channel *chan = popChannel(stack, proc, w, vm); chan->close(); } void ChannelClosedProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { Channel *chan = popChannel(stack, proc, w, vm); stack.push(vm->GetAllocator().newBool(chan->closed())); } void ImageRotatedProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); double degrees = popDoubleOrCoercable(stack, proc, w, vm); QTransform trans; double width, height; QImage *img2; width = handle->width()/2; height = handle->height() /2 ; #ifndef ENGLISH_PL // negative because of 'Arabic' coordinate system trans = trans.translate(width,height).rotate(-degrees).translate(-width,-height); #else trans = trans.translate(width,height).rotate(degrees).translate(-width,-height); #endif img2 = new QImage(handle->width(),handle->height(), handle->format()); QPainter p(img2); QBrush brsh(handle->pixel(0,0)); p.setBrush(brsh); p.fillRect(0,0,handle->width(), handle->height(), handle->pixel(0,0)); p.translate(width, height); p.rotate(-degrees); p.translate(-width, -height); p.drawImage(0,0, *handle); Value *ret = newGuiObject(img2, type, vm); stack.push(ret); } void ImageScaledProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); double s1= popDoubleOrCoercable(stack, proc, w, vm); double s2= popDoubleOrCoercable(stack, proc, w, vm); QTransform trans; trans = trans.scale(s1, s2); QImage *img2 = new QImage(handle->transformed(trans)); Value *ret = newGuiObject(img2, type, vm); stack.push(ret); } void ImageDrawLineProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); int x1 = popIntOrCoercable(stack, proc, w, vm); int y1 = popIntOrCoercable(stack, proc, w, vm); int x2 = popIntOrCoercable(stack, proc, w, vm); int y2 = popIntOrCoercable(stack, proc, w, vm); { QPainter p(handle); p.drawLine(x1,y1,x2,y2); } } void ImageFlippedProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); double s1 = popDoubleOrCoercable(stack, proc, w, vm); double s2 = popDoubleOrCoercable(stack, proc, w, vm); if(s1>0) s1 = 1; else if(s1<0) s1 = -1; if(s2>0) s2 = 1; else if(s2<0) s2 = -1; QTransform trans; trans = trans.scale(s1, s2); QImage *img2 = new QImage(handle->transformed(trans)); Value *ret = newGuiObject(img2, type, vm); stack.push(ret); } void ImageCopiedProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); QImage *img2 = new QImage(handle->copy()); Value *ret = newGuiObject(img2, type, vm); stack.push(ret); } void ImageSetPixelColorProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); int x = popIntOrCoercable(stack, proc, w, vm); int y = popIntOrCoercable(stack, proc, w, vm); int clr = popIntOrCoercable(stack, proc, w, vm); handle->setPixel(x,y, clr); } void ImagePixelColorProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); int x = popIntOrCoercable(stack, proc, w, vm); int y = popIntOrCoercable(stack, proc, w, vm); int clr = handle->pixel(x, y); stack.push(vm->GetAllocator().newInt(clr)); } void ImageWidthProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newInt(handle->width())); } void ImageHeightProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newInt(handle->height())); } void ImageDrawTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QImage *handle = popGuiReceiver<QImage *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); int x = popIntOrCoercable(stack, proc, w, vm); int y = popIntOrCoercable(stack, proc, w, vm); QPainter p(handle); p.setFont(QFont("Arial", 12)); p.drawText(x, y, text); } void ForeignWindowMaximizeProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *win = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); win->setWindowState(Qt::WindowMaximized); } void ForeignWindowMoveToProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *win = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); int x = popIntOrCoercable(stack, proc, w, vm); int y = popIntOrCoercable(stack, proc, w, vm); win->move(x, y); } void ForeignWindowAddProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); QWidget *control = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); #ifndef ENGLISH_PL control->move(widget->width() - (control->x() + control->width()), control->y()); #endif control->setParent(widget); QFont f = control->font(); control->setFont(QFont(f.family(), f.pointSize()+3)); control->show(); } void ForeignWindowSetSizeProc(VOperandStack &stack, Process *proc, RunWindow *rw, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, rw, vm); int w = popIntOrCoercable(stack, proc, rw, vm); int h = popIntOrCoercable(stack, proc, rw, vm); #ifndef ENGLISH_PL //int wdiff = widget->width() - w; //* for(int i=0; i<widget->children().count(); i++) { QWidget *c = dynamic_cast<QWidget *>(widget->children().at(i)); if(c) { int cw = c->width(); int cx = c->x(); int cright = cx + cw; int right_delta = widget->width() - cright; int newx = w - (right_delta + cw); c->move(newx, c->y()); //qDebug() << "Moving " << c->windowTitle() << " to (" << c->x() <<", " << c->y() <<")"; } } //*/ // make it so resizing makes the righ side fixed, not // left side int left = widget->pos().x() + widget->width() - w; int top = widget->pos().y(); #endif widget->setFixedSize(w, h); #ifndef ENGLISH_PL widget->move(left, top); #endif } void ForeignWindowSetTitleProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); QString t = popString(stack, proc, w, vm); widget->setWindowTitle(t); } void ForeignWindowSetupProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IObject *window = unboxObj(popValue(stack, proc, w, vm)); QMainWindow *win = new QMainWindow(); Value *handle = vm->GetAllocator().newQObject(win); window->setSlotValue("handle", handle); } void ControlSetTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); QString str = popString(stack, proc, w, vm); widget->setWindowTitle(str); } void ControlSetSizeProc(VOperandStack &stack, Process *proc, RunWindow *rw, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, rw, vm); int w = popIntOrCoercable(stack, proc, rw, vm); int h = popIntOrCoercable(stack, proc, rw, vm); #ifndef ENGLISH_PL int originalx = widget->x() + widget->width(); #endif widget->resize(w, h); #ifndef ENGLISH_PL if(widget->parentWidget() != NULL) { originalx -= widget->width(); widget->move(originalx, widget->y()); } #endif } void ControlSetLocationProc(VOperandStack &stack, Process *proc, RunWindow *rw, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, rw, vm); int x = popIntOrCoercable(stack, proc, rw, vm); int y = popIntOrCoercable(stack, proc, rw, vm); #ifndef ENGLISH_PL if(widget->parentWidget()) { int pw = widget->parentWidget()->width(); x = (pw-1)-x; x-= widget->width(); } #endif widget->move(x, y); } void ControlTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newString(widget->windowTitle())); } void ControlShowProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); widget->show(); } void ControlHideProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); widget->hide(); } void ControlSetVisibleProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, w, vm); bool show = popBool(stack, proc, w, vm); widget->setVisible(show); } void ControlCloseProc(VOperandStack &stack, Process *proc, RunWindow *rw, VM *vm) { IClass *type; QWidget *widget = popGuiReceiver<QWidget *>(stack, type, proc, rw, vm); widget->close(); } void ButtonSetTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QPushButton *handle = popGuiReceiver<QPushButton *>(stack, type, proc, w, vm); QString s = popString(stack, proc, w, vm); handle->setText(s); } void ButtonTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QPushButton *handle = popGuiReceiver<QPushButton *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->text())); } void TextboxSetTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QTextEdit *handle = popGuiReceiver<QTextEdit *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->document()->setPlainText(text); } void TextboxTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QTextEdit *handle = popGuiReceiver<QTextEdit *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->document()->toPlainText())); } void TextboxAppendTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QTextEdit *handle = popGuiReceiver<QTextEdit *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->append(text); } void LineEditSetTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QLineEdit *handle = popGuiReceiver<QLineEdit *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->setText(text); } void LineEditTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QLineEdit *handle = popGuiReceiver<QLineEdit *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->text())); } void LineEditAppendTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QLineEdit *handle = popGuiReceiver<QLineEdit *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->setText(handle->text() + text); } void ListboxAddProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QListWidget *handle = popGuiReceiver<QListWidget *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->addItem(text); } void ListboxInsertItemProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QListWidget *handle = popGuiReceiver<QListWidget *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); int index = popInt(stack, proc, w, vm); handle->insertItem(index, text); } void ListboxGetItemProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QListWidget *handle = popGuiReceiver<QListWidget *>(stack, type, proc, w, vm); int index = popInt(stack, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->item(index)->text())); } void ComboBoxSetTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QComboBox *handle = popGuiReceiver<QComboBox *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->setEditText(text); } void ComboBoxTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QComboBox *handle = popGuiReceiver<QComboBox *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->currentText())); } void ComboBoxAddProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QComboBox *handle = popGuiReceiver<QComboBox *>(stack, type, proc, w, vm); Value *v = popValue(stack, proc, w, vm); handle->addItem(v->toString()); } void ComboBoxInsertItemProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QComboBox *handle = popGuiReceiver<QComboBox *>(stack, type, proc, w, vm); Value *v = popValue(stack, proc, w, vm); int index = popInt(stack, proc, w, vm); handle->insertItem(index, v->toString()); } void ComboBoxGetItemProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QComboBox *handle = popGuiReceiver<QComboBox *>(stack, type, proc, w, vm); int index = popInt(stack, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->itemText(index))); } void ComboBoxSetEditableProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QComboBox *handle = popGuiReceiver<QComboBox *>(stack, type, proc, w, vm); bool editable = popBool(stack, proc, w, vm); handle->setEditable(editable); } void LabelSetTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QLabel *handle = popGuiReceiver<QLabel *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->setText(text); } void LabelTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QLabel *handle = popGuiReceiver<QLabel *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->text())); } void CheckboxSetTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QCheckBox *handle = popGuiReceiver<QCheckBox *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->setText(text); } void CheckboxTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QCheckBox *handle = popGuiReceiver<QCheckBox *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->text())); } void CheckboxSetValueProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QCheckBox *handle = popGuiReceiver<QCheckBox *>(stack, type, proc, w, vm); int value = popInt(stack, proc, w, vm); handle->setCheckState((Qt::CheckState)value); } void CheckboxValueProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QCheckBox *handle = popGuiReceiver<QCheckBox *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newInt(handle->checkState())); } void RadioButtonSetTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QRadioButton *handle = popGuiReceiver<QRadioButton *>(stack, type, proc, w, vm); QString text = popString(stack, proc, w, vm); handle->setText(text); } void RadioButtonTextProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QRadioButton *handle = popGuiReceiver<QRadioButton *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newString(handle->text())); } void RadioButtonSetValueProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QRadioButton *handle = popGuiReceiver<QRadioButton *>(stack, type, proc, w, vm); bool value = popBool(stack, proc, w, vm); handle->setChecked(value); } void RadioButtonValueProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QRadioButton *handle = popGuiReceiver<QRadioButton *>(stack, type, proc, w, vm); stack.push(vm->GetAllocator().newBool(handle->isChecked())); } void ButtonGroupAddProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type, *type2; QButtonGroup *handle = popGuiReceiver<QButtonGroup *>(stack, type, proc, w, vm); verifyStackNotEmpty(stack, proc, vm); Value *btn = stack.top(); QAbstractButton *button = popGuiReceiver<QAbstractButton *>(stack, type2, proc, w, vm); if(!button) throw VMError(InternalError); button->setProperty("valueptr", QVariant::fromValue<void *>(btn)); int theId = ((ButtonGroupForeignClass *) type)->runningIdCount++; handle->addButton(button, theId); stack.push(vm->GetAllocator().newInt(theId)); } void ButtonGroupGetButtonProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { IClass *type; QButtonGroup *handle = popGuiReceiver<QButtonGroup *>(stack, type, proc, w, vm); int theId = popInt(stack, proc, w, vm); QAbstractButton *button = handle->button(theId); Value *btnObj = (Value *) button->property("valueptr").value<void *>(); stack.push(btnObj); } void ClassNewObjectProc(VOperandStack &stack, Process *proc, RunWindow *w, VM *vm) { Value *v = popValue(stack, proc, w, vm); IObject *theClassObj = unboxObj(v); IClass *theClass = dynamic_cast<IClass *>(theClassObj); if(theClass) { stack.push(vm->GetAllocator().newObject(theClass->newValue(&vm->GetAllocator()), theClass)); } else { throw VMError(InternalError); } } void setupChildren(QGridLayout *layout,Value *v, Reference *ref, QString label, int row, VM *vm) { QCheckBox *cb; QGroupBox *qf; QScrollArea *sa; Object *obj; QGridLayout *vb; QLineEdit *le; int subRow; VArray *arr; if(v->type == BuiltInTypes::IntType || v->type == BuiltInTypes::DoubleType || v->type == BuiltInTypes::LongType || v->type == BuiltInTypes::StringType) { layout->addWidget(new QLabel(label), row, 0); le = new QLineEdit(v->toString()); if(ref != NULL) { QObject::connect(le, SIGNAL(textChanged(QString)), new GUIEditWidgetHandler( ref, le, vm), SLOT(lineEditChanged())); } layout->addWidget(le, row, 1); } else if(v->type == BuiltInTypes::BoolType) { cb = new QCheckBox(); cb->setChecked(unboxBool(v)); if(ref != NULL) { QObject::connect(cb, SIGNAL(stateChanged(int)), new GUIEditWidgetHandler( ref, cb, vm), SLOT(checkboxChanged(int))); } layout->addWidget(new QLabel(label), row, 0); layout->addWidget(cb, row, 1); } else if(v->isObject()) { qf = new QGroupBox(label); layout->addWidget(qf, row, 0, 1, 2); obj = dynamic_cast<Object *>(unboxObj(v)); if(obj != NULL) { vb = new QGridLayout(); subRow = 0; for(QVector<QString>::iterator i = obj->slotNames.begin(); i!= obj->slotNames.end(); ++i) { setupChildren(vb, obj->_slots[*i], new FieldReference(obj, *i), *i, subRow++,vm); } qf->setLayout(vb); } } else if(v->type == BuiltInTypes::ArrayType) { sa = new QScrollArea(); vb = new QGridLayout(); layout->addWidget(sa, row, 0, 1, 2); arr = unboxArray(v); vb->addWidget(new QLabel(label), 0, 0, 1, 2); for(int i=0; i<arr->count(); i++) { setupChildren(vb, arr->Elements[i], new ArrayReference(arr, i),QString("%1").arg(i+1), i+1, vm); } sa->setLayout(vb); sa->adjustSize(); } } Value *editAndReturn(Value *v, RunWindow *w, VM *vm) { QDialog *dlg = new QDialog(w); dlg->setWindowTitle(VM::argumentErrors.get(ArgErr::Editing1, v->type->getName())); QVBoxLayout *ly = new QVBoxLayout(dlg); QFrame *frame = new QFrame(); QGridLayout *gl = new QGridLayout(); setupChildren(gl, v, NULL, "", 0, vm); frame->setLayout(gl); ly->addWidget(frame); QPushButton *ok = new QPushButton(VM::argumentErrors[ArgErr::Ok]); QPushButton *cancel = new QPushButton(VM::argumentErrors[ArgErr::Cancel]); ly->addWidget(ok); ly->addWidget(cancel); dlg->setLayout(ly); #ifndef ENGLISH_PL dlg->setLayoutDirection(Qt::RightToLeft); #endif dlg->connect(ok, SIGNAL(clicked()), dlg, SLOT(accept())); dlg->connect(cancel, SIGNAL(clicked()), dlg, SLOT(reject())); bool ret = dlg->exec()== QDialog::Accepted; v = vm->GetAllocator().newBool(ret); return v; }
32.398324
125
0.626588
mobadarah
13c9ea198c307d2022e1ff3d0e5f3797e3150574
550
cpp
C++
samples/snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocument.PreserveWhitespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocument.PreserveWhitespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocument.PreserveWhitespace Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <Snippet1> #using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; int main() { //Load XML data which includes white space, but ignore //any white space in the file. XmlDocument^ doc = gcnew XmlDocument; doc->PreserveWhitespace = false; doc->Load( "book.xml" ); //Save the document as is (no white space). Console::WriteLine( "Display the modified XML..." ); doc->PreserveWhitespace = true; doc->Save( Console::Out ); } // </Snippet1>
22
58
0.636364
hamarb123
13cb1f57f15f7fc9675cc13b4e8d934bb7121c62
7,934
cpp
C++
Firmware/or_firmware/ideas/ideas.cpp
razanskylab/Quadrature_Decoder_Board
d12b3d4c3254913a3005cdd44f546e1326324a30
[ "MIT" ]
null
null
null
Firmware/or_firmware/ideas/ideas.cpp
razanskylab/Quadrature_Decoder_Board
d12b3d4c3254913a3005cdd44f546e1326324a30
[ "MIT" ]
2
2020-10-25T16:15:04.000Z
2020-10-31T16:30:16.000Z
Firmware/or_firmware/ideas/ideas.cpp
razanskylab/Quadrature_Decoder_Board
d12b3d4c3254913a3005cdd44f546e1326324a30
[ "MIT" ]
null
null
null
#include "teensy_lib.h" // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void setup_io_pins() { for (uint8_t i=0; i<8; i++) { pinMode(pinTable[i],INPUT_PULLUP); } pinMode(HCTL_RST_PIN, OUTPUT); pinMode(HCTL_OE_PIN, OUTPUT); pinMode(HCTL_SEL_PIN, OUTPUT); pinMode(BUSY_LED, OUTPUT); pinMode(RANGE_LED, OUTPUT); pinMode(TRIGGER_LED, OUTPUT); pinMode(CALIB_LED, OUTPUT); pinMode(TRIG_OUT[0], OUTPUT); pinMode(TRIG_OUT[1], OUTPUT); pinMode(TRIG_OUT[2], OUTPUT); pinMode(HCTL_MANUAL_RESET_PIN, INPUT); pinMode(TRIG_COUNT_RESET, INPUT); digitalWriteFast(HCTL_RST_PIN, HIGH); digitalWriteFast(HCTL_OE_PIN, HIGH); digitalWriteFast(HCTL_SEL_PIN, HIGH); digitalWriteFast(BUSY_LED, LOW); digitalWriteFast(RANGE_LED, LOW); digitalWriteFast(CALIB_LED, LOW); digitalWriteFast(TRIGGER_LED, LOW); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void update_counter() { digitalWriteFast(HCTL_SEL_PIN, LOW); // select high bit digitalWriteFast(HCTL_OE_PIN, LOW); // start read WAIT_100_NS; // allow high bit to be stable ((unsigned char *)&posCounter)[1] = GPIOD_PDIR & 0xFF; // read msb digitalWriteFast(HCTL_SEL_PIN, HIGH); // select low bit // get msb, write directly to counter, also turns uint to int...lots of magic here // we do this after changing pin, as data now needs time to settle... // ((uint8_t *)&counter)[1] = msb; WAIT_100_NS; // allow high bit to be stable ((unsigned char *)&posCounter)[0] = GPIOD_PDIR & 0xFF; // read lsb // finish read out digitalWriteFast(HCTL_OE_PIN, HIGH); // digitalWriteFast(HCTL_SEL_PIN, HIGH); // might need to add delay here... // get lsb, write directly to counter, also turns uint to int...lots of magic here // ((uint8_t *)&counter)[0] = lsb; // if (posCounter == minusOne) // Serial.println("OVERFLOW WARN!"); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void trigger_ch(uint8_t channel) { trigPinState[channel] = !trigPinState[channel]; // invert, good old Urs trick ;-) digitalWriteFast(TRIG_OUT[channel], trigPinState[channel]); // select high bit triggerCounter[channel]++; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // reset counter chip values to zero void reset_hctl() { digitalWriteFast(HCTL_RST_PIN, LOW); // start read WAIT_60_NS; digitalWriteFast(HCTL_RST_PIN, HIGH); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% uint16_t serial_read_16bit() { serial_wait_next_command(); // wait for 2 bytes return Serial.read() + (Serial.read() << 8); // read a 16-bit number from 2 bytes } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% uint16_t serial_read_16bit_no_wait() { // same as serial_read_16bit but not checking for available bytes \ // used only where speed is critical return Serial.read() + (Serial.read() << 8); // read a 16-bit number from 2 bytes } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void serial_write_16bit(uint16_t writeData){ uint8_t outBuffer[2]; outBuffer[0] = writeData & 255; outBuffer[1] = (writeData >> 8) & 255; Serial.write(outBuffer, 2); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void serial_write_32bit(uint32_t writeData){ uint8_t outBuffer[4]; outBuffer[0] = writeData & 255; outBuffer[1] = (writeData >> 1*8) & 255; outBuffer[2] = (writeData >> 2*8) & 255; outBuffer[3] = (writeData >> 3*8) & 255; Serial.write(outBuffer, 4); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void serial_wait_next_command(){ // wait for 2 bytes to be available while(Serial.available() < 2){} } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void record_calibration_data(){ samplingPeriodCalib = serial_read_16bit(); for (uint16_t iPos=0; iPos<POS_DATA_ARRAY_SIZE; iPos++) { while((micros()-lastSamplingTime)<samplingPeriodCalib){} // wait for next meas point lastSamplingTime = micros(); // transfer current counter value from HCTL chip to teensy update_counter(); // get the current value of the position counter posDataArray[iPos] = posCounter; // use led to indicate we are calibrating calibLedState = ~calibLedState; digitalWriteFast(CALIB_LED, calibLedState); } digitalWriteFast(CALIB_LED, false); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void init_calibration_data(){ for (uint16_t iData=0; iData<POS_DATA_ARRAY_SIZE; iData++) { posDataArray[iData] = 0; } } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void send_calibration_data(){ nBytesCalib = serial_read_16bit(); posDataPtr = posDataArray; // reset pointer to the start for (uint16_t iPos = 0; iPos < nBytesCalib/2; iPos++) { serial_write_16bit(*posDataPtr); posDataPtr++; } } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void pos_based_triggering(){ uint16_t lastCount = 0; uint16_t diffCount = 0; init_calibration_data(); // set position to all zeros...we then fill part of it uint16_t arrayPos = 0; lowRange = serial_read_16bit(); // get range min upRange = serial_read_16bit(); // get range max stepSize = serial_read_16bit(); // get range max // get nTriggers? doTrigger = true; triggerCounter[2] = 0; // trigger counter for channel 2 bool inRange = 0; uint16_t range = upRange - lowRange; while(doTrigger) { update_counter(); // update current counter value (stored in posCounter) // UH: ich glaube da geht auch ein bitwise & inRange = (posCounter >= lowRange) && (posCounter <= upRange); if (inRange){ // we are in range again, trigger_ch(2); //send first trigger signal at border of ROI // if (arrayPos < POS_DATA_ARRAY_SIZE){ // posDataArray[arrayPos++] = posCounter; // FIXME just for debugging // } lastCount = posCounter; // save last position // digitalWriteFast(RANGE_LED, HIGH); // set the range led } // else{ // digitalWriteFast(RANGE_LED, LOW); // } while((posCounter >= lowRange) && (posCounter <= upRange)) { // check if still in range update_counter(); // update current counter value (stored in posCounter) // inRange = (posCounter >= lowRange) && (posCounter <= upRange); // inRange = ((posCounter - lowRange) < (upRange - lowCounter)); // abs can be improved using bitshifting // inline int32 Abs(int32 x) // { // int32 a = x >> 31; // return ((x ^ a) - a); // } if (abs(posCounter - lastCount) >= stepSize){ trigger_ch(2); // if (arrayPos < POS_DATA_ARRAY_SIZE){ // posDataArray[arrayPos++] = posCounter; // FIXME just for debugging // } lastCount = posCounter; // save last position } } // check if we got a new serial command to stop triggering // COMMAND_CHECK_INTERVALL is high, so we only check once in a while if((millis()-lastCommandCheck)>=COMMAND_CHECK_INTERVALL) { lastCommandCheck = millis(); if (Serial.available() >= 2) { currentCommand = serial_read_16bit_no_wait(); if (currentCommand == DISABLE_POS_TRIGGER) { doTrigger = false; } } } } // while triggering // send total trigger count over serial port to matlab serial_write_32bit(triggerCounter[2]); serial_write_16bit(DONE); // send the "ok, we are done" command send_calibration_data(); // serial_write_16bit(DONE); // send the "ok, we are done" command // enable trigger mode -> enter while loop // check every 500 ms if we still want to be in trigger mode }
33.618644
88
0.582052
razanskylab
13cd91429a6fa92865fb68a00bd30cce641f2a30
5,774
cpp
C++
FTSE/GenericPatcher.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
3
2019-10-05T15:51:12.000Z
2021-01-08T21:58:48.000Z
FTSE/GenericPatcher.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
2
2021-06-04T13:42:16.000Z
2021-07-27T10:38:38.000Z
FTSE/GenericPatcher.cpp
melindil/FTSE
c0b54194900ac45ce1ecc778d838a72d09278bab
[ "MIT" ]
2
2018-07-03T11:31:11.000Z
2021-06-16T21:05:38.000Z
/* MIT License Copyright (c) 2018 melindil 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 "GenericPatcher.h" #include "rapidjson/document.h" #include "rapidjson/istreamwrapper.h" #include "rapidjson/error/en.h" #include <stdlib.h> #include <Windows.h> #include "Version.h" #include <fstream> #include <sstream> GenericPatcher::ApplyType GenericPatcher::globals_[] = { // following entries keep pointer to weapon available for OnChanceToHitCalc {0x617911, {0x90}}, {0x61791e, {0x90}}, {0x617945, {0x90}}, {0x61796a, {0x90}}, {0x617a6e, {0x90}}, {0x617a8f, {0x90}}, {0x617aae,{0x90}}, {0x617ac1, {0x90}}, {0x617b0b, {0x90}}, {0x617b27, {0x90}}, }; GenericPatcher::GenericPatcher(Logger* log, std::string const& configname) : logger_(log), luaname_("ftse_base.lua") { ApplyDocument(configname); } void GenericPatcher::ApplyDocument(std::string const& configname) { try { std::ifstream infile(configname); if (!infile) { throw std::runtime_error(std::string("Could not open configuration file ") + configname); } rapidjson::IStreamWrapper isw(infile); rapidjson::Document doc; if (doc.ParseStream(isw).HasParseError()) { std::stringstream ss; ss << "JSON parse error (offset " << doc.GetErrorOffset() << "): " << rapidjson::GetParseError_En(doc.GetParseError()); throw std::runtime_error(ss.str()); } if (!doc.HasMember("patches") || !doc["patches"].IsArray()) { throw std::runtime_error("JSON document is missing the patches array element"); } if (doc.HasMember("lua")) { luaname_ = doc["lua"].GetString(); } for (auto itr = doc["patches"].Begin(); itr != doc["patches"].End(); itr++) { try { std::string patchname = (*itr)["name"].GetString(); PatchType& pt = patches_[patchname]; if (itr->HasMember("changes") && (*itr)["changes"].IsArray()) { pt.changes = ParseChanges(patchname, (*itr)["changes"]); } if (itr->HasMember("apply")) { std::string apply = (*itr)["apply"].GetString(); if (apply == "true" || apply == "True" || apply == "TRUE") { pt.apply = true; } else { pt.apply = false; } } } catch (std::exception& e) { *logger_ << e.what() << std::endl; } } if (doc.HasMember("custom-config")) { try { std::string name(doc["custom-config"].GetString()); ApplyDocument(name); } catch (std::exception& e) { *logger_ << e.what() << std::endl; } } } catch (std::exception& e) { *logger_ << e.what() << std::endl; } } std::string GenericPatcher::getLuaName() { return luaname_; } std::vector<GenericPatcher::ApplyType> GenericPatcher::ParseChanges( std::string const& patchname, rapidjson::Value const& val) { std::vector<ApplyType> ats; for (auto itr = val.Begin(); itr != val.End(); itr++) { ApplyType at; at.offset = std::stoul((*itr)["offset"].GetString(),nullptr, 16); std::string patch = (*itr)["patch"].GetString(); if (patch.length() % 2) { throw std::runtime_error("Patch \"" + patchname + "\" has a change with an odd number of hex digits. Skipping."); } at.patch = ConvertFromHex(patch); ats.push_back(at); } return ats; } std::vector<unsigned char> GenericPatcher::ConvertFromHex(std::string const& in) { std::vector<unsigned char> out(in.length() / 2); for (size_t i = 0 ; i < in.length(); i+=2) { std::string ch(in, i, 2); out[i / 2] = (unsigned char)(std::stoul(ch, nullptr, 16)); } return out; } GenericPatcher::~GenericPatcher() { } void GenericPatcher::apply() { for (auto patch : patches_) { if (patch.second.apply) { *logger_ << "Applying patch " << patch.first << std::endl; for (auto change : patch.second.changes) { try { apply_impl(change); } catch (std::exception& e) { *logger_ << e.what() << std::endl; } } } else { *logger_ << "Skipping patch " << patch.first << std::endl; } } for (auto change : globals_) { apply_impl(change); } ApplyType version_app; version_app.offset = 0x8aed98; char const* verstring = "1.27 + FTSE " FTSE_VERSION; char const** verloc = &verstring; version_app.patch.resize(4); memcpy(version_app.patch.data(), verloc, sizeof(char*)); apply_impl(version_app); } void GenericPatcher::apply_impl(GenericPatcher::ApplyType const& app) { DWORD old_protect = 0, bogus_protect = 0; if (!VirtualProtect((void*)(app.offset), app.patch.size(), PAGE_EXECUTE_READWRITE, &old_protect)) { std::stringstream ss; ss << "Could not protect memory address 0x" << std::hex << app.offset << ", skipping"; throw std::runtime_error(ss.str()); } memcpy((void*)(app.offset), app.patch.data(), app.patch.size()); VirtualProtect((void*)(app.offset), app.patch.size(), old_protect, &bogus_protect); }
25.436123
116
0.663665
melindil
13cdd59b5541a4979404d583295c43a6e54f437a
489
cpp
C++
book/cpp_templates/tmplbook/traits/issame.cpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/traits/issame.cpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/traits/issame.cpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
#include "issame.hpp" #include <iostream> template<typename T> void fooImpl(T, TrueType) { std::cout << "fooImpl(T,true) for int called\n"; } template<typename T> void fooImpl(T, FalseType) { std::cout << "fooImpl(T,false) for other type called\n"; } template<typename T> void foo(T t) { fooImpl(t, IsSameT<T,int>{}); // choose impl. depending on whether T is int } int main() { foo(42); // calls \TfooImpl(42, TrueType{}) foo(7.7); // calls \TfooImpl(42, FalseType{}) }
18.111111
78
0.654397
houruixiang
13d0f09f3ba3d762677475c6ae521a23e837b8e1
3,265
hpp
C++
src/scanner/scanner-input.hpp
aaron-michaux/giraffe
457b55d80f6d21616a5c40232c2f68ee9e2c8335
[ "MIT" ]
null
null
null
src/scanner/scanner-input.hpp
aaron-michaux/giraffe
457b55d80f6d21616a5c40232c2f68ee9e2c8335
[ "MIT" ]
null
null
null
src/scanner/scanner-input.hpp
aaron-michaux/giraffe
457b55d80f6d21616a5c40232c2f68ee9e2c8335
[ "MIT" ]
null
null
null
#pragma once #include <unistd.h> namespace giraffe { class ScannerInputInterface { public: virtual ~ScannerInputInterface() = default; /// How should this input be referred to? virtual string_view name() const noexcept = 0; /// Reads up to `max_size` bytes, placing them in `buffer`, returning amount virtual size_t read(char* buffer, size_t max_size) noexcept = 0; }; // -------------------------------------------------------------- read from FILE class FILE_ScannerInput final : public ScannerInputInterface { private: std::string name_ = ""s; FILE* fp_ = nullptr; bool interactive_ = false; // FALSE => reading block by block bool close_fp_ = false; void trace_stmt_() { TRACE(format( "input source = '{}', interactive = {}, close-fp = {}", name_, interactive_, close_fp_)); } public: FILE_ScannerInput(string_view name, bool interactive = false) noexcept(false) { name_ = name; fp_ = fopen(name.data(), "rb"); interactive_ = interactive; close_fp_ = true; if(fp_ == nullptr) throw std::runtime_error(format("could not open file '{}'", name)); // trace_stmt_(); } FILE_ScannerInput(string_view name, FILE* fp) : FILE_ScannerInput(name, fp, isatty(fileno(fp))) {} FILE_ScannerInput(string_view name, FILE* fp, bool interactive) : name_(begin(name), end(name)) , fp_(fp) , interactive_(interactive) { // trace_stmt_(); } ~FILE_ScannerInput() { if(close_fp_ && fp_ != nullptr) fclose(fp_); } string_view name() const noexcept override { return name_; } /// Reads up to `max_size` bytes, placing them in `buffer`, returning amount size_t read(char* buffer, size_t max_size) noexcept override { assert(max_size > 0); if(interactive_) { int c = getc_unlocked(fp_); return (c == EOF) ? 0 : (buffer[0] = char(c), 1); } return fread(buffer, 1, max_size, fp_); } }; // ---------------------------------------------------------- read from a string class StringScannerInput final : public ScannerInputInterface { private: std::string name_ = ""s; std::string buffer_ = ""s; size_t pos_ = 0; void trace_stmt_() { TRACE(format("input source = '{}', size = {}", name_, buffer_.size())); } public: StringScannerInput(string_view name, string_view buffer) : name_(begin(name), end(name)) , buffer_(begin(buffer), end(buffer)) { // trace_stmt_(); } StringScannerInput(string_view name, std::string&& buffer) : name_(begin(name), end(name)) , buffer_(std::move(buffer)) { // trace_stmt_(); } string_view name() const noexcept override { return name_; } /// Reads up to `max_size` bytes, placing them in `buffer`, returning amount size_t read(char* buffer, size_t max_size) noexcept override { assert(max_size > 0); assert(pos_ <= buffer_.size()); const size_t remainder = buffer_.size() - pos_; const size_t amount_read = std::min(remainder, max_size); memcpy(buffer, &buffer_[pos_], amount_read); pos_ += amount_read; return amount_read; } }; } // namespace giraffe
27.436975
99
0.600919
aaron-michaux
13d5d7c5f1969b0607a11091b16d5afe79451999
1,541
cpp
C++
examples/01-BasicVertexBuffer.cpp
dgavedissian/dgfx
cdb0b2f6cf9c2df5712ec49195549f40313860ea
[ "MIT" ]
3
2021-01-01T08:53:42.000Z
2022-01-29T18:55:34.000Z
examples/01-BasicVertexBuffer.cpp
dgavedissian/dgfx
cdb0b2f6cf9c2df5712ec49195549f40313860ea
[ "MIT" ]
null
null
null
examples/01-BasicVertexBuffer.cpp
dgavedissian/dgfx
cdb0b2f6cf9c2df5712ec49195549f40313860ea
[ "MIT" ]
1
2021-09-09T19:49:35.000Z
2021-09-09T19:49:35.000Z
/* * Dawn Graphics * Written by David Avedissian (c) 2017-2020 (git@dga.dev) */ #include "Common.h" class BasicVertexBuffer : public Example { public: VertexBufferHandle vb_; ProgramHandle program_; void start() override { // Load shaders. auto vs = util::loadShader(r, ShaderStage::Vertex, util::media("shaders/basic_colour.vert")); auto fs = util::loadShader(r, ShaderStage::Fragment, util::media("shaders/basic_colour.frag")); program_ = r.createProgram({vs, fs}); struct Vertex { float x; float y; u32 colour; }; Vertex vertices[] = { // Little-endian, so colours are 0xAABBGGRR. {0.0f, 0.5f, 0xff0000ff}, // Vertex 1: Red {-0.5f, -0.5f, 0xff00ff00}, // Vertex 2: Green {0.5f, -0.5f, 0xffff0000} // Vertex 3: Blue }; VertexDecl decl; decl.begin() .add(VertexDecl::Attribute::Position, 2, VertexDecl::AttributeType::Float) .add(VertexDecl::Attribute::Colour, 4, VertexDecl::AttributeType::Uint8, true) .end(); vb_ = r.createVertexBuffer(Memory(vertices, sizeof(vertices)), decl); } void render(float) override { r.setRenderQueueClear({0.0f, 0.0f, 0.2f}); r.setVertexBuffer(vb_); r.submit(program_, 3); } void stop() override { r.deleteProgram(program_); r.deleteVertexBuffer(vb_); } }; DEFINE_MAIN(BasicVertexBuffer);
29.634615
97
0.573653
dgavedissian
13df73b74d0d82429f4e3fc0a0e9925f98b2d67d
31,415
cpp
C++
src/server/frame/ipfilter.cpp
jvirkki/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
13
2015-10-09T05:59:20.000Z
2021-11-12T10:38:51.000Z
src/server/frame/ipfilter.cpp
JamesLinus/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
null
null
null
src/server/frame/ipfilter.cpp
JamesLinus/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
6
2016-05-23T10:53:29.000Z
2019-12-13T17:57:32.000Z
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the 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. */ /* * Description (ipfilter.c) * * This module supports access to a file containing IP host and * network specifications. These specifications are used to * accept or reject clients based on their IP address. */ #include "base/systems.h" #include "netsite.h" #include "nspr.h" #include "base/pblock.h" #include "base/objndx.h" #include "base/lexer.h" #include "frame/ipfilter.h" #include <assert.h> #include <fcntl.h> #include <ctype.h> #ifndef XP_WIN32 #include <netinet/in.h> #include <arpa/inet.h> #endif #include "base/daemon.h" #ifdef NOACL /* extern unsigned long inet_addr(char * ipastr); CKA: already defined somewhere else */ #define MYREADSIZE 1024 /* buffer size for file reads */ /* * Description (IPNode_t) * * This type describes an internal node in the radix tree. An internal * node has a link up the tree to its parent, and up to three links * down the tree to its descendants. Each internal node is used to * test a particular bit in a given IP address, and traverse down the * tree in a direction which depends on whether the bit is set, clear, * or masked out. The descendants of an internal node may be internal * nodes or leaf nodes (IPLeaf_t). */ /* Define indices of links in an IPNode_t */ #define IPN_CLEAR 0 /* link to node with ipn_bit clear */ #define IPN_SET 1 /* link to node with ipn_bit set */ #define IPN_MASKED 2 /* link to node with ipn_bit masked out */ #define IPN_NLINKS 3 /* number of links */ typedef struct IPNode_s IPNode_t; struct IPNode_s { char ipn_type; /* node type */ #define IPN_LEAF 0 /* leaf node */ #define IPN_NODE 1 /* internal node */ char ipn_bit; /* bit number (31-0) to test */ IPNode_t * ipn_parent; /* link to parent node */ IPNode_t * ipn_links[IPN_NLINKS]; }; /* Helper definitions */ #define ipn_clear ipn_links[IPN_CLEAR] #define ipn_set ipn_links[IPN_SET] #define ipn_masked ipn_links[IPN_MASKED] /* * Description (IPLeaf_t) * * This type describes a leaf node in the radix tree. A leaf node * contains an IP host or network address, and a network mask. A * given IP address matches a leaf node if the IP address, when masked * by ipl_netmask, equals ipl_ipaddr. */ typedef struct IPLeaf_s IPLeaf_t; struct IPLeaf_s { char ipl_type; /* see ipn_type in IPNode_t */ char ipl_disp; /* disposition of matching IP addresses */ #define IPL_ACCEPT 0 /* accept matching IP addresses */ #define IPL_REJECT 1 /* reject matching IP addresses */ IPAddr_t ipl_netmask; /* IP network mask */ IPAddr_t ipl_ipaddr; /* IP address of host or network */ }; typedef struct IPFilter_s IPFilter_t; struct IPFilter_s { char ipf_anchor[4]; /* "IPF" - ipfilter parameter value points here */ IPFilter_t * ipf_next; /* link to next filter */ char * ipf_acceptfile; /* name of ipaccept filter file */ char * ipf_rejectfile; /* name of ipreject filter file */ IPNode_t * ipf_tree; /* pointer to radix tree structure */ }; static IPFilter_t * filters = NULL; /* Handle for IP filter object index */ void * ipf_objndx = NULL; static char * classv[] = { " \t\r\f\013", /* class 0 - whitespace */ "\n", /* class 1 - newline */ ",", /* class 2 - comma */ ".", /* class 3 - period */ "0123456789", /* class 4 - digits */ /* class 5 - letters */ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", }; static int classc = sizeof(classv)/sizeof(char *); #define CCM_WS 0x1 /* whitespace */ #define CCM_NL 0x2 /* newline */ #define CCM_COMMA 0x4 /* comma */ #define CCM_PERIOD 0x8 /* period */ #define CCM_DIGIT 0x10 /* digits */ #define CCM_LETTER 0x20 /* letters */ static char * ip_errstr[] = { "insufficient memory", /* IPFERR_MALLOC -1 */ "file open error", /* IPFERR_FOPEN -2 */ "file I/O error", /* IPFERR_FILEIO -3 */ "duplicate filter specification", /* IPFERR_DUPSPEC -4 */ "internal error (bug)", /* IPFERR_INTERR -5 */ "syntax error in filter file", /* IPFERR_SYNTAX -6 */ "conflicting filter specification", /* IPFERR_CNFLICT -7 */ }; /* * Description (ip_filter_search) * * This function searches a specified subtree of the radix tree, * looking for the best match for a given IP address. * * Arguments: * * ipaddr - the IP host or network address value * root - the root node of the subtree to be searched * * Returns: * * A pointer to a matching leaf node is returned, if one is found. * Otherwise NULL is returned. */ NSAPI_PUBLIC IPLeaf_t * ip_filter_search(IPAddr_t ipaddr, IPNode_t * root) { IPLeaf_t * leaf; /* leaf node pointer */ IPAddr_t bitmask; /* bit mask for current node */ IPNode_t * ipn; /* current internal node */ IPNode_t * lastipn; /* last internal node seen in search */ IPNode_t * mipn; /* ipn_masked subtree root pointer */ lastipn = NULL; ipn = root; /* * The tree traversal first works down the tree, under the assumption * that all of the bits in the given IP address may be significant. * The internal nodes of the tree will cause particular bits of the * IP address to be tested, and the ipn_clear or ipn_set link to * a descendant followed accordingly. The internal nodes are arranged * in such a way that high-order bits are tested before low-order bits. * Usually some bits are skipped, as they are not needed to distinguish * the entries in the tree. * * At the bottom of the tree, a leaf node may be found, or the last * descendant link may be NULL. If a leaf node is found, it is * tested for a match against the given IP address. If it doesn't * match, or the link was NULL, backtracking begins, as described * below. * * Backtracking follows the ipn_parent links back up the tree from * the last internal node, looking for internal nodes with ipn_masked * descendants. The subtrees attached to these links are traversed * downward, as before, with the same processing at the bottom as * the first downward traversal. Following the ipn_masked links is * essentially examining the possibility that the IP address bit * associated with the internal node may be masked out by the * ipl_netmask in a leaf at the bottom of such a subtree. Since * the ipn_masked links are examined from the bottom of the tree * to the top, this looks at the low-order bits first. */ while (ipn != NULL) { /* * Work down the tree testing bits in the IP address indicated * by the internal nodes. Exit the loop when there are no more * internal nodes. */ while ((ipn != NULL) && (ipn->ipn_type == IPN_NODE)) { /* Save pointer to internal node */ lastipn = ipn; /* Get a mask for the bit this node tests */ bitmask = 1<<ipn->ipn_bit; /* Select link to follow for this IP address */ ipn = (bitmask & ipaddr) ? ipn->ipn_set : ipn->ipn_clear; } /* Did we end up with a non-NULL node pointer? */ if (ipn != NULL) { /* It must be a leaf node */ assert(ipn->ipn_type == IPN_LEAF); leaf = (IPLeaf_t *)ipn; /* Is it a matching leaf? */ if (leaf->ipl_ipaddr == (ipaddr & leaf->ipl_netmask)) { /* Yes, we are done */ return leaf; } } /* * Backtrack, starting at lastipn. Search each subtree * emanating from an ipn_masked link. Step up the tree * until the ipn_masked link of the node referenced by * "root" has been considered. */ for (ipn = lastipn; ipn != NULL; ipn = ipn->ipn_parent) { /* * Look for a node with a non-NULL masked link, but don't * go back to the node we just came from. */ if ((ipn->ipn_masked != NULL) && (ipn->ipn_masked != lastipn)) { /* Get the root of this subtree */ mipn = ipn->ipn_masked; /* If this is an internal node, start downward traversal */ if (mipn->ipn_type == IPN_NODE) { ipn = mipn; break; } /* Otherwise it's a leaf */ assert(mipn->ipn_type == IPN_LEAF); leaf = (IPLeaf_t *)mipn; /* Is it a matching leaf? */ if (leaf->ipl_ipaddr == (ipaddr & leaf->ipl_netmask)) { /* Yes, we are done */ return leaf; } } /* Don't consider nodes above the given root */ if (ipn == root) { /* No matching entry found */ return NULL; } lastipn = ipn; } } /* No matching entry found */ return NULL; } /* * Description (ip_filter_add) * * This function adds a new [IP address, netmask] entry to a * specified IP filter, along with an indication of whether matching * IP addresses are to be accepted or rejected. Duplicate entries, * that is entries with the same IP address and netmask, are not * permitted. * * Arguments: * * ipf - pointer to IPFilter_t structure * ipaddr - the IP host or network address value * netmask - the netmask associated with this IP address * disp - value for ipl_disp field of leaf * * Returns: * * Zero if successful. Otherwise an IPFERR_xxxx error code. */ NSAPI_PUBLIC int ip_filter_add(IPFilter_t * ipf, IPAddr_t ipaddr, IPAddr_t netmask, int disp) { IPNode_t * ipn; /* current node pointer */ IPNode_t * lastipn; /* last (lower) node pointer */ IPLeaf_t * leaf; /* leaf node pointer */ IPAddr_t bitmask; /* bit mask for current node */ int lastbit; /* number of last bit set in netmask */ int i; /* loop index */ lastipn = NULL; for (ipn = ipf->ipf_tree; (ipn != NULL) && (ipn->ipn_type == IPN_NODE); ) { /* Get a mask for the bit this node tests */ bitmask = 1<<ipn->ipn_bit; /* Save pointer to last internal node */ lastipn = ipn; /* Is this a bit we care about? */ if (bitmask & netmask) { /* Yes, get address of set or clear descendant pointer */ ipn = (bitmask & ipaddr) ? ipn->ipn_set : ipn->ipn_clear; } else { /* No, get the address of the masked descendant pointer */ ipn = ipn->ipn_masked; } } /* Did we end up at a leaf node? */ if (ipn == NULL) { /* * No, well, we need to find a leaf node if possible. The * reason is that we need an IP address and netmask to compare * to the IP address and netmask we're inserting. We know that * they're the same up to the bit tested by the lastipn node, * but we need to know the *highest* order bit that's different. * Any leaf node below lastipn will do. */ leaf = NULL; ipn = lastipn; while (ipn != NULL) { /* Look for any non-null child link of the current node */ for (i = 0; i < IPN_NLINKS; ++i) { if (ipn->ipn_links[i]) break; } /* * Fail search for leaf if no non-null child link found. * This should only happen on the root node of the tree * when the tree is empty. */ if (i >= IPN_NLINKS) { assert(ipn == ipf->ipf_tree); break; } /* Step to the child node */ ipn = ipn->ipn_links[i]; /* Is it a leaf? */ if (ipn->ipn_type == IPN_LEAF) { /* Yes, search is over */ leaf = (IPLeaf_t *)ipn; ipn = NULL; break; } } } else { /* Yes, loop terminated on a leaf node */ assert(ipn->ipn_type == IPN_LEAF); leaf = (IPLeaf_t *)ipn; /* Same IP address and netmask? */ if ((leaf->ipl_ipaddr == ipaddr) && (leaf->ipl_netmask == netmask)) { /* Yes, error if not same disp. Otherwise done. */ return (leaf->ipl_disp == disp) ? 0 : IPFERR_CNFLICT; } } /* Got a leaf yet? */ if (leaf != NULL) { /* Combine the IP address and netmask differences */ bitmask = (leaf->ipl_ipaddr ^ ipaddr) | (leaf->ipl_netmask ^ netmask); assert(bitmask != 0); /* Find the bit number of the first different bit */ for (lastbit = 31; (bitmask & 0x80000000) == 0; --lastbit, bitmask <<= 1) ; /* Generate a bit mask with just that bit */ bitmask = 1 << lastbit; /* * Go up the tree from lastipn, looking for an internal node * that tests lastbit. Stop if we get to a node that tests * a higher bit number first. */ for (ipn = lastipn, lastipn = (IPNode_t *)leaf; ipn != NULL; ipn = ipn->ipn_parent) { if (ipn->ipn_bit >= lastbit) { if (ipn->ipn_bit == lastbit) { /* Need to add a leaf off ipn node */ lastipn = NULL; } break; } lastipn = ipn; } assert(ipn != NULL); } else { /* Just hang a leaf off the lastipn node if no leaf */ ipn = lastipn; lastipn = NULL; lastbit = ipn->ipn_bit; } /* * If lastipn is not NULL at this point, the new leaf will hang * off an internal node inserted between the upper node, referenced * by ipn, and the lower node, referenced by lastipn. The lower * node may be an internal node or a leaf. */ if (lastipn != NULL) { IPNode_t * parent = ipn; /* parent of the new node */ assert((lastipn->ipn_type == IPN_LEAF) || (ipn == lastipn->ipn_parent)); /* Allocate space for the internal node */ ipn = (IPNode_t *)MALLOC(sizeof(IPNode_t)); if (ipn == NULL) { return IPFERR_MALLOC; } ipn->ipn_type = IPN_NODE; ipn->ipn_bit = lastbit; ipn->ipn_parent = parent; ipn->ipn_clear = NULL; ipn->ipn_set = NULL; ipn->ipn_masked = NULL; bitmask = 1 << lastbit; /* * The values in the leaf we found above determine which * descendant link of the new internal node will reference * the subtree that we just ascended. */ if (leaf->ipl_netmask & bitmask) { if (leaf->ipl_ipaddr & bitmask) { ipn->ipn_set = lastipn; } else { ipn->ipn_clear = lastipn; } } else { ipn->ipn_masked = lastipn; } /* Allocate space for the new leaf */ leaf = (IPLeaf_t *)MALLOC(sizeof(IPLeaf_t)); if (leaf == NULL) { FREE((void *)ipn); return IPFERR_MALLOC; } /* Insert internal node in tree */ /* First the downward link from the parent to the new node */ for (i = 0; i < IPN_NLINKS; ++i) { if (parent->ipn_links[i] == lastipn) { parent->ipn_links[i] = ipn; break; } } /* Then the upward link from the child (if it's not a leaf) */ if (lastipn->ipn_type == IPN_NODE) { lastipn->ipn_parent = ipn; } } else { /* Allocate space for a leaf node only */ leaf = (IPLeaf_t *)MALLOC(sizeof(IPLeaf_t)); if (leaf == NULL) { return IPFERR_MALLOC; } } /* Initialize the new leaf */ leaf->ipl_type = IPN_LEAF; leaf->ipl_disp = disp; leaf->ipl_ipaddr = ipaddr; leaf->ipl_netmask = netmask; /* * Select the appropriate descendant link of the internal node * and point it at the new leaf. */ bitmask = 1 << ipn->ipn_bit; if (bitmask & netmask) { if (bitmask & ipaddr) { assert(ipn->ipn_set == NULL); ipn->ipn_set = (IPNode_t *)leaf; } else { assert(ipn->ipn_clear == NULL); ipn->ipn_clear = (IPNode_t *)leaf; } } else { assert(ipn->ipn_masked == NULL); ipn->ipn_masked = (IPNode_t *)leaf; } /* Successful completion */ return 0; } /* Return error information in a IPFilterErr_t structure */ static void ip_filter_error(IPFilterErr_t * reterr, int errcode, int lineno, char * filename, char * errstr) { if (reterr != NULL) { reterr->errNo = errcode; reterr->lineno = lineno; reterr->filename = (filename) ? STRDUP(filename) : ""; if (errstr == NULL) { /* If no error string provided, try to supply one */ if ((errcode >= IPFERR_MIN) && (errcode <= IPFERR_MAX)) { errstr = ip_errstr[IPFERR_MAX-errcode]; } else errstr = "unknown error"; } reterr->errstr = errstr; } } /* Deallocate a IPFilter_t structure */ NSAPI_PUBLIC void ip_filter_destroy(void * ipfptr) { IPFilter_t * ipf = (IPFilter_t *)ipfptr; IPFilter_t **ipfp; IPNode_t * ipn; /* current node pointer */ IPNode_t * parent; /* parent node pointer */ int i; if (ipf != NULL) { /* Remove this filter from the list if it's there */ for (ipfp = &filters; *ipfp != NULL; ipfp = &(*ipfp)->ipf_next) { if (*ipfp == ipf) { *ipfp = ipf->ipf_next; break; } } if (ipf->ipf_acceptfile) { FREE((void *)ipf->ipf_acceptfile); } if (ipf->ipf_rejectfile) { FREE((void *)ipf->ipf_rejectfile); } /* Traverse tree, freeing nodes, except root */ for (parent = ipf->ipf_tree; parent != NULL; ) { /* Look for a link to a child node */ for (i = 0; i < IPN_NLINKS; ++i) { ipn = parent->ipn_links[i]; if (ipn != NULL) break; } /* Any children for the parent node? */ if (ipn == NULL) { /* No, if it's the root, we're done */ if (parent == ipf->ipf_tree) break; /* Otherwise back up the tree */ ipn = parent; parent = ipn->ipn_parent; /* Free the lower node */ FREE(ipn); continue; } /* * Found a child node for the current parent. * NULL out the downward link and check it out. */ parent->ipn_links[i] = NULL; /* Is it a leaf? */ if (ipn->ipn_type == IPN_LEAF) { /* Yes, free it */ FREE(ipn); continue; } /* No, step down the tree */ parent = ipn; } /* Free the IPFilter_t structure and the root IPNode_t */ FREE((void *)ipf); } } /* Variation of dns_filter_destroy() called by objndx at restart */ NSAPI_PUBLIC void ip_filter_decimate(void * ipfptr) { ip_filter_destroy(ipfptr); if (filters == NULL) { /* * The filter object index is about to go away. Reset * ipf_objndx so that we recreate it. */ ipf_objndx = NULL; } } NSAPI_PUBLIC IPFilter_t * ip_filter_new(char * acceptname, char * rejectname) { IPFilter_t * ipf; /* pointer to returned filter structure */ IPNode_t * ipn; /* pointer to initial node */ assert(sizeof(IPAddr_t) >= 4); ipf = (IPFilter_t *)MALLOC(sizeof(IPFilter_t) + sizeof(IPNode_t)); if (ipf) { strcpy(ipf->ipf_anchor, "IPF"); ipf->ipf_acceptfile = (acceptname) ? STRDUP(acceptname) : NULL; ipf->ipf_rejectfile = (rejectname) ? STRDUP(rejectname) : NULL; /* * Initialize a radix tree to filter IP addresses. The initial * tree contains only one internal node, for bit 31, with no * descendants. */ ipn = (IPNode_t *)(ipf + 1); ipn->ipn_type = IPN_NODE; ipn->ipn_bit = 31; ipn->ipn_parent = NULL; ipn->ipn_clear = NULL; ipn->ipn_set = NULL; ipn->ipn_masked = NULL; ipf->ipf_tree = ipn; } return ipf; } /* Helper routine for ip_filter_read, called from lexer */ static int read_more(LEXStream_t * lst) { PRFileDesc *fd = (PRFileDesc *)(lst->lst_strmid); int rlen; rlen = PR_Read(fd, lst->lst_buf, lst->lst_buflen); if (rlen < 0) { /* File I/O error */ return IPFERR_FILEIO; } lst->lst_len = rlen; return rlen; } /* * Description (ip_filter_read) * * This function reads and parses a IP filter file. Entries in * the file specify IP host or network addresses of clients. * Entries found in the file are entered into a filter structure, * with a value specified by the caller. * * Arguments: * * ipf - pointer to filter structure to receive info * filename - name of filter file to read * disp - value to be associated with filter entries * reterr - error information return pointer, or NULL */ NSAPI_PUBLIC int ip_filter_read(IPFilter_t * ipf, char * filename, int disp, IPFilterErr_t * reterr) { LEXStream_t * lst; /* input stream pointer */ void * chtab; /* character class table reference */ void * token; /* current token reference */ char * tokenstr; /* token string pointer */ IPAddr_t ipaddr; /* IP host or network address */ IPAddr_t netmask; /* IP network mask */ PRFileDesc *fd; int lineno = 0; int rv; fd = (PRFileDesc *)0; lst = NULL; chtab = NULL; token = NULL; /* XXX handle relative filename - set default directory */ /* Open the filter file */ fd = PR_Open(filename, O_RDONLY, 0); if (fd == 0) { ip_filter_error(reterr, IPFERR_FOPEN, 0, filename, NULL); return IPFERR_FOPEN; } /* Initialize a lexer stream for the file */ lst = lex_stream_create(read_more, (void *)fd, NULL, MYREADSIZE); if (lst == NULL) { ip_filter_error(reterr, IPFERR_MALLOC, 0, filename, NULL); rv = IPFERR_MALLOC; goto error_ret; } /* Initialize character classes for lexer processing */ rv = lex_class_create(classc, classv, &chtab); if (rv < 0) { goto error_ret; } rv = lex_token_new((pool_handle_t *)0, 24, 8, &token); if (rv < 0) { goto error_ret; } lineno = 1; /* Loop to read file */ for (;;) { /* Skip whitespace and commas, but not newline */ rv = lex_skip_over(lst, chtab, CCM_WS|CCM_COMMA); if (rv < 0) goto error_ret; /* Exit loop if EOF */ if (rv == 0) break; if (rv == '\n') { /* Keep count of lines as we're skipping whitespace */ ++lineno; (void)lex_next_char(lst, chtab, CCM_NL); continue; } /* Check for beginning of comment */ if (rv == '#') { /* Skip to a newline if so */ rv = lex_skip_to(lst, chtab, CCM_NL); if (rv < 0) break; continue; } /* Assume no netmask */ netmask = 0xffffffff; /* Initialize token for IP address */ rv = lex_token_start(token); /* Collect token including digits, letters, and periods */ rv = lex_scan_over(lst, chtab, (CCM_DIGIT|CCM_LETTER|CCM_PERIOD), token); if (rv < 0) goto error_ret; /* Get a pointer to the token string */ tokenstr = lex_token(token); /* A NULL pointer or an empty string is an error */ if (!tokenstr || !*tokenstr) { rv = IPFERR_SYNTAX; goto error_ret; } /* Convert IP address to binary */ ipaddr = inet_addr(tokenstr); if (ipaddr == (unsigned long)-1) { rv = IPFERR_SYNTAX; goto error_ret; } /* Skip whitespace */ rv = lex_skip_over(lst, chtab, CCM_WS); if (rv < 0) goto error_ret; /* If no digit, must not be a netmask */ if (!isdigit(rv)) goto add_entry; /* Initialize token for network mask */ rv = lex_token_start(token); /* Collect token including digits, letters, and periods */ rv = lex_scan_over(lst, chtab, (CCM_DIGIT|CCM_LETTER|CCM_PERIOD), token); if (rv < 0) goto error_ret; /* Get a pointer to the token string */ tokenstr = lex_token(token); /* A NULL pointer or an empty string is an error */ if (!tokenstr || !*tokenstr) { rv = IPFERR_SYNTAX; goto error_ret; } /* * Convert netmask to binary. Note 255.255.255.255 is not a * valid netmask. */ netmask = inet_addr(tokenstr); if (netmask == (unsigned long)-1) { rv = IPFERR_SYNTAX; goto error_ret; } add_entry: rv = ip_filter_add(ipf, ipaddr, netmask, disp); if (rv < 0) goto error_ret; } error_ret: if (fd >= 0) { PR_Close(fd); } if (lst) lex_stream_destroy(lst); if (chtab) lex_class_destroy(chtab); if (rv < 0) { ip_filter_error(reterr, rv, lineno, filename, NULL); } return rv; } /* * Description (ip_filter_setup) * * This function checks for "ipaccept" and "ipreject" parameter * definitions in a client parameter block. If one or both of * these are present, a IPFilter_t structure is created, and * through some questionable magic, a "ipfilter" parameter is * created to point it. This structure will subsequently be used * by ip_filter_check() to see if a client IP address matches any * of the filter specifications in the ipaccept and/or ipreject * files. * * Arguments: * * client - client parameter block pointer * reterr - pointer to structure for error info, or NULL * * Returns: * * If an error occurs, a negative error code (IPFERR_xxxxx) is * returned, and information about the error is stored in the * structure referenced by reterr, if any. If there is no error, * the return value is either one or zero, depending on whether * a filter is created or not, respectively. */ NSAPI_PUBLIC int ip_filter_setup(pblock * client, IPFilterErr_t * reterr) { char * acceptname; /* name of ipaccept file */ char * rejectname; /* name of ipreject file */ IPFilter_t * ipf; /* pointer to filter structure */ char * fname; /* name assigned to this filter */ pb_param * pp; /* "ipfilter" parameter pointer */ int rv; /* result value */ char namebuf[OBJNDXNAMLEN]; /* buffer for filter name */ /* "ipfilter" must not be defined by the user in any case */ pblock_remove("ipfilter", client); /* Get names of ipaccept and ipreject files, if any */ acceptname = pblock_findval("ipaccept", client); rejectname = pblock_findval("ipreject", client); /* If neither are specified, there's nothing to do */ if (!(acceptname || rejectname)) { return 0; } /* Initialize NSPR (assumes multiple PR_Init() calls ok) */ /* XXXMB can we get rid of this? */ PR_Init(PR_USER_THREAD, 1, 0); ipf = ip_filter_new(acceptname, rejectname); if (!ipf) { ip_filter_error(reterr, IPFERR_MALLOC, 0, (acceptname) ? acceptname : rejectname, NULL); rv = IPFERR_MALLOC; goto error_ret; } /* Is there a ipaccept file? */ if (ipf->ipf_acceptfile) { /* * Yes, parse the file, creating hash table entries for * the filter patterns. */ rv = ip_filter_read(ipf, ipf->ipf_acceptfile, IPL_ACCEPT, reterr); if (rv < 0) { ip_filter_destroy(ipf); goto error_ret; } } /* Is there a ipreject file? */ if (ipf->ipf_rejectfile) { /* * Yes, parse the file, creating hash table entries for * the filter patterns. */ rv = ip_filter_read(ipf, ipf->ipf_rejectfile, IPL_REJECT, reterr); if (rv < 0) { ip_filter_destroy(ipf); goto error_ret; } } /* Create the object index for IP filters if necessary */ if (ipf_objndx == NULL) { ipf_objndx = objndx_create(8, ip_filter_decimate); /* * Arrange for the object index and all the filters in it to * be cleaned up at restart. */ #if 0 daemon_atrestart(objndx_destroy, ipf_objndx); #endif } /* Register the filter in the object index */ fname = objndx_register(ipf_objndx, (void *)ipf, namebuf); if (fname == NULL) { ip_filter_destroy(ipf); ip_filter_error(reterr, IPFERR_MALLOC, 0, (acceptname) ? acceptname : rejectname, NULL); rv = IPFERR_MALLOC; goto error_ret; } /* Create a parameter for the client, ipfilter=<filter-name> */ pp = pblock_nvinsert("ipfilter", fname, client); if (pp == NULL) { ip_filter_destroy(ipf); ip_filter_error(reterr, IPFERR_MALLOC, 0, (acceptname) ? acceptname : rejectname, NULL); rv = IPFERR_MALLOC; goto error_ret; } /* Add this to the list of filters */ ipf->ipf_next = filters; filters = ipf; /* Indicate filter created */ return 1; error_ret: /* * Our assumption here is that our caller is just going to log our * error and keep going. Our caller may in fact get far enough * to make calls to dns_filter_check() for the current client, * in which case, we want ip_filter_check() to return an error * code to indicate that a filter was specified but not applied, * due to the current error condition. So we add a special * "ipfilter=?" parameter to the client, which ip_filter_check() * can recognize as a broken filter. */ pp = pblock_nvinsert("ipfilter", "?", client); return rv; } /* * Description (ip_filter_check) * * This function checks a client parameter block for a "ipfilter" * parameter. If present, its value will point to a IPFilter_t * structure, and the client's IP address will be checked against this * filter. * * Arguments: * * client - client parameter block pointer * cip - client IP address value * * Returns: * * -2 - there was a broken filter indication * (see "error_ret:" comments above) * -1 - there was a reject filter and the client was rejected, * or there was only an accept filter and it did not * accept the client * 0 - there was no filter present, or both filters were present * and neither matched the client * 1 - there was an accept filter and the client was accepted, * or there was only a reject filter and it did not * reject the client */ NSAPI_PUBLIC int ip_filter_check(pblock * client, unsigned long cip) { IPFilter_t * ipf; /* IP filter structure pointer */ char * fname; /* filter name */ IPLeaf_t * leaf; /* radix tree leaf pointer */ int disp = 0; /* return value */ fname = pblock_findval("ipfilter", client); if (fname == NULL) { /* No, nothing to do */ return 0; } /* Check for broken filter */ if (fname[0] == '?') { /* Yep, it's broke */ return -2; } /* Look up pointer to filter, using filter name */ ipf = (IPFilter_t *)objndx_lookup(ipf_objndx, fname); if (ipf != NULL) { /* Yes, look for a match on the client IP address */ leaf = ip_filter_search(cip, ipf->ipf_tree); if (leaf == NULL) { /* * There was no information for the client IP in the table. * If there is only a ipaccept file, but no ipreject file, * figure that the client should be rejected. On the other * hand, if there is only a ipreject file, but no ipaccept * file, figure that the client should be accepted. */ if (ipf->ipf_acceptfile != NULL) { /* Only an accept file, no reject file? */ if (ipf->ipf_rejectfile == NULL) { /* Reject client */ disp = -1; } } else if (ipf->ipf_rejectfile != NULL) { /* Accept client - no accept file, but reject file present */ disp = 1; } } else { disp = (leaf->ipl_disp == IPL_ACCEPT) ? 1 : -1; } } return disp; } #endif /* NOACL */
28.276328
89
0.641286
jvirkki
13e02daa0ce747eb0f3bf815d0d72948c9840267
675
hpp
C++
yazol_test/hpp/Utilities/Memory/TestStruct64.hpp
Meraz/yazol
caa0de3bd6ceb35c3e7e78f7807f3b32ea2c0bc5
[ "MIT" ]
2
2017-05-13T16:58:47.000Z
2017-06-11T15:55:20.000Z
UnitTest/Include/Utilities/Memory/TestStruct64.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
null
null
null
UnitTest/Include/Utilities/Memory/TestStruct64.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:06.000Z
2020-03-23T15:42:06.000Z
#pragma once #include <gtest/gtest.h> struct TestStruct64 { float f1 = 1; float f2 = f1 + f1; float f3 = f2 + f2; float f4 = f3 + f3; float f5 = f4 + f4; float f6 = f5 + f5; float f7 = f6 + f6; float f8 = f7 + f7; float f9 = f8 + f8; float f10 = f9 + f9; float f11 = f10 + f10; float f12 = f11 + f11; float f13 = f12 + f12; float f14 = f13 + f13; float f15 = f14 + f14; float f16 = f15 + f15; }; class TestStruct64Test : public testing::Test { public: TestStruct64Test() {} virtual ~TestStruct64Test() {} TestStruct64 testStruct; void SetUp() override {} void TearDown() override {} };
18.75
45
0.562963
Meraz
13e04c7138379bd352e4cf96701c44320e5266f5
1,584
cpp
C++
Testing/FlowGraphTesting.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
Testing/FlowGraphTesting.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
Testing/FlowGraphTesting.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. /************************************************************************* ------------------------------------------------------------------------- History: - 06:06:2009 Created by Federico Rebora *************************************************************************/ #include "StdAfx.h" #include "FlowGraphTesting.h" CryUnit::StringStream& operator << (CryUnit::StringStream& stringStream, const SInputPortConfig& portConfig) { stringStream << portConfig.name << ":" << portConfig.humanName; return stringStream; } namespace GameTesting { CFlowNodeTestingFacility::CFlowNodeTestingFacility( IFlowNode& nodeToTest, const unsigned int inputPortsCount ) : m_nodeToTest(nodeToTest) , m_inputData(0) { CRY_ASSERT(inputPortsCount > 0); SFlowNodeConfig flowNodeConfiguration; nodeToTest.GetConfiguration(flowNodeConfiguration); m_inputData = new TFlowInputData[inputPortsCount]; for (unsigned int inputIndex = 0; inputIndex < inputPortsCount; ++inputIndex) { const SInputPortConfig& inputPort = flowNodeConfiguration.pInputPorts[inputIndex]; const TFlowInputData& defaultData = inputPort.defaultData; m_inputData[inputIndex] = defaultData; } } CFlowNodeTestingFacility::~CFlowNodeTestingFacility() { delete[] m_inputData; m_inputData = 0; } void CFlowNodeTestingFacility::ProcessEvent( IFlowNode::EFlowEvent event ) { IFlowNode::SActivationInfo activationInformation(0, 0, 0, m_inputData); m_nodeToTest.ProcessEvent(event, &activationInformation); } }
31.68
139
0.66351
IvarJonsson
13e13ad5f9df4b47a1116195a510dba3ada4e849
2,874
cpp
C++
ENgine/Support/ImGuiHelper.cpp
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
13
2020-12-02T02:13:29.000Z
2022-03-11T06:14:54.000Z
ENgine/Support/ImGuiHelper.cpp
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
null
null
null
ENgine/Support/ImGuiHelper.cpp
ENgineE777/OakEngine
6890fc89a0e9d151e7a0bcc1c276c13594616e9a
[ "Zlib" ]
null
null
null
#include "ImGuiHelper.h" #include "Root/Files/Files.h" #include <filesystem> #include "Root/Root.h" namespace Oak::ImGuiHelper { ImVec4 Vec4ToImVec4(Math::Vector4 value) { return ImVec4(value.x, value.y, value.z, value.w); } Math::Vector4 ImVec4ToVec4(ImVec4 value) { return Math::Vector4(value.x, value.y, value.z, value.w); } void VerticalHorizontalPadding() { ImGui::Dummy(ImVec2(0.0f, 3.0f)); ImGui::Dummy(ImVec2(3.0f, 3.0f)); ImGui::SameLine(); } void HorizontalPadding() { ImGui::Dummy(ImVec2(3.0f, 3.0f)); ImGui::SameLine(); } bool InputString(const char* id, eastl::string& value) { struct Funcs { static int ResizeCallback(ImGuiInputTextCallbackData* data) { if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) { eastl::string* str = (eastl::string*)data->UserData; str->resize(data->BufSize + 1); data->Buf = str->begin(); } return 0; } }; return ImGui::InputText(id, value.begin(), (size_t)value.size() + 1, ImGuiInputTextFlags_CallbackResize, Funcs::ResizeCallback, (void*)&value); } bool InputCombobox(const char* id, int& index, eastl::vector<eastl::string>& names, eastl::string& namesList) { if (namesList.empty()) { int count = 0; for (int i = 0; i < names.size(); i++) { count += (int)names[i].size() + 1; } namesList.resize(count + 1); int index = 0; for (int i = 0; i < names.size(); i++) { int sz = (int)names[i].size() + 1; memcpy(&namesList[index], names[i].c_str(), sz); index += sz; } } return ImGui::Combo(id, &index, namesList.c_str()); } void GetAllStyles(eastl::vector<eastl::string>& names) { names.clear(); for (auto& entry : std::filesystem::directory_iterator("ENgine/editor/themes/")) { if (!entry.is_directory()) { names.push_back(entry.path().filename().string().c_str()); } } } void LoadStyle(const char* name) { ImGuiStyle& style = ImGui::GetStyle(); JsonReader reader; if (reader.ParseFile(StringUtils::PrintTemp("%s/ENgine/editor/themes/%s", std::filesystem::current_path().string().c_str(), name))) { if (reader.EnterBlock("colors")) { for (int i = 0; i < ImGuiCol_COUNT; i++) { auto color = ImVec4ToVec4(style.Colors[i]); reader.Read(ImGui::GetStyleColorName(i), color); style.Colors[i] = Vec4ToImVec4(color); } reader.LeaveBlock(); } } } void SaveStyle(const char* name) { ImGuiStyle& style = ImGui::GetStyle(); JsonWriter writer; if (writer.Start(StringUtils::PrintTemp("%s/ENgine/editor/themes/%s", std::filesystem::current_path().string().c_str(), name))) { writer.StartBlock("colors"); for (int i = 0; i < ImGuiCol_COUNT; i++) { auto color = ImVec4ToVec4(style.Colors[i]); writer.Write(ImGui::GetStyleColorName(i), color); } writer.FinishBlock(); } } }
21.938931
145
0.634656
ENgineE777
13e39628c9cc954562a6c4893815d9e714eed223
573
hpp
C++
Kernel/include/platform/x86_64/page_fault_interrupt_handler.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Kernel/include/platform/x86_64/page_fault_interrupt_handler.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Kernel/include/platform/x86_64/page_fault_interrupt_handler.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
#ifndef FLAPJACKOS_KERNEL_INCLUDE_PLATFORM_X86_64_PAGE_FAULT_INTERRUPT_HANDLER_HPP #define FLAPJACKOS_KERNEL_INCLUDE_PLATFORM_X86_64_PAGE_FAULT_INTERRUPT_HANDLER_HPP #include "generic_interrupt_handler.hpp" #include "interrupt_parameters.hpp" namespace x86_64 { class PageFaultInterruptHandler : public GenericInterruptHandler<InterruptParameters> { public: PageFaultInterruptHandler(); void int_handler(const InterruptParameters& params) override; }; } // namespace x86_64 #endif // FLAPJACKOS_KERNEL_INCLUDE_PLATFORM_X86_64_PAGE_FAULT_INTERRUPT_HANDLER_HPP
30.157895
87
0.86562
foxostro
13eb0edd6163e12728933ed90a8d82fb7b6ef503
985
cpp
C++
src/main/sendmail.cpp
ondra-novak/loginsrv
10043c26b2056767c0dab685001d925cbb1661c5
[ "MIT" ]
null
null
null
src/main/sendmail.cpp
ondra-novak/loginsrv
10043c26b2056767c0dab685001d925cbb1661c5
[ "MIT" ]
null
null
null
src/main/sendmail.cpp
ondra-novak/loginsrv
10043c26b2056767c0dab685001d925cbb1661c5
[ "MIT" ]
null
null
null
/* * sendmail.cpp * * Created on: 11. 3. 2020 * Author: ondra */ #include <regex> #include "sendmail.h" SendMail::SendMail(const std::string &sendmail_path):sendmail_path(sendmail_path) { } bool is_email_valid(const std::string& email) { const std::regex pattern ("[-a-zA-Z0-9.+_]+@[a-z0-9A-Z-]+(\\.[a-z0-9A-Z-]+)+"); return std::regex_match(email, pattern); } void SendMail::send(const std::string &recipient, const std::string &body) { if (!is_email_valid(recipient)) throw std::runtime_error("Recipient rejected: "+ recipient); std::string cmd = sendmail_path+" "+recipient; FILE *f = popen(cmd.c_str(),"w"); if (f == nullptr) throw std::runtime_error("Can't connect sendmail: " + cmd); if (fwrite(body.data(), body.size(), 1, f) != 1) { pclose(f); throw std::runtime_error("Failed to write body: " + cmd); } int res = pclose(f); if (res) throw std::runtime_error("Sendmail returned non-zero exit: " + cmd+ " - exit:" + std::to_string(res)); }
27.361111
104
0.650761
ondra-novak
13f12aa48930205d365af59691866cb3bd99ea52
7,324
cpp
C++
src/hssh/local_topological/area_detection/voronoi/search.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
6
2020-03-29T09:37:01.000Z
2022-01-20T08:56:31.000Z
src/hssh/local_topological/area_detection/voronoi/search.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
1
2021-03-05T08:00:50.000Z
2021-03-05T08:00:50.000Z
src/hssh/local_topological/area_detection/voronoi/search.cpp
h2ssh/Vulcan
cc46ec79fea43227d578bee39cb4129ad9bb1603
[ "MIT" ]
11
2019-05-13T00:04:38.000Z
2022-01-20T08:56:38.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file search.cpp * \author Collin Johnson * * Definition of find_path_along_skeleton function. */ #include <hssh/local_topological/area_detection/voronoi/search.h> #include <hssh/local_topological/area_detection/voronoi/voronoi_utils.h> #include <hssh/local_topological/voronoi_skeleton_grid.h> #include <utils/algorithm_ext.h> #include <boost/range/algorithm_ext.hpp> #include <boost/range/as_array.hpp> namespace vulcan { namespace hssh { using PredMap = CellToTypeMap<cell_t>; // maintain predecessors for extracting the path std::ostream& operator<<(std::ostream& out, const voronoi_path_t& path) { std::copy(path.cells.begin(), path.cells.end(), std::ostream_iterator<cell_t>(out, " ")); return out; } /* * astar_in_skeleton_grid finds a path from start until the goal condition is satisfied. The search will propagate to all * neighbors satisfying the mask. The GoalCondition is a functor with the signature: * * cond(cell, skeleton) * * and should return true or false depending on if the condition has been satisfied. */ template <class GoalCondition> voronoi_path_t astar_in_skeleton_grid(cell_t start, uint8_t mask, const VoronoiSkeletonGrid& skeleton, GoalCondition goal); voronoi_path_t extract_path_from_predecessors(cell_t goal, PredMap& predecessors, const VoronoiSkeletonGrid& skeleton); voronoi_path_t find_path_along_skeleton(cell_t start, cell_t goal, uint8_t mask, const VoronoiSkeletonGrid& skeleton) { assert(mask & (SKELETON_CELL_SKELETON | SKELETON_CELL_REDUCED_SKELETON)); voronoi_path_t startToSkeleton = path_to_skeleton(start, mask, skeleton); voronoi_path_t goalToSkeleton = path_to_skeleton(goal, mask, skeleton); std::reverse(goalToSkeleton.cells.begin(), goalToSkeleton.cells.end()); // reverse path to get skeleton to goal // If no path to the skeleton is found, then exit if(startToSkeleton.cells.empty()) { // std::cout << "ERROR: find_path_along_skeleton: Failed to find path from start cell to skeleton. Start:" // << start << '\n'; voronoi_path_t failed; failed.result = VoronoiPathResult::invalid_start; return failed; } if(goalToSkeleton.cells.empty()) { // std::cout << "ERROR: find_path_along_skeleton: Failed to find path from goal cell to skeleton. Goal:" // << goal << '\n'; voronoi_path_t failed; failed.result = VoronoiPathResult::invalid_goal; return failed; } // Run an A* search voronoi_path_t pathAlongSkeleton = astar_in_skeleton_grid( startToSkeleton.cells.back(), mask, skeleton, [&goalToSkeleton](cell_t cell, const VoronoiSkeletonGrid& skeleton) { return cell == goalToSkeleton.cells.front(); // find the cell along the skeleton leading to the goal }); if(pathAlongSkeleton.cells.empty()) { // std::cout << "ERROR: find_path_along_skeleton: Failed to find path along skeleton from " // << startToSkeleton.cells.back() << " to " << goalToSkeleton.cells.front() << '\n'; // // std::cout << "Start to skeleton:" << startToSkeleton << "\nSkeleton to goal:" << goalToSkeleton << '\n'; voronoi_path_t failed; failed.result = VoronoiPathResult::no_path_found; return failed; } // Concatenate the paths into one voronoi_path_t finalPath = startToSkeleton; boost::push_back(finalPath.cells, boost::as_array(pathAlongSkeleton.cells)); boost::push_back(finalPath.cells, boost::as_array(goalToSkeleton.cells)); utils::erase_unique(finalPath.cells); finalPath.length += pathAlongSkeleton.length + goalToSkeleton.length; finalPath.result = VoronoiPathResult::success; return finalPath; } voronoi_path_t path_to_skeleton(cell_t freeCell, uint8_t mask, const VoronoiSkeletonGrid& skeleton) { return astar_in_skeleton_grid(freeCell, SKELETON_CELL_FREE, // search through all free space for the path skeleton, [mask](cell_t cell, const VoronoiSkeletonGrid& skeleton) { return skeleton.getClassification(cell.x, cell.y) & mask; }); } template <class GoalCondition> voronoi_path_t astar_in_skeleton_grid(cell_t start, uint8_t mask, const VoronoiSkeletonGrid& skeleton, GoalCondition goalCond) { PredMap predecessors; predecessors[start] = start; // the start points to itself // If the start satisfies the goal, then we don't need to perform the full search if(goalCond(start, skeleton)) { return extract_path_from_predecessors(start, predecessors, skeleton); } NeighborArray neighbors; std::deque<cell_t> queue; queue.push_back(start); while(!queue.empty()) { cell_t active = queue.front(); queue.pop_front(); int numNeighbors = neighbor_cells_with_classification(active, mask, skeleton, FOUR_THEN_EIGHT_WAY, neighbors); for(int n = 0; n < numNeighbors; ++n) { cell_t next = neighbors[n]; // Ignore neighbor that already have predecessors because they have been reached already if(predecessors.find(next) != predecessors.end()) { continue; } predecessors[next] = active; queue.push_back(next); // As soon as the goal is found, then we're done if(goalCond(next, skeleton)) { return extract_path_from_predecessors(next, predecessors, skeleton); } } } // If we get to here, then the goal condition was never satisfied, so no path exists. voronoi_path_t failed; failed.result = VoronoiPathResult::no_path_found; return failed; } voronoi_path_t extract_path_from_predecessors(cell_t goal, PredMap& predecessors, const VoronoiSkeletonGrid& skeleton) { voronoi_path_t path; path.cells.push_back(goal); path.length = 0.0; path.result = VoronoiPathResult::success; while(predecessors[goal] != goal) { cell_t parent = predecessors[goal]; path.cells.push_back(parent); path.length += distance_between_points(utils::grid_point_to_global_point(goal, skeleton), utils::grid_point_to_global_point(parent, skeleton)); goal = parent; } std::reverse(path.cells.begin(), path.cells.end()); return path; } } // namespace hssh } // namespace vulcan
36.257426
120
0.643091
h2ssh
13f5359d3a8a6640411efc97a88bb2d19632530f
594
cpp
C++
Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.26.cpp
jesushilarioh/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
3
2019-02-02T16:59:48.000Z
2019-02-28T14:50:08.000Z
Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.26.cpp
jesushilariohernandez/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
null
null
null
Chapter-4-Making-Decisions/4.13 The Conditional Operator/Checkpoint/4.26.cpp
jesushilariohernandez/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
4
2020-04-10T17:22:17.000Z
2021-11-04T14:34:00.000Z
/******************************************************************** * * Checkpoint 4.26 * * What will the following program display? * * Jesus Hilario Hernandez * February 13, 2018 * ********************************************************************/ #include <iostream> using namespace std; int main() { const int UPPER = 8, LOWER = 2; int num1, num2, num3 = 12, num4 = 3; num1 = num3 < num4 ? UPPER : LOWER; // 2 num2 = num4 > UPPER ? num3 : LOWER; // 2 cout << num1 << " " << num2 << endl; // output: // 2 2 // Terminate program return 0; }
22
69
0.430976
jesushilarioh
13f635d6305300891e75cdb348712e302030e1cd
234
hpp
C++
src/abstractgl/api/opengl/shader/enum/vertex_shader.hpp
the-last-willy/abstractgl-api-opengl
8e6f5a93a85072a030aee2ea56fc2073f72df539
[ "MIT" ]
null
null
null
src/abstractgl/api/opengl/shader/enum/vertex_shader.hpp
the-last-willy/abstractgl-api-opengl
8e6f5a93a85072a030aee2ea56fc2073f72df539
[ "MIT" ]
null
null
null
src/abstractgl/api/opengl/shader/enum/vertex_shader.hpp
the-last-willy/abstractgl-api-opengl
8e6f5a93a85072a030aee2ea56fc2073f72df539
[ "MIT" ]
null
null
null
#pragma once namespace agl::api::opengl { struct EnumVertexShader { static constexpr auto _enum = GL_VERTEX_SHADER; constexpr operator GLenum() const noexcept { return _enum; } } constexpr VERTEX_SHADER; }
15.6
51
0.692308
the-last-willy
13fac257ffbd905374ccaa2b22242ca2d45e5a52
2,221
cpp
C++
test/test_psnr.cpp
bodhisatan/video_codec_evaluation
ad0560de0dd02732d1a0b7a24da988dfca9f5757
[ "Apache-2.0" ]
1
2021-06-18T01:57:56.000Z
2021-06-18T01:57:56.000Z
test/test_psnr.cpp
bodhisatan/video_codec_evaluation
ad0560de0dd02732d1a0b7a24da988dfca9f5757
[ "Apache-2.0" ]
null
null
null
test/test_psnr.cpp
bodhisatan/video_codec_evaluation
ad0560de0dd02732d1a0b7a24da988dfca9f5757
[ "Apache-2.0" ]
1
2020-09-01T02:55:27.000Z
2020-09-01T02:55:27.000Z
#include <iostream> #include <vector> #include <string> #include <boost/filesystem.hpp> #include <unistd.h> #include <stdio.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <stdint.h> #include <cstring> #include <cmath> #include <complex> #include <iomanip> #include <opencv2/opencv.hpp> #include <boost/lexical_cast.hpp> #include "../src/frame_drop_detect.h" #include "../src/psnr.h" #include "../src/matrixutils.h" int main(int argc, char *argv[]) { std::string f1 = "videoDB/t12.mp4"; std::string f2 = "videoDB/t13.mp4"; bool drop_frame_detect = true; YAML::Node conf = initPsnrConf(); if (!conf["psnr"] || !conf["psnr"]["ocrSrcDir"] || !conf["psnr"]["resDir"]) { std::cout << "解析psnr.yaml文件失败!" << std::endl; return 0; } std::string ocrSrcDir = conf["psnr"]["ocrSrcDir"].as<std::string>(); std::string resDir = conf["psnr"]["resDir"].as<std::string>(); // 获取原视频旋转角度 EVideoType t = getRotateAngle(f1); std::cout << "t: " << t << std::endl; // 获取分辨率信息和帧数信息 cv::Size r1 = GetVideoResolution(f1, t); std::cout << "( " << r1.width << "," << r1.height << " )" << std::endl; int oriWidth = r1.width; int oriHeight = r1.height; int frameNumber = GetVideoFrameNumber(f1); std::vector<int> v; v.clear(); if (drop_frame_detect) { // 清空目录 DeleteFiles(ocrSrcDir); // 获取帧号图像,存储在dir目录下 GetFrameLabel(f2, oriWidth, oriHeight, t, ocrSrcDir); // ocr检测, 丢帧信息存放在v中 CheckFrameDrop(ocrSrcDir, frameNumber, v); std::cout << "丢帧信息如下:" << std::endl; for (auto &i : v) { std::cout << i << " "; } std::cout << std::endl; } else { for (int i = 0; i < frameNumber; ++i) { v.emplace_back(1); } } std::string yuv1 = ""; std::string yuv2 = ""; if (!mp42yuv(f1, yuv1) || !mp42yuv(f2, yuv2)) { std::cout << "生成yuv文件错误." << std::endl; return 0; } psnrAndVisualize(yuv1, yuv2, YUV420, frameNumber, oriWidth, oriHeight, v, 1); std::cout << std::endl; std::cout << "计算psnr完毕" << std::endl; return 0; }
26.129412
81
0.568213
bodhisatan
cd04e81a5eaf7ba0415d368d5bec431b760529d3
2,361
cpp
C++
AmberEngine/src/AmberEngine/LowRenderer/Camera.cpp
maxbrundev/AmberEngine
e2d57fe673102c48ef34e32cca4c262bdde4e912
[ "MIT" ]
19
2018-09-28T20:35:25.000Z
2022-02-22T02:52:09.000Z
AmberEngine/src/AmberEngine/LowRenderer/Camera.cpp
maxbrundev/AmberEngine
e2d57fe673102c48ef34e32cca4c262bdde4e912
[ "MIT" ]
2
2018-10-01T21:55:37.000Z
2020-11-07T06:18:32.000Z
AmberEngine/src/AmberEngine/LowRenderer/Camera.cpp
maxbrundev/AmberEngine
e2d57fe673102c48ef34e32cca4c262bdde4e912
[ "MIT" ]
null
null
null
#include "Amberpch.h" #include "AmberEngine/LowRenderer/Camera.h" AmberEngine::LowRenderer::Camera::Camera() : m_clearColor(0.0f, 0.0f, 0.0f), m_yaw(-90.0f), m_pitch(0.0f), m_fov(45.0f), m_near(0.1f), m_far(100.0f) { UpdateCameraVectors(); } void AmberEngine::LowRenderer::Camera::UpdateCameraVectors() { glm::vec3 front; front.x = cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); front.y = sin(glm::radians(m_pitch)); front.z = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); m_forward = glm::normalize(front); m_right = glm::normalize(glm::cross(m_forward, glm::vec3(0.0f, 1.0f, 0.0f))); m_up = glm::normalize(glm::cross(m_right, m_forward)); } void AmberEngine::LowRenderer::Camera::CalculateMatrices(uint16_t p_windowWidth, uint16_t p_windowHeight, const glm::vec3& p_position) { CalculateViewMatrix(p_position, m_up); CalculateProjectionMatrix(p_windowWidth, p_windowHeight); } glm::mat4& AmberEngine::LowRenderer::Camera::GetViewMatrix() { return m_viewMatrix; } glm::mat4& AmberEngine::LowRenderer::Camera::GetProjectionMatrix() { return m_projectionMatrix; } const glm::vec3& AmberEngine::LowRenderer::Camera::GetForward() const { return m_forward; } const glm::vec3& AmberEngine::LowRenderer::Camera::GetRight() const { return m_right; } const glm::vec3& AmberEngine::LowRenderer::Camera::GetUp() const { return m_up; } void AmberEngine::LowRenderer::Camera::SetFov(float p_value) { m_fov = p_value; } void AmberEngine::LowRenderer::Camera::SetClearColor(const glm::vec3& p_clearColor) { m_clearColor = p_clearColor; } float& AmberEngine::LowRenderer::Camera::GetCameraFov() { return m_fov; } float& AmberEngine::LowRenderer::Camera::GetYaw() { return m_yaw; } float& AmberEngine::LowRenderer::Camera::GetPitch() { return m_pitch; } const glm::vec3& AmberEngine::LowRenderer::Camera::GetClearColor() const { return m_clearColor; } void AmberEngine::LowRenderer::Camera::CalculateViewMatrix(const glm::vec3& p_position, const glm::vec3& p_up) { m_viewMatrix = glm::lookAt(p_position, p_position + m_forward, p_up); } void AmberEngine::LowRenderer::Camera::CalculateProjectionMatrix(uint16_t p_windowWidth, uint16_t p_windowHeight) { if(p_windowHeight > 0) { m_projectionMatrix = glm::perspective(glm::radians(m_fov), p_windowWidth / static_cast<float>(p_windowHeight), m_near, m_far); } }
24.091837
135
0.745023
maxbrundev
cd08b7a711d58d9b9f425678acc6e90f3699a8cb
3,246
cpp
C++
3rd_party/zpp-1.0-alpha/Util.cpp
julienlopez/Eu4SaveAnalyzer
ab888a28a68b06889afd5c2de6c20798e1c3b5bc
[ "MIT" ]
null
null
null
3rd_party/zpp-1.0-alpha/Util.cpp
julienlopez/Eu4SaveAnalyzer
ab888a28a68b06889afd5c2de6c20798e1c3b5bc
[ "MIT" ]
null
null
null
3rd_party/zpp-1.0-alpha/Util.cpp
julienlopez/Eu4SaveAnalyzer
ab888a28a68b06889afd5c2de6c20798e1c3b5bc
[ "MIT" ]
null
null
null
/* ** ** $id:$ ** ** File: util.cpp -- utility functions for ZPP library. ** ** Copyright (C) 1999 Michael Cuddy, Fen's Ende Software. All Rights Reserved ** modifications Copyright (C) 2000-2003 Eero Pajarre ** ** check http://zpp-library.sourceforge.net for latest version ** ** 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. ** ** Change Log ** ---------- ** $Log: Util.cpp,v $ ** Revision 1.2 2003/06/22 19:24:02 epajarre ** Integrated all changes by me, testing still to be done ** ** Revision 1.1.1.1 2003/06/21 19:09:37 epajarre ** Initial import. (0.2) version) ** ** */ #ifdef _WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif /* _WINDOWS */ #if _MSC_VER <= 1200 #pragma warning ( disable : 4786 ) #endif /* _MSC_VER */ #include <list> #include <string> using namespace std; /* ** This function is used by the function zppZipArchive::openAll() to ** enumerate files in a directory. ** ** This implementation is for win32; other operating systems will need to ** add their own implementations. */ #ifdef _WINDOWS typedef list<string> stringList; stringList *enumerateDir(const string &wildPath, bool fullPath) { HANDLE h; WIN32_FIND_DATA findData; stringList *fileList = new stringList; string path; DWORD rc; int sep = wildPath.find_last_of("/\\"); if (sep == -1) { path = ""; } else { path = wildPath.substr(0,sep); } h = FindFirstFile(wildPath.c_str(), &findData); if (h == INVALID_HANDLE_VALUE) { rc = GetLastError(); //cout << "Find first fails." << endl; return 0; } //if (fullPath) { // fileList->push_back( path + "\\" + (string) findData.cFileName); //} else { // fileList->push_back ( (string) findData.cFileName ); //} do { if (fullPath) { string fname = path + findData.cFileName; fileList->push_back( fname ); } else { string fname(findData.cFileName); fileList->push_back ( fname ); } } while (FindNextFile(h, &findData)); rc = GetLastError(); FindClose(h); // neither of these errors is fatal. if (rc == ERROR_NO_MORE_FILES || rc == ERROR_FILE_NOT_FOUND) return fileList; // damn, some kind of error. delete fileList; return 0; } #endif /* _WINDOWS */
27.74359
81
0.687924
julienlopez
cd0c3faf602121db4fa82b346f58b88b6ebdc44a
160
cpp
C++
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/HW3_10(Stack Linked List)/main(13).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/HW3_10(Stack Linked List)/main(13).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/HW3_10(Stack Linked List)/main(13).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
#include"StackType.h" #include"StackType.cpp" using namespace std; int main() { ReadString(ifile); InfixToPostfixCon(); Print(); getchar(); return 0; }
10.666667
23
0.69375
diptu
998117e96e2aa0ef31cd5a6af8898d06c3638056
4,546
cpp
C++
Code.v05-00/src/Core/Vortex.cpp
MIT-LAE/APCEMM
2954bca64ec1c13552830d467d404dbe627ef71a
[ "MIT" ]
2
2022-03-21T20:49:37.000Z
2022-03-22T17:25:31.000Z
Code.v05-00/src/Core/Vortex.cpp
MIT-LAE/APCEMM
2954bca64ec1c13552830d467d404dbe627ef71a
[ "MIT" ]
null
null
null
Code.v05-00/src/Core/Vortex.cpp
MIT-LAE/APCEMM
2954bca64ec1c13552830d467d404dbe627ef71a
[ "MIT" ]
1
2022-03-21T20:50:50.000Z
2022-03-21T20:50:50.000Z
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* */ /* Aircraft Plume Chemistry, Emission and Microphysics Model */ /* (APCEMM) */ /* */ /* Vortex Program File */ /* */ /* Author : Thibaud M. Fritz */ /* Time : 7/26/2018 */ /* File : Vortex.cpp */ /* */ /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "Core/Vortex.hpp" Vortex::Vortex( ) { /* Default Constructor */ } /* End of Vortex::Vortex */ Vortex::Vortex( RealDouble temperature_K, RealDouble pressure_Pa, \ RealDouble N_BV, RealDouble span, RealDouble mass, \ RealDouble vFlight ) { /* This function uses a parametric model to estimate the initial depth, * width and maximum and mean downward displacements, delta_zw_ and * delta_z1_. * * The parametrization is taken from: * Schumann, U. "A contrail cirrus prediction model." Geoscientific Model Development 5.3 (2012): 543-580. * * INPUT: * - temperature_K: ambient temperature expressed in K * - pressure_Pa : ambient pressure expressed in Pa * - N_BV : Brunt-Väisala frequency expressed in s^-1 * - span : aircraft span in m * - mass : aircraft mass in kg * - vFlight : aircraft velocity in m/s * * The function computes: * - b_ : wake vortex separation in m * - gamma_ : initial circulation in m^2/s * - t_ : effective time scale in s * - w_ : initial velocity scale in m/s * - eps_star_: normalized dissipation rate * - delta_zw_: maximum sinking in m * - delta_z1_: initial sinking in m * - D1 : initial contrail depth in m * */ /* Constructor */ RealDouble rho = pressure_Pa / ( temperature_K * physConst::R_Air ); /* Wake vortex separation, [ m ] */ b_ = physConst::PI * span / 4; /* Initial circulation, [ m ^ 2 / s ] */ gamma_ = 4 * mass * physConst::g / ( physConst::PI * span * rho * vFlight ); /* Effective time scale, [ s ] */ t_ = 2 * physConst::PI * b_ * b_ / gamma_; /* Initial velocity scale, [ m / s ] */ w_ = gamma_ / ( 2 * physConst::PI * b_ ); /* Normalized dissipation rate, [ - ] */ eps_star_ = pow( physConst::EPSILON * b_, RealDouble(1.0/3.0) ) / w_; if ( N_BV <= 0 ) { std::cout << "In Vortex::Vortex: Brunt-Vaisala frequency takes negative value, N_BV = " << N_BV << " [s^-1]\n"; N_BV = 1.3E-02; } /* Allocate input to class */ N_BV_ = N_BV; if ( N_BV_ * t_ >= N_BVt_threshold ) { /* Strongly stratified conditions */ delta_zw_ = 1.49 * w_ / N_BV_; } else if ( eps_star_ < eps_threshold ) { /* Weakly stratified conditions */ delta_zw_ = b_ * ( 1.88 + 7.68 * ( 1.0 - 4.07 * eps_star_ + 5.67 * eps_star_ * eps_star_ ) * ( 0.79 - N_BV_ * t_ )); } else { std::cout << "In Vortex::Vortex:: Neither N_BV * t >= " << N_BVt_threshold << " nor eps* < " << eps_threshold << " are valid\n"; std::cout << "Setting delta_zw to " << delta_zw_default << "\n"; delta_zw_ = delta_zw_default; } delta_z1_ = Cz1 * delta_zw_; D_1_ = CD_0 * delta_zw_; } /* End of Vortex::Vortex */ Vortex::~Vortex( ) { /* Destructor */ } /* End of Vortex::~Vortex */ Vortex::Vortex( const Vortex &v ) { N_BV_ = v.N_BV_; b_ = v.b_; gamma_ = v.gamma_; t_ = v.t_; w_ = v.w_; eps_star_ = v.eps_star_; delta_zw_ = v.delta_zw_; delta_z1_ = v.delta_z1_; D_1_ = v.D_1_; } /* End of Vortex::Vortex */ Vortex& Vortex::operator=( const Vortex &v ) { if ( &v == this ) return *this; N_BV_ = v.N_BV_; b_ = v.b_; gamma_ = v.gamma_; t_ = v.t_; w_ = v.w_; eps_star_ = v.eps_star_; delta_zw_ = v.delta_zw_; delta_z1_ = v.delta_z1_; D_1_ = v.D_1_; return *this; } /* End of Vortex::operator= */ /* End of Vortex.cpp */
31.136986
136
0.476023
MIT-LAE
9981fcdfd217a037ef4bbc8c246c5d3e1f0b4481
1,915
hpp
C++
meta/for_each.hpp
monocle-ai/putils
49298d3ab1f07934923d599db0036ad90f233a34
[ "MIT" ]
null
null
null
meta/for_each.hpp
monocle-ai/putils
49298d3ab1f07934923d599db0036ad90f233a34
[ "MIT" ]
5
2020-07-30T21:23:04.000Z
2020-07-31T23:32:47.000Z
meta/for_each.hpp
monocle-ai/putils
49298d3ab1f07934923d599db0036ad90f233a34
[ "MIT" ]
3
2020-07-29T22:14:56.000Z
2020-07-30T17:32:49.000Z
#pragma once #include "type.hpp" #include "fwd.hpp" #define putils_macro_comma , namespace putils { // For each `T` in `Types` call `f(putils::meta::type<T>)` // `T` can then be recovered by using putils_wrapped_type // For instance: // ``` // putils::for_each_type<int, double>([](auto && t) { // using T = putils_wrapped_type(t); // std::cout << typeid(T).name() << std::endl; // }); // ``` // Will print something similar to: // int // double template<typename ...Types, typename Func> void for_each_type(Func && f); // For each `e` element in `tuple`, call `f(e)` // For instance: // ``` // std::tuple<int, std::string, int> t(42, "test", 1); // putils::tuple_for_each(t, [](auto &attr) { // std::cout << attr << std::endl; // }); // ``` // Will print // 42 // test // 1 // template<typename F, typename ...Args> void tuple_for_each(std::tuple<Args...> & tuple, F && f); template<typename F, typename ...Args> void tuple_for_each(const std::tuple<Args...> & tuple, F && f); // Implementation details template<typename ...Types, typename Func> void for_each_type(Func && f) { tuple_for_each(std::tuple<putils::meta::type<Types>...>(), FWD(f)); } namespace detail { template<typename F, typename Tuple, size_t ...Is> void tuple_for_each(F && f, Tuple && tuple, std::index_sequence<Is...>) { (f(std::get<Is>(tuple)), ...); } } template<typename F, typename ...Args> void tuple_for_each(std::tuple<Args...> & tuple, F && f) { detail::tuple_for_each(std::forward<F>(f), tuple, std::index_sequence_for<Args...>()); } template<typename F, typename ...Args> void tuple_for_each(const std::tuple<Args...> & tuple, F && f) { detail::tuple_for_each(std::forward<F>(f), tuple, std::index_sequence_for<Args...>()); } }
27.753623
94
0.579634
monocle-ai
99830468b7d11b6e03399a723f25af0009430872
36,555
cpp
C++
perf/perf_dynamic_table.cpp
matthewbeckler/nkit
5d1cfc7b38617c46dd35055d2917f2f74b969bec
[ "Apache-2.0" ]
1
2020-02-07T11:56:21.000Z
2020-02-07T11:56:21.000Z
perf/perf_dynamic_table.cpp
matthewbeckler/nkit
5d1cfc7b38617c46dd35055d2917f2f74b969bec
[ "Apache-2.0" ]
null
null
null
perf/perf_dynamic_table.cpp
matthewbeckler/nkit
5d1cfc7b38617c46dd35055d2917f2f74b969bec
[ "Apache-2.0" ]
1
2019-10-30T19:51:31.000Z
2019-10-30T19:51:31.000Z
/* Copyright 2010-2014 Boris T. Darchiev (boris.darchiev@gmail.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdio.h> //#include <valgrind/callgrind.h> #include <algorithm> #include <iomanip> #include <sqlite3.h> #include <csv_parser.h> #include <nkit/test.h> #include "nkit/dynamic_json.h" #include <nkit/logger_brief.h> #include <nkit/detail/ref_count_ptr.h> using namespace nkit; namespace nkit { namespace detail { std::string __PROGRAMM_DIR; } } const std::string & PROGRAMM_DIR_ = nkit::detail::__PROGRAMM_DIR; #if defined(NKIT_POSIX_PLATFORM) char path_delimiter_ = '/'; #elif defined(NKIT_WINNT_PLATFORM) char path_delimiter_ = '\\'; #else # error "Unknown platform" #endif //------------------------------------------------------------------------------ bool run_write_statement(sqlite3 * db, const std::string & st, std::string * error = NULL) { char * _error = NULL; int rc = sqlite3_exec(db, st.c_str(), NULL, NULL, &_error); if (rc != SQLITE_OK || _error != NULL) { if (_error != NULL) { if (error) *error = _error; sqlite3_free(_error); } else *error = "ERROR while executing '" + st + ";"; return false; } return true; } //------------------------------------------------------------------------------ class SqliteTransaction; class SqliteTable; class SqliteMemoryDb { friend class SqliteTransaction; friend class SqliteTable; public: typedef detail::ref_count_ptr<SqliteMemoryDb> Ptr; static Ptr Create(std::string * error) { sqlite3 * db; int rc = sqlite3_open(":memory:", &db); if (rc) return Ptr(); if (!run_write_statement(db, "PRAGMA synchronous = OFF", error)) return Ptr(); if (!run_write_statement(db, "PRAGMA journal_mode = MEMORY", error)) return Ptr(); return Ptr(new SqliteMemoryDb(db)); } ~SqliteMemoryDb() { sqlite3_close(db_); db_ = NULL; } detail::ref_count_ptr<SqliteTransaction> CreateTransaction(std::string * error); detail::ref_count_ptr<SqliteTable> CreateTable(const std::string & name, const std::string & columns_def, std::string * error); detail::ref_count_ptr<SqliteTable> CreateTable(const std::string & name, const Dynamic & src, std::string * error); private: SqliteMemoryDb(sqlite3 * db) : db_(db) {} private: sqlite3 * db_; }; //------------------------------------------------------------------------------ struct TypeMapping { std::string sqlite_column_type_; std::string dynamic_type_; }; static const TypeMapping sqlite3_type_to_dynamic_type[] = { {"text", "STRING"} , {"primary", "UNSIGNED_INTEGER"} , {"unsigned", "UNSIGNED_INTEGER"} , {"int", "INTEGER"} , {"real", "FLOAT"} , {"double", "FLOAT"} , {"float", "FLOAT"} , {"boolean", "BOOL"} , {"datetime", "DATE_TIME"} , {"", ""} }; static const TypeMapping dynamic_type_to_sqlite3_type[] = { {"TEXT", "STRING"} , {"UNSIGNED", "UNSIGNED_INTEGER"} , {"INT", "INTEGER"} , {"DOUBLE", "FLOAT"} , {"BOOLEAN", "BOOL"} , {"DATETIME", "DATE_TIME"} , {"", ""} }; const std::string & get_sqlite3_type_by_dynamic_type(const std::string & type) { size_t i = 0; while (!dynamic_type_to_sqlite3_type[i].dynamic_type_.empty()) { if (dynamic_type_to_sqlite3_type[i].dynamic_type_ == type) return dynamic_type_to_sqlite3_type[i].sqlite_column_type_; i++; } return dynamic_type_to_sqlite3_type[0].sqlite_column_type_; } class SqliteTable { friend class SqliteMemoryDb; public: typedef detail::ref_count_ptr<SqliteTable> Ptr; public: ~SqliteTable() {} Dynamic Group(const std::string & aggr_def, const std::string & _group_def, std::string * error) { data_of_current_select_ = Dynamic(); data_types_of_current_select_.clear(); std::string group_def; std::string order_def; if (_group_def.find('-') != _group_def.npos) { StringVector group_def_list, order_def_list; simple_split(_group_def, ",", &group_def_list); size_t size = group_def_list.size(); for (size_t i=0; i<size; ++i) { if (group_def_list[i][0] == '-') { group_def_list[i].erase(0, 1); order_def_list.push_back(group_def_list[i] + " DESC"); } else order_def_list.push_back(group_def_list[i] + " ASC"); } join(group_def_list, ", ", "", "", &group_def); join(order_def_list, ", ", "", "", &order_def); } else group_def = _group_def; char *_error; std::string sql("SELECT " + group_def + ", " + aggr_def + " FROM " + name_ + " GROUP BY " + group_def); if (!order_def.empty()) sql += " ORDER BY " + order_def; //CINFO(sql); int rc = sqlite3_exec(db_->db_, sql.c_str(), callback, this, &_error); if( rc != SQLITE_OK ) { if (error) *error = _error; sqlite3_free(_error); return Dynamic(); } return data_of_current_select_; } operator Dynamic() { data_of_current_select_ = Dynamic(); data_types_of_current_select_.clear(); char *_error; std::string select_from("SELECT * FROM "); int rc = sqlite3_exec(db_->db_, (select_from + name_).c_str(), callback, this, &_error); if( rc != SQLITE_OK ) { sqlite3_free(_error); return Dynamic(); } return data_of_current_select_; } bool InsertRow(const StringVector & values, std::string * error) { if (insert_row_values_.capacity() < insert_row_values_.size()) insert_row_values_.reserve(insert_row_values_.size()); insert_row_values_.clear(); join(values, ", ", "\"", "\"", &insert_row_values_); const std::string stmt = insert_row_begin_ + insert_row_values_ + ");"; //CINFO(stmt); return run_write_statement(db_->db_, stmt.c_str(), error); } bool CreateIndex(const std::string & name, const std::string & index_columns, std::string * error) { if (name.empty()) { if (error) *error = "Empty index name"; return false; } if (index_columns.empty()) { if (error) *error = "Empty columns definition for index '" + name + "'"; return false; } StringVector columns; nkit::simple_split(index_columns, ",", &columns); std::string sql; join(columns, ", ", "", "", &sql); std::string stmt = "CREATE INDEX " + name + " ON " + name_ + " (" + sql + ");"; return run_write_statement(db_->db_, stmt.c_str(), error); } private: static Ptr Create(SqliteMemoryDb * db, const std::string & name, const Dynamic & src, std::string * error); static Ptr Create(SqliteMemoryDb * db, const std::string & name, const std::string & columns_def, std::string * error) { if (name.empty()) { if (error) *error = "Empty table name"; return Ptr(); } if (columns_def.empty()) { if (error) *error = "Empty columns definition"; return Ptr(); } StringVector _columns; StringVector column_names, column_types, column_defs; nkit::simple_split(columns_def, ",", &_columns); StringVector::const_iterator it = _columns.begin(), end = _columns.end(); for (; it != end; ++it) { std::string column_name, column_type; nkit::simple_split(*it, ":", &column_name, &column_type); if (column_type.empty()) column_type = "TEXT"; column_names.push_back(column_name); column_types.push_back(column_type); } std::string sql_defs; join_pairs(column_names, column_types, " ", ", ", "", "", &sql_defs); if (!run_write_statement(db->db_, "CREATE TABLE IF NOT EXISTS " + name + " (" + sql_defs + ");", error)) return Ptr(); return Ptr(new SqliteTable(db, name, column_names, column_types)); } SqliteTable(SqliteMemoryDb * db, const std::string & name, const StringVector & column_names, const StringVector & column_types) : db_(db) , name_(name) , column_names_(column_names) , column_types_(column_types) { std::string column_names_sql; join(column_names_, ", ", "", "", &column_names_sql); insert_row_begin_ = "INSERT INTO " + name_ + "(" + column_names_sql + ") VALUES ("; } std::string GetColumnTypeByName(const std::string & name, uint64_t * dynamic_type) const { static std::string COUNT_("COUNT(*)"); static std::string MAX_("MAX("); static std::string MIN_("MIN("); static std::string SUM_("SUM("); for (size_t i=0; i < column_names_.size(); ++i) { if (stristr(name, COUNT_) == 0) { *dynamic_type = detail::UNSIGNED_INTEGER; return detail::dynamic_type_to_string(*dynamic_type); } std::string column_name; size_t begin = stristr(name, MAX_); if (begin != std::string::npos) { begin += MAX_.size(); size_t end = name.find(')', begin); column_name = name.substr(begin, end - begin); } if (column_name.empty()) { size_t begin = stristr(name, MIN_); if (begin != std::string::npos) { begin += MIN_.size(); size_t end = name.find(')', begin); column_name = name.substr(begin, end - begin); } } if (column_name.empty()) { size_t begin = stristr(name, SUM_); if (begin != std::string::npos) { begin += SUM_.size(); size_t end = name.find(')', begin); column_name = name.substr(begin, end - begin); } } if (column_name.empty()) column_name = name; if (column_names_[i] == column_name) { const std::string & sqlite_type = column_types_[i]; size_t tmi = 0; while (!sqlite3_type_to_dynamic_type[tmi].sqlite_column_type_.empty()) { if (stristr(sqlite_type, sqlite3_type_to_dynamic_type[tmi].sqlite_column_type_) != std::string::npos) { *dynamic_type = detail::string_to_dynamic_type( sqlite3_type_to_dynamic_type[tmi].dynamic_type_); return sqlite3_type_to_dynamic_type[tmi].dynamic_type_; } ++tmi; } } } *dynamic_type = detail::STRING; return detail::dynamic_type_to_string(*dynamic_type); } static int callback(void * _self, int argc, char **argv, char **column_names) { std::string error; SqliteTable * self = static_cast<SqliteTable *>(_self); if (unlikely(self->data_of_current_select_.IsUndef())) { StringVector table_def_list; detail::DynamicTypeVector data_types_of_current_select; for (int i = 0; i < argc; ++i) { std::string name = column_names[i]; uint64_t dynamic_type; std::string type = self->GetColumnTypeByName(name, &dynamic_type); data_types_of_current_select.push_back(dynamic_type); table_def_list.push_back(name + ":" + type); } std::string table_def; join(table_def_list, ",", "", "", &table_def); //std::cout << table_def << '\n'; self->data_of_current_select_ = Dynamic::Table(table_def, &error); if (self->data_of_current_select_.IsUndef()) return 1; self->data_types_of_current_select_ = data_types_of_current_select; } DynamicVector row; for(int i=0; i<argc; i++) { Dynamic cell; const char * value = argv[i]; if (likely(value)) { switch (self->data_types_of_current_select_[i]) { case detail::INTEGER: cell = Dynamic(static_cast<int64_t>(NKIT_STRTOLL(value, NULL, 10))); break; case detail::UNSIGNED_INTEGER: cell = Dynamic::UInt64( static_cast<uint64_t>(NKIT_STRTOULL(value, NULL, 10))); break; case detail::FLOAT: cell = Dynamic(std::strtod(value, NULL)); break; case detail::BOOL: cell = Dynamic(NKIT_STRTOLL(value, NULL, 10) != 0); break; case detail::DATE_TIME: cell = Dynamic::DateTimeFromTimestamp(NKIT_STRTOULL(value, NULL, 10)); break; default: cell = Dynamic(value); break; } } row.push_back(cell); } return self->data_of_current_select_.AppendRow(row) ? 0 : 1; } private: SqliteMemoryDb * db_; std::string name_; StringVector column_names_; StringVector column_types_; std::string insert_row_begin_; std::string insert_row_values_; Dynamic data_of_current_select_; detail::DynamicTypeVector data_types_of_current_select_; }; //------------------------------------------------------------------------------ class SqliteTransaction { friend class SqliteMemoryDb; public: typedef detail::ref_count_ptr<SqliteTransaction> Ptr; public: ~SqliteTransaction() { Commit(); } bool Commit(std::string * error = NULL) { if (commited_) return true; commited_ = true; return run_write_statement(db_->db_, "END TRANSACTION", error); } private: static Ptr Create(SqliteMemoryDb * db, std::string * error) { if (!run_write_statement(db->db_, "BEGIN TRANSACTION", error)) return Ptr(); return Ptr(new SqliteTransaction(db)); } SqliteTransaction(SqliteMemoryDb * db) : db_(db) , commited_(false) {} private: SqliteMemoryDb * db_; bool commited_; }; //------------------------------------------------------------------------------ detail::ref_count_ptr<SqliteTransaction> SqliteMemoryDb::CreateTransaction( std::string * error) { return SqliteTransaction::Create(this, error); } detail::ref_count_ptr<SqliteTable> SqliteMemoryDb::CreateTable( const std::string & name, const std::string & columns_def, std::string * error) { return SqliteTable::Create(this, name, columns_def, error); } detail::ref_count_ptr<SqliteTable> SqliteMemoryDb::CreateTable( const std::string & name, const Dynamic & src, std::string * error) { return SqliteTable::Create(this, name, src, error); } detail::ref_count_ptr<SqliteTable> SqliteTable::Create(SqliteMemoryDb * db, const std::string & name, const Dynamic & src, std::string * error) { StringVector column_names = src.GetColumnNames(); StringVector column_types = src.GetColumnTypes(); StringVector::iterator it = column_types.begin(), end = column_types.end(); for (; it != end; ++it) it->assign(get_sqlite3_type_by_dynamic_type(*it)); column_names.insert(column_names.begin(), "k"); column_types.insert(column_types.begin(), "INTEGER PRIMARY KEY"); std::string sql_defs; join_pairs(column_names, column_types, " ", ", ", "", "", &sql_defs); if (!run_write_statement(db->db_, "CREATE TABLE IF NOT EXISTS " + name + " (" + sql_defs + ");", error)) return Ptr(); Ptr dst(new SqliteTable(db, name, column_names, column_types)); SqliteTransaction::Ptr tr = db->CreateTransaction(error); if (!tr) return Ptr(); size_t width = src.width(); size_t k(0); Dynamic::TableIterator row = src.begin_t(), tend = src.end_t(); for (; row != tend; ++row) { StringVector srow; srow.push_back(string_cast(k++)); for (size_t c = 0; c < width; ++c) srow.push_back(row[c].GetString()); if (!dst->InsertRow(srow, error)) return Ptr(); } if (!tr->Commit(error)) return Ptr(); return dst; } //------------------------------------------------------------------------------ const size_t ITER_SIZE = 2000000; const size_t FACTOR = ITER_SIZE / 40; static int rnumbers[ITER_SIZE]; //------------------------------------------------------------------------------ void Init() { #ifdef NKIT_WINNT srand ((unsigned int)time(NULL)); #else srand (time(NULL)); #endif for (size_t i = 0; i < ITER_SIZE; i++) rnumbers[i] = rand() % FACTOR + 1; } //------------------------------------------------------------------------------ #define METRIC(expr_, duration) \ do \ {\ TimeMeter tm; \ tm.Start(); \ { expr_; } \ tm.Stop(); \ *duration = tm.GetTotal(); \ } while(0) //-------------------------------------------------------------------------- void GetMinusPlusPermutations(size_t count, StringList * minus_plus_permutatins) { minus_plus_permutatins->push_back(std::string(count, ' ')); for (size_t i = 1; i < count; ++i) { std::string signes(i, '-'); signes.append(count - i, ' '); std::sort(signes.begin(), signes.end()); do { minus_plus_permutatins->push_back(signes); } while (std::next_permutation(signes.begin(), signes.end())); } minus_plus_permutatins->push_back(std::string(count, '-')); } void GetIndexCombinations(const StringVector & fields, StringVector * combinations) { uint64_t count = 0; UniqueCombinationGenerator<std::string> ucgen(fields); while (true) { StringSet combination; if (!ucgen.GetNext(&combination)) break; Dynamic tmp = Dynamic::List(combination); StringVector permutation; tmp.SaveTo(&permutation); std::sort(permutation.begin(), permutation.end()); do { StringList minus_plus_permutatins; GetMinusPlusPermutations(combination.size(), &minus_plus_permutatins); StringList::const_iterator it = minus_plus_permutatins.begin(), end = minus_plus_permutatins.end(); for (; it != end; ++it) { count++; std::string joined; join_pairs(*it, permutation, "", ",", "", "", &joined); combinations->push_back(joined); } } while (std::next_permutation(permutation.begin(), permutation.end())); } } /* void PrepareData(std::vector<StringVector> * rows) { std::string error; std::string filename = PROGRAMM_DIR_ + "../../data/CrimeStatebyState.csv"; //+ "../../data/CrimeStatebyStateSmall.csv"; std::ifstream file(filename.c_str()); NKIT_TEST_ASSERT(file.good()); size_t c = 1; CSVIterator _row(file); CSVIterator end; if (_row != end) ++_row; for (; _row != end; ++_row) { StringVector & row = *_row; row.insert(row.begin(), string_cast(c++)); std::string s = row[4] + "-12-31 00:00:00"; Dynamic dt = Dynamic::DateTimeFromDefault(s, &error); NKIT_TEST_ASSERT_WITH_TEXT(dt, error); row.push_back(string_cast(dt.timestamp())); rows->push_back(row); } std::random_shuffle(rows->begin(), rows->end()); } */ const size_t REPEAT_COUNT = 10000; const size_t ARRAY_SIZE = 5; const size_t TOTAL = REPEAT_COUNT * ARRAY_SIZE; template <typename T> void populate(const T src[ARRAY_SIZE], DynamicVector * vv) { for (size_t i1 = 0; i1 < ARRAY_SIZE; ++i1) { for (size_t i2 = 0; i2 < REPEAT_COUNT; ++i2) vv->push_back(Dynamic(src[i1])); } } void populate(const uint64_t src[ARRAY_SIZE], DynamicVector * vv) { for (size_t i1 = 0; i1 < ARRAY_SIZE; ++i1) { for (size_t i2 = 0; i2 < REPEAT_COUNT; ++i2) vv->push_back(Dynamic::UInt64(src[i1])); } } void shift(size_t offset, DynamicVector * vv) { assert(offset < vv->size()); DynamicVector tmp(vv->size(), Dynamic()); std::copy(vv->begin() + (vv->size() - offset), vv->end(), tmp.begin()); std::copy(vv->begin(), vv->begin() + (vv->size() - offset), tmp.begin() + offset); *vv = tmp; } Dynamic PrepareData() { std::string error; const char * browser[ARRAY_SIZE] = { "chrome", "opera", "firefox", "safari", "ie"}; DynamicVector browsers; populate(browser, &browsers); size_t offset = 0; shift(++offset, &browsers); const char * os[ARRAY_SIZE] = { "Windows", "MacOS", "Ubuntu", "Debian", "iOS"}; DynamicVector oses; populate(os, &oses); shift(++offset, &oses); const int64_t year[ARRAY_SIZE] = { 2014, 2013, 2012, 2011, 2010}; DynamicVector years; populate(year, &years); shift(++offset, &years); const double rate[ARRAY_SIZE] = { 0.1, 0.2, 0.3, 0.4, 0.5}; DynamicVector rates; populate(rate, &rates); shift(++offset, &rates); const int64_t likes[ARRAY_SIZE] = { MAX_INT64_VALUE - 1, MAX_INT64_VALUE - 2, MAX_INT64_VALUE - 3, MAX_INT64_VALUE - 4, MAX_INT64_VALUE - 5}; DynamicVector likess; populate(likes, &likess); shift(++offset, &likess); const bool flag[ARRAY_SIZE] = { true, false, true, false, true}; DynamicVector flags; populate(flag, &flags); shift(++offset, &flags); std::vector<DynamicVector> rows; for (size_t i = 0; i < TOTAL; ++i) { DynamicVector row; row.push_back(browsers[i]); row.push_back(oses[i]); row.push_back(years[i]); row.push_back(rates[i]); row.push_back(likess[i]); row.push_back(flags[i]); rows.push_back(row); } std::random_shuffle(rows.begin(), rows.end()); Dynamic table = Dynamic::Table("browser:STRING, os:STRING, year:INTEGER," "rate:FLOAT, likes:INTEGER, flag:BOOL", &error); for (size_t i = 0; i < TOTAL; ++i) table.AppendRow(rows[i]); return table; } void TestGroup(Dynamic dynamic_table, SqliteTable::Ptr sqlite_table, const std::string & index_def) { CINFO(index_def); TimeMeter tm; std::string error; std::string aggr_def("COUNT, MIN(flag), MAX(likes), SUM(year)"); //----------------------------------------------- // grouping dynamic table by builder GroupedTableBuilder::Ptr builder = Dynamic::CreateGroupedTableBuilder( "browser:STRING, os:STRING, year:INTEGER," "rate:FLOAT, likes:INTEGER, flag:BOOL", index_def, aggr_def, &error); NKIT_TEST_ASSERT_WITH_TEXT(builder, error); size_t count = dynamic_table.height(); size_t width = dynamic_table.width(); DynamicVector row(width); tm.Start(); for (size_t i = 0; i < count; ++i) { for (size_t c = 0; c < width; ++c) row[c] = dynamic_table.GetCellValue(i, c); NKIT_TEST_ASSERT(builder->InsertRow(row)); } Dynamic grouped_by_builder = builder->GetResult(); tm.Stop(); NKIT_TEST_ASSERT(grouped_by_builder.IsTable()); double grouped_by_builder_time = tm.GetTotal(); tm.Clear(); //----------------------------------------------- // grouping dynamic table by method Group() tm.Start(); //CALLGRIND_START_INSTRUMENTATION; Dynamic grouped_table = dynamic_table.Group(index_def, aggr_def, &error); //CALLGRIND_STOP_INSTRUMENTATION; tm.Stop(); NKIT_TEST_ASSERT_WITH_TEXT(grouped_table.IsTable(), error); double dynamic_group_time = tm.GetTotal(); tm.Clear(); if (grouped_by_builder != grouped_table) { CINFO("-----------------------------------------------------"); CINFO(grouped_table); CINFO("-----------------------------------------------------"); CINFO(grouped_by_builder); NKIT_TEST_ASSERT(false); } //----------------------------------------------- // grouping sqlite3 table tm.Start(); Dynamic sqlite_grouped_table = sqlite_table->Group( "COUNT(*), MIN(flag), MAX(likes), SUM(year)", index_def, &error); tm.Stop(); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_grouped_table.IsTable(), error); if (sqlite_grouped_table != grouped_table) { CINFO("-----------------------------------------------------"); CINFO(grouped_table); CINFO("-----------------------------------------------------"); CINFO(sqlite_grouped_table); NKIT_TEST_ASSERT(false); } double sqlite3_group_time = tm.GetTotal(); tm.Clear(); if (dynamic_table.height() > grouped_table.height()) { std::cout << "builder/method: " << grouped_by_builder_time / dynamic_group_time << '\n'; std::cout << "Sqlite/Dynamic: " << sqlite3_group_time / dynamic_group_time << '\n'; std::cout << "Factor: " << std::setprecision(2) << dynamic_table.height() / grouped_table.height() << '\n'; //NKIT_TEST_ASSERT(sqlite3_group_time / dynamic_group_time > 1.0); } } _NKIT_TEST_CASE(TestGroupBuilder) { std::string error; Dynamic dynamic_table = PrepareData(); std::string index_def("browser,os"); std::string aggr_def("COUNT, MIN(flag), MAX(likes), SUM(year)"); GroupedTableBuilder::Ptr builder = Dynamic::CreateGroupedTableBuilder( "browser:STRING, os:STRING, year:INTEGER," "rate:FLOAT, likes:INTEGER, flag:BOOL", index_def, aggr_def, &error); size_t count = dynamic_table.height(); size_t width = dynamic_table.width(); DynamicVector row(width); for (size_t i = 0; i < count; ++i) { for (size_t c = 0; c < width; ++c) row[c] = dynamic_table.GetCellValue(i, c); NKIT_TEST_ASSERT(builder->InsertRow(row)); } Dynamic grouped_by_builder = builder->GetResult(); Dynamic grouped_by_method = dynamic_table.Group(index_def, aggr_def, &error); NKIT_TEST_ASSERT_WITH_TEXT(grouped_by_method.IsTable(), error); NKIT_TEST_ASSERT(grouped_by_builder = grouped_by_method); } _NKIT_TEST_CASE(TestCompare) { std::string error; detail::IndexKey k1, k2; //0, 1, 1960, 1960, //0, 1, 2005, 2005, //more k1.key_[0].i64_ = 0; k1.key_[1].i64_ = 1; k1.key_[2].ui64_ = 1960; k1.key_[3].i64_ = 1960; k1.size_ = 4; k2.key_[0].i64_ = 0; k2.key_[1].i64_ = 1; k2.key_[2].ui64_ = 2005; k2.key_[3].i64_ = 2005; k2.size_ = 4; StringVector mask; mask.push_back("1"); mask.push_back("1"); mask.push_back("-2"); mask.push_back("1"); nkit::detail::IndexCompare compare; NKIT_TEST_ASSERT_WITH_TEXT( nkit::detail::GetComparator(mask, &compare, &error), error); compare(k1, k2); return; } /* _NKIT_TEST_CASE(TestIndex) { std::string error; typedef std::map<detail::IndexKey, SizeVector, detail::IndexCompare const> IndexMap; StringVector mask; mask.push_back("1"); mask.push_back("1"); mask.push_back("-2"); mask.push_back("1"); nkit::detail::IndexCompare compare; NKIT_TEST_ASSERT_WITH_TEXT( nkit::detail::GetComparator(mask, &compare, &error), error); IndexMap index_map(compare); Dynamic dt1960(1960,1,1,0,0,0); Dynamic dt1962(1962,1,1,0,0,0); Dynamic dt2005(2005,1,1,0,0,0); Dynamic dt1971(1971,1,1,0,0,0); dt1960 = Dynamic::UInt64(1960); dt1962 = Dynamic::UInt64(1962); dt2005 = Dynamic::UInt64(2005); dt1971 = Dynamic::UInt64(1); Dynamic t = DTBL("state:INTEGER," "type:INTEGER," "dt:UNSIGNED_INTEGER," "year:INTEGER," "year2:INTEGER", 0 << 1 << dt1960 << 1960 << 1960 << 0 << 2 << dt2005 << 2005 << 2005 << 0 << 1 << dt2005 << 2005 << 2005 << 0 << 1 << dt2005 << 1 << 1 << 0 << 1 << dt1962 << 1962 << 1962); CINFO(t); Dynamic::TableIterator tbl_it = t.begin_t(), tbl_end = t.end_t(); for (; tbl_it != tbl_end; ++tbl_it) { detail::IndexKey key(4); Dynamic tmp(tbl_it[0]); CINFO(tmp); key.key_[0] = KeyFromData(tmp.data_, tmp.type_); tmp = tbl_it[1]; CINFO(tmp); key.key_[1] = KeyFromData(tmp.data_, tmp.type_); tmp = tbl_it[2]; CINFO(tmp); key.key_[2] = KeyFromData(tmp.data_, tmp.type_); tmp = tbl_it[3]; CINFO(tmp); key.key_[3] = KeyFromData(tmp.data_, tmp.type_); index_map[key] = SizeVector(); CINFO("---"); } CINFO(index_map.size()); IndexMap::const_iterator it = index_map.begin(), end = index_map.end(); for (; it != end; ++it) { std::cout << it->first.key_[0].i64_ << ", " << it->first.key_[1].i64_ << ", " << it->first.key_[2].ui64_ << ", " << it->first.key_[3].i64_ << ", " << '\n'; } } */ _NKIT_TEST_CASE(TestEmptyTableGroup) { std::string error; Dynamic table = Dynamic::Table("c1:STRING, c2:INTEGER, c3:DATE_TIME", &error); Dynamic grouped_table = table.Group("c1", "COUNT, SUM(c2)", &error); NKIT_TEST_ASSERT_WITH_TEXT(grouped_table.IsTable(), error); NKIT_TEST_ASSERT(grouped_table.empty()); } NKIT_TEST_CASE(TestGroup) { std::string error; Dynamic dynamic_table = PrepareData(); //----------------------------------------------- // getting sqlite3 table from dynamic table SqliteMemoryDb::Ptr db = SqliteMemoryDb::Create(&error); NKIT_TEST_ASSERT_WITH_TEXT(db, error); SqliteTable::Ptr sqlite_table = db->CreateTable("t", dynamic_table, &error); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table, error); //TestGroup(dynamic_table, sqlite_table, "browser, -year"); //return; StringVector fields; //fields.push_back("browser"); fields.push_back("year"); fields.push_back("os"); fields.push_back("likes"); fields.push_back("flag"); fields.push_back("rate"); StringVector index_combinations; GetIndexCombinations(fields, &index_combinations); size_t total = index_combinations.size(); StringVector::const_iterator it = index_combinations.begin(), comb_end = index_combinations.end(); for (size_t i=0; it != comb_end; ++it, ++i) { TestGroup(dynamic_table, sqlite_table, *it); std::cout << i << "/" << total << '\n'; } } _NKIT_TEST_CASE(TestSelectFromSqlite3) { Init(); std::string error; CINFO("Creating sqlite3 table"); TimeMeter tm; SqliteMemoryDb::Ptr db = SqliteMemoryDb::Create(&error); NKIT_TEST_ASSERT_WITH_TEXT(db, error); SqliteTable::Ptr sqlite_table = db->CreateTable("t", "k:INTEGER PRIMARY KEY," "name1:DATETIME, name2:TEXT, name3:INTEGER, name4:TEXT," " name5:INTEGER", &error); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table, error); SqliteTransaction::Ptr tr = db->CreateTransaction(&error); NKIT_TEST_ASSERT_WITH_TEXT(tr, error); StringVector row; row.reserve(6); for (size_t it_factor = 0; it_factor < ITER_SIZE; ++it_factor) { const size_t uniq = rnumbers[it_factor]; row.clear(); row.push_back(string_cast(it_factor)); row.push_back(string_cast(1386000000 + uniq)); row.push_back("name_" + string_cast(uniq)); row.push_back(string_cast(uniq + FACTOR)); row.push_back(std::string("name_" + string_cast(uniq + FACTOR))); row.push_back(string_cast(uniq + FACTOR + 1)); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table->InsertRow(row, &error), error); } NKIT_TEST_ASSERT_WITH_TEXT(tr->Commit(&error), error); tm.Start(); Dynamic table = *sqlite_table; tm.Stop(); double sqlite3_select_time = tm.GetTotal(); tm.Clear(); std::cout << "sqlite3_select_time: " << sqlite3_select_time << '\n'; tm.Start(); table = table.Clone(); size_t col_count = table.width(); size_t tmp_count = 0; Dynamic::TableIterator it = table.begin_t(), end = table.end_t(); for (; it != end; ++it) { for (size_t c = 0; c < col_count; ++c) { Dynamic tmp = it[c]; tmp_count += tmp.size(); } } tm.Stop(); double dynamic_select_time = tm.GetTotal(); tm.Clear(); std::cout << "dynamic_select_time: " << dynamic_select_time << '\n'; CINFO(tmp_count); tm.Start(); Dynamic grouped_table = table.Group("name1,name2", "COUNT,MIN(name3),MAX(name5),SUM(name5)", &error); tm.Stop(); NKIT_TEST_ASSERT_WITH_TEXT(grouped_table.IsTable(), error); double dynamic_group_time = tm.GetTotal(); tm.Clear(); std::cout << "dynamic_group_time: " << dynamic_group_time << '\n'; //CINFO(table); //CINFO(grouped_table); tm.Start(); Dynamic sqlite_grouped_table = sqlite_table->Group( "COUNT(*), MIN(name3), MAX(name5), SUM(name5)", "name1, name2", &error); tm.Stop(); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_grouped_table.IsTable(), error); //CINFO(sqlite_grouped_table); NKIT_TEST_ASSERT(sqlite_grouped_table == grouped_table); double sqlite3_group_time = tm.GetTotal(); tm.Clear(); std::cout << "sqlite3_group_time: " << sqlite3_group_time << '\n'; std::cout << "Dynamic group(3/4) is faster then " "sqlite3 group(4) by " << sqlite3_group_time / dynamic_group_time << " times" << '\n'; } //------------------------------------------------------------------------------ _NKIT_TEST_CASE(PerfCreateIndex) { Init(); std::string error; TimeMeter tm; // Creating dynamic table std::string table_def( "name1:INTEGER,name2:STRING,name3:INTEGER,name4:STRING,name5:DATE_TIME"); Dynamic table = Dynamic::Table(table_def, &error); tm.Start(); for (size_t it_factor = 0; it_factor < ITER_SIZE; ++it_factor) { const uint64_t uniq = rnumbers[it_factor]; NKIT_TEST_ASSERT( table.AppendRow(Dynamic(uniq), Dynamic(std::string("name_" + string_cast(uniq))), Dynamic(uniq + FACTOR), Dynamic(std::string("name_" + string_cast(uniq + FACTOR))), Dynamic::DateTimeFromTimestamp(1386000000 + uniq + FACTOR + 1))); } tm.Stop(); double dynamic_create_table_time = tm.GetTotal(); tm.Clear(); // Creating sqlite3 table SqliteMemoryDb::Ptr db = SqliteMemoryDb::Create(&error); NKIT_TEST_ASSERT_WITH_TEXT(db, error); SqliteTable::Ptr sqlite_table = db->CreateTable("t", "k:INTEGER PRIMARY KEY," "name1:INTEGER, name2:TEXT, name3:INTEGER, name4:TEXT," "name5:DATETIME", &error); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table, error); SqliteTransaction::Ptr tr = db->CreateTransaction(&error); NKIT_TEST_ASSERT_WITH_TEXT(tr, error); tm.Start(); StringVector row; row.reserve(6); for (size_t it_factor = 0; it_factor < ITER_SIZE; ++it_factor) { const size_t uniq = rnumbers[it_factor]; row.clear(); row.push_back(string_cast(it_factor)); row.push_back(string_cast(uniq)); row.push_back("name_" + string_cast(uniq)); row.push_back(string_cast(uniq + FACTOR)); row.push_back(std::string("name_" + string_cast(uniq + FACTOR))); row.push_back(string_cast(uniq + FACTOR + 1)); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table->InsertRow(row, &error), error); } NKIT_TEST_ASSERT_WITH_TEXT(tr->Commit(&error), error); tm.Stop(); double sqlite3_create_table_time = tm.GetTotal(); tm.Clear(); NKIT_TEST_ASSERT(sqlite3_create_table_time / dynamic_create_table_time > 1.0); std::cout << "Dynamic create table if faster then sqlite3 create table by: " << sqlite3_create_table_time / dynamic_create_table_time << '\n'; nkit::TableIndex::Ptr index; double dynamic_create_index_time; METRIC(index = table.CreateIndex("name1", &error), &dynamic_create_index_time); NKIT_TEST_ASSERT_WITH_TEXT(index, error); double sqlite3_create_index_time; METRIC( NKIT_TEST_ASSERT_WITH_TEXT( sqlite_table->CreateIndex( "idx1", "name5", &error), error), &sqlite3_create_index_time); NKIT_TEST_ASSERT(sqlite3_create_index_time / dynamic_create_index_time > 1.0); std::cout << "Dynamic create index(1) if faster then " "sqlite3 create index(1) by: " << sqlite3_create_index_time / dynamic_create_index_time << '\n'; METRIC(index = table.CreateIndex("name1,name2", &error), &dynamic_create_index_time); NKIT_TEST_ASSERT_WITH_TEXT(index, error); METRIC( NKIT_TEST_ASSERT_WITH_TEXT( sqlite_table->CreateIndex( "idx2", "name1, name2", &error), error), &sqlite3_create_index_time); NKIT_TEST_ASSERT(sqlite3_create_index_time / dynamic_create_index_time > 1.0); std::cout << "Dynamic create index(2) if faster then " "sqlite3 create index(2) by: " << sqlite3_create_index_time / dynamic_create_index_time << '\n'; METRIC(index = table.CreateIndex("name1,name2,name3", &error), &dynamic_create_index_time); NKIT_TEST_ASSERT_WITH_TEXT(index, error); METRIC( NKIT_TEST_ASSERT_WITH_TEXT( sqlite_table->CreateIndex( "idx3", "name1, name2, name3", &error), error), &sqlite3_create_index_time); NKIT_TEST_ASSERT(sqlite3_create_index_time / dynamic_create_index_time > 1.0); std::cout << "Dynamic create index(3) if faster then " "sqlite3 create index(3) by: " << sqlite3_create_index_time / dynamic_create_index_time << '\n'; } int main(int argc, char ** argv) { if (argc >= 1) { detail::__PROGRAMM_DIR = argv[0]; size_t pos = detail::__PROGRAMM_DIR.rfind(path_delimiter_); if (pos != detail::__PROGRAMM_DIR.npos) detail::__PROGRAMM_DIR.erase(pos + 1); } return nkit::test::run_all_tests(); }
28.05449
108
0.621201
matthewbeckler
9983a02523ae94b25678482f5dbb37ef2431f748
502
cpp
C++
uva/893.cpp
larc/competitive_programming
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
1
2019-05-23T19:05:39.000Z
2019-05-23T19:05:39.000Z
uva/893.cpp
larc/oremor
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
null
null
null
uva/893.cpp
larc/oremor
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
null
null
null
#include <cstdio> inline bool leap(size_t y) { return !(y % 400) || (!(y % 4) && (y % 100)); } inline size_t month(size_t m, size_t y) { if(m == 2) return leap(y) ? 29 : 28; if(m == 4 || m == 6 || m == 9 || m == 11) return 30; return 31; } int main() { size_t p, d, m, y, dd, mm, yy, rd, rm; while(scanf("%ld %ld %ld %ld", &p, &d, &m, &y) != EOF && p && d && m && y) { yy = p/365; p %= 365; mm = p/30; p %= 30; dd = p; printf("%ld %ld %ld\n", dd, mm + m, yy + y); } return 0; }
17.310345
75
0.462151
larc
998607d27a2b09f69d678c63ba34b6803bd4abfc
3,058
cpp
C++
Tray.cpp
Wumpf/SteamMeUp
61446352ad9843b5ce6815c44b0665cd1c88c0d9
[ "MIT" ]
null
null
null
Tray.cpp
Wumpf/SteamMeUp
61446352ad9843b5ce6815c44b0665cd1c88c0d9
[ "MIT" ]
null
null
null
Tray.cpp
Wumpf/SteamMeUp
61446352ad9843b5ce6815c44b0665cd1c88c0d9
[ "MIT" ]
null
null
null
#include <Windows.h> #include "Log.h" #include "SteamMeUp.h" #include "resource.h" #define TRAY_CALLBACK_MESSAGE (WM_USER + 200) #define TRAY_CONTEXMENU_STEAMBIGPIC (WM_USER + 401) #define TRAY_CONTEXMENU_STEAM (WM_USER + 402) #define TRAY_CONTEXMENU_EXIT (WM_USER + 403) namespace { HMENU hPopupMenu; HWND hWnd; NOTIFYICONDATA notifyIconData; LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch (LOWORD(wParam)) { case TRAY_CONTEXMENU_STEAMBIGPIC: StartSteam(true); break; case TRAY_CONTEXMENU_STEAM: StartSteam(false); break; case TRAY_CONTEXMENU_EXIT: DestroyWindow(hWnd); break; } break; case WM_DESTROY: Shell_NotifyIcon(NIM_DELETE, &notifyIconData); PostQuitMessage(0); break; case TRAY_CALLBACK_MESSAGE: switch (LOWORD(lParam)) { case WM_RBUTTONUP: { POINT pt = {}; if (GetCursorPos(&pt)) { SetForegroundWindow(hWnd); TrackPopupMenu(hPopupMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN, pt.x, pt.y, 0, hWnd, NULL); } } } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } } bool InitTray() { WNDCLASSEXW wcex; memset(&wcex, 0, sizeof(WNDCLASSEXW)); wcex.cbSize = sizeof(WNDCLASSEX); wcex.lpfnWndProc = WndProc; wcex.hInstance = GetModuleHandle(nullptr); wcex.lpszClassName = L"SteamMeUp"; RegisterClassExW(&wcex); hWnd = CreateWindowExW(0, wcex.lpszClassName, L"SteamMeUp", WS_DISABLED, 0, 0, 0, 0, nullptr, nullptr, wcex.hInstance, nullptr); if (!hWnd) { LOG(LogLevel::FAIL, "Failed to create Window: " << GetLastErrorAsString()); return false; } memset(&notifyIconData, 0, sizeof(NOTIFYICONDATA)); notifyIconData.cbSize = sizeof(NOTIFYICONDATA); notifyIconData.hWnd = hWnd; notifyIconData.uID = 1; notifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; notifyIconData.uCallbackMessage = TRAY_CALLBACK_MESSAGE; notifyIconData.hIcon = (HICON)LoadImage(wcex.hInstance, MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); lstrcpy(notifyIconData.szTip, L"SteamMeUp - Start Steam big picture with the Xbox home button."); if (!Shell_NotifyIcon(NIM_ADD, &notifyIconData)) { LOG(LogLevel::FAIL, "Failed to display tray icon: " << GetLastErrorAsString()); return false; } hPopupMenu = CreatePopupMenu(); AppendMenuW(hPopupMenu, MF_STRING | MF_GRAYED | MF_DISABLED, TRAY_CONTEXMENU_EXIT, g_steamInstallationPath); AppendMenuW(hPopupMenu, MF_SEPARATOR, 0, nullptr); AppendMenuW(hPopupMenu, MF_STRING, TRAY_CONTEXMENU_STEAMBIGPIC, L"Start Steam in Big Picture Mode"); AppendMenuW(hPopupMenu, MF_STRING, TRAY_CONTEXMENU_STEAM, L"Start Steam"); AppendMenuW(hPopupMenu, MF_SEPARATOR, 0, nullptr); AppendMenuW(hPopupMenu, MF_STRING, TRAY_CONTEXMENU_EXIT, L"Exit"); return true; } void RunWinApiMessageLoop() { MSG msg; while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
27.061947
176
0.734467
Wumpf
9986162fa57494ee5bcec4d84776c609fa455ea6
26,262
cpp
C++
original_source/src/items.cpp
RichardMarks/sawd-revival
670aff96e81b6cedf706fa891ca4d2b57ebdc4b4
[ "MIT" ]
null
null
null
original_source/src/items.cpp
RichardMarks/sawd-revival
670aff96e81b6cedf706fa891ca4d2b57ebdc4b4
[ "MIT" ]
null
null
null
original_source/src/items.cpp
RichardMarks/sawd-revival
670aff96e81b6cedf706fa891ca4d2b57ebdc4b4
[ "MIT" ]
null
null
null
/* SAWD Small ASCII Walk-around Demo (C) Copyright 2008, CCPS Solutions This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <cstdarg> #include <cstdlib> #include <cstdio> #include <cstring> #include "clib.h" #include "sawd.h" /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// // satisfy the item target class item_target::item_target(void* self, void* target):self_(self),target_(target){} item_target::~item_target(){} void* item_target::GetSelf(){return self_;} void* item_target::GetTarget(){return target_;} /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void setmods(obj*o, int*mods) { o->cur_hp += mods[ITEM_MODIFIER_HP]; o->cur_mp += mods[ITEM_MODIFIER_MP]; o->cur_ap += mods[ITEM_MODIFIER_AP]; o->attack += mods[ITEM_MODIFIER_ATTACK]; o->defense += mods[ITEM_MODIFIER_DEFENSE]; o->strength += mods[ITEM_MODIFIER_STRENGTH]; o->magic += mods[ITEM_MODIFIER_MAGIC]; o->max_hp += mods[ITEM_MODIFIER_MAX_HP]; o->max_mp += mods[ITEM_MODIFIER_MAX_MP]; o->max_ap += mods[ITEM_MODIFIER_MAX_AP]; } void unsetmods(obj*o, int*mods) { o->cur_hp -= mods[ITEM_MODIFIER_HP]; o->cur_mp -= mods[ITEM_MODIFIER_MP]; o->cur_ap -= mods[ITEM_MODIFIER_AP]; o->attack -= mods[ITEM_MODIFIER_ATTACK]; o->defense -= mods[ITEM_MODIFIER_DEFENSE]; o->strength -= mods[ITEM_MODIFIER_STRENGTH]; o->magic -= mods[ITEM_MODIFIER_MAGIC]; o->max_hp -= mods[ITEM_MODIFIER_MAX_HP]; o->max_mp -= mods[ITEM_MODIFIER_MAX_MP]; o->max_ap -= mods[ITEM_MODIFIER_MAX_AP]; } void equip_leather_vest(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_leather_boots(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_leather_gauntlets(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_leather_vest(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_leather_boots(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_leather_gauntlets(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_short_sword(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); if (target->chr_class == 0) { setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } else { cl->show_message(3,"","Cannot equip the Short Sword!",""); } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_heavy_axe(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); if (target->chr_class == 1) { setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } else { cl->show_message(3,"","Cannot equip the Heavy Axe!",""); } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_wooden_bow(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); if (target->chr_class == 2) { setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } else { cl->show_message(3,"","Cannot equip the Wooden Bow!",""); } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_wooden_staff(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); if (target->chr_class == 3) { setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } else { cl->show_message(3,"","Cannot equip the Wooden Staff!",""); } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_short_sword(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_heavy_axe(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_wooden_bow(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_wooden_staff(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_silver_vest(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_silver_boots(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_silver_gauntlets(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_silver_vest(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_silver_boots(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_silver_gauntlets(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_silver_sword(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); if (target->chr_class == 0) { setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } else { cl->show_message(3,"","Cannot equip the Silver Sword!",""); } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_silver_axe(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); if (target->chr_class == 1) { setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } else { cl->show_message(3,"","Cannot equip the Silver Axe!",""); } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_silver_bow(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); if (target->chr_class == 2) { setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } else { cl->show_message(3,"","Cannot equip the Silver Bow!",""); } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void equip_silver_staff(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); if (target->chr_class == 3) { setmods(target, self->modifiers); target->items_equipped.push_back(self->name); } else { cl->show_message(3,"","Cannot equip the Silver Staff!",""); } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_silver_sword(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_silver_axe(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_silver_bow(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); unsetmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void unequip_silver_staff(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_healing_powder(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); char m[80]; int hp = self->modifiers[ITEM_MODIFIER_HP]; player->cur_hp += hp; if (player->cur_hp > player->max_hp) { player->cur_hp = player->max_hp; } sprintf_s(m,80,"%s: %d HP Restored!",target->name, hp); cl->show_message(3,"",m,""); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_escape_roots(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message(3,"","Nothing Happened...",""); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_burn_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message(3,"","BURN SPELL SCROLL USED",""); setmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_break_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message(3,"","BREAK SPELL SCROLL USED",""); setmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_healing_powder(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_escape_roots(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_burn_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_break_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_anti_venom(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message(3,"","Nothing Happened...",""); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_inferno_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message(3,"","INFERNO SPELL SCROLL USED",""); setmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_shatter_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message(3,"","SHATTER SPELL SCROLL USED",""); setmods(target, self->modifiers); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_drain_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message(3,"","DRAIN SPELL SCROLL USED",""); setmods(target, self->modifiers); player->cur_hp += self->modifiers[ITEM_MODIFIER_HP]; cl->show_message(3,"","You drained life from the enemy!",""); if (player->cur_hp > player->max_hp) player->cur_hp = player->max_hp; } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_anti_venom(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_inferno_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_shatter_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_drain_scroll(void* d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_beerpint(void*d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message(3,"","You down your Pint 'O Beer and feel a bit dizzy.",""); player->drinks+=4; if (player->drinks > player->level*2) { cl->show_message_centered(3,"","You are drunk! Be careful out there!",""); player->drunk = true; } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_bottledbeer(void*d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message_centered(3,"","Ahh that sure does taste good...",""); player->drinks++; if (player->drinks > player->level*2) { cl->show_message_centered(3,"","You are drunk! Be careful out there!",""); player->drunk = true; } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void use_liquor(void*d) { item_target* t = (item_target*)d; shop_item* self = (shop_item*)t->GetSelf(); obj* target = (obj*)t->GetTarget(); cl->show_message_centered(3,"","Ahh that sure does taste good...",""); player->drinks+=10; if (player->drinks > player->level*2) { cl->show_message_centered(3,"","You are drunk! Be careful out there!",""); player->drunk = true; } } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_beerpint(void*d) { cl->show_message_centered(3,"","You dropped a pint of beer! Oh the humanity!",""); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_bottledbeer(void*d) { cl->show_message_centered(3,"","Dropping beer bottles is fun to you?",""); } /////////////////////////////////////////////////////////////////////////////// //###########################################################################// /////////////////////////////////////////////////////////////////////////////// void drop_liquor(void*d) { cl->show_message_centered(3,"","What a waste of good liquor!",""); }
32.868586
83
0.360064
RichardMarks
998deac9dbd924cb26f34102a230e157a6772414
526
cpp
C++
codeforces/701/a.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
codeforces/701/a.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
codeforces/701/a.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> using namespace std; bool touched[103]; int printSearch(int *arr,int n,int ele){ int i; for(i=1;(i<=n && arr[i]!=ele) || touched[i]!=0;i++); touched[i]=1; return i; } int main(int argc, char const *argv[]) { int n,arr[103],temp[103]; cin>>n; for(int i=1;i<=n;i++) {cin>>arr[i];temp[i]=arr[i];} sort(temp,temp+n+1); for(int i=1;i<=(n/2);i++){ cout<<printSearch(arr,n,temp[i])<<" "<<printSearch(arr,n,temp[n-i+1])<<endl; } return 0; }
25.047619
84
0.558935
AadityaJ
998e14ed07f898b45d5b1eae682e2457e247f5fd
1,506
cpp
C++
lab6/Circuit.cpp
carinaioana/oop-2022
b2cd27a40f95b2ca549bba0cb9c2a55921c8ca0d
[ "MIT" ]
null
null
null
lab6/Circuit.cpp
carinaioana/oop-2022
b2cd27a40f95b2ca549bba0cb9c2a55921c8ca0d
[ "MIT" ]
null
null
null
lab6/Circuit.cpp
carinaioana/oop-2022
b2cd27a40f95b2ca549bba0cb9c2a55921c8ca0d
[ "MIT" ]
null
null
null
#include "Circuit.h" #include "Dacia.h" #include "Mercedes.h" #include "Ford.h" #include "Mazda.h" #include "Toyota.h" #include "Car.h" #include <vector> #include <iostream> void Circuit::SetLength(float l) { this->length = l; } void Circuit::SetWeather(Weather w) { this->weather = w; } void Circuit::AddCar(Car* newCar) { CarVector.push_back(newCar); } void Circuit::Race() { int n = CarVector.size(); for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (CarVector[i]->getAvgSpeed() < CarVector[j]->getAvgSpeed()) std::swap(CarVector[i], CarVector[j]); } void Circuit::ShowFinalRanks() { int p = 1; std::cout << "The time cars have finished the race (from fastest to lowest) :"; for (int i = 0; i < CarVector.size(); i++) { if (CarVector[i]->getFuelCap() / CarVector[i]->getFuelCons() * 100 >= this->length) { float t = this->length / CarVector[i]->getAvgSpeed() * 100; std::cout << "Locul " << p++ << ": " << CarVector[i]->getName() << " " << "a terminat cursa in " << t << " minute" << '\n'; } } }// it will print the time each car needed to finish the circuit sorted from the fastest car to the slowest. void Circuit::ShowWhoDidNotFinish() { std::cout << "The cars that did not finish are:"; for (int i = 0; i < CarVector.size(); i++) { if (CarVector[i]->getFuelCap() / CarVector[i]->getFuelCons() * 100 <= this->length) std::cout << CarVector[i] << ' '; } } // it is possible that some cars don't have enough fuel to finish the circuit
28.415094
126
0.623506
carinaioana
998f58df6a594396a0288e36adf362be84cd985e
35,061
cpp
C++
DyssolMainWindow/Dyssol.cpp
FlowsheetSimulation/Dyssol-open
557d57d959800868e1b3fd161b26cad16481382b
[ "BSD-3-Clause" ]
7
2020-12-02T02:54:31.000Z
2022-03-08T20:37:46.000Z
DyssolMainWindow/Dyssol.cpp
FlowsheetSimulation/Dyssol-open
557d57d959800868e1b3fd161b26cad16481382b
[ "BSD-3-Clause" ]
33
2021-03-26T12:20:18.000Z
2022-02-23T11:37:56.000Z
DyssolMainWindow/Dyssol.cpp
FlowsheetSimulation/Dyssol-open
557d57d959800868e1b3fd161b26cad16481382b
[ "BSD-3-Clause" ]
6
2020-07-17T08:17:37.000Z
2022-02-24T13:45:16.000Z
/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */ #include "Dyssol.h" #include "StatusWindow.h" #include "AboutWindow.h" #include "ScriptExporter.h" #include "FileSystem.h" #include "DyssolStringConstants.h" #include "DyssolSystemFunctions.h" #include "ThreadPool.h" #include <QDesktopWidget> #include <QCloseEvent> #include <QFileDialog> #include <QDesktopServices> #include <filesystem> #include <fstream> ////////////////////////////////////////////////////////////////////////// /// Dyssol ////////////////////////////////////////////////////////////////////////// Dyssol::Dyssol(QWidget *parent /*= 0*/, Qt::WindowFlags flags /*= {}*/) : QMainWindow(parent, flags) { ui.setupUi(this); resize(QDesktopWidget().availableGeometry(this).size() * 0.7); SetFlowsheetModified(false); InitializeThreadPool(); // setup flowsheet and simulator m_Simulator.SetFlowsheet(&m_Flowsheet); // setup config file m_sSettingsPath = QFileInfo(QSettings(QSettings::IniFormat, QSettings::UserScope, StrConst::Dyssol_ApplicationName, StrConst::Dyssol_ConfigApp).fileName()).absolutePath(); // create directory for temporary data if it doesn't exist if (!std::filesystem::exists(m_sSettingsPath.toStdString())) std::filesystem::create_directory(m_sSettingsPath.toStdString()); const QString globalConfigFile = m_sSettingsPath + "/" + StrConst::Dyssol_ConfigFileName; const QString localConfigFile = QString{ "./" } + StrConst::Dyssol_ConfigFileName; #ifdef _MSC_VER const QString currConfigFile = QFile::exists(globalConfigFile) ? globalConfigFile : localConfigFile; #else const QString currConfigFile = QFile::exists(localConfigFile) ? localConfigFile : globalConfigFile; std::cout << "Use config file: " << currConfigFile.toStdString()<< std::endl; // If the config file not exist at all, we will copy the template of config file into the currConfigFile // It is needed mostly for packages if ((currConfigFile == globalConfigFile) && (not (QFile::exists(currConfigFile)))) { std::cout << "Config file: " << currConfigFile.toStdString()<< "does not exist. It will be copied from "<< INSTALL_CONFIG_PATH << StrConst::Dyssol_ConfigFileName << std::endl; std::filesystem::copy_file(std::filesystem::path{ INSTALL_CONFIG_PATH } / StrConst::Dyssol_ConfigFileName, currConfigFile.toStdString()); } #endif // create config file m_pSettings = new QSettings(currConfigFile, QSettings::IniFormat, this); // create dialogs and windows m_pModelsManagerTab = new CModulesManagerTab(&m_ModelsManager, m_pSettings, this); m_pCalcSequenceEditor = new CCalculationSequenceEditor(&m_Flowsheet, this); m_pMaterialsDatabaseTab = new CMaterialsDatabaseTab(&m_MaterialsDatabase, m_pSettings, this); m_pCompoundsManager = new CCompoundsManager(&m_Flowsheet, &m_MaterialsDatabase, this); m_pFlowsheetEditor = new CFlowsheetEditor(&m_Flowsheet, &m_MaterialsDatabase, &m_ModelsManager, this); m_pGridEditor = new CGridEditor(&m_Flowsheet, m_MaterialsDatabase, this); m_pHoldupsEditor = new CHoldupsEditor(&m_Flowsheet, &m_MaterialsDatabase, this); m_pOptionsEditor = new COptionsEditor(&m_Flowsheet, &m_MaterialsDatabase, this); m_pPhasesEditor = new CPhasesEditor(&m_Flowsheet, this); m_pSimulatorTab = new CSimulatorTab(&m_Flowsheet, &m_Simulator, this); m_pStreamsViewer = new CStreamsViewer(&m_Flowsheet, &m_MaterialsDatabase, this); m_pUnitsViewer = new CUnitsViewer(&m_Flowsheet, &m_MaterialsDatabase, this); m_pTearStreamsEditor = new CTearStreamsEditor(&m_Flowsheet, &m_MaterialsDatabase, this); m_pDustTesterTab = new CDustFormationTesterTab(&m_Flowsheet, &m_MaterialsDatabase, this); m_pSettingsEditor = new CSettingsEditor(m_pSettings, this); // setup main window: add tabs to mainTabWidget ui.mainTabWidget->addTab(m_pFlowsheetEditor, StrConst::Dyssol_FlowsheetTabName); ui.mainTabWidget->addTab(m_pSimulatorTab, StrConst::Dyssol_SimulatorTabName); ui.mainTabWidget->addTab(m_pStreamsViewer, StrConst::Dyssol_StreamsTabName); ui.mainTabWidget->addTab(m_pUnitsViewer, StrConst::Dyssol_UnitsTabName); ui.mainTabWidget->setStyleSheet("QTabBar::tab { min-width: 100px; }"); // current flowsheet saving file m_sCurrFlowsheetFile = ""; // status modal windows m_pLoadingWindow = new CStatusWindow(StrConst::Dyssol_StatusLoadingTitle, StrConst::Dyssol_StatusLoadingText, StrConst::Dyssol_StatusLoadingQuestion, false, this); m_pSavingWindow = new CStatusWindow(StrConst::Dyssol_StatusSavingTitle, StrConst::Dyssol_StatusSavingText, StrConst::Dyssol_StatusSavingQuestion, false); // threads for saving and loading m_pLoadingThread = new CSaveLoadThread(&m_Flowsheet, false); m_pSavingThread = new CSaveLoadThread(&m_Flowsheet, true); // create and setup menu CreateMenu(); UpdateMenu(); // configure cache parameters SetupCache(); // load materials database LoadMaterialsDatabase(); } Dyssol::~Dyssol() { delete m_pSavingThread; delete m_pLoadingThread; delete m_pLoadingWindow; delete m_pSavingWindow; } void Dyssol::InitializeConnections() const { // initialize connections of widgets m_pCalcSequenceEditor->InitializeConnections(); m_pMaterialsDatabaseTab->InitializeConnections(); m_pCompoundsManager->InitializeConnections(); m_pFlowsheetEditor->InitializeConnections(); m_pGridEditor->InitializeConnections(); m_pHoldupsEditor->InitializeConnections(); m_pModelsManagerTab->InitializeConnections(); m_pOptionsEditor->InitializeConnections(); m_pPhasesEditor->InitializeConnections(); m_pSimulatorTab->InitializeConnections(); m_pStreamsViewer->InitializeConnections(); m_pUnitsViewer->InitializeConnections(); m_pTearStreamsEditor->InitializeConnections(); m_pDustTesterTab->InitializeConnections(); m_pSettingsEditor->InitializeConnections(); // signals to dialogs from menu entries connect(ui.actionCalcSequencerEditor, &QAction::triggered, m_pCalcSequenceEditor, &QDialog::raise); connect(ui.actionCalcSequencerEditor, &QAction::triggered, m_pCalcSequenceEditor, &QDialog::show); connect(ui.actionCompoundsEditor, &QAction::triggered, m_pMaterialsDatabaseTab, &QDialog::raise); connect(ui.actionCompoundsEditor, &QAction::triggered, m_pMaterialsDatabaseTab, &QDialog::show); connect(ui.actionCompoundsManager, &QAction::triggered, m_pCompoundsManager, &QDialog::raise); connect(ui.actionCompoundsManager, &QAction::triggered, m_pCompoundsManager, &QDialog::show); connect(ui.actionGridEditor, &QAction::triggered, m_pGridEditor, &QDialog::raise); connect(ui.actionGridEditor, &QAction::triggered, m_pGridEditor, &QDialog::show); connect(ui.actionHoldupsEditor, &QAction::triggered, m_pHoldupsEditor, &QDialog::raise); connect(ui.actionHoldupsEditor, &QAction::triggered, m_pHoldupsEditor, &QDialog::show); connect(ui.actionModelsManager, &QAction::triggered, m_pModelsManagerTab, &QDialog::raise); connect(ui.actionModelsManager, &QAction::triggered, m_pModelsManagerTab, &QDialog::show); connect(ui.actionOptionsEditor, &QAction::triggered, m_pOptionsEditor, &QDialog::raise); connect(ui.actionOptionsEditor, &QAction::triggered, m_pOptionsEditor, &QDialog::show); connect(ui.actionPhasesEditor, &QAction::triggered, m_pPhasesEditor, &QDialog::raise); connect(ui.actionPhasesEditor, &QAction::triggered, m_pPhasesEditor, &QDialog::show); connect(ui.actionRecycleStreams, &QAction::triggered, m_pTearStreamsEditor, &QDialog::raise); connect(ui.actionRecycleStreams, &QAction::triggered, m_pTearStreamsEditor, &QDialog::show); connect(ui.actionDustFormationTester, &QAction::triggered, m_pDustTesterTab, &QDialog::raise); connect(ui.actionDustFormationTester, &QAction::triggered, m_pDustTesterTab, &QDialog::show); connect(ui.actionSettingsEditor, &QAction::triggered, m_pSettingsEditor, &QDialog::raise); connect(ui.actionSettingsEditor, &QAction::triggered, m_pSettingsEditor, &QDialog::show); // connections from file menu entries connect(ui.actionNewFlowsheet, &QAction::triggered, this, &Dyssol::NewFlowsheet); connect(ui.actionOpenFlowsheet, &QAction::triggered, this, &Dyssol::OpenFlowsheet); connect(ui.actionSaveFlowsheet, &QAction::triggered, this, &Dyssol::SaveFlowsheet); connect(ui.actionSaveFlowsheetAs, &QAction::triggered, this, &Dyssol::SaveFlowsheetAs); connect(ui.actionSaveScript, &QAction::triggered, this, &Dyssol::SaveScriptFile); connect(ui.actionSaveGraph, &QAction::triggered, this, &Dyssol::SaveGraphFile); connect(ui.actionSaveGraphImage, &QAction::triggered, this, &Dyssol::SaveGraphImage); connect(ui.actionAbout, &QAction::triggered, this, &Dyssol::ShowAboutDialog); // signals from threads connect(m_pLoadingThread, &CSaveLoadThread::Finished, this, &Dyssol::LoadingFinished); connect(m_pSavingThread, &CSaveLoadThread::Finished, this, &Dyssol::SavingFinished); // signals between widgets connect(m_pFlowsheetEditor, &CFlowsheetEditor::ModelsChanged, m_pHoldupsEditor, &CHoldupsEditor::UpdateWholeView); connect(m_pFlowsheetEditor, &CFlowsheetEditor::ModelsChanged, m_pCalcSequenceEditor, &CCalculationSequenceEditor::UpdateWholeView); connect(m_pFlowsheetEditor, &CFlowsheetEditor::ModelsChanged, m_pTearStreamsEditor, &CTearStreamsEditor::UpdateWholeView); connect(m_pFlowsheetEditor, &CFlowsheetEditor::StreamsChanged, m_pCalcSequenceEditor, &CCalculationSequenceEditor::UpdateWholeView); connect(m_pFlowsheetEditor, &CFlowsheetEditor::StreamsChanged, m_pTearStreamsEditor, &CTearStreamsEditor::UpdateWholeView); connect(m_pFlowsheetEditor, &CFlowsheetEditor::StreamsChanged, m_pDustTesterTab, &CDustFormationTesterTab::UpdateWholeView); connect(m_pFlowsheetEditor, &CFlowsheetEditor::UnitChanged, m_pHoldupsEditor, &CHoldupsEditor::UpdateWholeView); connect(m_pFlowsheetEditor, &CFlowsheetEditor::UnitChanged, m_pDustTesterTab, &CDustFormationTesterTab::UpdateWholeView); connect(m_pHoldupsEditor, &CHoldupsEditor::DataChanged, m_pUnitsViewer, &CUnitsViewer::UpdateWholeView); connect(m_pHoldupsEditor, &CHoldupsEditor::DataChanged, m_pDustTesterTab, &CDustFormationTesterTab::UpdateWholeView); connect(m_pGridEditor, &CGridEditor::DataChanged, m_pHoldupsEditor, &CHoldupsEditor::UpdateWholeView); connect(m_pGridEditor, &CGridEditor::DataChanged, m_pUnitsViewer, &CUnitsViewer::UpdateWholeView); connect(m_pGridEditor, &CGridEditor::DataChanged, m_pTearStreamsEditor, &CTearStreamsEditor::UpdateWholeView); connect(m_pGridEditor, &CGridEditor::DataChanged, m_pDustTesterTab, &CDustFormationTesterTab::UpdateWholeView); connect(m_pMaterialsDatabaseTab, &CMaterialsDatabaseTab::MaterialDatabaseWasChanged, m_pHoldupsEditor, &CHoldupsEditor::UpdateWholeView); connect(m_pMaterialsDatabaseTab, &CMaterialsDatabaseTab::MaterialDatabaseWasChanged, m_pGridEditor, &CGridEditor::UpdateWholeView); connect(m_pMaterialsDatabaseTab, &CMaterialsDatabaseTab::MaterialDatabaseWasChanged, m_pCompoundsManager, &CCompoundsManager::UpdateWholeView); connect(m_pMaterialsDatabaseTab, &CMaterialsDatabaseTab::MaterialDatabaseWasChanged, m_pTearStreamsEditor, &CTearStreamsEditor::UpdateWholeView); connect(m_pCompoundsManager, &CCompoundsManager::DataChanged, m_pHoldupsEditor, &CHoldupsEditor::UpdateWholeView); connect(m_pCompoundsManager, &CCompoundsManager::DataChanged, m_pUnitsViewer, &CUnitsViewer::UpdateWholeView); connect(m_pCompoundsManager, &CCompoundsManager::DataChanged, m_pTearStreamsEditor, &CTearStreamsEditor::UpdateWholeView); connect(m_pCompoundsManager, &CCompoundsManager::DataChanged, m_pDustTesterTab, &CDustFormationTesterTab::UpdateWholeView); connect(m_pPhasesEditor, &CPhasesEditor::DataChanged, m_pHoldupsEditor, &CHoldupsEditor::UpdateWholeView); connect(m_pPhasesEditor, &CPhasesEditor::DataChanged, m_pUnitsViewer, &CUnitsViewer::UpdateWholeView); connect(m_pPhasesEditor, &CPhasesEditor::DataChanged, m_pTearStreamsEditor, &CTearStreamsEditor::UpdateWholeView); connect(m_pPhasesEditor, &CPhasesEditor::DataChanged, m_pDustTesterTab, &CDustFormationTesterTab::UpdateWholeView); connect(m_pModelsManagerTab, &CModulesManagerTab::ModelsListWasChanged, m_pFlowsheetEditor, &CFlowsheetEditor::UpdateAvailableUnits); connect(m_pModelsManagerTab, &CModulesManagerTab::ModelsListWasChanged, m_pFlowsheetEditor, &CFlowsheetEditor::UpdateAvailableSolvers); connect(m_pSimulatorTab, &CSimulatorTab::SimulatorStateToggled, this, &Dyssol::BlockUI); connect(m_pOptionsEditor, &COptionsEditor::NeedSaveAndReopen, this, &Dyssol::SlotSaveAndReopen); connect(m_pSettingsEditor, &CSettingsEditor::NeedRestart, this, &Dyssol::SlotRestart); connect(m_pSettingsEditor, &CSettingsEditor::NeedCacheClear, this, &Dyssol::SlotClearCache); connect(this, &Dyssol::NewFlowsheetLoaded, m_pCalcSequenceEditor, &CCalculationSequenceEditor::UpdateWholeView); connect(this, &Dyssol::NewFlowsheetLoaded, m_pCompoundsManager, &CCompoundsManager::UpdateWholeView); connect(this, &Dyssol::NewFlowsheetLoaded, m_pGridEditor, &CGridEditor::UpdateWholeView); connect(this, &Dyssol::NewFlowsheetLoaded, m_pHoldupsEditor, &CHoldupsEditor::UpdateWholeView); connect(this, &Dyssol::NewFlowsheetLoaded, m_pOptionsEditor, &COptionsEditor::UpdateWholeView); connect(this, &Dyssol::NewFlowsheetLoaded, m_pPhasesEditor, &CPhasesEditor::UpdateWholeView); connect(this, &Dyssol::NewFlowsheetLoaded, m_pTearStreamsEditor, &CTearStreamsEditor::UpdateWholeView); connect(this, &Dyssol::NewFlowsheetLoaded, m_pDustTesterTab, &CDustFormationTesterTab::UpdateWholeView); connect(this, &Dyssol::NewFlowsheetLoaded, m_pSimulatorTab, &CSimulatorTab::OnNewFlowsheet); // modification signals connect(m_pCalcSequenceEditor, &CCalculationSequenceEditor::DataChanged, this, &Dyssol::FlowsheetStateChanged); connect(m_pCompoundsManager, &CCompoundsManager::DataChanged, this, &Dyssol::FlowsheetStateChanged); connect(m_pFlowsheetEditor, &CFlowsheetEditor::DataChanged, this, &Dyssol::FlowsheetStateChanged); connect(m_pGridEditor, &CGridEditor::DataChanged, this, &Dyssol::FlowsheetStateChanged); connect(m_pHoldupsEditor, &CHoldupsEditor::DataChanged, this, &Dyssol::FlowsheetStateChanged); connect(m_pOptionsEditor, &COptionsEditor::DataChanged, this, &Dyssol::FlowsheetStateChanged); connect(m_pPhasesEditor, &CPhasesEditor::DataChanged, this, &Dyssol::FlowsheetStateChanged); connect(m_pSimulatorTab, &CSimulatorTab::DataChanged, this, &Dyssol::FlowsheetStateChanged); connect(m_pTearStreamsEditor, &CTearStreamsEditor::DataChanged, this, &Dyssol::FlowsheetStateChanged); } void Dyssol::UpdateWholeView() const { switch (ui.mainTabWidget->currentIndex()) { case FLOWSHEET_TAB: m_pFlowsheetEditor->UpdateWholeView(); break; case SIMULATOR_TAB: m_pSimulatorTab->UpdateWholeView(); break; case STREAMS_TAB: m_pStreamsViewer->UpdateWholeView(); break; case UNITS_TAB: m_pUnitsViewer->UpdateWholeView(); break; default: break; } } void Dyssol::RestoreLastState() const { const QVariant path = m_pSettings->value(StrConst::Dyssol_ConfigLastParamName); if (path.isValid() && !path.toString().isEmpty()) LoadFromFile(path.toString()); } void Dyssol::OpenFromCommandLine(const QString& _sPath) { if(_sPath.simplified().isEmpty()) return; if (!CheckAndAskUnsaved()) return; LoadFromFile(_sPath); } void Dyssol::OpenDyssol() const { if (m_pSettings->value(StrConst::Dyssol_ConfigLoadLastFlag).toBool()) RestoreLastState(); } void Dyssol::closeEvent(QCloseEvent* event) { if (m_Simulator.GetCurrentStatus() != ESimulatorStatus::SIMULATOR_IDLE) { const QMessageBox::StandardButtons buttons = QMessageBox::Yes | QMessageBox::Cancel | QMessageBox::No; const QMessageBox::StandardButton reply = QMessageBox::question(this, StrConst::Dyssol_MainWindowName, StrConst::Dyssol_AbortMessage, buttons); if (reply == QMessageBox::Yes) CloseDyssol(); else { event->ignore(); return; } } if (!CheckAndAskUnsaved()) event->ignore(); else CloseDyssol(); } void Dyssol::SetupCache() { // remove old cache data ClearCache(); // set the default cache path to config.ini if it has not been set or does not exist const QVariant cachePathVar = m_pSettings->value(StrConst::Dyssol_ConfigCachePath); if (!cachePathVar.isValid() || cachePathVar.toString().isEmpty() || !std::filesystem::exists(cachePathVar.toString().toStdString())) m_pSettings->setValue(StrConst::Dyssol_ConfigCachePath, m_sSettingsPath); // setup cache path const QString cachePath = m_pSettings->value(StrConst::Dyssol_ConfigCachePath).toString(); #if _DEBUG m_Flowsheet.GetParameters()->CachePath((cachePath + StrConst::Dyssol_CacheDirDebug).toStdWString()); #else m_Flowsheet.GetParameters()->CachePath((cachePath + StrConst::Dyssol_CacheDirRelease).toStdWString()); #endif // check whether the cache path is accessible if (FileSystem::IsWriteProtected(cachePath.toStdWString())) { m_pSavingThread->Block(); m_pLoadingThread->Block(); QMessageBox::critical(this, StrConst::Dyssol_MainWindowName, "Unable to access the selected cache path because it is write-protected:\n'" + cachePath + "'\nPlease choose another path using Tools -> Settings -> Change path...\nSaving/loading of flowsheets is blocked until that."); } m_Flowsheet.UpdateCacheSettings(); } void Dyssol::ClearCache() { // check whether other instances are running if (OtherRunningDyssolCount()) return; // close flowsheet m_Flowsheet.Clear(); // clear cache std::filesystem::remove_all((m_pSettings->value(StrConst::Dyssol_ConfigCachePath).toString() + StrConst::Dyssol_CacheDirDebug).toStdString()); std::filesystem::remove_all((m_pSettings->value(StrConst::Dyssol_ConfigCachePath).toString() + StrConst::Dyssol_CacheDirRelease).toStdString()); } void Dyssol::CreateMenu() { /// remove graphviz on Windows #ifndef GRAPHVIZ ui.menuFile->removeAction(ui.actionSaveGraphImage); #endif /// recent files for (size_t i = 0; i < MAX_RECENT_FILES; ++i) { auto* pAction = new QAction(this); pAction->setVisible(false); pAction->setToolTip(""); connect(pAction, &QAction::triggered, this, &Dyssol::LoadRecentFile); ui.menuFile->insertAction(ui.actionExit, pAction); m_vRecentFilesActions.push_back(pAction); } ui.menuFile->insertSeparator(ui.actionExit); /// help files // Introduction QMenu* menuIntroduction = ui.menuDocumentation->addMenu("Introduction"); menuIntroduction->addAction("Get Started" , this, [&] { OpenHelp("first.html" ); }); menuIntroduction->addAction("Architecture" , this, [&] { OpenHelp("simulation.html" ); }); menuIntroduction->addAction("Algorithms" , this, [&] { OpenHelp("theory.html" ); }); menuIntroduction->addAction("User Interface" , this, [&] { OpenHelp("first.html#introduction-to-gui"); }); // Units QMenu* menuUnits = ui.menuDocumentation->addMenu("Units"); menuUnits->addAction("Agglomerator" , this, [&] { OpenHelp("units.html#agglomerator"); }); menuUnits->addAction("Bunker" , this, [&] { OpenHelp("units.html#bunker" ); }); menuUnits->addAction("Crusher" , this, [&] { OpenHelp("units.html#crusher" ); }); menuUnits->addAction("Granulator" , this, [&] { OpenHelp("units.html#granulator" ); }); menuUnits->addAction("Inlet Flow" , this, [&] { OpenHelp("units.html#inlet-flow" ); }); menuUnits->addAction("Mixer" , this, [&] { OpenHelp("units.html#mixer" ); }); menuUnits->addAction("Outlet Flow" , this, [&] { OpenHelp("units.html#outlet-flow" ); }); menuUnits->addAction("Screen" , this, [&] { OpenHelp("units.html#screen" ); }); menuUnits->addAction("Splitter" , this, [&] { OpenHelp("units.html#splitter" ); }); menuUnits->addAction("Time Delay" , this, [&] { OpenHelp("units.html#time-delay" ); }); // Solvers QMenu* menuSolvers = ui.menuDocumentation->addMenu("Solvers"); menuSolvers->addAction("Agglomeration Cell Average", this, [&] { OpenHelp("solver.html#cell-average-solver"); }); menuSolvers->addAction("Agglomeration Fixed Pivot" , this, [&] { OpenHelp("solver.html#fixed-pivot-solver" ); }); menuSolvers->addAction("Agglomeration FFT" , this, [&] { OpenHelp("solver.html#fft-solver" ); }); // Development QMenu* menuDevelopment = ui.menuDocumentation->addMenu("Development"); menuDevelopment->addAction("Configuration of VCProject", this, [&] { OpenHelp("developer.html#configuration-of-visual-studio-project-template"); }); menuDevelopment->addAction("Units Development" , this, [&] { OpenHelp("developer.html#unit-development" ); }); menuDevelopment->addAction("Solvers Development" , this, [&] { OpenHelp("developer.html#solver-development" ); }); // Development - Program Interfaces QMenu* menuInterfaces = menuDevelopment->addMenu("Program Interfaces"); menuInterfaces->addAction("BaseUnit" , this, [&] { OpenHelp("class.html#basic-unit" ); }); menuInterfaces->addAction("Stream" , this, [&] { OpenHelp("class.html#stream" ); }); menuInterfaces->addAction("DAESolver" , this, [&] { OpenHelp("class.html#dae-systems" ); }); menuInterfaces->addAction("ExternalSolver" , this, [&] { OpenHelp("class.html#external-solver" ); }); menuInterfaces->addAction("TransformMatrix" , this, [&] { OpenHelp("class.html#transformation-matrix" ); }); menuInterfaces->addAction("MDMatrix" , this, [&] { OpenHelp("class.html#multidimensional-matrix" ); }); menuInterfaces->addAction("Matrix2D" , this, [&] { OpenHelp("class.html#two-dimensional-matrix" ); }); menuInterfaces->addAction("PSD Functions" , this, [&] { OpenHelp("class.html#particle-size-distribution" ); }); menuInterfaces->addAction("Predefined Constants", this, [&] { OpenHelp("class.html#list-of-universal-constants"); }); // Main ui.menuDocumentation->addAction("Command Line Interface", this, [&] { OpenHelp("first.html#configuration-file" ); }); ui.menuDocumentation->addAction("Convergence" , this, [&] { OpenHelp("theory.html#convergence-methods"); }); } void Dyssol::UpdateMenu() { const QStringList filesList = m_pSettings->value(StrConst::Dyssol_ConfigRecentParamName).toStringList(); for (int i = 0; i < filesList.size(); ++i) { const std::wstring cleanFileName = CH5Handler::DisplayFileName(std::filesystem::path{ filesList[i].toStdWString() }).wstring(); const QString displayFileName = QFileInfo(QString::fromStdWString(cleanFileName)).fileName(); QString displayText = tr("&%1 %2").arg(i + 1).arg(displayFileName); m_vRecentFilesActions[i]->setText(displayText); m_vRecentFilesActions[i]->setData(filesList[i]); m_vRecentFilesActions[i]->setVisible(true); } // hide empty for (int i = filesList.size(); i < MAX_RECENT_FILES; ++i) m_vRecentFilesActions[i]->setVisible(false); } void Dyssol::SaveToFile(const QString& _sFileName) const { if (_sFileName.isEmpty()) return; QApplication::setOverrideCursor(Qt::WaitCursor); m_pSavingWindow->SetFileName(_sFileName); m_pSavingWindow->show(); m_pSavingWindow->raise(); m_pSavingThread->SetFileName(_sFileName); m_pSavingThread->Run(); } void Dyssol::LoadFromFile(const QString& _sFileName) const { QApplication::setOverrideCursor(Qt::WaitCursor); m_pLoadingWindow->SetFileName(QString::fromStdWString(CH5Handler::DisplayFileName(std::filesystem::path{ _sFileName.toStdWString() }).wstring())); m_pLoadingWindow->show(); m_pLoadingWindow->raise(); m_pLoadingThread->SetFileName(_sFileName); m_pLoadingThread->Run(); } void Dyssol::SetCurrFlowsheetFile(const QString& _fileName) { const QString newFile = !_fileName.isEmpty() ? QFileInfo(_fileName).absoluteFilePath() : ""; if (newFile == m_sCurrFlowsheetFile) return; m_sCurrFlowsheetFile = newFile; AddFileToRecentList(m_sCurrFlowsheetFile); const QString sWinNamePrefix = QString(StrConst::Dyssol_MainWindowName); if (!m_sCurrFlowsheetFile.isEmpty()) setWindowTitle(sWinNamePrefix + " - " + QString::fromStdWString(CH5Handler::DisplayFileName(m_sCurrFlowsheetFile.toStdWString()).wstring()) + "[*]"); else setWindowTitle(sWinNamePrefix); if (!m_sCurrFlowsheetFile.isEmpty()) m_pSettings->setValue(StrConst::Dyssol_ConfigLastParamName, m_sCurrFlowsheetFile); } void Dyssol::AddFileToRecentList(const QString& _fileToAdd) { if (_fileToAdd.isEmpty()) return; QStringList filesList = m_pSettings->value(StrConst::Dyssol_ConfigRecentParamName).toStringList(); // get the list of recent files filesList.removeAll(_fileToAdd); // remove all occurrences of the file itself if (filesList.size() == MAX_RECENT_FILES) // max amount of recent files reached filesList.pop_back(); // remove the oldest file filesList.push_front(_fileToAdd); // put the file to the list as the first one m_pSettings->setValue(StrConst::Dyssol_ConfigRecentParamName, filesList); // write down updated list to the file UpdateMenu(); } bool Dyssol::CheckAndAskUnsaved() { if (m_Flowsheet.IsEmpty() || !IsFlowsheetModified()) return true; const QMessageBox::StandardButtons buttons = QMessageBox::Yes | QMessageBox::Cancel | QMessageBox::No; const QMessageBox::StandardButton reply = QMessageBox::question(this, StrConst::Dyssol_MainWindowName, StrConst::Dyssol_SaveMessageBoxText, buttons); if (reply == QMessageBox::Yes) if(!SaveAndWait()) return false; return reply != QMessageBox::Cancel; } bool Dyssol::SaveAndWait() { SaveFlowsheet(); // wait until the end of saving QEventLoop loop; QTimer timer; connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); while (m_pSavingThread->IsRunning()) { timer.start(200); loop.exec(); } return m_pSavingThread->IsSuccess(); } void Dyssol::CloseDyssol(int _errCode /*= 0*/) { QCoreApplication::exit(_errCode); } void Dyssol::SetFlowsheetModified(bool _bModified) { m_bFlowsheetChanged = _bModified; setWindowModified(_bModified); } bool Dyssol::IsFlowsheetModified() const { return m_bFlowsheetChanged; } void Dyssol::LoadMaterialsDatabase() { const QVariant mdbPath = m_pSettings->value(StrConst::Dyssol_ConfigDMDBPath); if (!mdbPath.isValid()) return; m_MaterialsDatabase.LoadFromFile(mdbPath.toString().toStdWString()); // try to load as from absolute path if (m_MaterialsDatabase.CompoundsNumber() == 0) // loaded MDB is empty { const QString sPath = QCoreApplication::applicationDirPath() + "/" + mdbPath.toString(); // get relative path m_MaterialsDatabase.LoadFromFile(sPath.toStdWString()); // try to load as from relative path if (m_MaterialsDatabase.CompoundsNumber() != 0) m_pSettings->setValue(StrConst::Dyssol_ConfigDMDBPath, sPath); // save full path to config file } else m_pSettings->setValue(StrConst::Dyssol_ConfigDMDBPath, mdbPath.toString()); // save used path to config file } size_t Dyssol::OtherRunningDyssolCount() { #ifdef _MSC_VER return SystemFunctions::ActiveInstancesCount(StringFunctions::String2WString(std::string(StrConst::Dyssol_ApplicationName) + ".exe")) - 1; #else // HACK // TODO: implement for Linux to allow proper cache cleaning return 1; #endif } void Dyssol::setVisible(bool _visible) { QMainWindow::setVisible(_visible); if (_visible) UpdateWholeView(); } void Dyssol::LoadRecentFile() { auto* pAction = qobject_cast<QAction*>(sender()); if (!pAction) return; if (!CheckAndAskUnsaved()) return; const QString newFile = pAction->data().toString(); if (newFile == m_sCurrFlowsheetFile) return; LoadFromFile(newFile); SetFlowsheetModified(false); } void Dyssol::NewFlowsheet() { if (!CheckAndAskUnsaved()) return; SetFlowsheetModified(true); m_Flowsheet.Clear(); SetCurrFlowsheetFile(""); UpdateWholeView(); emit NewFlowsheetLoaded(); } void Dyssol::OpenFlowsheet() { if (!CheckAndAskUnsaved()) return; const QString sFileName = QFileDialog::getOpenFileName(this, StrConst::Dyssol_DialogOpenName, m_sCurrFlowsheetFile, StrConst::Dyssol_DialogDflwFilter); if (sFileName.isEmpty()) return; LoadFromFile(sFileName); SetFlowsheetModified(false); } void Dyssol::SaveFlowsheet() { if (!m_sCurrFlowsheetFile.isEmpty()) SaveToFile(m_sCurrFlowsheetFile); else SaveFlowsheetAs(); } void Dyssol::SaveFlowsheetAs() { const QString sFileName = QFileDialog::getSaveFileName(this, StrConst::Dyssol_DialogSaveName, m_sCurrFlowsheetFile, StrConst::Dyssol_DialogDflwFilter); SaveToFile(sFileName); } void Dyssol::SaveScriptFile() { const QString filePath = QString::fromStdWString(CH5Handler::DisplayFileName(std::filesystem::path{ m_sCurrFlowsheetFile.toStdWString() }).wstring()); const QString txtFileName = QFileInfo(filePath).absolutePath() + "/" + QFileInfo(filePath).baseName() + ".txt"; const QString sFileName = QFileDialog::getSaveFileName(this, StrConst::Dyssol_DialogSaveConfigName, txtFileName, StrConst::Dyssol_DialogTxtFilter); QApplication::setOverrideCursor(Qt::WaitCursor); ScriptInterface::ExportScript(sFileName.toStdWString(), m_sCurrFlowsheetFile.toStdWString(), m_Flowsheet, m_ModelsManager, m_MaterialsDatabase); QApplication::restoreOverrideCursor(); } void Dyssol::SaveGraphFile() { const QString filePath = QString::fromStdWString(CH5Handler::DisplayFileName(std::filesystem::path{ m_sCurrFlowsheetFile.toStdWString() }).wstring()); const QString outFileName = QFileInfo(filePath).absolutePath() + "/" + QFileInfo(filePath).baseName() + ".dot"; const QString outFile = QFileDialog::getSaveFileName(this, StrConst::Dyssol_DialogSaveGraphName, outFileName, StrConst::Dyssol_DialogGraphFilter); QApplication::setOverrideCursor(Qt::WaitCursor); std::ofstream file(outFile.toStdString()); file << m_Flowsheet.GenerateDOTFile(); file.close(); QApplication::restoreOverrideCursor(); } void Dyssol::SaveGraphImage() { const QString filePath = QString::fromStdWString(CH5Handler::DisplayFileName(std::filesystem::path{ m_sCurrFlowsheetFile.toStdWString() }).wstring()); const QString outFileName = QFileInfo(filePath).absolutePath() + "/" + QFileInfo(filePath).baseName() + ".png"; const QString outFile = QFileDialog::getSaveFileName(this, StrConst::Dyssol_DialogSaveImageName, outFileName, StrConst::Dyssol_DialogPNGFilter); QApplication::setOverrideCursor(Qt::WaitCursor); m_Flowsheet.GeneratePNGFile(outFile.toStdString()); QApplication::restoreOverrideCursor(); } void Dyssol::SavingFinished() { if(m_pSavingThread->IsSuccess()) { SetCurrFlowsheetFile(m_pSavingThread->GetFinalFileName()); SetFlowsheetModified(false); } else { QString message = "Unable to save the flowsheet to the file:\n'" + m_pSavingThread->GetFileName(); if (FileSystem::IsWriteProtected(FileSystem::FilePath(m_pSavingThread->GetFileName().toStdWString()))) message += "'\nThe selected path may be write-protected."; QMessageBox::warning(this, StrConst::Dyssol_MainWindowName, message); } m_pSavingThread->Stop(); m_pSavingWindow->accept(); QApplication::restoreOverrideCursor(); } void Dyssol::LoadingFinished() { if (m_pLoadingThread->IsSuccess()) SetCurrFlowsheetFile(m_pLoadingThread->GetFinalFileName()); m_pLoadingThread->Stop(); UpdateWholeView(); emit NewFlowsheetLoaded(); m_pLoadingWindow->accept(); QApplication::restoreOverrideCursor(); if (!m_pLoadingThread->IsSuccess()) QMessageBox::warning(this, StrConst::Dyssol_MainWindowName, "Unable to load the selected file\n" + m_pLoadingThread->GetFileName()); } void Dyssol::OpenHelp(const QString& _link) const { QDesktopServices::openUrl(QUrl(StrConst::Dyssol_HelpURL + _link)); } void Dyssol::ShowAboutDialog() { CAboutWindow about(this); about.exec(); } void Dyssol::SlotSaveAndReopen() { SaveAndWait(); m_Flowsheet.Clear(); LoadFromFile(m_sCurrFlowsheetFile); } void Dyssol::SlotRestart() { if (CheckAndAskUnsaved()) CloseDyssol(Dyssol::EXIT_CODE_REBOOT); } void Dyssol::SlotClearCache() { if (!CheckAndAskUnsaved()) return; while (OtherRunningDyssolCount()) { const auto reply = QMessageBox::warning(this, "Clear cache", tr("%1 other instances of Dyssol are still running. Close them to proceed.").arg(OtherRunningDyssolCount()), QMessageBox::Retry | QMessageBox::Cancel); if (reply == QMessageBox::Cancel) return; } ClearCache(); CloseDyssol(EXIT_CODE_REBOOT); } void Dyssol::FlowsheetStateChanged() { SetFlowsheetModified(true); } void Dyssol::BlockUI(bool _block) const { for (int i = 0; i < ui.mainTabWidget->count(); ++i) if (i != SIMULATOR_TAB) ui.mainTabWidget->setTabEnabled(i, !_block); ui.menuFile->setEnabled(!_block); ui.menuFlowsheet->setEnabled(!_block); ui.menuModules->setEnabled(!_block); ui.menuTools->setEnabled(!_block); }
48.967877
283
0.709535
FlowsheetSimulation
999000843154b495752896330056fdbb948c91cb
848
hh
C++
src/core/include/chase/utilities/UtilityFunctions.hh
chase-cps/chase
87db0754bf0eaa94beb10c355794b6d3c6d9e883
[ "BSD-3-Clause" ]
4
2019-06-15T15:33:37.000Z
2022-02-10T19:10:50.000Z
src/core/include/chase/utilities/UtilityFunctions.hh
chase-cps/chase
87db0754bf0eaa94beb10c355794b6d3c6d9e883
[ "BSD-3-Clause" ]
null
null
null
src/core/include/chase/utilities/UtilityFunctions.hh
chase-cps/chase
87db0754bf0eaa94beb10c355794b6d3c6d9e883
[ "BSD-3-Clause" ]
3
2018-02-02T18:14:48.000Z
2021-01-31T12:18:25.000Z
/** * @author <a href="mailto:michele.lora@univr.it">Michele Lora</a> * @date 11/21/2019 * This project is released under the 3-Clause BSD License. * */ #pragma once #include <vector> #include <list> #include <string> namespace chase { /// \todo Document it!!! template< typename T > void getSubsetBySize( std::vector< T > elements, unsigned int size, unsigned int left, unsigned int index, std::vector< T >& combination, std::list< std::vector<T> > &results); template<> void getSubsetBySize( std::vector< std::string > elements, unsigned int size, unsigned int left, unsigned int index, std::vector< std::string >& combination, std::list< std::vector<std::string> > &results); }
21.2
72
0.571934
chase-cps
9998ceca97a817bbfb946fbd05e4e6f4b58d4c89
6,682
cpp
C++
src/collisionDetection/test/RayVsPlaneTest.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
5
2015-10-11T10:22:39.000Z
2019-07-24T10:09:13.000Z
src/collisionDetection/test/RayVsPlaneTest.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
null
null
null
src/collisionDetection/test/RayVsPlaneTest.cpp
Robograde/Robograde
2c9a7d0b8250ec240102d504127f5c54532cb2b0
[ "Zlib" ]
null
null
null
/************************************************** Zlib Copyright 2015 Ola Enberg ***************************************************/ #include <gtest/gtest.h> #include "../volume/Ray.h" #include "../volume/Plane.h" #include "../detection/IntersectionTestLookupTable.h" using glm::vec3; TEST( CollisionTests, RayVsPlane_OutsideTowards ) { Ray ray; ray.Position = vec3( 1.0f, 7.0f, 2.0f ); ray.Direction = glm::normalize( vec3( 0.0f, -1.0f, 0.0f ) ); Plane plane; plane.Position = vec3( 30.0f, 0.0f, -50.0f ); plane.Normal = glm::normalize( vec3( 0.0f, 1.0f, 0.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_TRUE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); EXPECT_EQ( vec3( 1.0f, 0.0f, 2.0f ), intersectionPoint ); } TEST( CollisionTests, RayVsPlane_OutsideAway ) { Ray ray; ray.Position = vec3( 0.0f, 7.0f, 0.0f ); ray.Direction = glm::normalize( vec3( 0.0f, 1.0f, 0.0f ) ); Plane plane; plane.Position = vec3( 30.0f, 0.0f, -50.0f ); plane.Normal = glm::normalize( vec3( 0.0f, 1.0f, 0.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_FALSE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); } TEST( CollisionTests, RayVsPlane_OutsideParallel ) { Ray ray; ray.Position = vec3( 3.0f, -4.0f, 8.0f ); ray.Direction = glm::normalize( vec3( -1.0f, 0.0f, 0.0f ) ); Plane plane; plane.Position = vec3( 75.0f, 5.0f, -23.0f ); plane.Normal = glm::normalize( vec3( 0.0f, -1.0f, 0.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_FALSE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); } TEST( CollisionTests, RayVsPlane_InsideDiving ) { Ray ray; ray.Position = vec3( 27.0f, 7.0f, -5.0f ); ray.Direction = glm::normalize( vec3( -1.0f, 1.0f, 0.0f ) ); Plane plane; plane.Position = vec3( 30.0f, 56.0f, -53.0f ); plane.Normal = glm::normalize( vec3( 1.0f, 0.0f, 0.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_FALSE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); } TEST( CollisionTests, RayVsPlane_InsideSurfacing ) { Ray ray; ray.Position = vec3( 27.0f, 7.0f, -5.0f ); ray.Direction = glm::normalize( vec3( 1.0f, 1.0f, 0.0f ) ); Plane plane; plane.Position = vec3( 30.0f, 56.0f, -53.0f ); plane.Normal = glm::normalize( vec3( 1.0f, 0.0f, 0.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_FALSE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); } TEST( CollisionTests, RayVsPlane_InsideParallel ) { Ray ray; ray.Position = vec3( 27.0f, 7.0f, -5.0f ); ray.Direction = glm::normalize( vec3( 0.0f, 0.0f, -1.0f ) ); Plane plane; plane.Position = vec3( 30.0f, 56.0f, -53.0f ); plane.Normal = glm::normalize( vec3( 1.0f, 0.0f, 0.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_FALSE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); } TEST( CollisionTests, RayVsPlane_SurfaceDiving ) { Ray ray; ray.Position = vec3( 31.0f, -5.0f, -3.0f ); ray.Direction = glm::normalize( vec3( -1.0f, 0.0f, 1.0f ) ); Plane plane; plane.Position = vec3( -13.0f, 7.0f, -3.0f ); plane.Normal = glm::normalize( vec3( 0.0f, 0.0f, -1.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_TRUE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); EXPECT_EQ( ray.Position, intersectionPoint ); } TEST( CollisionTests, RayVsPlane_SurfaceLeaving ) { Ray ray; ray.Position = vec3( 31.0f, -5.0f, -3.0f ); ray.Direction = glm::normalize( vec3( -1.0f, 0.0f, -1.0f ) ); Plane plane; plane.Position = vec3( -13.0f, 7.0f, -3.0f ); plane.Normal = glm::normalize( vec3( 0.0f, 0.0f, -1.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_FALSE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); } TEST( CollisionTests, RayVsPlane_SurfaceParallel ) { Ray ray; ray.Position = vec3( 31.0f, -5.0f, -3.0f ); ray.Direction = glm::normalize( vec3( 3.0f, -5.0f, 0.0f ) ); Plane plane; plane.Position = vec3( -13.0f, 7.0f, -3.0f ); plane.Normal = glm::normalize( vec3( 0.0f, 0.0f, -1.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_FALSE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); } TEST( CollisionTests, RayVsPlane_OutsideRayDiagonal ) { Ray ray; ray.Position = vec3( 0.0f, 4.0f, 0.0f ); ray.Direction = glm::normalize( vec3( 1, -1.0f, -1.0f ) ); Plane plane; plane.Position = vec3( -17.0f, 2.0f, 11.0f ); plane.Normal = glm::normalize( vec3( 0.0f, 1.0f, 0.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_TRUE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); EXPECT_EQ( vec3( 2.0f, 2.0f, -2.0f ), intersectionPoint ); } TEST( CollisionTests, RayVsPlane_OutsidePlaneDiagonal ) { Ray ray; ray.Position = vec3( 0.0f, 4.0f, 0.0f ); ray.Direction = glm::normalize( vec3( 0, -1.0f, 0.0f ) ); Plane plane; plane.Position = vec3( 0.0f, 2.0f, 0.0f ); plane.Normal = glm::normalize( vec3( -1.0f, 1.0f, 2.0f ) ); IntersectionTestLookupTable testLookup; IntersectionTestFunction intersectionTestFunction = testLookup.Fetch( ray.GetVolumeType(), plane.GetVolumeType() ); vec3 intersectionPoint; EXPECT_TRUE( (*intersectionTestFunction)( &ray, &plane, &intersectionPoint ) ); EXPECT_EQ( vec3( 0.0f, 2.0f, 0.0f ), intersectionPoint ); }
31.370892
116
0.702335
Robograde
99a0753b4771d939c747ecc609e07c735eaf893c
13,267
cpp
C++
modules/tracktion_engine/3rd_party/airwindows/Focus/FocusProc.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
734
2018-11-16T09:39:40.000Z
2022-03-30T16:56:14.000Z
modules/tracktion_engine/3rd_party/airwindows/Focus/FocusProc.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
100
2018-11-16T18:04:08.000Z
2022-03-31T17:47:53.000Z
modules/tracktion_engine/3rd_party/airwindows/Focus/FocusProc.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
123
2018-11-16T15:51:50.000Z
2022-03-29T12:21:27.000Z
/* ======================================== * Focus - Focus.h * Copyright (c) 2016 airwindows, All rights reserved * ======================================== */ #ifndef __Focus_H #include "Focus.h" #endif void Focus::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames) { float* in1 = inputs[0]; float* in2 = inputs[1]; float* out1 = outputs[0]; float* out2 = outputs[1]; //[0] is frequency: 0.000001 to 0.499999 is near-zero to near-Nyquist //[1] is resonance, 0.7071 is Butterworth. Also can't be zero double boost = pow(10.0,(A*12.0)/20.0); figureL[0] = figureR[0] = 3515.775/getSampleRate(); //fixed frequency, 3.515775k figureL[1] = figureR[1] = pow(pow(B,3)*2,2)+0.0001; //resonance int mode = (int) ( C * 4.999 ); double output = D; double wet = E; double K = tan(M_PI * figureR[0]); double norm = 1.0 / (1.0 + K / figureR[1] + K * K); figureL[2] = figureR[2] = K / figureR[1] * norm; figureL[4] = figureR[4] = -figureR[2]; figureL[5] = figureR[5] = 2.0 * (K * K - 1.0) * norm; figureL[6] = figureR[6] = (1.0 - K / figureR[1] + K * K) * norm; while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-37) inputSampleL = fpd * 1.18e-37; if (fabs(inputSampleR)<1.18e-37) inputSampleR = fpd * 1.18e-37; long double drySampleL = inputSampleL; long double drySampleR = inputSampleR; inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR); //encode Console5: good cleanness long double tempSample = (inputSampleL * figureL[2]) + figureL[7]; figureL[7] = -(tempSample * figureL[5]) + figureL[8]; figureL[8] = (inputSampleL * figureL[4]) - (tempSample * figureL[6]); inputSampleL = tempSample; tempSample = (inputSampleR * figureR[2]) + figureR[7]; figureR[7] = -(tempSample * figureR[5]) + figureR[8]; figureR[8] = (inputSampleR * figureR[4]) - (tempSample * figureR[6]); inputSampleR = tempSample; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //without this, you can get a NaN condition where it spits out DC offset at full blast! inputSampleL = asin(inputSampleL); inputSampleR = asin(inputSampleR); //decode Console5 long double groundSampleL = drySampleL - inputSampleL; //set up UnBox long double groundSampleR = drySampleR - inputSampleR; //set up UnBox inputSampleL *= boost; //now, focussed area gets cranked before distort inputSampleR *= boost; //now, focussed area gets cranked before distort switch (mode) { case 0: //Density if (inputSampleL > 1.570796326794897) inputSampleL = 1.570796326794897; if (inputSampleL < -1.570796326794897) inputSampleL = -1.570796326794897; if (inputSampleR > 1.570796326794897) inputSampleR = 1.570796326794897; if (inputSampleR < -1.570796326794897) inputSampleR = -1.570796326794897; //clip to 1.570796326794897 to reach maximum output inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR); break; case 1: //Drive if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleL -= (inputSampleL * (fabs(inputSampleL) * 0.6) * (fabs(inputSampleL) * 0.6)); inputSampleR -= (inputSampleR * (fabs(inputSampleR) * 0.6) * (fabs(inputSampleR) * 0.6)); inputSampleL *= 1.6; inputSampleR *= 1.6; break; case 2: //Spiral if (inputSampleL > 1.2533141373155) inputSampleL = 1.2533141373155; if (inputSampleL < -1.2533141373155) inputSampleL = -1.2533141373155; if (inputSampleR > 1.2533141373155) inputSampleR = 1.2533141373155; if (inputSampleR < -1.2533141373155) inputSampleR = -1.2533141373155; //clip to 1.2533141373155 to reach maximum output inputSampleL = sin(inputSampleL * fabs(inputSampleL)) / ((inputSampleL == 0.0) ?1:fabs(inputSampleL)); inputSampleR = sin(inputSampleR * fabs(inputSampleR)) / ((inputSampleR == 0.0) ?1:fabs(inputSampleR)); break; case 3: //Mojo long double mojo; mojo = pow(fabs(inputSampleL),0.25); if (mojo > 0.0) inputSampleL = (sin(inputSampleL * mojo * M_PI * 0.5) / mojo) * 0.987654321; mojo = pow(fabs(inputSampleR),0.25); if (mojo > 0.0) inputSampleR = (sin(inputSampleR * mojo * M_PI * 0.5) / mojo) * 0.987654321; //mojo is the one that flattens WAAAAY out very softly before wavefolding break; case 4: //Dyno long double dyno; dyno = pow(fabs(inputSampleL),4); if (dyno > 0.0) inputSampleL = (sin(inputSampleL * dyno) / dyno) * 1.1654321; dyno = pow(fabs(inputSampleR),4); if (dyno > 0.0) inputSampleR = (sin(inputSampleR * dyno) / dyno) * 1.1654321; //dyno is the one that tries to raise peak energy break; } if (output != 1.0) { inputSampleL *= output; inputSampleR *= output; } inputSampleL += groundSampleL; //effectively UnBox inputSampleR += groundSampleR; //effectively UnBox if (wet !=1.0) { inputSampleL = (inputSampleL * wet) + (drySampleL * (1.0-wet)); inputSampleR = (inputSampleR * wet) + (drySampleR * (1.0-wet)); } //begin 32 bit stereo floating point dither int expon; frexpf((float)inputSampleL, &expon); fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSampleL += ((double(fpd)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62)); frexpf((float)inputSampleR, &expon); fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSampleR += ((double(fpd)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62)); //end 32 bit stereo floating point dither *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } } void Focus::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames) { double* in1 = inputs[0]; double* in2 = inputs[1]; double* out1 = outputs[0]; double* out2 = outputs[1]; //[0] is frequency: 0.000001 to 0.499999 is near-zero to near-Nyquist //[1] is resonance, 0.7071 is Butterworth. Also can't be zero double boost = pow(10.0,(A*12.0)/20.0); figureL[0] = figureR[0] = 3515.775/getSampleRate(); //fixed frequency, 3.515775k figureL[1] = figureR[1] = pow(pow(B,3)*2,2)+0.0001; //resonance int mode = (int) ( C * 4.999 ); double output = D; double wet = E; double K = tan(M_PI * figureR[0]); double norm = 1.0 / (1.0 + K / figureR[1] + K * K); figureL[2] = figureR[2] = K / figureR[1] * norm; figureL[4] = figureR[4] = -figureR[2]; figureL[5] = figureR[5] = 2.0 * (K * K - 1.0) * norm; figureL[6] = figureR[6] = (1.0 - K / figureR[1] + K * K) * norm; while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-43) inputSampleL = fpd * 1.18e-43; if (fabs(inputSampleR)<1.18e-43) inputSampleR = fpd * 1.18e-43; long double drySampleL = inputSampleL; long double drySampleR = inputSampleR; inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR); //encode Console5: good cleanness long double tempSample = (inputSampleL * figureL[2]) + figureL[7]; figureL[7] = -(tempSample * figureL[5]) + figureL[8]; figureL[8] = (inputSampleL * figureL[4]) - (tempSample * figureL[6]); inputSampleL = tempSample; tempSample = (inputSampleR * figureR[2]) + figureR[7]; figureR[7] = -(tempSample * figureR[5]) + figureR[8]; figureR[8] = (inputSampleR * figureR[4]) - (tempSample * figureR[6]); inputSampleR = tempSample; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //without this, you can get a NaN condition where it spits out DC offset at full blast! inputSampleL = asin(inputSampleL); inputSampleR = asin(inputSampleR); //decode Console5 long double groundSampleL = drySampleL - inputSampleL; //set up UnBox long double groundSampleR = drySampleR - inputSampleR; //set up UnBox inputSampleL *= boost; //now, focussed area gets cranked before distort inputSampleR *= boost; //now, focussed area gets cranked before distort switch (mode) { case 0: //Density if (inputSampleL > 1.570796326794897) inputSampleL = 1.570796326794897; if (inputSampleL < -1.570796326794897) inputSampleL = -1.570796326794897; if (inputSampleR > 1.570796326794897) inputSampleR = 1.570796326794897; if (inputSampleR < -1.570796326794897) inputSampleR = -1.570796326794897; //clip to 1.570796326794897 to reach maximum output inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR); break; case 1: //Drive if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleL -= (inputSampleL * (fabs(inputSampleL) * 0.6) * (fabs(inputSampleL) * 0.6)); inputSampleR -= (inputSampleR * (fabs(inputSampleR) * 0.6) * (fabs(inputSampleR) * 0.6)); inputSampleL *= 1.6; inputSampleR *= 1.6; break; case 2: //Spiral if (inputSampleL > 1.2533141373155) inputSampleL = 1.2533141373155; if (inputSampleL < -1.2533141373155) inputSampleL = -1.2533141373155; if (inputSampleR > 1.2533141373155) inputSampleR = 1.2533141373155; if (inputSampleR < -1.2533141373155) inputSampleR = -1.2533141373155; //clip to 1.2533141373155 to reach maximum output inputSampleL = sin(inputSampleL * fabs(inputSampleL)) / ((inputSampleL == 0.0) ?1:fabs(inputSampleL)); inputSampleR = sin(inputSampleR * fabs(inputSampleR)) / ((inputSampleR == 0.0) ?1:fabs(inputSampleR)); break; case 3: //Mojo long double mojo; mojo = pow(fabs(inputSampleL),0.25); if (mojo > 0.0) inputSampleL = (sin(inputSampleL * mojo * M_PI * 0.5) / mojo) * 0.987654321; mojo = pow(fabs(inputSampleR),0.25); if (mojo > 0.0) inputSampleR = (sin(inputSampleR * mojo * M_PI * 0.5) / mojo) * 0.987654321; //mojo is the one that flattens WAAAAY out very softly before wavefolding break; case 4: //Dyno long double dyno; dyno = pow(fabs(inputSampleL),4); if (dyno > 0.0) inputSampleL = (sin(inputSampleL * dyno) / dyno) * 1.1654321; dyno = pow(fabs(inputSampleR),4); if (dyno > 0.0) inputSampleR = (sin(inputSampleR * dyno) / dyno) * 1.1654321; //dyno is the one that tries to raise peak energy break; } if (output != 1.0) { inputSampleL *= output; inputSampleR *= output; } inputSampleL += groundSampleL; //effectively UnBox inputSampleR += groundSampleR; //effectively UnBox if (wet !=1.0) { inputSampleL = (inputSampleL * wet) + (drySampleL * (1.0-wet)); inputSampleR = (inputSampleR * wet) + (drySampleR * (1.0-wet)); } //begin 64 bit stereo floating point dither int expon; frexp((double)inputSampleL, &expon); fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSampleL += ((double(fpd)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62)); frexp((double)inputSampleR, &expon); fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5; inputSampleR += ((double(fpd)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62)); //end 64 bit stereo floating point dither *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } }
46.550877
118
0.56584
jbloit
99a2a08f3001b30c684ca712865606c3c7b0c336
600
cpp
C++
src/Particle.cpp
towa7bc/SFMLParticleAnimation
685cc0fc12a8b40ea7dc682f468de4962cb2ae93
[ "Unlicense" ]
null
null
null
src/Particle.cpp
towa7bc/SFMLParticleAnimation
685cc0fc12a8b40ea7dc682f468de4962cb2ae93
[ "Unlicense" ]
null
null
null
src/Particle.cpp
towa7bc/SFMLParticleAnimation
685cc0fc12a8b40ea7dc682f468de4962cb2ae93
[ "Unlicense" ]
null
null
null
// // Created by Michael Wittmann on 05/06/2020. // #include "Particle.hpp" #include <SFML/Graphics/PrimitiveType.hpp> // for Points #include <SFML/Graphics/RenderTarget.hpp> // for RenderTarget namespace app { void Particle::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(&draw_vertex_, 1, sf::Points, states); } void Particle::updateDrawVertexColorAlpha(const sf::Uint8 &alpha) { draw_vertex_.color.a = static_cast<sf::Uint8>(draw_vertex_.color.a - alpha); } void Particle::updateVelocity(const sf::Vector2f &vel) { velocity_ += vel; } } // namespace app
27.272727
78
0.728333
towa7bc
99a365de7422f1a18975644823c97142882c4a72
1,885
hpp
C++
ML_Weapons/CFG/cfgRecoils.hpp
linus-berg/Mafia-Life
d9b7678c02738e8e555ebf068fa4c0e5170ffa5e
[ "MIT" ]
null
null
null
ML_Weapons/CFG/cfgRecoils.hpp
linus-berg/Mafia-Life
d9b7678c02738e8e555ebf068fa4c0e5170ffa5e
[ "MIT" ]
null
null
null
ML_Weapons/CFG/cfgRecoils.hpp
linus-berg/Mafia-Life
d9b7678c02738e8e555ebf068fa4c0e5170ffa5e
[ "MIT" ]
2
2019-08-31T19:04:38.000Z
2022-03-29T02:59:43.000Z
#define Xcoef (0.001) #define Ycoef (0.004) #define LynxXcoef (0.003) #define LynxYcoef (0.008) class cfgRecoils { recoil_single_Test_rifle_01[]= { 0,0,0, 0.03, 36.943*(Xcoef)*(0.3), 3.587*(Ycoef)*(3), 0.03, 31.817*(Xcoef)*(0.5), 1.251*(Ycoef)*(3.4), 0.03, 19.755*(Xcoef)*(0.7), 0.764*(Ycoef)*(3.8), 0.06, 7.388*(Xcoef)*(0.9), 0.285*(Ycoef)*(4.2), 0.06, -2.402*(Xcoef)*(0.3), -0.096*(Ycoef)*(7), 0.06, -3.53*(Xcoef)*(0.5), -0.141*(Ycoef)*(5), 0.06, -3.677*(Xcoef)*(0.5), -0.147*(Ycoef)*(3), 0.06, -3.138*(Xcoef)*(0.3), -0.125*(Ycoef)*(1), 0.06, 0, 0 }; recoil_single_prone_Test_rifle_01[]= { 0,0,0, 0.03, 36.943*(Xcoef)*(0.3), 3.587*(Ycoef)*(0.7), 0.03, 31.817*(Xcoef)*(0.5), 1.251*(Ycoef)*(1.1), 0.03, 19.755*(Xcoef)*(0.7), 0.764*(Ycoef)*(1.5), 0.06, 7.388*(Xcoef)*(0.9), 0.285*(Ycoef)*(1.9), 0.06, -2.402*(Xcoef)*(0.3), -0.096*(Ycoef)*(2), 0.06, -3.53*(Xcoef)*(0.5), -0.141*(Ycoef)*(1), 0.06, -3.677*(Xcoef)*(0.5), -0.147*(Ycoef)*(0.5), 0.06, -3.138*(Xcoef)*(0.3), -0.125*(Ycoef)*(0.3), 0.06, 0, 0 }; recoil_auto_Test_rifle_01[]= { 0,0,0, 0.06, 36.943*(Xcoef)*(1.2), 3.587*(Ycoef)*(1.7), 0.06, 31.817*(Xcoef)*(1.5), 1.251*(Ycoef)*(2.1), 0.06, 19.755*(Xcoef)*(1.7), 0.764*(Ycoef)*(2.4), 0.06, 7.388*(Xcoef)*(1.9), 0.285*(Ycoef)*(2.8), 0.03, -2.402*(Xcoef)*(0.3), -0.096*(Ycoef)*(7), 0.03, -3.53*(Xcoef)*(0.5), -0.141*(Ycoef)*(5), 0.03, -3.677*(Xcoef)*(0.5), -0.147*(Ycoef)*(3), 0.06, 0, 0 }; recoil_auto_prone_Test_rifle_01[]= { 0,0,0, 0.06, 36.943*(Xcoef)*(1.2), 3.587*(Ycoef)*(0.3), 0.06, 31.817*(Xcoef)*(1.5), 1.251*(Ycoef)*(0.7), 0.06, 19.755*(Xcoef)*(1.7), 0.764*(Ycoef)*(1.1), 0.06, 7.388*(Xcoef)*(1.9), 0.285*(Ycoef)*(1.5), 0.03, -2.402*(Xcoef)*(0.3), -0.096*(Ycoef)*(4), 0.03, -3.53*(Xcoef)*(0.5), -0.141*(Ycoef)*(2), 0.03, -3.677*(Xcoef)*(0.5), -0.147*(Ycoef)*(1), 0.06, 0, 0 }; };
31.949153
52
0.517772
linus-berg
99a94de9fec99a1f9fe70da5cbb6722f71d6fa36
594
hpp
C++
frame/message.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
frame/message.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
frame/message.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
// frame/message.hpp // // Copyright (c) 2013 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #ifndef SOLID_FRAME_SIGNAL_HPP #define SOLID_FRAME_SIGNAL_HPP #include "frame/common.hpp" #include "utility/dynamictype.hpp" #include <string> namespace solid{ namespace frame{ struct Message: Dynamic<Message>{ Message(); virtual ~Message(); }; }//namespace frame }//namespace solid #endif
19.16129
89
0.739057
joydit
99aaa798f6f2e9110767ba49b98ef332ba4e5105
49,213
cpp
C++
dualarm_controller/Control/Controller.cpp
hyujun/DualArm_Sim
5a0eea7cfec45b4db8f097dbcfb101ecdc1ce7e1
[ "MIT" ]
2
2021-03-26T04:41:02.000Z
2021-12-10T13:36:59.000Z
dualarm_controller/Control/Controller.cpp
hyujun/DualArm_Sim
5a0eea7cfec45b4db8f097dbcfb101ecdc1ce7e1
[ "MIT" ]
null
null
null
dualarm_controller/Control/Controller.cpp
hyujun/DualArm_Sim
5a0eea7cfec45b4db8f097dbcfb101ecdc1ce7e1
[ "MIT" ]
2
2021-03-26T04:41:02.000Z
2021-03-26T04:43:26.000Z
/* * Controller.cpp * * Created on: 2019. 5. 15. * Author: Junho Park */ #include "Controller.h" #include <utility> namespace HYUControl { Controller::Controller():m_Jnum(6) { this->pManipulator = nullptr; } Controller::Controller(std::shared_ptr<SerialManipulator> Manipulator) { this->pManipulator = Manipulator; m_Jnum = this->pManipulator->GetTotalDoF(); Kp.resize(m_Jnum); Kp.setConstant(KpBase); Kd.resize(m_Jnum); Kd.setConstant(KdBase); Ki.resize(m_Jnum); Ki.setConstant(KiBase); K_Hinf.resize(m_Jnum); K_Hinf.setConstant(HinfBase); KpTask.resize(6*this->pManipulator->GetTotalChain()); KdTask.resize(6*this->pManipulator->GetTotalChain()); KiTask.resize(6*this->pManipulator->GetTotalChain()); KpImp.setZero(6*this->pManipulator->GetTotalChain()); KdImp.setZero(6*this->pManipulator->GetTotalChain()); Kp_elbow.setZero(6*this->pManipulator->GetTotalChain()); Kd_elbow.setZero(6*this->pManipulator->GetTotalChain()); KpImpNull.setZero(m_Jnum); KdImpNull.setZero(m_Jnum); e.setZero(m_Jnum); e_dev.setZero(m_Jnum); e_int.setZero(m_Jnum); e_int_sat.setZero(m_Jnum); eTask.setZero(6*this->pManipulator->GetTotalChain()); eTask2.setZero(6*this->pManipulator->GetTotalChain()); edotTask.setZero(6*this->pManipulator->GetTotalChain2()); edotTask2.setZero(6*this->pManipulator->GetTotalChain2()); edotTmp.setZero(6*this->pManipulator->GetTotalChain(), 6*this->pManipulator->GetTotalChain()); FrictionTorque.setZero(m_Jnum); #if defined(__SIMULATION__) GainWeightFactor.resize(m_Jnum); GainWeightFactor.setConstant(15.0); dq.setZero(m_Jnum); dqdot.setZero(m_Jnum); dqddot.setZero(m_Jnum); dq_old.setZero(m_Jnum); KpImp.setConstant(12,2000000000000); KdImp.setConstant(12,100000000); KpImpNull.setConstant(16, 0.01); KdImpNull.setConstant(16,0.1); Kp_elbow.setZero(12); Kp_elbow(4)=50; Kp_elbow(10)=50; Kd_elbow.setZero(12); Kd_elbow(4)=2.5; Kd_elbow(10)=2.5; #else GainWeightFactor.setZero(m_Jnum); GainWeightFactor.setConstant(15.0); Kp = GainWeightFactor*KpBase; Kd = GainWeightFactor*KdBase; Ki = GainWeightFactor*KiBase; dq.resize(m_Jnum); dqdot.resize(m_Jnum); dqddot.resize(m_Jnum); dq_old.setZero(m_Jnum); KpImp.setConstant(12,2000000000000.0); KdImp.setConstant(12,10000000000.0); KpImpNull.setConstant(16,0.01); KdImpNull.setConstant(16,0.1); Kp_elbow.setConstant(12,100); Kp_elbow(4)=200; Kp_elbow(10)=200; Kd_elbow.setConstant(12,10); #endif } Controller::~Controller() { } void Controller::ClearError(void) { e.setZero(); e_dev.setZero(); e_int.setZero(); return; } void Controller::SetPIDGain(double &_Kp, double &_Kd, double &_Hinf, int &_JointNum) { Kp(_JointNum-1) = _Kp; Kd(_JointNum-1) = _Kd; K_Hinf(_JointNum-1) = _Hinf; } void Controller::SetPIDGain( VectorXd &_Kp, VectorXd &_Kd, VectorXd &_Ki, VectorXd &_Kinf ) { K_Hinf = _Kinf; Kp = _Kinf.cwiseProduct(_Kp); Kd = _Kinf.cwiseProduct(_Kd); Ki = _Kinf.cwiseProduct(_Ki); } void Controller::GetPIDGain(double *_Kp, double *_Kd, double *_Hinf, int &_JointNum) { _JointNum = this->m_Jnum; Map<VectorXd>(_Kp, this->m_Jnum) = Kp; Map<VectorXd>(_Kd, this->m_Jnum) = Kd; Map<VectorXd>(_Hinf, this->m_Jnum) = K_Hinf; } void Controller::GetPIDGain(VectorXd &_Kp, VectorXd &_Kd, VectorXd &_Ki) { _Kp = Kp; _Kd = Kd; _Ki = Ki; } void Controller::SetCLIKGain(const double &_Kp_Translation, const double &_Kp_Rotation) { for(int i=0; i<pManipulator->GetTotalChain(); i++) { KpTask.segment(6*i,3) = _Kp_Rotation*Vector3d::Ones(); KpTask.segment(6*i+3, 3) = _Kp_Translation*Vector3d::Ones(); } } void Controller::SetTaskspaceGain(const VectorXd &_KpTask, const VectorXd &_KdTask) { KpTask.setZero(12); KdTask.setZero(12); KpTask = _KpTask; KdTask = _KdTask; } void Controller::SetImpedanceGain( const VectorXd &_Kp_Imp, const VectorXd &_Kd_Imp, const VectorXd &_Kp_Imp_Null, const VectorXd &_Kd_Imp_Null, const VectorXd &_des_m ) { KpImp = _Kp_Imp; KdImp = _Kd_Imp; KpImpNull = _Kp_Imp_Null; KdImpNull = _Kd_Imp_Null; mass_shaped = _des_m; } void Controller::GetControllerStates(VectorXd &_dq, VectorXd &_dqdot, VectorXd &_ErrTask) { _dq = dq; _dqdot = dqdot; _ErrTask = eTask; } void Controller::GetControllerStates2(VectorXd &_dq, VectorXd &_dqdot, VectorXd &_ErrTask) { _dq = dq; _dqdot = dqdot; _ErrTask = eTask2; } void Controller::PDController( const VectorXd &_q, const VectorXd &_qdot, const VectorXd &_dq, const VectorXd &_dqdot, VectorXd &_Toq) { e = _dq - _q; e_dev = _dqdot - _qdot; _Toq.setZero(m_Jnum); _Toq.noalias() += Kp.cwiseProduct(e); _Toq.noalias() += Kd.cwiseProduct(e_dev); } void Controller::PDGravController( const VectorXd &_q, const VectorXd &_qdot, const VectorXd &_dq, const VectorXd &_dqdot, VectorXd &_Toq ) { pManipulator->pDyn->G_Matrix(G); e = _dq - _q; e_dev = _dqdot - _qdot; FrictionCompensator(_qdot, _dqdot); _Toq = G; _Toq.noalias() += Kp.cwiseProduct(e); _Toq.noalias() += Kd.cwiseProduct(e_dev); #if !defined(__SIMULATION__) _Toq.noalias() += FrictionTorque; #endif } void Controller::InvDynController(const VectorXd &_q, const VectorXd &_qdot, const VectorXd &_dq, const VectorXd &_dqdot, const VectorXd &_dqddot, VectorXd &_Toq, const double &_dt ) { pManipulator->pDyn->MG_Mat_Joint(M, G); //pManipulator->pDyn->G_Matrix(G); dq_old = _dq; e = _dq - _q; e_dev = _dqdot - _qdot; e_int += e*_dt; for(int i = 0;i<m_Jnum;i++) e_int(i) = tanh(e_int(i)); // FrictionCompensator(_qdot, _dqdot); FrictionCompensator2( _dqdot); VectorXd u0; u0.setZero(m_Jnum); u0.noalias() += _dqddot; u0.noalias() += Kd.cwiseProduct(e_dev); u0.noalias() += Kp.cwiseProduct(e); // u0.noalias() += Ki.cwiseProduct(e_int); _Toq = G; _Toq.noalias() += M*u0; // _Toq.noalias() += FrictionTorque; #if !defined(__SIMULATION__) //_Toq.noalias() += FrictionTorque; #endif } void Controller::InvDynController2(const VectorXd &_q, const VectorXd &_qdot, const VectorXd &_dq, const VectorXd &_dqdot, const VectorXd &_dqddot, VectorXd &_Toq, VectorXd &_frictionToq, const double &_dt ) { pManipulator->pDyn->MG_Mat_Joint(M, G); //pManipulator->pDyn->G_Matrix(G); dq_old = _dq; e = _dq - _q; e_dev = _dqdot - _qdot; e_int += e*_dt*0.1; // for(int i = 0;i<m_Jnum;i++) // e_int(i) = tanh(e_int(i)); // FrictionCompensator(_qdot, _dqdot); FrictionCompensator2( _dqdot); VectorXd u0; u0.setZero(m_Jnum); u0.noalias() += _dqddot; u0.noalias() += Kd.cwiseProduct(e_dev); u0.noalias() += Kp.cwiseProduct(e); u0.noalias() += Ki.cwiseProduct(e_int); _Toq = G; _Toq.noalias() += M*u0; // _Toq.noalias() += FrictionTorque; _frictionToq = FrictionTorque; #if !defined(__SIMULATION__) //_Toq.noalias() += FrictionTorque; #endif } void Controller::TaskInvDynController( Cartesiand *_dx, const VectorXd &_dxdot, const VectorXd &_dxddot, const VectorXd &_q, const VectorXd &_qdot, VectorXd &_Toq, const double &_dt, const int mode) { pManipulator->pDyn->MG_Mat_Joint(M, G); if( mode == 1 ) // Regulation { MatrixXd J; pManipulator->pKin->GetAnalyticJacobian(J); MatrixXd ScaledJT; pManipulator->pKin->GetScaledTransJacobian(ScaledJT); MatrixXd pInvJ; pManipulator->pKin->GetpinvJacobian(pInvJ); TaskError(_dx, _dxddot, _qdot, eTask, edotTask); VectorXd u0; u0.setZero(16); u0.noalias() += KpTask.cwiseProduct(eTask); u0.noalias() += -KdTask.cwiseProduct(J*_qdot); //MatrixXd mat_tmp = Matrix<double, 16, 16>::Identity(); //mat_tmp.noalias() += -J.transpose()*J; //VectorXd q0dot; //alpha=5.0; //pManipulator->pKin->Getq0dotWithMM(alpha, q0dot); _Toq = G; _Toq.noalias() += ScaledJT*u0; //_Toq.noalias() += pInvJ*u0; //_Toq.noalias() += mat_tmp*q0dot; } else if( mode == 2 ) //tracking { MatrixXd ScaledJT; pManipulator->pKin->GetScaledTransJacobian(ScaledJT); pManipulator->pKin->GetScaledTransJacobian(ScaledJT); MatrixXd Jdot; pManipulator->pKin->GetAnalyticJacobianDot(_qdot, Jdot); MatrixXd DpInvJ; pManipulator->pKin->GetDampedpInvJacobian(DpInvJ); TaskError(_dx, _dxddot, _qdot, eTask, edotTask); Matrix<double, 12, 1> uTask; uTask = _dxddot; uTask.noalias() += -Jdot*_qdot; uTask.noalias() += KdTask.cwiseProduct(edotTask); uTask.noalias() += KpTask.cwiseProduct(eTask); MatrixXd u0 = Matrix<double, 16,1>::Zero(); //u0.noalias() += DpInvJ*uTask; u0.noalias() += ScaledJT*uTask; _Toq = G; _Toq.noalias() += M*u0; } } void Controller::TaskError( Cartesiand *_dx, const VectorXd &_dxdot, const VectorXd &_qdot, VectorXd &_error_x, VectorXd &_error_xdot ) { _error_x.setZero(6*2); _error_xdot.setZero(6*2); int EndJoint[2] = {9, 16}; SE3 aSE3; SO3 dSO3; Vector3d eOrient; double theta; for(int i=0; i<2; i++) { //dSO3 = _dx[i].r; aSE3 = pManipulator->pKin->GetForwardKinematicsSE3(EndJoint[i]); //pManipulator->pKin->SO3toRollPitchYaw(aSE3.block(0,0,3,3).transpose()*dSO3, eOrient); //pManipulator->pKin->LogSO3(aSE3.block(0,0,3,3).transpose()*dSO3, eOrient,theta); //_error_x.segment(6*i,3) = eOrient; //Matrix3d SO3Tmp = aSE3.block(0,0,3,3).transpose()*dSO3; //Quaterniond eSO3; //eSO3 = SO3Tmp; Quaterniond q_d; q_d = _dx[i].r; Quaterniond q_a; q_a = pManipulator->pKin->GetForwardKinematicsSO3(EndJoint[i]); Vector3d e_orientation; Vector3d e_orientation2; Vector3d qd_vec; Vector3d qa_vec; qd_vec = q_d.vec(); qa_vec = q_a.vec(); double e_orientation1; e_orientation1 = q_a.w()*q_d.w()+qa_vec.transpose()*q_d.vec(); e_orientation = q_d.w()*q_a.vec() - q_a.w()*q_d.vec() + SkewMatrix(qd_vec)*q_a.vec(); //_error_x.segment(6*i,3) = eSO3.vec(); _error_x.segment(6*i,3) = -e_orientation; _error_x.segment(6*i+3,3) = _dx[i].p - aSE3.block(0,3,3,1); } MatrixXd AnalyticJac; pManipulator->pKin->GetAnalyticJacobian(AnalyticJac); _error_xdot = _dxdot; _error_xdot.noalias() += -AnalyticJac*_qdot; } void Controller::TaskError2( Cartesiand *_dx, const VectorXd &_dxdot, const VectorXd &_qdot, VectorXd &_error_x, VectorXd &_error_xdot ,Quaterniond _q_R,Quaterniond _q_L, Vector3d _TargetPos_Linear_R, Vector3d _TargetPos_Linear_L) { _error_x.setZero(6*2); _error_xdot.setZero(6*2); int EndJoint[2] = {9, 16}; SE3 aSE3; SO3 dSO3; Vector3d eOrient; double theta; for(int i=0; i<2; i++) { aSE3 = pManipulator->pKin->GetForwardKinematicsSE3(EndJoint[i]); Quaterniond q_d; if(i ==0) { q_d = _q_R; _error_x.segment(6 * i + 3, 3) = _TargetPos_Linear_R - aSE3.block(0, 3, 3, 1); } else { q_d = _q_L; _error_x.segment(6 * i + 3, 3) = _TargetPos_Linear_L - aSE3.block(0, 3, 3, 1); } Quaterniond q_a; q_a = pManipulator->pKin->GetForwardKinematicsSO3(EndJoint[i]); if (q_d.coeffs().dot(q_a.coeffs()) < 0.0) { q_a.coeffs() << -q_a.coeffs(); } Vector3d e_orientation; Vector3d qd_vec; Vector3d qa_vec; qd_vec = q_d.vec(); qa_vec = q_a.vec(); e_orientation = q_d.w()*q_a.vec() - q_a.w()*q_d.vec() + SkewMatrix(qd_vec)*q_a.vec(); _error_x.segment(6*i,3) = -e_orientation; } MatrixXd AnalyticJac; pManipulator->pKin->GetAnalyticJacobian(AnalyticJac); _error_xdot = _dxdot; _error_xdot.noalias() += -AnalyticJac*_qdot; // std::cout<<_error_xdot<<std::endl; // std::cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<<std::endl; } void Controller::TaskError3( const VectorXd &_dxdot2, const VectorXd &_qdot, VectorXd &_error_x2, VectorXd &_error_xdot2 , Vector3d _TargetPos_Linear_R2, Vector3d _TargetPos_Linear_L2) { _error_x2.setZero(6*2); _error_xdot2.setZero(6*2); int EndJoint[2] = {6, 13}; SE3 aSE3; SO3 dSO3; Vector3d eOrient; double theta; MatrixXd AnalyticJac2; MatrixXd ZERO(6,2); ZERO<< 0,0,0,0,0,0,0,0,0,0,0,0; pManipulator->pKin->GetAnalyticJacobian(AnalyticJac2); AnalyticJac2.block(0,7,6,2) = ZERO; AnalyticJac2.block(6,14,6,2)= ZERO; for(int i=0; i<2; i++) { aSE3 = pManipulator->pKin->GetForwardKinematicsSE3(EndJoint[i]); // std::cout << aSE3 << std::endl; if(i ==0) { _error_x2.segment(6 * i + 3, 3) = _TargetPos_Linear_R2 - aSE3.block(0, 3, 3, 1); } else { _error_x2.segment(6 * i + 3, 3) = _TargetPos_Linear_L2 - aSE3.block(0, 3, 3, 1); } } // std::cout << _error_x2 << std::endl; // std::cout << AnalyticJac2 << std::endl; // std::cout << aSE3 << std::endl; _error_xdot2 = _dxdot2; _error_xdot2.noalias() += -AnalyticJac2*_qdot; // std::cout << _error_xdot2 << std::endl; // std::cout << AnalyticJac2*_qdot << std::endl; } void Controller::TaskRelativeError( Cartesiand *_dx, const VectorXd &_dxdot, const VectorXd &_qdot, VectorXd &_error_x, VectorXd &_error_xdot ) { _error_x.setZero(6*2); _error_xdot.setZero(6*2); int EndJoint[2] = {9, 16}; SE3 aSE3, aSE3_Rel; SO3 dSO3; MatrixXd AnalyticJac, RelativeJac; Vector3d eOrient; dSO3 = _dx[0].r; aSE3 = pManipulator->pKin->GetForwardKinematicsSE3(EndJoint[0]); pManipulator->pKin->SO3toRollPitchYaw(aSE3.block(0,0,3,3).transpose()*dSO3, eOrient); _error_x.segment(0,3) = eOrient; _error_x.segment(3,3) = _dx[0].p - aSE3.block(0,3,3,1); dSO3 = _dx[1].r; aSE3_Rel.setZero(); aSE3_Rel.noalias() += inverse_SE3(aSE3)*pManipulator->pKin->GetForwardKinematicsSE3(EndJoint[1]); pManipulator->pKin->SO3toRollPitchYaw(aSE3_Rel.block(0,0,3,3).transpose()*dSO3, eOrient); _error_x.segment(6,3) = eOrient; _error_x.segment(9,3) = _dx[1].p - aSE3_Rel.block(0,3,3,1); pManipulator->pKin->GetAnalyticJacobian(AnalyticJac); _error_xdot.head(6) = _dxdot.head(6); _error_xdot.head(6).noalias() += -AnalyticJac.block(0,0,6,16)*_qdot; pManipulator->pKin->GetRelativeJacobian(RelativeJac); _error_xdot.tail(6) = _dxdot.tail(6); _error_xdot.tail(6).noalias() += -RelativeJac*_qdot; } void Controller::CLIKTaskController( const VectorXd &_q, const VectorXd &_qdot, Cartesiand *_dx, const VectorXd &_dxdot, const VectorXd &_sensor, VectorXd &_Toq, const double &_dt, const int mode ) { dq.setZero(16); dqdot.setZero(16); dqddot.setZero(16); pManipulator->pKin->GetAnalyticJacobian(AnalyticJacobian); pManipulator->pKin->GetpinvJacobian(pInvJacobian); alpha = 10.0; if( mode == 7 ) { TaskRelativeError(_dx, _dxdot, _qdot, eTask, edotTask); } else { TaskError(_dx, _dxdot, _qdot, eTask, edotTask); } Vector_temp = _dxdot; Vector_temp.noalias() += KpTask.cwiseProduct(eTask); if(mode == 1) // jacobian pseudoinverse { pManipulator->pKin->Getq0dotWithMM(alpha, q0dot); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvJacobian*AnalyticJacobian; dqdot.noalias() += pInvJacobian*Vector_temp; dqdot.noalias() += Matrix_temp*q0dot; } else if(mode == 2) // jacobian transpose { pManipulator->pKin->Getq0dotWithMM(alpha, q0dot); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvJacobian*AnalyticJacobian; dqdot.noalias() += AnalyticJacobian.transpose()*Vector_temp; dqdot.noalias() += Matrix_temp*q0dot; } else if(mode == 3) // Damped jacobian pseudoinverse { pManipulator->pKin->Getq0dotWithMM(alpha, q0dot); pManipulator->pKin->GetDampedpInvJacobian(DampedpInvJacobian); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvJacobian*AnalyticJacobian; dqdot.noalias() += DampedpInvJacobian*Vector_temp; dqdot.noalias() += Matrix_temp*q0dot; } else if(mode == 4) // scaled jacobian transpose { pManipulator->pKin->Getq0dotWithMM(alpha, q0dot); pManipulator->pKin->GetScaledTransJacobian(ScaledTransJacobian); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvJacobian*AnalyticJacobian; dqdot.noalias() += ScaledTransJacobian*Vector_temp; dqdot.noalias() += Matrix_temp*q0dot; } else if(mode == 5) // block jacobian pseudoinverse { pManipulator->pKin->Getq0dotWithMM(alpha, q0dot); pManipulator->pKin->GetBlockpInvJacobian(BlockpInvJacobian); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -BlockpInvJacobian*AnalyticJacobian; dqdot.noalias() += BlockpInvJacobian*Vector_temp; dqdot.noalias() += Matrix_temp*q0dot; } else if(mode == 6) // weight damped jacobian pseudoinverse with task priority { MatrixXd weight; weight.setIdentity(16,16); //pManipulator->pDyn->M_Matrix(weight); //pManipulator->pKin->Getq0dotWithMM(alpha, q0dot); VectorXd dx_tmp(12); Quaterniond q_tmp; q_tmp = _dx[0].r; dx_tmp.segment(0,3) = q_tmp.vec(); dx_tmp.segment(3,3) = _dx[0].p; q_tmp = _dx[1].r; dx_tmp.segment(6,3) = q_tmp.vec(); dx_tmp.segment(9,3) = _dx[1].p; pManipulator->pKin->GetWeightDampedpInvJacobian(dx_tmp, weight, WdampedpInvJacobian); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -WdampedpInvJacobian*AnalyticJacobian; dqdot.noalias() += WdampedpInvJacobian*Vector_temp; //dqdot.noalias() += Matrix_temp*q0dot; } else if(mode == 7) // relative jacobian { pManipulator->pKin->GetRelativeJacobian(RelJacobian); AJacwithRel = AnalyticJacobian; AJacwithRel.block(6,0,6,16) = RelJacobian; pManipulator->pKin->GetDampedpInvJacobian(AJacwithRel, dpInvRelJacobian); dqdot.noalias() += dpInvRelJacobian*Vector_temp; } else { pManipulator->pKin->Getq0dotWithMM(alpha, q0dot); pManipulator->pKin->GetDampedpInvJacobian(DampedpInvJacobian); dqdot.noalias() += DampedpInvJacobian*Vector_temp; dqdot.noalias() += Matrix_temp*q0dot; } dq = dq_old + dqdot * _dt; InvDynController(_q, _qdot, dq, dqdot, dqddot, _Toq, _dt); } void Controller::InertiaShaping( const VectorXd &_Mass, MatrixXd &_M_Shaped_inv ) { // ellipsoid volume = 4*M_PI*a*b*c/3 const auto a=0.01; // radius(m) of x-axis const auto b=0.01; // radius(m) of y-axis const auto c=0.01; // radius(m) of z-axis _M_Shaped_inv.setZero(6*_Mass.size(),6*_Mass.size()); _M_Shaped_inv(0,0) = 1.0/(_Mass(0)*(b*b + c*c)/5.0); _M_Shaped_inv(1,1) = 1.0/(_Mass(0)*(a*a + c*c)/5.0); _M_Shaped_inv(2,2) = 1.0/(_Mass(0)*(a*a + b*b)/5.0); _M_Shaped_inv.block(3,3,3,3).noalias() += Matrix<double, 3,3>::Identity()/_Mass(0); _M_Shaped_inv(6,6) = 1.0/(_Mass(1)*(b*b + c*c)/5.0); _M_Shaped_inv(7,7) = 1.0/(_Mass(1)*(a*a + c*c)/5.0); _M_Shaped_inv(8,8) = 1.0/(_Mass(1)*(a*a + b*b)/5.0); _M_Shaped_inv.block(9,9,3,3).noalias() += Matrix<double, 3,3>::Identity()/_Mass(1); } void Controller:: TaskImpedanceController(const VectorXd &_q, const VectorXd &_qdot, Cartesiand *_dx, const VectorXd &_dxdot, const VectorXd &_dxddot, const VectorXd &_sensor, VectorXd &_Toq, const int mode) { MatrixXd pInvMat; pManipulator->pDyn->MG_Mat_Joint(M, G); pManipulator->pKin->GetAnalyticJacobian(AnalyticJacobian); pManipulator->pKin->GetAnalyticJacobianDot(_qdot, AnalyticJacobianDot); dqN.setZero(16); dqdotN.setZero(16); alpha = 7.5; if(mode == 1) // Mx = Mx_desired { VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u04 = VectorXd::Zero(AnalyticJacobian.cols()); u01 = _dxddot; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskError(_dx, _dxdot, _qdot, eTask, edotTask); u02.noalias() += KdImp.cwiseProduct(edotTask); u02.noalias() += KpImp.cwiseProduct(eTask); //dqN = 0.5*(pManipulator->pKin->qLimit_High - pManipulator->pKin->qLimit_Low); pManipulator->pKin->Getq0dotWithMM(alpha, dqdotN); //dqdotN.noalias() += -0.5*(pManipulator->pKin->qLimit_Low - _q).cwiseInverse(); //dqdotN.noalias() += 0.5*(_q - pManipulator->pKin->qLimit_High).cwiseInverse(); //u04.noalias() += KpImpNull.cwiseProduct(dqN - _q); u04.noalias() += KdImpNull.cwiseProduct(dqdotN - _qdot); MatrixXd weight; //weight.setIdentity(16,16); weight = M; VectorXd dx_tmp(12); Quaterniond q_tmp; q_tmp = _dx[0].r; dx_tmp.segment(0,3) = q_tmp.vec(); dx_tmp.segment(3,3) = _dx[0].p; q_tmp = _dx[1].r; dx_tmp.segment(6,3) = q_tmp.vec(); dx_tmp.segment(9,3) = _dx[1].p; pManipulator->pKin->GetWeightDampedpInvJacobian(dx_tmp, weight, AnalyticJacobian, pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; _Toq = G; _Toq.noalias() += M*(pInvMat*u01); _Toq.noalias() += AnalyticJacobian.transpose()*u02; _Toq.noalias() += Matrix_temp*u04; VectorXd jobDesired=VectorXd::Zero(16); MatrixXd Kp_job=Eigen::MatrixXd::Identity(16,16);; for(int i=0;i<16;i++) Kp_job(i,i) = 10.0; jobDesired(1) = -20.0*DEGtoRAD; jobDesired(3) = -45.0*DEGtoRAD; jobDesired(3+7) = -jobDesired(3); jobDesired(6) = -90.00*DEGtoRAD; jobDesired(6+7) = -jobDesired(6); _Toq.noalias() += Kp_job*(jobDesired-_q); _Toq.noalias() += Matrix_temp*u04; } else if(mode == 2) // Mx != Mx_desired { MatrixXd MxdInv; InertiaShaping(mass_shaped, MxdInv); pManipulator->pKin->GetDampedpInvJacobian(pInvMat); pManipulator->pDyn->M_Mat_Task(Mx, pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u03 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u04 = VectorXd::Zero(AnalyticJacobian.cols()); u01 = _dxddot ; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskError(_dx, _dxdot, _qdot, eTask, edotTask); u02.noalias() += KdImp.cwiseProduct(edotTask); u02.noalias() += KpImp.cwiseProduct(eTask); MatrixXd M_Shaped = MatrixXd::Zero(AnalyticJacobian.rows(),AnalyticJacobian.rows()); M_Shaped.noalias() += Mx*MxdInv; u03.noalias() += M_Shaped*u02; u03.noalias() += (M_Shaped - MatrixXd::Identity(AnalyticJacobian.rows(),AnalyticJacobian.rows()))*_sensor; dqN = 0.5*(pManipulator->pKin->qLimit_High - pManipulator->pKin->qLimit_Low); pManipulator->pKin->Getq0dotWithMM(alpha, dqdotN); // dqdotN.noalias() += 0.5*(pManipulator->pKin->qLimit_Low - _q).cwiseInverse(); // dqdotN.noalias() += -0.5*(_q - pManipulator->pKin->qLimit_High).cwiseInverse(); u04.noalias() += KpImpNull.cwiseProduct(dqN - _q); u04.noalias() += KdImpNull.cwiseProduct(dqdotN - _qdot); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; _Toq = G; _Toq.noalias() += M*(pInvMat*u01); _Toq.noalias() += AnalyticJacobian.transpose()*u03; _Toq.noalias() += Matrix_temp*u04; } else if(mode == 3) // relative jacobian { pManipulator->pKin->GetRelativeJacobian(RelativeJacobian); pManipulator->pKin->GetRelativeJacobianDot(_qdot, RelativeJacobianDot); AnalyticJacobian.block(6,0,6,16) = RelativeJacobian; AnalyticJacobianDot.block(6,0,6,16) = RelativeJacobianDot; VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u04 = VectorXd::Zero(AnalyticJacobian.cols()); u01 = _dxddot; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskRelativeError(_dx, _dxdot, _qdot, eTask, edotTask); u02.noalias() += KdImp.cwiseProduct(edotTask); u02.noalias() += KpImp.cwiseProduct(eTask); //dqN = 0.5*(pManipulator->pKin->qLimit_High - pManipulator->pKin->qLimit_Low); pManipulator->pKin->Getq0dotWithMM(alpha, dqdotN); //pManipulator->pKin->Getq0dotWithMM_Relative(alpha, AnalyticJacobian, dqdotN); //dqdotN.noalias() += 0.5*(pManipulator->pKin->qLimit_Low - _q).cwiseInverse(); //dqdotN.noalias() += -0.5*(_q - pManipulator->pKin->qLimit_High).cwiseInverse(); //u04.noalias() += KpImpNull.cwiseProduct(dqN - _q); u04.noalias() += KdImpNull.cwiseProduct(dqdotN - _qdot); MatrixXd weight; //weight.setIdentity(16,16); weight = M; VectorXd dx_tmp(12); Quaterniond q_tmp; q_tmp = _dx[0].r; dx_tmp.segment(0,3) = q_tmp.vec(); dx_tmp.segment(3,3) = _dx[0].p; q_tmp = _dx[1].r; dx_tmp.segment(6,3) = q_tmp.vec(); dx_tmp.segment(9,3) = _dx[1].p; pManipulator->pKin->GetWeightDampedpInvJacobian(dx_tmp, weight, AnalyticJacobian, pInvMat); //pManipulator->pKin->GetDampedpInvBlockJacobian(AnalyticJacobian, pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; _Toq = G; _Toq.noalias() += M*(pInvMat*u01); _Toq.noalias() += AnalyticJacobian.transpose()*u02; _Toq.noalias() += Matrix_temp*u04; } else { pManipulator->pKin->GetDampedpInvJacobian(pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); u01 = _dxddot; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskError(_dx, _dxdot, _qdot, eTask, edotTask); u02.noalias() += KdImp.cwiseProduct(edotTask); u02.noalias() += KpImp.cwiseProduct(eTask); _Toq = G; _Toq.noalias() += M*(pInvMat*u01); _Toq.noalias() += AnalyticJacobian.transpose()*u02; } } void Controller:: TaskImpedanceController2(const VectorXd &_q, const VectorXd &_qdot, Cartesiand *_dx, const VectorXd &_dxdot, const VectorXd &_dxddot, const VectorXd &_sensor, VectorXd &_Toq, Quaterniond &_q_R, Quaterniond &_q_L, Vector3d &_Targetpos_Linear_R, Vector3d &_Targetpos_Linear_L, VectorXd &_frictionToq, const int mode) { MatrixXd pInvMat; pManipulator->pDyn->MG_Mat_Joint(M, G); pManipulator->pKin->GetAnalyticJacobian(AnalyticJacobian); // pManipulator->pKin->GetAnalyticJacobian2(AnalyticJacobian2); pManipulator->pKin->GetAnalyticJacobianDot(_qdot, AnalyticJacobianDot); dqN.setZero(16); dqdotN.setZero(16); alpha = 7.5; if(mode == 1) // Mx = Mx_desired { VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u04 = VectorXd::Zero(AnalyticJacobian.cols()); VectorXd u05 = VectorXd::Zero(AnalyticJacobian2.rows()); u01 = _dxddot; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskError2(_dx, _dxdot, _qdot, eTask, edotTask,_q_R,_q_L,_Targetpos_Linear_R,_Targetpos_Linear_L); u02.noalias() += KdImp.cwiseProduct(edotTask); u02.noalias() += KpImp.cwiseProduct(eTask); pManipulator->pKin->Getq0dotWithMM(alpha, dqdotN); u04.noalias() += KdImpNull.cwiseProduct(dqdotN - _qdot); MatrixXd weight; //weight.setIdentity(16,16); weight = M; VectorXd dx_tmp(12); Quaterniond q_tmp; q_tmp = _q_R; dx_tmp.segment(0,3) = q_tmp.vec(); dx_tmp.segment(3,3) = _Targetpos_Linear_R; q_tmp = _q_L; dx_tmp.segment(6,3) = q_tmp.vec(); dx_tmp.segment(9,3) = _Targetpos_Linear_L; pManipulator->pKin->GetWeightDampedpInvJacobian(dx_tmp, weight, AnalyticJacobian, pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; _Toq = G; _Toq.noalias() += M*(pInvMat*u01); _Toq.noalias() += AnalyticJacobian.transpose()*u02; // _Toq.noalias() += Matrix_temp*u04; VectorXd jobDesired=VectorXd::Zero(16); MatrixXd Kp_job=Eigen::MatrixXd::Identity(16,16);; for(int i=0;i<16;i++) Kp_job(i,i) = 10.0; jobDesired(1) = -20.0*DEGtoRAD; jobDesired(3) = -45.0*DEGtoRAD; jobDesired(3+7) = -jobDesired(3); jobDesired(6) = -90.00*DEGtoRAD; jobDesired(6+7) = -jobDesired(6); _Toq.noalias() += Kp_job*(jobDesired-_q); // FrictionCompensator2(_qdot); _frictionToq = FrictionTorque; _Toq.noalias() += Matrix_temp*u04; // _Toq.noalias() += FrictionTorque; } else { pManipulator->pKin->GetDampedpInvJacobian(pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); u01 = _dxddot; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskError(_dx, _dxdot, _qdot, eTask, edotTask); u02.noalias() += KdImp.cwiseProduct(edotTask); u02.noalias() += KpImp.cwiseProduct(eTask); _Toq = G; _Toq.noalias() += M*(pInvMat*u01); _Toq.noalias() += AnalyticJacobian.transpose()*u02; } } void Controller:: TaskImpedanceController3(const VectorXd &_q, const VectorXd &_qdot, Cartesiand *_dx, const VectorXd &_dxdot, const VectorXd &_dxdot2,const VectorXd &_dxddot, const VectorXd &_sensor, VectorXd &_Toq, Quaterniond &_q_R, Quaterniond &_q_L, Vector3d &_Targetpos_Linear_R, Vector3d &_Targetpos_Linear_L, Vector3d &_Targetpos_Linear_R2, Vector3d &_Targetpos_Linear_L2, const int mode, VectorXd emgsig, VectorXd &_Mx, VectorXd &_Kd_emg,VectorXd &_Kp_emg) { MatrixXd pInvMat; pManipulator->pDyn->MG_Mat_Joint(M, G); // std::cout << emgsig(0) << std::endl; pManipulator->pKin->GetAnalyticJacobian(AnalyticJacobian); MatrixXd AnalyticJac2; MatrixXd ZERO(6,2); ZERO<< 0,0,0,0,0,0,0,0,0,0,0,0; pManipulator->pKin->GetAnalyticJacobian(AnalyticJac2); // std::cout << AnalyticJacobian2 << std::endl; for(int i=0; i<2; i++) { if(i ==0) { AnalyticJac2.block(6*i,7,6,2) = ZERO; } else { AnalyticJac2.block(6*i,14,6,2)= ZERO; } } pManipulator->pKin->GetAnalyticJacobianDot(_qdot, AnalyticJacobianDot); dqN.setZero(16); dqdotN.setZero(16); alpha = 7.5; if(mode == 1) // Mx = Mx_desired { pManipulator->pKin->GetDampedpInvJacobian(pInvMat); pManipulator->pDyn->M_Mat_Task(Mx, pInvMat); VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u04 = VectorXd::Zero(AnalyticJacobian.cols()); VectorXd u05 = VectorXd::Zero(AnalyticJacobian.rows()); u01 = _dxddot; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskError2(_dx, _dxdot, _qdot, eTask, edotTask,_q_R,_q_L,_Targetpos_Linear_R,_Targetpos_Linear_L); TaskError3(_dxdot2, _qdot, eTask2, edotTask2,_Targetpos_Linear_R2,_Targetpos_Linear_L2); VectorXd KpImp_emg, KdImp_emg; KpImp_emg.setZero(12); KdImp_emg.setZero(12); for(int i=0; i<3; i++) { emgsig(i)=0; emgsig(i+3)=emgsig(i+3)/Mx(i+3,i+3); // std::cout<<emgsig(i+3)<<std::endl; } for(int i=0; i<3; i++) { emgsig(i+6)=0; emgsig(i+9)=emgsig(i+9)/Mx(i+9,i+9); // std::cout<<emgsig(i+9)<<std::endl; } // for(int i=0; i<12; i++) // { // Mx(i,i); // std::cout<<Mx(i,i)<<std::endl; // } // std::cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<<std::endl; for(int i=0; i<12; i++){ _Mx(i)=Mx(i,i); } // std::cout<<Mx<<std::endl; // std::cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<<std::endl; KpImp_emg= KpImp + emgsig; KdImp_emg= KdImp + (emgsig)/10; // cout<<KpImp_emg<<endl; _Kp_emg=KpImp_emg; _Kd_emg=KdImp_emg; u02.noalias() += KdImp_emg.cwiseProduct(edotTask); u02.noalias() += KpImp_emg.cwiseProduct(eTask); pManipulator->pKin->Getq0dotWithMM(alpha, dqdotN); // u04.noalias() += KpImpNull.cwiseProduct(dqN - _q); u04.noalias() += KdImpNull.cwiseProduct(dqdotN - _qdot); // std::cout << u04<< std::endl; u05.noalias() += Kd_elbow.cwiseProduct(edotTask2); u05.noalias() += Kp_elbow.cwiseProduct(eTask2); // std::cout << u05.segment(3,3) << std::endl; MatrixXd weight; //weight.setIdentity(16,16); weight = M; VectorXd dx_tmp(12); Quaterniond q_tmp; q_tmp = _q_R; dx_tmp.segment(0,3) = q_tmp.vec(); dx_tmp.segment(3,3) = _Targetpos_Linear_R; q_tmp = _q_L; dx_tmp.segment(6,3) = q_tmp.vec(); dx_tmp.segment(9,3) = _Targetpos_Linear_L; pManipulator->pKin->GetWeightDampedpInvJacobian(dx_tmp, weight, AnalyticJacobian, pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; _Toq = G; _Toq.noalias() += M*(pInvMat*u01); _Toq.noalias() += AnalyticJacobian.transpose()*u02; _Toq.noalias() += AnalyticJac2.transpose()*u05; // std::cout <<AnalyticJac2.transpose()*u05 << std::endl; _Toq.noalias() += Matrix_temp*u04; VectorXd jobDesired=VectorXd::Zero(16); MatrixXd Kp_job=Eigen::MatrixXd::Identity(16,16);; for(int i=0;i<16;i++) Kp_job(i,i) = 5.0; jobDesired(1) = -20.0*DEGtoRAD; jobDesired(3) = -45.0*DEGtoRAD; jobDesired(4) = -40.0*DEGtoRAD; jobDesired(4+7) = -jobDesired(4); jobDesired(5) = 30.0*DEGtoRAD; jobDesired(5+7) = -jobDesired(5); jobDesired(3+7) = -jobDesired(3); jobDesired(6) = -90.00*DEGtoRAD; jobDesired(6+7) = -jobDesired(6); _Toq.noalias() += Kp_job*(jobDesired-_q); // FrictionCompensator2(_qdot); _Toq.noalias() += Matrix_temp*u04; // _Toq.noalias() += FrictionTorque; } else if(mode==2) //inertia shape { MatrixXd MxdInv; InertiaShaping(mass_shaped, MxdInv); pManipulator->pKin->GetDampedpInvJacobian(pInvMat); pManipulator->pDyn->M_Mat_Task(Mx, pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u03 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u04 = VectorXd::Zero(AnalyticJacobian.cols()); VectorXd u05 = VectorXd::Zero(AnalyticJacobian.rows()); u01 = _dxddot; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskError2(_dx, _dxdot, _qdot, eTask, edotTask,_q_R,_q_L,_Targetpos_Linear_R,_Targetpos_Linear_L); TaskError3(_dxdot2, _qdot, eTask2, edotTask2,_Targetpos_Linear_R2,_Targetpos_Linear_L2); VectorXd KpImp_emg, KdImp_emg; KpImp_emg.setZero(12); KdImp_emg.setZero(12); KpImp_emg= KpImp + emgsig; KdImp_emg= (KdImp + emgsig)/20; u02.noalias() += KdImp_emg.cwiseProduct(edotTask); u02.noalias() += KpImp_emg.cwiseProduct(eTask); MatrixXd M_Shaped = MatrixXd::Zero(AnalyticJacobian.rows(),AnalyticJacobian.rows()); M_Shaped.noalias() += Mx*MxdInv; u03.noalias() += M_Shaped*u02; u03.noalias() += (M_Shaped - MatrixXd::Identity(AnalyticJacobian.rows(),AnalyticJacobian.rows()))*_sensor; pManipulator->pKin->Getq0dotWithMM(alpha, dqdotN); u04.noalias() += KdImpNull.cwiseProduct(dqdotN - _qdot); u05.noalias() += Kd_elbow.cwiseProduct(edotTask2); u05.noalias() += Kp_elbow.cwiseProduct(eTask2); // std::cout << u05.segment(3,3) << std::endl; MatrixXd weight; weight.setIdentity(16,16); weight = M; VectorXd dx_tmp(12); Quaterniond q_tmp; q_tmp = _q_R; dx_tmp.segment(0,3) = q_tmp.vec(); dx_tmp.segment(3,3) = _Targetpos_Linear_R; q_tmp = _q_L; dx_tmp.segment(6,3) = q_tmp.vec(); dx_tmp.segment(9,3) = _Targetpos_Linear_L; pManipulator->pKin->GetWeightDampedpInvJacobian(dx_tmp, weight, AnalyticJacobian, pInvMat); // std::cout<<pInvMat<<std::endl; Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; _Toq.noalias() += Matrix_temp*u04; VectorXd jobDesired=VectorXd::Zero(16); MatrixXd Kp_job=Eigen::MatrixXd::Identity(16,16);; for(int i=0;i<16;i++) Kp_job(i,i) = 10.0; jobDesired(1) = -20.0*DEGtoRAD; jobDesired(3) = -45.0*DEGtoRAD; jobDesired(4) = -40.0*DEGtoRAD; jobDesired(4+7) = -jobDesired(4); jobDesired(5) = 30.0*DEGtoRAD; jobDesired(5+7) = -jobDesired(5); jobDesired(3+7) = -jobDesired(3); jobDesired(6) = -90.00*DEGtoRAD; jobDesired(6+7) = -jobDesired(6); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; _Toq = G; _Toq.noalias() += M*(pInvMat*u01); // _Toq.noalias() += AnalyticJacobian.transpose()*u03; _Toq.noalias() += Kp_job*(jobDesired-_q); _Toq.noalias() += Matrix_temp*u04; } else { pManipulator->pKin->GetDampedpInvJacobian(pInvMat); Matrix_temp = Eigen::MatrixXd::Identity(16,16); Matrix_temp += -pInvMat*AnalyticJacobian; VectorXd u01 = VectorXd::Zero(AnalyticJacobian.rows()); VectorXd u02 = VectorXd::Zero(AnalyticJacobian.rows()); u01 = _dxddot; u01.noalias() += -AnalyticJacobianDot*_qdot; TaskError(_dx, _dxdot, _qdot, eTask, edotTask); u02.noalias() += KdImp.cwiseProduct(edotTask); u02.noalias() += KpImp.cwiseProduct(eTask); _Toq = G; _Toq.noalias() += M*(pInvMat*u01); _Toq.noalias() += AnalyticJacobian.transpose()*u02; } } double SignFunction(double value) { if (value<0.0f) { return -1.0f; } else if(value>0.0f) { return 1.0f; } else return 0.0f; return 0.0f; } void Controller::FrictionCompensator2( const VectorXd &_dqdot) { FrictionTorque.setZero(m_Jnum); FrictionTorque(0) = 18.3f*0.8*SignFunction(_dqdot(0)); FrictionTorque(1) = 25.6f*0.5*SignFunction(_dqdot(1)); FrictionTorque(2) = 6.8f*SignFunction(_dqdot(2)); FrictionTorque(3) = 4.3f*SignFunction(_dqdot(3)); FrictionTorque(4) = 7.2f*SignFunction(_dqdot(4)); FrictionTorque(5) = 4.08f*SignFunction(_dqdot(5)); FrictionTorque(6) = 4.24f*SignFunction(_dqdot(6)); FrictionTorque(7) = 3.04f*SignFunction(_dqdot(7)); FrictionTorque(8) = 2.56f*SignFunction(_dqdot(8)); FrictionTorque(9) = 9.2f*SignFunction(_dqdot(9)); FrictionTorque(10) = 5.2f*SignFunction(_dqdot(10)); FrictionTorque(11) = 7.0f*SignFunction(_dqdot(11)); FrictionTorque(12) = 4.4*SignFunction(_dqdot(12)); FrictionTorque(13) = 2.4*SignFunction(_dqdot(13)); FrictionTorque(14) = 3.6f*SignFunction(_dqdot(14)); FrictionTorque(15) = 2.24f*SignFunction(_dqdot(15)); } void Controller::FrictionIdentification( const VectorXd &_q, const VectorXd &_qdot, VectorXd &_dq, VectorXd &_dqdot, VectorXd &_dqddot, VectorXd &_Toq, const double &gt ) { GainWeightFactor(4.0); Kp = GainWeightFactor.cwiseProduct(Kp); Kd = GainWeightFactor.cwiseProduct(Kd); _dq.setZero(); _dqdot.setZero(); _dqddot.setZero(); int testjoint = 4; double T, omega, amp; if(InitTime == 0) { InitTime = gt; } else { switch(testjoint) { case 0: T = 29.3; omega = 2.0*M_PI/T; amp = 70; _dq(testjoint) = amp*M_PI/180.0*sin(omega*(gt-InitTime)); _dqdot(testjoint) = amp*M_PI/180.0*omega*cos(omega*(gt-InitTime)); _dqddot(testjoint) = -amp*M_PI/180*pow(omega,2)*sin(omega*(gt-InitTime)); break; case 1: T = 16.7; omega = 2.0*M_PI/T; amp = 40; _dq(testjoint) = amp*M_PI/180.0*sin(omega*(gt-InitTime)+0.8481) - 30*M_PI/180.0; _dqdot(testjoint) = amp*M_PI/180.0*omega*cos(omega*(gt-InitTime)+0.8481); _dqddot(testjoint) = -amp*M_PI/180*pow(omega,2)*sin(omega*(gt-InitTime)+0.8481); break; case 2: T = 20.9; omega = 2.0*M_PI/T; amp = 50; _dq(testjoint) = amp*M_PI/180.0*sin(omega*(gt-InitTime)+0.6435) - 30*M_PI/180.0; _dqdot(testjoint) = amp*M_PI/180.0*omega*cos(omega*(gt-InitTime)+0.6435); _dqddot(testjoint) = -amp*M_PI/180*pow(omega,2)*sin(omega*(gt-InitTime)+0.6435); _dq(testjoint+6) = -_dq(testjoint); _dqdot(testjoint+6) = -_dqdot(testjoint); _dqddot(testjoint+6) = -_dqddot(testjoint); break; case 3: T = 30.0; omega = 2.0*M_PI/T; amp = 50; _dq(testjoint) = amp*M_PI/180.0*sin(omega*(gt-InitTime)+0.4115) - 20*M_PI/180.0; _dqdot(testjoint) = amp*M_PI/180.0*omega*cos(omega*(gt-InitTime)+0.4115); _dqddot(testjoint) = -amp*M_PI/180*pow(omega,2)*sin(omega*(gt-InitTime)+0.4115); _dq(testjoint+6) = -_dq(testjoint); _dqdot(testjoint+6) = -_dqdot(testjoint); _dqddot(testjoint+6) = -_dqddot(testjoint); break; case 4: T = 18.8; omega = 2.0*M_PI/T; amp = 45; _dq(testjoint) = amp*M_PI/180.0*sin(omega*(gt-InitTime)+0.729) - 30*M_PI/180.0; _dqdot(testjoint) = amp*M_PI/180.0*omega*cos(omega*(gt-InitTime)+0.729); _dqddot(testjoint) = -amp*M_PI/180*pow(omega,2)*sin(omega*(gt-InitTime)+0.729); _dq(testjoint+6) = -_dq(testjoint); _dqdot(testjoint+6) = -_dqdot(testjoint); _dqddot(testjoint+6) = -_dqddot(testjoint); break; case 5: T = 29.3; omega = 2.0*M_PI/T; amp = 70.0; _dq(testjoint) = amp*M_PI/180.0*sin(omega*(gt-InitTime)); _dqdot(testjoint) = amp*M_PI/180.0*omega*cos(omega*(gt-InitTime)); _dqddot(testjoint) = -amp*M_PI/180*pow(omega,2)*sin(omega*(gt-InitTime)); _dq(testjoint+6) = _dq(testjoint); _dqdot(testjoint+6) = _dqdot(testjoint); _dqddot(testjoint+6) = _dqddot(testjoint); break; case 6: T = 16.7; omega = 2.0*M_PI/T; amp = 40.0; _dq(testjoint) = amp*M_PI/180.0*sin(omega*(gt-InitTime)); _dqdot(testjoint) = amp*M_PI/180.0*omega*cos(omega*(gt-InitTime)); _dqddot(testjoint) = -amp*M_PI/180*pow(omega,2)*sin(omega*(gt-InitTime)); _dq(testjoint+6) = _dq(testjoint); _dqdot(testjoint+6) = _dqdot(testjoint); _dqddot(testjoint+6) = _dqddot(testjoint); break; case 7: T = 16.7; omega = 2.0*M_PI/T; amp = 40.0; _dq(testjoint) = amp*M_PI/180.0*sin(omega*(gt-InitTime)); _dqdot(testjoint) = amp*M_PI/180.0*omega*cos(omega*(gt-InitTime)); _dqddot(testjoint) = -amp*M_PI/180*pow(omega,2)*sin(omega*(gt-InitTime)); _dq(testjoint+6) = _dq(testjoint); _dqdot(testjoint+6) = _dqdot(testjoint); _dqddot(testjoint+6) = _dqddot(testjoint); break; default: _dq.setZero(); _dqdot.setZero(); _dqddot.setZero(); break; } } pManipulator->pDyn->MG_Mat_Joint(M, G); e = _dq - _q; e_dev = _dqdot - _qdot; FrictionCompensator(_qdot, _dqdot); //ToqOut = M.diagonal().cwiseProduct(dqddot) + Kp.cwiseProduct(e) + Kd.cwiseProduct(e_dev) + G + FrictionTorque; //ToqOut = M.diagonal().cwiseProduct(dqddot) + Kp.cwiseProduct(e) + Kd.cwiseProduct(e_dev) + G; VectorXd u0; u0.setZero(m_Jnum); u0.noalias() += _dqddot; u0.noalias() += Kd.cwiseProduct(e_dev); u0.noalias() += Kp.cwiseProduct(e); _Toq.setZero(m_Jnum); _Toq = G; _Toq.noalias() += M*u0; _Toq.noalias() += FrictionTorque; } void Controller::FrictionCompensator( const VectorXd &_qdot, const VectorXd &_dqdot ) { FrictionTorque.setZero(m_Jnum); for(int i=0; i < this->m_Jnum; i++) { FrictionTorque(i) = frictiontanh[i].a*(tanh(frictiontanh[i].b*_dqdot(i)) - tanh(frictiontanh[i].c*_dqdot(i))) + frictiontanh[i].d*tanh(frictiontanh[i].e*_dqdot(i)) + frictiontanh[i].f*_dqdot(i); } } void Controller::OutputSaturation(double *pInput , double &_MaxInput) { for(int i=0; i<m_Jnum; ++i) { if(pInput[i] <= -_MaxInput) { pInput[i] = -_MaxInput; } else if(pInput[i] >= _MaxInput) { pInput[i] = _MaxInput; } } } } /* namespace HYUCtrl */
32.612989
231
0.586248
hyujun
99ac9b88f6a6f083188018865b7f9971b4126a5b
4,588
cpp
C++
src/gui/tagsystem.cpp
P-Sc/Pirateers
440e477d33bbbcd79d291700c369f74fd0a6cc7d
[ "MIT" ]
null
null
null
src/gui/tagsystem.cpp
P-Sc/Pirateers
440e477d33bbbcd79d291700c369f74fd0a6cc7d
[ "MIT" ]
null
null
null
src/gui/tagsystem.cpp
P-Sc/Pirateers
440e477d33bbbcd79d291700c369f74fd0a6cc7d
[ "MIT" ]
null
null
null
#include "tagsystem.h" #include <SFML/Graphics.hpp> #include "graphics/textures.h" /** * @brief Pfeilrotation berechnen * @param shipPos Position des Schiffes * @return Nötige Rotation für den Pfeil */ float TagSystem::getArrowAngle(sf::Vector2f shipPos) { sf::Vector2f dir = shipPos - cameraCenter; return (atan2(dir.y, dir.x) / M_PI) * 180 + 90; } /** * @brief Schiffsposition auf Kamerarand projezieren * @param shipPos Das Schiff * @param borderOffset Abstand zum Kamerarand (positiv = nach innen) * @return Die projezierte Position */ sf::Vector2f TagSystem::getArrowPos(sf::Vector2f shipPos, float borderOffset) { sf::Vector2f arrowPos = shipPos; arrowPos.x = std::max(arrowPos.x, cameraBounds.left + borderOffset); arrowPos.x = std::min(arrowPos.x, cameraBounds.left + cameraBounds.width - borderOffset); arrowPos.y = std::max(arrowPos.y, cameraBounds.top + borderOffset); arrowPos.y = std::min(arrowPos.y, cameraBounds.top + cameraBounds.height - borderOffset); return arrowPos; } /** * @copydoc GameSystem::update * Komponenten aktualisieren und zeichnen */ void TagSystem::update(float dt) { GameSystem::update(dt); for (unsigned int i = 0; i < componentList.size(); i++) { if (componentList[i].visible) { window->draw(componentList[i].borderRight); window->draw(componentList[i].borderTopRight); window->draw(componentList[i].borderBottomRight); window->draw(componentList[i].borderLeft); window->draw(componentList[i].borderTopLeft); window->draw(componentList[i].borderBottomLeft); window->draw(componentList[i].hullBackgroundBar); window->draw(componentList[i].hullBorderBar); window->draw(componentList[i].hullBar); window->draw(componentList[i].shieldBackgroundBar); window->draw(componentList[i].shieldBorderBar); window->draw(componentList[i].shieldBar); window->draw(componentList[i].energyBackgroundBar); window->draw(componentList[i].energyBorderBar); window->draw(componentList[i].energyBar); if (!cameraBounds.contains(componentList[i].borderLeft.getPosition()) && !cameraBounds.contains(componentList[i].borderRight.getPosition())) { sf::Vector2f shipPos = componentList[i].borderLeft.getPosition() + 0.5f * (componentList[i].borderLeft.getPosition() - componentList[i].borderRight.getPosition()); if (componentList[i].arrow.getScale() != sf::Vector2f(scale, scale)) { componentList[i].arrow.setScale(scale, scale); } componentList[i].arrow.setRotation(getArrowAngle(shipPos)); float offset = componentList[i].arrow.getGlobalBounds().width * 0.3; componentList[i].arrow.setPosition(getArrowPos(shipPos, offset)); window->draw(componentList[i].arrow); } } } } /** * @copydoc GameSystem::notify * - ::evCameraChanged Kameraposition und -skalierung anpassen */ void TagSystem::notify(EventMessage *message) { switch (message->event) { case evCameraChanged: { EventCameraMessage* cameraMessage = (EventCameraMessage*) message; cameraBounds.left = (cameraMessage->center.x - cameraMessage->size.x / 2); cameraBounds.top = (cameraMessage->center.y - cameraMessage->size.y / 2); cameraBounds.width = cameraMessage->size.x; cameraBounds.height = cameraMessage->size.y; cameraCenter.x = cameraMessage->center.x; cameraCenter.y = cameraMessage->center.y; scale = cameraMessage->scale * arrowScale; break; } } delete message;; } Handle *TagSystem::createComponent(TagSettings settings) { Handle* handle = GameSystem::createComponent(settings); editLock.lock(); componentList[indices.get(handle->id)].arrow.setTexture(arrowTexture); componentList[indices.get(handle->id)].arrow.setColor(settings.color); componentList[indices.get(handle->id)].arrow.setOrigin(arrowTexture.getSize().x / 2.f, arrowTexture.getSize().y / 2.f); componentList[indices.get(handle->id)].arrow.scale(arrowScale, arrowScale); editLock.unlock(); return handle; } TagSystem::TagSystem(sf::RenderWindow *window) : window(window), arrowTexture(Textures::get("gui/arrow.png")) { }
39.213675
95
0.645597
P-Sc
99acdd6768b4e7fabc5f494c26ceff05d3c7708a
7,808
cc
C++
Kernel/CG/Coordinates/XYZ.cc
gustavo-castillo-bautista/Mercury
eeb402ccec8e487652229d4595c46ec84f6aefbb
[ "BSD-3-Clause" ]
null
null
null
Kernel/CG/Coordinates/XYZ.cc
gustavo-castillo-bautista/Mercury
eeb402ccec8e487652229d4595c46ec84f6aefbb
[ "BSD-3-Clause" ]
null
null
null
Kernel/CG/Coordinates/XYZ.cc
gustavo-castillo-bautista/Mercury
eeb402ccec8e487652229d4595c46ec84f6aefbb
[ "BSD-3-Clause" ]
null
null
null
//Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved. //For the list of developers, see <http://www.MercuryDPM.org/Team>. // //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 MercuryDPM 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 MERCURYDPM DEVELOPERS TEAM BE LIABLE FOR ANY //DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND //ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS //SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "XYZ.h" #include "Particles/BaseParticle.h" #include "DPMBase.h" using namespace CGCoordinates; void XYZ::writeNames(std::ostream& os) { os << "x y z "; } /*! * \param[out] os the ostream file to which the position is written */ void XYZ::write(std::ostream& os) const { os << p_ << ' '; } /*! * \details If averaged dimensions are present (i.e. for all Coordinates except * XYZ), the CGFunction has to be divided by a factor (here called volume) * due to integrating the variables over the averaged dimensions. * \param[in] min the lower limits of the mesh domain (xMin, yMin, zMin) * \param[in] max the upper limits of the mesh domain (xMax, yMax, zMax) * \return the volume factor */ Mdouble XYZ::getVolumeOfAveragedDimensions(const Vec3D& min UNUSED, const Vec3D& max UNUSED) { return 1.0; } /*! * \param[in] p the position that is to be set. */ void XYZ::setXYZ(Vec3D p) { p_ = p; } /*! * \details This function is needed to evaluate the CGFunction, as this function * has the distance between the CGPoint and the Particle as an argument. To * properly account for the averaging, the distance is only computed in the * non-averaged directions. * \param[in] p the position of a particle for which the distance is computed. */ Mdouble XYZ::getDistanceSquared(const Vec3D& p) const { return Vec3D::getLengthSquared(p_ - p); } /*! * \param[in] p vector whose length should be determined * \return length of the vector in the non-averaged directions * \todo */ Mdouble XYZ::getLength(const Vec3D& p) { return sqrt(p.X * p.X + p.Y * p.Y + p.Z * p.Z); } /*! * \param[in] c the Interaction object from which iNormal is computed * \return iNormal, one of the three distances needed to calculate the line * integral \f$\psi\f$ which defines the stress distribution (see image). * \image html LineIntegral.jpeg Illustration of the line integral */ Mdouble XYZ::getINormal(const BaseInteraction& c, const Vec3D& normal) const { return Vec3D::dot(c.getI()->getPosition() - p_, c.getNormal()); } /*! * \param[in] c the Interaction object from which iNormal is computed * \return pNormal, one of the three distances needed to calculate the line * integral \f$\psi\f$ which defines the stress distribution (see image). * \image html LineIntegral.jpeg Illustration of the line integral */Mdouble XYZ::getPNormal(const BaseInteraction& c, const Vec3D& normal) const { return Vec3D::dot(c.getP()->getPosition() - p_, c.getNormal()); } /*! * \param[in] c the Interaction object from which iNormal is computed * \return cNormal, one of the three distances needed to calculate the line * integral \f$\psi\f$ which defines the stress distribution (see image). * \image html LineIntegral.jpeg Illustration of the line integral */Mdouble XYZ::getCNormal(const BaseInteraction& c, const Vec3D& normal) const { return Vec3D::dot(c.getContactPoint() - p_, c.getNormal()); } /*! * \param[in] c the Interaction object from which iNormal is computed * \param[in] pNormal the output of getPNormal needed for the computation. * \return iNormal, one of the three distances needed to calculate the line * integral \f$\psi\f$ which defines the stress distribution (see image). * \image html LineIntegral.jpeg Illustration of the line integral */ Mdouble XYZ::getTangentialSquared(const BaseInteraction& c, Mdouble pNormal) const { return Vec3D::getLengthSquared(c.getP()->getPosition() - p_) - mathsFunc::square(pNormal); } /*! * \details The prefactor of the Gauss CGFunction is set such that the integral * over the non-averaged dimensions is unity. * \param[in] width width (equals the standard deviation in 1D) of the Gauss CGFunction. * \param[in] cutoff cutoff of the Gauss CGFunction * \return the prefactor of the Gauss CGFunction. */ Mdouble XYZ::getGaussPrefactor(Mdouble width, Mdouble cutoff) { //Wolfram alpha: erf(c/(sqrt(2) w))-(sqrt(2/pi) c e^(-c^2/(2 w^2)))/w Mdouble prefactor = 1.0 / (constants::sqrt_2 * constants::sqrt_pi * width); Mdouble cw = cutoff / width; return mathsFunc::cubic(prefactor) / ( erf(cw / constants::sqrt_2) - constants::sqrt_2 / constants::sqrt_pi * cw * exp(-0.5 * mathsFunc::square(cw)) ); } /*! * \details The prefactor of the Gauss line integral is set such that the integral * over the non-averaged dimensions is unity. * \param[in] distance length of the branch vector along which the line integral is evaluated. * \param[in] width width (equals the standard deviation in 1D) of the Gauss CGFunction. * \param[in] cutoff cutoff of the Gauss CGFunction * \return the prefactor of the Gauss CGFunction. */ Mdouble XYZ::getGaussIntegralPrefactor(Mdouble distance, Mdouble width, Mdouble cutoff) { Mdouble widthSqrt2 = width * constants::sqrt_2; Mdouble a = -cutoff; Mdouble b = cutoff + distance; //full 2D prefactor Mdouble prefactor = 1.0 / (constants::sqrt_2 * constants::sqrt_pi * width); prefactor = mathsFunc::square(prefactor) / (1.0 - exp(-0.5 * mathsFunc::square(cutoff / width))); return prefactor * 0.5 / ( +erf(b / widthSqrt2) * b + widthSqrt2 / constants::sqrt_pi * exp(-mathsFunc::square(b / widthSqrt2)) - erf(a / widthSqrt2) * a - widthSqrt2 / constants::sqrt_pi * exp(-mathsFunc::square(a / widthSqrt2)) ); } /*! * \details The volume is computed as * \f[volume= \int_0^1\sum_{i=1}^n c_i r/c^i 4 pi r^2 dr = 4 pi \sum_{i=1}^n c_i/(i+3) \f] * with 4 pi r^2 the surface area of a sphere. * \param[in,out] coefficients the coefficients of Polynomial CGFunctions. * \param[in] cutoff cutoff of the Gauss CGFunction */ void XYZ::normalisePolynomialCoefficients(std::vector<Mdouble>& coefficients, Mdouble cutoff) { Mdouble volume = 0.0; for (std::size_t i = 0; i < coefficients.size(); i++) volume += coefficients[i] / static_cast<Mdouble>(i + 3); volume *= 4.0 * constants::pi * mathsFunc::cubic(cutoff); for (double& coefficient : coefficients) coefficient /= volume; } const unsigned XYZ::countVariables() { return 3; } std::string XYZ::getName() { return "XYZ"; }
39.04
101
0.712602
gustavo-castillo-bautista
99ada3ad22ec0443d474129f91af9ec8abbf082f
3,261
cpp
C++
src/leakfile.cpp
isRyven/map-compiler
c2f22acf6c02c33fea2609e0b69521eaf91a7033
[ "MIT" ]
3
2018-02-14T16:02:45.000Z
2019-02-27T13:31:12.000Z
src/leakfile.cpp
isRyven/map-compiler
c2f22acf6c02c33fea2609e0b69521eaf91a7033
[ "MIT" ]
30
2018-02-12T13:49:48.000Z
2018-10-19T17:23:15.000Z
src/leakfile.cpp
isRyven/map-compiler
c2f22acf6c02c33fea2609e0b69521eaf91a7033
[ "MIT" ]
1
2018-02-13T16:26:16.000Z
2018-02-13T16:26:16.000Z
/* ------------------------------------------------------------------------------- Copyright (C) 1999-2007 id Software, Inc. and contributors. For a list of contributors, see the accompanying CONTRIBUTORS file. This file is part of GtkRadiant. GtkRadiant 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. GtkRadiant is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GtkRadiant; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ---------------------------------------------------------------------------------- This code has been altered significantly from its original form, to support several games based on the Quake III Arena engine, in the form of "Q3Map2." ------------------------------------------------------------------------------- */ /* marker */ #define LEAKFILE_C /* dependencies */ #include "q3map2.h" /* ============================================================================== LEAK FILE GENERATION Save out name.lin for qe3 to read ============================================================================== */ /* ============= LeakFile Finds the shortest possible chain of portals that leads from the outside leaf to a specifically occupied leaf TTimo: builds a polyline xml node ============= */ void LeakFile( tree_t *tree, const char *filename ){ vec3_t mid; FILE *linefile; node_t *node; int count; //xmlNodePtr xml_node, point; if ( !tree->outside_node.occupied ) { return; } Sys_FPrintf( SYS_VRB,"--- LeakFile ---\n" ); // // write the points to the file // linefile = fopen( filename, "w" ); if ( !linefile ) { Error( "Couldn't open %s\n", filename ); } //xml_node = xmlNewNode( NULL, (xmlChar*)"polyline" ); count = 0; node = &tree->outside_node; while ( node->occupied > 1 ) { int next; portal_t *p, *nextportal = NULL; node_t *nextnode = NULL; int s; // find the best portal exit next = node->occupied; for ( p = node->portals ; p ; p = p->next[!s] ) { s = ( p->nodes[0] == node ); if ( p->nodes[s]->occupied && p->nodes[s]->occupied < next ) { nextportal = p; nextnode = p->nodes[s]; next = nextnode->occupied; } } node = nextnode; WindingCenter( nextportal->winding, mid ); fprintf( linefile, "%f %f %f\n", mid[0], mid[1], mid[2] ); // point = xml_NodeForVec( mid ); // xmlAddChild( xml_node, point ); count++; } // add the occupant center GetVectorForKey( node->occupant, "origin", mid ); fprintf( linefile, "%f %f %f\n", mid[0], mid[1], mid[2] ); //point = xml_NodeForVec( mid ); //xmlAddChild( xml_node, point ); Sys_FPrintf( SYS_VRB, "%9d point linefile\n", count + 1 ); fclose( linefile ); // return xml_node; }
26.088
85
0.570377
isRyven
99b051ec3a0824dad01eb83782653abcac73785e
1,724
cpp
C++
test/common/managed_pointer_test.cpp
AndiLynn/terrier
6002f8a902d3d0d19bc67998514098f8b41ca264
[ "MIT" ]
null
null
null
test/common/managed_pointer_test.cpp
AndiLynn/terrier
6002f8a902d3d0d19bc67998514098f8b41ca264
[ "MIT" ]
null
null
null
test/common/managed_pointer_test.cpp
AndiLynn/terrier
6002f8a902d3d0d19bc67998514098f8b41ca264
[ "MIT" ]
null
null
null
#include "common/managed_pointer.h" #include <iostream> #include <memory> #include <sstream> #include <string> #include "gtest/gtest.h" namespace terrier { // NOLINTNEXTLINE TEST(ManagedPointerTests, EqualityTest) { std::string val0 = "abcde"; char *raw_ptr0 = val0.data(); std::string val1 = "12345"; char *raw_ptr1 = val1.data(); common::ManagedPointer<char *> ptr0(&raw_ptr0); common::ManagedPointer<char *> ptr1(&raw_ptr1); common::ManagedPointer<char *> ptr2(&raw_ptr0); EXPECT_NE(ptr0, ptr1); EXPECT_EQ(ptr0, ptr2); } // NOLINTNEXTLINE TEST(ManagedPointerTests, PointerAccessTest) { std::string val0 = "Peloton Is Dead"; char *raw_ptr0 = val0.data(); std::string val1 = "WuTang"; char *raw_ptr1 = val1.data(); common::ManagedPointer<char *> ptr0(&raw_ptr0); common::ManagedPointer<char *> ptr1(&raw_ptr1); EXPECT_EQ(*ptr0, raw_ptr0); EXPECT_NE(*ptr0, raw_ptr1); } // NOLINTNEXTLINE TEST(ManagedPointerTests, OutputHashTest) { // Make sure that ManagedPointer has the same output and hashing // behavior as std::shared_ptr std::string orig = "ODBRIP"; char *raw_ptr = orig.data(); std::shared_ptr<char *> ptr0(&raw_ptr, [=](char **ptr) { // Do nothing in this custom delete function so that // the shared_ptr doesn't try to deallocate the string's memory }); std::ostringstream os0; os0 << ptr0; std::hash<std::shared_ptr<char *>> hash_func0; size_t hash0 = hash_func0(ptr0); common::ManagedPointer<char *> ptr1(&raw_ptr); std::ostringstream os1; os1 << ptr1; std::hash<common::ManagedPointer<char *>> hash_func1; size_t hash1 = hash_func1(ptr1); EXPECT_EQ(os0.str(), os1.str()); EXPECT_EQ(hash0, hash1); } } // namespace terrier
26.121212
67
0.693735
AndiLynn
99be5822baaf3b0f8080da7c58c3748be606b9df
1,888
cpp
C++
test/test_shader.cpp
taylor-santos/roguelike
67913a3c1a56b82c3bc260fde08ae91409ce024b
[ "MIT" ]
null
null
null
test/test_shader.cpp
taylor-santos/roguelike
67913a3c1a56b82c3bc260fde08ae91409ce024b
[ "MIT" ]
10
2021-05-08T06:20:20.000Z
2021-12-30T02:12:28.000Z
test/test_shader.cpp
taylor-santos/roguelike
67913a3c1a56b82c3bc260fde08ae91409ce024b
[ "MIT" ]
null
null
null
// // Created by taylor-santos on 5/24/2021 at 21:34. // #include "shader.h" #include "doctest/doctest.h" #include "glfw.h" TEST_SUITE_BEGIN("Shader"); #ifndef DISABLE_RENDER_TESTS TEST_CASE("SyntaxError") { GLFW::Window::get(500, 500, "window"); CHECK_THROWS(Shader("this is a syntax error", Shader::Type::FRAGMENT)); } TEST_CASE("ShaderProgram") { GLFW::Window::get(500, 500, "window"); auto builder = ShaderProgram::Builder(); SUBCASE("WithShader") { std::string src = "#version 140\n" "out vec4 outputColor;" "uniform vec3 aUniform;" "void main() {" " outputColor = vec4(aUniform, 1);" "}"; Shader shader(src, Shader::Type::FRAGMENT); builder.withShader(shader); SUBCASE("Build") { CHECK_NOTHROW((void)builder.build()); } SUBCASE("Use") { auto program = builder.build(); program.use(); } SUBCASE("GetUniformLocation") { auto program = builder.build(); CHECK(program.getUniformLocation("aUniform") != -1); } SUBCASE("InvalidUniform") { auto program = builder.build(); CHECK(program.getUniformLocation("invalidName") == -1); } SUBCASE("ShaderAttachedTwice") { builder.withShader(shader); CHECK_THROWS((void)builder.build()); } } SUBCASE("UnresolvedFunction") { std::string src = "#version 140\n" "void foo();" "void main() {" " foo();" "}"; builder.withShader(Shader(src, Shader::Type::FRAGMENT)); CHECK_THROWS((void)builder.build()); } } #endif // DISABLE_RENDER_TESTS
29.968254
75
0.514301
taylor-santos
99be82b82df547ad0809a8c9020cbe594ce0134f
652
hpp
C++
SpellChecker/SpellChecker/SpellChecking/Header/SpellChecker.hpp
TomColdenhoff/SpellChecker
3c0e54afdc3b06d07790034bdb70e755b4d96d24
[ "MIT" ]
null
null
null
SpellChecker/SpellChecker/SpellChecking/Header/SpellChecker.hpp
TomColdenhoff/SpellChecker
3c0e54afdc3b06d07790034bdb70e755b4d96d24
[ "MIT" ]
null
null
null
SpellChecker/SpellChecker/SpellChecking/Header/SpellChecker.hpp
TomColdenhoff/SpellChecker
3c0e54afdc3b06d07790034bdb70e755b4d96d24
[ "MIT" ]
null
null
null
// // SpellChecker.hpp // SpellChecker // // Created by Tom Coldenhoff on 14/01/2020. // Copyright © 2020 Tom Coldenhoff. All rights reserved. // #ifndef SpellChecker_hpp #define SpellChecker_hpp #include "SpellChecker.h" #include "WordDictionaryNode.h" #include <string> namespace spellchecker::spellchecking { class SpellChecker : public spellchecker::spellchecking::interface::SpellChecker { public: SpellChecker(models::WordDictionaryNode* rootWordDictionaryNode); bool CheckSpelling(std::string word) override; private: models::WordDictionaryNode* rootWordDictionaryNode = nullptr; }; } #endif /* SpellChecker_hpp */
22.482759
82
0.753067
TomColdenhoff
99c00a4d48915814f7718f0c2edce6fe141cb9d3
2,709
cpp
C++
src/common/buses/usb/USBTransferHelper.cpp
ska/SeaBreeze
09aac3e764867825f51f75c519a025a863d03590
[ "MIT" ]
null
null
null
src/common/buses/usb/USBTransferHelper.cpp
ska/SeaBreeze
09aac3e764867825f51f75c519a025a863d03590
[ "MIT" ]
null
null
null
src/common/buses/usb/USBTransferHelper.cpp
ska/SeaBreeze
09aac3e764867825f51f75c519a025a863d03590
[ "MIT" ]
1
2020-07-03T08:36:47.000Z
2020-07-03T08:36:47.000Z
/***************************************************//** * @file USBTransferHelper.cpp * @date February 2009 * @author Ocean Optics, Inc. * * LICENSE: * * SeaBreeze Copyright (C) 2014, Ocean Optics Inc * * 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 "common/globals.h" #include "common/buses/usb/USBTransferHelper.h" #include <string> using namespace seabreeze; using namespace std; USBTransferHelper::USBTransferHelper(USB *usbDescriptor, int sendEndpoint, int receiveEndpoint) : TransferHelper() { this->usb = usbDescriptor; this->sendEndpoint = sendEndpoint; this->receiveEndpoint = receiveEndpoint; } USBTransferHelper::USBTransferHelper(USB *usbDescriptor) : TransferHelper() { this->usb = usbDescriptor; } USBTransferHelper::~USBTransferHelper() { } int USBTransferHelper::receive(vector<byte> &buffer, unsigned int length) throw (BusTransferException) { int retval = 0; retval = this->usb->read(this->receiveEndpoint, (void *)&(buffer[0]), length); if((0 == retval && length > 0) || (retval < 0)) { string error("Failed to read any data from USB."); throw BusTransferException(error); } return retval; } int USBTransferHelper::send(const vector<byte> &buffer, unsigned int length) const throw (BusTransferException) { int retval = 0; retval = this->usb->write(this->sendEndpoint, (void *)&(buffer[0]), length); if((0 == retval && length > 0) || (retval < 0)) { string error("Failed to write any data to USB."); throw BusTransferException(error); } return retval; }
34.291139
82
0.680694
ska
99c3d099d46d35826f75b5935bf579301b2b9f3a
6,479
cc
C++
libtransport/src/auth/signer.cc
manang/hicn
006c9aec768d5ff80fed0bf36cc51990f7fa1d8e
[ "Apache-2.0" ]
null
null
null
libtransport/src/auth/signer.cc
manang/hicn
006c9aec768d5ff80fed0bf36cc51990f7fa1d8e
[ "Apache-2.0" ]
null
null
null
libtransport/src/auth/signer.cc
manang/hicn
006c9aec768d5ff80fed0bf36cc51990f7fa1d8e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <hicn/transport/auth/signer.h> extern "C" { #ifndef _WIN32 TRANSPORT_CLANG_DISABLE_WARNING("-Wextern-c-compat") #endif #include <hicn/hicn.h> } #include <chrono> #define ALLOW_UNALIGNED_READS 1 using namespace std; namespace transport { namespace auth { Signer::Signer() : signer_(nullptr), key_id_(nullptr) { parcSecurity_Init(); } Signer::Signer(PARCSigner *signer) : Signer() { setSigner(signer); } Signer::~Signer() { if (signer_) parcSigner_Release(&signer_); if (key_id_) parcKeyId_Release(&key_id_); parcSecurity_Fini(); } void Signer::signPacket(PacketPtr packet) { parcAssertNotNull(signer_, "Expected non-null signer"); const utils::MemBuf &header_chain = *packet; core::Packet::Format format = packet->getFormat(); auto suite = getCryptoSuite(); size_t signature_len = getSignatureSize(); if (!packet->authenticationHeader()) { throw errors::MalformedAHPacketException(); } packet->setSignatureSize(signature_len); // Copy IP+TCP / ICMP header before zeroing them hicn_header_t header_copy; hicn_packet_copy_header(format, packet->packet_start_, &header_copy, false); packet->resetForHash(); // Fill in the HICN_AH header auto now = chrono::duration_cast<chrono::milliseconds>( chrono::system_clock::now().time_since_epoch()) .count(); packet->setSignatureTimestamp(now); packet->setValidationAlgorithm(suite); // Set the key ID KeyId key_id; key_id.first = static_cast<uint8_t *>( parcBuffer_Overlay((PARCBuffer *)parcKeyId_GetKeyId(key_id_), 0)); packet->setKeyId(key_id); // Calculate hash CryptoHasher hasher(parcSigner_GetCryptoHasher(signer_)); const utils::MemBuf *current = &header_chain; hasher.init(); do { hasher.updateBytes(current->data(), current->length()); current = current->next(); } while (current != &header_chain); CryptoHash hash = hasher.finalize(); // Compute signature PARCSignature *signature = parcSigner_SignDigestNoAlloc( signer_, hash.hash_, packet->getSignature(), (uint32_t)signature_len); PARCBuffer *buffer = parcSignature_GetSignature(signature); size_t bytes_len = parcBuffer_Remaining(buffer); if (bytes_len > signature_len) { throw errors::MalformedAHPacketException(); } // Put signature in AH header hicn_packet_copy_header(format, &header_copy, packet->packet_start_, false); // Release allocated objects parcSignature_Release(&signature); } void Signer::setSigner(PARCSigner *signer) { parcAssertNotNull(signer, "Expected non-null signer"); if (signer_) parcSigner_Release(&signer_); if (key_id_) parcKeyId_Release(&key_id_); signer_ = parcSigner_Acquire(signer); key_id_ = parcSigner_CreateKeyId(signer_); } size_t Signer::getSignatureSize() const { parcAssertNotNull(signer_, "Expected non-null signer"); return parcSigner_GetSignatureSize(signer_); } CryptoSuite Signer::getCryptoSuite() const { parcAssertNotNull(signer_, "Expected non-null signer"); return static_cast<CryptoSuite>(parcSigner_GetCryptoSuite(signer_)); } CryptoHashType Signer::getCryptoHashType() const { parcAssertNotNull(signer_, "Expected non-null signer"); return static_cast<CryptoHashType>(parcSigner_GetCryptoHashType(signer_)); } PARCSigner *Signer::getParcSigner() const { return signer_; } PARCKeyStore *Signer::getParcKeyStore() const { parcAssertNotNull(signer_, "Expected non-null signer"); return parcSigner_GetKeyStore(signer_); } AsymmetricSigner::AsymmetricSigner(CryptoSuite suite, PARCKeyStore *key_store) { parcAssertNotNull(key_store, "Expected non-null key_store"); auto crypto_suite = static_cast<PARCCryptoSuite>(suite); switch (suite) { case CryptoSuite::DSA_SHA256: case CryptoSuite::RSA_SHA256: case CryptoSuite::RSA_SHA512: case CryptoSuite::ECDSA_256K1: break; default: throw errors::RuntimeException( "Invalid crypto suite for asymmetric signer"); } setSigner( parcSigner_Create(parcPublicKeySigner_Create(key_store, crypto_suite), PARCPublicKeySignerAsSigner)); } SymmetricSigner::SymmetricSigner(CryptoSuite suite, PARCKeyStore *key_store) { parcAssertNotNull(key_store, "Expected non-null key_store"); auto crypto_suite = static_cast<PARCCryptoSuite>(suite); switch (suite) { case CryptoSuite::HMAC_SHA256: case CryptoSuite::HMAC_SHA512: break; default: throw errors::RuntimeException( "Invalid crypto suite for symmetric signer"); } setSigner(parcSigner_Create(parcSymmetricKeySigner_Create( (PARCSymmetricKeyStore *)key_store, parcCryptoSuite_GetCryptoHash(crypto_suite)), PARCSymmetricKeySignerAsSigner)); } SymmetricSigner::SymmetricSigner(CryptoSuite suite, const string &passphrase) { auto crypto_suite = static_cast<PARCCryptoSuite>(suite); switch (suite) { case CryptoSuite::HMAC_SHA256: case CryptoSuite::HMAC_SHA512: break; default: throw errors::RuntimeException( "Invalid crypto suite for symmetric signer"); } PARCBufferComposer *composer = parcBufferComposer_Create(); parcBufferComposer_PutString(composer, passphrase.c_str()); PARCBuffer *key_buf = parcBufferComposer_ProduceBuffer(composer); parcBufferComposer_Release(&composer); PARCSymmetricKeyStore *key_store = parcSymmetricKeyStore_Create(key_buf); PARCSymmetricKeySigner *key_signer = parcSymmetricKeySigner_Create( key_store, parcCryptoSuite_GetCryptoHash(crypto_suite)); setSigner(parcSigner_Create(key_signer, PARCSymmetricKeySignerAsSigner)); parcSymmetricKeySigner_Release(&key_signer); parcSymmetricKeyStore_Release(&key_store); parcBuffer_Release(&key_buf); } } // namespace auth } // namespace transport
31
80
0.73607
manang
99c4f806134e61afce3dfc85fd6091d6ccba7e20
6,372
cpp
C++
src/core/queueContext.cpp
gflegar/pal
93d6aba82af14ae57ae6d84a4cf0cca3d9aa8c6b
[ "MIT" ]
268
2017-12-22T11:03:10.000Z
2022-03-31T15:37:31.000Z
src/core/queueContext.cpp
gflegar/pal
93d6aba82af14ae57ae6d84a4cf0cca3d9aa8c6b
[ "MIT" ]
79
2017-12-22T12:26:52.000Z
2022-03-30T13:06:30.000Z
src/core/queueContext.cpp
gflegar/pal
93d6aba82af14ae57ae6d84a4cf0cca3d9aa8c6b
[ "MIT" ]
92
2017-12-22T12:21:16.000Z
2022-03-29T22:34:17.000Z
/* *********************************************************************************************************************** * * Copyright (c) 2016-2021 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ #include "core/device.h" #include "core/queue.h" #include "core/queueContext.h" #include "palAssert.h" using namespace Util; namespace Pal { // ===================================================================================================================== QueueContext::~QueueContext() { if (m_waitForIdleTs.IsBound()) { m_waitForIdleTs.Update(nullptr, 0); // We assume we allocated this timestamp together with the exclusive exec TS. PAL_ASSERT(m_exclusiveExecTs.IsBound()); if ((m_pDevice->GetPlatform() != nullptr) && (m_pDevice->GetPlatform()->GetEventProvider() != nullptr)) { ResourceDestroyEventData destroyData = {}; destroyData.pObj = &m_waitForIdleTs; m_pDevice->GetPlatform()->GetEventProvider()->LogGpuMemoryResourceDestroyEvent(destroyData); } } if (m_exclusiveExecTs.IsBound()) { m_pDevice->MemMgr()->FreeGpuMem(m_exclusiveExecTs.Memory(), m_exclusiveExecTs.Offset()); m_exclusiveExecTs.Update(nullptr, 0); if ((m_pDevice->GetPlatform() != nullptr) && (m_pDevice->GetPlatform()->GetEventProvider() != nullptr)) { ResourceDestroyEventData destroyData = {}; destroyData.pObj = &m_exclusiveExecTs; m_pDevice->GetPlatform()->GetEventProvider()->LogGpuMemoryResourceDestroyEvent(destroyData); } } } // ===================================================================================================================== // Initializes the queue context submission info describing the submission preamble, postamble and paging fence value. Result QueueContext::PreProcessSubmit( InternalSubmitInfo* pSubmitInfo, uint32 cmdBufferCount) { pSubmitInfo->numPreambleCmdStreams = 0; pSubmitInfo->numPostambleCmdStreams = 0; pSubmitInfo->pagingFence = 0; return Result::Success; } // ===================================================================================================================== // Suballocates any timestamp memory needed by our subclasses. The memory is mapped and initialized to zero. Result QueueContext::CreateTimestampMem( bool needWaitForIdleMem) { // We always allocate the exclusive exec timestamp but might not need the wait-for-idle timestamp. GpuMemoryCreateInfo createInfo = { }; createInfo.alignment = sizeof(uint32); createInfo.size = needWaitForIdleMem ? sizeof(uint64) : sizeof(uint32); createInfo.priority = GpuMemPriority::Normal; createInfo.vaRange = VaRange::Default; createInfo.heaps[0] = GpuHeap::GpuHeapLocal; createInfo.heaps[1] = GpuHeap::GpuHeapGartUswc; createInfo.heapCount = 2; GpuMemoryInternalCreateInfo internalInfo = { }; internalInfo.flags.alwaysResident = 1; GpuMemory* pGpuMemory = nullptr; gpusize offset = 0; Result result = m_pDevice->MemMgr()->AllocateGpuMem(createInfo, internalInfo, false, &pGpuMemory, &offset); if (result == Result::Success) { m_exclusiveExecTs.Update(pGpuMemory, offset); if (needWaitForIdleMem) { m_waitForIdleTs.Update(pGpuMemory, offset + sizeof(uint32)); } if ((m_pDevice->GetPlatform() != nullptr) && (m_pDevice->GetPlatform()->GetEventProvider() != nullptr)) { ResourceCreateEventData createData = {}; createData.type = ResourceType::Timestamp; createData.pObj = &m_exclusiveExecTs; createData.pResourceDescData = nullptr; createData.resourceDescSize = 0; m_pDevice->GetPlatform()->GetEventProvider()->LogGpuMemoryResourceCreateEvent(createData); GpuMemoryResourceBindEventData bindData = {}; bindData.pGpuMemory = pGpuMemory; bindData.pObj = &m_exclusiveExecTs; bindData.offset = offset; bindData.requiredGpuMemSize = sizeof(uint32); m_pDevice->GetPlatform()->GetEventProvider()->LogGpuMemoryResourceBindEvent(bindData); if (needWaitForIdleMem) { createData.pObj = &m_waitForIdleTs; m_pDevice->GetPlatform()->GetEventProvider()->LogGpuMemoryResourceCreateEvent(createData); bindData.offset = offset + sizeof(uint32); bindData.pObj = &m_waitForIdleTs; m_pDevice->GetPlatform()->GetEventProvider()->LogGpuMemoryResourceBindEvent(bindData); } } void* pPtr = nullptr; result = m_exclusiveExecTs.Map(&pPtr); if (result == Result::Success) { if (needWaitForIdleMem) { *static_cast<uint64*>(pPtr) = 0; } else { *static_cast<uint32*>(pPtr) = 0; } result = m_exclusiveExecTs.Unmap(); } } return result; } } // Pal
39.092025
120
0.598399
gflegar
99cd0727fda0596bf5e00dd39f02734dc08ededa
17,850
cpp
C++
src/finiteVolume/processes/speciesTransport.cpp
kolosret/ablate
755089ab5e39388d9cda8dedac5a45ba1b016dd5
[ "BSD-3-Clause" ]
null
null
null
src/finiteVolume/processes/speciesTransport.cpp
kolosret/ablate
755089ab5e39388d9cda8dedac5a45ba1b016dd5
[ "BSD-3-Clause" ]
null
null
null
src/finiteVolume/processes/speciesTransport.cpp
kolosret/ablate
755089ab5e39388d9cda8dedac5a45ba1b016dd5
[ "BSD-3-Clause" ]
null
null
null
#include "speciesTransport.hpp" #include "finiteVolume/compressibleFlowFields.hpp" #include "utilities/mathUtilities.hpp" ablate::finiteVolume::processes::SpeciesTransport::SpeciesTransport(std::shared_ptr<eos::EOS> eosIn, std::shared_ptr<fluxCalculator::FluxCalculator> fluxCalcIn, std::shared_ptr<eos::transport::TransportModel> transportModelIn) : fluxCalculator(std::move(fluxCalcIn)), eos(std::move(eosIn)), transportModel(std::move(transportModelIn)), advectionData() { if (fluxCalculator) { // set the decode state function advectionData.numberSpecies = (PetscInt)eos->GetSpecies().size(); // extract the difference function from fluxDifferencer object advectionData.fluxCalculatorFunction = fluxCalculator->GetFluxCalculatorFunction(); advectionData.fluxCalculatorCtx = fluxCalculator->GetFluxCalculatorContext(); } if (transportModel) { // set the eos functions diffusionData.numberSpecies = (PetscInt)eos->GetSpecies().size(); diffusionData.speciesSpeciesSensibleEnthalpy.resize(eos->GetSpecies().size()); } numberSpecies = (PetscInt)eos->GetSpecies().size(); } void ablate::finiteVolume::processes::SpeciesTransport::Initialize(ablate::finiteVolume::FiniteVolumeSolver &flow) { if (!eos->GetSpecies().empty()) { if (fluxCalculator) { flow.RegisterRHSFunction(AdvectionFlux, &advectionData, CompressibleFlowFields::DENSITY_YI_FIELD, {CompressibleFlowFields::EULER_FIELD, CompressibleFlowFields::DENSITY_YI_FIELD}, {}); advectionData.computeTemperature = eos->GetThermodynamicFunction(eos::ThermodynamicProperty::Temperature, flow.GetSubDomain().GetFields()); advectionData.computeInternalEnergy = eos->GetThermodynamicTemperatureFunction(eos::ThermodynamicProperty::InternalSensibleEnergy, flow.GetSubDomain().GetFields()); advectionData.computeSpeedOfSound = eos->GetThermodynamicTemperatureFunction(eos::ThermodynamicProperty::SpeedOfSound, flow.GetSubDomain().GetFields()); advectionData.computePressure = eos->GetThermodynamicTemperatureFunction(eos::ThermodynamicProperty::Pressure, flow.GetSubDomain().GetFields()); } if (transportModel) { diffusionData.diffFunction = transportModel->GetTransportTemperatureFunction(eos::transport::TransportProperty::Diffusivity, flow.GetSubDomain().GetFields()); if (diffusionData.diffFunction.function) { flow.RegisterRHSFunction(DiffusionEnergyFlux, &diffusionData, CompressibleFlowFields::EULER_FIELD, {CompressibleFlowFields::EULER_FIELD, CompressibleFlowFields::DENSITY_YI_FIELD}, {CompressibleFlowFields::YI_FIELD}); flow.RegisterRHSFunction(DiffusionSpeciesFlux, &diffusionData, CompressibleFlowFields::DENSITY_YI_FIELD, {CompressibleFlowFields::EULER_FIELD, CompressibleFlowFields::DENSITY_YI_FIELD}, {CompressibleFlowFields::YI_FIELD}); diffusionData.computeTemperatureFunction = eos->GetThermodynamicFunction(eos::ThermodynamicProperty::Temperature, flow.GetSubDomain().GetFields()); diffusionData.computeSpeciesSensibleEnthalpyFunction = eos->GetThermodynamicTemperatureFunction(eos::ThermodynamicProperty::SpeciesSensibleEnthalpy, flow.GetSubDomain().GetFields()); } } flow.RegisterAuxFieldUpdate( UpdateAuxMassFractionField, &numberSpecies, std::vector<std::string>{CompressibleFlowFields::YI_FIELD}, {CompressibleFlowFields::EULER_FIELD, CompressibleFlowFields::DENSITY_YI_FIELD}); // clean up the species flow.RegisterPostEvaluate(NormalizeSpecies); } } PetscErrorCode ablate::finiteVolume::processes::SpeciesTransport::UpdateAuxMassFractionField(PetscReal time, PetscInt dim, const PetscFVCellGeom *cellGeom, const PetscInt uOff[], const PetscScalar *conservedValues, const PetscInt aOff[], PetscScalar *auxField, void *ctx) { PetscFunctionBeginUser; PetscReal density = conservedValues[uOff[0] + CompressibleFlowFields::RHO]; auto numberSpecies = (PetscInt *)ctx; for (PetscInt sp = 0; sp < *numberSpecies; sp++) { auxField[aOff[0] + sp] = conservedValues[uOff[1] + sp] / density; } PetscFunctionReturn(0); } PetscErrorCode ablate::finiteVolume::processes::SpeciesTransport::DiffusionEnergyFlux(PetscInt dim, const PetscFVFaceGeom *fg, const PetscInt *uOff, const PetscInt *uOff_x, const PetscScalar *fieldL, const PetscScalar *fieldR, const PetscScalar *gradL, const PetscScalar *gradR, const PetscInt *aOff, const PetscInt *aOff_x, const PetscScalar *auxL, const PetscScalar *auxR, const PetscScalar *gradAuxL, const PetscScalar *gradAuxR, PetscScalar *flux, void *ctx) { PetscFunctionBeginUser; // this order is based upon the order that they are passed into RegisterRHSFunction const int yi = 0; const int euler = 0; auto flowParameters = (DiffusionData *)ctx; // get the current density from euler const PetscReal density = 0.5 * (fieldL[uOff[euler] + CompressibleFlowFields::RHO] + fieldR[uOff[euler] + CompressibleFlowFields::RHO]); // compute the temperature in this volume PetscErrorCode ierr; PetscReal temperatureLeft; ierr = flowParameters->computeTemperatureFunction.function(fieldL, &temperatureLeft, flowParameters->computeTemperatureFunction.context.get()); CHKERRQ(ierr); PetscReal temperatureRight; ierr = flowParameters->computeTemperatureFunction.function(fieldR, &temperatureRight, flowParameters->computeTemperatureFunction.context.get()); CHKERRQ(ierr); // compute the enthalpy for each species PetscReal temperature = 0.5 * (temperatureLeft + temperatureRight); ierr = flowParameters->computeSpeciesSensibleEnthalpyFunction.function( fieldR, temperature, flowParameters->speciesSpeciesSensibleEnthalpy.data(), flowParameters->computeSpeciesSensibleEnthalpyFunction.context.get()); CHKERRQ(ierr); // set the non rho E fluxes to zero flux[CompressibleFlowFields::RHO] = 0.0; flux[CompressibleFlowFields::RHOE] = 0.0; for (PetscInt d = 0; d < dim; d++) { flux[CompressibleFlowFields::RHOU + d] = 0.0; } // compute diff PetscReal diffLeft = 0.0; flowParameters->diffFunction.function(fieldL, temperatureLeft, &diffLeft, flowParameters->diffFunction.context.get()); PetscReal diffRight = 0.0; flowParameters->diffFunction.function(fieldR, temperatureRight, &diffRight, flowParameters->diffFunction.context.get()); PetscReal diff = 0.5 * (diffLeft + diffRight); for (PetscInt sp = 0; sp < flowParameters->numberSpecies; ++sp) { for (PetscInt d = 0; d < dim; ++d) { // speciesFlux(-rho Di dYi/dx - rho Di dYi/dy - rho Di dYi//dz) . n A const int offset = aOff_x[yi] + (sp * dim) + d; PetscReal speciesFlux = -fg->normal[d] * density * diff * flowParameters->speciesSpeciesSensibleEnthalpy[sp] * 0.5 * (gradAuxL[offset] + gradAuxR[offset]); flux[CompressibleFlowFields::RHOE] += speciesFlux; } } PetscFunctionReturn(0); } PetscErrorCode ablate::finiteVolume::processes::SpeciesTransport::DiffusionSpeciesFlux(PetscInt dim, const PetscFVFaceGeom *fg, const PetscInt *uOff, const PetscInt *uOff_x, const PetscScalar *fieldL, const PetscScalar *fieldR, const PetscScalar *gradL, const PetscScalar *gradR, const PetscInt *aOff, const PetscInt *aOff_x, const PetscScalar *auxL, const PetscScalar *auxR, const PetscScalar *gradAuxL, const PetscScalar *gradAuxR, PetscScalar *flux, void *ctx) { PetscFunctionBeginUser; // this order is based upon the order that they are passed into RegisterRHSFunction const int yi = 0; const int euler = 0; auto flowParameters = (DiffusionData *)ctx; // get the current density from euler const PetscReal density = 0.5 * (fieldL[uOff[euler] + CompressibleFlowFields::RHO] + fieldR[uOff[euler] + CompressibleFlowFields::RHO]); PetscErrorCode ierr; PetscReal temperatureLeft; ierr = flowParameters->computeTemperatureFunction.function(fieldL, &temperatureLeft, flowParameters->computeTemperatureFunction.context.get()); CHKERRQ(ierr); PetscReal temperatureRight; ierr = flowParameters->computeTemperatureFunction.function(fieldR, &temperatureRight, flowParameters->computeTemperatureFunction.context.get()); CHKERRQ(ierr); // compute diff PetscReal diffLeft = 0.0; flowParameters->diffFunction.function(fieldL, temperatureLeft, &diffLeft, flowParameters->diffFunction.context.get()); PetscReal diffRight = 0.0; flowParameters->diffFunction.function(fieldR, temperatureRight, &diffRight, flowParameters->diffFunction.context.get()); PetscReal diff = 0.5 * (diffLeft + diffRight); // species equations for (PetscInt sp = 0; sp < flowParameters->numberSpecies; ++sp) { flux[sp] = 0; for (PetscInt d = 0; d < dim; ++d) { // speciesFlux(-rho Di dYi/dx - rho Di dYi/dy - rho Di dYi//dz) . n A const int offset = aOff_x[yi] + (sp * dim) + d; PetscReal speciesFlux = -fg->normal[d] * density * diff * 0.5 * (gradAuxL[offset] + gradAuxR[offset]); flux[sp] += speciesFlux; } } PetscFunctionReturn(0); } PetscErrorCode ablate::finiteVolume::processes::SpeciesTransport::AdvectionFlux(PetscInt dim, const PetscFVFaceGeom *fg, const PetscInt *uOff, const PetscInt *uOff_x, const PetscScalar *fieldL, const PetscScalar *fieldR, const PetscScalar *gradL, const PetscScalar *gradR, const PetscInt *aOff, const PetscInt *aOff_x, const PetscScalar *auxL, const PetscScalar *auxR, const PetscScalar *gradAuxL, const PetscScalar *gradAuxR, PetscScalar *flux, void *ctx) { PetscFunctionBeginUser; auto eulerAdvectionData = (AdvectionData *)ctx; // Compute the norm PetscReal norm[3]; utilities::MathUtilities::NormVector(dim, fg->normal, norm); const PetscReal areaMag = utilities::MathUtilities::MagVector(dim, fg->normal); const int EULER_FIELD = 0; const int YI_FIELD = 1; // Decode the left and right states PetscReal densityL; PetscReal normalVelocityL; PetscReal velocityL[3]; PetscReal internalEnergyL; PetscReal aL; PetscReal pL; // decode the left side { densityL = fieldL[uOff[EULER_FIELD] + CompressibleFlowFields::RHO]; PetscReal temperatureL; PetscErrorCode ierr = eulerAdvectionData->computeTemperature.function(fieldL, &temperatureL, eulerAdvectionData->computeTemperature.context.get()); CHKERRQ(ierr); // Get the velocity in this direction normalVelocityL = 0.0; for (PetscInt d = 0; d < dim; d++) { velocityL[d] = fieldL[uOff[EULER_FIELD] + CompressibleFlowFields::RHOU + d] / densityL; normalVelocityL += velocityL[d] * norm[d]; } ierr = eulerAdvectionData->computeInternalEnergy.function(fieldL, temperatureL, &internalEnergyL, eulerAdvectionData->computeInternalEnergy.context.get()); CHKERRQ(ierr); ierr = eulerAdvectionData->computeSpeedOfSound.function(fieldL, temperatureL, &aL, eulerAdvectionData->computeSpeedOfSound.context.get()); CHKERRQ(ierr); ierr = eulerAdvectionData->computePressure.function(fieldL, temperatureL, &pL, eulerAdvectionData->computePressure.context.get()); CHKERRQ(ierr); } PetscReal densityR; PetscReal normalVelocityR; PetscReal velocityR[3]; PetscReal internalEnergyR; PetscReal aR; PetscReal pR; { // decode right state densityR = fieldR[uOff[EULER_FIELD] + CompressibleFlowFields::RHO]; PetscReal temperatureR; PetscErrorCode ierr = eulerAdvectionData->computeTemperature.function(fieldR, &temperatureR, eulerAdvectionData->computeTemperature.context.get()); CHKERRQ(ierr); // Get the velocity in this direction normalVelocityR = 0.0; for (PetscInt d = 0; d < dim; d++) { velocityR[d] = fieldR[uOff[EULER_FIELD] + CompressibleFlowFields::RHOU + d] / densityR; normalVelocityR += velocityR[d] * norm[d]; } ierr = eulerAdvectionData->computeInternalEnergy.function(fieldR, temperatureR, &internalEnergyR, eulerAdvectionData->computeInternalEnergy.context.get()); CHKERRQ(ierr); ierr = eulerAdvectionData->computeSpeedOfSound.function(fieldR, temperatureR, &aR, eulerAdvectionData->computeSpeedOfSound.context.get()); CHKERRQ(ierr); ierr = eulerAdvectionData->computePressure.function(fieldR, temperatureR, &pR, eulerAdvectionData->computePressure.context.get()); CHKERRQ(ierr); } // get the face values PetscReal massFlux; if (eulerAdvectionData->fluxCalculatorFunction(eulerAdvectionData->fluxCalculatorCtx, normalVelocityL, aL, densityL, pL, normalVelocityR, aR, densityR, pR, &massFlux, nullptr) == fluxCalculator::LEFT) { // march over each gas species for (PetscInt sp = 0; sp < eulerAdvectionData->numberSpecies; sp++) { // Note: there is no density in the flux because uR and UL are density*yi flux[sp] = (massFlux * fieldL[uOff[YI_FIELD] + sp] / densityL) * areaMag; } } else { // march over each gas species for (PetscInt sp = 0; sp < eulerAdvectionData->numberSpecies; sp++) { // Note: there is no density in the flux because uR and UL are density*yi flux[sp] = (massFlux * fieldR[uOff[YI_FIELD] + sp] / densityR) * areaMag; } } PetscFunctionReturn(0); } void ablate::finiteVolume::processes::SpeciesTransport::NormalizeSpecies(TS ts, ablate::solver::Solver &solver) { // Get the density and densityYi field info const auto &eulerFieldInfo = solver.GetSubDomain().GetField(CompressibleFlowFields::EULER_FIELD); const auto &densityYiFieldInfo = solver.GetSubDomain().GetField(CompressibleFlowFields::DENSITY_YI_FIELD); // Get the solution vec and dm auto dm = solver.GetSubDomain().GetDM(); auto solVec = solver.GetSubDomain().GetSolutionVector(); // Get the array vector PetscScalar *solutionArray; VecGetArray(solVec, &solutionArray) >> checkError; // March over each cell in this domain IS cellIS; PetscInt cStart, cEnd; const PetscInt *cells; solver.GetCellRange(cellIS, cStart, cEnd, cells); for (PetscInt c = cStart; c < cEnd; ++c) { PetscInt cell = cells ? cells[c] : c; // Get the euler and density field const PetscScalar *euler = nullptr; DMPlexPointGlobalFieldRead(dm, cell, eulerFieldInfo.id, solutionArray, &euler) >> checkError; PetscScalar *densityYi; DMPlexPointGlobalFieldRef(dm, cell, densityYiFieldInfo.id, solutionArray, &densityYi) >> checkError; // Only update if in the global vector if (euler) { // Get density const PetscScalar density = euler[CompressibleFlowFields::RHO]; PetscScalar yiSum = 0.0; for (PetscInt sp = 0; sp < densityYiFieldInfo.numberComponents - 1; sp++) { // Limit the bounds PetscScalar yi = densityYi[sp] / density; yi = PetscMax(0.0, yi); yi = PetscMin(1.0, yi); yiSum += yi; // Set it back densityYi[sp] = yi * density; } // Now cleanup yi if (yiSum > 1.0) { for (PetscInt sp = 0; sp < densityYiFieldInfo.numberComponents; sp++) { PetscScalar yi = densityYi[sp] / density; yi /= yiSum; densityYi[sp] = density * yi; } densityYi[densityYiFieldInfo.numberComponents - 1] = 0.0; } else { densityYi[densityYiFieldInfo.numberComponents - 1] = density * (1.0 - yiSum); } } } // cleanup VecRestoreArray(solVec, &solutionArray) >> checkError; solver.RestoreRange(cellIS, cStart, cEnd, cells); }; #include "registrar.hpp" REGISTER(ablate::finiteVolume::processes::Process, ablate::finiteVolume::processes::SpeciesTransport, "diffusion/advection for the species yi field", ARG(ablate::eos::EOS, "eos", "the equation of state used to describe the flow"), OPT(ablate::finiteVolume::fluxCalculator::FluxCalculator, "fluxCalculator", "the flux calculator (default is no advection)"), OPT(ablate::eos::transport::TransportModel, "transport", "the diffusion transport model (default is no diffusion)"));
52.810651
200
0.651317
kolosret
99cd1a4611c31fc13b0e7ed9ce5ae73a13cd1f05
190
hpp
C++
src/parser/script/ScriptParser.hpp
AlexeyGurevsky/bbtube
d7329b52cec08cdc80c521e8f3d4f5de746639e7
[ "Apache-2.0" ]
15
2020-07-13T03:51:10.000Z
2022-03-16T13:56:28.000Z
src/parser/script/ScriptParser.hpp
AlexeyGurevsky/bbtube
d7329b52cec08cdc80c521e8f3d4f5de746639e7
[ "Apache-2.0" ]
2
2021-01-07T20:31:29.000Z
2021-12-15T21:20:34.000Z
src/parser/script/ScriptParser.hpp
AlexeyGurevsky/bbtube
d7329b52cec08cdc80c521e8f3d4f5de746639e7
[ "Apache-2.0" ]
4
2020-08-15T01:52:31.000Z
2022-03-16T13:56:30.000Z
#ifndef SCRIPTPARSER_HPP_ #define SCRIPTPARSER_HPP_ #include "ScriptData.hpp" class ScriptParser { public: static ScriptData parse(QString script); }; #endif /* SCRIPTPARSER_HPP_ */
13.571429
44
0.763158
AlexeyGurevsky
99cfeeb7ca614431fde10e995b9ed4a8cac1ee98
2,226
cpp
C++
TouchMindLib/touchmind/util/OSVersionChecker.cpp
yohei-yoshihara/TouchMind
3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa
[ "MIT" ]
15
2015-07-10T05:03:27.000Z
2021-06-08T08:24:46.000Z
TouchMindLib/touchmind/util/OSVersionChecker.cpp
yohei-yoshihara/TouchMind
3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa
[ "MIT" ]
null
null
null
TouchMindLib/touchmind/util/OSVersionChecker.cpp
yohei-yoshihara/TouchMind
3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa
[ "MIT" ]
10
2015-01-04T01:23:56.000Z
2020-12-29T11:35:47.000Z
#include "StdAfx.h" #include <strsafe.h> #include "touchmind/logging/Logging.h" #include "touchmind/util/OSVersionChecker.h" #include <VersionHelpers.h> touchmind::util::OSVersion touchmind::util::OSVersionChecker::GetOSVersion() { if (IsWindows7OrGreater()) { return OSVersion_Windows7; } else if (IsWindowsVistaOrGreater()) { return OSVersion_WindowsVista; } else { return OSVersion_WindowsXP; } /* OSVERSIONINFOEX osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!GetVersionEx((OSVERSIONINFO *) &osvi)) { return OSVersion_OlderThanXP; } if (VER_PLATFORM_WIN32_NT == osvi.dwPlatformId && osvi.dwMajorVersion > 4) { if (osvi.dwMajorVersion == 6) { if (osvi.dwMinorVersion == 0) { return OSVersion_WindowsVista; } else if (osvi.dwMinorVersion == 1) { return OSVersion_Windows7; } } else if (osvi.dwMajorVersion == 5) { if (osvi.dwMinorVersion == 2) { return OSVersion_Windows2003; } else if (osvi.dwMinorVersion == 1) { return OSVersion_WindowsXP; } } } return OSVersion_OlderThanXP; */ } bool touchmind::util::OSVersionChecker::IsVista() { OSVERSIONINFOEX ver; DWORDLONG condMask = 0; ZeroMemory(&ver, sizeof(OSVERSIONINFOEX)); ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ver.dwMajorVersion = 6; ver.dwMinorVersion = 0; VER_SET_CONDITION(condMask, VER_MAJORVERSION, VER_GREATER_EQUAL); VER_SET_CONDITION(condMask, VER_MINORVERSION, VER_GREATER_EQUAL); BOOL bRet = VerifyVersionInfo(&ver, VER_MAJORVERSION | VER_MINORVERSION, condMask); return bRet == TRUE; } bool touchmind::util::OSVersionChecker::IsWin7() { OSVERSIONINFOEX ver; DWORDLONG condMask = 0; ZeroMemory(&ver, sizeof(OSVERSIONINFOEX)); ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ver.dwMajorVersion = 6; ver.dwMinorVersion = 1; VER_SET_CONDITION(condMask, VER_MAJORVERSION, VER_GREATER_EQUAL); VER_SET_CONDITION(condMask, VER_MINORVERSION, VER_GREATER_EQUAL); BOOL bRet = VerifyVersionInfo(&ver, VER_MAJORVERSION | VER_MINORVERSION, condMask); return bRet == TRUE; }
32.735294
85
0.704852
yohei-yoshihara
99d02c5369de3bc72a4972d1887bea45fbb04834
9,433
cpp
C++
lib/RoomLayout.cpp
frasercrmck/LevelSyn
549e24447e07ef2d325da5bd5decb0e9ad783037
[ "BSD-3-Clause" ]
null
null
null
lib/RoomLayout.cpp
frasercrmck/LevelSyn
549e24447e07ef2d325da5bd5decb0e9ad783037
[ "BSD-3-Clause" ]
null
null
null
lib/RoomLayout.cpp
frasercrmck/LevelSyn
549e24447e07ef2d325da5bd5decb0e9ad783037
[ "BSD-3-Clause" ]
null
null
null
#include "RoomLayout.h" unsigned CRoomLayout::GetNumOfVertices() { unsigned numOfVertices = 0; for (unsigned i = 0; i < GetNumOfRooms(); i++) { numOfVertices += m_rooms[i].GetNumOfVertices(); } return numOfVertices; } unsigned CRoomLayout::GetNumOfEdges() { unsigned numOfEdges = 0; for (unsigned i = 0; i < GetNumOfRooms(); i++) { numOfEdges += m_rooms[i].GetNumOfEdges(); } return numOfEdges; } AABB2i CRoomLayout::GetLayoutBoundingBox() const { v2i pMin(std::numeric_limits<int>::max()); v2i pMax(std::numeric_limits<int>::min()); for (unsigned i = 0; i < GetNumOfRooms(); i++) { AABB2i bbTmp = GetRoom(i).GetRoomBoundingBox(); for (unsigned j = 0; j < 2; j++) { pMin[j] = std::min(pMin[j], bbTmp.m_posMin[j]); pMax[j] = std::max(pMax[j], bbTmp.m_posMax[j]); } } return AABB2i{pMin, pMax}; } void CRoomLayout::MoveToSceneCenter() { AABB2i bb = GetLayoutBoundingBox(); v2i posCen = floor_midpoint(bb.m_posMin, bb.m_posMax); for (unsigned i = 0; i < GetNumOfRooms(); i++) { GetRoom(i).TranslateRoom(-posCen); } } std::vector<v2i> CRoomLayout::GetRoomPositions() { std::vector<v2i> roomPositions(GetNumOfRooms()); for (unsigned i = 0; i < GetNumOfRooms(); i++) { roomPositions[i] = GetRoom(i).GetRoomCenter(); } return roomPositions; } void CRoomLayout::ResetRoomEnergies() { for (unsigned i = 0; i < GetNumOfRooms(); i++) { GetRoom(i).ResetEnergy(); } } void CRoomLayout::PrintLayout() const { std::cout << "A layout with " << GetNumOfRooms() << " rooms...\n"; for (unsigned i = 0; i < GetNumOfRooms(); i++) { std::cout << i << "th room:\n"; GetRoom(i).PrintRoom(); } } #include "PlanarGraph.h" bool CRoomLayout::SaveLayoutAsSVG(const char *fileName, int wd /* = 400 */, int ht /* = 400 */, bool visitedOnly /* = FALSE */, class CPlanarGraph *graphBest /* = NULL */, bool labelFlag /* = true */) { int strokeWd = 4; AABB2i bb = GetLayoutBoundingBox(); float pMin = std::min(bb.m_posMin[0], bb.m_posMin[1]); float pMax = std::max(bb.m_posMax[0], bb.m_posMax[1]); /* #ifdef DUMP_INTERMEDIATE_OUTPUT pMin = -1.f; pMax = 1.f; #endif */ float scaling = 1.05f; pMin *= scaling; pMax *= scaling; const char *str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\n" "<!-- layout visualization -->\n" "<svg>\n" "</svg>\n"; TiXmlDocument doc; doc.Parse(str); TiXmlElement *root = doc.RootElement(); std::ostringstream ossViewBox; ossViewBox << 0 << " " << 0 << " " << wd << " " << ht; root->SetAttribute("viewBox", ossViewBox.str().c_str()); root->SetAttribute("xmlns", "http://www.w3.org/2000/svg"); // Draw a background... TiXmlElement bgElement("rect"); bgElement.SetAttribute("x", 0); bgElement.SetAttribute("y", 0); bgElement.SetAttribute("width", wd); bgElement.SetAttribute("height", ht); bgElement.SetAttribute("fill", "#00A000"); bgElement.SetAttribute("stroke", "none"); // root->InsertEndChild(bgElement); // Dump rooms as closed polygons... for (int i = 0; i < GetNumOfRooms(); i++) { if (graphBest != NULL && graphBest->GetNode(i).GetFlagVisited() == false && visitedOnly) { continue; } TiXmlElement roomElement("path"); std::ostringstream ossPath; CRoom &room = GetRoom(i); for (int j = 0; j < room.GetNumOfVertices(); j++) { v2f pj = v2i_to_v2f(room.GetVertex(j)); if (j == 0) { ossPath << "M "; } else { ossPath << "L "; } ossPath << ConvertPosX(pj[0], pMin, pMax, wd) << " "; ossPath << ConvertPosY(pj[1], pMin, pMax, ht) << " "; } ossPath << "z"; roomElement.SetAttribute("d", ossPath.str().c_str()); if (room.GetFlagFixed() == true) { roomElement.SetAttribute("fill", "#808080"); } else if (room.GetBoundaryType() == 2) { // Corridors... roomElement.SetAttribute("fill", "#FAFAFA"); } else { roomElement.SetAttribute("fill", "#E0E0E0"); } roomElement.SetAttribute("stroke", "none"); root->InsertEndChild(roomElement); } // Dump rooms as sets of line segments... for (int i = 0; i < GetNumOfRooms(); i++) { if (graphBest != NULL && graphBest->GetNode(i).GetFlagVisited() == false && visitedOnly) { continue; } TiXmlElement roomElement("path"); std::ostringstream ossPath; CRoom &room = GetRoom(i); if (room.HasWalls() == false) { for (int j = 0; j < room.GetNumOfVertices(); j++) { v2f pj = v2i_to_v2f(room.GetVertex(j)); if (j == 0) { ossPath << "M "; } else { ossPath << "L "; } ossPath << ConvertPosX(pj[0], pMin, pMax, wd) << " "; ossPath << ConvertPosY(pj[1], pMin, pMax, ht) << " "; } ossPath << "z"; } else { for (int j = 0; j < room.GetNumOfWalls(); j++) { RoomWall &wall = room.GetWall(j); v2f p1 = v2i_to_v2f(wall.GetPos1()); v2f p2 = v2i_to_v2f(wall.GetPos2()); ossPath << "M "; ossPath << ConvertPosX(p1[0], pMin, pMax, wd) << " "; ossPath << ConvertPosY(p1[1], pMin, pMax, ht) << " "; ossPath << "L "; ossPath << ConvertPosX(p2[0], pMin, pMax, wd) << " "; ossPath << ConvertPosY(p2[1], pMin, pMax, ht) << " "; } } roomElement.SetAttribute("d", ossPath.str().c_str()); roomElement.SetAttribute("fill", "none"); roomElement.SetAttribute("stroke", "black"); roomElement.SetAttribute("stroke-width", strokeWd); root->InsertEndChild(roomElement); } // Dump vertices... for (unsigned i = 0; i < GetNumOfRooms(); i++) { if (graphBest != NULL && graphBest->GetNode(i).GetFlagVisited() == false && visitedOnly) { continue; } CRoom &room = GetRoom(i); for (unsigned j = 0; j < room.GetNumOfVertices(); j++) { TiXmlElement vertexElement("circle"); v2f pj = v2i_to_v2f(room.GetVertex(j)); vertexElement.SetAttribute("cx", ConvertPosX(pj[0], pMin, pMax, wd)); vertexElement.SetAttribute("cy", ConvertPosY(pj[1], pMin, pMax, ht)); vertexElement.SetAttribute("r", strokeWd / 2); vertexElement.SetAttribute("fill", "black"); vertexElement.SetAttribute("stroke", "none"); root->InsertEndChild(vertexElement); } } // Dump corridor walls... for (int i = 0; i < GetNumOfCorridorWalls(); i++) { CorridorWall &wall = GetCorridorWall(i); v2f p1 = v2i_to_v2f(wall.GetPos1()); v2f p2 = v2i_to_v2f(wall.GetPos2()); TiXmlElement wallElement("path"); std::ostringstream ossWall; ossWall << "M "; ossWall << CRoomLayout::ConvertPosX(p1[0], pMin, pMax, wd) << " "; ossWall << CRoomLayout::ConvertPosY(p1[1], pMin, pMax, ht) << " "; ossWall << "L "; ossWall << CRoomLayout::ConvertPosX(p2[0], pMin, pMax, wd) << " "; ossWall << CRoomLayout::ConvertPosY(p2[1], pMin, pMax, ht) << " "; wallElement.SetAttribute("d", ossWall.str().c_str()); wallElement.SetAttribute("fill", "none"); wallElement.SetAttribute("stroke", "black"); wallElement.SetAttribute("stroke-width", strokeWd); root->InsertEndChild(wallElement); TiXmlElement vertexElement1("circle"); vertexElement1.SetAttribute("cx", ConvertPosX(p1[0], pMin, pMax, wd)); vertexElement1.SetAttribute("cy", ConvertPosY(p1[1], pMin, pMax, ht)); vertexElement1.SetAttribute("r", strokeWd / 2); vertexElement1.SetAttribute("fill", "black"); vertexElement1.SetAttribute("stroke", "none"); root->InsertEndChild(vertexElement1); TiXmlElement vertexElement2("circle"); vertexElement2.SetAttribute("cx", ConvertPosX(p2[0], pMin, pMax, wd)); vertexElement2.SetAttribute("cy", ConvertPosY(p2[1], pMin, pMax, ht)); vertexElement2.SetAttribute("r", strokeWd / 2); vertexElement2.SetAttribute("fill", "black"); vertexElement2.SetAttribute("stroke", "none"); root->InsertEndChild(vertexElement2); } // Dump labels... for (int i = 0; i < GetNumOfRooms(); i++) { if (graphBest != NULL && graphBest->GetNode(i).GetFlagVisited() == false && visitedOnly) { continue; } int shiftX = (i >= 10) ? 8 : 3; int shiftY = 5; v2i pi = GetRoom(i).GetRoomCenter(); pi = pi + GetRoom(i).GetCenterShift(); TiXmlElement labelElement("text"); labelElement.SetAttribute("x", ConvertPosX(pi[0], pMin, pMax, wd) - shiftX); labelElement.SetAttribute("y", ConvertPosY(pi[1], pMin, pMax, ht) + shiftY); labelElement.SetAttribute("font-family", "Verdana"); labelElement.SetAttribute("font-size", 15); labelElement.SetAttribute("fill", "blue"); std::ostringstream ossLabel; ossLabel << i; TiXmlText labelText(ossLabel.str().c_str()); labelElement.InsertEndChild(labelText); if (labelFlag == true) { root->InsertEndChild(labelElement); } } bool saveFlag = doc.SaveFile(fileName); return saveFlag; } int CRoomLayout::ConvertPos(int p, int pMin, int pMax, int sz) { return (float)(p - pMin) / (float)(pMax - pMin) * sz; } int CRoomLayout::ConvertPosX(int p, int pMin, int pMax, int sz) { return ConvertPos(p, pMin, pMax, sz); } int CRoomLayout::ConvertPosY(int p, int pMin, int pMax, int sz) { return sz - 1 - ConvertPos(p, pMin, pMax, sz); }
35.066914
80
0.601717
frasercrmck
99d1effd5e653c56cf316395290f636e65727f49
11,688
hpp
C++
optlib/include/ArgParser.hpp
radj307/307lib
16c5052481b2414ee68beeb7746c006461e8160f
[ "MIT" ]
1
2021-12-09T20:01:21.000Z
2021-12-09T20:01:21.000Z
optlib/include/ArgParser.hpp
radj307/307lib
16c5052481b2414ee68beeb7746c006461e8160f
[ "MIT" ]
null
null
null
optlib/include/ArgParser.hpp
radj307/307lib
16c5052481b2414ee68beeb7746c006461e8160f
[ "MIT" ]
null
null
null
#pragma once #include <ArgContainer.hpp> #include <str.hpp> #include <var.hpp> #include <vector> #include <concepts> namespace opt { using StrVec = std::vector<std::string>; static struct { /// @brief Defines valid argument prefix delimiters. By default, only '-' characters are accepted, however on windows forward-slash characters may be desired as well. std::vector<char> delimiters{ '-' }; } Settings_ArgParser; ///< @brief Static (non-const) settings structure. /** * @brief Check if the given character is a valid delimiter, according to the static Settings_ArgParser object. * @param c Input Character * @returns bool */ inline WINCONSTEXPR const bool is_delimiter(const char& c) { return std::any_of(Settings_ArgParser.delimiters.begin(), Settings_ArgParser.delimiters.end(), [&c](auto&& delim) { return delim == c; }); } /** * @brief Checks if the given string is a valid integer, floating-point, or hexadecimal number. Hexadecimal numbers must be prefixed with "0x" (or "-0x") to be detected properly. * @param str Input String * @returns bool */ inline bool is_number(const std::string& str) { if (str.empty()) return false; const bool is_negative{ str.front() == '-' }, has_hex_prefix{ str.find("0x") == (is_negative ? 1ull : 0ull) }; return ( (has_hex_prefix && std::all_of(str.begin() + 2ull + !!is_negative, str.end(), [](auto&& ch) { return isdigit(ch) || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f'; })) ) // check if number is hexadecimal, short circuit the all_of check if a hex prefix wasn't found. || (std::all_of(str.begin() + !!is_negative, str.end(), [](auto&& ch) { return isdigit(ch) || ch == '.'; })); // decimal number } /** * @brief Check if the given iterator CAN capture the next argument by checking *\n if the next argument is not prefixed with a '-' or is prefixed with '-' but is also a number. *\n Does NOT check if the given iterator is present on the capturelist! * @param here The current iterator position. * @param end The position of the end of the iterable range. * @returns bool */ inline bool can_capture_next(StrVec::const_iterator& here, const StrVec::const_iterator& end) { return (here != end - 1ll) // incrementing iterator won't go out-of-bounds && ((here + 1ll)->front() != '-' // AND next argument doesn't start with a dash || is_number(*(here + 1ll))); // OR next argument is a number } /** * @brief Count the number of characters at the beginning of a string. * @tparam ...DelimT Variadic Template, accepts only char types. * @param str Input string. * @param max_delims Maximum number of delimiters to count before stopping, even if more delimiters exist. * @param ...delims At least one char type to count. * @returns size_t */ [[nodiscard]] inline size_t count_prefix(const std::string& str, const size_t& max_delims) { size_t count{ 0ull }; for (size_t i{ 0ull }; i < str.size() && i < max_delims; ++i) { if (is_delimiter(str.at(i))) ++count; else break; } return count; } /** * @brief Count & remove prefix delimiters from a given string. Returns the stripped string & the number of removed delimiters. * @param str Input string. * @param max_delims Maximum number of delimiter prefixes to strip before stopping, even if there are more delimiters. * @returns std::pair<std::string, size_t> */ inline std::pair<std::string, size_t> strip_prefix(const std::string& str, const size_t& max_delims) { const auto count{ count_prefix(str, max_delims) }; return{ str.substr(count), count }; } /** * @struct CaptureList * @brief Contains a list of arguments that should be allowed to capture additional arguments. This is used by the parse function. */ struct CaptureList { /// @brief Vector of input wrapper strings that contains the argument names. const std::vector<InputWrapper> vec; /** * @brief Default Constructor. * @tparam VT... Variadic Templated Types. * @param ...capturing_arguments Arguments that should be allowed to capture additional arguments. Names should not contain prefix delimiters, but if they do, they are removed. */ template<ValidInputType... VT> constexpr CaptureList(const VT&... capturing_arguments) : vec{ var::variadic_accumulate<InputWrapper>(str::strip_line(InputWrapper{ capturing_arguments }, "", "-")...) } {} WINCONSTEXPR operator const std::vector<InputWrapper>() const { return vec; } /** * @brief Check if a given argument appears in the capture list. Names are case-sensitive. * @tparam Variadic Templated Type. (char) * @param name Input Argument Name. * @param ...delims Optional list of delimiters to remove from the given name. * @returns bool */ template<var::all_same<char>... DelimT> constexpr bool is_present(const std::string& name, const DelimT&... delims) const { constexpr const bool strip_delims{ var::at_least_one<DelimT...> }; // check if delimiters were included return std::any_of(vec.begin(), vec.end(), [&name, &strip_delims, &delims...](auto&& elem) { const auto elemname{ elem.operator const std::string() }; return name == elemname // if names match directly, or if delimiters were included, if the stripped name matches any elements. || strip_delims && str::strip_line(name, "", var::string_accumulate<std::string>(delims...)) == elemname; }); } }; /** * @brief Parse commandline arguments into an ArgContainer instance. *\n __Argument Types__ *\n - Parameters are any arguments that do not begin with a dash '-' character that were not captured by another argument type. *\n - Options are arguments that begin with 2 dash '-' characters, and can capture additional arguments if the option name appears in the capture list. *\n - Flags are arguments that begin with a single dash '-' character, are a single character in length, and can capture additional arguments. Flags can appear alone, or in "chains" where each character is treated as an individual flag. In a flag chain, only the last flag can capture additional arguments. *\n __Capture Rules__ *\n - Only options/flags specified in the capture list are allowed to capture additional arguments. Capture list entries should not include a delimiter prefix. *\n - Options/Flags cannot be captured under any circumstance. ex: "--opt --opt captured" results in "--opt", & "--opt" + "captured". *\n - If a flag in a chain should capture an argument (either with an '=' delimiter or by context), it must appear at the end of the chain. *\n - Any captured arguments do not appear in the argument list by themselves, and must be accessed through the argument that captured them. * @param args Commandline arguments as a vector of strings, in order and including argv[0]. * @param captures A CaptureList instance specifying which arguments are allowed to capture other arguments as their parameters * @returns ArgContainer */ inline ArgContainerType parse(StrVec&& args, const CaptureList& captures) { // remove empty arguments, which are possible when passing arguments from automated testing applications args.erase(std::remove_if(args.begin(), args.end(), [](auto&& s) { return s.empty(); }), args.end()); ArgContainerType cont{}; cont.reserve(args.size()); for (StrVec::const_iterator it{ args.begin() }; it != args.end(); ++it) { auto [arg, d_count] { strip_prefix(*it, 2ull) }; switch (d_count) { case 2ull: // Option if (const auto eqPos{ arg.find('=') }; eqPos != std::string::npos) {// argument contains an equals sign auto opt{ arg.substr(0ull, eqPos) }, cap{ arg.substr(eqPos + 1ull) }; if (captures.is_present(opt)) cont.emplace_back(opt::Option(std::make_pair(std::move(opt), std::move(cap)))); else { cont.emplace_back(opt::Option(std::make_pair(std::move(opt), std::nullopt))); if (!cap.empty()) { arg = cap; goto JUMP_TO_PARAMETER; // skip flag case, add invalid capture as a parameter } } } else if (captures.is_present(arg) && can_capture_next(it, args.end())) // argument can capture next arg cont.emplace_back(opt::Option(std::make_pair(arg, *++it))); else cont.emplace_back(opt::Option(std::make_pair(arg, std::nullopt))); break; case 1ull: // Flag if (!is_number(arg)) { // single-dash prefix is not a number std::optional<opt::Flag> capt{ std::nullopt }; // this can contain a flag if there is a capturing flag at the end of a chain std::string invCap{}; // for invalid captures that should be treated as parameters if (const auto eqPos{ arg.find('=') }; eqPos != std::string::npos) { invCap = arg.substr(eqPos + 1ull); // get string following '=', use invCap in case flag can't capture if (const auto flag{ arg.substr(eqPos - 1ull, 1ull) }; captures.is_present(flag)) { capt = opt::Flag(flag.front(), invCap); // push the capturing flag to capt, insert into vector once all other flags in this chain are parsed arg = arg.substr(0ull, eqPos - 1ull); // remove last flag, '=', and captured string from arg invCap.clear(); // flag can capture, clear invCap } else arg = arg.substr(0ull, eqPos); // remove everything from eqPos to arg.end() } // iterate through characters in arg for (auto fl{ arg.begin() }; fl != arg.end(); ++fl) { // If this is the last char, and it can capture if (fl == arg.end() - 1ll && captures.is_present(std::string(1ull, *fl)) && can_capture_next(it, args.end())) cont.emplace_back(opt::Flag(std::make_pair(*fl, *++it))); else // not last char, or can't capture cont.emplace_back(opt::Flag(std::make_pair(*fl, std::nullopt))); } if (capt.has_value()) // flag captures are always at the end, but parsing them first puts them out of chronological order. cont.emplace_back(std::move(capt.value())); if (invCap.empty()) break; else arg = invCap; // set argument to invalid capture and fallthrough to add it as a parameter } else // this is a negative number, re-add '-' prefix and fallthrough arg = *it; [[fallthrough]]; case 0ull: JUMP_TO_PARAMETER: [[fallthrough]]; // Parameter default: cont.emplace_back(opt::Parameter(arg)); break; } } cont.shrink_to_fit(); return cont; } /** * @brief Parse commandline arguments into an ArgContainer instance. This function accepts a variadic capture list. * @tparam VT... Variadic Templated Input Type * @param args Commandline arguments as a vector of strings, in order and including argv[0]. * @param ...captures The names of any arguments that are allowed to capture additional arguments. If the user attempts to force capture an argument by appending "=..." but the argument is not on this list, the invalid capture will be added separately as a parameter instead. * @returns ArgContainer */ template<ValidInputType... VT> inline static auto parse(auto&& args, const VT&... captures) { return parse(std::forward<decltype(args)>(args), CaptureList(captures...)); } /** * @brief Make a std::vector of std::strings from a char** array. * @param sz Size of the array. * @param arr Array. * @param off The index to start at. Any elements that are skipped are ignored. * @returns StrVec */ inline WINCONSTEXPR static StrVec vectorize(const int& sz, char** arr, const int& off = 0) { StrVec vec; vec.reserve(sz); for (int i{ off }; i < sz; ++i) vec.emplace_back(std::string{ std::move(arr[i]) }); vec.shrink_to_fit(); return vec; } }
50.16309
311
0.68027
radj307
99d41aea8798baa57332d1f404ff490082d44c22
20,368
cpp
C++
export/release/macos/obj/src/PauseSubState.cpp
tikycookies/KE1.3.1Week7Bulid
4c51f87f87510f3d1289fa292215e67e09cf109b
[ "Apache-2.0" ]
null
null
null
export/release/macos/obj/src/PauseSubState.cpp
tikycookies/KE1.3.1Week7Bulid
4c51f87f87510f3d1289fa292215e67e09cf109b
[ "Apache-2.0" ]
null
null
null
export/release/macos/obj/src/PauseSubState.cpp
tikycookies/KE1.3.1Week7Bulid
4c51f87f87510f3d1289fa292215e67e09cf109b
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.2.2 #include <hxcpp.h> #ifndef INCLUDED_Alphabet #include <Alphabet.h> #endif #ifndef INCLUDED_Controls #include <Controls.h> #endif #ifndef INCLUDED_CoolUtil #include <CoolUtil.h> #endif #ifndef INCLUDED_MainMenuState #include <MainMenuState.h> #endif #ifndef INCLUDED_MusicBeatState #include <MusicBeatState.h> #endif #ifndef INCLUDED_MusicBeatSubstate #include <MusicBeatSubstate.h> #endif #ifndef INCLUDED_Paths #include <Paths.h> #endif #ifndef INCLUDED_PauseSubState #include <PauseSubState.h> #endif #ifndef INCLUDED_PlayState #include <PlayState.h> #endif #ifndef INCLUDED_PlayerSettings #include <PlayerSettings.h> #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_Type #include <Type.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_FlxCamera #include <flixel/FlxCamera.h> #endif #ifndef INCLUDED_flixel_FlxG #include <flixel/FlxG.h> #endif #ifndef INCLUDED_flixel_FlxGame #include <flixel/FlxGame.h> #endif #ifndef INCLUDED_flixel_FlxObject #include <flixel/FlxObject.h> #endif #ifndef INCLUDED_flixel_FlxSprite #include <flixel/FlxSprite.h> #endif #ifndef INCLUDED_flixel_FlxState #include <flixel/FlxState.h> #endif #ifndef INCLUDED_flixel_FlxSubState #include <flixel/FlxSubState.h> #endif #ifndef INCLUDED_flixel_addons_transition_FlxTransitionableState #include <flixel/addons/transition/FlxTransitionableState.h> #endif #ifndef INCLUDED_flixel_addons_transition_TransitionData #include <flixel/addons/transition/TransitionData.h> #endif #ifndef INCLUDED_flixel_addons_ui_FlxUIState #include <flixel/addons/ui/FlxUIState.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IEventGetter #include <flixel/addons/ui/interfaces/IEventGetter.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IFlxUIState #include <flixel/addons/ui/interfaces/IFlxUIState.h> #endif #ifndef INCLUDED_flixel_group_FlxTypedGroup #include <flixel/group/FlxTypedGroup.h> #endif #ifndef INCLUDED_flixel_group_FlxTypedSpriteGroup #include <flixel/group/FlxTypedSpriteGroup.h> #endif #ifndef INCLUDED_flixel_input_FlxBaseKeyList #include <flixel/input/FlxBaseKeyList.h> #endif #ifndef INCLUDED_flixel_input_FlxKeyManager #include <flixel/input/FlxKeyManager.h> #endif #ifndef INCLUDED_flixel_input_IFlxInputManager #include <flixel/input/IFlxInputManager.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxAction #include <flixel/input/actions/FlxAction.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxActionDigital #include <flixel/input/actions/FlxActionDigital.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxActionSet #include <flixel/input/actions/FlxActionSet.h> #endif #ifndef INCLUDED_flixel_input_keyboard_FlxKeyList #include <flixel/input/keyboard/FlxKeyList.h> #endif #ifndef INCLUDED_flixel_input_keyboard_FlxKeyboard #include <flixel/input/keyboard/FlxKeyboard.h> #endif #ifndef INCLUDED_flixel_math_FlxPoint #include <flixel/math/FlxPoint.h> #endif #ifndef INCLUDED_flixel_math_FlxRandom #include <flixel/math/FlxRandom.h> #endif #ifndef INCLUDED_flixel_system_FlxSound #include <flixel/system/FlxSound.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_CameraFrontEnd #include <flixel/system/frontEnds/CameraFrontEnd.h> #endif #ifndef INCLUDED_flixel_system_frontEnds_SoundFrontEnd #include <flixel/system/frontEnds/SoundFrontEnd.h> #endif #ifndef INCLUDED_flixel_text_FlxText #include <flixel/text/FlxText.h> #endif #ifndef INCLUDED_flixel_text_FlxTextBorderStyle #include <flixel/text/FlxTextBorderStyle.h> #endif #ifndef INCLUDED_flixel_tweens_FlxEase #include <flixel/tweens/FlxEase.h> #endif #ifndef INCLUDED_flixel_tweens_FlxTween #include <flixel/tweens/FlxTween.h> #endif #ifndef INCLUDED_flixel_tweens_misc_VarTween #include <flixel/tweens/misc/VarTween.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif #ifndef INCLUDED_flixel_util_IFlxPooled #include <flixel/util/IFlxPooled.h> #endif #ifndef INCLUDED_openfl_display_DisplayObject #include <openfl/display/DisplayObject.h> #endif #ifndef INCLUDED_openfl_display_DisplayObjectContainer #include <openfl/display/DisplayObjectContainer.h> #endif #ifndef INCLUDED_openfl_display_IBitmapDrawable #include <openfl/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl_display_InteractiveObject #include <openfl/display/InteractiveObject.h> #endif #ifndef INCLUDED_openfl_display_Sprite #include <openfl/display/Sprite.h> #endif #ifndef INCLUDED_openfl_events_EventDispatcher #include <openfl/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_IEventDispatcher #include <openfl/events/IEventDispatcher.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_17d383cbce329512_16_new,"PauseSubState","new",0x00d575d9,"PauseSubState.new","PauseSubState.hx",16,0x953dc7b7) static const ::String _hx_array_data_08e59567_2[] = { HX_("Resume",cd,dd,18,3d),HX_("Restart Song",06,b6,fe,13),HX_("Exit to menu",82,87,9a,a9), }; HX_LOCAL_STACK_FRAME(_hx_pos_17d383cbce329512_81_update,"PauseSubState","update",0x6d53d230,"PauseSubState.update","PauseSubState.hx",81,0x953dc7b7) HX_LOCAL_STACK_FRAME(_hx_pos_17d383cbce329512_124_destroy,"PauseSubState","destroy",0xc2ba82f3,"PauseSubState.destroy","PauseSubState.hx",124,0x953dc7b7) HX_LOCAL_STACK_FRAME(_hx_pos_17d383cbce329512_131_changeSelection,"PauseSubState","changeSelection",0x8f960fb5,"PauseSubState.changeSelection","PauseSubState.hx",131,0x953dc7b7) void PauseSubState_obj::__construct(Float x,Float y){ HX_GC_STACKFRAME(&_hx_pos_17d383cbce329512_16_new) HXLINE( 21) this->curSelected = 0; HXLINE( 20) this->menuItems = ::Array_obj< ::String >::fromData( _hx_array_data_08e59567_2,3); HXLINE( 27) super::__construct(); HXLINE( 29) ::flixel::_hx_system::FlxSound _hx_tmp = ::flixel::_hx_system::FlxSound_obj::__alloc( HX_CTX ); HXDLIN( 29) ::String library = null(); HXDLIN( 29) this->pauseMusic = _hx_tmp->loadEmbedded(::Paths_obj::getPath((((HX_("music/",ea,bf,1b,3f) + HX_("breakfast",db,b2,0c,49)) + HX_(".",2e,00,00,00)) + HX_("ogg",4f,94,54,00)),HX_("MUSIC",85,08,49,8e),library),true,true,null()); HXLINE( 30) this->pauseMusic->set_volume(( (Float)(0) )); HXLINE( 31) ::flixel::_hx_system::FlxSound _hx_tmp1 = this->pauseMusic; HXDLIN( 31) ::flixel::math::FlxRandom _hx_tmp2 = ::flixel::FlxG_obj::random; HXDLIN( 31) _hx_tmp1->play(false,_hx_tmp2->_hx_int(0,::Std_obj::_hx_int((this->pauseMusic->_length / ( (Float)(2) ))),null()),null()); HXLINE( 33) ::flixel::FlxG_obj::sound->list->add(this->pauseMusic).StaticCast< ::flixel::_hx_system::FlxSound >(); HXLINE( 35) ::flixel::FlxSprite bg = ::flixel::FlxSprite_obj::__alloc( HX_CTX ,null(),null(),null())->makeGraphic(::flixel::FlxG_obj::width,::flixel::FlxG_obj::height,-16777216,null(),null()); HXLINE( 36) bg->set_alpha(( (Float)(0) )); HXLINE( 37) bg->scrollFactor->set(null(),null()); HXLINE( 38) this->add(bg); HXLINE( 40) ::flixel::text::FlxText levelInfo = ::flixel::text::FlxText_obj::__alloc( HX_CTX ,20,15,0,HX_("",00,00,00,00),32,null()); HXLINE( 41) levelInfo->set_text(( (::String)((levelInfo->text + ::PlayState_obj::SONG->__Field(HX_("song",d5,23,58,4c),::hx::paccDynamic))) )); HXLINE( 42) levelInfo->scrollFactor->set(null(),null()); HXLINE( 43) levelInfo->setFormat((HX_("assets/fonts/",37,ff,a5,9c) + HX_("vcr.ttf",9d,d2,a7,82)),32,null(),null(),null(),null(),null()); HXLINE( 44) levelInfo->updateHitbox(); HXLINE( 45) this->add(levelInfo); HXLINE( 47) ::flixel::text::FlxText levelDifficulty = ::flixel::text::FlxText_obj::__alloc( HX_CTX ,20,47,0,HX_("",00,00,00,00),32,null()); HXLINE( 48) ::String levelDifficulty1 = levelDifficulty->text; HXDLIN( 48) levelDifficulty->set_text((levelDifficulty1 + ::CoolUtil_obj::difficultyString())); HXLINE( 49) levelDifficulty->scrollFactor->set(null(),null()); HXLINE( 50) levelDifficulty->setFormat((HX_("assets/fonts/",37,ff,a5,9c) + HX_("vcr.ttf",9d,d2,a7,82)),32,null(),null(),null(),null(),null()); HXLINE( 51) levelDifficulty->updateHitbox(); HXLINE( 52) this->add(levelDifficulty); HXLINE( 54) levelDifficulty->set_alpha(( (Float)(0) )); HXLINE( 55) levelInfo->set_alpha(( (Float)(0) )); HXLINE( 57) int _hx_tmp3 = ::flixel::FlxG_obj::width; HXDLIN( 57) levelInfo->set_x((( (Float)(_hx_tmp3) ) - (levelInfo->get_width() + 20))); HXLINE( 58) int _hx_tmp4 = ::flixel::FlxG_obj::width; HXDLIN( 58) levelDifficulty->set_x((( (Float)(_hx_tmp4) ) - (levelDifficulty->get_width() + 20))); HXLINE( 60) ::flixel::tweens::FlxTween_obj::tween(bg, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("alpha",5e,a7,96,21),((Float)0.6))),((Float)0.4), ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("ease",ee,8b,0c,43),::flixel::tweens::FlxEase_obj::quartInOut_dyn()))); HXLINE( 61) ::flixel::tweens::FlxTween_obj::tween(levelInfo, ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("y",79,00,00,00),20) ->setFixed(1,HX_("alpha",5e,a7,96,21),1)),((Float)0.4), ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("startDelay",c1,af,3d,f3),((Float)0.3)) ->setFixed(1,HX_("ease",ee,8b,0c,43),::flixel::tweens::FlxEase_obj::quartInOut_dyn()))); HXLINE( 62) ::flixel::tweens::FlxTween_obj::tween(levelDifficulty, ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("y",79,00,00,00),(levelDifficulty->y + 5)) ->setFixed(1,HX_("alpha",5e,a7,96,21),1)),((Float)0.4), ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("startDelay",c1,af,3d,f3),((Float)0.5)) ->setFixed(1,HX_("ease",ee,8b,0c,43),::flixel::tweens::FlxEase_obj::quartInOut_dyn()))); HXLINE( 64) this->grpMenuShit = ::flixel::group::FlxTypedGroup_obj::__alloc( HX_CTX ,null()); HXLINE( 65) this->add(this->grpMenuShit); HXLINE( 67) { HXLINE( 67) int _g = 0; HXDLIN( 67) int _g1 = this->menuItems->length; HXDLIN( 67) while((_g < _g1)){ HXLINE( 67) _g = (_g + 1); HXDLIN( 67) int i = (_g - 1); HXLINE( 69) ::Alphabet songText = ::Alphabet_obj::__alloc( HX_CTX ,( (Float)(0) ),( (Float)(((70 * i) + 30)) ),this->menuItems->__get(i),true,false); HXLINE( 70) songText->isMenuItem = true; HXLINE( 71) songText->targetY = ( (Float)(i) ); HXLINE( 72) this->grpMenuShit->add(songText).StaticCast< ::Alphabet >(); } } HXLINE( 75) this->changeSelection(null()); HXLINE( 77) this->set_cameras(::Array_obj< ::Dynamic>::__new(1)->init(0,::flixel::FlxG_obj::cameras->list->__get((::flixel::FlxG_obj::cameras->list->length - 1)).StaticCast< ::flixel::FlxCamera >())); } Dynamic PauseSubState_obj::__CreateEmpty() { return new PauseSubState_obj; } void *PauseSubState_obj::_hx_vtable = 0; Dynamic PauseSubState_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< PauseSubState_obj > _hx_result = new PauseSubState_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool PauseSubState_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x62817b24) { if (inClassId<=(int)0x5661ffbf) { if (inClassId<=(int)0x519cdafb) { return inClassId==(int)0x00000001 || inClassId==(int)0x519cdafb; } else { return inClassId==(int)0x5661ffbf; } } else { return inClassId==(int)0x62817b24; } } else { if (inClassId<=(int)0x7ccf8994) { return inClassId==(int)0x7c795c9f || inClassId==(int)0x7ccf8994; } else { return inClassId==(int)0x7fce3ab0; } } } void PauseSubState_obj::update(Float elapsed){ HX_GC_STACKFRAME(&_hx_pos_17d383cbce329512_81_update) HXLINE( 82) if ((this->pauseMusic->_volume < ((Float)0.5))) { HXLINE( 83) ::flixel::_hx_system::FlxSound fh = this->pauseMusic; HXDLIN( 83) fh->set_volume((fh->_volume + (((Float)0.01) * elapsed))); } HXLINE( 85) this->super::update(elapsed); HXLINE( 87) bool upP = ::PlayerSettings_obj::player1->controls->_upP->check(); HXLINE( 88) bool downP = ::PlayerSettings_obj::player1->controls->_downP->check(); HXLINE( 89) bool accepted = ::PlayerSettings_obj::player1->controls->_accept->check(); HXLINE( 91) if (upP) { HXLINE( 93) this->changeSelection(-1); } HXLINE( 95) if (downP) { HXLINE( 97) this->changeSelection(1); } HXLINE( 100) if (accepted) { HXLINE( 102) ::String daSelected = this->menuItems->__get(this->curSelected); HXLINE( 104) ::String _hx_switch_0 = daSelected; if ( (_hx_switch_0==HX_("Exit to menu",82,87,9a,a9)) ){ HXLINE( 111) ::PlayState_obj::loadRep = false; HXLINE( 112) { HXLINE( 112) ::flixel::FlxState nextState = ::MainMenuState_obj::__alloc( HX_CTX ,null(),null()); HXDLIN( 112) if (::flixel::FlxG_obj::game->_state->switchTo(nextState)) { HXLINE( 112) ::flixel::FlxG_obj::game->_requestedState = nextState; } } HXLINE( 110) goto _hx_goto_3; } if ( (_hx_switch_0==HX_("Restart Song",06,b6,fe,13)) ){ HXLINE( 109) ::flixel::FlxState nextState = ( ( ::flixel::FlxState)(::Type_obj::createInstance(::Type_obj::getClass(::flixel::FlxG_obj::game->_state),::cpp::VirtualArray_obj::__new(0))) ); HXDLIN( 109) if (::flixel::FlxG_obj::game->_state->switchTo(nextState)) { HXLINE( 109) ::flixel::FlxG_obj::game->_requestedState = nextState; } HXDLIN( 109) goto _hx_goto_3; } if ( (_hx_switch_0==HX_("Resume",cd,dd,18,3d)) ){ HXLINE( 107) this->close(); HXDLIN( 107) goto _hx_goto_3; } _hx_goto_3:; } HXLINE( 116) ::flixel::input::keyboard::FlxKeyList _this = ( ( ::flixel::input::keyboard::FlxKeyList)(::flixel::FlxG_obj::keys->justPressed) ); HXDLIN( 116) bool _hx_tmp = _this->keyManager->checkStatus(74,_this->status); } void PauseSubState_obj::destroy(){ HX_STACKFRAME(&_hx_pos_17d383cbce329512_124_destroy) HXLINE( 125) this->pauseMusic->destroy(); HXLINE( 127) this->super::destroy(); } void PauseSubState_obj::changeSelection(::hx::Null< int > __o_change){ int change = __o_change.Default(0); HX_STACKFRAME(&_hx_pos_17d383cbce329512_131_changeSelection) HXLINE( 132) ::PauseSubState _hx_tmp = ::hx::ObjectPtr<OBJ_>(this); HXDLIN( 132) _hx_tmp->curSelected = (_hx_tmp->curSelected + change); HXLINE( 134) if ((this->curSelected < 0)) { HXLINE( 135) this->curSelected = (this->menuItems->length - 1); } HXLINE( 136) if ((this->curSelected >= this->menuItems->length)) { HXLINE( 137) this->curSelected = 0; } HXLINE( 139) int bullShit = 0; HXLINE( 141) { HXLINE( 141) int _g = 0; HXDLIN( 141) ::Array< ::Dynamic> _g1 = this->grpMenuShit->members; HXDLIN( 141) while((_g < _g1->length)){ HXLINE( 141) ::Alphabet item = _g1->__get(_g).StaticCast< ::Alphabet >(); HXDLIN( 141) _g = (_g + 1); HXLINE( 143) item->targetY = ( (Float)((bullShit - this->curSelected)) ); HXLINE( 144) bullShit = (bullShit + 1); HXLINE( 146) item->set_alpha(((Float)0.6)); HXLINE( 149) if ((item->targetY == 0)) { HXLINE( 151) item->set_alpha(( (Float)(1) )); } } } } HX_DEFINE_DYNAMIC_FUNC1(PauseSubState_obj,changeSelection,(void)) ::hx::ObjectPtr< PauseSubState_obj > PauseSubState_obj::__new(Float x,Float y) { ::hx::ObjectPtr< PauseSubState_obj > __this = new PauseSubState_obj(); __this->__construct(x,y); return __this; } ::hx::ObjectPtr< PauseSubState_obj > PauseSubState_obj::__alloc(::hx::Ctx *_hx_ctx,Float x,Float y) { PauseSubState_obj *__this = (PauseSubState_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(PauseSubState_obj), true, "PauseSubState")); *(void **)__this = PauseSubState_obj::_hx_vtable; __this->__construct(x,y); return __this; } PauseSubState_obj::PauseSubState_obj() { } void PauseSubState_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(PauseSubState); HX_MARK_MEMBER_NAME(grpMenuShit,"grpMenuShit"); HX_MARK_MEMBER_NAME(menuItems,"menuItems"); HX_MARK_MEMBER_NAME(curSelected,"curSelected"); HX_MARK_MEMBER_NAME(pauseMusic,"pauseMusic"); ::flixel::FlxSubState_obj::__Mark(HX_MARK_ARG); HX_MARK_END_CLASS(); } void PauseSubState_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(grpMenuShit,"grpMenuShit"); HX_VISIT_MEMBER_NAME(menuItems,"menuItems"); HX_VISIT_MEMBER_NAME(curSelected,"curSelected"); HX_VISIT_MEMBER_NAME(pauseMusic,"pauseMusic"); ::flixel::FlxSubState_obj::__Visit(HX_VISIT_ARG); } ::hx::Val PauseSubState_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"update") ) { return ::hx::Val( update_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"destroy") ) { return ::hx::Val( destroy_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"menuItems") ) { return ::hx::Val( menuItems ); } break; case 10: if (HX_FIELD_EQ(inName,"pauseMusic") ) { return ::hx::Val( pauseMusic ); } break; case 11: if (HX_FIELD_EQ(inName,"grpMenuShit") ) { return ::hx::Val( grpMenuShit ); } if (HX_FIELD_EQ(inName,"curSelected") ) { return ::hx::Val( curSelected ); } break; case 15: if (HX_FIELD_EQ(inName,"changeSelection") ) { return ::hx::Val( changeSelection_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val PauseSubState_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 9: if (HX_FIELD_EQ(inName,"menuItems") ) { menuItems=inValue.Cast< ::Array< ::String > >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"pauseMusic") ) { pauseMusic=inValue.Cast< ::flixel::_hx_system::FlxSound >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"grpMenuShit") ) { grpMenuShit=inValue.Cast< ::flixel::group::FlxTypedGroup >(); return inValue; } if (HX_FIELD_EQ(inName,"curSelected") ) { curSelected=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void PauseSubState_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("grpMenuShit",04,32,b8,f0)); outFields->push(HX_("menuItems",e1,15,e5,5c)); outFields->push(HX_("curSelected",fb,eb,ab,32)); outFields->push(HX_("pauseMusic",cf,6d,d3,e5)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo PauseSubState_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::flixel::group::FlxTypedGroup */ ,(int)offsetof(PauseSubState_obj,grpMenuShit),HX_("grpMenuShit",04,32,b8,f0)}, {::hx::fsObject /* ::Array< ::String > */ ,(int)offsetof(PauseSubState_obj,menuItems),HX_("menuItems",e1,15,e5,5c)}, {::hx::fsInt,(int)offsetof(PauseSubState_obj,curSelected),HX_("curSelected",fb,eb,ab,32)}, {::hx::fsObject /* ::flixel::_hx_system::FlxSound */ ,(int)offsetof(PauseSubState_obj,pauseMusic),HX_("pauseMusic",cf,6d,d3,e5)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *PauseSubState_obj_sStaticStorageInfo = 0; #endif static ::String PauseSubState_obj_sMemberFields[] = { HX_("grpMenuShit",04,32,b8,f0), HX_("menuItems",e1,15,e5,5c), HX_("curSelected",fb,eb,ab,32), HX_("pauseMusic",cf,6d,d3,e5), HX_("update",09,86,05,87), HX_("destroy",fa,2c,86,24), HX_("changeSelection",bc,98,b5,48), ::String(null()) }; ::hx::Class PauseSubState_obj::__mClass; void PauseSubState_obj::__register() { PauseSubState_obj _hx_dummy; PauseSubState_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("PauseSubState",67,95,e5,08); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(PauseSubState_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< PauseSubState_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = PauseSubState_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = PauseSubState_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
41.398374
239
0.713325
tikycookies
99d6829dce868bdbb3ac1e4949d7fa7b9730bea3
1,784
cpp
C++
src/core/exceptions.cpp
florianbehrens/DeCoF2
7d7c0e62c1773fe9fc6d245301fa28eb7e9c7865
[ "Apache-2.0" ]
2
2015-08-05T02:02:00.000Z
2020-12-10T05:51:10.000Z
src/core/exceptions.cpp
florianbehrens/DeCoF2
7d7c0e62c1773fe9fc6d245301fa28eb7e9c7865
[ "Apache-2.0" ]
33
2015-07-29T12:11:17.000Z
2020-07-11T13:16:00.000Z
src/core/exceptions.cpp
florianbehrens/DeCoF2
7d7c0e62c1773fe9fc6d245301fa28eb7e9c7865
[ "Apache-2.0" ]
6
2016-03-08T14:41:46.000Z
2020-07-09T12:56:52.000Z
/* * Copyright (c) 2014 Florian Behrens * * 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 "exceptions.h" namespace decof { runtime_error::runtime_error(int code, const char* what) : std::runtime_error(what), code_(code) { } int runtime_error::code() const { return code_; } access_denied_error::access_denied_error() : runtime_error(ACCESS_DENIED, "Access denied") { } invalid_parameter_error::invalid_parameter_error() : runtime_error(INVALID_PARAMETER, "Invalid parameter") { } wrong_type_error::wrong_type_error() : runtime_error(WRONG_TYPE, "Wrong type") { } invalid_value_error::invalid_value_error() : runtime_error(INVALID_VALUE, "Invalid value") { } unknown_operation_error::unknown_operation_error() : runtime_error(UNKNOWN_OPERATION, "Unknown operation") { } parse_error::parse_error() : runtime_error(PARSE_ERROR, "Parse error") { } not_implemented_error::not_implemented_error() : runtime_error(NOT_IMPLEMENTED, "Not implemented") { } invalid_userlevel_error::invalid_userlevel_error() : runtime_error(INVALID_USERLEVEL, "Invalid userlevel") { } not_subscribed_error::not_subscribed_error() : runtime_error(NOT_SUBSCRIBED, "Not subscribed") { } } // namespace decof
26.626866
107
0.735987
florianbehrens
99d89a1f86153a1352696b0a72b5daa2a804796b
11,381
cpp
C++
planning/freespace_planning_algorithms/src/astar_search.cpp
tzhong518/autoware.universe
580565a24ff9af8c86006905681f3d1036c8724a
[ "Apache-2.0" ]
null
null
null
planning/freespace_planning_algorithms/src/astar_search.cpp
tzhong518/autoware.universe
580565a24ff9af8c86006905681f3d1036c8724a
[ "Apache-2.0" ]
null
null
null
planning/freespace_planning_algorithms/src/astar_search.cpp
tzhong518/autoware.universe
580565a24ff9af8c86006905681f3d1036c8724a
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2019 Autoware Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "freespace_planning_algorithms/astar_search.hpp" #include <tier4_autoware_utils/tier4_autoware_utils.hpp> #include <tf2/utils.h> #ifdef USE_TF2_GEOMETRY_MSGS_DEPRECATED_HEADER #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #else #include <tf2_geometry_msgs/tf2_geometry_msgs.hpp> #endif #include <vector> namespace freespace_planning_algorithms { double calcReedsSheppDistance( const geometry_msgs::msg::Pose & p1, const geometry_msgs::msg::Pose & p2, double radius) { auto rs_space = ReedsSheppStateSpace(radius); ReedsSheppStateSpace::StateXYT pose0{p1.position.x, p1.position.y, tf2::getYaw(p1.orientation)}; ReedsSheppStateSpace::StateXYT pose1{p2.position.x, p2.position.y, tf2::getYaw(p2.orientation)}; return rs_space.distance(pose0, pose1); } void setYaw(geometry_msgs::msg::Quaternion * orientation, const double yaw) { *orientation = tier4_autoware_utils::createQuaternionFromYaw(yaw); } geometry_msgs::msg::Pose calcRelativePose( const geometry_msgs::msg::Pose & base_pose, const geometry_msgs::msg::Pose & pose) { tf2::Transform tf_transform; tf2::convert(base_pose, tf_transform); geometry_msgs::msg::TransformStamped transform; transform.transform = tf2::toMsg(tf_transform.inverse()); geometry_msgs::msg::PoseStamped transformed; geometry_msgs::msg::PoseStamped pose_orig; pose_orig.pose = pose; tf2::doTransform(pose_orig, transformed, transform); return transformed.pose; } geometry_msgs::msg::Pose node2pose(const AstarNode & node) { geometry_msgs::msg::Pose pose_local; pose_local.position.x = node.x; pose_local.position.y = node.y; pose_local.position.z = 0; pose_local.orientation = tier4_autoware_utils::createQuaternionFromYaw(node.theta); return pose_local; } AstarSearch::TransitionTable createTransitionTable( const double minimum_turning_radius, const double maximum_turning_radius, const int turning_radius_size, const double theta_size, const bool use_back) { // Vehicle moving for each angle AstarSearch::TransitionTable transition_table; transition_table.resize(theta_size); const double dtheta = 2.0 * M_PI / theta_size; // Minimum moving distance with one state update // arc = r * theta const auto & R_min = minimum_turning_radius; const auto & R_max = maximum_turning_radius; const double step_min = R_min * dtheta; const double dR = (R_max - R_min) / turning_radius_size; // NodeUpdate actions std::vector<NodeUpdate> forward_node_candidates; const NodeUpdate forward_straight{step_min, 0.0, 0.0, step_min, false, false}; forward_node_candidates.push_back(forward_straight); for (int i = 0; i < turning_radius_size + 1; ++i) { double R = R_min + i * dR; double step = R * dtheta; NodeUpdate forward_left{R * sin(dtheta), R * (1 - cos(dtheta)), dtheta, step, true, false}; NodeUpdate forward_right = forward_left.flipped(); forward_node_candidates.push_back(forward_left); forward_node_candidates.push_back(forward_right); } for (int i = 0; i < theta_size; i++) { const double theta = dtheta * i; for (const auto & nu : forward_node_candidates) { transition_table[i].push_back(nu.rotated(theta)); } if (use_back) { for (const auto & nu : forward_node_candidates) { transition_table[i].push_back(nu.reversed().rotated(theta)); } } } return transition_table; } AstarSearch::AstarSearch( const PlannerCommonParam & planner_common_param, const AstarParam & astar_param) : AbstractPlanningAlgorithm(planner_common_param), astar_param_(astar_param), goal_node_(nullptr), use_reeds_shepp_(true) { transition_table_ = createTransitionTable( planner_common_param_.minimum_turning_radius, planner_common_param_.maximum_turning_radius, planner_common_param_.turning_radius_size, planner_common_param_.theta_size, astar_param_.use_back); } void AstarSearch::setMap(const nav_msgs::msg::OccupancyGrid & costmap) { AbstractPlanningAlgorithm::setMap(costmap); const auto height = costmap_.info.height; const auto width = costmap_.info.width; // Initialize nodes nodes_.clear(); nodes_.resize(height); for (uint32_t i = 0; i < height; i++) { nodes_[i].resize(width); for (uint32_t j = 0; j < width; j++) { nodes_[i][j].resize(planner_common_param_.theta_size); } } } bool AstarSearch::makePlan( const geometry_msgs::msg::Pose & start_pose, const geometry_msgs::msg::Pose & goal_pose) { start_pose_ = global2local(costmap_, start_pose); goal_pose_ = global2local(costmap_, goal_pose); if (!setStartNode()) { return false; } if (!setGoalNode()) { return false; } return search(); } bool AstarSearch::setStartNode() { const auto index = pose2index(costmap_, start_pose_, planner_common_param_.theta_size); if (detectCollision(index)) { return false; } // Set start node AstarNode * start_node = getNodeRef(index); start_node->x = start_pose_.position.x; start_node->y = start_pose_.position.y; start_node->theta = 2.0 * M_PI / planner_common_param_.theta_size * index.theta; start_node->gc = 0; start_node->hc = estimateCost(start_pose_); start_node->is_back = false; start_node->status = NodeStatus::Open; start_node->parent = nullptr; // Push start node to openlist openlist_.push(start_node); return true; } bool AstarSearch::setGoalNode() { const auto index = pose2index(costmap_, goal_pose_, planner_common_param_.theta_size); if (detectCollision(index)) { return false; } return true; } double AstarSearch::estimateCost(const geometry_msgs::msg::Pose & pose) { double total_cost = 0.0; // Temporarily, until reeds_shepp gets stable. if (use_reeds_shepp_) { double radius = (planner_common_param_.minimum_turning_radius + planner_common_param_.maximum_turning_radius) * 0.5; total_cost += calcReedsSheppDistance(pose, goal_pose_, radius) * astar_param_.distance_heuristic_weight; } else { total_cost += tier4_autoware_utils::calcDistance2d(pose, goal_pose_) * astar_param_.distance_heuristic_weight; } return total_cost; } bool AstarSearch::search() { const rclcpp::Time begin = rclcpp::Clock(RCL_ROS_TIME).now(); // Start A* search while (!openlist_.empty()) { // Check time and terminate if the search reaches the time limit const rclcpp::Time now = rclcpp::Clock(RCL_ROS_TIME).now(); const double msec = (now - begin).seconds() * 1000.0; if (msec > planner_common_param_.time_limit) { return false; } // Expand minimum cost node AstarNode * current_node = openlist_.top(); openlist_.pop(); current_node->status = NodeStatus::Closed; if (isGoal(*current_node)) { goal_node_ = current_node; setPath(*current_node); return true; } // Transit const auto index_theta = discretizeAngle(current_node->theta, planner_common_param_.theta_size); for (const auto & transition : transition_table_[index_theta]) { const bool is_turning_point = transition.is_back != current_node->is_back; const double move_cost = is_turning_point ? planner_common_param_.reverse_weight * transition.distance : transition.distance; // Calculate index of the next state geometry_msgs::msg::Pose next_pose; next_pose.position.x = current_node->x + transition.shift_x; next_pose.position.y = current_node->y + transition.shift_y; setYaw(&next_pose.orientation, current_node->theta + transition.shift_theta); const auto next_index = pose2index(costmap_, next_pose, planner_common_param_.theta_size); if (detectCollision(next_index)) { continue; } // Compare cost AstarNode * next_node = getNodeRef(next_index); const double next_gc = current_node->gc + move_cost; if (next_node->status == NodeStatus::None || next_gc < next_node->gc) { next_node->status = NodeStatus::Open; next_node->x = next_pose.position.x; next_node->y = next_pose.position.y; next_node->theta = tf2::getYaw(next_pose.orientation); next_node->gc = next_gc; next_node->hc = estimateCost(next_pose); next_node->is_back = transition.is_back; next_node->parent = current_node; openlist_.push(next_node); continue; } } } // Failed to find path return false; } void AstarSearch::setPath(const AstarNode & goal_node) { std_msgs::msg::Header header; header.stamp = rclcpp::Clock(RCL_ROS_TIME).now(); header.frame_id = costmap_.header.frame_id; waypoints_.header = header; waypoints_.waypoints.clear(); // From the goal node to the start node const AstarNode * node = &goal_node; while (node != nullptr) { geometry_msgs::msg::PoseStamped pose; pose.header = header; pose.pose = local2global(costmap_, node2pose(*node)); // PlannerWaypoint PlannerWaypoint pw; pw.pose = pose; pw.is_back = node->is_back; waypoints_.waypoints.push_back(pw); // To the next node node = node->parent; } // Reverse the vector to be start to goal order std::reverse(waypoints_.waypoints.begin(), waypoints_.waypoints.end()); // Update first point direction if (waypoints_.waypoints.size() > 1) { waypoints_.waypoints.at(0).is_back = waypoints_.waypoints.at(1).is_back; } } bool AstarSearch::hasFeasibleSolution() { if (goal_node_ == nullptr) { return false; } const AstarNode * node = goal_node_; while (node != nullptr) { auto index = pose2index(costmap_, node2pose(*node), planner_common_param_.theta_size); if (isOutOfRange(index) || detectCollision(index)) { return false; } node = node->parent; } return true; } bool AstarSearch::isGoal(const AstarNode & node) { const double lateral_goal_range = planner_common_param_.lateral_goal_range / 2.0; const double longitudinal_goal_range = planner_common_param_.longitudinal_goal_range / 2.0; const double goal_angle = tier4_autoware_utils::deg2rad(planner_common_param_.angle_goal_range / 2.0); const auto relative_pose = calcRelativePose(goal_pose_, node2pose(node)); // Check conditions if (astar_param_.only_behind_solutions && relative_pose.position.x > 0) { return false; } if ( std::fabs(relative_pose.position.x) > longitudinal_goal_range || std::fabs(relative_pose.position.y) > lateral_goal_range) { return false; } const auto angle_diff = tier4_autoware_utils::normalizeRadian(tf2::getYaw(relative_pose.orientation)); if (std::abs(angle_diff) > goal_angle) { return false; } return true; } } // namespace freespace_planning_algorithms
30.759459
100
0.715315
tzhong518
99d900dec8334d8daefcbcdb8dbf61de033aa636
1,359
cpp
C++
plugin/jsbindings/manual/jsb_pluginx_extension_registration.cpp
CocosRobot/cocos2d-x
1a527ea331363cfe108b5e2f0ac04a61f8883527
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
1
2016-05-12T11:12:19.000Z
2016-05-12T11:12:19.000Z
plugin/jsbindings/manual/jsb_pluginx_extension_registration.cpp
nghialv/cocos2d-x
b44da014d2cc7e40689c4f28051e4877c6da3a8a
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
plugin/jsbindings/manual/jsb_pluginx_extension_registration.cpp
nghialv/cocos2d-x
b44da014d2cc7e40689c4f28051e4877c6da3a8a
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
#include "jsb_pluginx_extension_registration.h" #include "jsb_pluginx_manual_iap.h" static jsval anonEvaluate(JSContext *cx, JSObject *thisObj, const char* string) { jsval out; if (JS_EvaluateScript(cx, thisObj, string, strlen(string), "(string)", 1, &out) == JS_TRUE) { return out; } return JSVAL_VOID; } extern JSObject *jsb_ProtocolIAP_prototype; extern JSObject *jsb_ProtocolAds_prototype; extern JSObject *jsb_ProtocolSocial_prototype; void register_pluginx_js_extensions(JSContext* cx, JSObject* global) { // first, try to get the ns jsval nsval; JSObject *ns; JS_GetProperty(cx, global, "plugin", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); nsval = OBJECT_TO_JSVAL(ns); JS_SetProperty(cx, global, "plugin", &nsval); } else { JS_ValueToObject(cx, nsval, &ns); } JS_DefineFunction(cx, jsb_ProtocolIAP_prototype, "setResultListener", js_pluginx_ProtocolIAP_setResultListener, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, jsb_ProtocolAds_prototype, "setAdsListener", js_pluginx_ProtocolAds_setAdsListener, 1, JSPROP_READONLY | JSPROP_PERMANENT); JS_DefineFunction(cx, jsb_ProtocolSocial_prototype, "setResultListener", js_pluginx_ProtocolSocial_setResultListener, 1, JSPROP_READONLY | JSPROP_PERMANENT); }
39.970588
161
0.743194
CocosRobot
99db806d4d15bfe7004dd7ebe64f20046db00fde
2,356
cpp
C++
DISE_Server/src/Environment.cpp
castroaj/CPP_ROBUST_DISTRIBUTED_SYMMETRIC-KEY_ENCRYPTION
054dcccd0f2413bba815b9161544e3b884bbfb11
[ "Apache-2.0" ]
1
2021-04-12T01:23:53.000Z
2021-04-12T01:23:53.000Z
DISE_Server/src/Environment.cpp
castroaj/CPP_ROBUST_DISTRIBUTED_SYMMETRIC-KEY_ENCRYPTION
054dcccd0f2413bba815b9161544e3b884bbfb11
[ "Apache-2.0" ]
null
null
null
DISE_Server/src/Environment.cpp
castroaj/CPP_ROBUST_DISTRIBUTED_SYMMETRIC-KEY_ENCRYPTION
054dcccd0f2413bba815b9161544e3b884bbfb11
[ "Apache-2.0" ]
1
2021-05-16T07:11:46.000Z
2021-05-16T07:11:46.000Z
#include "../hdr/Environment.h" Environment::Environment() { set_compromised(false); } Environment::~Environment() { } void Environment::print_environment() { using namespace std; cout << "ENVIRONMENT:" << endl; cout << "\tThread Count: " << threadCount << endl; cout << "\tMachineNum: " << machineNum << endl; cout << "\tTotalKeys: " << totalKeyNum << endl; cout << "\tKeysPerMachine: " << keysPerMachine << endl; cout << "\tSizeOfEachKey: " << sizeOfEachKey << endl; cout << "\tN: " << N << endl; cout << "\tT: " << T << endl; if (compromised) { cout << "\tCompromised" << endl; } cout << "\tADDRESSES:" << endl; for (int i =0 ; i < addresses->size(); i++) { auto t = addresses->at(i); QTextStream(stdout) << "\t" << i << ": " << t->first << ":" << t->second << "\n"; } cout << "\tKEY LIST:" << endl; if (N != 24) { QMapIterator<int, unsigned char*> iter(*keyList); while (iter.hasNext()) { iter.next(); cout << "\t" << iter.key() << ": "; unsigned char* v = iter.value(); for (int i = 0; i < sizeOfEachKey; i++) printf("%x ", *(v + i)); cout << "\n"; } } else { cout << "\t\tKEY LIST RECIEVED IS TOO BIG TO PRINT" << endl; } cout << "\tOMEGA MATRIX" << endl; if (N != 24) { // iterate through n machines held keys QMap<int, QSet<int>*>::iterator rowIter; for (rowIter = omegaTable->begin(); rowIter != omegaTable->end(); ++rowIter) { std::cout << "\t" << rowIter.key() << ": "; // print key values in omega row QSet<int>* omegaRow = rowIter.value(); QSet<int>::iterator keyIter; for (keyIter = omegaRow->begin(); keyIter != omegaRow->end(); ++keyIter) std::cout << *keyIter << " "; std::cout << "\n"; } } else { cout << "\t\tMATRIX RECIEVED IS TOO BIG TO PRINT" << endl; } } bool Environment::server_owns_key(int server, int keyId) { return omegaTable->contains(server) && omegaTable->value(server)->contains(keyId); }
26.772727
90
0.471562
castroaj
99dfc50b4158042e6d5efc01c78c7f0c42195ed1
15,586
cpp
C++
packages/websocket/src/Endpoint.cpp
aaronchongth/soss_v2
b531c2046e24684670a4a2ea2fd3c134fcba0591
[ "Apache-2.0" ]
null
null
null
packages/websocket/src/Endpoint.cpp
aaronchongth/soss_v2
b531c2046e24684670a4a2ea2fd3c134fcba0591
[ "Apache-2.0" ]
null
null
null
packages/websocket/src/Endpoint.cpp
aaronchongth/soss_v2
b531c2046e24684670a4a2ea2fd3c134fcba0591
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "Endpoint.hpp" #include <cstdlib> namespace soss { namespace websocket { //============================================================================== struct CallHandle { std::string service_name; std::string service_type; std::string id; std::shared_ptr<void> connection_handle; }; //============================================================================== inline std::shared_ptr<CallHandle> make_call_handle( std::string service_name, std::string service_type, std::string id, std::shared_ptr<void> connection_handle) { return std::make_shared<CallHandle>( CallHandle{std::move(service_name), std::move(service_type), std::move(id), std::move(connection_handle)}); } //============================================================================== Endpoint::Endpoint() : _next_service_call_id(1) { // Do nothing } //============================================================================== bool Endpoint::configure( const RequiredTypes& types, const YAML::Node& configuration) { if(const YAML::Node encode_node = configuration[YamlEncodingKey]) { const std::string encoding_str = [&]() -> std::string { std::string encoding = encode_node.as<std::string>(""); std::transform(encoding.begin(), encoding.end(), encoding.begin(), ::tolower); return encoding; }(); if(encoding_str == YamlEncoding_Rosbridge_v2_0) { _encoding = make_rosbridge_v2_0(); } else { std::cerr << "[soss::websocket::SystemHnadle::configure] Unknown " << "encoding type was requested: [" << _encoding << "]" << std::endl; return false; } } else { _encoding = make_rosbridge_v2_0(); } if(!_encoding) { std::cerr << "[soss::websocket::SystemHandle::configure] Reached a line [" << __LINE__ << "] that should be impossible. Please report this " << "bug!" << std::endl; return false; } _endpoint = configure_endpoint(types, configuration); return static_cast<bool>(_endpoint); } //============================================================================== bool Endpoint::subscribe( const std::string& topic_name, const std::string& message_type, SubscriptionCallback callback, const YAML::Node& configuration) { _startup_messages.emplace_back( _encoding->encode_subscribe_msg( topic_name, message_type, "", configuration)); TopicSubscribeInfo& info = _topic_subscribe_info[topic_name]; info.type = message_type; info.callback = callback; return true; } //============================================================================== std::shared_ptr<TopicPublisher> Endpoint::advertise( const std::string& topic_name, const std::string& message_type, const YAML::Node& configuration) { return make_topic_publisher( topic_name, message_type, "", configuration, *this); } //============================================================================== bool Endpoint::create_client_proxy( const std::string& service_name, const std::string& service_type, RequestCallback callback, const YAML::Node& /*configuration*/) { ClientProxyInfo& info = _client_proxy_info[service_name]; info.type = service_type; info.callback = callback; return true; } //============================================================================== std::shared_ptr<ServiceProvider> Endpoint::create_service_proxy( const std::string& service_name, const std::string& service_type, const YAML::Node& configuration) { ServiceProviderInfo& info = _service_provider_info[service_name]; info.type = service_type; info.configuration = configuration; return make_service_provider(service_name, *this); } //============================================================================== void Endpoint::startup_advertisement( const std::string& topic, const std::string& message_type, const std::string& id, const YAML::Node& configuration) { TopicPublishInfo& info = _topic_publish_info[topic]; info.type = message_type; _startup_messages.emplace_back( _encoding->encode_advertise_msg( topic, message_type, id, configuration)); } //============================================================================== bool Endpoint::publish( const std::string& topic, const soss::Message& message) { const TopicPublishInfo& info = _topic_publish_info.at(topic); // If no one is listening, then don't bother publishing if(info.listeners.empty()) return true; for(const auto& v_handle : info.listeners) { auto connection_handle = _endpoint->get_con_from_hdl(v_handle.first); auto ec = connection_handle->send( _encoding->encode_publication_msg(topic, info.type, "", message)); if(ec) { std::cerr << "[soss::websocket::Endpoint] Failed to send publication on " << "topic [" << topic << "]: " << ec.message() << std::endl; } } return true; } //============================================================================== void Endpoint::call_service( const std::string& service, const soss::Message& request, ServiceClient& client, std::shared_ptr<void> call_handle) { const std::size_t id = _next_service_call_id++; const std::string id_str = std::to_string(id); _service_request_info[id_str] = {&client, std::move(call_handle)}; ServiceProviderInfo& provider_info = _service_provider_info.at(service); const std::string payload = _encoding->encode_call_service_msg( service, provider_info.type, request, id_str, provider_info.configuration); _endpoint->get_con_from_hdl(provider_info.connection_handle)->send(payload); } //============================================================================== void Endpoint::receive_response( std::shared_ptr<void> v_call_handle, const soss::Message& response) { const auto& call_handle = *static_cast<const CallHandle*>(v_call_handle.get()); auto connection_handle = _endpoint->get_con_from_hdl( call_handle.connection_handle); connection_handle->send( _encoding->encode_service_response_msg( call_handle.service_name, call_handle.service_type, call_handle.id, response, true)); } //============================================================================== void Endpoint::receive_topic_advertisement_ws( const std::string& topic_name, const std::string& message_type, const std::string& /*id*/, std::shared_ptr<void> connection_handle) { auto it = _topic_subscribe_info.find(topic_name); if(it != _topic_subscribe_info.end()) { TopicSubscribeInfo& info = it->second; if(message_type != info.type) { info.blacklist.insert(connection_handle); std::cerr << "[soss::websocket] A remote connection advertised a topic " << "we want to subscribe to [" << topic_name << "] but with " << "the wrong message type [" << message_type << "]. The " << "expected type is [" << info.type << "]. Messages from " << "this connection will be ignored." << std::endl; } else { info.blacklist.erase(connection_handle); } } } //============================================================================== void Endpoint::receive_topic_unadvertisement_ws( const std::string& /*topic_name*/, const std::string& /*id*/, std::shared_ptr<void> /*connection_handle*/) { // TODO(MXG): Do anything here? } //============================================================================== void Endpoint::receive_publication_ws( const std::string& topic_name, const soss::Message& message, std::shared_ptr<void> connection_handle) { auto it = _topic_subscribe_info.find(topic_name); if(it == _topic_subscribe_info.end()) return; TopicSubscribeInfo& info = it->second; if(info.blacklist.count(connection_handle) > 0) return; info.callback(message); } //============================================================================== void Endpoint::receive_subscribe_request_ws( const std::string& topic_name, const std::string& message_type, const std::string& id, std::shared_ptr<void> connection_handle) { auto insertion = _topic_publish_info.insert( std::make_pair(topic_name, TopicPublishInfo{})); const bool inserted = insertion.second; TopicPublishInfo& info = insertion.first->second; if(inserted) { std::cerr << "[soss::websocket] Received subscription request for a " << "topic that we are not currently advertising [" << topic_name << "]" << std::endl; } else { if(!message_type.empty() && message_type != info.type) { std::cerr << "[soss::websocket] Received subscription request for topic [" << topic_name << "], but the requested message type [" << message_type << "] does not match the one we are publishing " << "[" << info.type << "]" << std::endl; return; } } info.listeners[connection_handle].insert(id); } //============================================================================== void Endpoint::receive_unsubscribe_request_ws( const std::string& topic_name, const std::string& id, std::shared_ptr<void> connection_handle) { auto it = _topic_publish_info.find(topic_name); if(it == _topic_publish_info.end()) { std::cerr << "[soss::websocket] Received an unsubscription request for a " << "topic that we are not advertising [" << topic_name << "]" << std::endl; return; } TopicPublishInfo& info = it->second; auto lit = info.listeners.find(connection_handle); if(lit == info.listeners.end()) return; if(id.empty()) { // If id is empty, then we should erase this connection as a listener // entirely. info.listeners.erase(lit); return; } std::unordered_set<std::string>& listeners = lit->second; listeners.erase(id); if(listeners.empty()) { // If no more unique ids are listening from this connection, then // erase it entirely. info.listeners.erase(lit); } } //============================================================================== void Endpoint::receive_service_request_ws( const std::string& service_name, const soss::Message& request, const std::string& id, std::shared_ptr<void> connection_handle) { auto it = _client_proxy_info.find(service_name); if(it == _client_proxy_info.end()) { std::cerr << "[soss::websocket] Received a service request for a service " << "[" << service_name << "] that we are not providing!" << std::endl; return; } ClientProxyInfo& info = it->second; info.callback(request, *this, make_call_handle(service_name, info.type, id, connection_handle)); } //============================================================================== void Endpoint::receive_service_advertisement_ws( const std::string& service_name, const std::string& service_type, std::shared_ptr<void> connection_handle) { _service_provider_info[service_name] = ServiceProviderInfo{service_type, connection_handle, YAML::Node{}}; } //============================================================================== void Endpoint::receive_service_unadvertisement_ws( const std::string& service_name, const std::string& /*service_type*/, std::shared_ptr<void> connection_handle) { auto it = _service_provider_info.find(service_name); if(it == _service_provider_info.end()) return; if(it->second.connection_handle == connection_handle) _service_provider_info.erase(it); } //============================================================================== void Endpoint::receive_service_response_ws( const std::string& /*service_name*/, const soss::Message& response, const std::string& id, std::shared_ptr<void> /*connection_handle*/) { auto it = _service_request_info.find(id); if(it == _service_request_info.end()) { std::cerr << "[soss::websocket] A remote connection provided a service " << "response with an unrecognized id [" << id << "]" << std::endl; return; } // TODO(MXG): We could use the service_name and connection_handle info to // verify that the service response is coming from the source that we were // expecting. ServiceRequestInfo& info = it->second; info.client->receive_response(info.call_handle, response); _service_request_info.erase(it); } //============================================================================== const Encoding& Endpoint::get_encoding() const { return *_encoding; } //============================================================================== void Endpoint::notify_connection_opened( const WsCppConnectionPtr& connection_handle) { for(const std::string& msg : _startup_messages) connection_handle->send(msg); } //============================================================================== void Endpoint::notify_connection_closed( const std::shared_ptr<void>& connection_handle) { for(auto& entry : _topic_subscribe_info) entry.second.blacklist.erase(connection_handle); for(auto& entry : _topic_publish_info) entry.second.listeners.erase(connection_handle); std::vector<std::string> lost_services; lost_services.reserve(_service_provider_info.size()); for(auto& entry : _service_provider_info) { if(entry.second.connection_handle == connection_handle) lost_services.push_back(entry.first); } for(const std::string& s : lost_services) _service_provider_info.erase(s); // NOTE(MXG): We'll leave _service_request_info alone, because it's feasible // that the service response might arrive later after the other side has // reconnected. The downside is this could allow lost services to accumulate. } //============================================================================== int32_t parse_port(const YAML::Node& configuration) { if(const YAML::Node port_node = configuration[YamlPortKey]) { try { return port_node.as<int>(); } catch(const YAML::InvalidNode& v) { std::cerr << "[soss::websocket::SystemHandle::configure] Could not " << "parse an integer value for the port setting [" << port_node.as<std::string>("") << "]: " << v.what() << std::endl; } } else { std::cerr << "[soss::websocket::SystemHandle::configure] You must specify " << "a port setting in your soss-websocket configuration!" << std::endl; } return -1; } } // namespace websocket } // namespace soss
30.924603
80
0.582767
aaronchongth
99e1f5c832739d48cde45bb0df9897c4ec2275f2
482
hpp
C++
include/cage/http_request.hpp
pancpp/cage
3a4eb5e3b6d40e6dee8e61bf984c83bf336e5999
[ "BSL-1.0" ]
null
null
null
include/cage/http_request.hpp
pancpp/cage
3a4eb5e3b6d40e6dee8e61bf984c83bf336e5999
[ "BSL-1.0" ]
null
null
null
include/cage/http_request.hpp
pancpp/cage
3a4eb5e3b6d40e6dee8e61bf984c83bf336e5999
[ "BSL-1.0" ]
null
null
null
/** * COPYRIGHT (C) 2020 Leyuan Pan ALL RIGHTS RESERVED. * * @brief Conversion between beast http and cage http messages. * @author Leyuan Pan * @date Oct 06, 2020 */ #ifndef CAGE_HTTP_REQUEST_HPP_ #define CAGE_HTTP_REQUEST_HPP_ #include "boost/beast/http/message.hpp" #include "boost/beast/http/string_body.hpp" namespace cage { using HttpRequest = boost::beast::http::request<boost::beast::http::string_body>; } // namespace cage #endif // CAGE_HTTP_REQUEST_HPP_
21.909091
65
0.736515
pancpp
99e261bb14b4403a69f54d9b08dcf67c65edda30
108
cpp
C++
RTEngine/PCG/test-high/check-pcg64_k1024_fast.cpp
RootinTootinCoodin/RTEngine
916354d8868f6eca5675390071e3ec93df497ed3
[ "MIT" ]
613
2015-01-27T09:47:36.000Z
2022-03-17T20:26:02.000Z
third_party/pcg/test-high/check-pcg64_k1024_fast.cpp
Zephilinox/Enki
5f405fec9ae0f3c3344a99fbee590d76ed4dbe55
[ "MIT" ]
59
2015-03-12T23:11:48.000Z
2022-03-31T08:24:52.000Z
third_party/pcg/test-high/check-pcg64_k1024_fast.cpp
Zephilinox/Enki
5f405fec9ae0f3c3344a99fbee590d76ed4dbe55
[ "MIT" ]
104
2015-02-24T16:25:17.000Z
2022-03-22T09:55:51.000Z
#define RNG pcg64_k1024_fast #define TWO_ARG_INIT 0 #define AWKWARD_128BIT_CODE 1 #include "pcg-test.cpp"
15.428571
29
0.805556
RootinTootinCoodin
99e3cd0ed2ef72b24b43d22b3934e9d2b12f891d
4,722
cpp
C++
CPVulkan/Trampoline.cpp
MatthewSmit/CPVulkan
d96f2f6db4cbbabcc41c2023a48ec63d1950dec0
[ "MIT" ]
1
2019-11-13T00:47:05.000Z
2019-11-13T00:47:05.000Z
CPVulkan/Trampoline.cpp
MatthewSmit/CPVulkan
d96f2f6db4cbbabcc41c2023a48ec63d1950dec0
[ "MIT" ]
null
null
null
CPVulkan/Trampoline.cpp
MatthewSmit/CPVulkan
d96f2f6db4cbbabcc41c2023a48ec63d1950dec0
[ "MIT" ]
null
null
null
#include "Trampoline.h" // ReSharper disable CppUnusedIncludeDirective #include "CommandBuffer.h" #include "Device.h" #include "Instance.h" #include "PhysicalDevice.h" #include "Queue.h" #define CONCAT_IMPL(x, y) x##y #define MACRO_CONCAT(x, y) CONCAT_IMPL(x, y) #ifdef _MSC_VER # define GET_ARG_COUNT(_, ...) INTERNAL_EXPAND_ARGS_PRIVATE(INTERNAL_ARGS_AUGMENTER(__VA_ARGS__)) # define INTERNAL_ARGS_AUGMENTER(...) unused, __VA_ARGS__ # define INTERNAL_EXPAND(x) x # define INTERNAL_EXPAND_ARGS_PRIVATE(...) INTERNAL_EXPAND(INTERNAL_GET_ARG_COUNT_PRIVATE(__VA_ARGS__, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) # define INTERNAL_GET_ARG_COUNT_PRIVATE(_1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, _9_, _10_, _11_, _12_, _13_, _14_, _15_, _16_, _17_, _18_, _19_, _20_, _21_, _22_, _23_, _24_, _25_, _26_, _27_, _28_, _29_, _30_, _31_, _32_, _33_, _34_, _35_, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, count, ...) count #else # define GET_ARG_COUNT(...) INTERNAL_GET_ARG_COUNT_PRIVATE(__VA_ARGS__, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) # define INTERNAL_GET_ARG_COUNT_PRIVATE(_0, _1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, _9_, _10_, _11_, _12_, _13_, _14_, _15_, _16_, _17_, _18_, _19_, _20_, _21_, _22_, _23_, _24_, _25_, _26_, _27_, _28_, _29_, _30_, _31_, _32_, _33_, _34_, _35_, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, count, ...) count #endif #define GET_NAMES0 #define GET_NAMES1 , a #define GET_NAMES2 , a, b #define GET_NAMES3 , a, b, c #define GET_NAMES4 , a, b, c, d #define GET_NAMES5 , a, b, c, d, e #define GET_NAMES6 , a, b, c, d, e, f #define GET_NAMES7 , a, b, c, d, e, f, g #define GET_NAMES8 , a, b, c, d, e, f, g, h #define GET_NAMES9 , a, b, c, d, e, f, g, h, i #define GET_NAMES10 , a, b, c, d, e, f, g, h, i, j #define GET_NAMES11 , a, b, c, d, e, f, g, h, i, j, k #define GET_NAMES12 , a, b, c, d, e, f, g, h, i, j, k, l #define GET_NAMES13 , a, b, c, d, e, f, g, h, i, j, k, l, m #define GET_NAMES14 , a, b, c, d, e, f, g, h, i, j, k, l, m, n #define GET_NAMES(...) MACRO_CONCAT(GET_NAMES, GET_ARG_COUNT(__VA_ARGS__)) #define GET_ARGS0(_) #define GET_ARGS1(_, T0) , T0 a #define GET_ARGS2(_, T0, T1) , T0 a, T1 b #define GET_ARGS3(_, T0, T1, T2) , T0 a, T1 b, T2 c #define GET_ARGS4(_, T0, T1, T2, T3) , T0 a, T1 b, T2 c, T3 d #define GET_ARGS5(_, T0, T1, T2, T3, T4) , T0 a, T1 b, T2 c, T3 d, T4 e #define GET_ARGS6(_, T0, T1, T2, T3, T4, T5) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f #define GET_ARGS7(_, T0, T1, T2, T3, T4, T5, T6) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f, T6 g #define GET_ARGS8(_, T0, T1, T2, T3, T4, T5, T6, T7) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f, T6 g, T7 h #define GET_ARGS9(_, T0, T1, T2, T3, T4, T5, T6, T7, T8) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f, T6 g, T7 h, T8 i #define GET_ARGS10(_, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f, T6 g, T7 h, T8 i, T9 j #define GET_ARGS11(_, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f, T6 g, T7 h, T8 i, T9 j, T10 k #define GET_ARGS12(_, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f, T6 g, T7 h, T8 i, T9 j, T10 k, T11 l #define GET_ARGS13(_, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f, T6 g, T7 h, T8 i, T9 j, T10 k, T11 l, T12 m #define GET_ARGS14(_, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) , T0 a, T1 b, T2 c, T3 d, T4 e, T5 f, T6 g, T7 h, T8 i, T9 j, T10 k, T11 l, T12 m, T13 n #define GET_ARGS(...) MACRO_CONCAT(GET_ARGS, GET_ARG_COUNT(__VA_ARGS__))(__VA_ARGS__) #define VULKAN_FUNCTION(method, returnType, clazz, ...) VKAPI_ATTR returnType VKAPI_PTR __##clazz##_##method(void* ptr GET_ARGS(__VA_ARGS__)) noexcept\ {\ typedef returnType (VKAPI_PTR* FunctionArg)(__VA_ARGS__);\ const auto clazzMethod = &clazz::method;\ const auto redirect = *(FunctionArg*)&clazzMethod;\ return redirect(static_cast<uint8_t*>(ptr) + 16 GET_NAMES(__VA_ARGS__));\ } #include "VulkanFunctions.h" #undef VULKAN_FUNCTION
69.441176
439
0.626006
MatthewSmit
99e661e87df4b855ac57d42d331879f91de9791c
3,874
hpp
C++
cpp/src/core/dubinswind.hpp
arthur-bit-monnot/fire-rs-saop
321e16fceebf44e8e97b482c24f37fbf6dd7d162
[ "BSD-2-Clause" ]
13
2018-11-19T15:51:23.000Z
2022-01-16T11:24:21.000Z
cpp/src/core/dubinswind.hpp
fire-rs-laas/fire-rs-saop
321e16fceebf44e8e97b482c24f37fbf6dd7d162
[ "BSD-2-Clause" ]
14
2017-10-12T16:19:19.000Z
2018-03-12T12:07:56.000Z
cpp/src/core/dubinswind.hpp
fire-rs-laas/fire-rs-saop
321e16fceebf44e8e97b482c24f37fbf6dd7d162
[ "BSD-2-Clause" ]
4
2018-03-12T12:28:55.000Z
2021-07-07T18:32:17.000Z
/* Copyright (c) 2018, CNRS-LAAS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PLANNING_CPP_DUBINSWIND_HPP #define PLANNING_CPP_DUBINSWIND_HPP #include <cmath> #include <stdexcept> #include <vector> #include "../ext/dubins.h" #include "dubins3d.hpp" #include "waypoint.hpp" namespace SAOP { class DubinsWindPathNotFoundException : public std::invalid_argument { public: DubinsWindPathNotFoundException(const Waypoint3d& from, const Waypoint3d& to, WindVector wind, double uav_airspeed, std::string message) : std::invalid_argument( "DubinsWindPathNotFoundException [from " + from.to_string() + " to " + to.to_string() + " airspeed " + std::to_string(uav_airspeed) + " wind " + wind.to_string() + "] " + message + ".") {} }; class DubinsWind { public: DubinsWind(const Waypoint3d& from, const Waypoint3d& to, const WindVector& constant_wind, double uav_air_speed, double turn_radius); std::vector<Waypoint3d> sampled(double l_step) const; std::pair<std::vector<Waypoint3d>, std::vector<double>> sampled_with_time(double l_step) const; std::vector<Waypoint3d> sampled_airframe(double l_step) const; Waypoint3d start() const { return wp_s; } Waypoint3d end() const { return wp_e; } double d() const { return d_star; } double T() const { return dubins_path_length(&air_path) / air_speed; } double uav_airspeed() const { return air_speed; }; WindVector wind() const { return wind_vector; }; private: // start and end waypoints // See McGee2005 section I.B. for Orientation angle vs. Velociy direction Waypoint3d wp_s{0, 0, 0, 0}; // start waypoint (dir is velocity direction) Waypoint3d wp_e{0, 0, 0, 0}; // end waypoint (dir is velocity direction) // Path parameters WindVector wind_vector; double air_speed; double r_min; // Minimal possible radius double d_star; // Best d DubinsPath air_path = {}; double find_d(const Waypoint3d& from, const Waypoint3d& to, WindVector wind, double uav_speed, double turn_radius, DubinsPath* dubins_conf); opt<double> G(double d, const Waypoint3d& from, const Waypoint3d& to, WindVector wind, double uav_speed, double turn_radius, DubinsPath* dubins_air_conf); }; } #endif //PLANNING_CPP_DUBINSWIND_HPP
35.87037
119
0.67811
arthur-bit-monnot
99e999cb2bafedb3bd16d9e5c8c12cb22b522e24
1,605
hpp
C++
src/systems/physics/physics_task.hpp
vi3itor/Blunted2
318af452e51174a3a4634f3fe19b314385838992
[ "Unlicense" ]
56
2020-07-22T22:11:06.000Z
2022-03-09T08:11:43.000Z
GameplayFootball/src/systems/physics/physics_task.hpp
ElsevierSoftwareX/SOFTX-D-20-00016
48c28adb72aa167a251636bc92111b3c43c0be67
[ "MIT" ]
9
2021-04-22T07:06:25.000Z
2022-01-22T12:54:52.000Z
GameplayFootball/src/systems/physics/physics_task.hpp
ElsevierSoftwareX/SOFTX-D-20-00016
48c28adb72aa167a251636bc92111b3c43c0be67
[ "MIT" ]
20
2017-11-07T16:52:32.000Z
2022-01-25T02:42:48.000Z
// written by bastiaan konings schuiling 2008 - 2014 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #ifndef _HPP_SYSTEMS_PHYSICS_TASK #define _HPP_SYSTEMS_PHYSICS_TASK #include "defines.hpp" #include "systems/isystemtask.hpp" #include "wrappers/interface_physics.hpp" namespace blunted { class PhysicsSystem; class PhysicsTask : public ISystemTask { public: PhysicsTask(PhysicsSystem *system); virtual ~PhysicsTask(); virtual void operator()(); protected: void GetPhase(); void ProcessPhase(); void PutPhase(); bool quit; PhysicsSystem *physicsSystem; // remaining time to pass to next RenderFrame int remainder_ms; // resolution int timeStep_ms; unsigned long previousTime_ms; }; class PhysicsTaskCommand_StepTime : public Command { public: PhysicsTaskCommand_StepTime(IPhysicsWrapper *physics, int timediff_ms, int resolution_ms) : Command("StepTime"), physics(physics), timediff_ms(timediff_ms), resolution_ms(resolution_ms) {}; int remainder_ms; protected: virtual bool Execute(void *caller = NULL); IPhysicsWrapper *physics; int timediff_ms, resolution_ms; }; class PhysicsTaskCommand_UpdateGeometry : public Command { public: PhysicsTaskCommand_UpdateGeometry() : Command("UpdateGeometry") {} protected: virtual bool Execute(void *caller = NULL); }; } #endif
22.928571
195
0.704673
vi3itor
99f11e1787d02c32e8387f7bee594e5d5a325a7e
1,425
cpp
C++
insensitive-palindrome/solution.cpp
devcbandung/clashofcode-testdata-and-solution
fc0a9a85552ec15691018ec24e6020fdb5424ebd
[ "MIT" ]
5
2020-06-28T07:20:05.000Z
2020-07-01T08:13:08.000Z
insensitive-palindrome/solution.cpp
devcbandung/clashofcode-testdata-and-solution
fc0a9a85552ec15691018ec24e6020fdb5424ebd
[ "MIT" ]
null
null
null
insensitive-palindrome/solution.cpp
devcbandung/clashofcode-testdata-and-solution
fc0a9a85552ec15691018ec24e6020fdb5424ebd
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // Program kita akan tetap benar jika kita menggunakan toLowerCase char toUpperCase(char c) { // Jika c sudah upper-case, maka tidak perlu ubah apa-apa if ('A' <= c && c <= 'Z') { return c; } // Jika c bukan upper-case, maka asumsikan c adalah lower-case. // Kita dapat mengubah c menjadi upper-case dengan perhitungan sederhana. // c - 'a' menyatakan huruf ke berapa c, jika 'a' dihitung 0 dan 'z' dihitung 25. // maka, menambahkan nilai ini dengan 'A' akan menghasilkan huruf yang sama tapi dalam case yang berbeda. return c - 'a' + 'A'; } int main() { string s; cin >> s; int n = s.length(); bool isPalindrome = true; bool isSensitive = true; // iterasi dari kiri dan kanan secara simultan. // pada tiap iterasi, increment indeks di kiri dan decrement indeks di kanan. for (int l = 0, r = n-1; l < r; l++, r--) { // pertama-tama, bandingkan secara case-insenstive. if (toUpperCase(s[l]) != toUpperCase(s[r])) { isPalindrome = false; isSensitive = false; break; } // kemudian, baru bandingkan secara case-sensitive. if (s[l] != s[r]) { isSensitive = false; break; } } if (isPalindrome && isSensitive) { cout << "sensitive palindrome" << endl; } else if (isPalindrome) { cout << "insensitive palindrome" << endl; } else { cout << "not a palindrome" << endl; } }
29.6875
107
0.630877
devcbandung
99f3f735ac14ac41dee94f6848db8fa91d52f157
9,235
cpp
C++
Cores/Mednafen/mednafen/src/pce_fast/huc.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
3,459
2015-01-07T14:07:09.000Z
2022-03-25T03:51:10.000Z
Cores/Mednafen/mednafen/src/pce_fast/huc.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
1,046
2018-03-24T17:56:16.000Z
2022-03-23T08:13:09.000Z
Cores/Mednafen/mednafen/src/pce_fast/huc.cpp
ianclawson/Provenance
e9cc8c57f41a4d122a998cf53ffd69b1513d4205
[ "BSD-3-Clause" ]
549
2015-01-07T14:07:15.000Z
2022-01-07T16:13:05.000Z
/* Mednafen - Multi-system Emulator * * Portions of this file Copyright (C) 2004 Ki * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* TODO: Allow HuC6280 code to execute properly in the Street Fighter 2 mapper's bankswitched region. */ #include "pce.h" #include "pcecd.h" #include <mednafen/hw_misc/arcade_card/arcade_card.h> #include <mednafen/hash/md5.h> #include <mednafen/file.h> #include <mednafen/cdrom/CDInterface.h> #include <mednafen/mempatcher.h> #include <mednafen/compress/GZFileStream.h> #include "huc.h" namespace MDFN_IEN_PCE_FAST { static const uint8 BRAM_Init_String[8] = { 'H', 'U', 'B', 'M', 0x00, 0x88, 0x10, 0x80 }; //"HUBM\x00\x88\x10\x80"; ArcadeCard *arcade_card = NULL; static uint8 *HuCROM = NULL; static bool IsPopulous; bool PCE_IsCD; static uint8 SaveRAM[2048]; static DECLFW(ACPhysWrite) { arcade_card->PhysWrite(A, V); } static DECLFR(ACPhysRead) { return(arcade_card->PhysRead(A)); } static DECLFR(SaveRAMRead) { if((!PCE_IsCD || PCECD_IsBRAMEnabled()) && (A & 8191) < 2048) return(SaveRAM[A & 2047]); else return(0xFF); } static DECLFW(SaveRAMWrite) { if((!PCE_IsCD || PCECD_IsBRAMEnabled()) && (A & 8191) < 2048) SaveRAM[A & 2047] = V; } static DECLFR(HuCRead) { return ROMSpace[A]; } static DECLFW(HuCRAMWrite) { ROMSpace[A] = V; } static DECLFW(HuCRAMWriteCDSpecial) // Hyper Dyne Special hack { BaseRAM[0x2000 | (A & 0x1FFF)] = V; ROMSpace[A] = V; } static uint8 HuCSF2Latch = 0; static DECLFR(HuCSF2Read) { return(HuCROM[(A & 0x7FFFF) + 0x80000 + HuCSF2Latch * 0x80000 ]); // | (HuCSF2Latch << 19) ]); } static DECLFW(HuCSF2Write) { if((A & 0x1FFC) == 0x1FF0) { HuCSF2Latch = (A & 0x3); } } static void Cleanup(void) MDFN_COLD; static void Cleanup(void) { if(arcade_card) { delete arcade_card; arcade_card = NULL; } if(PCE_IsCD) { PCECD_Close(); } if(HuCROM) { delete[] HuCROM; HuCROM = NULL; } } static void LoadSaveMemory(const std::string& path, uint8* const data, const uint64 len) { try { GZFileStream fp(path, GZFileStream::MODE::READ); const uint64 fp_size_tmp = fp.size(); if(fp_size_tmp != len) throw MDFN_Error(0, _("Save game memory file \"%s\" is an incorrect size(%llu bytes). The correct size is %llu bytes."), path.c_str(), (unsigned long long)fp_size_tmp, (unsigned long long)len); fp.read(data, len); } catch(MDFN_Error &e) { if(e.GetErrno() != ENOENT) throw; } } uint32 HuC_Load(Stream* fp) { uint32 crc = 0; try { uint32 sf2_threshold = 2048 * 1024; uint32 sf2_required_size = 2048 * 1024 + 512 * 1024; uint64 len = fp->size(); if(len & 512) // Skip copier header. { len &= ~512; fp->seek(512, SEEK_SET); } uint64 m_len = (len + 8191)&~8191; bool sf2_mapper = false; if(m_len >= sf2_threshold) { sf2_mapper = true; if(m_len != sf2_required_size) m_len = sf2_required_size; } IsPopulous = 0; PCE_IsCD = 0; HuCROM = new uint8[m_len]; memset(HuCROM, 0xFF, m_len); fp->read(HuCROM, std::min<uint64>(m_len, len)); md5_context md5; md5.starts(); md5.update(HuCROM, std::min<uint64>(m_len, len)); md5.finish(MDFNGameInfo->MD5); crc = crc32(0, HuCROM, std::min<uint64>(m_len, len)); MDFN_printf(_("ROM: %lluKiB\n"), (unsigned long long)(std::min<uint64>(m_len, len) / 1024)); MDFN_printf(_("ROM CRC32: 0x%04x\n"), crc); MDFN_printf(_("ROM MD5: 0x%s\n"), md5_context::asciistr(MDFNGameInfo->MD5, 0).c_str()); memset(ROMSpace, 0xFF, 0x88 * 8192 + 8192); if(m_len == 0x60000) { memcpy(ROMSpace + 0x00 * 8192, HuCROM, 0x20 * 8192); memcpy(ROMSpace + 0x20 * 8192, HuCROM, 0x20 * 8192); memcpy(ROMSpace + 0x40 * 8192, HuCROM + 0x20 * 8192, 0x10 * 8192); memcpy(ROMSpace + 0x50 * 8192, HuCROM + 0x20 * 8192, 0x10 * 8192); memcpy(ROMSpace + 0x60 * 8192, HuCROM + 0x20 * 8192, 0x10 * 8192); memcpy(ROMSpace + 0x70 * 8192, HuCROM + 0x20 * 8192, 0x10 * 8192); } else if(m_len == 0x80000) { memcpy(ROMSpace + 0x00 * 8192, HuCROM, 0x40 * 8192); memcpy(ROMSpace + 0x40 * 8192, HuCROM + 0x20 * 8192, 0x20 * 8192); memcpy(ROMSpace + 0x60 * 8192, HuCROM + 0x20 * 8192, 0x20 * 8192); } else { memcpy(ROMSpace + 0x00 * 8192, HuCROM, (m_len < 1024 * 1024) ? m_len : 1024 * 1024); } for(int x = 0x00; x < 0x80; x++) { HuCPU.FastMap[x] = &ROMSpace[x * 8192]; HuCPU.PCERead[x] = HuCRead; } if(!memcmp(HuCROM + 0x1F26, "POPULOUS", strlen("POPULOUS"))) { uint8 *PopRAM = ROMSpace + 0x40 * 8192; memset(PopRAM, 0xFF, 32768); LoadSaveMemory(MDFN_MakeFName(MDFNMKF_SAV, 0, "sav"), PopRAM, 32768); IsPopulous = 1; MDFN_printf("Populous\n"); for(int x = 0x40; x < 0x44; x++) { HuCPU.FastMap[x] = &PopRAM[(x & 3) * 8192]; HuCPU.PCERead[x] = HuCRead; HuCPU.PCEWrite[x] = HuCRAMWrite; } MDFNMP_AddRAM(32768, 0x40 * 8192, PopRAM); } else { memset(SaveRAM, 0x00, 2048); memcpy(SaveRAM, BRAM_Init_String, 8); // So users don't have to manually intialize the file cabinet // in the CD BIOS screen. LoadSaveMemory(MDFN_MakeFName(MDFNMKF_SAV, 0, "sav"), SaveRAM, 2048); HuCPU.PCEWrite[0xF7] = SaveRAMWrite; HuCPU.PCERead[0xF7] = SaveRAMRead; MDFNMP_AddRAM(2048, 0xF7 * 8192, SaveRAM); } // 0x1A558 //if(len >= 0x20000 && !memcmp(HuCROM + 0x1A558, "STREET FIGHTER#", strlen("STREET FIGHTER#"))) if(sf2_mapper) { for(int x = 0x40; x < 0x80; x++) { HuCPU.PCERead[x] = HuCSF2Read; } HuCPU.PCEWrite[0] = HuCSF2Write; MDFN_printf("Street Fighter 2 Mapper\n"); HuCSF2Latch = 0; } } catch(...) { Cleanup(); throw; } return crc; } bool IsBRAMUsed(void) { if(memcmp(SaveRAM, BRAM_Init_String, 8)) // HUBM string is modified/missing return(1); for(int x = 8; x < 2048; x++) if(SaveRAM[x]) return(1); return(0); } void HuC_LoadCD(const std::string& bios_path) { static const std::vector<FileExtensionSpecStruct> KnownBIOSExtensions = { { ".pce", 0, gettext_noop("PC Engine ROM Image") }, { ".bin", -10, gettext_noop("PC Engine ROM Image") }, { ".bios", 0, gettext_noop("BIOS Image") }, }; try { MDFNFILE fp(&NVFS, bios_path.c_str(), KnownBIOSExtensions, _("CD BIOS")); memset(ROMSpace, 0xFF, 262144); if(fp.size() & 512) fp.seek(512, SEEK_SET); fp.read(ROMSpace, 262144); fp.Close(); PCE_IsCD = 1; PCE_InitCD(); MDFN_printf(_("Arcade Card Emulation: %s\n"), PCE_ACEnabled ? _("Enabled") : _("Disabled")); for(int x = 0; x < 0x40; x++) { HuCPU.FastMap[x] = &ROMSpace[x * 8192]; HuCPU.PCERead[x] = HuCRead; } for(int x = 0x68; x < 0x88; x++) { HuCPU.FastMap[x] = &ROMSpace[x * 8192]; HuCPU.PCERead[x] = HuCRead; HuCPU.PCEWrite[x] = HuCRAMWrite; } HuCPU.PCEWrite[0x80] = HuCRAMWriteCDSpecial; // Hyper Dyne Special hack MDFNMP_AddRAM(262144, 0x68 * 8192, ROMSpace + 0x68 * 8192); if(PCE_ACEnabled) { arcade_card = new ArcadeCard(); for(int x = 0x40; x < 0x44; x++) { HuCPU.PCERead[x] = ACPhysRead; HuCPU.PCEWrite[x] = ACPhysWrite; } } memset(SaveRAM, 0x00, 2048); memcpy(SaveRAM, BRAM_Init_String, 8); // So users don't have to manually intialize the file cabinet // in the CD BIOS screen. LoadSaveMemory(MDFN_MakeFName(MDFNMKF_SAV, 0, "sav"), SaveRAM, 2048); HuCPU.PCEWrite[0xF7] = SaveRAMWrite; HuCPU.PCERead[0xF7] = SaveRAMRead; MDFNMP_AddRAM(2048, 0xF7 * 8192, SaveRAM); } catch(...) { Cleanup(); throw; } } void HuC_StateAction(StateMem *sm, int load, int data_only) { SFORMAT StateRegs[] = { SFPTR8(ROMSpace + 0x40 * 8192, IsPopulous ? 32768 : 0), SFPTR8(SaveRAM, IsPopulous ? 0 : 2048), SFPTR8(ROMSpace + 0x68 * 8192, PCE_IsCD ? 262144 : 0), SFVAR(HuCSF2Latch), SFEND }; MDFNSS_StateAction(sm, load, data_only, StateRegs, "HuC"); if(load) HuCSF2Latch &= 0x3; if(PCE_IsCD) { PCECD_StateAction(sm, load, data_only); if(arcade_card) arcade_card->StateAction(sm, load, data_only); } } // // HuC_Kill() may be called before HuC_Load*() is called or even after it errors out, so we have a separate HuC_SaveNV() // to prevent save game file corruption in case of error. void HuC_Kill(void) { Cleanup(); } void HuC_SaveNV(void) { if(IsPopulous) { MDFN_DumpToFile(MDFN_MakeFName(MDFNMKF_SAV, 0, "sav"), ROMSpace + 0x40 * 8192, 32768); } else if(IsBRAMUsed()) { MDFN_DumpToFile(MDFN_MakeFName(MDFNMKF_SAV, 0, "sav"), SaveRAM, 2048); } } void HuC_Power(void) { if(PCE_IsCD) memset(ROMSpace + 0x68 * 8192, 0x00, 262144); if(arcade_card) arcade_card->Power(); } };
22.746305
197
0.653817
ianclawson
99f64b6766c922beb97bc9a7656c3dd73f4402ea
25,148
cpp
C++
src/pgen/exp_SedovTaylor.cpp
roarkhabegger/athena-public-version
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
[ "BSD-3-Clause" ]
null
null
null
src/pgen/exp_SedovTaylor.cpp
roarkhabegger/athena-public-version
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
[ "BSD-3-Clause" ]
null
null
null
src/pgen/exp_SedovTaylor.cpp
roarkhabegger/athena-public-version
3446d2f4601c1dbbfd7a98d4f53335d97e21e195
[ "BSD-3-Clause" ]
null
null
null
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file exp_default_pgen.cpp // \brief Provides default (empty) versions of all functions in problem generator files // This means user does not have to implement these functions if they are not needed. // // #include <algorithm> #include <cmath> #include <stdexcept> #include <string> #include <iostream> // Athena++ headers #include "../athena.hpp" #include "../athena_arrays.hpp" #include "../parameter_input.hpp" #include "../mesh/mesh.hpp" #include "../coordinates/coordinates.hpp" #include "../eos/eos.hpp" #include "../field/field.hpp" #include "../globals.hpp" #include "../hydro/hydro.hpp" #ifdef MPI_PARALLEL #include <mpi.h> #endif //======================================================================================== // Time Dependent Grid Functions // \brief Functions for time dependent grid, including two example boundary conditions //======================================================================================== Real WallVel(Real xf, int i, Real time, Real dt, int dir, AthenaArray<Real> gridData); void UpdateGridData(Mesh *pm); //Global Variables for OuterX1 Real ambDens; Real ambVel; Real ambPres; Real Eej; Real dej; Real Rej; void OuterX1_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh); void OuterX2_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh); void OuterX3_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh); void InnerX1_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh); void InnerX2_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh); void InnerX3_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh); //======================================================================================== //! \fn void WallVel(Real xf, int i, Real time, Real dt, int dir, AthenaArray<Real> gridData) // \brief Function that returns the velocity of cell wall i at location xf. Time, total // time step and direction are all given. Direction is one of 0,1,2, corresponding to x1,x2,x3 // and gridData is an athena array that contains overall mesh data. gridData is updated // before every time sub-step by the UpdateGridData function. Some instances do not need // this data to be updated and the UpdateGridData function can be left blank. The gridData // array is supposed to carry all mesh-level information, i.e. the information used for // multiple cell walls in the simulation. //======================================================================================== Real WallVel(Real xf, int i, Real time, Real dt, int dir, AthenaArray<Real> gridData) { Real retVal = 0.0; Real myVel = 0.0; Real vol = 0.0; Real vej = 0.0; Real tST = 0.0; Real myX = xf; if (COORDINATE_SYSTEM == "cartesian") { if (dir == gridData(1)){ if ((myX > 0.0)&&(gridData(3)>0.0)){ if (gridData(2)==0.0) retVal = 0.0; else retVal = gridData(2) * myX/gridData(3); } else if ((myX < 0.0)&&(gridData(0)<0.0)){ if (gridData(2) == 0.0) retVal = 0.0; else retVal = -1.0*gridData(2) * myX/gridData(0); } } else if (dir == gridData(5)) { if ((myX > 0.0)&&(gridData(7)>0.0)){ if (gridData(6)==0.0) retVal = 0.0; else retVal = gridData(6) * myX/gridData(7); } else if ((myX < 0.0)&&(gridData(4)<0.0)){ if (gridData(6) == 0.0) retVal = 0.0; else retVal = -1.0*gridData(6) * myX/gridData(4); } } else if (dir == gridData(9)) { if ((myX > 0.0)&&(gridData(11)>0.0)){ if (gridData(10)==0.0) retVal = 0.0; else retVal = gridData(10) * myX/gridData(11); } else if ((myX < 0.0)&&(gridData(8)<0.0)){ if (gridData(10) == 0.0) retVal = 0.0; else retVal = -1.0*gridData(10) * myX/gridData(8); } } } else if (COORDINATE_SYSTEM == "cylindrical") { if (dir != gridData(1)){ retVal = 0.0; } else if (myX<=gridData(0)){ retVal = 0.0; } else if (myX > gridData(0)){ if (gridData(2)==0.0) retVal = 0.0; else retVal = gridData(2) * (myX-gridData(0))/(gridData(3)-gridData(0)); } } else if (COORDINATE_SYSTEM == "spherical_polar") { vol = 4.0/3.0*M_PI*std::pow(Rej,3.0); vej = std::pow(Eej*2/(dej*vol),0.5); tST = std::pow(dej/ambDens,1.0/3.0)*Rej/vej; if (time < tST) { myVel =4* vej; } else { myVel =2*1.2*1.2* vej*std::pow(time/tST,-0.6)*1.16*1.17*0.4; } if (dir != gridData(1)){ retVal = 0.0; } else if (myX<=gridData(0)){ retVal = 0.0; } else if (myX > gridData(0)){ retVal = myVel * (myX-gridData(0))/(gridData(3)-gridData(0)); } } return retVal; } //======================================================================================== //! \fn void UpdateGridData(Mesh *pm) // \brief Function which can edit and calculate any terms in gridData, which is used // in the WallVel function. The object in mesh is GridData(i) and i can range over the // integers, limited by SetGridData argument in InitMeshUserData. See exp_blast for an // example use of this function. //======================================================================================== void UpdateGridData(Mesh *pm) { Real xMax; Real xMin; if (COORDINATE_SYSTEM == "cartesian") { xMax = pm->mesh_size.x1max; xMin = pm->mesh_size.x1min; pm->GridData(3) = xMax; pm->GridData(0) = xMin; xMax = pm->mesh_size.x2max; xMin = pm->mesh_size.x2min; pm->GridData(7) = xMax; pm->GridData(4) = xMin; xMax = pm->mesh_size.x3max; xMin = pm->mesh_size.x3min; pm->GridData(11) = xMax; pm->GridData(8) = xMin; Real myVel = 0.0; Real t = pm->time; Real vol = 4.0/3.0*M_PI*std::pow(Rej,3.0); Real vej = std::pow(Eej*2/(dej*vol),0.5); Real tST = std::pow(dej/ambDens,1.0/3.0)*Rej/vej; if (t < tST) { myVel = vej; } else { myVel = vej*std::pow(t/tST,-0.6)*1.16*1.17*0.4; } pm->GridData(2) = myVel; pm->GridData(6) = myVel; pm->GridData(10) = myVel; } else { xMax = pm->mesh_size.x1max; pm->GridData(3) = xMax; } return; } //======================================================================================== //! \fn void Mesh::InitUserMeshData(ParameterInput *pin) // \brief Function to initialize problem-specific data in Mesh class. Can also be used // to initialize variables which are global to (and therefore can be passed to) other // functions in this file. Called in Mesh constructor. //======================================================================================== void Mesh::InitUserMeshData(ParameterInput *pin) { //======================================================================================== //! \brief For a time dependent grid, make sure to use SetGridData, EnrollGridDiffEq, and // EnrollCalcGridData here. The boundary conditions are of course optional. Reflecting // is a good boundary function if a wall of the simulation is static. But if there is // any expansion of the grid, it is recommended that you use the UniformMedium condition // for the expanding boundary. Otherwise, reconstruction might fail because the data is // inaccurate (for example, periodic boundary conditions do not make sense // for an expanding grid). //======================================================================================== if (EXPANDING) { EnrollGridDiffEq(WallVel); if (COORDINATE_SYSTEM == "cartesian") { SetGridData(12); if (mesh_bcs[OUTER_X1] == GetBoundaryFlag("user")) { EnrollUserBoundaryFunction(OUTER_X1,OuterX1_UniformMedium); } if (mesh_bcs[OUTER_X2] == GetBoundaryFlag("user")) { EnrollUserBoundaryFunction(OUTER_X2,OuterX2_UniformMedium); } if (mesh_bcs[OUTER_X3] == GetBoundaryFlag("user")) { EnrollUserBoundaryFunction(OUTER_X3,OuterX3_UniformMedium); } if (mesh_bcs[INNER_X1] == GetBoundaryFlag("user")) { EnrollUserBoundaryFunction(INNER_X1,InnerX1_UniformMedium); } if (mesh_bcs[INNER_X2] == GetBoundaryFlag("user")) { EnrollUserBoundaryFunction(INNER_X2,InnerX2_UniformMedium); } if (mesh_bcs[INNER_X3] == GetBoundaryFlag("user")) { EnrollUserBoundaryFunction(INNER_X3,InnerX3_UniformMedium); } } else { SetGridData(4); if (mesh_bcs[OUTER_X1] == GetBoundaryFlag("user")) { EnrollUserBoundaryFunction(OUTER_X1,OuterX1_UniformMedium); } } EnrollCalcGridData(UpdateGridData); Rej = pin->GetReal("problem","radius"); ambPres = pin->GetOrAddReal("problem","pamb",1.0); ambDens = pin->GetOrAddReal("problem","damb",1.0); dej = pin->GetOrAddReal("problem","dej",ambDens); Eej = pin->GetOrAddReal("problem","Eej",0.0); ambVel = 0.0; if (COORDINATE_SYSTEM == "cartesian") { GridData(0) = mesh_size.x1min; GridData(1) = 1; GridData(2) = 0.0; GridData(3) = mesh_size.x1max; GridData(4) = mesh_size.x2min; GridData(5) = 2; GridData(6) = 0.0; GridData(7) = mesh_size.x2max; GridData(8) = mesh_size.x3min; GridData(9) = 3; GridData(10) = 0.0; GridData(11) = mesh_size.x3max; } else { GridData(0) = mesh_size.x1min; GridData(1) = 1; GridData(2) = 0.0; GridData(3) = mesh_size.x1max; } } return; } //======================================================================================== //! \fn void OuterX1_UniformMedium(MeshBlock *pmb, Coordinates *pco, // AthenaArray<Real> &prim,FaceField &b, Real time, // Real dt, int is, int ie, int js, int je, // int ks, int ke, int ngh) { // \brief Function for outer boundary being a uniform medium with density, velocity, // and pressure given by the global variables listed at the beginning of the file. //======================================================================================== void OuterX1_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh) { for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=1; i<=ngh; ++i) { prim(IVX,k,j,ie+i) = ambVel; prim(IDN,k,j,ie+i) = ambDens; prim(IPR,k,j,ie+i) = ambPres; prim(IVY,k,j,ie+i) = 0.0; prim(IVZ,k,j,ie+i) = 0.0; } } } // no magnetic fields in ambient medium if (MAGNETIC_FIELDS_ENABLED) { for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=1; i<=ngh; ++i) { b.x1f(k,j,(ie+i)) = 0.0; } } } for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je+1; ++j) { #pragma omp simd for (int i=1; i<=ngh; ++i) { b.x2f(k,j,(ie+i)) = 0.0; } } } for (int k=ks; k<=ke+1; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=1; i<=ngh; ++i) { b.x3f(k,j,(ie+i)) = 0.0; } } } } return; } //======================================================================================== //! \fn void OuterX2_UniformMedium(MeshBlock *pmb, Coordinates *pco, // AthenaArray<Real> &prim,FaceField &b, Real time, // Real dt, int is, int ie, int js, int je, // int ks, int ke, int ngh) { // \brief Function for outer boundary being a uniform medium with density, velocity, // and pressure given by the global variables listed at the beginning of the file. //======================================================================================== void OuterX2_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh) { for (int k=ks; k<=ke; ++k) { for (int i=is; i<=ie; ++i) { #pragma omp simd for (int j=1; j<=ngh; ++j) { prim(IVX,k,je+j,i) = ambVel; prim(IDN,k,je+j,i) = ambDens; prim(IPR,k,je+j,i) = ambPres; prim(IVY,k,je+j,i) = 0.0; prim(IVZ,k,je+j,i) = 0.0; } } } // no magnetic fields in ambient medium if (MAGNETIC_FIELDS_ENABLED) { for (int k=ks; k<=ke; ++k) { for (int i=is; i<=ie+1; ++i) { #pragma omp simd for (int j=1; j<=ngh; ++j) { b.x1f(k,je+j,i) = 0.0; } } } for (int k=ks; k<=ke; ++k) { for (int i=is; i<=ie; ++i) { #pragma omp simd for (int j=1; j<=ngh; ++j) { b.x2f(k,je+j,i) = 0.0; } } } for (int k=ks; k<=ke+1; ++k) { for (int i=is; i<=ie; ++i) { #pragma omp simd for (int j=1; j<=ngh; ++j) { b.x3f(k,je+j,i) = 0.0; } } } } return; } //======================================================================================== //! \fn void OuterX3_UniformMedium(MeshBlock *pmb, Coordinates *pco, // AthenaArray<Real> &prim,FaceField &b, Real time, // Real dt, int is, int ie, int js, int je, // int ks, int ke, int ngh) { // \brief Function for outer boundary being a uniform medium with density, velocity, // and pressure given by the global variables listed at the beginning of the file. //======================================================================================== void OuterX3_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh) { for (int j=js; j<=je; ++j) { for (int i=is; i<=ie; ++i) { #pragma omp simd for (int k=1; k<=ngh; ++k) { prim(IVX,ke+k,j,i) = ambVel; prim(IDN,ke+k,j,i) = ambDens; prim(IPR,ke+k,j,i) = ambPres; prim(IVY,ke+k,j,i) = 0.0; prim(IVZ,ke+k,j,i) = 0.0; } } } // no magnetic fields in ambient medium if (MAGNETIC_FIELDS_ENABLED) { for (int j=js; j<=je; ++j) { for (int i=is; i<=ie+1; ++i) { #pragma omp simd for (int k=1; k<=ngh; ++k) { b.x1f(ke+k,j,i) = 0.0; } } } for (int j=js; j<=je+1; ++j) { for (int i=is; i<=ie; ++i) { #pragma omp simd for (int k=1; k<=ngh; ++k) { b.x2f(ke+k,j,i) = 0.0; } } } for (int j=js; j<=je; ++j) { for (int i=is; i<=ie; ++i) { #pragma omp simd for (int k=1; k<=ngh; ++k) { b.x3f(ke+k,j,i) = 0.0; } } } } return; } //======================================================================================== //! \fn void InnerX1_UniformMedium(MeshBlock *pmb, Coordinates *pco, // AthenaArray<Real> &prim,FaceField &b, Real time, // Real dt, int is, int ie, int js, int je, // int ks, int ke, int ngh) { // \brief Function for inner boundary being a uniform medium with density, velocity, // and pressure given by the global variables listed at the beginning of the file. //======================================================================================== void InnerX1_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh) { for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=1; i<=ngh; ++i) { prim(IVX,k,j,is-i) = ambVel; prim(IDN,k,j,is-i) = ambDens; prim(IPR,k,j,is-i) = ambPres; prim(IVY,k,j,is-i) = 0.0; prim(IVZ,k,j,is-i) = 0.0; } } } // no magnetic fields in ambient medium if (MAGNETIC_FIELDS_ENABLED) { for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=1; i<=ngh; ++i) { b.x1f(k,j,(is-i)) = 0.0; } } } for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je+1; ++j) { #pragma omp simd for (int i=1; i<=ngh; ++i) { b.x2f(k,j,(is-i)) = 0.0; } } } for (int k=ks; k<=ke+1; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=1; i<=ngh; ++i) { b.x3f(k,j,(is-i)) = 0.0; } } } } return; } //======================================================================================== //! \fn void InnerX2_UniformMedium(MeshBlock *pmb, Coordinates *pco, // AthenaArray<Real> &prim,FaceField &b, Real time, // Real dt, int is, int ie, int js, int je, // int ks, int ke, int ngh) { // \brief Function for inner boundary being a uniform medium with density, velocity, // and pressure given by the global variables listed at the beginning of the file. //======================================================================================== void InnerX2_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh) { for (int k=ks; k<=ke; ++k) { for (int j=1; j<=ngh; ++j) { #pragma omp simd for (int i=is; i<=ie; ++i) { prim(IVX,k,js-j,i) = ambVel; prim(IDN,k,js-j,i) = ambDens; prim(IPR,k,js-j,i) = ambPres; prim(IVY,k,js-j,i) = 0.0; prim(IVZ,k,js-j,i) = 0.0; } } } // no magnetic fields in ambient medium if (MAGNETIC_FIELDS_ENABLED) { for (int k=ks; k<=ke; ++k) { for (int j=1; j<=ngh; ++j) { #pragma omp simd for (int i=is; i<=ie+1; ++i) { b.x1f(k,js-j,i) = 0.0; } } } for (int k=ks; k<=ke; ++k) { for (int j=1; j<=ngh; ++j) { #pragma omp simd for (int i=is; i<=ie; ++i) { b.x2f(k,js-j,i) = 0.0; } } } for (int k=ks; k<=ke+1; ++k) { for (int j=1; j<=ngh; ++j) { #pragma omp simd for (int i=is; i<=ie; ++i) { b.x3f(k,js-j,i) = 0.0; } } } } return; } //======================================================================================== //! \fn void InnerX3_UniformMedium(MeshBlock *pmb, Coordinates *pco, // AthenaArray<Real> &prim,FaceField &b, Real time, // Real dt, int is, int ie, int js, int je, // int ks, int ke, int ngh) { // \brief Function for inner boundary being a uniform medium with density, velocity, // and pressure given by the global variables listed at the beginning of the file. //======================================================================================== void InnerX3_UniformMedium(MeshBlock *pmb, Coordinates *pco, AthenaArray<Real> &prim, FaceField &b, Real time, Real dt, int is, int ie, int js, int je, int ks, int ke, int ngh) { for (int k=1; k<=ngh; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=is; i<=ie; ++i) { prim(IVX,ks-k,j,i) = ambVel; prim(IDN,ks-k,j,i) = ambDens; prim(IPR,ks-k,j,i) = ambPres; prim(IVY,ks-k,j,i) = 0.0; prim(IVZ,ks-k,j,i) = 0.0; } } } // no magnetic fields in ambient medium if (MAGNETIC_FIELDS_ENABLED) { for (int k=1; k<=ngh; ++k) { for (int j=js; j<=ke; ++j) { #pragma omp simd for (int i=is; i<=ie+1; ++i) { b.x1f(ks-1,j,i) = 0.0; } } } for (int k=1; k<=ngh; ++k) { for (int j=js; j<=je+1; ++j) { #pragma omp simd for (int i=is; i<=ie; ++i) { b.x2f(ks-k,j,i) = 0.0; } } } for (int k=1; k<=ngh; ++k) { for (int j=js; j<=je; ++j) { #pragma omp simd for (int i=is; i<=ie; ++i) { b.x3f(ks-k,j,i) = 0.0; } } } } return; } //======================================================================================== //! \fn void MeshBlock::ProblemGenerator(ParameterInput *pin) // \brief Should be used to set initial conditions. //======================================================================================== void MeshBlock::ProblemGenerator(ParameterInput *pin) { // In practice, this function should *always* be replaced by a version // that sets the initial conditions for the problem of interest. Real rout = pin->GetReal("problem","radius"); Rej = rout; Real dr = pin->GetOrAddReal("problem","ramp",0.1); Real rout2 = pin->GetReal("problem","radius2"); Real dr2 = pin->GetOrAddReal("problem","ramp2",0.1); ambPres = pin->GetOrAddReal("problem","pamb",1.0); ambDens = pin->GetOrAddReal("problem","damb",1.0); //Real prat = pin->GetReal("problem","prat"); dej = pin->GetOrAddReal("problem","dej",ambDens); Eej = pin->GetOrAddReal("problem","Eej",0.0); Real b0,angle; if (MAGNETIC_FIELDS_ENABLED) { b0 = pin->GetReal("problem","b0"); angle = (PI/180.0)*pin->GetReal("problem","angle"); } Real gamma = peos->GetGamma(); Real gm1 = gamma - 1.0; Real Pej = Eej * gm1 /(4/3*M_PI*std::pow(rout-0.5*dr,3)); Real KE = Eej; // get coordinates of center of blast, and convert to Cartesian if necessary Real x1_0 = pin->GetOrAddReal("problem","x1_0",0.0); Real x2_0 = pin->GetOrAddReal("problem","x2_0",0.0); Real x3_0 = pin->GetOrAddReal("problem","x3_0",0.0); Real x0,y0,z0; if (COORDINATE_SYSTEM == "cartesian") { x0 = x1_0; y0 = x2_0; z0 = x3_0; } else if (COORDINATE_SYSTEM == "cylindrical") { x0 = x1_0*std::cos(x2_0); y0 = x1_0*std::sin(x2_0); z0 = x3_0; } else if (COORDINATE_SYSTEM == "spherical_polar") { x0 = x1_0*std::sin(x2_0)*std::cos(x3_0); y0 = x1_0*std::sin(x2_0)*std::sin(x3_0); z0 = x1_0*std::cos(x2_0); } else { // Only check legality of COORDINATE_SYSTEM once in this function std::cout << "### FATAL ERROR in blast.cpp ProblemGenerator" << std::endl << "Unrecognized COORDINATE_SYSTEM= " << COORDINATE_SYSTEM << std::endl; } // setup uniform ambient medium with spherical over-pressured region for (int k=ks; k<=ke; k++) { for (int j=js; j<=je; j++) { for (int i=is; i<=ie; i++) { Real rad; if (COORDINATE_SYSTEM == "cartesian") { Real x = pcoord->x1v(i); Real y = pcoord->x2v(j); Real z = pcoord->x3v(k); rad = std::sqrt(SQR(x - x0) + SQR(y - y0) + SQR(z - z0)); } else if (COORDINATE_SYSTEM == "cylindrical") { Real x = pcoord->x1v(i)*std::cos(pcoord->x2v(j)); Real y = pcoord->x1v(i)*std::sin(pcoord->x2v(j)); Real z = pcoord->x3v(k); rad = std::sqrt(SQR(x - x0) + SQR(y - y0) + SQR(z - z0)); } else { // if (COORDINATE_SYSTEM == "spherical_polar") Real x = pcoord->x1v(i)*std::sin(pcoord->x2v(j))*std::cos(pcoord->x3v(k)); Real y = pcoord->x1v(i)*std::sin(pcoord->x2v(j))*std::sin(pcoord->x3v(k)); Real z = pcoord->x1v(i)*std::cos(pcoord->x2v(j)); rad = std::sqrt(SQR(x - x0) + SQR(y - y0) + SQR(z - z0)); } Real dens = ambDens; dens += dej*0.5*(1.0-std::tanh((rad-rout)/dr)); Real vel = 0.0; vel += rad*std::pow(KE*5/(2*M_PI*(ambDens+dej)),0.5)*std::pow(rout,-2.5)*0.5*(1.0-std::tanh((rad-rout)/dr)) + 0.75*rout*std::pow(KE*5/(2*M_PI*(ambDens+dej)),0.5)*std::pow(rout,-2.5)*0.5*(std::tanh((rad-rout)/dr)-std::tanh((rad-rout2)/dr2)); phydro->u(IDN,k,j,i) = dens; phydro->u(IM1,k,j,i) = vel*dens; phydro->u(IM2,k,j,i) = 0.0; phydro->u(IM3,k,j,i) = 0.0; if (NON_BAROTROPIC_EOS) { Real pres = ambPres; pres += Pej*0.5*(1.0-std::tanh((rad-rout)/dr)); phydro->u(IEN,k,j,i) =pres/gm1+0.5*vel*vel*dens; } if (NSCALARS > 0) { for (int n=NHYDRO-NSCALARS; n<NHYDRO; ++n) { phydro->u(n,k,j,i) = dens; } } }}} return; }
35.620397
143
0.513401
roarkhabegger
99fcf1d356a972ef915670d0f29c696130c9ffb7
2,640
cpp
C++
Axis.CommonLibrary/application/output/collectors/summarizers/SummaryNodeVelocityCollector.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.CommonLibrary/application/output/collectors/summarizers/SummaryNodeVelocityCollector.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.CommonLibrary/application/output/collectors/summarizers/SummaryNodeVelocityCollector.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#include "SummaryNodeVelocityCollector.hpp" #include <assert.h> #include "domain/elements/Node.hpp" #include "domain/analyses/NumericalModel.hpp" namespace aaocs = axis::application::output::collectors::summarizers; namespace aaoc = axis::application::output::collectors; namespace aaor = axis::application::output::recordsets; namespace ada = axis::domain::analyses; namespace ade = axis::domain::elements; namespace asmm = axis::services::messaging; aaocs::SummaryNodeVelocityCollector::SummaryNodeVelocityCollector(const axis::String& targetSetName, SummaryType summaryType ) : SummaryNode3DCollector(targetSetName, summaryType) { // nothing to do here } aaocs::SummaryNodeVelocityCollector::SummaryNodeVelocityCollector(const axis::String& targetSetName, SummaryType summaryType, aaoc::XDirectionState xState, aaoc::YDirectionState yState, aaoc::ZDirectionState zState ) : SummaryNode3DCollector(targetSetName, summaryType, xState, yState, zState) { // nothing to do here } aaocs::SummaryNodeVelocityCollector::~SummaryNodeVelocityCollector( void ) { // nothing to do here } aaocs::SummaryNodeVelocityCollector& aaocs::SummaryNodeVelocityCollector::Create( const axis::String& targetSetName, SummaryType summaryType ) { return *new aaocs::SummaryNodeVelocityCollector(targetSetName, summaryType); } aaocs::SummaryNodeVelocityCollector& aaocs::SummaryNodeVelocityCollector::Create( const axis::String& targetSetName, SummaryType summaryType, aaoc::XDirectionState xState, aaoc::YDirectionState yState, aaoc::ZDirectionState zState ) { return *new aaocs::SummaryNodeVelocityCollector(targetSetName, summaryType, xState, yState, zState); } void aaocs::SummaryNodeVelocityCollector::Destroy( void ) const { delete this; } real aaocs::SummaryNodeVelocityCollector::CollectValue( const asmm::ResultMessage&, const ade::Node& node, int directionIndex, const ada::NumericalModel& numericalModel ) { id_type vIdx = node.GetDoF(directionIndex).GetId(); return numericalModel.Kinematics().Velocity()(vIdx); } axis::String aaocs::SummaryNodeVelocityCollector::GetVariableName( bool plural ) const { if (plural) return _T("velocities"); return _T("velocity"); }
40
102
0.659848
renato-yuzup
8201fb56e961368defa50ec1093fde45507f9e71
483
cpp
C++
src/gkom/World.cpp
akowalew/mill-opengl
91ef11e6cdbfe691e0073d9883e42c0a29d29b45
[ "MIT" ]
null
null
null
src/gkom/World.cpp
akowalew/mill-opengl
91ef11e6cdbfe691e0073d9883e42c0a29d29b45
[ "MIT" ]
null
null
null
src/gkom/World.cpp
akowalew/mill-opengl
91ef11e6cdbfe691e0073d9883e42c0a29d29b45
[ "MIT" ]
null
null
null
#include "gkom/World.hpp" #include <cassert> #include "gkom/Logging.hpp" #include "gkom/Entity.hpp" namespace gkom { World::World() : logger_(Logging::getLogger("World")) { logger_("Initialized"); } World::~World() = default; Entity* World::createEntity() { logger_("Creating new entity..."); const auto& entity = entities.emplace_back(std::make_unique<Entity>()); assert(entity != nullptr); return entity.get(); } void World::clear() { entities.clear(); } } // gkom
14.636364
72
0.677019
akowalew