hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
ebbc339bf0e5777aaa57e473b13d2ae9d71ec356
6,165
cpp
C++
dali/integration-api/debug.cpp
smohantty/dali-core
b01725e68bf496872010ec0e148eaa848a582165
[ "Apache-2.0", "BSD-3-Clause" ]
21
2016-11-18T10:26:40.000Z
2021-11-02T09:46:15.000Z
dali/integration-api/debug.cpp
smohantty/dali-core
b01725e68bf496872010ec0e148eaa848a582165
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-10-18T17:39:12.000Z
2020-12-01T11:45:36.000Z
dali/integration-api/debug.cpp
smohantty/dali-core
b01725e68bf496872010ec0e148eaa848a582165
[ "Apache-2.0", "BSD-3-Clause" ]
16
2017-03-08T15:50:32.000Z
2021-05-24T06:58:10.000Z
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/integration-api/debug.h> // EXTERNAL INCLUDES #include <chrono> #include <cstdarg> namespace Dali { #ifdef DEBUG_ENABLED // Fake globals for gdb typedefs Dali::DebugPropertyValueArray gValueArray; Dali::DebugPropertyValueMap gValueMap; #endif namespace Integration { namespace Log { thread_local LogFunction gthreadLocalLogFunction = nullptr; /* Forward declarations */ std::string FormatToString(const char* format, ...); std::string ArgListToString(const char* format, va_list args); void LogMessage(DebugPriority priority, const char* format, ...) { if(!gthreadLocalLogFunction) { return; } va_list arg; va_start(arg, format); std::string message = ArgListToString(format, arg); va_end(arg); gthreadLocalLogFunction(priority, message); } void InstallLogFunction(const LogFunction& logFunction) { // TLS stores a pointer to an object. // It needs to be allocated on the heap, because TLS will destroy it when the thread exits. gthreadLocalLogFunction = logFunction; } void UninstallLogFunction() { gthreadLocalLogFunction = nullptr; } #ifdef DEBUG_ENABLED /*Change false to true if trace is needed but don't commit to codeline*/ Filter* Filter::gRender = Filter::New(Debug::Concise, false, "LOG_RENDER"); Filter* Filter::gResource = Filter::New(Debug::Concise, false, "LOG_RESOURCE"); Filter* Filter::gGLResource = Filter::New(Debug::Concise, false, "LOG_GL_RESOURCE"); Filter* Filter::gObject = nullptr; Filter* Filter::gImage = Filter::New(Debug::Concise, false, "LOG_IMAGE"); Filter* Filter::gModel = Filter::New(Debug::Concise, false, "LOG_MODEL"); Filter* Filter::gNode = nullptr; Filter* Filter::gElement = nullptr; Filter* Filter::gActor = Filter::New(Debug::Concise, false, "LOG_ACTOR"); Filter* Filter::gShader = Filter::New(Debug::Concise, false, "LOG_SHADER"); Filter::FilterList* Filter::GetActiveFilters() { static Filter::FilterList* activeFilters = new FilterList; return activeFilters; } Filter* Filter::New(LogLevel level, bool trace, const char* environmentVariableName) { char* environmentVariableValue = getenv(environmentVariableName); if(environmentVariableValue) { unsigned int envLevel(0); char envTraceString(0); sscanf(environmentVariableValue, "%u,%c", &envLevel, &envTraceString); if(envLevel > Verbose) { envLevel = Verbose; } level = LogLevel(envLevel); // Just use 'f' and 't' as it's faster than doing full string comparisons if(envTraceString == 't') { trace = true; } else if(envTraceString == 'f') { trace = false; } } Filter* filter = new Filter(level, trace); filter->mNesting++; GetActiveFilters()->push_back(filter); return filter; } /** * Enable trace on all filters. */ void Filter::EnableGlobalTrace() { for(FilterIter iter = GetActiveFilters()->begin(); iter != GetActiveFilters()->end(); iter++) { (*iter)->EnableTrace(); } } /** * Disable trace on all filters. */ void Filter::DisableGlobalTrace() { for(FilterIter iter = GetActiveFilters()->begin(); iter != GetActiveFilters()->end(); iter++) { (*iter)->DisableTrace(); } } void Filter::SetGlobalLogLevel(LogLevel level) { for(FilterIter iter = GetActiveFilters()->begin(); iter != GetActiveFilters()->end(); iter++) { (*iter)->SetLogLevel(level); } } void Filter::Log(LogLevel level, const char* format, ...) { if(level <= mLoggingLevel) { va_list arg; va_start(arg, format); if(mTraceEnabled) { char* buffer = nullptr; int numChars = asprintf(&buffer, " %-*c %s", mNesting, ':', format); if(numChars >= 0) // No error { std::string message = ArgListToString(buffer, arg); LogMessage(DebugInfo, message.c_str()); free(buffer); } } else { std::string message = ArgListToString(format, arg); LogMessage(DebugInfo, message.c_str()); } va_end(arg); } } TraceObj::TraceObj(Filter* filter, const char* format, ...) : mFilter(filter) { if(mFilter && mFilter->IsTraceEnabled()) { va_list arg; va_start(arg, format); mMessage = ArgListToString(format, arg); va_end(arg); LogMessage(DebugInfo, "Entr%-*c %s\n", mFilter->mNesting, ':', mMessage.c_str()); ++mFilter->mNesting; } } TraceObj::~TraceObj() { if(mFilter && mFilter->IsTraceEnabled()) { if(mFilter->mNesting) { --mFilter->mNesting; } LogMessage(DebugInfo, "Exit%-*c %s\n", mFilter->mNesting, ':', mMessage.c_str()); } } #endif // DEBUG_ENABLED std::string ArgListToString(const char* format, va_list args) { std::string str; // empty string if(format != nullptr) { char* buffer = nullptr; int err = vasprintf(&buffer, format, args); if(err >= 0) // No error { str = buffer; free(buffer); } } return str; } std::string FormatToString(const char* format, ...) { va_list arg; va_start(arg, format); std::string s = ArgListToString(format, arg); va_end(arg); return s; } #ifdef DEBUG_ENABLED void GetNanoseconds(uint64_t& timeInNanoseconds) { // Get the time of a monotonic clock since its epoch. auto epoch = std::chrono::steady_clock::now().time_since_epoch(); auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(epoch); timeInNanoseconds = static_cast<uint64_t>(duration.count()); } #endif // DEBUG_ENABLED } // namespace Log } // namespace Integration } // namespace Dali
24.176471
95
0.673642
[ "object" ]
ebc18e735174fcb64813c539b3913b969ee7e51b
1,289
cc
C++
Consolidation3/P96766.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
Consolidation3/P96766.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
Consolidation3/P96766.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
//F011B. Palíndroms més llargs #include <iostream> #include <string> #include <vector> using namespace std; bool es_palindrom(const string& s){ int n = s.size(); for (int i = 0; i < n; ++i){ if (s[i] != s[n-1-i]) return false; } return true; } void omple(vector<string>& v){ for(int i = 0; i < v.size(); ++i){ cin >> v[i]; } } int main(){ int n; string pal; cout << "-----" << endl; while(cin >> n and n != 0){ int max = 0; vector<string> v(n); omple(v); for (int i = 0; i < n; ++i){ if(es_palindrom(v[i])){ if (v[i].size() > max){ max = v[i].size(); } } } bool cap = true; for (int i = 0; i < n; ++i){ if(es_palindrom(v[i]) and v[i].size() == max){ cout << v[i] << endl; cap = false; } } if(cap) cout << "cap palindrom" << endl; cout << "-----" << endl; } }
28.021739
70
0.324282
[ "vector" ]
ebc201e8fd7fa5789172d126406e4bf0153714d2
3,714
cpp
C++
range.example.cpp
badearobert/range
ddec92e44df8a8f9f021a03d3f92ec4b091f19de
[ "BSL-1.0" ]
null
null
null
range.example.cpp
badearobert/range
ddec92e44df8a8f9f021a03d3f92ec4b091f19de
[ "BSL-1.0" ]
null
null
null
range.example.cpp
badearobert/range
ddec92e44df8a8f9f021a03d3f92ec4b091f19de
[ "BSL-1.0" ]
null
null
null
// think-cell public library // // Copyright (C) 2016-2018 think-cell Software GmbH // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt #include "tc/range.h" #include "tc/format.h" #include "tc/make_c_str.h" #include <boost/range/adaptors.hpp> #include <vector> #include <cstdio> namespace { template <typename... Args> void print(Args&&... args) noexcept { std::printf("%s", boost::implicit_cast<char const*>(tc::make_c_str<char>(std::forward<Args>(args)...))); } //---- Basic ------------------------------------------------------------------------------------------------------------------ void basic () { std::vector<int> v = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; tc::for_each( tc::filter(v, [](const int& n){ return (n%2==0);}), [&](auto const& n) { print(tc::as_dec(n), ", "); } ); print("\n"); } //---- Generator Range -------------------------------------------------------------------------------------------------------- namespace { struct generator_range { template< typename Func > void operator()( Func func ) const& { for(int i=0;i<50;++i) { func(i); } } }; } void ex_generator_range () { tc::for_each( tc::filter( generator_range(), [](int i){ return i%2==0; } ), [](int i) { print(tc::as_dec(i), ", "); }); print("\n"); } //---- Generator Range (with break) ------------------------------------------------------------------------------------------- namespace { struct generator_range_break { template< typename Func > tc::break_or_continue operator()( Func func ) const& { using namespace tc; for(int i=0;i<5000;++i) { if (func(i)==break_) { return break_; } } return continue_; } }; } void ex_generator_range_break () { tc::for_each( tc::filter( generator_range_break(), [](int i){ return i%2==0; } ), [](int i) -> tc::break_or_continue { print(tc::as_dec(i), ", "); return (i>=50)? tc::break_ : tc::continue_; }); print("\n"); } //---- Stacked filters -------------------------------------------------------------------------------------------------------- void stacked_filters() { tc::for_each( tc::filter( tc::filter( tc::filter( generator_range_break(), [](int i){ return i%2!=0; } ), [](int i){ return i%3!=0; } ), [](int i){ return i%5!=0; } ) , [](int i) -> tc::break_or_continue { print(tc::as_dec(i), ", "); return (i>25)? tc::break_ : tc::continue_; }); print("\n"); } } int main() { print("-- Running Examples ----------\n"); basic(); ex_generator_range(); ex_generator_range_break(); stacked_filters(); using namespace tc; int av[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; auto v = std::vector<int> (av, av+sizeof(av)/sizeof(int)); //---- filter example with iterators ------------------------------------------- auto r = tc::filter( tc::filter( tc::filter( v, [](int i){ return i%2!=0; } ), [](int i){ return i%3!=0; } ), [](int i){ return i%5!=0; } ); for (auto it = std::begin(r), end = std::end(r); it != end; ++it) { print(tc::as_dec(*it), ", "); } print("\n"); //---- boost for comparison ----------------------------------------------------- auto br = v | boost::adaptors::filtered([](int i){ return i%2!=0; }) | boost::adaptors::filtered([](int i){ return i%3!=0; }) | boost::adaptors::filtered([](int i){ return i%5!=0; }); for (auto it = std::begin(br), end = std::end(br); it != end; ++it) { print(tc::as_dec(*it), ", "); } print("\n"); print("-- Done ----------\n"); std::fflush(stdout); return EXIT_SUCCESS; }
24.76
127
0.492461
[ "vector" ]
ebc78ed8ff4c0fde439f3e9ba6865fee44b97ab6
9,512
cpp
C++
test/unit/contrib/parallel/buffer_queue_parallel_test.cpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
283
2017-03-14T23:43:33.000Z
2022-03-28T02:30:02.000Z
test/unit/contrib/parallel/buffer_queue_parallel_test.cpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
2,754
2017-03-21T18:39:02.000Z
2022-03-31T13:26:15.000Z
test/unit/contrib/parallel/buffer_queue_parallel_test.cpp
joergi-w/seqan3
b757646eee3cddf1f2487db8f1c9f3576ee37391
[ "CC-BY-4.0", "CC0-1.0" ]
88
2017-03-20T12:43:42.000Z
2022-03-17T08:56:13.000Z
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <gtest/gtest.h> #include <atomic> #include <chrono> #include <numeric> #include <random> #include <thread> #include <seqan3/contrib/parallel/buffer_queue.hpp> template <typename sequential_push_t, typename sequential_pop_t> void test_buffer_queue_wait_status() { size_t thread_count = std::thread::hardware_concurrency(); // limit thread count as virtualbox (used by Travis) seems to have problems with thread congestion if (thread_count > 4) thread_count = 4; size_t writer_count = thread_count / 2; if constexpr (sequential_push_t::value) writer_count = 1; if constexpr (sequential_pop_t::value) thread_count = writer_count + 1; // std::cout << "threads: " << thread_count << ‘\n‘; // std::cout << "writers: " << writer_count << ‘\n‘; constexpr size_t size_v = 10000; seqan3::contrib::dynamic_buffer_queue<uint32_t> queue{100}; std::atomic<uint32_t> cnt{1}; // Define the producer section auto produce = [&]() { while (true) { // Load atomic uint32_t intermediate = cnt.fetch_add(1); if (intermediate > size_v) return; // wait semantics seqan3::contrib::queue_op_status status = queue.wait_push(intermediate); if (status != seqan3::contrib::queue_op_status::success) return; } }; // Define the consumer section std::atomic<uint32_t> sum{0}; auto consume = [&]() mutable { uint32_t i = 0; while (queue.wait_pop(i) != seqan3::contrib::queue_op_status::closed) sum.fetch_add(i, std::memory_order_relaxed); }; // Create producer pool std::vector<std::thread> producer_pool; for (size_t n = 0; n < writer_count; ++n) producer_pool.emplace_back(produce); // Create consumer pool std::vector<std::thread> consumer_pool; for (size_t n = 0; n < thread_count - writer_count; ++n) consumer_pool.emplace_back(consume); for (auto & t : producer_pool) { if (t.joinable()) t.join(); } // Notify queue that no more work is going to be added. queue.close(); for (auto & t : consumer_pool) { if (t.joinable()) t.join(); } EXPECT_EQ(sum.load(), (size_v * (size_v + 1)) / 2); } TEST(buffer_queue, spsc_sum) { test_buffer_queue_wait_status<std::true_type, std::true_type>(); } TEST(buffer_queue, spmc_sum) { test_buffer_queue_wait_status<std::true_type, std::false_type>(); } TEST(buffer_queue, mpsc_sum) { test_buffer_queue_wait_status<std::false_type, std::true_type>(); } TEST(buffer_queue, mpmc_sum) { test_buffer_queue_wait_status<std::false_type, std::false_type>(); } template <typename sequential_push_t, typename sequential_pop_t, seqan3::contrib::buffer_queue_policy buffer_policy> void test_buffer_queue_wait_throw(size_t initialCapacity) { using queue_t = seqan3::contrib::buffer_queue<size_t, std::vector<size_t>, buffer_policy>; queue_t queue{initialCapacity}; std::vector<size_t> random; std::mt19937 rng(0); size_t chk_sum = 0; random.resize(100000); for (size_t i = 0; i < random.size(); ++i) { random[i] = rng(); chk_sum ^= random[i]; } volatile std::atomic<size_t> chk_sum2 = 0; size_t thread_count = std::thread::hardware_concurrency(); // limit thread count as virtualbox (used by Travis) seems to have problems with thread congestion if (thread_count > 4) thread_count = 4; size_t writer_count = thread_count / 2; if constexpr (sequential_push_t::value) writer_count = 1; if constexpr (sequential_pop_t::value) thread_count = writer_count + 1; // std::cout << "threads: " << thread_count << ‘\n‘; // std::cout << "writers: " << writer_count << ‘\n‘; ASSERT_GE(thread_count, 2u); // std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); std::vector<std::thread> workers; std::atomic<size_t> registered_writer = 0; std::atomic<size_t> registered_reader = 0; seqan3::contrib::queue_op_status push_status = seqan3::contrib::queue_op_status::success; seqan3::contrib::queue_op_status pop_status = seqan3::contrib::queue_op_status::success; for (size_t tid = 0; tid < thread_count; ++tid) { workers.push_back(std::thread([&, tid]() { // Become writer! if (tid < writer_count) { { // Wait until all reader are present. seqan3::detail::spin_delay delay{}; ++registered_writer; while (registered_reader.load() < (thread_count - writer_count)) delay.wait(); } // printf("start writer #%ld\n", tid); size_t offset = tid * (random.size() / writer_count); size_t offset_end = std::min(static_cast<size_t>((tid + 1) * (random.size() / writer_count)), random.size()); for (size_t pos = offset; pos != offset_end; ++pos) { try { queue.push(random[pos]); } catch (seqan3::contrib::queue_op_status & ex) { push_status = ex; } } // printf("stop writer #%ld %lu\n", tid, offset_end - offset); // Last writer! No more values will come, so we close the queue. ++registered_writer; if (registered_writer.load() == (2 * writer_count)) { queue.close(); // printf("writer #%ld closed the queue\n", tid); } } // Become reader! if (tid >= writer_count) { { // Wait until all writers are setup. seqan3::detail::spin_delay delay{}; ++registered_reader; while (registered_writer.load() < writer_count) delay.wait(); } // printf("start reader #%lu\n", (long unsigned)tid); size_t chk_sum_local = 0, cnt = 0; for (;;) { try { size_t val = queue.value_pop(); chk_sum_local ^= val; ++cnt; // if ((cnt & 0xff) == 0) // printf("%ld ", tid); } catch (seqan3::contrib::queue_op_status & ex) { pop_status = ex; break; } } chk_sum2.fetch_xor(chk_sum_local); // printf("stop reader #%lu %lu\n", static_cast<size_t>(tid), cnt); } })); } for (auto & t : workers) { if (t.joinable()) t.join(); } // std::chrono::steady_clock::time_point stop = std::chrono::steady_clock::now(); // double time_span = std::chrono::duration_cast<std::chrono::duration<double> >(stop - start).count(); // std::cout << "throughput: " << static_cast<size_t>(random.size() / time_span) << " values/s\n"; EXPECT_EQ(chk_sum, chk_sum2); EXPECT_TRUE(push_status == seqan3::contrib::queue_op_status::success); EXPECT_TRUE(pop_status == seqan3::contrib::queue_op_status::closed); } TEST(buffer_queue, spsc_dynamicsize) { test_buffer_queue_wait_throw<std::true_type, std::true_type, seqan3::contrib::buffer_queue_policy::dynamic>(0u); } TEST(buffer_queue, spsc_fixedsize) { test_buffer_queue_wait_throw<std::true_type, std::true_type, seqan3::contrib::buffer_queue_policy::fixed>(30u); } TEST(buffer_queue, spmc_dynamicsize) { test_buffer_queue_wait_throw<std::true_type, std::false_type, seqan3::contrib::buffer_queue_policy::dynamic>(0u); } TEST(buffer_queue, spmc_fixedsize) { test_buffer_queue_wait_throw<std::true_type, std::false_type, seqan3::contrib::buffer_queue_policy::fixed>(30u); } TEST(buffer_queue, mpsc_dynamicsize) { test_buffer_queue_wait_throw<std::false_type, std::true_type, seqan3::contrib::buffer_queue_policy::dynamic>(0u); } TEST(buffer_queue, mpsc_fixedsize) { test_buffer_queue_wait_throw<std::false_type, std::true_type, seqan3::contrib::buffer_queue_policy::fixed>(30u); } TEST(buffer_queue, mpmc_dynamicsize) { test_buffer_queue_wait_throw<std::false_type, std::false_type, seqan3::contrib::buffer_queue_policy::dynamic>(0u); } TEST(buffer_queue, mpmc_fixedsize) { test_buffer_queue_wait_throw<std::false_type, std::false_type, seqan3::contrib::buffer_queue_policy::fixed>(30u); }
32.913495
118
0.574432
[ "vector" ]
ebc80844fccf6d3ae0feabbf739cd4ecf5f9a90b
6,248
cpp
C++
src/chroma/cpp/Sphere.cpp
bensteinert/chromarenderer
d29b1b080e7f7e4e8650eaa74f03752a07afdab8
[ "MIT" ]
null
null
null
src/chroma/cpp/Sphere.cpp
bensteinert/chromarenderer
d29b1b080e7f7e4e8650eaa74f03752a07afdab8
[ "MIT" ]
null
null
null
src/chroma/cpp/Sphere.cpp
bensteinert/chromarenderer
d29b1b080e7f7e4e8650eaa74f03752a07afdab8
[ "MIT" ]
1
2018-03-06T03:31:08.000Z
2018-03-06T03:31:08.000Z
#include <iostream> #include "Chroma.h" #include "Ray.h" #include "Sphere.h" #include "Hitpoint.h" #include "BoundingBox.h" #include "Sampler.h" Sphere::Sphere() : Primitive(&stdDiffuse, true, &stdAir), center(Vector3(0, 0, 0)), radius(0.0f) { area = 0.0f; } Sphere::Sphere(float coords[4], Material *mat_in) : Primitive(mat_in, true, &stdAir), center(coords), radius(coords[3]) { area = getArea(); } Sphere::Sphere(const Vector3 &c, const float rad, Material *mat_in) : Primitive(mat_in, true, &stdAir), center(c), radius(rad) { area = getArea(); } Sphere::~Sphere() { } void Sphere::getBoundingBox(BoundingBox &bb) const { Vector3 extent = Vector3(radius, radius, radius);; bb.pMin = center - extent; bb.pMax = center + extent; } Vector3 Sphere::getNormal(const Vector3 &pos, const Vector3 &dir) const { // dir and normal are to show in the same direction! Vector3 n = (pos - center).normalizedCopy(); return n * ieeeSignWOif(n * dir); } void Sphere::getNormal(const Vector3 &dir, Hitpoint &hit) const { // dir is reversed ray direction in general! Vector3 n = (hit.p - center).normalizedCopy(); if (n * dir > 0.0f) { hit.n = n; hit.flipped = false; } else { hit.n = -n; hit.flipped = true; } } float Sphere::getArea() const { return 4.0f * PI_f * radius * radius; } float Sphere::intersectRay(const Ray *ray, float &u, float &v) const { //code from http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection //Compute A, B and C coefficients Vector3 OminusC = ray->origin - center; double a = HPrecDot(ray->direction, ray->direction); double b = HPrecDot(ray->direction, OminusC) * 2.0; double c = HPrecDot(OminusC, OminusC) - ((double) radius * (double) radius); //Find discriminant double disc = (b * b) - (4.0 * a * c); // if discriminant is negative there are no real roots, so return // false as ray misses sphere if (disc < 0.0) return 0.0f; // compute q as described above double distSqrt = sqrt(disc); double q; q = b < 0 ? (-b - distSqrt) / 2.0 : (-b + distSqrt) / 2.0; // compute t0 and t1 float t0 = q / a; float t1 = c / q; // make sure t0 is smaller than t1 if (t0 > t1) { float temp = t0; t0 = t1; t1 = temp; } // ignore imprecision flaws..... if (!(t0 < NaNLIMIT) || !(t1 < NaNLIMIT)) { std::cout << "NAN" << std::endl; return 0.0f; } // if t1 is less than tmin, the object is in the ray's negative direction // and consequently the ray misses the sphere if (t1 < ray->tMin + EPS) return 0.0f; // if t0 is less than zero, the intersection point is at t1 if (t0 < ray->tMin + EPS) //if (t0 < 0.05f) return t1; // else the intersection point is at t0 else return t0; // return t with ray interval because 2nd hitpint could be interesting! } int Sphere::intersectRay(const Ray *ray, Hitpoint &hit) const { std::cerr << "Sphere::intersectRay(const Ray *ray, Hitpoint& hit, float& u, float& v) not yet implemented!" << std::endl; return 0; } int Sphere::intersectRay2(const Ray *ray, float &t1, float &t2) const { //code from http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection //special intersect routine returning both t values for later analysis eg in lens intersection test //Compute A, B and C coefficients Vector3 OminusC = ray->origin - center; double a = HPrecDot(ray->direction, ray->direction); double b = HPrecDot(ray->direction, (OminusC)) * 2.0; double c = HPrecDot(OminusC, OminusC) - ((double) radius * (double) radius); // float a = ray->direction*ray->direction; // float b = ray->direction*(OminusC)*2.0f; // float c = (OminusC*OminusC) - (radius * radius); //Find discriminant double disc = (b * b) - (4.0 * a * c); // if discriminant is negative there are no real roots, so return // false as ray misses sphere if (disc < 0.0) { t1 = 0.0f; t2 = 0.0f; return 0; }; // compute q as described above double distSqrt = sqrt(disc); double q; q = b < 0 ? (-b - distSqrt) / 2.0 : (-b + distSqrt) / 2.0; // compute t0 and t1 t1 = q / a; t2 = c / q; if (t1 > t2) { float temp = t1; t1 = t2; t2 = temp; } return 1; } float Sphere::intersectSphere(const Sphere &s) const { // compute everything beside original values due to better calculation possibilities // virtual center of this: 0,0,0 // virtual center or s: dist,0,0 float dist = (s.center - center).length(); // the intersection of two spheres is a circle with radius result // the following formula origins Wolfram Mathworld: Chapter Sphere-Sphere Intersection if (dist < EPS) { if (radius == s.radius) { // if spheres overlap completely the overlap circle has the maximum radius // extra case needed, because 1/dist would be INF return radius; } else { // one sphere lies completely in the other one. return 0.0f; } } float distSq = dist * dist; float radiusS1Sq = radius * radius; float radiusS2Sq = s.radius * s.radius; float sqrtTerm = (4.0f * distSq * radiusS1Sq) - powf(distSq - radiusS2Sq + radiusS1Sq, 2.0f); if (sqrtTerm <= 0.0f) // case that spheres do not intersect (tangential case means no intersection!) return 0.0f; float result = (1.0f / (2.0f * dist)) * sqrtf(sqrtTerm); return 2.0f * result; } float Sphere::getunifdistrSample(Sampler &s, Vector3 &position, Vector3 &normal) const { double u = (s.genrand_real3() - 0.5) * 2.0; double v = s.genrand_real2(); double sqrtone_u = sqrt(1.0 - u * u); // sin² + cos² = 1 -> sin = sqrt(1-cos²) float v2pi = v * TWO_PI_f; position = Vector3(sqrtone_u * cosf(v2pi), sqrtone_u * sinf(v2pi), u); normal = (position - center).normalizedCopy(); return area; } void Sphere::transform(const Vector3 &translation, const float &scale, const Matrix3x3 &rotation) { //TODO :) }
27.768889
114
0.607875
[ "object", "transform" ]
ebc82b35c8b7340153220323d6f9e99b34e8527f
8,569
hpp
C++
paper/PerfEvent.hpp
fsolleza/fsst
11210fbe5a3978e661d0a391c8dde3f527dcb6fb
[ "MIT" ]
189
2020-03-03T15:37:44.000Z
2022-02-19T17:47:53.000Z
paper/PerfEvent.hpp
fsolleza/fsst
11210fbe5a3978e661d0a391c8dde3f527dcb6fb
[ "MIT" ]
5
2020-09-20T12:25:10.000Z
2021-12-02T07:10:39.000Z
paper/PerfEvent.hpp
fsolleza/fsst
11210fbe5a3978e661d0a391c8dde3f527dcb6fb
[ "MIT" ]
17
2020-08-12T02:56:22.000Z
2022-01-16T22:10:03.000Z
/* Copyright (c) 2018 Viktor Leis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #if defined(__linux__) #include <chrono> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> #include <asm/unistd.h> #include <linux/perf_event.h> #include <sys/ioctl.h> #include <unistd.h> struct PerfEvent { struct event { struct read_format { uint64_t value; uint64_t time_enabled; uint64_t time_running; uint64_t id; }; perf_event_attr pe; int fd; read_format prev; read_format data; double readCounter() { double multiplexingCorrection = static_cast<double>(data.time_enabled - prev.time_enabled) / (data.time_running - prev.time_running); return (data.value - prev.value) * multiplexingCorrection; } }; std::vector<event> events; std::vector<std::string> names; std::chrono::time_point<std::chrono::steady_clock> startTime; std::chrono::time_point<std::chrono::steady_clock> stopTime; PerfEvent() { registerCounter("cycles", PERF_TYPE_HARDWARE, PERF_COUNT_HW_CPU_CYCLES); registerCounter("instructions", PERF_TYPE_HARDWARE, PERF_COUNT_HW_INSTRUCTIONS); registerCounter("L1-misses", PERF_TYPE_HW_CACHE, PERF_COUNT_HW_CACHE_L1D|(PERF_COUNT_HW_CACHE_OP_READ<<8)|(PERF_COUNT_HW_CACHE_RESULT_MISS<<16)); registerCounter("LLC-misses", PERF_TYPE_HARDWARE, PERF_COUNT_HW_CACHE_MISSES); registerCounter("branch-misses", PERF_TYPE_HARDWARE, PERF_COUNT_HW_BRANCH_MISSES); registerCounter("task-clock", PERF_TYPE_SOFTWARE, PERF_COUNT_SW_TASK_CLOCK); // additional counters can be found in linux/perf_event.h for (unsigned i=0; i<events.size(); i++) { auto& event = events[i]; event.fd = syscall(__NR_perf_event_open, &event.pe, 0, -1, -1, 0); if (event.fd < 0) { std::cerr << "Error opening counter " << names[i] << std::endl; events.resize(0); names.resize(0); return; } } } void registerCounter(const std::string& name, uint64_t type, uint64_t eventID) { names.push_back(name); events.push_back(event()); auto& event = events.back(); auto& pe = event.pe; memset(&pe, 0, sizeof(struct perf_event_attr)); pe.type = type; pe.size = sizeof(struct perf_event_attr); pe.config = eventID; pe.disabled = true; pe.inherit = 1; pe.inherit_stat = 0; pe.exclude_kernel = false; pe.exclude_hv = false; pe.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; } void startCounters() { for (unsigned i=0; i<events.size(); i++) { auto& event = events[i]; ioctl(event.fd, PERF_EVENT_IOC_RESET, 0); ioctl(event.fd, PERF_EVENT_IOC_ENABLE, 0); if (read(event.fd, &event.prev, sizeof(uint64_t) * 3) != sizeof(uint64_t) * 3) std::cerr << "Error reading counter " << names[i] << std::endl; } startTime = std::chrono::steady_clock::now(); } ~PerfEvent() { for (auto& event : events) { close(event.fd); } } void stopCounters() { stopTime = std::chrono::steady_clock::now(); for (unsigned i=0; i<events.size(); i++) { auto& event = events[i]; if (read(event.fd, &event.data, sizeof(uint64_t) * 3) != sizeof(uint64_t) * 3) std::cerr << "Error reading counter " << names[i] << std::endl; ioctl(event.fd, PERF_EVENT_IOC_DISABLE, 0); } } double getDuration() { return std::chrono::duration<double>(stopTime - startTime).count(); } double getIPC() { return getCounter("instructions") / getCounter("cycles"); } double getCPUs() { return getCounter("task-clock") / (getDuration() * 1e9); } double getGHz() { return getCounter("cycles") / getCounter("task-clock"); } double getCounter(const std::string& name) { for (unsigned i=0; i<events.size(); i++) if (names[i]==name) return events[i].readCounter(); return -1; } static void printCounter(std::ostream& headerOut, std::ostream& dataOut, std::string name, std::string counterValue,bool addComma=true) { auto width=std::max(name.length(),counterValue.length()); headerOut << std::setw(width) << name << (addComma ? "," : "") << " "; dataOut << std::setw(width) << counterValue << (addComma ? "," : "") << " "; } template <typename T> static void printCounter(std::ostream& headerOut, std::ostream& dataOut, std::string name, T counterValue,bool addComma=true) { std::stringstream stream; stream << std::fixed << std::setprecision(2) << counterValue; PerfEvent::printCounter(headerOut,dataOut,name,stream.str(),addComma); } void printReport(std::ostream& out, uint64_t normalizationConstant) { std::stringstream header; std::stringstream data; printReport(header,data,normalizationConstant); out << header.str() << std::endl; out << data.str() << std::endl; } void printReport(std::ostream& headerOut, std::ostream& dataOut, uint64_t normalizationConstant) { if (!events.size()) return; // print all metrics for (unsigned i=0; i<events.size(); i++) { printCounter(headerOut,dataOut,names[i],events[i].readCounter()/normalizationConstant); } printCounter(headerOut,dataOut,"scale",normalizationConstant); // derived metrics printCounter(headerOut,dataOut,"IPC",getIPC()); printCounter(headerOut,dataOut,"CPUs",getCPUs()); printCounter(headerOut,dataOut,"GHz",getGHz(),false); } }; struct BenchmarkParameters { void setParam(const std::string& name,const std::string& value) { params[name]=value; } void setParam(const std::string& name,const char* value) { params[name]=value; } template <typename T> void setParam(const std::string& name,T value) { setParam(name,std::to_string(value)); } void printParams(std::ostream& header,std::ostream& data) { for (auto& p : params) { PerfEvent::printCounter(header,data,p.first,p.second); } } BenchmarkParameters(std::string name="") { if (name.length()) setParam("name",name); } private: std::map<std::string,std::string> params; }; struct PerfEventBlock { PerfEvent e; uint64_t scale; BenchmarkParameters parameters; bool printHeader; PerfEventBlock(uint64_t scale = 1, BenchmarkParameters params = {}, bool printHeader = true) : scale(scale), parameters(params), printHeader(printHeader) { e.startCounters(); } ~PerfEventBlock() { e.stopCounters(); std::stringstream header; std::stringstream data; parameters.printParams(header,data); PerfEvent::printCounter(header,data,"time sec",e.getDuration()); e.printReport(header, data, scale); if (printHeader) std::cout << header.str() << std::endl; std::cout << data.str() << std::endl; } }; #else #include <ostream> struct PerfEvent { void startCounters() {} void stopCounters() {} void printReport(std::ostream&, uint64_t) {} template <class T> void setParam(const std::string&, const T&) {}; }; struct BenchmarkParameters { }; struct PerfEventBlock { PerfEventBlock(uint64_t = 1, BenchmarkParameters = {}, bool = true) {}; PerfEventBlock(PerfEvent e, uint64_t = 1, BenchmarkParameters = {}, bool = true) { (void) e; }; }; #endif
31.855019
151
0.657486
[ "vector" ]
1b0b4b7bebec5a689eefce6fa9ddba245a5aa8cf
3,584
cpp
C++
samples/cpp/tutorial_code/ImgProc/morph_lines_detection/Morphology_3.cpp
paleozogt/opencv
c4b158ff91b2acb33252f4169ef0b24e0427e3e9
[ "BSD-3-Clause" ]
6
2018-03-08T09:06:31.000Z
2021-05-16T22:07:34.000Z
samples/cpp/tutorial_code/ImgProc/morph_lines_detection/Morphology_3.cpp
LiangYue1981816/ComputeVision-opencv
1f214d232daa6f6a4d0f297327e656f638e8e13a
[ "BSD-3-Clause" ]
1
2019-10-10T22:25:52.000Z
2019-10-10T22:25:52.000Z
samples/cpp/tutorial_code/ImgProc/morph_lines_detection/Morphology_3.cpp
LiangYue1981816/ComputeVision-opencv
1f214d232daa6f6a4d0f297327e656f638e8e13a
[ "BSD-3-Clause" ]
11
2016-03-20T18:32:24.000Z
2020-12-31T21:22:22.000Z
/** * @file Morphology_3(Extract_Lines).cpp * @brief Use morphology transformations for extracting horizontal and vertical lines sample code * @author OpenCV team */ #include <opencv2/opencv.hpp> void show_wait_destroy(const char* winname, cv::Mat img); using namespace std; using namespace cv; int main(int, char** argv) { //! [load_image] // Load the image Mat src = imread(argv[1]); // Check if image is loaded fine if(src.empty()){ printf(" Error opening image\n"); printf(" Program Arguments: [image_path]\n"); return -1; } // Show source image imshow("src", src); //! [load_image] //! [gray] // Transform source image to gray if it is not already Mat gray; if (src.channels() == 3) { cvtColor(src, gray, CV_BGR2GRAY); } else { gray = src; } // Show gray image show_wait_destroy("gray", gray); //! [gray] //! [bin] // Apply adaptiveThreshold at the bitwise_not of gray, notice the ~ symbol Mat bw; adaptiveThreshold(~gray, bw, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2); // Show binary image show_wait_destroy("binary", bw); //! [bin] //! [init] // Create the images that will use to extract the horizontal and vertical lines Mat horizontal = bw.clone(); Mat vertical = bw.clone(); //! [init] //! [horiz] // Specify size on horizontal axis int horizontal_size = horizontal.cols / 30; // Create structure element for extracting horizontal lines through morphology operations Mat horizontalStructure = getStructuringElement(MORPH_RECT, Size(horizontal_size, 1)); // Apply morphology operations erode(horizontal, horizontal, horizontalStructure, Point(-1, -1)); dilate(horizontal, horizontal, horizontalStructure, Point(-1, -1)); // Show extracted horizontal lines show_wait_destroy("horizontal", horizontal); //! [horiz] //! [vert] // Specify size on vertical axis int vertical_size = vertical.rows / 30; // Create structure element for extracting vertical lines through morphology operations Mat verticalStructure = getStructuringElement(MORPH_RECT, Size(1, vertical_size)); // Apply morphology operations erode(vertical, vertical, verticalStructure, Point(-1, -1)); dilate(vertical, vertical, verticalStructure, Point(-1, -1)); // Show extracted vertical lines show_wait_destroy("vertical", vertical); //! [vert] //! [smooth] // Inverse vertical image bitwise_not(vertical, vertical); show_wait_destroy("vertical_bit", vertical); // Extract edges and smooth image according to the logic // 1. extract edges // 2. dilate(edges) // 3. src.copyTo(smooth) // 4. blur smooth img // 5. smooth.copyTo(src, edges) // Step 1 Mat edges; adaptiveThreshold(vertical, edges, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, -2); show_wait_destroy("edges", edges); // Step 2 Mat kernel = Mat::ones(2, 2, CV_8UC1); dilate(edges, edges, kernel); show_wait_destroy("dilate", edges); // Step 3 Mat smooth; vertical.copyTo(smooth); // Step 4 blur(smooth, smooth, Size(2, 2)); // Step 5 smooth.copyTo(vertical, edges); // Show final result show_wait_destroy("smooth - final", vertical); //! [smooth] return 0; } void show_wait_destroy(const char* winname, cv::Mat img) { imshow(winname, img); moveWindow(winname, 500, 0); waitKey(0); destroyWindow(winname); }
25.971014
97
0.6476
[ "transform" ]
1b0c05e2db009a57abfecca51916096f8dee311f
10,034
hpp
C++
modules/core/include/virt86/platform/features.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
148
2019-02-19T11:05:28.000Z
2022-02-26T11:57:05.000Z
modules/core/include/virt86/platform/features.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
16
2019-02-19T02:51:48.000Z
2019-12-11T21:17:12.000Z
modules/core/include/virt86/platform/features.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
17
2019-02-19T04:05:33.000Z
2021-05-02T12:14:13.000Z
/* Contains definitions of the optional features exposed by a hypervisor platform. ------------------------------------------------------------------------------- MIT License Copyright (c) 2019 Ivan Roberto de Oliveira Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "virt86/util/bitmask_enum.hpp" #include "virt86/vp/exception.hpp" #include "virt86/vp/cpuid.hpp" #include <vector> namespace virt86 { /** * Floating point extensions supported by the hypervisor and the host CPU. */ enum class FloatingPointExtension : int64_t { /** * No floating point extension supported. * XMM/YMM/ZMM registers are unavailable. */ None = 0, /** * Supports MMX extensions, which includes the following set of registers: * - MM0 to MM7 */ MMX = (1 << 0), /** * Supports SSE extensions, which includes the following set of registers: * - XMM0 to XMM7 */ SSE = (1 << 1), /** * Supports SSE2 extensions, which adds the following set of registers: * - XMM0 to XMM15 (in IA-32e mode) */ SSE2 = (1 << 2), /** * Supports SSE3 extensions. */ SSE3 = (1 << 3), /** * Supports SSSE3 extensions. */ SSSE3 = (1 << 4), /** * Supports SSE4.1 extensions. */ SSE4_1 = (1 << 5), /** * Supports SSE4.2 extensions. */ SSE4_2 = (1 << 6), /** * Supports SSE4a extensions. AMD CPUs only. */ SSE4a = (1 << 7), /** * Supports XOP (extended operations). AMD CPUs only. */ XOP = (1 << 8), /** * Supports 16-bit Floating-Point conversion instructions. * Also known as CVT16. */ F16C = (1 << 9), /** * Supports 4-operand fused multiply-add instructions. * AMD CPUs only (so far). */ FMA4 = (1 << 10), /** * Supports AVX extensions, which adds the following set of registers: * - YMM0 to YMM7 * - YMM0 to YMM15 (in IA-32e mode) * AVX also adds support for the VEX prefix, allowing SSE instructions to * access YMM registers and use a third operand for parity with AVX. */ AVX = (1 << 11), /** * Supports 3-operand fused multiply-add instructions. */ FMA3 = (1 << 12), /** * Supports AVX2 extensions. */ AVX2 = (1 << 13), /** * Supports AVX-512 foundation extensions, which adds the following set of * registers: * - ZMM0 to ZMM7 * - XMM0 to XMM31 (in IA-32e mode) * - YMM0 to YMM31 (in IA-32e mode) * - ZMM0 to ZMM31 (in IA-32e mode) * AVX-512 also adds support for the EVEX prefix, allowing SSE and AVX * instructions to access ZMM registers. */ AVX512F = (1 << 14), /** * Supports AVX-512 Double and Quadword instructions. */ AVX512DQ = (1 << 15), /** * Supports AVX-512 Integer Fused Multiply-Add instructions. */ AVX512IFMA = (1 << 16), /** * Supports AVX-512 Prefetch instructions. */ AVX512PF = (1 << 17), /** * Supports AVX-512 Exponential and Reciprocal instructions. */ AVX512ER = (1 << 18), /** * Supports AVX-512 Conflict Detection instructions. */ AVX512CD = (1 << 19), /** * Supports AVX-512 Byte and Word instructions. */ AVX512BW = (1 << 20), /** * Supports AVX-512 Vector Length extensions. */ AVX512VL = (1 << 21), /** * Supports AVX-512 Vector Bit Manipulation instructions. */ AVX512VBMI = (1 << 22), /** * Supports AVX-512 Vector Bit Manipulation instructions, version 2. */ AVX512VBMI2 = (1 << 23), /** * Supports AVX-512 Galois Field New Instructions. */ AVX512GFNI = (1 << 24), /** * Supports AVX-512 Vector AES instructions. */ AVX512VAES = (1 << 25), /** * Supports AVX-512 Vector Neural Network instructions. */ AVX512VNNI = (1 << 26), /** * Supports AVX-512 Bit Algorithms. */ AVX512BITALG = (1 << 27), /** * Supports AVX-512 Vector Population Count Doubleword and Quadword instructions. */ AVX512VPOPCNTDQ = (1 << 28), /** * Supports AVX-512 Vector Neural Network Instructions Word Variable Precision instructions. */ AVX512QVNNIW = (1 << 29), /** * Supports AVX-512 Fused Multiply Accumulation Packed Single Precision instructions. */ AVX512QFMA = (1 << 30), /** * Supports the FXSAVE and FXRSTOR instructions. */ FXSAVE = (1 << 31), /** * Supports the XSAVE and XRSTOR instructions. */ XSAVE = (1ull << 32), }; /** * Extended control registers exposed by the hypervisor. */ enum class ExtendedControlRegister { None = 0, // No extended control registers exposed XCR0 = (1 << 0), CR8 = (1 << 1), MXCSRMask = (1 << 2), }; /** * Additional VM exit reasons supported by the hypervisor. */ enum class ExtendedVMExit { None = 0, // No extended VM exits supported CPUID = (1 << 0), // Supports VM exit due to the CPUID instruction MSRAccess = (1 << 1), // Supports VM exit on MSR access Exception = (1 << 2), // Supports VM exit on CPU exception TSCAccess = (1 << 3), // Supports VM exit on TSC access (RDTSC, RDTSCP, RDMSR, WRMSR) }; /** * Specifies the features supported by a virtualization platform. */ struct PlatformFeatures { /** * The maximum number of virtual processors supported by the hypervisor. */ uint32_t maxProcessorsGlobal = 0; /** * The maximum number of virtual processors supported per VM. */ uint32_t maxProcessorsPerVM = 0; /** * Guest physical address limits. */ struct { /** * The number of bits in a valid guest physical address. * Based on the host's capabilities and the platform's limits. */ uint8_t maxBits; /** * The maximum guest physical address supported by the platform. * Based on the host's capabilities and the platform's limits. */ uint64_t maxAddress; /** * A precomputed mask for guest physical addresses. * If any bit is set outside of the mask, the address is unsupported. */ uint64_t mask; } guestPhysicalAddress; /** * Unrestricted guests are supported. */ bool unrestrictedGuest = false; /** * Extended Page Tables (EPT) are supported. */ bool extendedPageTables = false; /** * Guest debugging is available. */ bool guestDebugging = false; /** * Guest memory protection is available. */ bool guestMemoryProtection = false; /** * Dirty page tracking is available. */ bool dirtyPageTracking = false; /** * Hypervisor allows users to read the dirty bitmap of a subregion of * mapped memory. When false, only full memory regions may be queried, if * the platform supports dirty page tracking. */ bool partialDirtyBitmap = false; /** * Allows mapping memory regions larger than 4 GiB. */ bool largeMemoryAllocation = false; /** * Guest memory aliasing (mapping one host memory range to multiple guest * memory ranges) is supported. */ bool memoryAliasing = false; /** * Memory unmapping is supported. */ bool memoryUnmapping = false; /** * Partial guest memory unmapping is supported. */ bool partialUnmapping = false; /** * The instruction emulator used by the platform performs one MMIO * operation per execution, which causes more complex instructions to * require more than one execution to complete. */ bool partialMMIOInstructions = false; /** * Floating point extensions supported by the hypervisor. */ FloatingPointExtension floatingPointExtensions = FloatingPointExtension::None; /** * Extended control registers exposed by the hypervisor. */ ExtendedControlRegister extendedControlRegisters = ExtendedControlRegister::None; /** * Additional VM exit reasons supported by the hypervisor. */ ExtendedVMExit extendedVMExits = ExtendedVMExit::None; /** * Types of exception exits supported by the hypervisor. */ ExceptionCode exceptionExits = ExceptionCode::None; /** * Hypervisor allows custom CPUID results to be configured. */ bool customCPUIDs = false; /** * Supported CPUID codes and their default responses. Only valid if custom * CPUIDs are supported. Not all platforms fill this list. */ std::vector<CPUIDResult> supportedCustomCPUIDs; /** * Guest TSC scaling and virtual TSC offset is supported. */ bool guestTSCScaling = false; }; } ENABLE_BITMASK_OPERATORS(virt86::FloatingPointExtension) ENABLE_BITMASK_OPERATORS(virt86::ExtendedControlRegister) ENABLE_BITMASK_OPERATORS(virt86::ExtendedVMExit)
25.728205
96
0.617999
[ "vector" ]
1b0d7121c12169940f9d466a7589424dd86bd60b
2,450
cc
C++
ui/events/ozone/evdev/touch_filter/false_touch_finder.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ui/events/ozone/evdev/touch_filter/false_touch_finder.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ui/events/ozone/evdev/touch_filter/false_touch_finder.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/events/ozone/evdev/touch_filter/false_touch_finder.h" #include "base/metrics/histogram_macros.h" #include "ui/events/event_utils.h" #include "ui/events/ozone/evdev/touch_filter/edge_touch_filter.h" #include "ui/events/ozone/evdev/touch_filter/far_apart_taps_touch_noise_filter.h" #include "ui/events/ozone/evdev/touch_filter/horizontally_aligned_touch_noise_filter.h" #include "ui/events/ozone/evdev/touch_filter/single_position_touch_noise_filter.h" #include "ui/events/ozone/evdev/touch_filter/touch_filter.h" namespace ui { FalseTouchFinder::FalseTouchFinder( bool touch_noise_filtering, bool edge_filtering, gfx::Size touchscreen_size) : last_noise_time_(ui::EventTimeForNow()) { if (touch_noise_filtering) { noise_filters_.push_back(std::make_unique<FarApartTapsTouchNoiseFilter>()); noise_filters_.push_back( std::make_unique<HorizontallyAlignedTouchNoiseFilter>()); noise_filters_.push_back( std::make_unique<SinglePositionTouchNoiseFilter>()); } if (edge_filtering) { edge_touch_filter_ = std::make_unique<EdgeTouchFilter>(touchscreen_size); } } FalseTouchFinder::~FalseTouchFinder() { } void FalseTouchFinder::HandleTouches( const std::vector<InProgressTouchEvdev>& touches, base::TimeTicks time) { for (const InProgressTouchEvdev& touch : touches) { if (!touch.was_touching) { slots_with_noise_.set(touch.slot, false); slots_should_delay_.set(touch.slot, false); } } bool had_noise = slots_with_noise_.any(); for (const auto& filter : noise_filters_) filter->Filter(touches, time, &slots_with_noise_); if (edge_touch_filter_) edge_touch_filter_->Filter(touches, time, &slots_should_delay_); RecordUMA(had_noise, time); } bool FalseTouchFinder::SlotHasNoise(size_t slot) const { return slots_with_noise_.test(slot); } bool FalseTouchFinder::SlotShouldDelay(size_t slot) const { return slots_should_delay_.test(slot); } void FalseTouchFinder::RecordUMA(bool had_noise, base::TimeTicks time) { if (slots_with_noise_.any()) { if (!had_noise) { UMA_HISTOGRAM_LONG_TIMES( "Ozone.TouchNoiseFilter.TimeSinceLastNoiseOccurrence", time - last_noise_time_); } last_noise_time_ = time; } } } // namespace ui
31.012658
87
0.753469
[ "vector" ]
1b1f31d6988baf6def2dcc53dbf5ed1439c6758c
607
cpp
C++
Algorithms/LC/cpp/0026 Remove Duplicates from Sorted Array/LC0026.cpp
tjzhym/LeetCode-solution
06bd35bae619caaf8153b81849dae9dcc7bc9491
[ "MIT" ]
null
null
null
Algorithms/LC/cpp/0026 Remove Duplicates from Sorted Array/LC0026.cpp
tjzhym/LeetCode-solution
06bd35bae619caaf8153b81849dae9dcc7bc9491
[ "MIT" ]
null
null
null
Algorithms/LC/cpp/0026 Remove Duplicates from Sorted Array/LC0026.cpp
tjzhym/LeetCode-solution
06bd35bae619caaf8153b81849dae9dcc7bc9491
[ "MIT" ]
null
null
null
// Problem : https://leetcode.com/problems/remove-duplicates-from-sorted-array/ // Solution: https://github.com/tjzhym/LeetCode-solution // Author : zhym (tjzhym) // Date : 2021-9-10 #include <vector> class Solution { public: int removeDuplicates(vector<int>& nums) { int numIndex = 1; while (numIndex < nums.size()) { if (nums[numIndex] == nums[numIndex - 1]) { nums.erase(nums.begin() + numIndex); } else { numIndex += 1; } } return nums.size(); } }; // brute force
24.28
82
0.527183
[ "vector" ]
1b23ec9b0afdd479e530e9adcedd098cbcf8cd10
163
hh
C++
tests/Dispatch/Order.hh
GroovyCarrot/hhvm-event-dispatcher
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
[ "MIT" ]
null
null
null
tests/Dispatch/Order.hh
GroovyCarrot/hhvm-event-dispatcher
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
[ "MIT" ]
null
null
null
tests/Dispatch/Order.hh
GroovyCarrot/hhvm-event-dispatcher
0140f298c06ce60eeb2f07e7cc1f95aeca5ca853
[ "MIT" ]
null
null
null
<?hh // strict namespace Tests\GroovyCarrot\Event\Dispatch; class Order { public function __construct( public Vector<string> $items, ) { } }
13.583333
44
0.644172
[ "vector" ]
1b2d1317da351cb6921f5457d223da28b43dcdb6
12,800
cpp
C++
Source.cpp
hack-jp/Shader2gif
775c24e3f737db6803b940acd89ab337a7a4c3b6
[ "MIT" ]
1
2021-12-15T02:52:54.000Z
2021-12-15T02:52:54.000Z
Source.cpp
hack-jp/Shader2gif
775c24e3f737db6803b940acd89ab337a7a4c3b6
[ "MIT" ]
null
null
null
Source.cpp
hack-jp/Shader2gif
775c24e3f737db6803b940acd89ab337a7a4c3b6
[ "MIT" ]
null
null
null
#ifndef UNICODE #define UNICODE #endif #pragma comment(lib, "gdiplus") #pragma comment(lib, "glew32s") #pragma comment(lib, "shlwapi") #define GLEW_STATIC #include <vector> #include <string> #include <windows.h> #include <shlwapi.h> #include <gdiplus.h> #include <richedit.h> #include <math.h> #include <GL/glew.h> #include <GL/glut.h> #include "GifEncoder.h" #include "resource.h" #define PREVIEW_WIDTH 512 #define PREVIEW_HEIGHT 384 #define WM_CREATED WM_APP HDC hDC; BOOL active; GLuint program; GLuint vao; GLuint vbo; const TCHAR szClassName[] = TEXT("Window"); const GLfloat position[][2] = { { -1.f, -1.f }, { 1.f, -1.f }, { 1.f, 1.f }, { -1.f, 1.f } }; const int vertices = sizeof position / sizeof position[0]; const GLchar vsrc[] = "in vec4 position;void main(void){gl_Position = position;}"; GLuint texture1; inline GLint GetShaderInfoLog(GLuint shader) { GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == 0) OutputDebugString(TEXT("Compile Error\n")); GLsizei bufSize; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &bufSize); if (bufSize > 1) { LPSTR infoLog = (LPSTR)GlobalAlloc(0, bufSize); GLsizei length; glGetShaderInfoLog(shader, bufSize, &length, infoLog); OutputDebugStringA(infoLog); GlobalFree(infoLog); } return status; } inline GLint GetProgramInfoLog(GLuint program) { GLint status; glGetProgramiv(program, GL_LINK_STATUS, &status); if (status == 0) OutputDebugString(TEXT("Link Error\n")); GLsizei bufSize; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufSize); if (bufSize > 1) { LPSTR infoLog = (LPSTR)GlobalAlloc(0, bufSize); GLsizei length; glGetProgramInfoLog(program, bufSize, &length, infoLog); OutputDebugStringA(infoLog); GlobalFree(infoLog); } return status; } inline GLuint CreateProgram(LPCSTR vsrc, LPCSTR fsrc) { const GLuint vobj = glCreateShader(GL_VERTEX_SHADER); if (!vobj) return 0; glShaderSource(vobj, 1, &vsrc, 0); glCompileShader(vobj); if (GetShaderInfoLog(vobj) == 0) { glDeleteShader(vobj); return 0; } const GLuint fobj = glCreateShader(GL_FRAGMENT_SHADER); if (!fobj) { glDeleteShader(vobj); return 0; } glShaderSource(fobj, 1, &fsrc, 0); glCompileShader(fobj); if (GetShaderInfoLog(fobj) == 0) { glDeleteShader(vobj); glDeleteShader(fobj); return 0; } GLuint program = glCreateProgram(); if (program) { glAttachShader(program, vobj); glAttachShader(program, fobj); glLinkProgram(program); if (GetProgramInfoLog(program) == 0) { glDetachShader(program, fobj); glDetachShader(program, vobj); glDeleteProgram(program); program = 0; } } glDeleteShader(vobj); glDeleteShader(fobj); return program; } VOID SetTexture(HBITMAP hBitmap) { BITMAP inf; GetObject(hBitmap, sizeof(BITMAP), &inf); if (inf.bmBitsPixel != 24){ return; } if (texture1) { glDeleteTextures(1, &texture1); } glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_1D, texture1); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexImage1D(GL_TEXTURE_1D, 0, 3, inf.bmWidth, inf.bmHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, inf.bmBits); glEnable(GL_TEXTURE_1D); } inline BOOL InitGL(GLvoid) { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)* 2 * vertices, position, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, 0, 0, 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); HBITMAP hBitmap = (HBITMAP)LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(IDB_BITMAP1), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); SetTexture(hBitmap); DeleteObject(hBitmap); return TRUE; } inline VOID DrawGLScene() { glClear(GL_COLOR_BUFFER_BIT); glUseProgram(program); glUniform1f(glGetUniformLocation(program, "time"), GetTickCount() / 1000.0f); glBindVertexArray(vao); glDrawArrays(GL_QUADS, 0, vertices); glBindVertexArray(0); glUseProgram(0); glFlush(); SwapBuffers(hDC); } inline VOID DrawGLScene(HDC hdc, GLfloat time) { glClear(GL_COLOR_BUFFER_BIT); glUseProgram(program); glUniform1f(glGetUniformLocation(program, "time"), time); glBindVertexArray(vao); glDrawArrays(GL_QUADS, 0, vertices); glBindVertexArray(0); glUseProgram(0); glFlush(); SwapBuffers(hDC); BITMAPINFO bitmapInfo; ::memset(&bitmapInfo, 0, sizeof(BITMAPINFO)); bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfo.bmiHeader.biPlanes = 1; bitmapInfo.bmiHeader.biBitCount = 32; bitmapInfo.bmiHeader.biCompression = BI_RGB; bitmapInfo.bmiHeader.biWidth = PREVIEW_WIDTH; bitmapInfo.bmiHeader.biHeight = PREVIEW_HEIGHT; bitmapInfo.bmiHeader.biSizeImage = PREVIEW_WIDTH * PREVIEW_HEIGHT * 4; void *bmBits = 0; HDC memDC = CreateCompatibleDC(hdc); HBITMAP memBM = CreateDIBSection(0, &bitmapInfo, DIB_RGB_COLORS, &bmBits, 0, 0); glReadPixels(0, 0, PREVIEW_WIDTH, PREVIEW_HEIGHT, GL_BGRA_EXT, GL_UNSIGNED_BYTE, bmBits); HGDIOBJ prevBitmap = SelectObject(memDC, memBM); BitBlt(hdc, 0, 0, PREVIEW_WIDTH, PREVIEW_HEIGHT, memDC, 0, 0, SRCCOPY); SelectObject(memDC, prevBitmap); DeleteObject(memBM); DeleteDC(memDC); } inline void CreateAnimationGif(LPCTSTR lpszFilePath, int nTime, int nFrameRate) { CGifEncoder gifEncoder; gifEncoder.SetFrameSize(PREVIEW_WIDTH, PREVIEW_HEIGHT); gifEncoder.SetFrameRate(nFrameRate); gifEncoder.StartEncoder(std::wstring(lpszFilePath)); Gdiplus::Bitmap *bmp = new Gdiplus::Bitmap(PREVIEW_WIDTH, PREVIEW_HEIGHT); for (int time = 0; time < nTime; time++) { Gdiplus::Graphics g(bmp); const HDC hdc = g.GetHDC(); DrawGLScene(hdc, time / 10.f); g.ReleaseHDC(hdc); gifEncoder.AddFrame(bmp); } delete bmp; gifEncoder.FinishEncoder(); } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; static GLuint PixelFormat; static HWND hStatic; static HWND hEdit; static HWND hButton; static HFONT hFont; static HINSTANCE hRtLib; static BOOL bEditVisible = TRUE; static HGLRC hRC; switch (msg) { case WM_CREATE: hRtLib = LoadLibrary(TEXT("RICHED32")); hFont = CreateFont(24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TEXT("Consolas")); hStatic = CreateWindow(TEXT("STATIC"), 0, WS_VISIBLE | WS_CHILD | SS_SIMPLE, 10, 10, PREVIEW_WIDTH, PREVIEW_HEIGHT, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0); hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, RICHEDIT_CLASS, 0, WS_VISIBLE | WS_CHILD | WS_HSCROLL | WS_VSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_NOHIDESEL, 0, 0, 0, 0, hWnd, (HMENU)ID_EDIT, ((LPCREATESTRUCT)lParam)->hInstance, 0); hButton = CreateWindow(TEXT("BUTTON"), TEXT("GIF出力..."), WS_VISIBLE | WS_CHILD, PREVIEW_WIDTH / 2 - 54, PREVIEW_HEIGHT + 20, 128, 32, hWnd, (HMENU)ID_EXPORT, ((LPCREATESTRUCT)lParam)->hInstance, 0); SendMessage(hEdit, EM_SETTEXTMODE, TM_PLAINTEXT, 0); SendMessage(hEdit, EM_LIMITTEXT, -1, 0); SendMessage(hEdit, WM_SETFONT, (WPARAM)hFont, 0); if (!(hDC = GetDC(hStatic)) || !(PixelFormat = ChoosePixelFormat(hDC, &pfd)) || !SetPixelFormat(hDC, PixelFormat, &pfd) || !(hRC = wglCreateContext(hDC)) || !wglMakeCurrent(hDC, hRC) || glewInit() != GLEW_OK || !InitGL()) return -1; SetWindowText(hEdit, TEXT("#define pi 3.14159265358979\r\n") TEXT("uniform float time;\r\n") TEXT("void main()\r\n") TEXT("{\r\n") TEXT(" vec2 p = gl_FragCoord;\r\n") TEXT(" float c = 0.0;\r\n") TEXT(" for (float i = 0.0; i < 5.0; i++)\r\n") TEXT(" {\r\n") TEXT(" vec2 b = vec2(\r\n") TEXT(" sin(time + i * pi / 7) * 128 + 256,\r\n") TEXT(" cos(time + i * pi / 2) * 128 + 192\r\n") TEXT(" );\r\n") TEXT(" c += 16 / distance(p, b);\r\n") TEXT(" }\r\n") TEXT(" gl_FragColor = vec4(c*c / sin(time), c*c / 2, c*c, 1.0);\r\n") TEXT("}\r\n") ); PostMessage(hWnd, WM_CREATED, 0, 0); break; case WM_CREATED: SendMessage(hWnd, WM_COMMAND, MAKEWPARAM(ID_EDIT, EN_CHANGE), (long)hEdit); SendMessage(hEdit, EM_SETEVENTMASK, 0, (LPARAM)(SendMessage(hEdit, EM_GETEVENTMASK, 0, 0) | ENM_CHANGE)); SetFocus(hEdit); DragAcceptFiles(hWnd, TRUE); break; case WM_SIZE: MoveWindow(hEdit, PREVIEW_WIDTH + 20, 10, LOWORD(lParam) - PREVIEW_WIDTH - 30, HIWORD(lParam) - 20, 1); break; case WM_COMMAND: switch (LOWORD(wParam)) { case ID_EDIT: if (HIWORD(wParam) == EN_CHANGE) { const DWORD dwSize = GetWindowTextLengthA(hEdit); if (!dwSize) return 0; LPSTR lpszText = (LPSTR)GlobalAlloc(0, (dwSize + 1)*sizeof(CHAR)); if (!lpszText) return 0; GetWindowTextA(hEdit, lpszText, dwSize + 1); const GLuint newProgram = CreateProgram(vsrc, lpszText); if (newProgram) { if (program) glDeleteProgram(program); program = newProgram; SetWindowText(hWnd, TEXT("フラグメントシェーダ [コンパイル成功]")); } else { SetWindowText(hWnd, TEXT("フラグメントシェーダ [コンパイル失敗]")); } GlobalFree(lpszText); } break; case ID_SELECTALL: if (IsWindowVisible(hEdit)) { SendMessage(hEdit, EM_SETSEL, 0, -1); SetFocus(hEdit); } break; case ID_EXPORT: { TCHAR szFileName[MAX_PATH] = {0}; OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hWnd; ofn.lpstrFilter = TEXT("GIF(*.gif)\0*.gif\0すべてのファイル(*.*)\0*.*\0\0"); ofn.lpstrFile = szFileName; ofn.nMaxFile = sizeof(szFileName); ofn.Flags = OFN_FILEMUSTEXIST | OFN_OVERWRITEPROMPT; if (GetSaveFileName(&ofn)) { CreateAnimationGif(szFileName, 50, 100); MessageBox(hWnd, TEXT("完了しました。"), TEXT("確認"), MB_ICONINFORMATION); } } break; case ID_IMPORT_TEXTURE: { TCHAR szFileName[MAX_PATH] = { 0 }; OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hWnd; ofn.lpstrFilter = TEXT("Bitmap(*.bmp)\0*.bmp\0すべてのファイル(*.*)\0*.*\0\0"); ofn.lpstrFile = szFileName; ofn.nMaxFile = sizeof(szFileName); ofn.Flags = OFN_FILEMUSTEXIST; if (GetOpenFileName(&ofn)) { const HBITMAP hBitmap = (HBITMAP)LoadImage(GetModuleHandle(0), szFileName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION); SetTexture(hBitmap); DeleteObject(hBitmap); } } break; } break; case WM_DROPFILES: { const HDROP hDrop = (HDROP)wParam; TCHAR szFileName[MAX_PATH]; DragQueryFile(hDrop, 0, szFileName, sizeof(szFileName)); LPCTSTR lpExt = PathFindExtension(szFileName); if (PathMatchSpec(lpExt, TEXT("*.bmp"))) { const HBITMAP hBitmap = (HBITMAP)LoadImage(GetModuleHandle(0), szFileName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION); SetTexture(hBitmap); DeleteObject(hBitmap); } DragFinish(hDrop); } break; case WM_ACTIVATE: active = !HIWORD(wParam); break; case WM_DESTROY: DeleteObject(hFont); if (texture1) glDeleteTextures(1, &texture1); if (program) glDeleteProgram(program); if (vbo) glDeleteBuffers(1, &vbo); if (vao) glDeleteVertexArrays(1, &vao); if (hRC) { wglMakeCurrent(0, 0); wglDeleteContext(hRC); } if (hDC) ReleaseDC(hStatic, hDC); DestroyWindow(hEdit); FreeLibrary(hRtLib); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreInst, LPSTR pCmdLine, int nCmdShow) { ULONG_PTR gdiToken; Gdiplus::GdiplusStartupInput gdiSI; Gdiplus::GdiplusStartup(&gdiToken, &gdiSI, NULL); MSG msg; const WNDCLASS wndclass = { 0, WndProc, 0, 0, hInstance, 0, LoadCursor(0, IDC_ARROW), (HBRUSH)(COLOR_WINDOW + 1), MAKEINTRESOURCE(IDR_MENU1), szClassName }; RegisterClass(&wndclass); const HWND hWnd = CreateWindow(szClassName, 0, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInstance, 0); ShowWindow(hWnd, SW_SHOWDEFAULT); UpdateWindow(hWnd); ACCEL Accel[] = { { FVIRTKEY | FCONTROL, 'A', ID_SELECTALL } }; const HACCEL hAccel = CreateAcceleratorTable(Accel, sizeof(Accel) / sizeof(ACCEL)); BOOL done = 0; while (!done) { if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { done = TRUE; } else if (!TranslateAccelerator(hWnd, hAccel, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } else if (active) { DrawGLScene(); } } DestroyAcceleratorTable(hAccel); Gdiplus::GdiplusShutdown(gdiToken); return msg.wParam; }
29.767442
157
0.701016
[ "vector" ]
1b2ec71051e056490d8071573dc3cfde4a941049
13,316
cpp
C++
src/sha1.cpp
503387955/ciyam
630149b406cad12d9fb8bced502240791335d48c
[ "MIT" ]
1
2021-09-15T12:32:29.000Z
2021-09-15T12:32:29.000Z
src/sha1.cpp
503387955/ciyam
630149b406cad12d9fb8bced502240791335d48c
[ "MIT" ]
null
null
null
src/sha1.cpp
503387955/ciyam
630149b406cad12d9fb8bced502240791335d48c
[ "MIT" ]
null
null
null
// Copyright (c) 2007-2012 CIYAM Pty. Ltd. ACN 093 704 539 // Copyright (c) 2012-2021 CIYAM Developers // // Distributed under the MIT/X11 software license, please refer to the file license.txt // in the root project directory or http://www.opensource.org/licenses/mit-license.php. #ifdef PRECOMPILE_H # include "precompile.h" #endif #pragma hdrstop #ifndef HAS_PRECOMPILED_STD_HEADERS # include <cstdio> # include <cstring> # include <string> # include <sstream> # include <iomanip> # include <iostream> # include <algorithm> #endif #include "sha1.h" #include "utilities.h" using namespace std; //#define COMPILE_TESTBED_MAIN namespace { const unsigned int c_buffer_size = 4096; /* SHA-1 in C By Steve Reid <steve@edmweb.com> 100% Public Domain Test Vectors (from FIPS PUB 180-1) "abc" A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 A million repetitions of "a" 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F */ //#define LITTLE_ENDIAN // This should be #define'd if true //#define SHA1HANDSOFF // Copies data before messing with it. typedef struct { unsigned int state[ 5 ]; unsigned int count[ 2 ]; unsigned char buffer[ 64 ]; } sha1_context; void sha1_transform( unsigned int state[ 5 ], unsigned char buffer[ 64 ] ); void sha1_init( sha1_context* context ); void sha1_update( sha1_context* context, unsigned char* data, unsigned int len ); void sha1_final( unsigned char digest[ 20 ], sha1_context* context ); #define rol( value, bits ) ( ( ( value ) << ( bits ) ) | ( ( value ) >> ( 32 - ( bits ) ) ) ) // blk0( ) and blk( ) perform the initial expand. // I got the idea of expanding during the round function from SSLeay #ifdef LITTLE_ENDIAN # define blk0( i ) ( block->l[ i ] = \ ( rol( block->l[ i ], 24 ) & 0xFF00FF00 ) | ( rol ( block->l[ i ], 8 ) & 0x00FF00FF ) ) #else # define blk0( i ) block->l[ i ] #endif #define blk( i ) ( block->l[ i & 15 ] = \ rol( block->l[ ( i + 13 ) & 15 ] ^ block->l[ ( i + 8 ) & 15 ] \ ^ block->l[ ( i + 2 ) & 15 ] ^ block->l[ i & 15 ], 1 ) ) // ( R0 + R1 ), R2, R3, R4 are the different operations used in SHA1 #define R0( v, w, x, y, z, i ) z += ( ( w & ( x ^ y ) ) ^ y ) \ + blk0( i ) + 0x5A827999 + rol( v, 5 ); w = rol( w, 30 ); #define R1( v, w, x, y, z, i ) z += ( ( w & ( x ^ y ) ) ^ y ) \ + blk( i ) + 0x5A827999 + rol( v, 5 ); w = rol( w, 30 ); #define R2( v, w, x, y, z, i ) z += ( w ^ x ^ y ) \ + blk( i ) + 0x6ED9EBA1 + rol( v, 5 ); w = rol( w, 30 ); #define R3( v, w, x, y, z, i ) z += ( ( ( w | x ) & y ) | ( w & x ) ) \ + blk( i ) + 0x8F1BBCDC + rol( v, 5 ); w = rol( w, 30 ); #define R4( v, w, x, y, z, i ) z += ( w ^ x ^ y ) \ + blk( i ) + 0xCA62C1D6 + rol( v, 5 ); w = rol( w, 30 ); // Hash a single 512-bit block. This is the core of the algorithm. void sha1_transform( unsigned int state[ 5 ], unsigned char buffer[ 64 ] ) { unsigned int a, b, c, d, e; typedef union { unsigned char c[ 64 ]; unsigned int l[ 16 ]; } CHAR64LONG16; CHAR64LONG16* block; #ifdef SHA1HANDSOFF static unsigned char workspace[ 64 ]; block = ( CHAR64LONG16* )workspace; memcpy( block, buffer, 64 ); #else block = ( CHAR64LONG16* )buffer; #endif // Copy context->state[ ] to working vars a = state[ 0 ]; b = state[ 1 ]; c = state[ 2 ]; d = state[ 3 ]; e = state[ 4 ]; // 4 rounds of 20 operations each. Loop unrolled. R0( a, b, c, d, e, 0 ); R0( e, a, b, c, d, 1 ); R0( d, e, a, b, c, 2 ); R0( c, d, e, a, b, 3 ); R0( b, c, d, e, a, 4 ); R0( a, b, c, d, e, 5 ); R0( e, a, b, c, d, 6 ); R0( d, e, a, b, c, 7 ); R0( c, d, e, a, b, 8 ); R0( b, c, d, e, a, 9 ); R0( a, b, c, d, e, 10 ); R0( e, a, b, c, d, 11 ); R0( d, e, a, b, c, 12 ); R0( c, d, e, a, b, 13 ); R0( b, c, d, e, a, 14 ); R0( a, b, c, d, e, 15 ); R1( e, a, b, c, d, 16 ); R1( d, e, a, b, c, 17 ); R1( c, d, e, a, b, 18 ); R1( b, c, d, e, a, 19 ); R2( a, b, c, d, e, 20 ); R2( e, a, b, c, d, 21 ); R2( d, e, a, b, c, 22 ); R2( c, d, e, a, b, 23 ); R2( b, c, d, e, a, 24 ); R2( a, b, c, d, e, 25 ); R2( e, a, b, c, d, 26 ); R2( d, e, a, b, c, 27 ); R2( c, d, e, a, b, 28 ); R2( b, c, d, e, a, 29 ); R2( a, b, c, d, e, 30 ); R2( e, a, b, c, d, 31 ); R2( d, e, a, b, c, 32 ); R2( c, d, e, a, b, 33 ); R2( b, c, d, e, a, 34 ); R2( a, b, c, d, e, 35 ); R2( e, a, b, c, d, 36 ); R2( d, e, a, b, c, 37 ); R2( c, d, e, a, b, 38 ); R2( b, c, d, e, a, 39 ); R3( a, b, c, d, e, 40 ); R3( e, a, b, c, d, 41 ); R3( d, e, a, b, c, 42 ); R3( c, d, e, a, b, 43 ); R3( b, c, d, e, a, 44 ); R3( a, b, c, d, e, 45 ); R3( e, a, b, c, d, 46 ); R3( d, e, a, b, c, 47 ); R3( c, d, e, a, b, 48 ); R3( b, c, d, e, a, 49 ); R3( a, b, c, d, e, 50 ); R3( e, a, b, c, d, 51 ); R3( d, e, a, b, c, 52 ); R3( c, d, e, a, b, 53 ); R3( b, c, d, e, a, 54 ); R3( a, b, c, d, e, 55 ); R3( e, a, b, c, d, 56 ); R3( d, e, a, b, c, 57 ); R3( c, d, e, a, b, 58 ); R3( b, c, d, e, a, 59 ); R4( a, b, c, d, e, 60 ); R4( e, a, b, c, d, 61 ); R4( d, e, a, b, c, 62 ); R4( c, d, e, a, b, 63 ); R4( b, c, d, e, a, 64 ); R4( a, b, c, d, e, 65 ); R4( e, a, b, c, d, 66 ); R4( d, e, a, b, c, 67 ); R4( c, d, e, a, b, 68 ); R4( b, c, d, e, a, 69 ); R4( a, b, c, d, e, 70 ); R4( e, a, b, c, d, 71 ); R4( d, e, a, b, c, 72 ); R4( c, d, e, a, b, 73 ); R4( b, c, d, e, a, 74 ); R4( a, b, c, d, e, 75 ); R4( e, a, b, c, d, 76 ); R4( d, e, a, b, c, 77 ); R4( c, d, e, a, b, 78 ); R4( b, c, d, e, a, 79 ); // Add the working vars back into context.state[ ] state[ 0 ] += a; state[ 1 ] += b; state[ 2 ] += c; state[ 3 ] += d; state[ 4 ] += e; // Wipe variables a = b = c = d = e = 0; ( void )a; // avoid BCB "is assigned a value that is never used" warning } void sha1_init( sha1_context* context ) { // SHA1 initialization constants context->state[ 0 ] = 0x67452301; context->state[ 1 ] = 0xEFCDAB89; context->state[ 2 ] = 0x98BADCFE; context->state[ 3 ] = 0x10325476; context->state[ 4 ] = 0xC3D2E1F0; context->count[ 0 ] = context->count[ 1 ] = 0; } // Run your data through this. void sha1_update( sha1_context* context, unsigned char* data, unsigned int len ) { unsigned int i, j; j = ( context->count[ 0 ] >> 3 ) & 63; if( ( context->count[ 0 ] += len << 3 ) < ( len << 3 ) ) context->count[ 1 ]++; context->count[ 1 ] += ( len >> 29 ); if( ( j + len ) > 63 ) { memcpy( &context->buffer[ j ], data, ( i = 64 - j ) ); sha1_transform( context->state, context->buffer ); for( ; i + 63 < len; i += 64 ) sha1_transform( context->state, &data[ i ] ); j = 0; } else i = 0; if( len > i ) memcpy( &context->buffer[ j ], &data[ i ], len - i ); } // Add padding and return the message digest. void sha1_final( unsigned char digest[ 20 ], sha1_context* context ) { unsigned int i, j; unsigned char finalcount[ 8 ]; for( i = 0; i < 8; i++ ) finalcount[ i ] = // Endian independent ( unsigned char )( ( context->count[ ( i >= 4 ? 0 : 1 ) ] >> ( ( 3 - ( i & 3 ) ) * 8 ) ) & 255 ); sha1_update( context, ( unsigned char* )"\200", 1 ); while( ( context->count[ 0 ] & 504 ) != 448 ) sha1_update( context, ( unsigned char* )"\0", 1 ); sha1_update( context, finalcount, 8 ); // should cause a sha1_transform( ) for( i = 0; i < 20; i++ ) digest[ i ] = ( unsigned char )( ( context->state[ i >> 2 ] >> ( ( 3 - ( i & 3 ) ) * 8 ) ) & 255 ); // Wipe variables i = j = 0; memset( context->buffer, 0, 64 ); memset( context->state, 0, 20 ); memset( context->count, 0, 8 ); memset( &finalcount, 0, 8 ); #ifdef SHA1HANDSOFF // make sha1_transform overwrite it's own static vars sha1_transform( context->state, context->buffer ); #endif ( void )i; // avoid BCB "is assigned a value that is never used" warning ( void )j; // avoid BCB "is assigned a value that is never used" warning } } // namespace struct sha1::impl { bool final; unsigned char digest[ c_sha1_digest_size ]; sha1_context context; ~impl( ) { for( size_t i = 0; i < c_sha1_digest_size; i++ ) digest[ i ] = 0; } }; sha1::sha1( ) { p_impl = new impl; init( ); } sha1::sha1( const std::string& str ) { p_impl = new impl; init( ); update( ( const unsigned char* )&str[ 0 ], str.length( ) ); } sha1::sha1( const unsigned char* p_data, unsigned int length ) { p_impl = new impl; init( ); update( p_data, length ); } sha1::~sha1( ) { delete p_impl; } void sha1::init( ) { p_impl->final = false; sha1_init( &p_impl->context ); } void sha1::update( const std::string& str ) { update( ( const unsigned char* )&str[ 0 ], str.length( ) ); } void sha1::update( const unsigned char* p_data, unsigned int length ) { unsigned char buf[ c_buffer_size ]; unsigned int pos = 0; unsigned int chunk = min( length, c_buffer_size ); if( p_impl->final ) init( ); while( chunk > 0 ) { memcpy( buf, p_data + pos, chunk ); sha1_update( &p_impl->context, buf, chunk ); pos += chunk; length -= chunk; chunk = min( length, c_buffer_size ); } } void sha1::copy_digest_to_buffer( unsigned char* p_buffer ) { if( !p_impl->final ) { p_impl->final = true; sha1_final( p_impl->digest, &p_impl->context ); } memcpy( p_buffer, p_impl->digest, c_sha1_digest_size ); } void sha1::get_digest_as_string( string& s ) { if( !p_impl->final ) { p_impl->final = true; sha1_final( p_impl->digest, &p_impl->context ); } if( s.length( ) > 40 ) s.resize( 40 ); else if( s.length( ) != 40 ) s = string( 40, '\0' ); for( size_t i = 0, j = 0; i < c_sha1_digest_size; i++ ) { s[ j++ ] = ascii_digit( ( p_impl->digest[ i ] & 0xf0 ) >> 4 ); s[ j++ ] = ascii_digit( p_impl->digest[ i ] & 0x0f ); } } string sha1::get_digest_as_string( char separator ) { if( !p_impl->final ) { p_impl->final = true; sha1_final( p_impl->digest, &p_impl->context ); } ostringstream outs; for( size_t i = 0; i < c_sha1_digest_size; i++ ) { if( i && i % 4 == 0 && separator != '\0' ) outs << separator; outs << hex << setw( 2 ) << setfill( '0' ) << ( unsigned )p_impl->digest[ i ]; } return outs.str( ); } string hmac_sha1( const string& key, const string& message ) { string s( 40, '\0' ); unsigned char buffer[ c_sha1_digest_size ]; hmac_sha1( key, message, buffer ); for( size_t i = 0, j = 0; i < c_sha1_digest_size; i++ ) { s[ j++ ] = ascii_digit( ( buffer[ i ] & 0xf0 ) >> 4 ); s[ j++ ] = ascii_digit( buffer[ i ] & 0x0f ); } return s; } void hmac_sha1( const string& key, const string& message, unsigned char* p_buffer ) { int key_len = key.length( ); int msg_len = message.length( ); const unsigned char* p_key = ( const unsigned char* )key.data( ); const unsigned char* p_msg = ( const unsigned char* )message.data( ); unsigned char k_ipad[ 65 ]; unsigned char k_opad[ 65 ]; unsigned char tk[ c_sha1_digest_size ]; unsigned char tk2[ c_sha1_digest_size ]; unsigned char bufferIn[ 1024 ]; unsigned char bufferOut[ 1024 ]; if( key_len > 64 ) { sha1 hash( key ); hash.copy_digest_to_buffer( tk ); p_key = tk; key_len = 64; } memset( k_ipad, 0, 65 ); memset( k_opad, 0, 65 ); memcpy( k_ipad, p_key, key_len ); memcpy( k_opad, p_key, key_len ); for( int i = 0; i < 64; i++ ) { k_ipad[ i ] ^= 0x36; k_opad[ i ] ^= 0x5c; } memset( bufferIn, 0x00, 1024 ); memcpy( bufferIn, k_ipad, 64 ); memcpy( bufferIn + 64, p_msg, msg_len ); sha1 hash1( bufferIn, 64 + msg_len ); hash1.copy_digest_to_buffer( tk2 ); memset( bufferOut, 0x00, 1024 ); memcpy( bufferOut, k_opad, 64 ); memcpy( bufferOut + 64, tk2, c_sha1_digest_size ); sha1 hash2( bufferOut, 64 + c_sha1_digest_size ); hash2.copy_digest_to_buffer( p_buffer ); } #ifdef COMPILE_TESTBED_MAIN int main( int argc, char* argv[ ] ) { if( argc > 1 && argv[ 1 ] == string( "/?" ) ) { cout << "Usage: sha1 [<file>]" << endl; return 0; } sha1 hash; if( argc > 1 ) { FILE* fp = fopen( argv[ 1 ], "rb" ); if( !fp ) { cerr << "Error: Unable to open file '" << argv[ 1 ] << "' for input." << endl; return 1; } unsigned int len; unsigned char buf[ 8192 ]; while( !feof( fp ) ) { len = fread( buf, 1, 8192, fp ); hash.update( buf, len ); } fclose( fp ); string s = hash.get_digest_as_string( ' ' ); transform( s.begin( ), s.end( ), s.begin( ), ( int( * )( int ) )toupper ); cout << "SHA-1 digest: " << s << endl; } else { string next; while( getline( cin, next ) ) { if( cin.eof( ) ) break; hash.init( ); hash.update( ( const unsigned char* )next.c_str( ), next.length( ) ); string s = hash.get_digest_as_string( ' ' ); transform( s.begin( ), s.end( ), s.begin( ), ( int( * )( int ) )toupper ); cout << "SHA-1 digest: " << s << '\n' << '\n'; } } } #endif
28.392324
105
0.535671
[ "transform" ]
1b32ae27326adcd5d051e3f0024dc655544269d5
1,727
cpp
C++
341.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
341.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
341.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PIII pair<int,PII> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; int N,x,y,z,i,cost,source,dest,ans; int par[15],dis[15]; vector<PII> adjlist[15]; vector<int> path; priority_queue<PIII,vector<PIII>,greater<PIII> > pq; int dijkstra() { int i,j; memset(par,-1,sizeof(par)); for(i=1;i<=N;i++) dis[i]=INF; pq.push(mp(0,mp(source,-1))); while(!pq.empty()) { int now=pq.top().se.fi; int from=pq.top().se.se; int cost=pq.top().fi; pq.pop(); if(dis[now]==INF) { dis[now]=cost; par[now]=from; for(j=0;j<adjlist[now].size();j++) { int next=adjlist[now][j].fi; pq.push(mp(dis[now]+adjlist[now][j].se,mp(next,now))); } } } return(dis[dest]); } int main() { i=0; while(1) { scanf("%d",&N); if(!N) break; for(x=1;x<=N;x++) { adjlist[x].clear(); scanf("%d",&y); while(y--) { scanf("%d %d",&z,&cost); adjlist[x].pb(mp(z,cost)); } } scanf("%d %d",&source,&dest); ans=dijkstra(); x=dest; do { path.pb(x); x=par[x]; }while(par[x]!=-1); path.pb(source); printf("Case %d: Path =",++i); while(!path.empty()) { printf(" %d",path.back()); path.pop_back(); } printf("; %d second delay\n",ans); } return 0; }
17.09901
59
0.55414
[ "vector" ]
1b3850e8bbcaea1305baaabbb869ebdac388913c
6,132
cpp
C++
design-hashmap.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
1
2021-01-20T16:04:54.000Z
2021-01-20T16:04:54.000Z
design-hashmap.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
293
2018-11-29T14:54:29.000Z
2021-01-29T16:07:26.000Z
design-hashmap.cpp
cfriedt/leetcode
ad15031b407b895f12704897eb81042d7d56d07d
[ "MIT" ]
1
2020-11-10T10:49:12.000Z
2020-11-10T10:49:12.000Z
/* * Copyright (c) 2018 Christopher Friedt * * SPDX-License-Identifier: MIT */ #include <functional> #include <utility> #include <vector> using namespace std; class MyHashMap { public: // https://leetcode.com/problems/design-hashset MyHashMap() : n_items(0), buckets(bucket_block_size, nullptr) {} void put(int key, int value) { put(key, value, nullptr); } int get(int key) { size_t hash = hasher(key); uint32_t modded = hash % buckets.size(); bucket_list_node *b; for (b = buckets[modded]; nullptr != b && b->key != key; b = b->next) ; if (nullptr == b) { return -1; } else { return b->value; } } void remove(int key) { size_t hash = hasher(key); uint32_t modded = hash % buckets.size(); bucket_list_node *b, *b_prev; for (b_prev = nullptr, b = buckets[modded]; nullptr != b && b->key != key; b_prev = b, b = b->next) ; if (b) { if (!b_prev) { buckets[modded] = b->next; } else { b_prev->next = b->next; } delete b; n_items--; refactor(false); } } bool contains(int key) { size_t hash = hasher(key); uint32_t modded = hash % buckets.size(); bucket_list_node *b; for (b = buckets[modded]; nullptr != b && b->key != key; b = b->next) ; return nullptr != b; } vector<size_t> histogram() { vector<size_t> hist; for (size_t i = 0; i < buckets.size(); i++) { size_t j; bucket_list_node *b; for (b = buckets[i], j = 0; nullptr != b; b = b->next) j++; hist.push_back(j); } return hist; } protected: // We're going to use the approach that a hash table is an array of buckets // containing linked lists. There is a hash function that translates the key // to a hashed key, and then the hashed key will be used as an index to say // which bucket / linked-list we are going to add / remove / check for our // value. // // A critical measure of the speed of a hash table / set is its load factor. // Which (I believe) is defined as the number of items in the set / the number // of buckets. IIRC, this should definitely be less than unity - I would say // less than 0.5 to be on the safe side. // // Each time our hash table / set grows to a high threshold load factor, we // need to increase its size. Certain sizes might increase collisions, but I'm // going to ignore that for the purpose of this implementation. // // We'll start out with an initial hash size of 64, and when resizing, we'll // keep adding blocks of 64 until our load factor hits a lower threshold. // // Let's make the high threshold load factor 0.5 and the low threshold load // factor 0.25. // // We should always be able to get a histogram of bucket list lengths too, // which will indicate how uniform our hashing algorithm is and how many // collisions it produces for a given number of buckets. static constexpr size_t bucket_block_size = 64; static constexpr float load_factor_low = 0.1; static constexpr float load_factor_high = 0.5; static const function<size_t(int)> hasher; explicit MyHashMap(size_t n_buckets) : n_items(0), buckets(n_buckets, nullptr) {} struct bucket_list_node { int key; int value; size_t hash; bucket_list_node *next; bucket_list_node() : bucket_list_node(0, 0) {} explicit bucket_list_node(int key, int value) : key(key), value(value), hash(hasher(key)), next(nullptr) {} }; size_t n_items; vector<bucket_list_node *> buckets; void put(int key, int value, bucket_list_node *bucket) { size_t hash; if (nullptr == bucket) { hash = hasher(key); } else { key = bucket->key; value = bucket->value; hash = bucket->hash; } uint32_t modded = hash % buckets.size(); if (nullptr == buckets[modded]) { if (nullptr == bucket) { buckets[modded] = new bucket_list_node(key, value); } else { buckets[modded] = bucket; } n_items++; refactor(true); } else { bucket_list_node *b; for (b = buckets[modded]; nullptr != b->next && b->key != key; b = b->next) ; if (b->key == key) { b->value = value; } else { if (nullptr == bucket) { b->next = new bucket_list_node(key, value); } else { b->next = bucket; } } n_items++; refactor(true); } } void putAll(size_t n_items, vector<bucket_list_node *> &buckets) { for (size_t i = 0; i < buckets.size() && n_items > 0; i++) { vector<bucket_list_node *> stack; for (bucket_list_node *b = buckets[i]; b; b = b->next) { stack.push_back(b); } for (auto &b : stack) { b->next = nullptr; put(-1, -1, b); } } } float loadFactor() { return loadFactor(n_items, buckets.size()); } static float loadFactor(size_t n_items, size_t n_buckets) { return float(n_items) / n_buckets; } void refactor(bool increased) { size_t n_items = this->n_items; size_t n_buckets = buckets.size(); float lf = loadFactor(n_items, n_buckets); if (increased) { if (lf >= load_factor_high) { for (; lf >= (load_factor_low + load_factor_high) / 2; n_buckets += bucket_block_size, lf = loadFactor(n_items, n_buckets)) ; MyHashMap new_bucket_list(n_buckets); new_bucket_list.putAll(n_items, buckets); buckets = new_bucket_list.buckets; } } else { if (lf < load_factor_low) { for (; n_buckets > bucket_block_size && lf < (load_factor_low + load_factor_high) / 2; n_buckets -= bucket_block_size, lf = loadFactor(n_items, n_buckets)) ; if (0 != n_buckets) { MyHashMap new_bucket_list(n_buckets); new_bucket_list.putAll(n_items, buckets); buckets = new_bucket_list.buckets; } } } } }; const function<size_t(int)> MyHashMap::hasher = hash<int>();
25.443983
80
0.596217
[ "vector" ]
1b39870ea365e626e041e9db3359e31ebf414bc8
13,736
cc
C++
third_party/webrtc/src/chromium/src/chromecast/media/cma/pipeline/media_pipeline_impl.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
8
2016-02-08T11:59:31.000Z
2020-05-31T15:19:54.000Z
third_party/webrtc/src/chromium/src/chromecast/media/cma/pipeline/media_pipeline_impl.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
1
2021-05-05T11:11:31.000Z
2021-05-05T11:11:31.000Z
third_party/webrtc/src/chromium/src/chromecast/media/cma/pipeline/media_pipeline_impl.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
7
2016-02-09T09:28:14.000Z
2020-07-25T19:03:36.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/media/cma/pipeline/media_pipeline_impl.h" #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/location.h" #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "base/time/time.h" #include "chromecast/media/cdm/browser_cdm_cast.h" #include "chromecast/media/cma/base/buffering_controller.h" #include "chromecast/media/cma/base/buffering_state.h" #include "chromecast/media/cma/base/cma_logging.h" #include "chromecast/media/cma/base/coded_frame_provider.h" #include "chromecast/media/cma/pipeline/audio_pipeline_impl.h" #include "chromecast/media/cma/pipeline/video_pipeline_impl.h" #include "chromecast/public/media/media_clock_device.h" #include "chromecast/public/media/media_pipeline_backend.h" #include "media/base/timestamp_constants.h" namespace chromecast { namespace media { namespace { // Buffering parameters when load_type is kLoadTypeUrl. const base::TimeDelta kLowBufferThresholdURL( base::TimeDelta::FromMilliseconds(2000)); const base::TimeDelta kHighBufferThresholdURL( base::TimeDelta::FromMilliseconds(6000)); // Buffering parameters when load_type is kLoadTypeMediaSource. const base::TimeDelta kLowBufferThresholdMediaSource( base::TimeDelta::FromMilliseconds(0)); const base::TimeDelta kHighBufferThresholdMediaSource( base::TimeDelta::FromMilliseconds(300)); // Interval between two updates of the media time. const base::TimeDelta kTimeUpdateInterval( base::TimeDelta::FromMilliseconds(250)); // Interval between two updates of the statistics is equal to: // kTimeUpdateInterval * kStatisticsUpdatePeriod. const int kStatisticsUpdatePeriod = 4; } // namespace MediaPipelineImpl::MediaPipelineImpl() : has_audio_(false), has_video_(false), target_playback_rate_(0.0), enable_time_update_(false), pending_time_update_task_(false), statistics_rolling_counter_(0), weak_factory_(this) { CMALOG(kLogControl) << __FUNCTION__; weak_this_ = weak_factory_.GetWeakPtr(); thread_checker_.DetachFromThread(); } MediaPipelineImpl::~MediaPipelineImpl() { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); weak_factory_.InvalidateWeakPtrs(); // Since av pipeline still need to access device components in their // destructor, it's important to delete them first. video_pipeline_.reset(); audio_pipeline_.reset(); media_pipeline_backend_.reset(); if (!client_.pipeline_backend_destroyed_cb.is_null()) client_.pipeline_backend_destroyed_cb.Run(); } void MediaPipelineImpl::Initialize( LoadType load_type, scoped_ptr<MediaPipelineBackend> media_pipeline_backend) { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); media_pipeline_backend_.reset(media_pipeline_backend.release()); clock_device_ = media_pipeline_backend_->GetClock(); if (!client_.pipeline_backend_created_cb.is_null()) client_.pipeline_backend_created_cb.Run(); if (load_type == kLoadTypeURL || load_type == kLoadTypeMediaSource) { base::TimeDelta low_threshold(kLowBufferThresholdURL); base::TimeDelta high_threshold(kHighBufferThresholdURL); if (load_type == kLoadTypeMediaSource) { low_threshold = kLowBufferThresholdMediaSource; high_threshold = kHighBufferThresholdMediaSource; } scoped_refptr<BufferingConfig> buffering_config( new BufferingConfig(low_threshold, high_threshold)); buffering_controller_.reset(new BufferingController( buffering_config, base::Bind(&MediaPipelineImpl::OnBufferingNotification, weak_this_))); } audio_pipeline_.reset( new AudioPipelineImpl(media_pipeline_backend_->GetAudio())); video_pipeline_.reset( new VideoPipelineImpl(media_pipeline_backend_->GetVideo())); } void MediaPipelineImpl::SetClient(const MediaPipelineClient& client) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!client.error_cb.is_null()); DCHECK(!client.time_update_cb.is_null()); DCHECK(!client.buffering_state_cb.is_null()); DCHECK(!client.pipeline_backend_created_cb.is_null()); DCHECK(!client.pipeline_backend_destroyed_cb.is_null()); client_ = client; } void MediaPipelineImpl::SetCdm(int cdm_id) { CMALOG(kLogControl) << __FUNCTION__ << " cdm_id=" << cdm_id; DCHECK(thread_checker_.CalledOnValidThread()); NOTIMPLEMENTED(); // TODO(gunsch): SetCdm(int) is not implemented. // One possibility would be a GetCdmByIdCB that's passed in. } void MediaPipelineImpl::SetCdm(BrowserCdmCast* cdm) { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); audio_pipeline_->SetCdm(cdm); video_pipeline_->SetCdm(cdm); } AudioPipeline* MediaPipelineImpl::GetAudioPipeline() const { return audio_pipeline_.get(); } VideoPipeline* MediaPipelineImpl::GetVideoPipeline() const { return video_pipeline_.get(); } void MediaPipelineImpl::InitializeAudio( const ::media::AudioDecoderConfig& config, scoped_ptr<CodedFrameProvider> frame_provider, const ::media::PipelineStatusCB& status_cb) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!has_audio_); if (clock_device_->GetState() == MediaClockDevice::kStateUninitialized && !clock_device_->SetState(MediaClockDevice::kStateIdle)) { status_cb.Run(::media::PIPELINE_ERROR_INITIALIZATION_FAILED); return; } has_audio_ = true; audio_pipeline_->Initialize(config, frame_provider.Pass(), status_cb); } void MediaPipelineImpl::InitializeVideo( const std::vector<::media::VideoDecoderConfig>& configs, scoped_ptr<CodedFrameProvider> frame_provider, const ::media::PipelineStatusCB& status_cb) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!has_video_); if (clock_device_->GetState() == MediaClockDevice::kStateUninitialized && !clock_device_->SetState(MediaClockDevice::kStateIdle)) { status_cb.Run(::media::PIPELINE_ERROR_INITIALIZATION_FAILED); return; } has_video_ = true; video_pipeline_->Initialize(configs, frame_provider.Pass(), status_cb); } void MediaPipelineImpl::StartPlayingFrom(base::TimeDelta time) { CMALOG(kLogControl) << __FUNCTION__ << " t0=" << time.InMilliseconds(); DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(has_audio_ || has_video_); DCHECK(!pending_flush_callbacks_); // Reset the start of the timeline. DCHECK_EQ(clock_device_->GetState(), MediaClockDevice::kStateIdle); clock_device_->ResetTimeline(time.InMicroseconds()); // Start the clock. If the playback rate is 0, then the clock is started // but does not increase. if (!clock_device_->SetState(MediaClockDevice::kStateRunning)) { OnError(::media::PIPELINE_ERROR_ABORT); return; } // Enable time updates. enable_time_update_ = true; statistics_rolling_counter_ = 0; if (!pending_time_update_task_) { pending_time_update_task_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&MediaPipelineImpl::UpdateMediaTime, weak_this_)); } // Setup the audio and video pipeline for the new timeline. if (has_audio_) { scoped_refptr<BufferingState> buffering_state; if (buffering_controller_) buffering_state = buffering_controller_->AddStream("audio"); if (!audio_pipeline_->StartPlayingFrom(time, buffering_state)) { OnError(::media::PIPELINE_ERROR_ABORT); return; } } if (has_video_) { scoped_refptr<BufferingState> buffering_state; if (buffering_controller_) buffering_state = buffering_controller_->AddStream("video"); if (!video_pipeline_->StartPlayingFrom(time, buffering_state)) { OnError(::media::PIPELINE_ERROR_ABORT); return; } } } void MediaPipelineImpl::Flush(const ::media::PipelineStatusCB& status_cb) { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(has_audio_ || has_video_); DCHECK(!pending_flush_callbacks_); DCHECK(clock_device_->GetState() == MediaClockDevice::kStateUninitialized || clock_device_->GetState() == MediaClockDevice::kStateRunning); // No need to update media time anymore. enable_time_update_ = false; buffering_controller_->Reset(); // The clock should return to idle. if (!clock_device_->SetState(MediaClockDevice::kStateIdle)) { status_cb.Run(::media::PIPELINE_ERROR_ABORT); return; } // Flush both the audio and video pipeline. ::media::SerialRunner::Queue bound_fns; if (has_audio_) { bound_fns.Push(base::Bind( &AudioPipelineImpl::Flush, base::Unretained(audio_pipeline_.get()))); } if (has_video_) { bound_fns.Push(base::Bind( &VideoPipelineImpl::Flush, base::Unretained(video_pipeline_.get()))); } ::media::PipelineStatusCB transition_cb = base::Bind(&MediaPipelineImpl::StateTransition, weak_this_, status_cb); pending_flush_callbacks_ = ::media::SerialRunner::Run(bound_fns, transition_cb); } void MediaPipelineImpl::Stop() { CMALOG(kLogControl) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(has_audio_ || has_video_); // Cancel pending flush callbacks since we are about to stop/shutdown // audio/video pipelines. This will ensure A/V Flush won't happen in // stopped state. pending_flush_callbacks_.reset(); // No need to update media time anymore. enable_time_update_ = false; // Release hardware resources on Stop. // Note: Stop can be called from any state. if (clock_device_->GetState() == MediaClockDevice::kStateRunning) clock_device_->SetState(MediaClockDevice::kStateIdle); if (clock_device_->GetState() == MediaClockDevice::kStateIdle) clock_device_->SetState(MediaClockDevice::kStateUninitialized); // Stop both the audio and video pipeline. if (has_audio_) audio_pipeline_->Stop(); if (has_video_) video_pipeline_->Stop(); } void MediaPipelineImpl::SetPlaybackRate(double rate) { CMALOG(kLogControl) << __FUNCTION__ << " rate=" << rate; DCHECK(thread_checker_.CalledOnValidThread()); target_playback_rate_ = rate; if (!buffering_controller_ || !buffering_controller_->IsBuffering()) media_pipeline_backend_->GetClock()->SetRate(rate); } AudioPipelineImpl* MediaPipelineImpl::GetAudioPipelineImpl() const { return audio_pipeline_.get(); } VideoPipelineImpl* MediaPipelineImpl::GetVideoPipelineImpl() const { return video_pipeline_.get(); } void MediaPipelineImpl::StateTransition( const ::media::PipelineStatusCB& status_cb, ::media::PipelineStatus status) { pending_flush_callbacks_.reset(); status_cb.Run(status); } void MediaPipelineImpl::OnBufferingNotification(bool is_buffering) { CMALOG(kLogControl) << __FUNCTION__ << " is_buffering=" << is_buffering; DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(buffering_controller_); if (!client_.buffering_state_cb.is_null()) { ::media::BufferingState buffering_state = is_buffering ? ::media::BUFFERING_HAVE_NOTHING : ::media::BUFFERING_HAVE_ENOUGH; client_.buffering_state_cb.Run(buffering_state); } if (media_pipeline_backend_->GetClock()->GetState() == MediaClockDevice::kStateUninitialized) { return; } if (is_buffering) { // Do not consume data in a rebuffering phase. media_pipeline_backend_->GetClock()->SetRate(0.0); } else { media_pipeline_backend_->GetClock()->SetRate(target_playback_rate_); } } void MediaPipelineImpl::UpdateMediaTime() { pending_time_update_task_ = false; if (!enable_time_update_) return; if (statistics_rolling_counter_ == 0) { audio_pipeline_->UpdateStatistics(); video_pipeline_->UpdateStatistics(); } statistics_rolling_counter_ = (statistics_rolling_counter_ + 1) % kStatisticsUpdatePeriod; base::TimeDelta media_time = base::TimeDelta::FromMicroseconds(clock_device_->GetTimeMicroseconds()); if (media_time == ::media::kNoTimestamp()) { pending_time_update_task_ = true; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&MediaPipelineImpl::UpdateMediaTime, weak_this_), kTimeUpdateInterval); return; } base::TimeTicks stc = base::TimeTicks::Now(); base::TimeDelta max_rendering_time = media_time; if (buffering_controller_) { buffering_controller_->SetMediaTime(media_time); // Receiving the same time twice in a row means playback isn't moving, // so don't interpolate ahead. if (media_time != last_media_time_) { max_rendering_time = buffering_controller_->GetMaxRenderingTime(); if (max_rendering_time == ::media::kNoTimestamp()) max_rendering_time = media_time; // Cap interpolation time to avoid interpolating too far ahead. max_rendering_time = std::min(max_rendering_time, media_time + 2 * kTimeUpdateInterval); } } last_media_time_ = media_time; if (!client_.time_update_cb.is_null()) client_.time_update_cb.Run(media_time, max_rendering_time, stc); pending_time_update_task_ = true; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&MediaPipelineImpl::UpdateMediaTime, weak_this_), kTimeUpdateInterval); } void MediaPipelineImpl::OnError(::media::PipelineStatus error) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_NE(error, ::media::PIPELINE_OK) << "PIPELINE_OK is not an error!"; if (!client_.error_cb.is_null()) client_.error_cb.Run(error); } } // namespace media } // namespace chromecast
35.040816
80
0.749418
[ "vector" ]
1b3cea4de424d386c787879cc321b5b26a0d4aff
18,413
cpp
C++
lib/mayaUsd/ufe/UsdAttribute.cpp
ika-rporter/maya-usd
8f216a4fb955fc44c0abda55caa53ed295aaa625
[ "Apache-2.0" ]
3
2020-03-18T10:11:32.000Z
2020-05-27T08:52:26.000Z
lib/mayaUsd/ufe/UsdAttribute.cpp
ika-rporter/maya-usd
8f216a4fb955fc44c0abda55caa53ed295aaa625
[ "Apache-2.0" ]
null
null
null
lib/mayaUsd/ufe/UsdAttribute.cpp
ika-rporter/maya-usd
8f216a4fb955fc44c0abda55caa53ed295aaa625
[ "Apache-2.0" ]
2
2020-03-18T10:11:46.000Z
2021-02-20T06:45:47.000Z
// // Copyright 2019 Autodesk // // 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 "UsdAttribute.h" #include "private/Utils.h" #include <mayaUsd/ufe/StagesSubject.h> #include <mayaUsd/ufe/Utils.h> #include <mayaUsd/undo/UsdUndoBlock.h> #include <mayaUsd/undo/UsdUndoableItem.h> #include <pxr/base/tf/token.h> #include <pxr/base/vt/value.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/attributeSpec.h> #include <pxr/usd/usd/schemaRegistry.h> #include <sstream> #include <unordered_map> #include <unordered_set> // Note: normally we would use this using directive, but here we cannot because // our class is called UsdAttribute which is exactly the same as the one // in USD. // PXR_NAMESPACE_USING_DIRECTIVE static constexpr char kErrorMsgFailedConvertToString[] = "Could not convert the attribute to a string"; static constexpr char kErrorMsgInvalidType[] = "USD attribute does not match created attribute class type"; //------------------------------------------------------------------------------ // Helper functions //------------------------------------------------------------------------------ namespace { template <typename T> bool setUsdAttr(const PXR_NS::UsdAttribute& attr, const T& value) { // USD Attribute Notification doubling problem: // As of 24-Nov-2019, calling Set() on a UsdAttribute causes two "info only" // change notifications to be sent (see StagesSubject::stageChanged). With // the current USD implementation (USD 19.11), UsdAttribute::Set() ends up // in UsdStage::_SetValueImpl(). This function calls in sequence: // - UsdStage::_CreateAttributeSpecForEditing(), which has an SdfChangeBlock // whose expiry causes a notification to be sent. // - SdfLayer::SetField(), which also has an SdfChangeBlock whose // expiry causes a notification to be sent. // These two calls appear to be made on all calls to UsdAttribute::Set(), // not just on the first call. // // Trying to wrap the call to UsdAttribute::Set() inside an additional // SdfChangeBlock fails: no notifications are sent at all. This is most // likely because of the warning given in the SdfChangeBlock documentation: // // https://graphics.pixar.com/usd/docs/api/class_sdf_change_block.html // // which stages that "it is not safe to use [...] [a] downstream API [such // as Usd] while a changeblock is open [...]". // // Therefore, we have implemented an attribute change block notification of // our own in the StagesSubject, which we invoke here, so that only a // single UFE attribute changed notification is generated. MayaUsd::ufe::AttributeChangedNotificationGuard guard; std::string errMsg; bool isSetAttrAllowed = MayaUsd::ufe::isAttributeEditAllowed(attr, &errMsg); if (!isSetAttrAllowed) { MGlobal::displayError(errMsg.c_str()); return false; } return attr.Set<T>(value); } PXR_NS::UsdTimeCode getCurrentTime(const Ufe::SceneItem::Ptr& item) { // Attributes with time samples will fail when calling Get with default time code. // So we'll always use the current time when calling Get. If there are no time // samples, it will fall-back to the default time code. return MayaUsd::ufe::getTime(item->path()); } std::string getUsdAttributeValueAsString(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) { if (!attr.HasValue()) return std::string(); PXR_NS::VtValue v; if (attr.Get(&v, time)) { if (v.CanCast<std::string>()) { PXR_NS::VtValue v_str = v.Cast<std::string>(); return v_str.Get<std::string>(); } std::ostringstream os; os << v; return os.str(); } TF_CODING_ERROR(kErrorMsgFailedConvertToString); return std::string(); } template <typename T, typename U> U getUsdAttributeVectorAsUfe(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) { if (!attr.HasValue()) return U(); PXR_NS::VtValue vt; if (attr.Get(&vt, time) && vt.IsHolding<T>()) { T gfVec = vt.UncheckedGet<T>(); U ret(gfVec[0], gfVec[1], gfVec[2]); return ret; } return U(); } template <typename T, typename U> void setUsdAttributeVectorFromUfe( PXR_NS::UsdAttribute& attr, const U& value, const PXR_NS::UsdTimeCode& time) { T vec; vec.Set(value.x(), value.y(), value.z()); setUsdAttr<T>(attr, vec); } template <typename T, typename A = MayaUsd::ufe::TypedUsdAttribute<T>> class SetUndoableCommand : public Ufe::UndoableCommand { public: SetUndoableCommand(const typename A::Ptr& attr, const T& newValue) : _attr(attr) , _newValue(newValue) { } void execute() override { MayaUsd::UsdUndoBlock undoBlock(&_undoableItem); _attr->set(_newValue); } void undo() override { _undoableItem.undo(); } void redo() override { _undoableItem.redo(); } private: const typename A::Ptr _attr; const T _newValue; MayaUsd::UsdUndoableItem _undoableItem; }; } // end namespace namespace MAYAUSD_NS_DEF { namespace ufe { //------------------------------------------------------------------------------ // UsdAttribute: //------------------------------------------------------------------------------ UsdAttribute::UsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : fUsdAttr(usdAttr) { fPrim = item->prim(); } UsdAttribute::~UsdAttribute() { } bool UsdAttribute::hasValue() const { return fUsdAttr.HasValue(); } std::string UsdAttribute::name() const { // Should be the same as the name we were created with. return fUsdAttr.GetName().GetString(); } std::string UsdAttribute::documentation() const { return fUsdAttr.GetDocumentation(); } std::string UsdAttribute::string(const Ufe::SceneItem::Ptr& item) const { return getUsdAttributeValueAsString(fUsdAttr, getCurrentTime(item)); } //------------------------------------------------------------------------------ // UsdAttributeGeneric: //------------------------------------------------------------------------------ UsdAttributeGeneric::UsdAttributeGeneric( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::AttributeGeneric(item) , UsdAttribute(item, usdAttr) { } /*static*/ UsdAttributeGeneric::Ptr UsdAttributeGeneric::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeGeneric>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeGeneric - Ufe::AttributeGeneric overrides //------------------------------------------------------------------------------ std::string UsdAttributeGeneric::nativeType() const { return fUsdAttr.GetTypeName().GetType().GetTypeName(); } //------------------------------------------------------------------------------ // UsdAttributeEnumString: //------------------------------------------------------------------------------ UsdAttributeEnumString::UsdAttributeEnumString( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::AttributeEnumString(item) , UsdAttribute(item, usdAttr) { } /*static*/ UsdAttributeEnumString::Ptr UsdAttributeEnumString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeEnumString>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeEnumString - Ufe::AttributeEnumString overrides //------------------------------------------------------------------------------ std::string UsdAttributeEnumString::get() const { PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem())) && vt.IsHolding<TfToken>()) { TfToken tok = vt.UncheckedGet<TfToken>(); return tok.GetString(); } return std::string(); } void UsdAttributeEnumString::set(const std::string& value) { PXR_NS::TfToken tok(value); setUsdAttr<PXR_NS::TfToken>(fUsdAttr, tok); } Ufe::UndoableCommand::Ptr UsdAttributeEnumString::setCmd(const std::string& value) { auto self = std::dynamic_pointer_cast<UsdAttributeEnumString>(shared_from_this()); if (!TF_VERIFY(self, kErrorMsgInvalidType)) return nullptr; return std::make_shared<SetUndoableCommand<std::string, UsdAttributeEnumString>>(self, value); } Ufe::AttributeEnumString::EnumValues UsdAttributeEnumString::getEnumValues() const { PXR_NS::TfToken tk(name()); auto attrDefn = fPrim.GetPrimDefinition().GetSchemaAttributeSpec(tk); if (attrDefn && attrDefn->HasAllowedTokens()) { auto tokenArray = attrDefn->GetAllowedTokens(); std::vector<PXR_NS::TfToken> tokenVec(tokenArray.begin(), tokenArray.end()); EnumValues tokens = PXR_NS::TfToStringVector(tokenVec); return tokens; } return EnumValues(); } //------------------------------------------------------------------------------ // TypedUsdAttribute<T>: //------------------------------------------------------------------------------ template <typename T> TypedUsdAttribute<T>::TypedUsdAttribute( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::TypedAttribute<T>(item) , UsdAttribute(item, usdAttr) { } template <typename T> Ufe::UndoableCommand::Ptr TypedUsdAttribute<T>::setCmd(const T& value) { // See // https://stackoverflow.com/questions/17853212/using-shared-from-this-in-templated-classes // for explanation of this->shared_from_this() in templated class. return std::make_shared<SetUndoableCommand<T>>(this->shared_from_this(), value); } //------------------------------------------------------------------------------ // TypedUsdAttribute<T> - Ufe::TypedAttribute overrides //------------------------------------------------------------------------------ template <> std::string TypedUsdAttribute<std::string>::get() const { if (!hasValue()) return std::string(); PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem()))) { // The USDAttribute can be holding either TfToken or string. if (vt.IsHolding<TfToken>()) { TfToken tok = vt.UncheckedGet<TfToken>(); return tok.GetString(); } else if (vt.IsHolding<std::string>()) { return vt.UncheckedGet<std::string>(); } } return std::string(); } template <> void TypedUsdAttribute<std::string>::set(const std::string& value) { // We need to figure out if the USDAttribute is holding a TfToken or string. const PXR_NS::SdfValueTypeName typeName = fUsdAttr.GetTypeName(); if (typeName.GetHash() == SdfValueTypeNames->String.GetHash()) { setUsdAttr<std::string>(fUsdAttr, value); return; } else if (typeName.GetHash() == SdfValueTypeNames->Token.GetHash()) { PXR_NS::TfToken tok(value); setUsdAttr<PXR_NS::TfToken>(fUsdAttr, tok); return; } // If we get here it means the USDAttribute type wasn't TfToken or string. TF_CODING_ERROR(kErrorMsgInvalidType); } template <> Ufe::Color3f TypedUsdAttribute<Ufe::Color3f>::get() const { return getUsdAttributeVectorAsUfe<GfVec3f, Ufe::Color3f>(fUsdAttr, getCurrentTime(sceneItem())); } // Note: cannot use setUsdAttributeVectorFromUfe since it relies on x/y/z template <> void TypedUsdAttribute<Ufe::Color3f>::set(const Ufe::Color3f& value) { GfVec3f vec; vec.Set(value.r(), value.g(), value.b()); setUsdAttr<GfVec3f>(fUsdAttr, vec); } template <> Ufe::Vector3i TypedUsdAttribute<Ufe::Vector3i>::get() const { return getUsdAttributeVectorAsUfe<GfVec3i, Ufe::Vector3i>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3i>::set(const Ufe::Vector3i& value) { setUsdAttributeVectorFromUfe<GfVec3i, Ufe::Vector3i>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <> Ufe::Vector3f TypedUsdAttribute<Ufe::Vector3f>::get() const { return getUsdAttributeVectorAsUfe<GfVec3f, Ufe::Vector3f>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3f>::set(const Ufe::Vector3f& value) { setUsdAttributeVectorFromUfe<GfVec3f, Ufe::Vector3f>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <> Ufe::Vector3d TypedUsdAttribute<Ufe::Vector3d>::get() const { return getUsdAttributeVectorAsUfe<GfVec3d, Ufe::Vector3d>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3d>::set(const Ufe::Vector3d& value) { setUsdAttributeVectorFromUfe<GfVec3d, Ufe::Vector3d>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <typename T> T TypedUsdAttribute<T>::get() const { if (!hasValue()) return T(); PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(Ufe::Attribute::sceneItem())) && vt.IsHolding<T>()) { return vt.UncheckedGet<T>(); } return T(); } template <typename T> void TypedUsdAttribute<T>::set(const T& value) { setUsdAttr<T>(fUsdAttr, value); } //------------------------------------------------------------------------------ // UsdAttributeBool: //------------------------------------------------------------------------------ /*static*/ UsdAttributeBool::Ptr UsdAttributeBool::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeBool>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeInt: //------------------------------------------------------------------------------ /*static*/ UsdAttributeInt::Ptr UsdAttributeInt::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeInt>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeFloat: //------------------------------------------------------------------------------ /*static*/ UsdAttributeFloat::Ptr UsdAttributeFloat::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeFloat>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeDouble: //------------------------------------------------------------------------------ /*static*/ UsdAttributeDouble::Ptr UsdAttributeDouble::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeDouble>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeString: //------------------------------------------------------------------------------ /*static*/ UsdAttributeString::Ptr UsdAttributeString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeString>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeColorFloat3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeColorFloat3::Ptr UsdAttributeColorFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeColorFloat3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeInt3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeInt3::Ptr UsdAttributeInt3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeInt3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeFloat3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeFloat3::Ptr UsdAttributeFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeFloat3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeDouble3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeDouble3::Ptr UsdAttributeDouble3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeDouble3>(item, usdAttr); return attr; } #if 0 // Note: if we were to implement generic attribute setting (via string) this // would be the way it could be done. bool UsdAttribute::setValue(const std::string& value) { // Put the input string into a VtValue so we can cast it to the proper type. PXR_NS::VtValue val(value.c_str()); // Attempt to cast the value to what we want. Get a default value for this // attribute's type name. PXR_NS::VtValue defVal = fUsdAttr.GetTypeName().GetDefaultValue(); // Attempt to cast the given string to the default value's type. // If casting fails, attempt to continue with the given value. PXR_NS::VtValue cast = PXR_NS::VtValue::CastToTypeOf(val, defVal); if (!cast.IsEmpty()) cast.Swap(val); return setUsdAttr<PXR_NS::VtValue>(fUsdAttr, val); } #endif } // namespace ufe } // namespace MAYAUSD_NS_DEF
33.236462
100
0.593005
[ "vector" ]
1b3cfc764825a4ee89dd4afe7c7325ca456adf72
13,843
cpp
C++
src/engines/ioda/src/ioda/Engines/HH/HH-util.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
null
null
null
src/engines/ioda/src/ioda/Engines/HH/HH-util.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
null
null
null
src/engines/ioda/src/ioda/Engines/HH/HH-util.cpp
NOAA-EMC/ioda
366ce1aa4572dde7f3f15862a2970f3dd3c82369
[ "Apache-2.0" ]
null
null
null
/* * (C) Copyright 2020-2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /*! \addtogroup ioda_internals_engines_hh * * @{ * \file HH-util.cpp * \brief HDF5 utility functions. */ #include "./HH/HH-util.h" #include <hdf5_hl.h> #include <algorithm> #include <cstring> #include <iterator> #include <string> #include <utility> #include <vector> #include "./HH/Handles.h" #include "./HH/HH-attributes.h" #include "./HH/HH-variables.h" #include "ioda/Exception.h" namespace ioda { namespace detail { namespace Engines { namespace HH { /// Callback function for H5Aiterate / H5Aiterate2 / H5Aiterate1. #if H5_VERSION_GE(1, 8, 0) herr_t iterate_find_attr(hid_t loc_id, const char* name, const H5A_info_t* info, void* op_data) { #else herr_t iterate_find_attr(hid_t loc_id, const char* name, void* op_data) { H5A_info_t in_info; H5Aget_info_by_name(loc_id, ".", name, &in_info, H5P_DEFAULT);) H5A_info_t* info = &in_info; #endif Iterator_find_attr_data_t* op = (Iterator_find_attr_data_t*)op_data; // NOLINT: HDF5 mandates that op_data be void*. if (name == nullptr) return -1; if (std::string(name) == op->search_for) { op->success = true; return 1; } op->idx++; return 0; } H5_index_t getAttrCreationOrder(hid_t obj, H5O_type_t objType) { if (objType != H5O_TYPE_DATASET && objType != H5O_TYPE_GROUP) throw Exception("Invalid object type", ioda_Here()); // Apparently files do not have a creation plist. They show up as groups, // so we catch this and return H5_INDEX_NAME. if (objType == H5O_TYPE_GROUP) { H5I_type_t typ = H5Iget_type(obj); // NOLINT if (typ < 0) throw Exception("Error determining object type", ioda_Here()); if (typ == H5I_FILE) return H5_INDEX_NAME; // NOLINT } unsigned crt_order_flags = 0; hid_t hcreatepl = (objType == H5O_TYPE_DATASET) ? H5Dget_create_plist(obj) : H5Gget_create_plist(obj); HH_hid_t createpl(hcreatepl, Handles::Closers::CloseHDF5PropertyList::CloseP); if (createpl() < 0) throw Exception("Cannot get creation property list", ioda_Here()); if (0 > H5Pget_attr_creation_order(createpl(), &crt_order_flags)) throw Exception("Cannot get attribute creation order", ioda_Here()); // We only care if this property is tracked. Indexing is performed on the fly // if it is not available (and incurs a read penalty), but this has performance of // at least ordering by name. return (crt_order_flags & H5P_CRT_ORDER_TRACKED) // NOLINT ? H5_INDEX_CRT_ORDER : H5_INDEX_NAME; } std::pair<bool, hsize_t> iterativeAttributeSearch(hid_t baseObject, const char* attname, H5_index_t iteration_type) { // H5Aiterate2 exists in v1.8 and up. hsize_t pos = 0; Iterator_find_attr_data_t opts; opts.search_for = std::string(attname); herr_t append_ret = H5Aiterate2(baseObject, // Search on this dataset iteration_type, // Iterate by name or creation order H5_ITER_NATIVE, // Fastest ordering possible &pos, // Initial (and current) index iterate_find_attr, // C-style search function reinterpret_cast<void*>(&opts) // Data passed to/from the C-style search function ); if (append_ret < 0) return std::pair<bool, hsize_t>(false, -2); return std::pair<bool, hsize_t>(opts.success, opts.idx); } HH_Attribute iterativeAttributeSearchAndOpen(hid_t baseObject, H5O_type_t objType, const char* attname) { // Get search order H5_index_t iteration_type = getAttrCreationOrder(baseObject, objType); auto searchres = iterativeAttributeSearch(baseObject, attname, iteration_type); bool searchSuccess = searchres.first; hsize_t idx = searchres.second; HH_Attribute aDims_HH; // Either create the attribute and set its initial data or open the attribute and append. if (searchSuccess) { // Open attribute and read data hid_t found_att = H5Aopen_by_idx(baseObject, ".", iteration_type, H5_ITER_NATIVE, idx, H5P_DEFAULT, H5P_DEFAULT); if (found_att < 0) throw Exception("Cannot open attribute by index", ioda_Here()); aDims_HH = HH_Attribute(HH_hid_t(std::move(found_att), Handles::Closers::CloseHDF5Attribute::CloseP)); } else { aDims_HH = HH_Attribute(HH_hid_t()); } return aDims_HH; } void attr_update_dimension_list(HH_Variable* var, const std::vector<std::vector<ref_t>>& new_dim_list) { hid_t var_id = var->get()(); auto dims = var->getDimensions(); // dimension of the "DIMENSION_LIST" array hsize_t hdims[1] = {gsl::narrow<hsize_t>(dims.dimensionality)}; // The attribute's dataspace HH_hid_t sid{-1, Handles::Closers::CloseHDF5Dataspace::CloseP}; if ((sid = H5Screate_simple(1, hdims, NULL)).get() < 0) throw Exception("Cannot create simple dataspace.", ioda_Here()); // The attribute's datatype HH_hid_t tid{-1, Handles::Closers::CloseHDF5Datatype::CloseP}; if ((tid = H5Tvlen_create(H5T_STD_REF_OBJ)).get() < 0) throw Exception("Cannot create variable length array type.", ioda_Here()); // Check if the DIMENSION_LIST attribute exists. HH_Attribute aDimList = iterativeAttributeSearchAndOpen(var_id, H5O_TYPE_DATASET, DIMENSION_LIST); // If the DIMENSION_LIST attribute does not exist, create it. // If it exists, read it. using std::vector; vector<hvl_t> dimlist_in_data(dims.dimensionality); if (!aDimList.get().isValid()) { // Create hid_t aid = H5Acreate(var_id, DIMENSION_LIST, tid(), sid(), H5P_DEFAULT, H5P_DEFAULT); if (aid < 0) throw Exception("Cannot create attribute", ioda_Here()); aDimList = HH_Attribute(HH_hid_t(aid, Handles::Closers::CloseHDF5Attribute::CloseP)); // Initialize dimlist_in_data to nulls. Used in merge operation later. for (auto & d : dimlist_in_data) { d.len = 0; d.p = nullptr; } } else { // Read if (H5Aread(aDimList.get()(), tid(), static_cast<void*>(dimlist_in_data.data())) < 0) throw Exception("Cannot read attribute", ioda_Here()); } // Allocate a new list that combines any previous DIMENSION_LIST with ref_axis. vector<hvl_t> dimlist_out_data(dims.dimensionality); // Merge the new allocations with any previous DIMENSION_LIST entries. // NOTE: Memory is explicitly freed at the end of the function. Since we are // using pure C function calls, throws will not happen even if we run out of memory. for (size_t dim = 0; dim < gsl::narrow<size_t>(dims.dimensionality); ++dim) { View_hvl_t<hobj_ref_t> olddims(dimlist_in_data[dim]); const std::vector<ref_t>& newdims = new_dim_list[dim]; View_hvl_t<hobj_ref_t> outdims(dimlist_out_data[dim]); // TODO(ryan)!!!!! // When merging, check if any references are equal. // Given our intended usage of this function, this may never happen. // Note the names here. old + new = out; outdims.resize(olddims.size() + newdims.size()); for (size_t i = 0; i < olddims.size(); ++i) { *outdims[i] = *olddims[i]; } for (size_t i = 0; i < newdims.size(); ++i) { *outdims[i + olddims.size()] = newdims[i]; } } // Write the new list. Deallocate the "old" lists after write, and then check for any errors. // Pure C code in between, so the deallocation always occurs. herr_t write_success = H5Awrite(aDimList.get()(), tid(), static_cast<void*>(dimlist_out_data.data())); // Deallocate old memory H5Dvlen_reclaim(tid.get(), sid.get(), H5P_DEFAULT, reinterpret_cast<void*>(dimlist_in_data.data())); for (size_t dim = 0; dim < gsl::narrow<size_t>(dims.dimensionality); ++dim) { View_hvl_t<hobj_ref_t> outdims(dimlist_out_data[dim]); // The View_hvl_t is a "view" that allows us to reinterpret dimlist_out_data[dim] // as a sequence of hobj_ref_t objects. // We use the resize method to trigger a deliberate free of held memory // that can result from the above merge step. outdims.resize(0); } if (write_success < 0) throw Exception("Failed to write DIMENSION_LIST.", ioda_Here()); } HH_hid_t attr_reference_list_type() { static HH_hid_t tid{-1, Handles::Closers::CloseHDF5Datatype::CloseP}; if (!tid.isValid()) { // The attribute's datatype if ((tid = H5Tcreate(H5T_COMPOUND, sizeof(ds_list_t))).get() < 0) throw Exception("Cannot create compound datatype.", ioda_Here()); if (H5Tinsert(tid(), "dataset", HOFFSET(ds_list_t, ref), H5T_STD_REF_OBJ) < 0) throw Exception("Cannot create compound datatype.", ioda_Here()); if (H5Tinsert(tid(), "dimension", HOFFSET(ds_list_t, dim_idx), H5T_NATIVE_INT) < 0) throw Exception("Cannot create compound datatype.", ioda_Here()); } return tid; } HH_hid_t attr_reference_list_space(hsize_t numrefs) { HH_hid_t sid{-1, Handles::Closers::CloseHDF5Dataspace::CloseP}; // dimension of the "REFERENCE_LIST" array const hsize_t hdims[1] = {numrefs}; // The attribute's dataspace if ((sid = H5Screate_simple(1, hdims, NULL)).get() < 0) throw Exception("Cannot create simple dataspace.", ioda_Here()); return sid; } void attr_update_reference_list(HH_Variable* scale, const std::vector<ds_list_t>& ref_var_axis) { using std::vector; HH_hid_t type = attr_reference_list_type(); hid_t scale_id = scale->get()(); // The REFERENCE_LIST attribute must be deleted and re-created each time // new references are added. // For the append operation, first check whether the attribute exists. vector<ds_list_t> oldrefs; HH_Attribute aDimListOld = iterativeAttributeSearchAndOpen(scale_id, H5O_TYPE_DATASET, REFERENCE_LIST); if (aDimListOld.get().isValid()) { oldrefs.resize(gsl::narrow<size_t>(aDimListOld.getDimensions().numElements)); if (H5Aread(aDimListOld.get()(), type(), oldrefs.data()) < 0) throw Exception("Cannot read REFERENCE_LIST attribute.", ioda_Here()); // Release the object handle and delete the attribute. aDimListOld = HH_Attribute(); scale->atts.remove(REFERENCE_LIST); } vector<ds_list_t> refs = oldrefs; refs.reserve(ref_var_axis.size() + oldrefs.size()); std::copy(ref_var_axis.begin(), ref_var_axis.end(), std::back_inserter(refs)); // Create the new REFERENCE_LIST attribute. HH_hid_t sid = attr_reference_list_space(gsl::narrow<hsize_t>(refs.size())); hid_t aid = H5Acreate(scale_id, REFERENCE_LIST, type(), sid(), H5P_DEFAULT, H5P_DEFAULT); if (aid < 0) throw Exception("Cannot create new REFERENCE_LIST attribute.", ioda_Here()); HH_Attribute newAtt(HH_hid_t(aid, Handles::Closers::CloseHDF5Attribute::CloseP)); if (H5Awrite(newAtt.get()(), type(), static_cast<void*>(refs.data())) < 0) throw Exception("Cannot write REFERENCE_LIST attribute.", ioda_Here()); } std::string getNameFromIdentifier(hid_t obj_id) { ssize_t sz = H5Iget_name(obj_id, nullptr, 0); if (sz < 0) throw Exception("Cannot get object name", ioda_Here()); std::vector<char> data(sz + 1, 0); ssize_t ret = H5Iget_name(obj_id, data.data(), data.size()); if (ret < 0) throw Exception("Cannot get object name", ioda_Here()); return std::string(data.data()); } std::vector<char> convertVariableLengthToFixedLength( gsl::span<const char> in_buf, size_t unitLength, bool lengthsAreExact) { // in_buf is pointer to plain old data (POD). Guaranteed by the marshalling operation at the // frontend / backend interface. Assuming that all POD data types have the same pointer size. // This is a reasonable assumption. const size_t ptrSize = sizeof(char *); if (in_buf.size() % ptrSize) throw Exception("In-memory variable-length buffer has " "the wrong number of elements. Should be a multiple of the size of a pointer.", ioda_Here()).add("in_buf.size()", in_buf.size()).add("ptrSize", ptrSize); const size_t numObjs = in_buf.size() / ptrSize; gsl::span<const char* const> data_as_ptrs( reinterpret_cast<const char* const*>(in_buf.data()), numObjs); // Construct the output buffer std::vector<char> buffer(numObjs * unitLength); for (size_t i=0; i < data_as_ptrs.size(); ++i) { // strlen is not quite the length of a string. It is the number of bytes until a NULL is found. size_t len = (lengthsAreExact) ? unitLength : std::min(unitLength, strlen(data_as_ptrs[i])); std::memcpy(buffer.data() + (i*unitLength), data_as_ptrs[i], len); } return buffer; } Marshalled_Data<char*, char*, true> convertFixedLengthToVariableLength( gsl::span<const char> in_buf, size_t unitLength) { if (in_buf.size() % unitLength) throw Exception("In-memory variable-length buffer has " "the wrong number of elements. Should be a multiple of unitLength.", ioda_Here()).add("in_buf.size()", in_buf.size()).add("unitLength", unitLength); const size_t numObjs = in_buf.size() / unitLength; // Construct the output buffer Marshalled_Data<char*, char*, true> out_buf; out_buf.DataPointers.resize(numObjs); for (size_t i=0; i < out_buf.DataPointers.size(); ++i) { // Select a span. Trim multiple trailing nulls and use in construction of a new null-terminated string. gsl::span<const char> untrimmed(in_buf.data() + (unitLength * i), unitLength); auto pos_first_null = std::find(untrimmed.begin(), untrimmed.end(), '\0'); const size_t sz = (pos_first_null != untrimmed.end()) ? pos_first_null - untrimmed.begin() : unitLength; out_buf.DataPointers[i] = (char*)malloc(sz+1); // NOLINT: deliberate malloc call. strncpy(out_buf.DataPointers[i], untrimmed.data(), sz); } return out_buf; } } // namespace HH } // namespace Engines } // namespace detail } // namespace ioda
42.46319
117
0.693925
[ "object", "vector" ]
1b3dc380397e299a857d1008a7e6eff12650e5f3
6,056
cpp
C++
src/hdt.cpp
svakulenk0/pyHDT
1ec234d0306914da53f4b0800394d3b8800ba871
[ "MIT" ]
null
null
null
src/hdt.cpp
svakulenk0/pyHDT
1ec234d0306914da53f4b0800394d3b8800ba871
[ "MIT" ]
null
null
null
src/hdt.cpp
svakulenk0/pyHDT
1ec234d0306914da53f4b0800394d3b8800ba871
[ "MIT" ]
1
2020-06-20T12:40:04.000Z
2020-06-20T12:40:04.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "docstrings.hpp" #include "hdt_document.hpp" #include "triple_iterator.hpp" #include "tripleid_iterator.hpp" #include "join_iterator.hpp" namespace py = pybind11; PYBIND11_MODULE(hdt, m) { m.doc() = MODULE_DOC; py::class_<TripleIterator>(m, "TripleIterator", TRIPLE_ITERATOR_CLASS_DOC) .def("next", &TripleIterator::next, TRIPLE_ITERATOR_NEXT_DOC) .def("__next__", &TripleIterator::next, TRIPLE_ITERATOR_NEXT_DOC) .def("peek", &TripleIterator::peek, TRIPLE_ITERATOR_PEEK_DOC) .def("has_next", &TripleIterator::hasNext, TRIPLE_ITERATOR_HASNEXT_DOC) .def("size_hint", &TripleIterator::sizeHint, TRIPLE_ITERATOR_SIZE_DOC) .def("__len__", &TripleIterator::sizeHint, TRIPLE_ITERATOR_SIZE_DOC) .def("__iter__", &TripleIterator::python_iter) .def_property_readonly("subject", &TripleIterator::getSubject, TRIPLE_ITERATOR_GETSUBJECT_DOC) .def_property_readonly("predicate", &TripleIterator::getPredicate, TRIPLE_ITERATOR_GETPREDICATE_DOC) .def_property_readonly("object", &TripleIterator::getObject, TRIPLE_ITERATOR_GETOBJECT_DOC) .def_property_readonly("limit", &TripleIterator::getLimit, TRIPLE_ITERATOR_GETLIMIT_DOC) .def_property_readonly("offset", &TripleIterator::getOffset, TRIPLE_ITERATOR_GETOFFSET_DOC) .def_property_readonly("nb_reads", &TripleIterator::getNbResultsRead, TRIPLE_ITERATOR_NBREADS_DOC) .def("__repr__", &TripleIterator::python_repr); py::class_<TripleIDIterator>(m, "TripleIDIterator", TRIPLE_ID_ITERATOR_CLASS_DOC) .def("next", &TripleIDIterator::next, TRIPLE_ITERATOR_NEXT_DOC) .def("__next__", &TripleIDIterator::next, TRIPLE_ITERATOR_NEXT_DOC) .def("peek", &TripleIDIterator::peek, TRIPLE_ITERATOR_PEEK_DOC) .def("has_next", &TripleIDIterator::hasNext, TRIPLE_ITERATOR_HASNEXT_DOC) .def("size_hint", &TripleIDIterator::sizeHint, TRIPLE_ITERATOR_SIZE_DOC) .def("__len__", &TripleIDIterator::sizeHint, TRIPLE_ITERATOR_SIZE_DOC) .def("__iter__", &TripleIDIterator::python_iter) .def_property_readonly("subject", &TripleIDIterator::getSubject, TRIPLE_ITERATOR_GETSUBJECT_DOC) .def_property_readonly("predicate", &TripleIDIterator::getPredicate, TRIPLE_ITERATOR_GETPREDICATE_DOC) .def_property_readonly("object", &TripleIDIterator::getObject, TRIPLE_ITERATOR_GETOBJECT_DOC) .def_property_readonly("limit", &TripleIDIterator::getLimit, TRIPLE_ITERATOR_GETLIMIT_DOC) .def_property_readonly("offset", &TripleIDIterator::getOffset, TRIPLE_ITERATOR_GETOFFSET_DOC) .def_property_readonly("nb_reads", &TripleIDIterator::getNbResultsRead, TRIPLE_ITERATOR_NBREADS_DOC) .def("__repr__", &TripleIDIterator::python_repr); py::class_<JoinIterator>(m, "JoinIterator") .def("next", &JoinIterator::next) .def("has_next", &JoinIterator::hasNext) .def("cardinality", &JoinIterator::estimatedCardinality) .def("reset", &JoinIterator::reset) .def("__len__", &JoinIterator::estimatedCardinality) .def("__next__", &JoinIterator::next) .def("__iter__", &JoinIterator::python_iter); py::class_<HDTDocument>(m, "HDTDocument", HDT_DOCUMENT_CLASS_DOC) .def(py::init(&HDTDocument::create)) .def_property_readonly("file_path", &HDTDocument::getFilePath, HDT_DOCUMENT_GETFILEPATH_DOC) .def_property_readonly("total_triples", &HDTDocument::getNbTriples, HDT_DOCUMENT_GETNBTRIPLES_DOC) .def_property_readonly("nb_subjects", &HDTDocument::getNbSubjects, HDT_DOCUMENT_GETNBSUBJECTS_DOC) .def_property_readonly("nb_predicates", &HDTDocument::getNbPredicates, HDT_DOCUMENT_GETNBPREDICATES_DOC) .def_property_readonly("nb_objects", &HDTDocument::getNbObjects, HDT_DOCUMENT_GETNBOBJECTS_DOC) .def_property_readonly("nb_shared", &HDTDocument::getNbShared, HDT_DOCUMENT_GETNBSHARED_DOC) .def("search_triples", &HDTDocument::search, HDT_DOCUMENT_SEARCH_TRIPLES_DOC, py::arg("subject"), py::arg("predicate"), py::arg("object"), py::arg("limit") = 0, py::arg("offset") = 0) .def("search_join", &HDTDocument::searchJoin) .def("configure_hops", &HDTDocument::configureHops) .def("compute_all_hops", &HDTDocument::computeAllHopsIDs) .def("cloneHDT", &HDTDocument::cloneHDT) .def("compute_hops", &HDTDocument::computeHopsIDs) .def("filter_types", &HDTDocument::filterTypeIDs) .def("remove", &HDTDocument::remove) .def("string_to_id", &HDTDocument::StringToid) .def("id_to_string", &HDTDocument::idToString) .def("string_to_global_id", &HDTDocument::StringToGlobalId) .def("global_id_to_string", &HDTDocument::globalIdToString) .def("search_triples_ids", &HDTDocument::searchIDs, HDT_DOCUMENT_SEARCH_TRIPLES_IDS_DOC, py::arg("subject"), py::arg("predicate"), py::arg("object"), py::arg("limit") = 0, py::arg("offset") = 0) .def("tripleid_to_string", &HDTDocument::idsToString, HDT_DOCUMENT_TRIPLES_IDS_TO_STRING_DOC, py::arg("subject"), py::arg("predicate"), py::arg("object")) .def("__len__", &HDTDocument::getNbTriples, HDT_DOCUMENT_GETNBTRIPLES_DOC) .def("__repr__", &HDTDocument::python_repr); py::enum_<hdt::TripleComponentRole>(m, "TripleComponentRole", py::arithmetic()) .value("SUBJECT", hdt::TripleComponentRole::SUBJECT) .value("PREDICATE", hdt::TripleComponentRole::PREDICATE) .value("OBJECT", hdt::TripleComponentRole::OBJECT); }
53.59292
83
0.673217
[ "object" ]
1b3ea1d1d7065a4677f86413cd5e0f3f6c24d524
5,549
hxx
C++
include/seglib/cgp2d/cells/cell1.hxx
DerThorsten/seglib
4655079e390e301dd93e53f5beed6c9737d6df9f
[ "MIT" ]
null
null
null
include/seglib/cgp2d/cells/cell1.hxx
DerThorsten/seglib
4655079e390e301dd93e53f5beed6c9737d6df9f
[ "MIT" ]
null
null
null
include/seglib/cgp2d/cells/cell1.hxx
DerThorsten/seglib
4655079e390e301dd93e53f5beed6c9737d6df9f
[ "MIT" ]
null
null
null
#ifndef CGP2D_CELL_1_HXX #define CGP2D_CELL_1_HXX /* std library */ #include <set> #include <vector> #include <iostream> #include <algorithm> #include <cmath> #include <deque> #include <map> #include <stdexcept> #include <sstream> /* vigra */ #include <vigra/multi_array.hxx> #include <vigra/tinyvector.hxx> #include <vigra/multi_array.hxx> #include "seglib/cgp2d/tgrid.hxx" namespace cgp2d{ template<class COORDINATE_TYPE,class LABEL_TYPE> class Cell<COORDINATE_TYPE,LABEL_TYPE,1> : public CellBase<COORDINATE_TYPE,LABEL_TYPE,1>{ public: typedef LABEL_TYPE LabelType; typedef COORDINATE_TYPE CoordinateType; typedef TopologicalGrid<LabelType> TopologicalGridType; typedef vigra::TinyVector<CoordinateType,2> PointType; typedef vigra::TinyVector<float,2> FloatPointType; typedef LinePath2d<CoordinateType> LinePath2dType; void getAngles(){ angles_.resize(this->size()); LinePath2dType linePath(this->points_,angles_); } float getAngles(const size_t start,const size_t center,const size_t end){ //std::cout<<"s "<<start<<" c "<<center<<" e "<<end<<"\n"; FloatPointType sp = this->points_[start]; FloatPointType akkP(0.0,0.0); size_t c=0; for(size_t i=start+1;i<end;++i){ ++c; akkP+=this->points_[i]; } CGP_ASSERT_OP(c,==,(end-start-1)); akkP/=(end-start-1); akkP-=sp; const float result = std::atan2 (akkP[1],akkP[0]) * 180.0 / M_PI; return result; } void sortCells(){ size_t finishedPoints=0; std::vector<bool> finishedPoint(this->size(),false); std::deque<LabelType> sorted; PointType pFront = this->points_[0]; PointType pBack = this->points_[0]; // insert first point sorted.push_back(0); finishedPoint[0]=true; finishedPoints=1; while(finishedPoints < this->size()){ const size_t oldSize=finishedPoints; for(size_t i=0;i<this->size();++i){ if(finishedPoint[i]==false){ const PointType & point = this->points_[i]; if(adjacent2Cells(pFront,point)){ sorted.push_front(i); pFront=point; finishedPoint[i]=true; ++finishedPoints; break; } else if(adjacent2Cells(pBack,point)){ sorted.push_back(i); pBack=point; finishedPoint[i]=true; ++finishedPoints; break; } } } if(oldSize+1!=finishedPoints){ std::cout<<"\n\n\n\n size "<<this->size()<<"\n"; } CGP_ASSERT_OP(oldSize+1,==,finishedPoints); } std::vector<PointType> points; points.reserve(this->size()); while(sorted.empty()==false){ points.push_back(this->points_[sorted.front()]); sorted.pop_front(); } this->points_=points; this->getAngles(); } private: bool adjacent2Cells(const PointType & pa,const PointType & pb ){ // A|B // vertical boundary point if(pa[0]%2==1){ // six possible neighbours: // // | case 1 // --*-- case 2,3 // | <-self // --*-- case 4,5 // | case 6 // // 1 // 2 * 3 // | // 4 * 5 // 6 //case 1 (with border check) if (pa[1]!=0 && ( pa[0] ==pb[0] && pa[1]-2==pb[1] ) ){return true;} //case 2 else if(pa[1]!=0 && ( pa[0]-1==pb[0] && pa[1]-1==pb[1] ) ){return true;} //case 3 else if(pa[1]!=0 && ( pa[0]+1==pb[0] && pa[1]-1==pb[1] ) ){return true;} //case 4 else if( ( pa[0]-1==pb[0] && pa[1]+1==pb[1] ) ){return true;} //case 5 else if( ( pa[0]+1==pb[0] && pa[1]+1==pb[1] ) ){return true;} //case 6 else if( ( pa[0] ==pb[0] && pa[1]+2==pb[1] ) ){return true;} return false; } // horizontal boundary else{ // six possible neighbours: // // | | // --*--*-- // | | // // 2 4 // 1 *--* 6 // 3 5 //case 1 (with border check) if (pa[0]!=0 && ( pa[0] -2 ==pb[0] && pa[1] ==pb[1] ) ){return true;} //case 2 else if(pa[0]!=0 && ( pa[0] -1 ==pb[0] && pa[1]-1==pb[1] ) ){return true;} //case 3 else if(pa[0]!=0 && ( pa[0] -1 ==pb[0] && pa[1]+1==pb[1] ) ){return true;} //case 4 else if( ( pa[0] +1 ==pb[0] && pa[1]-1==pb[1] ) ){return true;} //case 5 else if( ( pa[0] +1 ==pb[0] && pa[1]+1==pb[1] ) ){return true;} else if( ( pa[0] +2 ==pb[0] && pa[1] ==pb[1] ) ){return true;} return false; } } public: std::vector<vigra::TinyVector<float,2> > angles_; }; } #endif // CGP2D_CELL_1_HXX
31
89
0.452874
[ "vector" ]
1b3ea20cb0f4e03bdaad44e6476cfdd0608046eb
40,515
cpp
C++
tests/unit/execution_tree/primitives/not_equal_operation.cpp
rtohid/phylanx
c2e4e8e531c204a70b1907995b1fd467870e6d9d
[ "BSL-1.0" ]
null
null
null
tests/unit/execution_tree/primitives/not_equal_operation.cpp
rtohid/phylanx
c2e4e8e531c204a70b1907995b1fd467870e6d9d
[ "BSL-1.0" ]
null
null
null
tests/unit/execution_tree/primitives/not_equal_operation.cpp
rtohid/phylanx
c2e4e8e531c204a70b1907995b1fd467870e6d9d
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <phylanx/phylanx.hpp> #include <hpx/hpx_main.hpp> #include <hpx/include/lcos.hpp> #include <hpx/util/lightweight_test.hpp> #include <cstdint> #include <iostream> #include <utility> #include <vector> void test_not_equal_operation_0d_true() { phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(41.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(1.0)); phylanx::execution_tree::primitive not_equal; not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); HPX_TEST_EQ(phylanx::ir::node_data<double>(1.0), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(true), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d_bool_true() { phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(true)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(false)); phylanx::execution_tree::primitive not_equal; not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(true), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d_false() { phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(1.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(1.0)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); HPX_TEST_EQ(phylanx::ir::node_data<double>(0.0), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(false), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d_lit_true() { phylanx::ir::node_data<double> lhs(41.0); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(1.0)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); HPX_TEST_EQ(phylanx::ir::node_data<double>(1.0), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(true), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d_lit_false() { phylanx::ir::node_data<double> lhs(1.0); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(1.0)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); HPX_TEST_EQ(phylanx::ir::node_data<double>(0.0), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(false)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d1d() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v = gen.generate(1007UL, 0, 2); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(2.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<double> expected = blaze::map(v, [](double x) { return (x != 2.0); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d1d_lit() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v = gen.generate(1007UL, 0, 2); phylanx::ir::node_data<double> lhs(2.0); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<double> expected = blaze::map(v, [](double x) { return (x != 2.0); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d1d_bool() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<std::uint8_t> v = gen.generate(1007UL, 0, 1); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(false)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(v)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<std::uint8_t> expected = blaze::map(v, [](bool x) { return (x != false); }); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d1d_bool_lit() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<std::uint8_t> v = gen.generate(1007UL, 0, 1); phylanx::ir::node_data<double> lhs(false); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<std::uint8_t> expected = blaze::map(v, [](bool x) { return (x != false); }); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d2d() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<double> m = gen.generate(101UL, 101UL, 0, 2); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(2.0)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected = blaze::map(m, [](double x) { return (x != 2.0); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d2d_lit() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<double> m = gen.generate(101UL, 101UL, 0, 2); phylanx::ir::node_data<double> lhs(2.0); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected = blaze::map(m, [](double x) { return (x != 2.0); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d2d_bool() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<std::uint8_t> m = gen.generate(101UL, 101UL, 0, 1); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(true)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(m)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<std::uint8_t> expected = blaze::map(m, [](bool x) { return (x != true); }); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_0d2d_bool_lit() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<std::uint8_t> m = gen.generate(101UL, 101UL, 0, 1); phylanx::ir::node_data<std::uint8_t> lhs(true); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(m)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<std::uint8_t> expected = blaze::map(m, [](bool x) { return (x != true); }); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_1d() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v1 = gen.generate(100UL, 0, 2); blaze::DynamicVector<double> v2 = gen.generate(100UL, 0, 2); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v1)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v2)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<double> expected = blaze::map(v1, v2, [](double x, double y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>((expected)), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_1d_lit() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v1 = gen.generate(1007UL, 0, 2); blaze::DynamicVector<double> v2 = gen.generate(1007UL, 0, 2); phylanx::ir::node_data<double> lhs(v1); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v2)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<double> expected = blaze::map(v1, v2, [](double x, double y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_1d0d() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v = gen.generate(1007UL, 0, 2); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(2.0)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<double> expected = blaze::map(v, [](double x) { return (x != 2.0); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_1d0d_lit() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v = gen.generate(1007UL, 0, 2); phylanx::ir::node_data<double> lhs(v); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(2.0)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<double> expected = blaze::map(v, [](double x) { return (x != 2.0); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_1d0d_bool() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<std::uint8_t> v = gen.generate(1007UL, 0, 1); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(v)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(false)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<std::uint8_t> expected = blaze::map(v, [](bool x) { return (x != false); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_1d0d_bool_lit() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<std::uint8_t> v = gen.generate(1007UL, 0, 1); phylanx::ir::node_data<std::uint8_t> lhs(v); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(false)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicVector<std::uint8_t> expected = blaze::map(v, [](bool x) { return (x != false); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_1d2d() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v = gen.generate(104UL, 0, 2); blaze::Rand<blaze::DynamicMatrix<int>> mat_gen{}; blaze::DynamicMatrix<double> m = mat_gen.generate(101UL, 104UL, 0, 2); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected{m.rows(), m.columns()}; for (size_t i = 0UL; i < m.rows(); i++) blaze::row(expected, i) = blaze::map(blaze::row(m, i), blaze::trans(v), [](double x, double y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_1d2d_lit() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v = gen.generate(104UL, 0, 2); blaze::Rand<blaze::DynamicMatrix<double>> mat_gen{}; blaze::DynamicMatrix<double> m = mat_gen.generate(101UL, 104UL, 0, 2); phylanx::ir::node_data<double> lhs(v); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected{m.rows(), m.columns()}; for (size_t i = 0UL; i < m.rows(); i++) blaze::row(expected, i) = blaze::map(blaze::row(m, i), blaze::trans(v), [](double x, double y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<double> m1 = gen.generate(1007UL, 1007UL, 0, 2); blaze::DynamicMatrix<double> m2 = gen.generate(1007UL, 1007UL, 0, 2); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m1)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m2)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected = blaze::map(m1, m2, [](double x, double y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d_lit() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<double> m1 = gen.generate(1007UL, 1007UL, 0, 2); blaze::DynamicMatrix<double> m2 = gen.generate(1007UL, 1007UL, 0, 2); phylanx::ir::node_data<double> lhs(m1); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m2)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected = blaze::map(m1, m2, [](double x, double y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d_bool() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<std::uint8_t> m1 = gen.generate(1007UL, 1007UL, 0, 1); blaze::DynamicMatrix<std::uint8_t> m2 = gen.generate(1007UL, 1007UL, 0, 1); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(m1)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(m2)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<std::uint8_t> expected = blaze::map(m1, m2, [](bool x, bool y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d_bool_lit() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<std::uint8_t> m1 = gen.generate(1007UL, 1007UL, 0, 1); blaze::DynamicMatrix<std::uint8_t> m2 = gen.generate(1007UL, 1007UL, 0, 1); phylanx::ir::node_data<std::uint8_t> lhs(m1); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(m2)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<std::uint8_t> expected = blaze::map(m1, m2, [](bool x, bool y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d0d() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<double> m = gen.generate(101UL, 101UL, 0, 2); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(2.0)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected = blaze::map(m, [](double x) { return (x != 2.0); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d0d_lit() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<double> m = gen.generate(101UL, 101UL, 0, 2); phylanx::ir::node_data<double> lhs(m); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(2.0)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected = blaze::map(m, [](double x) { return (x != 2.0); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d0d_bool() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<std::uint8_t> m = gen.generate(101UL, 101UL, 0, 1); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(m)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(true)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<std::uint8_t> expected = blaze::map(m, [](bool x) { return (x != true); }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d0d_bool_lit() { blaze::Rand<blaze::DynamicMatrix<int>> gen{}; blaze::DynamicMatrix<std::uint8_t> m = gen.generate(101UL, 101UL, 0, 1); phylanx::ir::node_data<std::uint8_t> lhs(m); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(true)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<std::uint8_t> expected = blaze::map(m, [](bool x) { return (x != true); }); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d1d() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v = gen.generate(104UL, 0, 2); blaze::Rand<blaze::DynamicMatrix<double>> mat_gen{}; blaze::DynamicMatrix<double> m = mat_gen.generate(101UL, 104UL, 0, 2); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(m)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected{m.rows(), m.columns()}; for (size_t i = 0UL; i < m.rows(); i++) blaze::row(expected, i) = blaze::map(blaze::row(m, i), blaze::trans(v), [](double x, double y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d1d_lit() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<double> v = gen.generate(104UL, 0, 2); blaze::Rand<blaze::DynamicMatrix<double>> mat_gen{}; blaze::DynamicMatrix<double> m = mat_gen.generate(101UL, 104UL, 0, 2); phylanx::ir::node_data<double> lhs(m); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<double>(v)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<double> expected{m.rows(), m.columns()}; for (size_t i = 0UL; i < m.rows(); i++) blaze::row(expected, i) = blaze::map(blaze::row(m, i), blaze::trans(v), [](double x, double y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<double>(expected), phylanx::execution_tree::extract_numeric_value(f)); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d1d_bool() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<std::uint8_t> v = gen.generate(104UL, 0, 1); blaze::Rand<blaze::DynamicMatrix<int>> mat_gen{}; blaze::DynamicMatrix<std::uint8_t> m = mat_gen.generate(101UL, 104UL, 0, 1); phylanx::execution_tree::primitive lhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(m)); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(v)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<std::uint8_t> expected{m.rows(), m.columns()}; for (size_t i = 0UL; i < m.rows(); i++) blaze::row(expected, i) = blaze::map(blaze::row(m, i), blaze::trans(v), [](bool x, bool y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } void test_not_equal_operation_2d1d_bool_lit() { blaze::Rand<blaze::DynamicVector<int>> gen{}; blaze::DynamicVector<std::uint8_t> v = gen.generate(104UL, 0, 1); blaze::Rand<blaze::DynamicMatrix<int>> mat_gen{}; blaze::DynamicMatrix<std::uint8_t> m = mat_gen.generate(101UL, 104UL, 0, 1); phylanx::ir::node_data<std::uint8_t> lhs(m); phylanx::execution_tree::primitive rhs = phylanx::execution_tree::primitives::create_variable( hpx::find_here(), phylanx::ir::node_data<std::uint8_t>(v)); phylanx::execution_tree::primitive not_equal = phylanx::execution_tree::primitives::create_not_equal( hpx::find_here(), std::vector<phylanx::execution_tree::primitive_argument_type>{ std::move(lhs), std::move(rhs)}); phylanx::execution_tree::primitive_argument_type f = not_equal.eval().get(); blaze::DynamicMatrix<std::uint8_t> expected{m.rows(), m.columns()}; for (size_t i = 0UL; i < m.rows(); i++) blaze::row(expected, i) = blaze::map(blaze::row(m, i), blaze::trans(v), [](bool x, bool y) { return x != y; }); HPX_TEST_EQ(phylanx::ir::node_data<std::uint8_t>(std::move(expected)), phylanx::execution_tree::extract_boolean_data(f)); } int main(int argc, char* argv[]) { test_not_equal_operation_0d_false(); test_not_equal_operation_0d_bool_true(); test_not_equal_operation_0d_true(); test_not_equal_operation_0d_lit_false(); test_not_equal_operation_0d_lit_true(); test_not_equal_operation_0d1d(); test_not_equal_operation_0d1d_lit(); test_not_equal_operation_0d1d_bool(); test_not_equal_operation_0d1d_bool_lit(); test_not_equal_operation_0d2d(); test_not_equal_operation_0d2d_lit(); test_not_equal_operation_0d2d_bool(); test_not_equal_operation_0d2d_bool_lit(); test_not_equal_operation_1d(); test_not_equal_operation_1d_lit(); test_not_equal_operation_1d0d(); test_not_equal_operation_1d0d_lit(); test_not_equal_operation_1d0d_bool(); test_not_equal_operation_1d0d_bool_lit(); test_not_equal_operation_1d2d(); test_not_equal_operation_1d2d_lit(); test_not_equal_operation_2d(); test_not_equal_operation_2d_lit(); test_not_equal_operation_2d_bool(); test_not_equal_operation_2d_bool_lit(); test_not_equal_operation_2d0d(); test_not_equal_operation_2d0d_lit(); test_not_equal_operation_2d0d_bool(); test_not_equal_operation_2d0d_bool_lit(); test_not_equal_operation_2d1d(); test_not_equal_operation_2d1d_lit(); test_not_equal_operation_2d1d_bool(); test_not_equal_operation_2d1d_bool_lit(); return hpx::util::report_errors(); }
39.995064
81
0.672566
[ "vector" ]
1b45a056343b3d569b2c8ecd950e29221140750c
1,234
cpp
C++
HackerRank/SpecialNumbers.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
HackerRank/SpecialNumbers.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
HackerRank/SpecialNumbers.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned uint; const int MAXN = 100005; int N; int cnt[MAXN], d[MAXN]; bool p[MAXN]; vector<int> primes; void build(void) { memset(p, true, sizeof(p)); for (int i = 2; i < MAXN; i++) { if (p[i]) { for (int j = i * i; j > 0 && j < MAXN; j += i) { p[j] = false; } primes.push_back(i); } } } int func(int x) { int ans = 1; if (x == 1) return ans; for (int i = 0; i < (int) primes.size(); i++) { if (x <= 1) { break; } if (x % primes[i] == 0) { int p = 0; while (x % primes[i] == 0) { p += 1; x /= primes[i]; } ans *= (p + 1); } } return ans + 1; } int main(void) { build(); cin >> N; int ans = 0; for (int i = 1; i <= N; i++) { d[i] = func(i); if (cnt[d[i]] == 0) { ans += i; } cnt[d[i]] += 1; } cout << ans << endl; return 0; }
16.453333
67
0.484603
[ "vector" ]
1b48ef93c61b0b2e6c9aceead68e3b3170a34d7c
4,352
hpp
C++
mpl_test_node/src/example-utils.hpp
uzh-rpg/rpg_mpl_ros
9567bafc43929a8cd2929be060c2a75dcb6dfc25
[ "Apache-2.0" ]
2
2022-02-09T20:21:24.000Z
2022-03-19T07:39:19.000Z
mpl_test_node/src/example-utils.hpp
uzh-rpg/rpg_mpl_ros
9567bafc43929a8cd2929be060c2a75dcb6dfc25
[ "Apache-2.0" ]
1
2021-11-10T13:08:47.000Z
2022-02-28T03:17:07.000Z
mpl_test_node/src/example-utils.hpp
uzh-rpg/rpg_mpl_ros
9567bafc43929a8cd2929be060c2a75dcb6dfc25
[ "Apache-2.0" ]
null
null
null
// This software is in the public domain. Where that dedication is not // recognized, you are granted a perpetual, irrevocable license to copy, // distribute, and modify this file as you see fit. // https://github.com/ddiakopoulos/tinyply // This file is only required for the example and test programs. #pragma once #ifndef tinyply_example_utils_hpp #define tinyply_example_utils_hpp #include <thread> #include <chrono> #include <vector> #include <sstream> #include <fstream> #include <iostream> #include <cstring> #include <iterator> inline std::vector<uint8_t> read_file_binary(const std::string & pathToFile) { std::ifstream file(pathToFile, std::ios::binary); std::vector<uint8_t> fileBufferBytes; if (file.is_open()) { file.seekg(0, std::ios::end); size_t sizeBytes = file.tellg(); file.seekg(0, std::ios::beg); fileBufferBytes.resize(sizeBytes); if (file.read((char*)fileBufferBytes.data(), sizeBytes)) return fileBufferBytes; } else throw std::runtime_error("could not open binary ifstream to path " + pathToFile); return fileBufferBytes; } struct memory_buffer : public std::streambuf { char * p_start {nullptr}; char * p_end {nullptr}; size_t size; memory_buffer(char const * first_elem, size_t size) : p_start(const_cast<char*>(first_elem)), p_end(p_start + size), size(size) { setg(p_start, p_start, p_end); } pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override { if (dir == std::ios_base::cur) gbump(static_cast<int>(off)); else setg(p_start, (dir == std::ios_base::beg ? p_start : p_end) + off, p_end); return gptr() - p_start; } pos_type seekpos(pos_type pos, std::ios_base::openmode which) override { return seekoff(pos, std::ios_base::beg, which); } }; struct memory_stream : virtual memory_buffer, public std::istream { memory_stream(char const * first_elem, size_t size) : memory_buffer(first_elem, size), std::istream(static_cast<std::streambuf*>(this)) {} }; class manual_timer { std::chrono::high_resolution_clock::time_point t0; double timestamp{ 0.0 }; public: void start() { t0 = std::chrono::high_resolution_clock::now(); } void stop() { timestamp = std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - t0).count() * 1000.0; } const double & get() { return timestamp; } }; struct float2 { float x, y; }; struct float3 { float x, y, z; }; struct double3 { double x, y, z; }; struct uint3 { uint32_t x, y, z; }; struct uint4 { uint32_t x, y, z, w; }; struct geometry { std::vector<float3> vertices; std::vector<float3> normals; std::vector<float2> texcoords; std::vector<uint3> triangles; }; inline geometry make_cube_geometry() { geometry cube; const struct CubeVertex { float3 position, normal; float2 texCoord; } verts[] = { { { -1, -1, -1 },{ -1, 0, 0 },{ 0, 0 } },{ { -1, -1, +1 },{ -1, 0, 0 },{ 1, 0 } },{ { -1, +1, +1 },{ -1, 0, 0 },{ 1, 1 } },{ { -1, +1, -1 },{ -1, 0, 0 },{ 0, 1 } }, { { +1, -1, +1 },{ +1, 0, 0 },{ 0, 0 } },{ { +1, -1, -1 },{ +1, 0, 0 },{ 1, 0 } },{ { +1, +1, -1 },{ +1, 0, 0 },{ 1, 1 } },{ { +1, +1, +1 },{ +1, 0, 0 },{ 0, 1 } }, { { -1, -1, -1 },{ 0, -1, 0 },{ 0, 0 } },{ { +1, -1, -1 },{ 0, -1, 0 },{ 1, 0 } },{ { +1, -1, +1 },{ 0, -1, 0 },{ 1, 1 } },{ { -1, -1, +1 },{ 0, -1, 0 },{ 0, 1 } }, { { +1, +1, -1 },{ 0, +1, 0 },{ 0, 0 } },{ { -1, +1, -1 },{ 0, +1, 0 },{ 1, 0 } },{ { -1, +1, +1 },{ 0, +1, 0 },{ 1, 1 } },{ { +1, +1, +1 },{ 0, +1, 0 },{ 0, 1 } }, { { -1, -1, -1 },{ 0, 0, -1 },{ 0, 0 } },{ { -1, +1, -1 },{ 0, 0, -1 },{ 1, 0 } },{ { +1, +1, -1 },{ 0, 0, -1 },{ 1, 1 } },{ { +1, -1, -1 },{ 0, 0, -1 },{ 0, 1 } }, { { -1, +1, +1 },{ 0, 0, +1 },{ 0, 0 } },{ { -1, -1, +1 },{ 0, 0, +1 },{ 1, 0 } },{ { +1, -1, +1 },{ 0, 0, +1 },{ 1, 1 } },{ { +1, +1, +1 },{ 0, 0, +1 },{ 0, 1 } }}; std::vector<uint4> quads = { { 0, 1, 2, 3 },{ 4, 5, 6, 7 },{ 8, 9, 10, 11 },{ 12, 13, 14, 15 },{ 16, 17, 18, 19 },{ 20, 21, 22, 23 } }; for (auto & q : quads) { cube.triangles.push_back({ q.x,q.y,q.z }); cube.triangles.push_back({ q.x,q.z,q.w }); } for (int i = 0; i < 24; ++i) { cube.vertices.push_back(verts[i].position); cube.normals.push_back(verts[i].normal); cube.texcoords.push_back(verts[i].texCoord); } return cube; } #endif
35.096774
171
0.56296
[ "geometry", "vector" ]
1b49549aa32cdc1c5c1e3881dae74974e25209e6
7,420
cpp
C++
TE-1/PL-2/ethereal/libcrafter-master/libcrafter/crafter/Utils/ARPSpoofingRequest.cpp
Adityajn/College-Codes
f40e1eee53b951f2101981230fc72201081fd5f7
[ "Unlicense" ]
1
2017-02-22T18:22:39.000Z
2017-02-22T18:22:39.000Z
TE-1/PL-2/ethereal/libcrafter-master/libcrafter/crafter/Utils/ARPSpoofingRequest.cpp
Adityajn/College-Codes
f40e1eee53b951f2101981230fc72201081fd5f7
[ "Unlicense" ]
null
null
null
TE-1/PL-2/ethereal/libcrafter-master/libcrafter/crafter/Utils/ARPSpoofingRequest.cpp
Adityajn/College-Codes
f40e1eee53b951f2101981230fc72201081fd5f7
[ "Unlicense" ]
null
null
null
/* Copyright (c) 2012, Esteban Pellegrino All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> 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 ESTEBAN PELLEGRINO 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 <map> #include <signal.h> #include "ARPSpoofing.h" #include "ARPPing.h" using namespace std; using namespace Crafter; void* Crafter::ARPSpoofRequest(void* thread_arg) { /* Get the ARP context */ ARPContext* context = static_cast<ARPContext* >(thread_arg); /* Create generic headers */ Ethernet ether_header; ether_header.SetSourceMAC(context->AttackerMAC); ARP arp_header; arp_header.SetOperation(ARP::Request); arp_header.SetSenderMAC(context->AttackerMAC); /* Get size of both containers */ size_t victim_size = context->VictimIPs->size(); size_t target_size = context->TargetIPs->size(); /* Poison target table */ for(size_t i = 0 ; i < victim_size ; i++) { /* Set the sender IP address */ arp_header.SetSenderIP( (*(context->VictimIPs))[i] ); for(size_t j = 0 ; j < target_size ; j++) { ether_header.SetDestinationMAC( (*(context->TargetMACs))[j] ); arp_header.SetTargetIP( (*context->TargetIPs)[j] ); /* Now, craft the packet */ Packet* arp_packet = new Packet; arp_packet->PushLayer(ether_header); arp_packet->PushLayer(arp_header); context->arp_packets->push_back(arp_packet); } } /* Poison victim table */ for(size_t i = 0 ; i < target_size ; i++) { /* Set the sender IP address */ arp_header.SetSenderIP( (*context->TargetIPs)[i] ); for(size_t j = 0 ; j < victim_size ; j++) { ether_header.SetDestinationMAC( (*context->VictimMACs)[j] ); arp_header.SetTargetIP( (*context->VictimIPs)[j] ); /* Now, craft the packet */ Packet* arp_packet = new Packet; arp_packet->PushLayer(ether_header); arp_packet->PushLayer(arp_header); context->arp_packets->push_back(arp_packet); } } while(context->keep_going) { Send(context->arp_packets,context->iface,16); sleep(5); } /* Call pthread exit with a pointer to the new object */ pthread_exit(NULL); } void Crafter::ARPNormalRequest(void* thread_arg) { /* Get the ARP context */ ARPContext* context = static_cast<ARPContext* >(thread_arg); /* Create generic headers */ Ethernet ether_header; ARP arp_header; arp_header.SetOperation(ARP::Request); /* Get size of both containers */ size_t victim_size = context->VictimIPs->size(); size_t target_size = context->TargetIPs->size(); /* Poison target table */ for(size_t i = 0 ; i < victim_size ; i++) { /* Set the sender IP address */ ether_header.SetSourceMAC( (*context->VictimMACs)[i] ); arp_header.SetSenderIP( (*context->VictimIPs)[i] ); arp_header.SetSenderMAC( (*context->VictimMACs)[i] ); for(size_t j = 0 ; j < target_size ; j++) { ether_header.SetDestinationMAC( (*context->TargetMACs)[j] ); arp_header.SetTargetIP( (*context->TargetIPs)[j] ); /* Now, craft the packet */ Packet* arp_packet = new Packet; arp_packet->PushLayer(ether_header); arp_packet->PushLayer(arp_header); context->arp_packets->push_back(arp_packet); } } /* Poison victim table */ for(size_t i = 0 ; i < target_size ; i++) { /* Set the target IP address */ ether_header.SetSourceMAC( (*context->TargetMACs)[i] ); arp_header.SetSenderIP( (*context->TargetIPs)[i] ); arp_header.SetSenderMAC( (*context->TargetMACs)[i] ); for(size_t j = 0 ; j < victim_size ; j++) { ether_header.SetDestinationMAC( (*context->VictimMACs)[j] ); arp_header.SetTargetIP( (*context->VictimIPs)[j] ); /* Now, craft the packet */ Packet* arp_packet = new Packet; arp_packet->PushLayer(ether_header); arp_packet->PushLayer(arp_header); context->arp_packets->push_back(arp_packet); } } for(int i = 0 ; i < 3 ; i++) { Send(context->arp_packets,context->iface,16); sleep(2); } } ARPContext* Crafter::ARPSpoofingRequest(const std::string& net_target, const std::string& net_victim, const string& iface) { /* Print header */ cout << "[@] --- ARP Spoofer " << endl; /* Get attackers MAC addres */ string MyMAC = GetMyMAC(iface); /* Print local MAC addres */ cout << "[@] Attacker's MAC address = " << MyMAC << endl; /* ***************************** ARP ping -> Target net: */ map<string,string> TargetTable = ARPPingSendRcv(net_target,iface,3); /* Create container for MAC an IP addresses */ vector<string>* TargetIPs = new vector<string>; vector<string>* TargetMACs = new vector<string>; /* Iterate the IP/MAC table return by the ARPPing function */ map<string,string>::iterator it_table; for(it_table = TargetTable.begin() ; it_table != TargetTable.end() ; it_table++) { TargetIPs->push_back((*it_table).first); TargetMACs->push_back((*it_table).second); } /* ***************************** ARP ping -> Victim net: */ map<string,string> VictimTable = ARPPingSendRcv(net_victim,iface,3); /* Create container for MAC an IP addresses */ vector<string>* VictimIPs = new vector<string>; vector<string>* VictimMACs = new vector<string>; for(it_table = VictimTable.begin() ; it_table != VictimTable.end() ; it_table++) { VictimIPs->push_back((*it_table).first); VictimMACs->push_back((*it_table).second); } /* Create instance of ARP Spoofing Context */ ARPContext* context = new ARPContext; /* Set the type of spoofing */ context->type = ARPContext::Request; context->AttackerMAC = MyMAC; context->iface = iface; context->TargetIPs = TargetIPs; context->TargetMACs = TargetMACs; context->VictimIPs = VictimIPs; context->VictimMACs = VictimMACs; void* thread_arg = static_cast<void *>(context); /* Create thread */ pthread_t tid; /* Create a new packet container and put it into the context */ PacketContainer* arp_request = new PacketContainer; context->arp_packets = arp_request; context->SanityCheck(); context->keep_going = true; int rc = pthread_create(&tid, NULL, ARPSpoofRequest, thread_arg); if (rc) throw std::runtime_error("ARPSpoofingRequest : Creating thread. Returning code = " + StrPort(rc)); /* Put thread ID into the context */ context->tid = tid; return context; }
30.916667
124
0.705526
[ "object", "vector" ]
1b4a9e60800b78d60682d0931f5697ac01fbd207
3,766
cpp
C++
src/main/cpp/states/ballrelease/BallReleaseStateMgr.cpp
witcpalek/BetaTest2022
4f6601cdd9a14cec0c8c2b3b08ede209ace37e47
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/main/cpp/states/ballrelease/BallReleaseStateMgr.cpp
witcpalek/BetaTest2022
4f6601cdd9a14cec0c8c2b3b08ede209ace37e47
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/main/cpp/states/ballrelease/BallReleaseStateMgr.cpp
witcpalek/BetaTest2022
4f6601cdd9a14cec0c8c2b3b08ede209ace37e47
[ "BSD-3-Clause", "MIT" ]
null
null
null
//==================================================================================================================================================== // Copyright 2022 Lake Orion Robotics FIRST Team 302 // // 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. //==================================================================================================================================================== // C++ Includes #include <map> #include <memory> #include <vector> // FRC includes #include <networktables/NetworkTableInstance.h> #include <networktables/NetworkTable.h> #include <networktables/NetworkTableEntry.h> // Team 302 includes #include <states/IState.h> #include <states/ballrelease/BallReleaseStateMgr.h> #include <xmlmechdata/StateDataDefn.h> #include <controllers/MechanismTargetData.h> #include <utils/Logger.h> #include <gamepad/TeleopControl.h> #include <states/BallRelease/BallReleaseState.h> #include <subsys/MechanismFactory.h> #include <subsys/MechanismTypes.h> #include <states/StateMgr.h> #include <states/StateStruc.h> // Third Party Includes using namespace std; BallReleaseStateMgr* BallReleaseStateMgr::m_instance = nullptr; BallReleaseStateMgr* BallReleaseStateMgr::GetInstance() { if ( BallReleaseStateMgr::m_instance == nullptr ) { BallReleaseStateMgr::m_instance = new BallReleaseStateMgr(); } return BallReleaseStateMgr::m_instance; } /// @brief initialize the state manager, parse the configuration file and create the states. BallReleaseStateMgr::BallReleaseStateMgr() { map<string, StateStruc> stateMap; stateMap["BALLRELEASEHOLD"] = m_holdState; stateMap["BALLRELEASEOPEN"] = m_releaseState; Init(MechanismFactory::GetMechanismFactory()->GetBallRelease(), stateMap); } /// @brief run the current state /// @return void void BallReleaseStateMgr::CheckForStateTransition() { if ( MechanismFactory::GetMechanismFactory()->GetBallRelease() != nullptr ) { // process teleop/manual interrupts auto currentState = static_cast<BALL_RELEASE_STATE>(GetCurrentState()); auto controller = TeleopControl::GetInstance(); if ( controller != nullptr ) { auto releasePressed = controller->IsButtonPressed(TeleopControl::FUNCTION_IDENTIFIER::RELEASE); if (releasePressed && currentState != BALL_RELEASE_STATE::RELEASE ) { SetCurrentState( BALL_RELEASE_STATE::RELEASE, false ); } else if (!releasePressed && currentState != BALL_RELEASE_STATE::HOLD) { SetCurrentState(BALL_RELEASE_STATE::HOLD, false); } } } }
39.642105
152
0.655603
[ "vector" ]
1b4bc5b33f6012cafb6032dce0f06b9e5f498c40
629
cpp
C++
Dataset/Leetcode/train/102/823.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/102/823.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/102/823.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> XXX(TreeNode* root) { vector<vector<int>> ans; if(root==NULL) return ans; queue<TreeNode*> qnt; qnt.push(root); while(!qnt.empty()){ int count = qnt.size(); vector<int> tmp; while(count-->0){ root = qnt.front(); qnt.pop(); tmp.push_back(root->val); if(root->left) qnt.push(root->left); if(root->right) qnt.push(root->right); } ans.push_back(tmp); } return ans; } };
25.16
55
0.440382
[ "vector" ]
1b4c76e2e37f24793ed81fd9651c28bdd9e9bb64
887
hpp
C++
Typon/src/tools.hpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
65
2019-03-06T15:47:27.000Z
2022-03-05T09:14:29.000Z
Typon/src/tools.hpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
null
null
null
Typon/src/tools.hpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
5
2019-04-11T01:15:04.000Z
2021-11-21T18:57:47.000Z
#ifndef tools_hpp #define tools_hpp #include <ncurses.h> #include <cassert> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; bool isShifted(const int& key); string d_to_string(const double& d, const int& decimal); double s_to_double(const string& s); void reformat_spacedTokens(vector<string>& items, const vector<int>& width, ios_base& (*flag)(ios_base&)); void Exit(int n, const string& msg = ""); class Conversion_error : public exception { private: const string situation; public: Conversion_error(const string& s) : situation(s) {} const char* what() const throw() override { string msg = "String to Numeric type conversion failed when "; msg += situation; return msg.c_str(); } }; #endif /* tools_hpp */
21.634146
70
0.648253
[ "vector" ]
1b4d1e2d73de7d5e0369cbe610c22e57563b1f80
13,055
cpp
C++
vkconfig/dialog_applications.cpp
val-verde/lunarg-vulkan-tools
25a5b6544449281e90e39a6368730f809eef747a
[ "Apache-2.0" ]
null
null
null
vkconfig/dialog_applications.cpp
val-verde/lunarg-vulkan-tools
25a5b6544449281e90e39a6368730f809eef747a
[ "Apache-2.0" ]
null
null
null
vkconfig/dialog_applications.cpp
val-verde/lunarg-vulkan-tools
25a5b6544449281e90e39a6368730f809eef747a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-2021 Valve Corporation * Copyright (c) 2020-2021 LunarG, 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. * * Authors: * - Richard S. Wright Jr. <richard@lunarg.com> * - Christophe Riccio <christophe@lunarg.com> */ #include "dialog_applications.h" #include "configurator.h" #include "../vkconfig_core/alert.h" #include <QFileDialog> #include <QTextStream> #include <QCloseEvent> #include <QCheckBox> #include <cassert> ApplicationsDialog::ApplicationsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::dialog_applications()), _last_selected_application_index(-1) { ui->setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); Configurator &configurator = Configurator::Get(); // The header is hidden by default and stays hidden when no checkboxes are used. if (!configurator.environment.UseApplicationListOverrideMode()) setWindowTitle("Vulkan Applications Launcher Shortcuts"); else { ui->treeWidget->setHeaderHidden(false); ui->treeWidget->setHeaderLabel("Check to override Vulkan layers"); } // Show the current list const std::vector<Application> &applications = configurator.environment.GetApplications(); for (std::size_t i = 0, n = applications.size(); i < n; ++i) { CreateApplicationItem(applications[i]); } ui->treeWidget->installEventFilter(this); connect(ui->treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(selectedPathChanged(QTreeWidgetItem *, QTreeWidgetItem *))); connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(itemChanged(QTreeWidgetItem *, int))); connect(ui->lineEditAppName, SIGNAL(textEdited(const QString &)), this, SLOT(editAppName(const QString &))); connect(ui->lineEditExecutable, SIGNAL(textEdited(const QString &)), this, SLOT(editExecutable(const QString &))); connect(ui->lineEditCmdArgs, SIGNAL(textEdited(const QString &)), this, SLOT(editCommandLine(const QString &))); connect(ui->lineEditWorkingFolder, SIGNAL(textEdited(const QString &)), this, SLOT(editWorkingFolder(const QString &))); connect(ui->lineEditLogFile, SIGNAL(textEdited(const QString &)), this, SLOT(editLogFile(const QString &))); // If there is an item in the tree (nullptr is okay here), make it the currently selected item. // This is a work around for macOS, where the currentItemChanged() signal is being emitted (by something) // after this constructor, without actually selecting the first row. The effect there is, the remove button is // enabled, and the first item is selected, but not visibly so. Repainting does not fix the issue either. This // is a macOS only fix, but is put in for all platforms so that the GUI behavior is consistent across all // platforms. QTreeWidgetItem *item = ui->treeWidget->topLevelItem(0); ui->treeWidget->setCurrentItem(item); } bool ApplicationsDialog::eventFilter(QObject *target, QEvent *event) { // Launch tree does some fancy resizing and since it's down in // layouts and splitters, we can't just rely on the resize method // of this window. if (target == ui->treeWidget) { if (event->type() == QEvent::Resize) { ui->treeWidget->resizeColumnToContents(1); int nLastColumnWidth = ui->treeWidget->columnWidth(1); QRect rect = ui->treeWidget->geometry(); ui->treeWidget->setColumnWidth(0, rect.width() - nLastColumnWidth); } } return false; } /// Make sure any changes are saved void ApplicationsDialog::closeEvent(QCloseEvent *event) { Environment &environment = Configurator::Get().environment; event->accept(); // When we don't use overridden list only, no need to alert the user about empty list cases. if (!environment.UseApplicationListOverrideMode()) return; if (environment.GetApplications().empty() || !environment.HasOverriddenApplications()) { environment.SetMode(OVERRIDE_MODE_LIST, false); Alert::ApplicationListEmpty(); } } /// Browse for and select an executable file to add to the list. void ApplicationsDialog::on_pushButtonAdd_clicked() // Pick the test application { Configurator &configurator = Configurator::Get(); const std::string suggested_path(configurator.path.GetPath(PATH_EXECUTABLE).c_str()); std::string executable_full_path = configurator.path.SelectPath(this, PATH_EXECUTABLE, suggested_path).c_str(); // If they have selected something! if (!executable_full_path.empty()) { // On macOS, they may have selected a binary, or they may have selected an app bundle. // If the later, we need to drill down to the actuall applicaiton if (executable_full_path.find(".app") != std::string::npos) { // Start by drilling down ExactExecutableFromAppBundle(executable_full_path); } std::string app_name; if (executable_full_path.find(GetNativeSeparator()) != std::string::npos) { app_name = executable_full_path.substr(executable_full_path.rfind(GetNativeSeparator()) + 1); } else { app_name = executable_full_path; } Application new_application(app_name, executable_full_path, ""); configurator.environment.AppendApplication(new_application); QTreeWidgetItem *item = CreateApplicationItem(new_application); configurator.configurations.RefreshConfiguration(configurator.layers.available_layers); ui->treeWidget->setCurrentItem(item); configurator.environment.SelectActiveApplication(ui->treeWidget->indexOfTopLevelItem(item)); } } QTreeWidgetItem *ApplicationsDialog::CreateApplicationItem(const Application &application) const { Configurator &configurator = Configurator::Get(); QTreeWidgetItem *item = new QTreeWidgetItem(); ui->treeWidget->addTopLevelItem(item); if (configurator.environment.UseApplicationListOverrideMode()) { QCheckBox *check_box = new QCheckBox(application.app_name.c_str()); check_box->setChecked(application.override_layers); ui->treeWidget->setItemWidget(item, 0, check_box); connect(check_box, SIGNAL(clicked(bool)), this, SLOT(itemClicked(bool))); } else { item->setText(0, application.app_name.c_str()); } return item; } /// Easy enough, just remove the selected program from the list void ApplicationsDialog::on_pushButtonRemove_clicked() { QTreeWidgetItem *current = ui->treeWidget->currentItem(); int selection = ui->treeWidget->indexOfTopLevelItem(current); assert(selection >= 0 && selection < ui->treeWidget->topLevelItemCount()); Configurator &configurator = Configurator::Get(); ui->treeWidget->takeTopLevelItem(selection); ui->treeWidget->setCurrentItem(nullptr); configurator.environment.RemoveApplication(selection); ui->groupLaunchInfo->setEnabled(false); ui->pushButtonRemove->setEnabled(false); ui->pushButtonSelect->setEnabled(false); ui->lineEditAppName->setText(""); ui->lineEditExecutable->setText(""); ui->lineEditCmdArgs->setText(""); ui->lineEditWorkingFolder->setText(""); ui->lineEditLogFile->setText(""); configurator.configurations.RefreshConfiguration(configurator.layers.available_layers); ui->treeWidget->update(); } // Dismiss the dialog, and preserve app information so it can be set to // the launcher. void ApplicationsDialog::on_pushButtonSelect_clicked() { Configurator &configurator = Configurator::Get(); QTreeWidgetItem *item = ui->treeWidget->currentItem(); if (item != nullptr) { configurator.environment.SelectActiveApplication(ui->treeWidget->indexOfTopLevelItem(item)); } close(); } /// The remove button is disabled until/unless something is selected that can /// be removed. Also the working folder and command line arguments are updated void ApplicationsDialog::selectedPathChanged(QTreeWidgetItem *current_item, QTreeWidgetItem *previous_item) { (void)previous_item; int application_index = ui->treeWidget->indexOfTopLevelItem(current_item); ui->groupLaunchInfo->setEnabled(application_index >= 0); ui->pushButtonRemove->setEnabled(application_index >= 0); ui->pushButtonSelect->setEnabled(application_index >= 0); if (application_index < 0) { ui->lineEditAppName->setText(""); ui->lineEditExecutable->setText(""); ui->lineEditCmdArgs->setText(""); ui->lineEditWorkingFolder->setText(""); ui->lineEditLogFile->setText(""); return; } const Application &application = Configurator::Get().environment.GetApplication(application_index); ui->lineEditAppName->setText(application.app_name.c_str()); ui->lineEditExecutable->setText(application.executable_path.c_str()); ui->lineEditWorkingFolder->setText(application.working_folder.c_str()); ui->lineEditCmdArgs->setText(application.arguments.c_str()); ui->lineEditLogFile->setText(ReplaceBuiltInVariable(application.log_file.c_str()).c_str()); } void ApplicationsDialog::itemChanged(QTreeWidgetItem *item, int column) { _last_selected_application_index = ui->treeWidget->indexOfTopLevelItem(item); QCheckBox *check_box = dynamic_cast<QCheckBox *>(ui->treeWidget->itemWidget(item, column)); if (check_box != nullptr) { Configurator::Get().environment.GetApplication(_last_selected_application_index).override_layers = check_box->isChecked(); } } /// Something was clicked. We don't know what, and short of setting up a new /// signal/slot for each button, this seemed a reasonable approach. Just poll /// all of them. There aren't that many, so KISS (keep it simple stupid) /// If one of them had their state flipped, that's the one that was checked, make /// it the currently selected one. void ApplicationsDialog::itemClicked(bool clicked) { (void)clicked; Environment &environment = Configurator::Get().environment; const bool need_checkbox = environment.UseApplicationListOverrideMode(); if (!need_checkbox) return; // Loop through the whole list and reset the checkboxes for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i); QCheckBox *check_box = dynamic_cast<QCheckBox *>(ui->treeWidget->itemWidget(item, 0)); assert(check_box != nullptr); environment.GetApplication(i).override_layers = check_box->isChecked(); } } void ApplicationsDialog::editAppName(const QString &name) { QTreeWidgetItem *current = ui->treeWidget->currentItem(); _last_selected_application_index = ui->treeWidget->indexOfTopLevelItem(current); if (_last_selected_application_index < 0) return; Configurator::Get().environment.GetApplication(_last_selected_application_index).app_name = name.toStdString(); } void ApplicationsDialog::editExecutable(const QString &executable) { QTreeWidgetItem *current = ui->treeWidget->currentItem(); _last_selected_application_index = ui->treeWidget->indexOfTopLevelItem(current); if (_last_selected_application_index < 0) return; Configurator::Get().environment.GetApplication(_last_selected_application_index).executable_path = executable.toStdString(); } void ApplicationsDialog::editCommandLine(const QString &cmdLine) { QTreeWidgetItem *current = ui->treeWidget->currentItem(); _last_selected_application_index = ui->treeWidget->indexOfTopLevelItem(current); if (_last_selected_application_index < 0) return; Configurator::Get().environment.GetApplication(_last_selected_application_index).arguments = cmdLine.toStdString(); } void ApplicationsDialog::editWorkingFolder(const QString &workingFolder) { QTreeWidgetItem *current = ui->treeWidget->currentItem(); _last_selected_application_index = ui->treeWidget->indexOfTopLevelItem(current); if (_last_selected_application_index < 0) return; Configurator::Get().environment.GetApplication(_last_selected_application_index).working_folder = workingFolder.toStdString(); } void ApplicationsDialog::editLogFile(const QString &logFile) { QTreeWidgetItem *current = ui->treeWidget->currentItem(); _last_selected_application_index = ui->treeWidget->indexOfTopLevelItem(current); if (_last_selected_application_index < 0) return; Configurator::Get().environment.GetApplication(_last_selected_application_index).log_file = logFile.toStdString(); }
44.556314
130
0.729529
[ "geometry", "vector" ]
1b4d57efe32f77c138d30c239642952f5d5c9e85
22,100
cpp
C++
lib/djvViewApp/AboutDialog.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
456
2018-10-06T00:07:14.000Z
2022-03-31T06:14:22.000Z
lib/djvViewApp/AboutDialog.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
438
2018-10-31T15:05:51.000Z
2022-03-31T09:01:24.000Z
lib/djvViewApp/AboutDialog.cpp
pafri/DJV
9db15673b6b03ad3743f57119118261b1fbe8810
[ "BSD-3-Clause" ]
54
2018-10-29T10:18:36.000Z
2022-03-23T06:56:11.000Z
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2004-2020 Darby Johnston // All rights reserved. #include <djvViewApp/AboutDialog.h> #include <djvUI/Label.h> #include <djvUI/GridLayout.h> #include <djvUI/RowLayout.h> #include <djvUI/ScrollWidget.h> #include <djvUI/TextBlock.h> #include <djvSystem/Context.h> using namespace djv::Core; namespace djv { namespace ViewApp { struct AboutDialog::Private { std::map<std::string, std::shared_ptr<UI::Text::Label> > headers; std::map<std::string, std::shared_ptr<UI::Text::Block> > textBlocks; }; void AboutDialog::_init(const std::shared_ptr<System::Context>& context) { IDialog::_init(context); DJV_PRIVATE_PTR(); setClassName("djv::ViewApp::AboutDialog"); const std::vector<std::string> headers = { "Credits", "Sponsors", "License", "Copyright", "ThirdParty", "Trademarks" }; for (const auto& i : headers) { p.headers[i] = UI::Text::Label::create(context); p.headers[i]->setTextHAlign(UI::TextHAlign::Left); p.headers[i]->setFontSizeRole(UI::MetricsRole::FontLarge); } const std::vector<std::string> credits = { "Credits1", "Credits2", "Credits3", "Credits4", "Credits5", "Credits6", "Credits7", "Credits8", "Credits9", "Credits10", "Credits11" }; for (const auto& i : credits) { p.textBlocks[i] = UI::Text::Block::create(context); p.textBlocks[i]->setTextSizeRole(UI::MetricsRole::TextColumnLarge); } const std::vector<std::string> creditsText = { "Credits1Text", "Credits2Text", "Credits3Text", "Credits4Text", "Credits5Text", "Credits6Text", "Credits7Text", "Credits8Text", "Credits9Text", "Credits10Text", "Credits11Text" }; for (const auto& i : creditsText) { p.textBlocks[i] = UI::Text::Block::create(context); } const std::vector<std::string> sponsorsText = { "Sponsors1" }; for (const auto& i : sponsorsText) { p.textBlocks[i] = UI::Text::Block::create(context); } const std::vector<std::string> licenseText = { "License1", "License2", "License3", "License4", "License5", "License6" }; for (const auto& i : licenseText) { p.textBlocks[i] = UI::Text::Block::create(context); } p.textBlocks["CopyrightText"] = UI::Text::Block::create(context); const std::vector<std::string> copyrightText = { "Copyright1", "Copyright2", "Copyright3" }; for (const auto& i : copyrightText) { p.textBlocks[i] = UI::Text::Block::create(context); } p.textBlocks["ThirdPartyText"] = UI::Text::Block::create(context); const std::vector<std::string> thirdPartyText = { "ThirdParty1", "ThirdParty2", "ThirdParty3", "ThirdParty4", "ThirdParty5", "ThirdParty6", "ThirdParty7", "ThirdParty8", "ThirdParty9", "ThirdParty10", "ThirdParty11", "ThirdParty12", "ThirdParty13", "ThirdParty14", "ThirdParty15", "ThirdParty16", "ThirdParty17", "ThirdParty18", "ThirdParty19", "ThirdParty20" }; for (const auto& i : thirdPartyText) { p.textBlocks[i] = UI::Text::Block::create(context); } p.textBlocks["TrademarksText"] = UI::Text::Block::create(context); const std::vector<std::string> trademarksText = { "Trademarks1", "Trademarks2", "Trademarks3", "Trademarks4", "Trademarks5", "Trademarks6", "Trademarks7", "Trademarks8", "Trademarks9", "Trademarks10", "Trademarks11", "Trademarks12", "Trademarks13", "Trademarks14", "Trademarks15", "Trademarks16", "Trademarks17", "Trademarks18", "Trademarks19", "Trademarks20", "Trademarks21", "Trademarks22" }; for (const auto& i : trademarksText) { p.textBlocks[i] = UI::Text::Block::create(context); } p.textBlocks["TrademarksEnd"] = UI::Text::Block::create(context); const std::vector<std::string> madeInText = { "MadeIn" }; for (const auto& i : madeInText) { p.textBlocks[i] = UI::Text::Block::create(context); } auto textLayout = UI::VerticalLayout::create(context); textLayout->setMargin(UI::MetricsRole::Margin); textLayout->setSpacing(UI::MetricsRole::SpacingLarge); auto vLayout = UI::VerticalLayout::create(context); vLayout->addChild(p.headers["Credits"]); vLayout->addSeparator(); auto gridLayout = UI::GridLayout::create(context); gridLayout->addChild(p.textBlocks["Credits1"]); gridLayout->setGridPos(p.textBlocks["Credits1"], glm::ivec2(0, 0)); gridLayout->addChild(p.textBlocks["Credits1Text"]); gridLayout->setGridPos(p.textBlocks["Credits1Text"], glm::ivec2(1, 0)); gridLayout->setStretch(p.textBlocks["Credits1Text"], UI::GridStretch::Horizontal); gridLayout->addChild(p.textBlocks["Credits2"]); gridLayout->setGridPos(p.textBlocks["Credits2"], glm::ivec2(0, 1)); gridLayout->addChild(p.textBlocks["Credits2Text"]); gridLayout->setGridPos(p.textBlocks["Credits2Text"], glm::ivec2(1, 1)); gridLayout->addChild(p.textBlocks["Credits3"]); gridLayout->setGridPos(p.textBlocks["Credits3"], glm::ivec2(0, 2)); gridLayout->addChild(p.textBlocks["Credits3Text"]); gridLayout->setGridPos(p.textBlocks["Credits3Text"], glm::ivec2(1, 2)); gridLayout->addChild(p.textBlocks["Credits4"]); gridLayout->setGridPos(p.textBlocks["Credits4"], glm::ivec2(0, 3)); gridLayout->addChild(p.textBlocks["Credits4Text"]); gridLayout->setGridPos(p.textBlocks["Credits4Text"], glm::ivec2(1, 3)); gridLayout->addChild(p.textBlocks["Credits5"]); gridLayout->setGridPos(p.textBlocks["Credits5"], glm::ivec2(0, 4)); gridLayout->addChild(p.textBlocks["Credits5Text"]); gridLayout->setGridPos(p.textBlocks["Credits5Text"], glm::ivec2(1, 4)); gridLayout->addChild(p.textBlocks["Credits6"]); gridLayout->setGridPos(p.textBlocks["Credits6"], glm::ivec2(0, 5)); gridLayout->addChild(p.textBlocks["Credits6Text"]); gridLayout->setGridPos(p.textBlocks["Credits6Text"], glm::ivec2(1, 5)); gridLayout->addChild(p.textBlocks["Credits7"]); gridLayout->setGridPos(p.textBlocks["Credits7"], glm::ivec2(0, 6)); gridLayout->addChild(p.textBlocks["Credits7Text"]); gridLayout->setGridPos(p.textBlocks["Credits7Text"], glm::ivec2(1, 6)); gridLayout->addChild(p.textBlocks["Credits8"]); gridLayout->setGridPos(p.textBlocks["Credits8"], glm::ivec2(0, 7)); gridLayout->addChild(p.textBlocks["Credits8Text"]); gridLayout->setGridPos(p.textBlocks["Credits8Text"], glm::ivec2(1, 7)); gridLayout->addChild(p.textBlocks["Credits9"]); gridLayout->setGridPos(p.textBlocks["Credits9"], glm::ivec2(0, 8)); gridLayout->addChild(p.textBlocks["Credits9Text"]); gridLayout->setGridPos(p.textBlocks["Credits9Text"], glm::ivec2(1, 8)); gridLayout->addChild(p.textBlocks["Credits10"]); gridLayout->setGridPos(p.textBlocks["Credits10"], glm::ivec2(0, 9)); gridLayout->addChild(p.textBlocks["Credits10Text"]); gridLayout->setGridPos(p.textBlocks["Credits10Text"], glm::ivec2(1, 9)); gridLayout->addChild(p.textBlocks["Credits11"]); gridLayout->setGridPos(p.textBlocks["Credits11"], glm::ivec2(0, 10)); gridLayout->addChild(p.textBlocks["Credits11Text"]); gridLayout->setGridPos(p.textBlocks["Credits11Text"], glm::ivec2(1, 10)); vLayout->addChild(gridLayout); textLayout->addChild(vLayout); vLayout = UI::VerticalLayout::create(context); vLayout->addChild(p.headers["Sponsors"]); vLayout->addSeparator(); for (const auto& i : sponsorsText) { vLayout->addChild(p.textBlocks[i]); } textLayout->addChild(vLayout); vLayout = UI::VerticalLayout::create(context); vLayout->addChild(p.headers["License"]); vLayout->addSeparator(); for (size_t i = 1; i <= 2; ++i) { std::stringstream ss; ss << "License" << i; vLayout->addChild(p.textBlocks[ss.str()]); } auto vLayout2 = UI::VerticalLayout::create(context); vLayout2->setSpacing(UI::MetricsRole::None); for (size_t i = 3; i <= 5; ++i) { std::stringstream ss; ss << "License" << i; vLayout2->addChild(p.textBlocks[ss.str()]); } vLayout->addChild(vLayout2); vLayout->addChild(p.textBlocks["License6"]); textLayout->addChild(vLayout); vLayout = UI::VerticalLayout::create(context); vLayout->addChild(p.headers["Copyright"]); vLayout->addSeparator(); vLayout->addChild(p.textBlocks["CopyrightText"]); vLayout2 = UI::VerticalLayout::create(context); vLayout2->setSpacing(UI::MetricsRole::None); for (size_t i = 1; i <= copyrightText.size(); ++i) { std::stringstream ss; ss << "Copyright" << i; vLayout2->addChild(p.textBlocks[ss.str()]); } vLayout->addChild(vLayout2); textLayout->addChild(vLayout); vLayout = UI::VerticalLayout::create(context); vLayout->addChild(p.headers["ThirdParty"]); vLayout->addSeparator(); vLayout->addChild(p.textBlocks["ThirdPartyText"]); vLayout2 = UI::VerticalLayout::create(context); vLayout2->setSpacing(UI::MetricsRole::None); for (size_t i = 1; i <= thirdPartyText.size(); ++i) { std::stringstream ss; ss << "ThirdParty" << i; vLayout2->addChild(p.textBlocks[ss.str()]); } vLayout->addChild(vLayout2); textLayout->addChild(vLayout); vLayout = UI::VerticalLayout::create(context); vLayout->addChild(p.headers["Trademarks"]); vLayout->addSeparator(); vLayout->addChild(p.textBlocks["TrademarksText"]); vLayout2 = UI::VerticalLayout::create(context); vLayout2->setSpacing(UI::MetricsRole::None); for (size_t i = 1; i <= trademarksText.size(); ++i) { std::stringstream ss; ss << "Trademarks" << i; vLayout2->addChild(p.textBlocks[ss.str()]); } vLayout->addChild(vLayout2); vLayout->addChild(p.textBlocks["TrademarksEnd"]); textLayout->addChild(vLayout); vLayout = UI::VerticalLayout::create(context); vLayout->addSeparator(); vLayout2 = UI::VerticalLayout::create(context); vLayout2->addChild(p.textBlocks["MadeIn"]); vLayout->addChild(vLayout2); textLayout->addChild(vLayout); auto scrollWidget = UI::ScrollWidget::create(UI::ScrollType::Vertical, context); scrollWidget->setBorder(false); scrollWidget->setShadowOverlay({ UI::Side::Top }); scrollWidget->addChild(textLayout); addChild(scrollWidget); setStretch(scrollWidget); } AboutDialog::AboutDialog() : _p(new Private) {} AboutDialog::~AboutDialog() {} std::shared_ptr<AboutDialog> AboutDialog::create(const std::shared_ptr<System::Context>& context) { auto out = std::shared_ptr<AboutDialog>(new AboutDialog); out->_init(context); return out; } void AboutDialog::_initEvent(System::Event::Init & event) { IDialog::_initEvent(event); DJV_PRIVATE_PTR(); if (event.getData().text) { std::stringstream ss; ss << _getText(DJV_TEXT("about_title")); ss << " " << DJV_VERSION; setTitle(ss.str()); p.headers["Credits"]->setText(_getText(DJV_TEXT("about_section_credits"))); p.headers["Sponsors"]->setText(_getText(DJV_TEXT("about_section_sponsors"))); p.headers["License"]->setText(_getText(DJV_TEXT("about_section_license"))); p.headers["Copyright"]->setText(_getText(DJV_TEXT("about_section_copyright"))); p.headers["ThirdParty"]->setText(_getText(DJV_TEXT("about_section_third_party"))); p.headers["Trademarks"]->setText(_getText(DJV_TEXT("about_section_trademarks"))); p.textBlocks["Credits1"]->setText(_getText(DJV_TEXT("about_credits_darby_johnston"))); p.textBlocks["Credits1Text"]->setText(_getText(DJV_TEXT("about_credits_darby_johnston_text"))); p.textBlocks["Credits2"]->setText(_getText(DJV_TEXT("about_credits_kent_oberheu"))); p.textBlocks["Credits2Text"]->setText(_getText(DJV_TEXT("about_credits_kent_oberheu_text"))); p.textBlocks["Credits3"]->setText(_getText(DJV_TEXT("about_credits_siciliana_johnston"))); p.textBlocks["Credits3Text"]->setText(_getText(DJV_TEXT("about_credits_siciliana_johnston_text"))); p.textBlocks["Credits4"]->setText(_getText(DJV_TEXT("about_credits_mikael_sundell"))); p.textBlocks["Credits4Text"]->setText(_getText(DJV_TEXT("about_credits_mikael_sundell_text"))); p.textBlocks["Credits5"]->setText(_getText(DJV_TEXT("about_credits_cansecogpc"))); p.textBlocks["Credits5Text"]->setText(_getText(DJV_TEXT("about_credits_cansecogpc_text"))); p.textBlocks["Credits6"]->setText(_getText(DJV_TEXT("about_credits_jean-francois_panisset"))); p.textBlocks["Credits6Text"]->setText(_getText(DJV_TEXT("about_credits_jean-francois_panisset_text"))); p.textBlocks["Credits7"]->setText(_getText(DJV_TEXT("about_credits_haryo_sukmawanto"))); p.textBlocks["Credits7Text"]->setText(_getText(DJV_TEXT("about_credits_haryo_sukmawanto_text"))); p.textBlocks["Credits8"]->setText(_getText(DJV_TEXT("about_credits_damien_picard"))); p.textBlocks["Credits8Text"]->setText(_getText(DJV_TEXT("about_credits_damien_picard_text"))); p.textBlocks["Credits9"]->setText(_getText(DJV_TEXT("about_credits_stefan_ihringer"))); p.textBlocks["Credits9Text"]->setText(_getText(DJV_TEXT("about_credits_stefan_ihringer_text"))); p.textBlocks["Credits10"]->setText(_getText(DJV_TEXT("about_credits_kimball_thurston"))); p.textBlocks["Credits10Text"]->setText(_getText(DJV_TEXT("about_credits_kimball_thurston_text"))); p.textBlocks["Credits11"]->setText(_getText(DJV_TEXT("about_credits_yushi_tone"))); p.textBlocks["Credits11Text"]->setText(_getText(DJV_TEXT("about_credits_yushi_tone_text"))); p.textBlocks["Sponsors1"]->setText(_getText(DJV_TEXT("about_sponsors_unexpected"))); p.textBlocks["License1"]->setText(_getText(DJV_TEXT("about_license_1"))); p.textBlocks["License2"]->setText(_getText(DJV_TEXT("about_license_2"))); p.textBlocks["License3"]->setText(_getText(DJV_TEXT("about_license_3"))); p.textBlocks["License4"]->setText(_getText(DJV_TEXT("about_license_4"))); p.textBlocks["License5"]->setText(_getText(DJV_TEXT("about_license_5"))); p.textBlocks["License6"]->setText(_getText(DJV_TEXT("about_license_6"))); p.textBlocks["CopyrightText"]->setText(_getText(DJV_TEXT("about_copyright_text"))); p.textBlocks["Copyright1"]->setText(_getText(DJV_TEXT("about_copyright_darby_johnston"))); p.textBlocks["Copyright2"]->setText(_getText(DJV_TEXT("about_copyright_kent_oberheu"))); p.textBlocks["Copyright3"]->setText(_getText(DJV_TEXT("about_copyright_mikael_sundell"))); p.textBlocks["ThirdPartyText"]->setText(_getText(DJV_TEXT("about_third_party_text"))); p.textBlocks["ThirdParty1"]->setText(_getText(DJV_TEXT("about_third_party_cmake"))); p.textBlocks["ThirdParty2"]->setText(_getText(DJV_TEXT("about_third_party_ffmpeg"))); p.textBlocks["ThirdParty3"]->setText(_getText(DJV_TEXT("about_third_party_freetype"))); p.textBlocks["ThirdParty4"]->setText(_getText(DJV_TEXT("about_third_party_glfw"))); p.textBlocks["ThirdParty5"]->setText(_getText(DJV_TEXT("about_third_party_glm"))); p.textBlocks["ThirdParty6"]->setText(_getText(DJV_TEXT("about_third_party_mbedtls"))); p.textBlocks["ThirdParty7"]->setText(_getText(DJV_TEXT("about_third_party_openal"))); p.textBlocks["ThirdParty8"]->setText(_getText(DJV_TEXT("about_third_party_opencolorio"))); p.textBlocks["ThirdParty9"]->setText(_getText(DJV_TEXT("about_third_party_openexr"))); p.textBlocks["ThirdParty10"]->setText(_getText(DJV_TEXT("about_third_party_rtaudio"))); p.textBlocks["ThirdParty11"]->setText(_getText(DJV_TEXT("about_third_party_curl"))); p.textBlocks["ThirdParty12"]->setText(_getText(DJV_TEXT("about_third_party_dr_libs"))); p.textBlocks["ThirdParty13"]->setText(_getText(DJV_TEXT("about_third_party_glad"))); p.textBlocks["ThirdParty14"]->setText(_getText(DJV_TEXT("about_third_party_libjpeg"))); p.textBlocks["ThirdParty15"]->setText(_getText(DJV_TEXT("about_third_party_libjpeg-turbo"))); p.textBlocks["ThirdParty16"]->setText(_getText(DJV_TEXT("about_third_party_libpng"))); p.textBlocks["ThirdParty17"]->setText(_getText(DJV_TEXT("about_third_party_libtiff"))); p.textBlocks["ThirdParty18"]->setText(_getText(DJV_TEXT("about_third_party_opennurbs"))); p.textBlocks["ThirdParty19"]->setText(_getText(DJV_TEXT("about_third_party_rapidjson"))); p.textBlocks["ThirdParty20"]->setText(_getText(DJV_TEXT("about_third_party_zlib"))); p.textBlocks["TrademarksText"]->setText(_getText(DJV_TEXT("about_trademarks_text"))); p.textBlocks["Trademarks1"]->setText(_getText(DJV_TEXT("about_trademarks_apple"))); p.textBlocks["Trademarks2"]->setText(_getText(DJV_TEXT("about_trademarks_amd"))); p.textBlocks["Trademarks3"]->setText(_getText(DJV_TEXT("about_trademarks_autodesk"))); p.textBlocks["Trademarks4"]->setText(_getText(DJV_TEXT("about_trademarks_debian"))); p.textBlocks["Trademarks5"]->setText(_getText(DJV_TEXT("about_trademarks_ffmpeg"))); p.textBlocks["Trademarks6"]->setText(_getText(DJV_TEXT("about_trademarks_freebsd"))); p.textBlocks["Trademarks7"]->setText(_getText(DJV_TEXT("about_trademarks_github"))); p.textBlocks["Trademarks8"]->setText(_getText(DJV_TEXT("about_trademarks_intel"))); p.textBlocks["Trademarks9"]->setText(_getText(DJV_TEXT("about_trademarks_lucasfilm"))); p.textBlocks["Trademarks10"]->setText(_getText(DJV_TEXT("about_trademarks_kodak"))); p.textBlocks["Trademarks11"]->setText(_getText(DJV_TEXT("about_trademarks_linux"))); p.textBlocks["Trademarks12"]->setText(_getText(DJV_TEXT("about_trademarks_microsoft"))); p.textBlocks["Trademarks13"]->setText(_getText(DJV_TEXT("about_trademarks_mips"))); p.textBlocks["Trademarks14"]->setText(_getText(DJV_TEXT("about_trademarks_nvidia"))); p.textBlocks["Trademarks15"]->setText(_getText(DJV_TEXT("about_trademarks_red_hat"))); p.textBlocks["Trademarks16"]->setText(_getText(DJV_TEXT("about_trademarks_rhino"))); p.textBlocks["Trademarks17"]->setText(_getText(DJV_TEXT("about_trademarks_sgi"))); p.textBlocks["Trademarks18"]->setText(_getText(DJV_TEXT("about_trademarks_smpte"))); p.textBlocks["Trademarks19"]->setText(_getText(DJV_TEXT("about_trademarks_sourceforge"))); p.textBlocks["Trademarks20"]->setText(_getText(DJV_TEXT("about_trademarks_suse"))); p.textBlocks["Trademarks21"]->setText(_getText(DJV_TEXT("about_trademarks_ubuntu"))); p.textBlocks["Trademarks22"]->setText(_getText(DJV_TEXT("about_trademarks_unix"))); p.textBlocks["TrademarksEnd"]->setText(_getText(DJV_TEXT("about_trademarks_end"))); p.textBlocks["MadeIn"]->setText(_getText(DJV_TEXT("about_made_in"))); } } } // namespace ViewApp } // namespace djv
54.83871
119
0.59733
[ "vector" ]
1b52a019d36ce93c843f92917e239489802c88fc
1,697
cc
C++
elasticsearch/src/model/ListDataStreamsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
elasticsearch/src/model/ListDataStreamsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
elasticsearch/src/model/ListDataStreamsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/elasticsearch/model/ListDataStreamsRequest.h> using AlibabaCloud::Elasticsearch::Model::ListDataStreamsRequest; ListDataStreamsRequest::ListDataStreamsRequest() : RoaServiceRequest("elasticsearch", "2017-06-13") { setResourcePath("/openapi/instances/[InstanceId]/data-streams"); setMethod(HttpRequest::Method::Get); } ListDataStreamsRequest::~ListDataStreamsRequest() {} std::string ListDataStreamsRequest::getInstanceId()const { return instanceId_; } void ListDataStreamsRequest::setInstanceId(const std::string& instanceId) { instanceId_ = instanceId; setParameter("InstanceId", instanceId); } bool ListDataStreamsRequest::getIsManaged()const { return isManaged_; } void ListDataStreamsRequest::setIsManaged(bool isManaged) { isManaged_ = isManaged; setParameter("IsManaged", isManaged ? "true" : "false"); } std::string ListDataStreamsRequest::getName()const { return name_; } void ListDataStreamsRequest::setName(const std::string& name) { name_ = name; setParameter("Name", name); }
26.515625
75
0.748379
[ "model" ]
1b5635ae55ee138fa1bebc4198dd77478713c7a4
3,255
cc
C++
squim/ioutil/file_util.cc
baranov1ch/squim
5bde052735e0dac7c87e8f7939d0168e6ee05857
[ "Apache-2.0" ]
2
2016-05-06T01:15:49.000Z
2016-05-06T01:29:00.000Z
squim/ioutil/file_util.cc
baranov1ch/squim
5bde052735e0dac7c87e8f7939d0168e6ee05857
[ "Apache-2.0" ]
null
null
null
squim/ioutil/file_util.cc
baranov1ch/squim
5bde052735e0dac7c87e8f7939d0168e6ee05857
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Alexey Baranov <me@kotiki.cc>. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "squim/ioutil/file_util.h" #include "squim/base/logging.h" #include "squim/ioutil/chunk_reader.h" #include "squim/ioutil/chunk_writer.h" #include "squim/ioutil/read_util.h" #include "squim/ioutil/string_reader.h" #include "squim/ioutil/string_writer.h" #include "squim/os/file.h" #include "squim/os/file_system.h" namespace ioutil { os::FsResult ReadDir(const std::string& path, std::vector<os::FileInfo>* contents) { auto fs = os::FileSystem::CreateDefault(); std::unique_ptr<os::File> dir; auto result = fs->Open(path, &dir); if (!result.ok()) return result; return dir->Readdir(contents); } io::IoResult ReadFile(const std::string& path, io::Writer* writer) { auto fs = os::FileSystem::CreateDefault(); std::unique_ptr<os::File> file; auto result = fs->Open(path, &file); if (!result.ok()) return result.ToIoResult(); return Copy(writer, file.get()); } io::IoResult ReadFile(const std::string& path, io::ChunkPtr* chunk) { // TODO: make some space reservation after Stat. io::ChunkList chunks; ChunkListWriter writer(&chunks); auto result = ReadFile(path, &writer); *chunk = io::Chunk::Merge(chunks); return result; } io::IoResult ReadFile(const std::string& path, io::ChunkList* chunks) { ChunkListWriter writer(chunks); return ReadFile(path, &writer); } io::IoResult ReadFile(const std::string& path, std::string* contents) { StringWriter writer(contents); return ReadFile(path, &writer); } io::IoResult WriteFile(const std::string& path, io::Reader* reader, os::FileMode perm) { auto fs = os::FileSystem::CreateDefault(); std::unique_ptr<os::File> file; auto result = fs->OpenFile(path, os::kReadWrite | os::kCreate | os::kTruncate, perm, &file); if (!result.ok()) return result.ToIoResult(); // TODO: inefficient stuff! return Copy(file.get(), reader); } io::IoResult WriteFile(const std::string& path, const io::Chunk* chunk, os::FileMode perm) { ChunkReader reader(chunk); return WriteFile(path, &reader, perm); } io::IoResult WriteFile(const std::string& path, const io::ChunkList* chunks, os::FileMode perm) { ChunkListReader reader(chunks); return WriteFile(path, &reader, perm); } io::IoResult WriteFile(const std::string& path, const std::string& contents, os::FileMode perm) { StringReader reader(contents); return WriteFile(path, &reader, perm); } } // namespace ioutil
30.707547
80
0.661444
[ "vector" ]
1b58b02ba9a23e04a8d8640c40ffa6b81a262af3
934
cpp
C++
221. Maximal Square.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
221. Maximal Square.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
221. Maximal Square.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
// See detailed explanation in discuss. class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.size() == 0 || matrix[0].size() == 0) return 0; int maxSquare = 0; for(int i = 0; i < matrix.size(); i++) for(int j = 0; j < matrix[0].size(); j++) if(matrix[i][j] != '0') maxSquare = max(maxSquare, findSquare(matrix, i, j)); return maxSquare; } int findSquare(vector<vector<char>>& matrix, int r, int c){ int row = r - 1; int col = c - 1; while(row >= 0 && col >= 0 && matrix[r][col] == '1' && matrix[row][c] == '1'){ int i = row; int j = col; while(i < r && matrix[i][col] == '1') i++; while(j < c && matrix[row][j] == '1') j++; if(i != r || j != c) break; row--; col--; } return pow(r - row, 2); } };
33.357143
93
0.445396
[ "vector" ]
1b5a2aae685482717f62118105e3c833f6422dc3
2,118
cpp
C++
C++/1275.cpp
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
C++/1275.cpp
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
C++/1275.cpp
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 0 ms submission class Solution { public: string tictactoe(vector<vector<int>>& moves) { vector<vector<int>> vec(3, vector<int>(3, 0)); for (int i = 0; i < moves.size(); i++) { if (i % 2 == 0) vec[moves[i][0]][moves[i][1]] = 1; else vec[moves[i][0]][moves[i][1]] = -1; } int sum3 = 0; int sum4 = 0; int z_count = 0; for (int i = 0; i < 3; i++) { int sum1 = 0; int sum2 = 0; for (int j = 0; j < 3; j++) { sum1 += vec[i][j]; sum2 += vec[j][i]; if (vec[i][j] == 0) { z_count++; } } if (sum1 == 3 || sum2 == 3) { return "A"; } if (sum1 == -3 || sum2 == -3) { return "B"; } sum3 += vec[i][i]; sum4 += vec[i][2 - i]; } if (sum3 == 3 || sum4 == 3) return "A"; else if (sum3 == -3 || sum4 == -3) return "B"; else if (z_count > 0) { return "Pending"; } else { return "Draw"; } } }; __________________________________________________________________________________________________ 0ms class Solution { public: string tictactoe(vector<vector<int>>& moves) { vector<int> A(8,0), B(8,0); // 3 rows, 3 cols, 2 diagonals for(int i=0; i<moves.size(); i++) { int r=moves[i][0], c=moves[i][1]; vector<int>& player = (i%2==0)?A:B; player[r]++; player[c+3]++; if(r==c) player[6]++; if(r==2-c) player[7]++; } for(int i=0; i<8; i++) { if(A[i]==3) return "A"; if(B[i]==3) return "B"; } return moves.size()==9 ? "Draw":"Pending"; } }; __________________________________________________________________________________________________
29.830986
98
0.448064
[ "vector" ]
1b5d046c75b0b4bc6f3499aa98a56551247a3046
14,111
cpp
C++
submodules/hal/extract/tests/hal4dExtractTest.cpp
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
submodules/hal/extract/tests/hal4dExtractTest.cpp
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
submodules/hal/extract/tests/hal4dExtractTest.cpp
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
#include "hal.h" #include "hal4dExtract.h" #include "hal4dExtractTest.h" using namespace std; using namespace hal; void ConservedBed4dExtractTest::createCallBack(AlignmentPtr alignment) { Genome *root = alignment->addRootGenome("root"); Genome *leaf1 = alignment->addLeafGenome("leaf1", "root", 1); Genome *leaf2 = alignment->addLeafGenome("leaf2", "root", 1); vector<Sequence::Info> seqVec(1); seqVec[0] = Sequence::Info("rootSequence", 192, 0, 1); root->setDimensions(seqVec); seqVec[0] = Sequence::Info("leaf1Sequence", 192, 1, 0); leaf1->setDimensions(seqVec); seqVec[0] = Sequence::Info("leaf2Sequence", 192, 1, 0); leaf2->setDimensions(seqVec); // all possible codons, in a single frame -- we will test only a few but make // sure that the correct number of sites is output as well // changed final 4d site, which should change nothing since ancestors are // ignored root->setString("aaaaacaagaatacaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgttttgatgctggtgtttattcttgttt"); BottomSegmentIteratorPtr botIt = root->getBottomSegmentIterator(); botIt->setCoordinates(0, 192); botIt->setChildIndex(0, 0); botIt->setChildIndex(1, 0); botIt->setChildReversed(0, false); botIt->setChildReversed(1, false); botIt->setTopParseIndex(NULL_INDEX); // added unconserved 4d site at 2, disabled 4d site at 14 and 18/20 leaf1->setString("acaaacaagaataaaaccatgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt"); TopSegmentIteratorPtr topIt = leaf1->getTopSegmentIterator(); topIt->setCoordinates(0, 192); topIt->setParentIndex(0); topIt->setParentReversed(false); topIt->setNextParalogyIndex(NULL_INDEX); topIt->setBottomParseIndex(NULL_INDEX); // disabled 4d site at 14 leaf2->setString("aaaaacaagaataaaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt"); topIt = leaf2->getTopSegmentIterator(); topIt->setCoordinates(0, 192); topIt->setParentIndex(0); topIt->setParentReversed(false); topIt->setNextParalogyIndex(NULL_INDEX); topIt->setBottomParseIndex(NULL_INDEX); } void ConservedBed4dExtractTest::checkCallBack(AlignmentConstPtr alignment) { const Genome *genome = alignment->openGenome("root"); stringstream bedFile("rootSequence\t0\t192\tFORWARD\t0\t+\n" "rootSequence\t0\t192\tREV\t0\t-\n"); stringstream outStream; Extract4d extract; extract.run(genome, &bedFile, &outStream, -1, true); vector<string> streamResults = chopString(outStream.str(), "\n"); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t14\t15\tFORWARD\t0\t+") == streamResults.end()); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t177\t178\tREV\t0\t-") != streamResults.end()); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t18\t19\tREV\t0\t-") == streamResults.end()); // 14, 18(+ strand) /20 (- strand) disabled, so 3 are missing CuAssertTrue(_testCase, streamResults.size() == 61); } void Bed4dExtractTest::createCallBack(AlignmentPtr alignment) { Genome *genome = alignment->addRootGenome("root"); vector<Sequence::Info> seqVec(1); seqVec[0] = Sequence::Info("rootSequence", 192, 0, 0); genome->setDimensions(seqVec); // all possible codons, in a single frame -- we will test only a few but make // sure that the correct number of sites is output as well genome->setString("aaaaacaagaatacaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt"); } void Bed4dExtractTest::checkCallBack(AlignmentConstPtr alignment) { const Genome *genome = alignment->openGenome("root"); stringstream bedFile("rootSequence\t0\t192\tFORWARD\t0\t+\n" "rootSequence\t0\t192\tREV\t0\t-\n"); stringstream outStream; Extract4d extract; extract.run(genome, &bedFile, &outStream, -1); vector<string> streamResults = chopString(outStream.str(), "\n"); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t14\t15\tFORWARD\t0\t+") != streamResults.end()); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t177\t178\tREV\t0\t-") != streamResults.end()); CuAssertTrue(_testCase, streamResults.size() == 64); } void Block4dExtractTest::createCallBack(AlignmentPtr alignment) { Genome *genome = alignment->addRootGenome("root"); vector<Sequence::Info> seqVec(1); seqVec[0] = Sequence::Info("rootSequence", 192, 0, 0); genome->setDimensions(seqVec); // all possible codons, in a single frame -- we will test only a few but make // sure that the correct number of sites is output as well genome->setString("aaaaacaagaatacaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt"); } void Block4dExtractTest::checkCallBack(AlignmentConstPtr alignment) { const Genome *genome = alignment->openGenome("root"); // test frame shift stringstream bedFile("rootSequence\t0\t192\tFORWARD\t0\t+\t0\t192\t0\t3\t17,6,7\t0,30,60\n" "rootSequence\t0\t192\tREV\t0\t-\t0\t192\t0\t2\t13,17\t0,175"); stringstream outStream; Extract4d extract; extract.run(genome, &bedFile, &outStream, -1); vector<string> streamResults = chopString(outStream.str(), "\n"); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t0\t192\tFORWARD\t0\t+\t0\t192\t0,0,0\t5\t1,1,1,1,1\t14,30,33,60,66") != streamResults.end()); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t0\t192\tREV\t0\t-\t0\t192\t0,0,0\t4\t1,1,1,1\t3,6,12,177") != streamResults.end()); CuAssertTrue(_testCase, streamResults.size() == 2); } void ConservedBlock4dExtractTest::createCallBack(AlignmentPtr alignment) { Genome *root = alignment->addRootGenome("root"); Genome *leaf1 = alignment->addLeafGenome("leaf1", "root", 1); Genome *leaf2 = alignment->addLeafGenome("leaf2", "root", 1); vector<Sequence::Info> seqVec(2); seqVec[0] = Sequence::Info("rootSequence", 192, 0, 1); seqVec[1] = Sequence::Info("rootSequence2", 192, 0, 1); root->setDimensions(seqVec); seqVec[0] = Sequence::Info("leaf1Sequence", 192, 1, 0); seqVec[1] = Sequence::Info("leaf1Sequence2", 192, 1, 0); leaf1->setDimensions(seqVec); seqVec[0] = Sequence::Info("leaf2Sequence", 192, 1, 0); seqVec[1] = Sequence::Info("leaf2Sequence2", 192, 1, 0); leaf2->setDimensions(seqVec); // all possible codons, in a single frame -- we will test only a few but make // sure that the correct number of sites is output as well // changed final 4d site, which should change nothing since ancestors are // ignored root->setString("aaaaacaagaatacaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgttttgatgctggtgtttattcttgtttaaaaacaagaatacaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgttttgatgctggtgtttattcttgttt"); BottomSegmentIteratorPtr botIt = root->getBottomSegmentIterator(); botIt->setCoordinates(0, 192); botIt->setChildIndex(0, 0); botIt->setChildIndex(1, 0); botIt->setChildReversed(0, false); botIt->setChildReversed(1, false); botIt->setTopParseIndex(NULL_INDEX); botIt->toRight(); botIt->setCoordinates(192, 192); botIt->setChildIndex(0, 1); botIt->setChildIndex(1, 1); botIt->setChildReversed(0, false); botIt->setChildReversed(1, false); botIt->setTopParseIndex(NULL_INDEX); // added unconserved 4d site at 2, disabled 4d site at 14 and 18/20 leaf1->setString("acaaacaagaataaaaccatgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgtttacaaacaagaataaaaccatgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt"); TopSegmentIteratorPtr topIt = leaf1->getTopSegmentIterator(); topIt->setCoordinates(0, 192); topIt->setParentIndex(0); topIt->setParentReversed(false); topIt->setNextParalogyIndex(NULL_INDEX); topIt->setBottomParseIndex(NULL_INDEX); topIt->toRight(); topIt->setCoordinates(192, 192); topIt->setParentIndex(1); topIt->setParentReversed(false); topIt->setNextParalogyIndex(NULL_INDEX); topIt->setBottomParseIndex(NULL_INDEX); // disabled 4d site at 14 leaf2->setString("aaaaacaagaataaaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgtttaaaaacaagaataaaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt"); topIt = leaf2->getTopSegmentIterator(); topIt->setCoordinates(0, 192); topIt->setParentIndex(0); topIt->setParentReversed(false); topIt->setNextParalogyIndex(NULL_INDEX); topIt->setBottomParseIndex(NULL_INDEX); topIt->toRight(); topIt->setCoordinates(192, 192); topIt->setParentIndex(1); topIt->setParentReversed(false); topIt->setNextParalogyIndex(NULL_INDEX); topIt->setBottomParseIndex(NULL_INDEX); } void ConservedBlock4dExtractTest::checkCallBack(AlignmentConstPtr alignment) { const Genome *genome = alignment->openGenome("root"); // test frame shift stringstream bedFile("rootSequence\t0\t192\tFORWARD\t0\t+\t0\t192\t0\t3\t17,6,7\t0,30,60\n" "rootSequence\t0\t192\tREV\t0\t-\t0\t192\t0\t2\t13,17\t0,175\n" "rootSequence2\t0\t192\tFORWARD\t0\t+\t0\t192\t0\t3\t17,6,7\t0,30,60\n" "rootSequence2\t0\t192\tREV\t0\t-\t0\t192\t0\t2\t13,17\t0,175\n"); stringstream outStream; Extract4d extract; extract.run(genome, &bedFile, &outStream, -1, true); vector<string> streamResults = chopString(outStream.str(), "\n"); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t0\t192\tFORWARD\t0\t+\t0\t192\t0,0,0\t2\t1,1\t33,66") != streamResults.end()); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t0\t192\tREV\t0\t-\t0\t192\t0,0,0\t3\t1,1,1\t3,6,177") != streamResults.end()); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence2\t0\t192\tFORWARD\t0\t+\t0\t192\t0,0,0\t2\t1,1\t33,66") != streamResults.end()); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence2\t0\t192\tREV\t0\t-\t0\t192\t0,0,0\t3\t1,1,1\t3,6,177") != streamResults.end()); CuAssertTrue(_testCase, streamResults.size() == 4); } void CDS4dExtractTest::createCallBack(AlignmentPtr alignment) { Genome *genome = alignment->addRootGenome("root"); vector<Sequence::Info> seqVec(1); seqVec[0] = Sequence::Info("rootSequence", 213, 0, 0); genome->setDimensions(seqVec); // all possible codons, in a single frame, starting at position 21 // -- we will test only a few but make sure that the correct number // of sites is output as well genome->setString("caccatcatcatcatcatcataaaaacaagaatacaaccacgactagaagcaggagtataatcatgattcaacaccagcatccacccccgcctcgacgccggcgtctactcctgcttgaagacgaggatgcagccgcggctggaggcgggggtgtagtcgtggtttaatactagtattcatcctcgtcttgatgctggtgtttattcttgttt"); } void CDS4dExtractTest::checkCallBack(AlignmentConstPtr alignment) { const Genome *genome = alignment->openGenome("root"); stringstream bedFile("rootSequence\t1\t212\tFORWARD\t0\t+\t21\t88\t0\t5\t10,19,6,8,10\t0,18,50,80,90\n" "rootSequence\t1\t213\tREV\t0\t-\t25\t198\t0\t2\t13,17\t20,195"); stringstream outStream; Extract4d extract; extract.run(genome, &bedFile, &outStream, -1); vector<string> streamResults = chopString(outStream.str(), "\n"); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t1\t212\tFORWARD\t0\t+\t21\t88\t0,0,0\t5\t1,1,1,1,1\t34,50,53,80,86") != streamResults.end()); CuAssertTrue(_testCase, find(streamResults.begin(), streamResults.end(), "rootSequence\t1\t213\tREV\t0\t-\t25\t198\t0,0,0\t2\t1,1\t26,32") != streamResults.end()); CuAssertTrue(_testCase, streamResults.size() == 2); } void halBlock4dExtractTest(CuTest *testCase) { // try // { Block4dExtractTest tester; tester.check(testCase); // } // catch (...) // { // CuAssertTrue(testCase, false); // } } void halCDS4dExtractTest(CuTest *testCase) { // try // { CDS4dExtractTest tester; tester.check(testCase); // } // catch (...) // { // CuAssertTrue(testCase, false); // } } void halConservedBlock4dExtractTest(CuTest *testCase) { // try // { ConservedBlock4dExtractTest tester; tester.check(testCase); // } // catch (...) // { // CuAssertTrue(testCase, false); // } } CuSuite* hal4dExtractTestSuite(void) { CuSuite* suite = CuSuiteNew(); SUITE_ADD_TEST(suite, halBlock4dExtractTest); SUITE_ADD_TEST(suite, halConservedBlock4dExtractTest); SUITE_ADD_TEST(suite, halCDS4dExtractTest); return suite; } int hal4dExtractRunAllTests(void) { CuString *output = CuStringNew(); CuSuite* suite = CuSuiteNew(); CuSuiteAddSuite(suite, hal4dExtractTestSuite()); CuSuiteRun(suite); CuSuiteSummary(suite, output); CuSuiteDetails(suite, output); printf("%s\n", output->buffer); return suite->failCount > 0; } int main(int argc, char *argv[]) { return hal4dExtractRunAllTests(); }
47.996599
407
0.758274
[ "vector" ]
1b60220d643452a5136335d0ea430e420e1979c2
8,281
cpp
C++
application/MainWindow.cpp
momantang/learning
81b6447ebb96933576de36df09388d3a904319dc
[ "Unlicense" ]
null
null
null
application/MainWindow.cpp
momantang/learning
81b6447ebb96933576de36df09388d3a904319dc
[ "Unlicense" ]
null
null
null
application/MainWindow.cpp
momantang/learning
81b6447ebb96933576de36df09388d3a904319dc
[ "Unlicense" ]
null
null
null
#include "MainWindow.h" #include <QtWidgets> MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),textEdit(new QPlainTextEdit) { setCentralWidget(textEdit); createActions(); createStatusBar(); readSettings(); connect(textEdit->document(), &QTextDocument::contentsChange, this, &MainWindow::documentWasModified); #ifndef QT_NO_SESSIONMANAGER QGuiApplication::setFallbackSessionManagementEnabled(false); connect(qApp, &QGuiApplication::commitDataRequest, this, &MainWindow::commitData); #endif } void MainWindow::loadFile(const QString& filename) { QFile file(filename); if (!file.open(QFile::ReadOnly|QFile::Text)) { QMessageBox::warning(this, "Application", tr("Can not read file %1\n%2").arg(QDir::toNativeSeparators(filename), file.errorString())); return; } QTextStream in(&file); QApplication::setOverrideCursor(Qt::WaitCursor); textEdit->setPlainText(in.readAll()); QApplication::restoreOverrideCursor(); setCurrentFile(filename); statusBar()->showMessage("File loaded", 2000); } void MainWindow::closeEvent(QCloseEvent *event) { if (maybeSave()) { writeSettings(); event->accept(); } else { event->ignore(); } } void MainWindow::newFile() { if (maybeSave()) { textEdit->clear(); setCurrentFile(QString()); } } void MainWindow::open() { if (maybeSave()) { QString fileName = QFileDialog::getOpenFileName(this); if (!fileName.isEmpty()) { loadFile(fileName); } } } bool MainWindow::save() { if (curFile.isEmpty()) { return saveAs(); } else { return saveFile(curFile); } } bool MainWindow::saveAs() { QFileDialog dialog(this); dialog.setWindowModality(Qt::WindowModal); dialog.setAcceptMode(QFileDialog::AcceptSave); if (dialog.exec()!=QDialog::Accepted) { return false; } return saveFile(dialog.selectedFiles().first()); } void MainWindow::about() { QMessageBox::about(this, "About Application", "The <b>Application</b> example demonstrates how to " "write modern GUI applications using Qt, with a menu bar, " "toolbars, and a status bar."); } void MainWindow::documentWasModified() { setWindowModified(textEdit->document()->isModified()); } void MainWindow::commitData(QSessionManager &mananger) { if (mananger.allowsInteraction()) { if (!maybeSave()) { mananger.cancel(); } } else { if (textEdit->document()->isModified()) { save(); } } } void MainWindow::createActions() { QMenu* fileMenu = menuBar()->addMenu("&File"); QToolBar* fileToolBar = addToolBar("File"); //new const QIcon newIcon = QIcon::fromTheme("document-new",QIcon(":/images/new.png")); QAction *newAct = new QAction(newIcon, "&New", this); newAct->setShortcut(QKeySequence::New); newAct->setStatusTip("Create a new file"); connect(newAct, &QAction::triggered, this, &MainWindow::newFile); fileMenu->addAction(newAct); fileToolBar->addAction(newAct); //open const QIcon openIcon = QIcon::fromTheme("document-open", QIcon(":/images/open.png")); QAction *openAct = new QAction(openIcon, "&Open", this); openAct->setShortcut(QKeySequence::Open); openAct->setStatusTip("Open an existing file"); connect(openAct, &QAction::triggered, this, &MainWindow::open); fileMenu->addAction(openAct); fileToolBar->addAction(openAct); //save const QIcon saveIcon = QIcon::fromTheme("document-save", QIcon(":/images/save.png")); QAction *saveAct = new QAction(saveIcon, "&Save", this); saveAct->setShortcut(QKeySequence::Save); saveAct->setStatusTip("Save the document to disk"); connect(saveAct, &QAction::triggered, this, &MainWindow::save); fileMenu->addAction(saveAct); fileToolBar->addAction(saveAct); //Saveas const QIcon saveAsIcon = QIcon::fromTheme("document-save-as"); QAction *saveAsAct = fileMenu->addAction(saveAsIcon, "Save &As..", this,&MainWindow::saveAs); //fileToolBar->addAction(saveAsAct); fileMenu->addSeparator(); //exit const QIcon exitIcon = QIcon::fromTheme("document-exit"); QAction *exitAct = fileMenu->addAction(exitIcon, "&Exit", this,&QWidget::close); exitAct->setShortcut(QKeySequence::Quit); exitAct->setStatusTip("Exit the application"); QMenu* editMenu = menuBar()->addMenu("&Edit"); QToolBar *editToolBar = addToolBar("Edit"); #ifndef QT_NO_CLIPBOARD const QIcon cutIcon = QIcon::fromTheme("edit-cut", QIcon(":/images/cut.png")); QAction *cutAct = new QAction(cutIcon, "&Cut", this); cutAct->setShortcut(QKeySequence::Cut); cutAct->setStatusTip("Cut the current slection's conentents to the clipboard"); connect(cutAct, &QAction::triggered, textEdit,&QPlainTextEdit::cut); editMenu->addAction(cutAct); editToolBar->addAction(cutAct); const QIcon copyIcon = QIcon::fromTheme("edit-copy", QIcon(":/images/copy.png")); QAction *copyAct = new QAction(copyIcon, tr("&Copy"), this); copyAct->setShortcuts(QKeySequence::Copy); copyAct->setStatusTip(tr("Copy the current selection's contents to the " "clipboard")); connect(copyAct, &QAction::triggered, textEdit, &QPlainTextEdit::copy); editMenu->addAction(copyAct); editToolBar->addAction(copyAct); const QIcon pasteIcon = QIcon::fromTheme("edit-paste", QIcon(":/images/paste.png")); QAction *pasteAct = new QAction(pasteIcon, tr("&Paste"), this); pasteAct->setShortcuts(QKeySequence::Paste); pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current " "selection")); connect(pasteAct, &QAction::triggered, textEdit, &QPlainTextEdit::paste); editMenu->addAction(pasteAct); editToolBar->addAction(pasteAct); menuBar()->addSeparator(); #endif QMenu *helpMenu = menuBar()->addMenu(tr("&Help")); QAction *aboutAct = helpMenu->addAction(tr("&About"), this, &MainWindow::about); aboutAct->setStatusTip(tr("Show the application's About box")); QAction *aboutQtAct = helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt); aboutQtAct->setStatusTip(tr("Show the Qt library's About box")); #ifndef QT_NO_CLIPBOARD cutAct->setEnabled(false); copyAct->setEnabled(false); connect(textEdit, &QPlainTextEdit::copyAvailable, cutAct, &QAction::setEnabled); connect(textEdit, &QPlainTextEdit::copyAvailable, copyAct, &QAction::setEnabled); #endif // !QT_NO_CLIPBOARD } void MainWindow::createStatusBar() { statusBar()->showMessage("Ready"); } void MainWindow::readSettings() { QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName()); const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray(); if (geometry.isEmpty()) { const QRect availabelGeometry = QApplication::desktop()->availableGeometry(this); resize(availabelGeometry.width() / 3, availabelGeometry.height() / 2); move((availabelGeometry.width() - width()) / 2, (availabelGeometry.height() - height()) / 2); } else { restoreGeometry(geometry); } } void MainWindow::writeSettings() { QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName()); settings.setValue("geometry", saveGeometry()); } bool MainWindow::maybeSave() { if (!textEdit->document()->isModified()) { return true; } const QMessageBox::StandardButton ret = QMessageBox::warning(this, "Application", "The document has been modified.\n Do you want to save your changes",QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel); switch (ret) { case QMessageBox::Yes: return save(); case QMessageBox::Cancel: return false; default: break; } return true; } bool MainWindow::saveFile(const QString& filename) { QFile file(filename); if (!file.open(QIODevice::WriteOnly|QFile::Text)) { QMessageBox::warning(this, "application", tr("cannot write file %1\n%2").arg(QDir::toNativeSeparators(filename), file.errorString())); return false; } QTextStream out(&file); QApplication::setOverrideCursor(Qt::WaitCursor); out << textEdit->toPlainText(); QApplication::restoreOverrideCursor(); setCurrentFile(filename); statusBar()->showMessage("file saved", 2000); return true; } void MainWindow::setCurrentFile(const QString& filename) { curFile = filename; textEdit->document()->setModified(false); setWindowModified(false); QString shownName = curFile; if (curFile.isEmpty()) { shownName = "untitled.txt"; } setWindowFilePath(shownName); } QString MainWindow::strippedName(const QString& fullFilename) { return QFileInfo(fullFilename).fileName(); }
28.359589
212
0.728777
[ "geometry" ]
1b6436c4df546c621adef7743536e5f31dd094f7
680
hpp
C++
src/final/__unused/StereoCalibration.hpp
messo/diploma
e4fcf947482eec77d7426e97563a0d55d266bf2e
[ "MIT" ]
1
2016-03-08T19:19:39.000Z
2016-03-08T19:19:39.000Z
src/final/__unused/StereoCalibration.hpp
messo/diploma
e4fcf947482eec77d7426e97563a0d55d266bf2e
[ "MIT" ]
null
null
null
src/final/__unused/StereoCalibration.hpp
messo/diploma
e4fcf947482eec77d7426e97563a0d55d266bf2e
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <iostream> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "../camera/StereoCamera.hpp" class StereoCamera; class StereoCalibration { std::vector<cv::Mat> images; cv::Size imageSize; public: cv::Mat cameraMatrix[2], distCoeffs[2]; cv::Mat R, T, Q; cv::Mat rmap[2][2]; cv::Mat P1, P2, E, F; cv::Rect validRoiLeft, validRoiRight; StereoCalibration() { }; StereoCalibration(const std::string &intrinsics, const std::string &extrinsics); void acquireFrames(StereoCamera &stereoCamera); void calibrate(); };
19.428571
84
0.683824
[ "vector" ]
1b697986f6bc684893b261bed37b4eb985fcded0
7,781
cpp
C++
src/core/impl/graph/var_node_mem_mgr/static_mem_alloc/interval_move.cpp
jonrzhang/MegEngine
94b72022156a068d3e87bceed7e1c7ae77dada16
[ "Apache-2.0" ]
3
2020-10-23T06:33:57.000Z
2020-10-23T06:34:06.000Z
src/core/impl/graph/var_node_mem_mgr/static_mem_alloc/interval_move.cpp
yang-shuohao/MegEngine
2e8742086563ea442c357b14560245c54e0aa0a3
[ "Apache-2.0" ]
null
null
null
src/core/impl/graph/var_node_mem_mgr/static_mem_alloc/interval_move.cpp
yang-shuohao/MegEngine
2e8742086563ea442c357b14560245c54e0aa0a3
[ "Apache-2.0" ]
1
2022-02-21T10:41:55.000Z
2022-02-21T10:41:55.000Z
/** * \file src/core/impl/graph/var_node_mem_mgr/static_mem_alloc/interval_move.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "./impl.h" #include "./interval_move.h" #if !MGB_BUILD_SLIM_SERVING #include <algorithm> #include <cstring> using namespace mgb; using namespace mgb::cg; void StaticMemAllocIntervalMove::do_solve() { m_peak = 0; m_interval_extra.resize(m_interval.size()); // extend overwritten intervals and align sizes for (auto i: m_interval) { if (i->is_overwrite_root()) i->size = align(i->size); else update_max(i->overwrite_dest_root()->time_end, i->time_end); } sort_intervals(); IntervalPtrArray conflict; for (size_t cur_idx = 0; cur_idx < m_interval.size(); ++ cur_idx) { Interval* cur = m_interval[cur_idx]; if (!cur->is_overwrite_root()) { continue; } conflict.clear(); for (size_t i = 0; i < cur_idx; i ++) if (m_interval[i]->is_overwrite_root() && m_interval[i]->time_overlap(*cur)) { conflict.push_back(m_interval[i]); } insert_interval(*cur, conflict); m_interval_extra[cur->id].move_conflict.clear(); for (auto i: conflict) { mgb_assert(!cur->addr_overlap(*i), "detected conflict: cur=[%zu, %zu)@[%zu, %zu) " "conflict=[%zu, %zu)@[%zu, %zu)", cur->addr_begin, cur->addr_end(), cur->time_begin, cur->time_end, i->addr_begin, i->addr_end(), i->time_begin, i->time_end); if (i->addr_begin < cur->addr_begin) { m_interval_extra[i->id].move_conflict.push_back(cur); mgb_assert(i->addr_end() <= cur->addr_begin); } else { m_interval_extra[cur->id].move_conflict.push_back(i); mgb_assert(cur->addr_end() <= i->addr_begin); } } } for (auto i: m_interval) { if (!i->is_overwrite_root()) { mgb_assert(i->addr_begin == INVALID); i->addr_begin = i->overwrite_dest_root()->addr_begin + i->offset_in_overwrite_dest_root(); } } } void StaticMemAllocIntervalMove::sort_intervals() { auto cmp = [](const Interval *a, const Interval *b) { auto t0 = a->time_length(), t1 = b->time_length(); return (t0 > t1) || (t0 == t1 && (a->time_begin < b->time_begin || (a->time_begin == b->time_begin && a->size > b->size))); }; std::sort(m_interval.begin(), m_interval.end(), cmp); } void StaticMemAllocIntervalMove::insert_interval( Interval &dest, const IntervalPtrArray &conflict) { if (conflict.empty()) { dest.addr_begin = 0; update_max(m_peak, dest.addr_end()); return; } size_t peak_incr, orig_peak = m_peak; std::tie(dest.addr_begin, peak_incr) = find_best_fit(conflict, dest.size); auto dest_end = dest.addr_end(); update_max(m_peak, dest_end); for (auto i: conflict) { if (i->addr_end() > dest.addr_begin) move_interval_higher(i, dest_end); mgb_assert(!i->addr_overlap(dest)); } mgb_assert(m_peak == orig_peak + peak_incr); } std::pair<size_t, size_t> StaticMemAllocIntervalMove::find_best_fit( const IntervalPtrArray &conflict, size_t dest_size) { ++ m_move_space_size_version; size_t best_fit_peak_add = std::numeric_limits<size_t>::max(), best_fit_move = best_fit_peak_add, // min move for conflicted best_fit_space = best_fit_peak_add, // remaining size in free chunk best_fit_addr = INVALID; /* * First minimize peak_add. If it could be zero, minimize space; otherwise * miminize move */ auto consider_free_chunk = [&](size_t free_begin, size_t free_end) { mgb_assert(free_end >= free_begin); size_t free_size = free_end - free_begin; if (free_size >= dest_size) { size_t remain = free_size - dest_size; if (remain < best_fit_space) { best_fit_peak_add = best_fit_move = 0; best_fit_space = remain; best_fit_addr = free_begin; } } else { size_t chunk_end_incr = dest_size - free_size, peak_add = std::max(free_begin + dest_size, m_peak) - m_peak; for (auto i: conflict) { if (i->addr_end() <= free_begin) continue; mgb_assert(free_end <= i->addr_begin); size_t max_dist = i->addr_begin - free_end + get_move_space_size(i); if (max_dist < chunk_end_incr) update_max(peak_add, chunk_end_incr - max_dist); } if (peak_add < best_fit_peak_add || (peak_add == best_fit_peak_add && chunk_end_incr < best_fit_move)) { best_fit_peak_add = peak_add; best_fit_move = chunk_end_incr; best_fit_addr = free_begin; } } }; auto merged = merge_interval_by_addr(conflict); size_t prev_end = 0; for (auto &&i: merged) { consider_free_chunk(prev_end, i.begin); prev_end = i.end; } consider_free_chunk(prev_end, m_peak); mgb_assert(best_fit_addr != INVALID); return {best_fit_addr, best_fit_peak_add}; } std::vector<StaticMemAllocIntervalMove::MergedInterval> StaticMemAllocIntervalMove::merge_interval_by_addr( const IntervalPtrArray &intervals) { std::vector<MergedInterval> result; std::vector<std::pair<size_t, size_t>> addrs; // addr_begin, addr_end for (auto i: intervals) { addrs.emplace_back(i->addr_begin, i->addr_end()); } std::sort(addrs.begin(), addrs.end()); MergedInterval *current = nullptr; for (auto &&i: addrs) { if (!current || i.first >= current->end) { result.emplace_back(); current = &result.back(); current->begin = i.first; current->end = i.second; } else { update_min(current->begin, i.first); update_max(current->end, i.second); } } return result; } size_t StaticMemAllocIntervalMove::get_move_space_size(Interval *interval) { auto &&extra_info = m_interval_extra[interval->id]; auto &&rec = extra_info.move_space_size; if (rec.version == m_move_space_size_version) return rec.size; auto end = interval->addr_end(); size_t sz = m_peak - end; for (auto i: extra_info.move_conflict) { mgb_assert(i->addr_begin >= end); size_t psize = get_move_space_size(i) + i->addr_begin - end; update_min(sz, psize); } rec.version = m_move_space_size_version; rec.size = sz; return sz; } void StaticMemAllocIntervalMove::move_interval_higher( Interval *interval, size_t prev_end) { if (interval->addr_begin >= prev_end) return; interval->addr_begin = prev_end; size_t cur_end = interval->addr_end(); update_max(m_peak, cur_end); for (auto i: m_interval_extra[interval->id].move_conflict) { move_interval_higher(i, cur_end); mgb_assert(!interval->addr_overlap(*i)); } } #endif // !MGB_BUILD_SLIM_SERVING // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
33.252137
89
0.600565
[ "vector" ]
1b758f37f67a8ab232faf365182b0051cceed0ce
2,871
cpp
C++
src/autoxtime/codec/FarmtekCodec.cpp
nmaludy/autoxtime
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
[ "Apache-2.0" ]
null
null
null
src/autoxtime/codec/FarmtekCodec.cpp
nmaludy/autoxtime
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
[ "Apache-2.0" ]
4
2021-02-23T20:56:42.000Z
2021-04-03T01:56:08.000Z
src/autoxtime/codec/FarmtekCodec.cpp
nmaludy/autoxtime
c4c2603a6990ef3cfddaa1bfab14e48bc81ec2a3
[ "Apache-2.0" ]
null
null
null
#include <autoxtime/codec/FarmtekCodec.h> #include <autoxtime/transport/ITransport.h> #include <autoxtime/log/Log.h> AUTOXTIME_NAMESPACE_BEG // 13 byte fixed format message // First character is either B or R (although some modes of the Polaris unit may also give you a S and F, Start finish) // 2 signals are sent when an object passes completely through a light beam. // The beam break timestamp of the is sent with "B" // then the beam restore timestamp is sent with "R" // The 2nd character is a number 1-4 representing the eye number // Character 3-12 is a integer of the current "time" of the Polaris box when the signal is received from the eye // Character 13 is a carriage return. which is ASCII decimal (13) or hex "D" // // Setting this to 12 because the last byte is a CR that we are splitting on const int FARMTEK_MSG_EXPECTED_SIZE = 12; FarmtekCodec::FarmtekCodec(ITransport* pTransport, QObject* pParent) : QObject(pParent), mpTransport(pTransport), mDataBuffer() { connect(mpTransport, &ITransport::dataRead, this, &FarmtekCodec::handleDataRead); } void FarmtekCodec::handleDataRead(const QByteArray& data) { // for (int i = 0; i < read_data.size(); ++i) { // AXT_INFO << "handleReadyRead(): read data[" << i << "]: " << (int)read_data[i]; // } mDataBuffer.append(data); // yes, only search the newest line added so we don't have to scan the entire buffer // for stuff we already know doesn't have a newline // TODO make this more efficient so we're not scanning multiple times // TODO should we split up the data here or should we just pass it on to the codec "raw" // then let the codec buffer and figure it out? if (data.contains('\r')) { QList<QByteArray> lines = mDataBuffer.split('\r'); mDataBuffer = lines.takeLast(); for (const QByteArray& line : lines) { if (line.size() != FARMTEK_MSG_EXPECTED_SIZE) { AXT_WARNING << "Received Farmtek data that is not the correct size. " << "Expected=" << FARMTEK_MSG_EXPECTED_SIZE << " Received=" << line.size() << " Data=" << line; continue; } AXT_INFO << "Received a Farmtek string of correct size: " << line; // byte 0 = msg type, either "B" for break or "R" for reset char msg_type = line[0]; // byte 1 = string containing "1", "2", "3", "4" to indicate eye number int eye = QString(line[1]).toInt(); // bytes 2-11 = timestamp in 0.125us resolution QString timestamp_str = line.mid(2, 10); double timestamp_125us = timestamp_str.toDouble(); double timestamp_s = timestamp_125us / 8000.0; AXT_INFO << "msg_type=" << msg_type << " eye=" << eye << " timestamp_str=" << timestamp_str << " timestamp_s=" << timestamp_s; } } } AUTOXTIME_NAMESPACE_END
37.776316
119
0.656566
[ "object" ]
1b782469e18c89d097d754057bc179dee3befb0e
3,425
cpp
C++
src/cppad.git/cppad_ipopt/example/ode_check.cpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
1
2019-11-05T02:23:47.000Z
2019-11-05T02:23:47.000Z
src/cppad.git/cppad_ipopt/example/ode_check.cpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
null
null
null
src/cppad.git/cppad_ipopt/example/ode_check.cpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
1
2019-11-05T02:23:51.000Z
2019-11-05T02:23:51.000Z
/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell CppAD is distributed under the terms of the Eclipse Public License Version 2.0. This Source Code may also be made available under the following Secondary License when the conditions for such availability set forth in the Eclipse Public License, Version 2.0 are satisfied: GNU General Public License, Version 2.0 or later. ---------------------------------------------------------------------------- */ /* $begin ipopt_nlp_ode_check.cpp$$ $section Correctness Check for Both Simple and Fast Representations$$ $srcfile%cppad_ipopt/example/ode_check.cpp%0%// BEGIN C++%// END C++%1%$$ $end */ // BEGIN C++ # include "ode_run.hpp" bool ode_check(const SizeVector& N, const NumberVector& x) { bool ok = true; size_t i, j; // number of components of x corresponding to values for y size_t ny_inx = x.size() - Na; // compute the partial sums of the number of grid points // and the maximum step size for the trapezoidal approximation SizeVector S(Nz+1); S[0] = 0; Number max_step = 0.; for(i = 1; i <= Nz; i++) { S[i] = S[i-1] + N[i]; max_step = std::max(max_step, Number(s[i] - s[i-1]) / Number(N[i]) ); } // split out return values NumberVector a(Na), y_0(Ny), y_1(Ny), y_2(Ny); for(j = 0; j < Na; j++) a[j] = x[ny_inx+j]; for(j = 0; j < Ny; j++) { y_0[j] = x[j]; y_1[j] = x[Ny + j]; y_2[j] = x[2 * Ny + j]; } // Check some of the optimal a value Number rel_tol = max_step * max_step; Number abs_tol = rel_tol; Number check_a[] = {a0, a1, a2}; // see the y_one function for(j = 0; j < Na; j++) { ok &= CppAD::NearEqual( check_a[j], a[j], rel_tol, abs_tol ); } // check accuarcy of constraint equations rel_tol = 1e-9; abs_tol = 1e-9; // check the initial value constraint NumberVector F = eval_F(a); for(j = 0; j < Ny; j++) ok &= CppAD::NearEqual(F[j], y_0[j], rel_tol, abs_tol); // check the first trapezoidal equation NumberVector G_0 = eval_G(y_0, a); NumberVector G_1 = eval_G(y_1, a); Number dt = (s[1] - s[0]) / Number(N[1]); Number check; for(j = 0; j < Ny; j++) { check = y_1[j] - y_0[j] - (G_1[j]+G_0[j])*dt/2; ok &= CppAD::NearEqual( check, 0., rel_tol, abs_tol); } // // check the second trapezoidal equation NumberVector G_2 = eval_G(y_2, a); if( N[1] == 1 ) dt = (s[2] - s[1]) / Number(N[2]); for(j = 0; j < Ny; j++) { check = y_2[j] - y_1[j] - (G_2[j]+G_1[j])*dt/2; ok &= CppAD::NearEqual( check, 0., rel_tol, abs_tol); } // // check the objective function (specialized to this case) check = 0.; NumberVector y_i(Ny); for(size_t k = 0; k < Nz; k++) { for(j = 0; j < Ny; j++) y_i[j] = x[S[k+1] * Ny + j]; check += eval_H<Number>(k + 1, y_i, a); } Number obj_value = 0.; // optimal object (no noise in simulation) ok &= CppAD::NearEqual(check, obj_value, rel_tol, abs_tol); // Use this empty namespace function to avoid warning that it is not used static size_t ode_check_count = 0; ode_check_count++; ok &= count_eval_r() == ode_check_count; return ok; } // END C++
31.422018
79
0.554453
[ "object" ]
1b7cd78be6176d040300e1cc0f6d10fe8f19a54e
25,023
cpp
C++
test/hipcub/test_hipcub_util_ptx.cpp
lawruble13/hipCUB
3c8f379fe78d5317a319cb53e09bea3a04c3e9a5
[ "BSD-3-Clause" ]
null
null
null
test/hipcub/test_hipcub_util_ptx.cpp
lawruble13/hipCUB
3c8f379fe78d5317a319cb53e09bea3a04c3e9a5
[ "BSD-3-Clause" ]
null
null
null
test/hipcub/test_hipcub_util_ptx.cpp
lawruble13/hipCUB
3c8f379fe78d5317a319cb53e09bea3a04c3e9a5
[ "BSD-3-Clause" ]
null
null
null
// MIT License // // Copyright (c) 2017-2020 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 "common_test_header.hpp" // Custom structure struct custom_notaligned { short i; double d; float f; unsigned int u; HIPCUB_HOST_DEVICE custom_notaligned() {}; HIPCUB_HOST_DEVICE ~custom_notaligned() {}; }; HIPCUB_HOST_DEVICE inline bool operator==(const custom_notaligned& lhs, const custom_notaligned& rhs) { return lhs.i == rhs.i && lhs.d == rhs.d && lhs.f == rhs.f &&lhs.u == rhs.u; } // Custom structure aligned to 16 bytes struct custom_16aligned { int i; unsigned int u; float f; HIPCUB_HOST_DEVICE custom_16aligned() {}; HIPCUB_HOST_DEVICE ~custom_16aligned() {}; } __attribute__((aligned(16))); inline HIPCUB_HOST_DEVICE bool operator==(const custom_16aligned& lhs, const custom_16aligned& rhs) { return lhs.i == rhs.i && lhs.f == rhs.f && lhs.u == rhs.u; } // Params for tests template<class T, unsigned int LogicalWarpSize> struct params { using type = T; static constexpr unsigned int logical_warp_size = LogicalWarpSize; }; template<class Params> class HipcubUtilPtxTests : public ::testing::Test { public: using type = typename Params::type; static constexpr unsigned int logical_warp_size = Params::logical_warp_size; }; typedef ::testing::Types< params<int, 32>, params<int, 16>, params<int, 8>, params<int, 4>, params<int, 2>, params<float, HIPCUB_WARP_SIZE_32>, params<double, HIPCUB_WARP_SIZE_32>, params<unsigned char, HIPCUB_WARP_SIZE_32> #ifdef __HIP_PLATFORM_HCC__ ,params<float, HIPCUB_WARP_SIZE_64>, params<double, HIPCUB_WARP_SIZE_64>, params<unsigned char, HIPCUB_WARP_SIZE_64> #endif > UtilPtxTestParams; TYPED_TEST_SUITE(HipcubUtilPtxTests, UtilPtxTestParams); template<unsigned int LOGICAL_WARP_THREADS, class T> __global__ void shuffle_up_kernel(T* data, unsigned int src_offset) { const unsigned int index = (hipBlockIdx_x * hipBlockDim_x) + hipThreadIdx_x; T value = data[index]; // first_thread argument is ignored in hipCUB with rocPRIM-backend const unsigned int first_thread = 0; // Using mask is not supported in rocPRIM, so we don't test other masks const unsigned int member_mask = 0xffffffff; value = hipcub::ShuffleUp<LOGICAL_WARP_THREADS>( value, src_offset, first_thread, member_mask ); data[index] = value; } TYPED_TEST(HipcubUtilPtxTests, ShuffleUp) { using T = typename TestFixture::type; constexpr unsigned int logical_warp_size = TestFixture::logical_warp_size; const unsigned int current_device_warp_size = HIPCUB_HOST_WARP_THREADS; const size_t hardware_warp_size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? HIPCUB_WARP_SIZE_32 : HIPCUB_WARP_SIZE_64; const size_t size = hardware_warp_size; if (logical_warp_size > current_device_warp_size) { printf("Unsupported test warp size: %d Current device warp size: %d. Skipping test\n", logical_warp_size, current_device_warp_size); GTEST_SKIP(); } for (size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++) { unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count]; SCOPED_TRACE(testing::Message() << "with seed= " << seed_value); // Generate input auto input = test_utils::get_random_data<T>(size, T(-100), T(100), seed_value); std::vector<T> output(input.size()); auto src_offsets = test_utils::get_random_data<unsigned int>( std::max<size_t>(1, logical_warp_size/2), 1U, std::max<unsigned int>(1, logical_warp_size - 1), seed_value + seed_value_addition ); T* device_data; HIP_CHECK( test_common_utils::hipMallocHelper( &device_data, input.size() * sizeof(typename decltype(input)::value_type) ) ); for(auto src_offset : src_offsets) { SCOPED_TRACE(testing::Message() << "where src_offset = " << src_offset); // Calculate expected results on host std::vector<T> expected(size, 0); for(size_t i = 0; i < input.size()/logical_warp_size; i++) { for(size_t j = 0; j < logical_warp_size; j++) { size_t index = j + logical_warp_size * i; auto up_index = j > src_offset-1 ? index-src_offset : index; expected[index] = input[up_index]; } } // Writing to device memory HIP_CHECK( hipMemcpy( device_data, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Launching kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(shuffle_up_kernel<logical_warp_size, T>), dim3(1), dim3(hardware_warp_size), 0, 0, device_data, src_offset ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); // Read from device memory HIP_CHECK( hipMemcpy( output.data(), device_data, output.size() * sizeof(T), hipMemcpyDeviceToHost ) ); for(size_t i = 0; i < output.size(); i++) { ASSERT_EQ(output[i], expected[i]) << "where index = " << i; } } hipFree(device_data); } } template<unsigned int LOGICAL_WARP_THREADS, class T> __global__ void shuffle_down_kernel(T* data, unsigned int src_offset) { const unsigned int index = (hipBlockIdx_x * hipBlockDim_x) + hipThreadIdx_x; T value = data[index]; // last_thread argument is ignored in hipCUB with rocPRIM-backend const unsigned int last_thread = LOGICAL_WARP_THREADS - 1; // Using mask is not supported in rocPRIM, so we don't test other masks const unsigned int member_mask = 0xffffffff; value = hipcub::ShuffleDown<LOGICAL_WARP_THREADS>( value, src_offset, last_thread, member_mask ); data[index] = value; } TYPED_TEST(HipcubUtilPtxTests, ShuffleDown) { using T = typename TestFixture::type; constexpr unsigned int logical_warp_size = TestFixture::logical_warp_size; const unsigned int current_device_warp_size = HIPCUB_HOST_WARP_THREADS; const size_t hardware_warp_size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? HIPCUB_WARP_SIZE_32 : HIPCUB_WARP_SIZE_64; const size_t size = hardware_warp_size; if (logical_warp_size > current_device_warp_size) { printf("Unsupported test warp size: %d Current device warp size: %d. Skipping test\n", logical_warp_size, current_device_warp_size); GTEST_SKIP(); } for (size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++) { unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count]; SCOPED_TRACE(testing::Message() << "with seed= " << seed_value); // Generate input auto input = test_utils::get_random_data<T>(size, T(-100), T(100), seed_value); std::vector<T> output(input.size()); auto src_offsets = test_utils::get_random_data<unsigned int>( std::max<size_t>(1, logical_warp_size/2), 1U, std::max<unsigned int>(1, logical_warp_size - 1), seed_value + seed_value_addition ); T * device_data; HIP_CHECK( test_common_utils::hipMallocHelper( &device_data, input.size() * sizeof(typename decltype(input)::value_type) ) ); for(auto src_offset : src_offsets) { SCOPED_TRACE(testing::Message() << "where src_offset = " << src_offset); // Calculate expected results on host std::vector<T> expected(size, 0); for(size_t i = 0; i < input.size()/logical_warp_size; i++) { for(size_t j = 0; j < logical_warp_size; j++) { size_t index = j + logical_warp_size * i; auto down_index = j+src_offset < logical_warp_size ? index+src_offset : index; expected[index] = input[down_index]; } } // Writing to device memory HIP_CHECK( hipMemcpy( device_data, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Launching kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(shuffle_down_kernel<logical_warp_size, T>), dim3(1), dim3(hardware_warp_size), 0, 0, device_data, src_offset ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); // Read from device memory HIP_CHECK( hipMemcpy( output.data(), device_data, output.size() * sizeof(T), hipMemcpyDeviceToHost ) ); for(size_t i = 0; i < output.size(); i++) { ASSERT_EQ(output[i], expected[i]) << "where index = " << i; } } hipFree(device_data); } } template<unsigned int LOGICAL_WARP_THREADS, class T> __global__ void shuffle_index_kernel(T* data, int* src_offsets) { const unsigned int index = (hipBlockIdx_x * hipBlockDim_x) + hipThreadIdx_x; T value = data[index]; // Using mask is not supported in rocPRIM, so we don't test other masks const unsigned int member_mask = 0xffffffff; value = hipcub::ShuffleIndex<LOGICAL_WARP_THREADS>( value, src_offsets[hipThreadIdx_x/LOGICAL_WARP_THREADS], member_mask ); data[index] = value; } TYPED_TEST(HipcubUtilPtxTests, ShuffleIndex) { using T = typename TestFixture::type; constexpr unsigned int logical_warp_size = TestFixture::logical_warp_size; const unsigned int current_device_warp_size = HIPCUB_HOST_WARP_THREADS; const size_t hardware_warp_size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? HIPCUB_WARP_SIZE_32 : HIPCUB_WARP_SIZE_64; const size_t size = hardware_warp_size; if (logical_warp_size > current_device_warp_size) { printf("Unsupported test warp size: %d Current device warp size: %d. Skipping test\n", logical_warp_size, current_device_warp_size); GTEST_SKIP(); } for (size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++) { unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count]; SCOPED_TRACE(testing::Message() << "with seed= " << seed_value); // Generate input auto input = test_utils::get_random_data<T>(size, T(-100), T(100), seed_value); std::vector<T> output(input.size()); auto src_offsets = test_utils::get_random_data<int>( hardware_warp_size/logical_warp_size, 0, std::max<int>(1, logical_warp_size - 1), seed_value + seed_value_addition ); // Calculate expected results on host std::vector<T> expected(size, 0); for(size_t i = 0; i < input.size()/logical_warp_size; i++) { int src_index = src_offsets[i]; for(size_t j = 0; j < logical_warp_size; j++) { size_t index = j + logical_warp_size * i; if(src_index >= int(logical_warp_size) || src_index < 0) src_index = index; expected[index] = input[src_index + logical_warp_size * i]; } } // Writing to device memory T* device_data; int * device_src_offsets; HIP_CHECK( test_common_utils::hipMallocHelper( &device_data, input.size() * sizeof(typename decltype(input)::value_type) ) ); HIP_CHECK( test_common_utils::hipMallocHelper( &device_src_offsets, src_offsets.size() * sizeof(typename decltype(src_offsets)::value_type) ) ); HIP_CHECK( hipMemcpy( device_data, input.data(), input.size() * sizeof(typename decltype(input)::value_type), hipMemcpyHostToDevice ) ); HIP_CHECK( hipMemcpy( device_src_offsets, src_offsets.data(), src_offsets.size() * sizeof(typename decltype(src_offsets)::value_type), hipMemcpyHostToDevice ) ); // Launching kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(shuffle_index_kernel<logical_warp_size, T>), dim3(1), dim3(hardware_warp_size), 0, 0, device_data, device_src_offsets ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); // Read from device memory HIP_CHECK( hipMemcpy( output.data(), device_data, output.size() * sizeof(T), hipMemcpyDeviceToHost ) ); for(size_t i = 0; i < output.size(); i++) { ASSERT_EQ(output[i], expected[i]) << "where index = " << i; } hipFree(device_data); hipFree(device_src_offsets); } } TEST(HipcubUtilPtxTests, ShuffleUpCustomStruct) { using T = custom_notaligned; constexpr unsigned int logical_warp_size_32 = HIPCUB_WARP_SIZE_32; constexpr unsigned int logical_warp_size_64 = HIPCUB_WARP_SIZE_64; const unsigned int current_device_warp_size = HIPCUB_HOST_WARP_THREADS; const unsigned int logical_warp_size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? logical_warp_size_32 : logical_warp_size_64; const size_t size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? logical_warp_size_32 : logical_warp_size_64; for (size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++) { unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count]; SCOPED_TRACE(testing::Message() << "with seed= " << seed_value); // Generate data std::vector<double> random_data = test_utils::get_random_data<double>( 4 * size, -100, 100, seed_value ); std::vector<T> input(size); std::vector<T> output(input.size()); for(size_t i = 0; i < 4 * input.size(); i+=4) { input[i/4].i = random_data[i]; input[i/4].d = random_data[i+1]; input[i/4].f = random_data[i+2]; input[i/4].u = random_data[i+3]; } auto src_offsets = test_utils::get_random_data<unsigned int>( std::max<size_t>(1, logical_warp_size/2), 1U, std::max<unsigned int>(1, logical_warp_size - 1), seed_value + seed_value_addition ); T* device_data; HIP_CHECK( test_common_utils::hipMallocHelper( &device_data, input.size() * sizeof(typename decltype(input)::value_type) ) ); for(auto src_offset : src_offsets) { // Calculate expected results on host std::vector<T> expected(size); for(size_t i = 0; i < input.size()/logical_warp_size; i++) { for(size_t j = 0; j < logical_warp_size; j++) { size_t index = j + logical_warp_size * i; auto up_index = j > src_offset-1 ? index-src_offset : index; expected[index] = input[up_index]; } } // Writing to device memory HIP_CHECK( hipMemcpy( device_data, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); if (logical_warp_size == logical_warp_size_32) { // Launching kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(shuffle_up_kernel<logical_warp_size_32, T>), dim3(1), dim3(HIPCUB_WARP_SIZE_32), 0, 0, device_data, src_offset ); } else if (logical_warp_size == logical_warp_size_64) { // Launching kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(shuffle_up_kernel<logical_warp_size_64, T>), dim3(1), dim3(HIPCUB_WARP_SIZE_64), 0, 0, device_data, src_offset ); } HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); // Read from device memory HIP_CHECK( hipMemcpy( output.data(), device_data, output.size() * sizeof(T), hipMemcpyDeviceToHost ) ); for(size_t i = 0; i < output.size(); i++) { ASSERT_EQ(output[i], expected[i]) << "where index = " << i; } } hipFree(device_data); } } TEST(HipcubUtilPtxTests, ShuffleUpCustomAlignedStruct) { using T = custom_16aligned; constexpr unsigned int logical_warp_size_32 = HIPCUB_WARP_SIZE_32; constexpr unsigned int logical_warp_size_64 = HIPCUB_WARP_SIZE_64; const unsigned int current_device_warp_size = HIPCUB_HOST_WARP_THREADS; const unsigned int hardware_warp_size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? HIPCUB_WARP_SIZE_32 : HIPCUB_WARP_SIZE_64; const unsigned int logical_warp_size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? logical_warp_size_32 : logical_warp_size_64; const size_t size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? logical_warp_size_32 : logical_warp_size_64; for (size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++) { unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count]; SCOPED_TRACE(testing::Message() << "with seed= " << seed_value); // Generate data std::vector<double> random_data = test_utils::get_random_data<double>( 3 * size, -100, 100, seed_value ); std::vector<T> input(size); std::vector<T> output(input.size()); for(size_t i = 0; i < 3 * input.size(); i+=3) { input[i/3].i = random_data[i]; input[i/3].u = random_data[i+1]; input[i/3].f = random_data[i+2]; } auto src_offsets = test_utils::get_random_data<unsigned int>( std::max<size_t>(1, logical_warp_size/2), 1U, std::max<unsigned int>(1, logical_warp_size - 1), seed_value + seed_value_addition ); T* device_data; HIP_CHECK( test_common_utils::hipMallocHelper( &device_data, input.size() * sizeof(typename decltype(input)::value_type) ) ); for(auto src_offset : src_offsets) { // Calculate expected results on host std::vector<T> expected(size); for(size_t i = 0; i < input.size()/logical_warp_size; i++) { for(size_t j = 0; j < logical_warp_size; j++) { size_t index = j + logical_warp_size * i; auto up_index = j > src_offset-1 ? index-src_offset : index; expected[index] = input[up_index]; } } // Writing to device memory HIP_CHECK( hipMemcpy( device_data, input.data(), input.size() * sizeof(T), hipMemcpyHostToDevice ) ); if (logical_warp_size == logical_warp_size_32) { // Launching kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(shuffle_up_kernel<logical_warp_size_32, T>), dim3(1), dim3(hardware_warp_size), 0, 0, device_data, src_offset ); } else if (logical_warp_size == logical_warp_size_64) { // Launching kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(shuffle_up_kernel<logical_warp_size_64, T>), dim3(1), dim3(hardware_warp_size), 0, 0, device_data, src_offset ); } HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); // Read from device memory HIP_CHECK( hipMemcpy( output.data(), device_data, output.size() * sizeof(T), hipMemcpyDeviceToHost ) ); for(size_t i = 0; i < output.size(); i++) { ASSERT_EQ(output[i], expected[i]) << "where index = " << i; } } hipFree(device_data); } } __global__ void warp_id_kernel(unsigned int* output) { const unsigned int index = (hipBlockIdx_x * hipBlockDim_x) + hipThreadIdx_x; output[index] = hipcub::WarpId(); } TEST(HipcubUtilPtxTests, WarpId) { const unsigned int current_device_warp_size = HIPCUB_HOST_WARP_THREADS; const unsigned int hardware_warp_size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? HIPCUB_WARP_SIZE_32 : HIPCUB_WARP_SIZE_64; const size_t block_size = (current_device_warp_size == HIPCUB_WARP_SIZE_32) ? 4 * HIPCUB_WARP_SIZE_32 : 4 * HIPCUB_WARP_SIZE_64; const size_t size = 16 * block_size; std::vector<unsigned int> output(size); unsigned int* device_output; HIP_CHECK( test_common_utils::hipMallocHelper( &device_output, output.size() * sizeof(unsigned int) ) ); // Launching kernel hipLaunchKernelGGL( warp_id_kernel, dim3(size/block_size), dim3(block_size), 0, 0, device_output ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); // Read from device memory HIP_CHECK( hipMemcpy( output.data(), device_output, output.size() * sizeof(unsigned int), hipMemcpyDeviceToHost ) ); std::vector<size_t> warp_ids(block_size/hardware_warp_size, 0); for(size_t i = 0; i < output.size()/hardware_warp_size; i++) { auto prev = output[i * hardware_warp_size]; for(size_t j = 0; j < hardware_warp_size; j++) { auto index = j + i * hardware_warp_size; // less than number of warps in thread block ASSERT_LT(output[index], block_size/hardware_warp_size); ASSERT_GE(output[index], 0U); // > 0 ASSERT_EQ(output[index], prev); // all in warp_ids in warp are the same } warp_ids[prev]++; } // Check if each warp_id appears the same number of times. for(auto warp_id_no : warp_ids) { ASSERT_EQ(warp_id_no, size/block_size); } }
35.046218
139
0.589857
[ "vector" ]
1b8295b4b0c7d943becd617a36192ed7a61e6ad5
437
cpp
C++
algorithmic_toolbox/greedy_algorithms/different_summands.cpp
thegauravparmar/dsa-coursera-assignments
4e5261588547ea7a9ea139010ecb9a2c69ddf333
[ "MIT" ]
null
null
null
algorithmic_toolbox/greedy_algorithms/different_summands.cpp
thegauravparmar/dsa-coursera-assignments
4e5261588547ea7a9ea139010ecb9a2c69ddf333
[ "MIT" ]
null
null
null
algorithmic_toolbox/greedy_algorithms/different_summands.cpp
thegauravparmar/dsa-coursera-assignments
4e5261588547ea7a9ea139010ecb9a2c69ddf333
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long #define pb push_back #define print(v) \ for (auto &i : v) \ cout << i << ' ' using namespace std; typedef vector<int> ints; int32_t main() { int n, c(1); cin >> n; ints v; while (n) { v.pb(c); n -= c++; if (c > n) { v.back() += n; break; } } cout << v.size() << endl; print(v); return 0; }
18.208333
29
0.439359
[ "vector" ]
1b8436748e8d26d9c493e3200dbde414bf34b449
1,036
cpp
C++
src/process.cpp
claymore2000/CppND-System-Monitor
e978d41a913fcf50936cf279a62b82daf782215b
[ "MIT" ]
null
null
null
src/process.cpp
claymore2000/CppND-System-Monitor
e978d41a913fcf50936cf279a62b82daf782215b
[ "MIT" ]
null
null
null
src/process.cpp
claymore2000/CppND-System-Monitor
e978d41a913fcf50936cf279a62b82daf782215b
[ "MIT" ]
null
null
null
#include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include "process.h" #include "linux_parser.h" using std::string; using std::to_string; using std::vector; // "factory" method void Process::ObtainInfo(int tPid) { SetPid(tPid); SetUser(LinuxParser::User(LinuxParser::Uid(tPid))); SetRam(LinuxParser::Ram(tPid)); SetUpTime(LinuxParser::UpTime(tPid)); SetCmdline(LinuxParser::Command(tPid)); SetCpuUtilization(LinuxParser::ActiveJiffies(tPid)); } int Process::Pid() { return pid_; } float Process::CpuUtilization() { return cpu_; } string Process::Command() { return cmdline_; } string Process::Ram() const { return ram_; } string Process::User() { return user_; } long int Process::UpTime() { return uptime_; } bool Process::operator>(Process const& a) const { if ((Ram() == "") || (stoi(Ram()) < stoi(a.Ram()))) return false; return true; } bool Process::operator<(Process const& a) const { if (stoi(Ram()) < stoi(a.Ram())) return true; return false; }
20.313725
54
0.682432
[ "vector" ]
1b86c738bbb62d54b6169dca0d5de4e4759be1cd
3,317
hpp
C++
include/openpose/core/macros.hpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
43
2018-07-07T02:40:22.000Z
2020-12-17T08:18:18.000Z
include/openpose/core/macros.hpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
2
2018-10-09T13:46:10.000Z
2020-07-29T19:20:29.000Z
include/openpose/core/macros.hpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
26
2017-08-26T04:08:26.000Z
2022-02-08T09:34:05.000Z
#ifndef OPENPOSE_CORE_MACROS_HPP #define OPENPOSE_CORE_MACROS_HPP #include <memory> // std::shared_ptr #include <ostream> #include <string> #include <vector> // OpenPose name and version const std::string OPEN_POSE_NAME_STRING = "OpenPose"; const std::string OPEN_POSE_VERSION_STRING = "1.3.0"; const std::string OPEN_POSE_NAME_AND_VERSION = OPEN_POSE_NAME_STRING + " " + OPEN_POSE_VERSION_STRING; // #define COMMERCIAL_LICENSE #ifndef _WIN32 #define OP_API #elif defined OP_EXPORTS #define OP_API __declspec(dllexport) #else #define OP_API __declspec(dllimport) #endif //Disable some Windows Warnings #ifdef _WIN32 #pragma warning ( disable : 4251 ) // XXX needs to have dll-interface to be used by clients of class YYY #pragma warning( disable: 4275 ) // non dll-interface structXXX used as base #endif #define UNUSED(unusedVariable) (void)(unusedVariable) #define DELETE_COPY(className) \ className(const className&) = delete; \ className& operator=(const className&) = delete // Instantiate a class with all the basic types #define COMPILE_TEMPLATE_BASIC_TYPES_CLASS(className) COMPILE_TEMPLATE_BASIC_TYPES(className, class) #define COMPILE_TEMPLATE_BASIC_TYPES_STRUCT(className) COMPILE_TEMPLATE_BASIC_TYPES(className, struct) #define COMPILE_TEMPLATE_BASIC_TYPES(className, classType) \ template classType OP_API className<char>; \ template classType OP_API className<signed char>; \ template classType OP_API className<short>; \ template classType OP_API className<int>; \ template classType OP_API className<long>; \ template classType OP_API className<long long>; \ template classType OP_API className<unsigned char>; \ template classType OP_API className<unsigned short>; \ template classType OP_API className<unsigned int>; \ template classType OP_API className<unsigned long>; \ template classType OP_API className<unsigned long long>; \ template classType OP_API className<float>; \ template classType OP_API className<double>; \ template classType OP_API className<long double> /** * cout operator overload calling toString() function * @return std::ostream containing output from toString() */ #define OVERLOAD_C_OUT(className) \ template<typename T> std::ostream &operator<<(std::ostream& ostream, const op::className<T>& obj) \ { \ ostream << obj.toString(); \ return ostream; \ } // Instantiate a class with float and double specifications #define COMPILE_TEMPLATE_FLOATING_TYPES_CLASS(className) COMPILE_TEMPLATE_FLOATING_TYPES(className, class) #define COMPILE_TEMPLATE_FLOATING_TYPES_STRUCT(className) COMPILE_TEMPLATE_FLOATING_TYPES(className, struct) #define COMPILE_TEMPLATE_FLOATING_TYPES(className, classType) \ char gInstantiationGuard##className; \ template classType OP_API className<float>; \ template classType OP_API className<double> // PIMPL does not work if function arguments need the 3rd-party class. Alternative: // stackoverflow.com/questions/13978775/how-to-avoid-include-dependency-to-external-library?answertab=active#tab-top struct dim3; namespace caffe { template <typename T> class Blob; } namespace boost { template <typename T> class shared_ptr; // E.g., boost::shared_ptr<caffe::Blob<float>> } #endif // OPENPOSE_CORE_MACROS_HPP
38.569767
116
0.770576
[ "vector" ]
1b87dc497a661819229e9a4fbe26038110cc2e5b
8,028
cpp
C++
op3_read_write_demo/src/read_write.cpp
ROBOTIS-GIT/ROBOTIS-OP3-Demo
77d76182b39c8752388bda48d484cad5f9fedf70
[ "Apache-2.0" ]
6
2019-06-12T15:40:56.000Z
2020-10-16T03:10:32.000Z
op3_read_write_demo/src/read_write.cpp
Sappytomb796/ROBOTIS-OP3-Demo
0a71b4af27d71a334850ab499a3d59ab3426b6fc
[ "Apache-2.0" ]
4
2019-04-17T18:12:53.000Z
2019-05-16T23:57:24.000Z
op3_read_write_demo/src/read_write.cpp
Sappytomb796/ROBOTIS-OP3-Demo
0a71b4af27d71a334850ab499a3d59ab3426b6fc
[ "Apache-2.0" ]
12
2017-09-19T00:15:15.000Z
2021-10-02T08:02:16.000Z
/******************************************************************************* * Copyright 2017 ROBOTIS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* Author: Kayman Jung */ #include <ros/ros.h> #include <std_msgs/String.h> #include <sensor_msgs/JointState.h> #include "robotis_controller_msgs/SetModule.h" #include "robotis_controller_msgs/SyncWriteItem.h" void buttonHandlerCallback(const std_msgs::String::ConstPtr& msg); void jointstatesCallback(const sensor_msgs::JointState::ConstPtr& msg); void readyToDemo(); void setModule(const std::string& module_name); void goInitPose(); void setLED(int led); bool checkManagerRunning(std::string& manager_name); void torqueOnAll(); void torqueOff(const std::string& body_side); enum ControlModule { None = 0, DirectControlModule = 1, Framework = 2, }; const int SPIN_RATE = 30; const bool DEBUG_PRINT = false; ros::Publisher init_pose_pub; ros::Publisher sync_write_pub; ros::Publisher dxl_torque_pub; ros::Publisher write_joint_pub; ros::Publisher write_joint_pub2; ros::Subscriber buttuon_sub; ros::Subscriber read_joint_sub; ros::ServiceClient set_joint_module_client; int control_module = None; bool demo_ready = false; //node main int main(int argc, char **argv) { //init ros ros::init(argc, argv, "read_write"); ros::NodeHandle nh(ros::this_node::getName()); init_pose_pub = nh.advertise<std_msgs::String>("/robotis/base/ini_pose", 0); sync_write_pub = nh.advertise<robotis_controller_msgs::SyncWriteItem>("/robotis/sync_write_item", 0); dxl_torque_pub = nh.advertise<std_msgs::String>("/robotis/dxl_torque", 0); write_joint_pub = nh.advertise<sensor_msgs::JointState>("/robotis/set_joint_states", 0); write_joint_pub2 = nh.advertise<sensor_msgs::JointState>("/robotis/direct_control/set_joint_states", 0); read_joint_sub = nh.subscribe("/robotis/present_joint_states", 1, jointstatesCallback); buttuon_sub = nh.subscribe("/robotis/open_cr/button", 1, buttonHandlerCallback); // service set_joint_module_client = nh.serviceClient<robotis_controller_msgs::SetModule>("/robotis/set_present_ctrl_modules"); ros::start(); //set node loop rate ros::Rate loop_rate(SPIN_RATE); // wait for starting of op3_manager std::string manager_name = "/op3_manager"; while (ros::ok()) { ros::Duration(1.0).sleep(); if (checkManagerRunning(manager_name) == true) { break; ROS_INFO_COND(DEBUG_PRINT, "Succeed to connect"); } ROS_WARN("Waiting for op3 manager"); } readyToDemo(); //node loop while (ros::ok()) { // process //execute pending callbacks ros::spinOnce(); //relax to fit output rate loop_rate.sleep(); } //exit program return 0; } void buttonHandlerCallback(const std_msgs::String::ConstPtr& msg) { // starting demo using robotis_controller if (msg->data == "mode") { control_module = Framework; ROS_INFO("Button : mode | Framework"); readyToDemo(); } // starting demo using direct_control_module else if (msg->data == "start") { control_module = DirectControlModule; ROS_INFO("Button : start | Direct control module"); readyToDemo(); } // torque on all joints of ROBOTIS-OP3 else if (msg->data == "user") { torqueOnAll(); control_module = None; } } void jointstatesCallback(const sensor_msgs::JointState::ConstPtr& msg) { if(control_module == None) return; sensor_msgs::JointState write_msg; write_msg.header = msg->header; for(int ix = 0; ix < msg->name.size(); ix++) { std::string joint_name = msg->name[ix]; double joint_position = msg->position[ix]; // mirror and copy joint angles from right to left if(joint_name == "r_sho_pitch") { write_msg.name.push_back("r_sho_pitch"); write_msg.position.push_back(joint_position); write_msg.name.push_back("l_sho_pitch"); write_msg.position.push_back(-joint_position); } if(joint_name == "r_sho_roll") { write_msg.name.push_back("r_sho_roll"); write_msg.position.push_back(joint_position); write_msg.name.push_back("l_sho_roll"); write_msg.position.push_back(-joint_position); } if(joint_name == "r_el") { write_msg.name.push_back("r_el"); write_msg.position.push_back(joint_position); write_msg.name.push_back("l_el"); write_msg.position.push_back(-joint_position); } } // publish a message to set the joint angles if(control_module == Framework) write_joint_pub.publish(write_msg); else if(control_module == DirectControlModule) write_joint_pub2.publish(write_msg); } void readyToDemo() { ROS_INFO("Start Read-Write Demo"); // turn off LED setLED(0x04); torqueOnAll(); ROS_INFO("Torque on All joints"); // send message for going init posture goInitPose(); ROS_INFO("Go Init pose"); // wait while ROBOTIS-OP3 goes to the init posture. ros::Duration(4.0).sleep(); // turn on R/G/B LED [0x01 | 0x02 | 0x04] setLED(control_module); // change the module for demo if(control_module == Framework) { setModule("none"); ROS_INFO("Change module to none"); } else if(control_module == DirectControlModule) { setModule("direct_control_module"); ROS_INFO("Change module to direct_control_module"); } else return; // torque off : right arm torqueOff("right"); ROS_INFO("Torque off"); } void goInitPose() { std_msgs::String init_msg; init_msg.data = "ini_pose"; init_pose_pub.publish(init_msg); } void setLED(int led) { robotis_controller_msgs::SyncWriteItem syncwrite_msg; syncwrite_msg.item_name = "LED"; syncwrite_msg.joint_name.push_back("open-cr"); syncwrite_msg.value.push_back(led); sync_write_pub.publish(syncwrite_msg); } bool checkManagerRunning(std::string& manager_name) { std::vector<std::string> node_list; ros::master::getNodes(node_list); for (unsigned int node_list_idx = 0; node_list_idx < node_list.size(); node_list_idx++) { if (node_list[node_list_idx] == manager_name) return true; } ROS_ERROR("Can't find op3_manager"); return false; } void setModule(const std::string& module_name) { robotis_controller_msgs::SetModule set_module_srv; set_module_srv.request.module_name = module_name; if (set_joint_module_client.call(set_module_srv) == false) { ROS_ERROR("Failed to set module"); return; } return ; } void torqueOnAll() { std_msgs::String check_msg; check_msg.data = "check"; dxl_torque_pub.publish(check_msg); } void torqueOff(const std::string& body_side) { robotis_controller_msgs::SyncWriteItem syncwrite_msg; int torque_value = 0; syncwrite_msg.item_name = "torque_enable"; if(body_side == "right") { syncwrite_msg.joint_name.push_back("r_sho_pitch"); syncwrite_msg.value.push_back(torque_value); syncwrite_msg.joint_name.push_back("r_sho_roll"); syncwrite_msg.value.push_back(torque_value); syncwrite_msg.joint_name.push_back("r_el"); syncwrite_msg.value.push_back(torque_value); } else if(body_side == "left") { syncwrite_msg.joint_name.push_back("l_sho_pitch"); syncwrite_msg.value.push_back(torque_value); syncwrite_msg.joint_name.push_back("l_sho_roll"); syncwrite_msg.value.push_back(torque_value); syncwrite_msg.joint_name.push_back("l_el"); syncwrite_msg.value.push_back(torque_value); } else return; sync_write_pub.publish(syncwrite_msg); }
26.235294
118
0.701669
[ "vector" ]
1b8829fe2248fa63f24e8e684f29c3e2df57b2d6
6,229
hpp
C++
src/Module.hpp
willishoke/egress
81e07b8a33ff93126d8376ec43601ed2ffaa2e3e
[ "MIT" ]
null
null
null
src/Module.hpp
willishoke/egress
81e07b8a33ff93126d8376ec43601ed2ffaa2e3e
[ "MIT" ]
null
null
null
src/Module.hpp
willishoke/egress
81e07b8a33ff93126d8376ec43601ed2ffaa2e3e
[ "MIT" ]
null
null
null
#include <vector> #include <math.h> using Signal = double; class Module { public: virtual ~Module() {} Module(unsigned int inSize, unsigned int outSize) { this->inputs.resize(inSize); this->outputs.resize(outSize); } virtual void process() = 0; void postprocess() { for (auto & in : inputs) { in = 0.0; } // apply thresholding to restrict output to range [-10.0, 10.0] for (auto & out : outputs) { out = fmin(out, 10.0); out = fmax(out, -10.0); } } std::string module_name; protected: std::vector<Signal> inputs; std::vector<Signal> outputs; unsigned int sampleRate; private: friend class Rack; }; // saw core lets us "easily" get 4 output waveforms // core takes on values in range [0.0, 1.0] // output in range [-5.0, 5.0] class VCO : public Module { public: // invoke base class constructor VCO(int freq) : Module(IN_COUNT, OUT_COUNT) { frequency = freq; core = 0.0; } enum Ins { FM, FM_INDEX, IN_COUNT }; enum Outs { SAW, TRI, SIN, SQR, OUT_COUNT }; void process() { // calculate FM value double fm = pow(2, inputs[FM_INDEX] * inputs[FM] / 5.0); // apply exponential FM double freq = frequency * fm; // increment core value core += freq / 44100; // floating point modulus resets core when it hits 1.0 core = fmod(core, 1.0); // inverts signal if FM value is negative if (fm < 0.0) core = 1.0 - core; // saw is scaled and shifted version of core outputs[SAW] = 10.0 * core - 5.0; // tri is rectified and scaled saw outputs[TRI] = 2.0 * abs(outputs[SAW]) - 5.0; // scale tri to range [0.0, 1.0], apply cos, rescale outputs[SIN] = -5.0 * cos(M_PI * (outputs[TRI] / 10.0 + 0.5)); // simple step function outputs[SQR] = core - 0.5 > 0.0 ? 5.0 : -5.0; // invoke postprocessing routine Module::postprocess(); inputs[FM_INDEX] = 5.0; } private: double frequency; double core; }; class MUX : public Module { public: MUX() : Module(IN_COUNT, OUT_COUNT) {} enum Ins { IN1, IN2, CTRL, IN_COUNT }; enum Outs { OUT, OUT_COUNT }; void process() { // route input depending on polarity of control signal outputs[OUT] = inputs[CTRL] > 0.0 ? inputs[IN1] : inputs[IN2]; // invoke postprocessing routine Module::postprocess(); } }; // 4-quadrant multiplier // two inputs, one output class VCA : public Module { public: VCA() : Module(IN_COUNT, OUT_COUNT) {} enum Ins { IN1, IN2, IN_COUNT }; enum Outs { OUT, OUT_COUNT }; void process() { // update output value, downscaling to avoid clipping outputs[OUT] = inputs[IN1] * inputs[IN2] / 5.0; // clean up Module::postprocess(); } }; class ENV: public Module { public: ENV(double rise, double fall) : Module(IN_COUNT, OUT_COUNT) { this->rise = rise; this->fall = fall; // initialize core value to 0 this->core = 0.0; // module remains idle until positive value appears at TRIG this->stage = ENV::Stage::IDLE; } enum Ins { TRIG, RISE, FALL, IN_COUNT }; enum Outs { OUT, OUT_COUNT }; void process() { if (this->stage == ENV::Stage::IDLE) { if (this->inputs[TRIG] >= 0.0) { // update stage tag this->stage = ENV::Stage::RISING; // need to calculate frequency from wavelength double step = 1.0 / (this->rise * 44.1); // increment core value this->core += step; } } else if (this->stage == ENV::Stage::RISING) { // need to calculate frequency from wavelength double step = 1.0 / (this->rise * 44.1); // increment core value this->core += step; if (this->core >= 1.0) { this->core = 1.0; this->stage = ENV::Stage::FALLING; } } else if (this->stage == ENV::Stage::FALLING) { // need to calculate frequency from wavelength double step = 1.0 / (this->fall * 44.1); // increment core value this->core -= step; if (this->core <= 0.0) { this->core = 0.0; this->stage = ENV::Stage::IDLE; } } // update output value outputs[OUT] = 5.0 * this->core; // clean up Module::postprocess(); } private: enum class Stage { IDLE, // Module is waiting for trigger RISING, // Module is in rise phase FALLING, // Module is in fall phase } stage; double rise; // Value in milliseconds double fall; // Value in milliseconds double core; // Value in range [0.0, 5.0] }; class DELAY : public Module { public: DELAY(double time) : Module(IN_COUNT, OUT_COUNT) { bufferSize = time; bufferPosition = 0; buffer.resize(time); } enum Ins { IN, IN_COUNT }; enum Outs { OUT, OUT_COUNT }; void process() { // write most recent value to buffer buffer[bufferPosition++] = inputs[IN]; bufferPosition %= bufferSize; // update output value outputs[OUT] = buffer[bufferPosition]; // clean up Module::postprocess(); } private: unsigned int bufferSize; unsigned int bufferPosition; std::vector<Signal> buffer; }; class CONST : public Module { public: CONST(Signal s) : Module(IN_COUNT, OUT_COUNT) { value = s; } enum Ins { IN_COUNT }; enum Outs { OUT, OUT_COUNT }; void process() { // update output value outputs[OUT] = value; // clean up Module::postprocess(); } private: Signal value; };
18.055072
70
0.522074
[ "vector" ]
1b8990726dd54332a0eac3b2377c9bfb563f945d
3,525
hpp
C++
include/graphtyper/typer/genotype_paths.hpp
h-2/graphtyper
692eac909f00a888dcc14487fe57907ff88f6d17
[ "MIT" ]
null
null
null
include/graphtyper/typer/genotype_paths.hpp
h-2/graphtyper
692eac909f00a888dcc14487fe57907ff88f6d17
[ "MIT" ]
null
null
null
include/graphtyper/typer/genotype_paths.hpp
h-2/graphtyper
692eac909f00a888dcc14487fe57907ff88f6d17
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> // uint8_t, uint16_t #include <memory> #include <string> // std::string #include <vector> #include <seqan/sequence.h> #include <graphtyper/constants.hpp> // INSERT_SIZE_WHEN_NOT_PROPER_PAIR namespace gyper { // Forward declarations class Graph; class KmerLabel; class Path; class VariantCandidate; struct GenotypePathsDetails { std::string query_name; std::string read_group; }; class GenotypePaths { public: std::vector<char> read2; std::vector<char> qual2; std::vector<Path> paths; uint16_t read_length{0}; uint16_t flags{0}; uint32_t longest_path_length{0}; uint32_t original_pos{0}; // 0-based position from global alignment uint8_t score_diff{0}; // AS-XS from bwa // uint8_t original_clipped_bp{0}; uint8_t mapq{255}; int32_t ml_insert_size{INSERT_SIZE_WHEN_NOT_PROPER_PAIR}; #ifndef NDEBUG std::unique_ptr<GenotypePathsDetails> details; // Only used when statistics are kept #endif // NDEBUG /**************** * CONSTRUCTORS * ****************/ GenotypePaths(); explicit GenotypePaths(int16_t _flags, std::size_t _read_length); explicit GenotypePaths(GenotypePaths const & b); explicit GenotypePaths(GenotypePaths && b); GenotypePaths & operator=(GenotypePaths const &); GenotypePaths & operator=(GenotypePaths &&); ~GenotypePaths() = default; /*********************** * CLASS MODIFICATIONS * ***********************/ void add_next_kmer_labels(std::vector<KmerLabel> const & ll, uint32_t start_index, uint32_t read_end_index, int mismatches = 0); void add_prev_kmer_labels(std::vector<KmerLabel> const & ll, uint32_t const read_start_index, uint32_t const read_end_index, int const mismatches = 0); void clear_paths(); void walk_read_ends(seqan::IupacString const & read, int maximum_mismatches, // -1 if no limit gyper::Graph const & graph); void walk_read_starts(seqan::IupacString const & read, int maximum_mismatches, // -1 if no limit gyper::Graph const & graph); // Path filtering void remove_short_paths(); void remove_support_from_read_ends(); void remove_paths_within_variant_node(); void remove_paths_with_too_many_mismatches(); void remove_non_ref_paths_when_read_matches_ref(); void remove_fully_special_paths(); //std::vector<VariantCandidate> find_new_variants() const; void update_longest_path_size(); /********************* * CLASS INFORMATION * *********************/ std::size_t longest_path_size() const; // std::vector<Path> longest_paths() const; bool all_paths_unique() const; bool all_paths_fully_aligned() const; bool is_purely_reference() const; bool check_no_variant_is_missing() const; #ifndef NDEBUG std::string to_string() const; #endif // NDEBUG bool is_proper_pair() const; }; int compare_pair_of_genotype_paths(GenotypePaths const & geno1, GenotypePaths const & geno2); int compare_pair_of_genotype_paths(std::pair<GenotypePaths *, GenotypePaths *> const & genos1_ptr, std::pair<GenotypePaths *, GenotypePaths *> const & genos2_ptr); int compare_pair_of_genotype_paths(std::pair<GenotypePaths, GenotypePaths> & genos1, std::pair<GenotypePaths, GenotypePaths> & genos2); } // namespace gyper
29.621849
99
0.659574
[ "vector" ]
1b8acef2093d6843647850f5c1d01bdc78a290fa
2,843
cpp
C++
plugins/mmospray/src/OSPRayGlassMaterial.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
plugins/mmospray/src/OSPRayGlassMaterial.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
plugins/mmospray/src/OSPRayGlassMaterial.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * OSPRayGlassMaterial.cpp * Copyright (C) 2009-2017 by MegaMol Team * Alle Rechte vorbehalten. */ #include "OSPRayGlassMaterial.h" #include "mmcore/param/FloatParam.h" #include "mmcore/param/Vector3fParam.h" #include "stdafx.h" using namespace megamol::ospray; OSPRayGlassMaterial::OSPRayGlassMaterial(void) : AbstractOSPRayMaterial() , // GLASS glassEtaInside("EtaInside", "") , glassEtaOutside("EtaOutside", "") , glassAttenuationColorInside("AttenuationColorInside", "") , glassAttenuationColorOutside("AttenuationColorOutside", "") , glassAttenuationDistance("AttenuationDistance", "") { this->glassAttenuationColorInside << new core::param::Vector3fParam( vislib::math::Vector<float, 3>(1.0f, 1.0f, 1.0f)); this->glassAttenuationColorOutside << new core::param::Vector3fParam( vislib::math::Vector<float, 3>(1.0f, 1.0f, 1.0f)); this->glassAttenuationDistance << new core::param::FloatParam(1.0f); this->glassEtaOutside << new core::param::FloatParam(1.0f); this->glassEtaInside << new core::param::FloatParam(1.5f); this->MakeSlotAvailable(&this->glassAttenuationColorInside); this->MakeSlotAvailable(&this->glassAttenuationColorOutside); this->MakeSlotAvailable(&this->glassAttenuationDistance); this->MakeSlotAvailable(&this->glassEtaInside); this->MakeSlotAvailable(&this->glassEtaOutside); } OSPRayGlassMaterial::~OSPRayGlassMaterial(void) { this->Release(); } void OSPRayGlassMaterial::readParams() { materialContainer.materialType = materialTypeEnum::GLASS; glassMaterial gm; auto colori = this->glassAttenuationColorInside.Param<core::param::Vector3fParam>(); gm.glassAttenuationColorInside = colori->getArray(); auto coloro = this->glassAttenuationColorOutside.Param<core::param::Vector3fParam>(); gm.glassAttenuationColorOutside = coloro->getArray(); gm.glassEtaInside = this->glassEtaInside.Param<core::param::FloatParam>()->Value(); gm.glassEtaOutside = this->glassEtaOutside.Param<core::param::FloatParam>()->Value(); gm.glassAttenuationDistance = this->glassAttenuationDistance.Param<core::param::FloatParam>()->Value(); materialContainer.material = gm; } bool OSPRayGlassMaterial::InterfaceIsDirty() { if (this->glassAttenuationColorInside.IsDirty() || this->glassAttenuationColorOutside.IsDirty() || this->glassAttenuationDistance.IsDirty() || this->glassEtaInside.IsDirty() || this->glassEtaOutside.IsDirty()) { this->glassAttenuationColorInside.ResetDirty(); this->glassAttenuationColorOutside.ResetDirty(); this->glassAttenuationDistance.ResetDirty(); this->glassEtaInside.ResetDirty(); this->glassEtaOutside.ResetDirty(); return true; } else { return false; } }
40.042254
120
0.714386
[ "vector" ]
b846aa92074e014f6dd1c09fe2e408ddb66fd571
4,455
hpp
C++
include/lbann/callbacks/debug.hpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
include/lbann/callbacks/debug.hpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
include/lbann/callbacks/debug.hpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2022, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_CALLBACKS_CALLBACK_DEBUG_HPP_INCLUDED #define LBANN_CALLBACKS_CALLBACK_DEBUG_HPP_INCLUDED #include "lbann/callbacks/callback.hpp" #include <set> namespace lbann { namespace callback { /** * @brief Phase specific "printf debugging" * * Print verbose status updates to standard error stream. * This callback is useful for "printf debugging." * * Takes a prototext parameter @c phase: train | validate | test | \<empty\> * if \<empty\> will print messages for all phases * */ class debug : public callback_base { public: /** @brief Constructor. * * If modes is empty, status updates will be printed for all * execution modes. */ debug(std::set<execution_mode> modes={}) : m_modes(std::move(modes)) {} debug(const debug&) = default; debug& operator=(const debug&) = default; debug* copy() const override { return new debug(*this); } std::string name() const override { return "debug"; } /** @brief Print that a batch is beginning. */ void on_batch_begin(model *m) override; /** @brief Print that a batch is ending. */ void on_batch_end(model *m) override; /** @brief Print that a layer's forward prop is beginning. */ void on_batch_evaluate_begin(model *m) override; /** @brief Print that a layer's forward prop is ending. */ void on_batch_evaluate_end(model *m) override; using callback_base::on_forward_prop_begin; using callback_base::on_forward_prop_end; using callback_base::on_backward_prop_begin; using callback_base::on_backward_prop_end; using callback_base::on_evaluate_forward_prop_begin; using callback_base::on_evaluate_forward_prop_end; /** @brief Print that a layer's forward prop is beginning. */ void on_forward_prop_begin(model *m, Layer *l) override; /** @brief Print that a layer's forward prop is ending. */ void on_forward_prop_end(model *m, Layer *l) override; /** @brief Print that a layer's backward prop is beginning. */ void on_backward_prop_begin(model *m, Layer *l) override; /** @brief Print that a layer's backward prop is ending. */ void on_backward_prop_end(model *m, Layer *l) override; /** @brief Print that a layer's backward prop is beginning. */ void on_evaluate_forward_prop_begin(model *m, Layer *l) override; /** @brief Print that a layer's backward prop is ending. */ void on_evaluate_forward_prop_end(model *m, Layer *l) override; /** @brief Print that a weights' optimization step is beginning. */ void on_optimize_begin(model *m, weights *w) override; /** @brief Print that a weights' optimization step is ending. */ void on_optimize_end(model *m, weights *w) override; /** @name Serialization */ ///@{ /** @brief Store state to archive for checkpoint and restart */ template <class Archive> void serialize(Archive & ar); ///@} private: /** @brief Execution modes for which status updates will be printed. * * If empty, status updates are printed for all execution modes. */ std::set<execution_mode> m_modes; }; // Builder function std::unique_ptr<callback_base> build_debug_callback_from_pbuf( const google::protobuf::Message&, std::shared_ptr<lbann_summary> const&); } // namespace callback } // namespace lbann #endif // LBANN_CALLBACKS_CALLBACK_DEBUG_HPP_INCLUDED
36.219512
80
0.700786
[ "model" ]
b8471ff1bf947d8e0f10ee8abd62d27e71e80640
33,778
cpp
C++
automata/eudoxus_compiler.cpp
crustymonkey/ironbee
8350b383244e33b18c7a7b6ba989f67ffcbd945a
[ "Apache-2.0" ]
1
2019-12-22T21:08:35.000Z
2019-12-22T21:08:35.000Z
automata/eudoxus_compiler.cpp
crustymonkey/ironbee
8350b383244e33b18c7a7b6ba989f67ffcbd945a
[ "Apache-2.0" ]
null
null
null
automata/eudoxus_compiler.cpp
crustymonkey/ironbee
8350b383244e33b18c7a7b6ba989f67ffcbd945a
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronAutomata --- Eudoxus Compiler Implementation * * @author Christopher Alfeld <calfeld@qualys.com> */ #include <ironautomata/eudoxus_compiler.hpp> #include <ironautomata/bits.h> #include <ironautomata/eudoxus_automata.h> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <queue> #include <set> using namespace std; namespace IronAutomata { namespace EudoxusCompiler { #define CPP_EUDOXUS_VERSION 10 #if CPP_EUDOXUS_VERSION != IA_EUDOXUS_VERSION #error "Mismatch between compiler version and automata version." #endif const int EUDOXUS_VERSION = CPP_EUDOXUS_VERSION; #undef CPP_EUDOXUS_VERSION namespace { /** * Compiler for given @a id_width. * * This helper class implements compilation for a specific id width. * * @tparam id_width Width of all Eudoxus identifiers. */ template <size_t id_width> class Compiler { public: /** * Constructor. * * @param[in] result Where to store results. * @param[in] configuration Compiler configuration. */ Compiler( result_t& result, configuration_t configuration ); /** * Compile automata. * * @param[in] automata Automata to compile. */ void compile( const Intermediate::Automata& automata ); private: //! Subengine traits. typedef Eudoxus::subengine_traits<id_width> traits_t; //! Eudoxus Identifier. typedef typename traits_t::id_t e_id_t; //! Eudoxus Low Edge. typedef typename traits_t::low_edge_t e_low_edge_t; //! Eudoxus Low Node. typedef typename traits_t::low_node_t e_low_node_t; //! Eudoxus High Node typedef typename traits_t::high_node_t e_high_node_t; //! Eudoxus PC Node typedef typename traits_t::pc_node_t e_pc_node_t; //! Eudoxus Output List. typedef typename traits_t::output_list_t e_output_list_t; friend class BFSVisitor; //! True iff @a edge does not advance input. static bool is_nonadvancing(const Intermediate::Edge& edge) { return ! edge.advance(); } /** * Answer questions about nodes. */ struct NodeOracle { //! use_ali will be set if num_consecutive > c_ali_threshold. static const size_t c_ali_threshold = 32; //! Constructor. explicit NodeOracle(const Intermediate::node_p& node) { has_nonadvancing = ( find_if(node->edges().begin(), node->edges().end(), is_nonadvancing) ) != node->edges().end(); targets_by_input = node->build_targets_by_input(); deterministic = true; out_degree = 0; num_consecutive = 0; Intermediate::node_p previous_target; for (int c = 0; c < 256; ++c) { const Intermediate::Node::target_info_list_t& targets = targets_by_input[c]; if (targets.size() > 1) { deterministic = false; } if (targets.empty()) { continue; } const Intermediate::node_p& target = targets.front().first; if (target != node->default_target()) { ++out_degree; if (previous_target && target == previous_target) { ++num_consecutive; } previous_target = target; } } use_ali = (num_consecutive > c_ali_threshold); low_node_cost = 0; low_node_cost += sizeof(e_low_node_t); if (node->first_output()) { low_node_cost += sizeof(e_id_t); } if (! node->edges().empty()) { low_node_cost += sizeof(uint8_t); low_node_cost += sizeof(typename traits_t::low_edge_t) * out_degree; } if (node->default_target()) { low_node_cost += sizeof(e_id_t); } if (has_nonadvancing) { low_node_cost += (out_degree + 7) / 8; } high_node_cost = 0; high_node_cost += sizeof(e_high_node_t); if (node->first_output()) { high_node_cost += sizeof(e_id_t); } if (node->default_target()) { high_node_cost += sizeof(e_id_t); } if (has_nonadvancing) { high_node_cost += sizeof(ia_bitmap256_t); } if (out_degree < 256) { high_node_cost += sizeof(ia_bitmap256_t); } if (use_ali) { high_node_cost += sizeof(ia_bitmap256_t); } if (use_ali) { high_node_cost += sizeof(e_id_t) * (out_degree - num_consecutive); } else { high_node_cost += sizeof(e_id_t) * out_degree; } } //! True if there are non-advancing edges (not including default). bool has_nonadvancing; //! True if every input has at most 1 target. bool deterministic; //! Number of inputs with non-default targets. size_t out_degree; /** * Number of inputs with same target as last input. * * Does not include default targets. */ size_t num_consecutive; //! True if a high degree node should use an ALI. bool use_ali; //! Cost in bytes of representing with a low node. size_t low_node_cost; //! Cost in bytes of representing with a high node. size_t high_node_cost; //! Targets by input map. Intermediate::Node::targets_by_input_t targets_by_input; }; //! Set of nodes. typedef set<Intermediate::node_p> node_set_t; //! Map of nodes to set of nodes: it's parents. typedef map<Intermediate::node_p, node_set_t> parent_map_t; //! Compile @a node to @a end_of_path into a PC node. void pc_node( const Intermediate::node_p& node, const Intermediate::node_p& end_of_path, size_t path_length ) { size_t old_size = m_assembler.size(); { e_pc_node_t* header = m_assembler.append_object(e_pc_node_t()); header->header = IA_EUDOXUS_PC; if (node->first_output()) { header->header = ia_setbit8(header->header, 0 + IA_EUDOXUS_TYPE_WIDTH); } if (node->default_target()) { header->header = ia_setbit8(header->header, 1 + IA_EUDOXUS_TYPE_WIDTH); } if (node->advance_on_default()) { header->header = ia_setbit8(header->header, 2 + IA_EUDOXUS_TYPE_WIDTH); } if (end_of_path->edges().front().advance()) { header->header = ia_setbit8(header->header, 3 + IA_EUDOXUS_TYPE_WIDTH); } if (path_length >= 4) { header->header = ia_setbit8(header->header, 4 + IA_EUDOXUS_TYPE_WIDTH); } if (path_length > 4 || path_length == 3) { header->header = ia_setbit8(header->header, 5 + IA_EUDOXUS_TYPE_WIDTH); } register_node_ref( m_assembler.index(&(header->final_target)), end_of_path ); } if (node->first_output()) { append_output_ref(node->first_output()); m_outputs.insert(node->first_output()); } if (node->default_target()) { append_node_ref(node->default_target()); } assert(path_length >= 2); assert(path_length <= 255); if (path_length > 4) { m_assembler.append_object(uint8_t(path_length)); } for ( Intermediate::node_p cur = node; cur != end_of_path; cur = has_unique_child(cur) ) { assert(cur->edges().size() == 1); assert(cur->edges().front().size() == 1); m_assembler.append_object(uint8_t( *cur->edges().front().begin() )); } ++m_result.pc_nodes; m_result.pc_nodes_bytes += m_assembler.size() - old_size; } //! Compile node into a demux (high or low) node. void demux_node(const Intermediate::node_p& node) { NodeOracle oracle(node); if (! oracle.deterministic) { throw runtime_error( "Non-deterministic automata unsupported." ); } size_t old_size = m_assembler.size(); size_t* bytes_counter = NULL; size_t* nodes_counter = NULL; size_t cost_prediction = 0; if ( oracle.high_node_cost * m_configuration.high_node_weight > oracle.low_node_cost ) { cost_prediction = oracle.low_node_cost; bytes_counter = &m_result.low_nodes_bytes; nodes_counter = &m_result.low_nodes; low_node(*node, oracle); } else { cost_prediction = oracle.high_node_cost; bytes_counter = &m_result.high_nodes_bytes; nodes_counter = &m_result.high_nodes; high_node(*node, oracle); } size_t bytes_added = m_assembler.size() - old_size; if (cost_prediction != bytes_added) { throw logic_error( "Insanity: Incorrect cost prediction." " Please report as bug." ); } ++(*nodes_counter); (*bytes_counter) += bytes_added; } /** * Compile @a node as a low_node. * * Appends a low node to the buffer representing @a node. * * @param[in] node Intermediate node to compile. */ void low_node( const Intermediate::Node& node, const NodeOracle& oracle ) { { e_low_node_t* header = m_assembler.append_object(e_low_node_t()); header->header = IA_EUDOXUS_LOW; if (node.first_output()) { header->header = ia_setbit8(header->header, 0 + IA_EUDOXUS_TYPE_WIDTH); } if (oracle.has_nonadvancing) { header->header = ia_setbit8(header->header, 1 + IA_EUDOXUS_TYPE_WIDTH); } if (node.default_target()) { header->header = ia_setbit8(header->header, 2 + IA_EUDOXUS_TYPE_WIDTH); } if (node.advance_on_default()) { header->header = ia_setbit8(header->header, 3 + IA_EUDOXUS_TYPE_WIDTH); } if (oracle.out_degree > 0) { header->header = ia_setbit8(header->header, 4 + IA_EUDOXUS_TYPE_WIDTH); } } if (node.first_output()) { append_output_ref(node.first_output()); m_outputs.insert(node.first_output()); } if (oracle.out_degree > 0) { m_assembler.append_object( uint8_t(oracle.out_degree) ); } if (node.default_target()) { append_node_ref(node.default_target()); } size_t advance_index = 0; if (oracle.has_nonadvancing) { uint8_t* advance = m_assembler.template append_array<uint8_t>( (oracle.out_degree + 7) / 8 ); advance_index = m_assembler.index(advance); } size_t edge_i = 0; BOOST_FOREACH(const Intermediate::Edge& edge, node.edges()) { if (edge.epsilon()) { throw runtime_error( "Epsilon edges currently unsupported." ); } BOOST_FOREACH(uint8_t value, edge) { if (oracle.has_nonadvancing && edge.advance()) { ia_setbitv( m_assembler.template ptr<uint8_t>( advance_index ), edge_i ); } ++edge_i; e_low_edge_t* e_edge = m_assembler.append_object(e_low_edge_t()); e_edge->c = value; register_node_ref( m_assembler.index(&(e_edge->next_node)), edge.target() ); } } } /** * Compile @a node as a high_node. * * Appends a high node to the buffer representing @a node. * * @param[in] node Intermediate node to compile. */ void high_node( const Intermediate::Node& node, const NodeOracle& oracle ) { { e_high_node_t* header = m_assembler.append_object(e_high_node_t()); header->header = IA_EUDOXUS_HIGH; if (node.first_output()) { header->header = ia_setbit8(header->header, 0 + IA_EUDOXUS_TYPE_WIDTH); } if (oracle.has_nonadvancing) { header->header = ia_setbit8(header->header, 1 + IA_EUDOXUS_TYPE_WIDTH); } if (node.default_target()) { header->header = ia_setbit8(header->header, 2 + IA_EUDOXUS_TYPE_WIDTH); } if (node.advance_on_default()) { header->header = ia_setbit8(header->header, 3 + IA_EUDOXUS_TYPE_WIDTH); } if (oracle.out_degree < 256) { header->header = ia_setbit8(header->header, 4 + IA_EUDOXUS_TYPE_WIDTH); } if (oracle.use_ali) { header->header = ia_setbit8(header->header, 5 + IA_EUDOXUS_TYPE_WIDTH); } } if (node.first_output()) { append_output_ref(node.first_output()); m_outputs.insert(node.first_output()); } if (node.default_target()) { append_node_ref(node.default_target()); } if (oracle.has_nonadvancing) { ia_bitmap256_t& advance_bm = *m_assembler.append_object(ia_bitmap256_t()); for (int c = 0; c < 256; ++c) { if ( ! oracle.targets_by_input[c].empty() && oracle.targets_by_input[c].front().second ) { ia_setbitv64(advance_bm.bits, c); } } } if (oracle.out_degree < 256) { ia_bitmap256_t& target_bm = *m_assembler.append_object(ia_bitmap256_t()); for (int c = 0; c < 256; ++c) { if ( ! oracle.targets_by_input[c].empty() && oracle.targets_by_input[c].front().first != node.default_target() ) { ia_setbitv64(target_bm.bits, c); } } } if (oracle.use_ali) { Intermediate::node_p previous_target; ia_bitmap256_t& ali_bm = *m_assembler.append_object(ia_bitmap256_t()); for (int c = 0; c < 256; ++c) { if (! oracle.targets_by_input[c].empty()) { const Intermediate::node_p& target = oracle.targets_by_input[c].front().first; if (target == node.default_target()) { continue; } if ( previous_target && target != previous_target ) { ia_setbitv64(ali_bm.bits, c); } previous_target = target; } } // Using second loop as ali_bm might be moved by append_node_ref. previous_target.reset(); for (int c = 0; c < 256; ++c) { if (! oracle.targets_by_input[c].empty()) { const Intermediate::node_p& target = oracle.targets_by_input[c].front().first; if (target == node.default_target()) { continue; } if ( ! previous_target || target != previous_target ) { append_node_ref(target); } previous_target = target; } } } else { for (int c = 0; c < 256; ++c) { if (! oracle.targets_by_input[c].empty()) { const Intermediate::node_p& target = oracle.targets_by_input[c].front().first; if (target != node.default_target()) { append_node_ref(target); } } } } } /** * Go back over buffer and fill in the identifiers. * * This method combines @a id_map and @a object_map to fill in the * identifiers listed in @a id_map with the proper indices of their * referants as specified by @a object_map. * * It is called twice, once for output identifiers and once for input * identifiers. These can not be compiled as the intermediate format does * not guarantee separate ID spaces. * * @tparam IDMapType Type of @a id_map. * @tparam ObjectMapType Type of @a object_map. * @param[in] id_map Map of identifier index to object. * @param[in] object_map Map of object to object index. */ template <typename IDMapType, typename ObjectMapType> void fill_in_ids( const IDMapType& id_map, const ObjectMapType& object_map ) { BOOST_FOREACH( const typename IDMapType::value_type x, id_map ) { if (x.second) { typename ObjectMapType::const_iterator object_map_entry = object_map.find(x.second); if (object_map_entry == object_map.end()) { throw logic_error("Request ID fill but no such object."); } e_id_t* e_id = m_assembler.ptr<e_id_t>(x.first); *e_id = object_map_entry->second; } } } //! Record an output reference to @a output at location @a id_index. void register_output_ref( size_t id_index, const Intermediate::output_p& output ) { m_output_id_map[id_index] = output; } //! Record a node reference to @a node at location @a id_index. void register_node_ref( size_t id_index, const Intermediate::node_p& node ) { m_node_id_map[id_index] = node; } //! Append a reference to @a output. void append_output_ref(const Intermediate::output_p& output) { e_id_t* e_id = m_assembler.append_object(e_id_t()); register_output_ref(m_assembler.index(e_id), output); } //! Append a reference to a @node. void append_node_ref(const Intermediate::node_p& node) { e_id_t* e_id = m_assembler.append_object(e_id_t()); register_node_ref(m_assembler.index(e_id), node); } /** * Transitively close @c m_outputs. * * This method does a breadth first search starting with the contents * of @c m_outputs and adds any new outputs found to @c m_outputs. I.e., * finds outputs that are only referred to be other outputs and adds * them. */ void complete_outputs() { list<Intermediate::output_p> todo(m_outputs.begin(), m_outputs.end()); while (! todo.empty()) { const Intermediate::output_p output = todo.front(); todo.pop_front(); if (output->next_output()) { bool is_new = m_outputs.insert(output->next_output()).second; if (is_new) { todo.push_back(output->next_output()); } } } } //! Appends all output lists and outputs in @c m_outputs to the buffer. void append_outputs() { // Set first_output. m_assembler.ptr<ia_eudoxus_automata_t>( m_e_automata_index )->first_output = m_assembler.size(); // Calculate all contents. typedef map<Intermediate::byte_vector_t, size_t> output_content_map_t; output_content_map_t output_contents; BOOST_FOREACH(const Intermediate::output_p& output, m_outputs) { output_contents.insert(make_pair(output->content(), 0)); } // Append all contents. Note non-const reference. BOOST_FOREACH( output_content_map_t::value_type& v, output_contents ) { ia_eudoxus_output_t* e_output = m_assembler.append_object(ia_eudoxus_output_t()); v.second = m_assembler.index(e_output); e_output->length = v.first.size(); m_assembler.append_bytes(v.first.data(), v.first.size()); if (m_assembler.size() >= m_max_index) { throw out_of_range("id_width too small"); } } m_assembler.ptr<ia_eudoxus_automata_t>( m_e_automata_index )->num_outputs = output_contents.size(); m_result.ids_used += output_contents.size(); // Handle all outputs. m_assembler.ptr<ia_eudoxus_automata_t>( m_e_automata_index )->first_output_list = m_assembler.size(); BOOST_FOREACH(const Intermediate::output_p& output, m_outputs) { if (! output->next_output()) { // Single outputs will just point directly to the content. m_output_map[output] = output_contents[output->content()]; } else { // Multiple outputs need a list. e_output_list_t* e_output_list = m_assembler.append_object(e_output_list_t()); ++m_assembler.ptr<ia_eudoxus_automata_t>( m_e_automata_index )->num_output_lists; m_output_map[output] = m_assembler.index(e_output_list); e_output_list->output = output_contents[output->content()]; // Register even if NULL to get id count correct. register_output_ref( m_assembler.index(&(e_output_list->next_output)), output->next_output() ); } if (m_assembler.size() >= m_max_index) { throw out_of_range("id_width too small"); } } } //! Returns unique child of @a node or singular node_p if no unique child. static Intermediate::node_p has_unique_child(const Intermediate::node_p& node) { if ( node->edges().size() == 1 && node->edges().front().size() == 1 ) { return node->edges().front().target(); } return Intermediate::node_p(); } //! Returns true iff @a a and @a b have the same default behavior. static bool same_defaults( const Intermediate::node_p& a, const Intermediate::node_p& b ) { return a->default_target() == b->default_target() && a->advance_on_default() == b->advance_on_default(); } //! Add all children of @a node to @a parents. static void calculate_parents( parent_map_t& parents, const Intermediate::node_p& node ) { BOOST_FOREACH(const Intermediate::Edge& edge, node->edges()) { parents[edge.target()].insert(node); } if (node->default_target()) { parents[node->default_target()].insert(node); } } //! Logger to use. logger_t m_logger; //! Where to store the result. result_t& m_result; //! Compiler Configuration. configuration_t m_configuration; //! Assembler of m_result.buffer. BufferAssembler m_assembler; //! Index of automata structure. size_t m_e_automata_index; //! Type of m_node_map. typedef map<Intermediate::node_p, size_t> node_map_t; //! Type of m_output_map. typedef map<Intermediate::output_p, size_t> output_map_t; //! Map of node to location in buffer. node_map_t m_node_map; //! Map of output to location in buffer. output_map_t m_output_map; //! Type of m_node_id_map. typedef map<size_t, Intermediate::node_p> node_id_map_t; //! Type of m_output_id_map. typedef map<size_t, Intermediate::output_p> output_id_map_t; //! Map of id location to node. node_id_map_t m_node_id_map; //! Map of id location to output. output_id_map_t m_output_id_map; //! Type of m_outputs. typedef set<Intermediate::output_p> output_set_t; //! Set of all known outputs. output_set_t m_outputs; //! Maximum index of buffer based on id_width. const uint64_t m_max_index; }; template <size_t id_width> Compiler<id_width>::Compiler( result_t& result, configuration_t configuration ) : m_result(result), m_configuration(configuration), m_assembler(result.buffer), m_e_automata_index(0), m_max_index(numeric_limits<e_id_t>::max()) { // nop } template <size_t id_width> void Compiler<id_width>::compile( const Intermediate::Automata& automata ) { m_result.buffer.clear(); m_result.ids_used = 0; m_result.padding = 0; m_result.low_nodes = 0; m_result.low_nodes_bytes = 0; m_result.high_nodes = 0; m_result.high_nodes_bytes = 0; m_result.pc_nodes = 0; m_result.pc_nodes_bytes = 0; // Header ia_eudoxus_automata_t* e_automata = m_assembler.append_object(ia_eudoxus_automata_t()); e_automata->version = EUDOXUS_VERSION; e_automata->id_width = id_width; e_automata->is_big_endian = ia_eudoxus_is_big_endian(); e_automata->no_advance_no_output = automata.no_advance_no_output(); e_automata->reserved = 0; // Fill in later. e_automata->num_nodes = 0; e_automata->num_outputs = 0; e_automata->num_output_lists = 0; e_automata->data_length = 0; // Store index as it will likely move. m_e_automata_index = m_assembler.index(e_automata); // Calculate Node Parents parent_map_t parents; breadth_first( automata, boost::bind(calculate_parents, boost::ref(parents), _1) ); // Adapted BFS... Complicated by path compression nodes. queue<Intermediate::node_p> todo; set<Intermediate::node_p> queued; todo.push(automata.start_node()); queued.insert(automata.start_node()); while (! todo.empty()) { Intermediate::node_p node = todo.front(); todo.pop(); // Padding size_t index = m_assembler.size(); size_t alignment = index % m_configuration.align_to; size_t padding = ( alignment == 0 ? 0 : m_configuration.align_to - alignment ); if (padding > 0) { m_result.padding += padding; for (size_t i = 0; i < padding; ++i) { m_assembler.append_object(uint8_t(0xaa)); } } assert(m_assembler.size() % m_configuration.align_to == 0); // Record node location. m_node_map[node] = m_assembler.size(); Intermediate::node_p end_of_path = node; Intermediate::node_p child = has_unique_child(end_of_path); size_t path_length = 0; while ( path_length <= 255 && child && ! child->first_output() && end_of_path->edges().front().advance() && has_unique_child(child) && same_defaults(end_of_path, child) && parents[child].size() == 1 ) { end_of_path = child; child = has_unique_child(child); ++path_length; } if (path_length >= 2) { // Path Compression pc_node(node, end_of_path, path_length); // Add end of path. bool need_to_queue = queued.insert(end_of_path).second; if (need_to_queue) { todo.push(end_of_path); } } else { // Demux: High or Low demux_node(node); // And add all children. BOOST_FOREACH(const Intermediate::Edge& edge, node->edges()) { const Intermediate::node_p& target = edge.target(); bool need_to_queue = queued.insert(target).second; if (need_to_queue) { todo.push(target); } } } if (node->default_target()) { const Intermediate::node_p& target = node->default_target(); bool need_to_queue = queued.insert(target).second; if (need_to_queue) { todo.push(target); } } if (m_assembler.size() >= m_max_index) { throw out_of_range("id_width too small"); } } complete_outputs(); append_outputs(); fill_in_ids(m_node_id_map, m_node_map); fill_in_ids(m_output_id_map, m_output_map); // Append metadata. typedef map<string, string> map_t; size_t metadata_index = m_assembler.size(); BOOST_FOREACH(const map_t::value_type& v, automata.metadata()) { ia_eudoxus_output_t* e_output = m_assembler.append_object(ia_eudoxus_output_t()); e_output->length = v.first.size(); m_assembler.append_bytes( reinterpret_cast<const uint8_t*>(v.first.data()), v.first.size() ); e_output = m_assembler.append_object(ia_eudoxus_output_t()); e_output->length = v.second.size(); m_assembler.append_bytes( reinterpret_cast<const uint8_t*>(v.second.data()), v.second.size() ); } // Recover pointer. e_automata = m_assembler.ptr<ia_eudoxus_automata_t>(m_e_automata_index); e_automata->num_nodes = m_node_map.size(); e_automata->num_outputs = m_output_map.size(); e_automata->num_metadata = automata.metadata().size(); e_automata->metadata_index = metadata_index; e_automata->data_length = m_result.buffer.size(); assert(m_node_map[automata.start_node()] < 256); e_automata->start_index = m_node_map[automata.start_node()]; m_result.ids_used += m_node_id_map.size() + m_output_id_map.size(); } result_t compile_minimal( const Intermediate::Automata& automata, configuration_t configuration ) { static const size_t c_id_widths[] = {1, 2, 4, 8}; static const size_t c_num_id_widths = sizeof(c_id_widths) / sizeof(*c_id_widths); if (configuration.id_width != 0) { throw logic_error( "compile_minimal called with non-0 id_width." " Please report as bug." ); } result_t result; size_t i; for (i = 0; i < c_num_id_widths; ++i) { bool success = true; try { configuration.id_width = c_id_widths[i]; result = compile(automata, configuration); } catch (out_of_range) { // move on to next id_width. success = false; } if (success) { break; } } if (i == c_num_id_widths) { throw logic_error( "Insanity error. " "Could not fit automata in 2**8 bytes? " "Please report as bug." ); } return result; // RVO } } // Anonymous configuration_t::configuration_t() : id_width(0), align_to(1), high_node_weight(1.0) { // nop } result_t compile( const Intermediate::Automata& automata, configuration_t configuration ) { if (configuration.id_width == 0) { return compile_minimal(automata, configuration); } result_t result; result.configuration = configuration; switch (configuration.id_width) { case 1: Compiler<1>(result, configuration).compile(automata); break; case 2: Compiler<2>(result, configuration).compile(automata); break; case 4: Compiler<4>(result, configuration).compile(automata); break; case 8: Compiler<8>(result, configuration).compile(automata); break; default: throw logic_error("Unsupported id_width."); } return result; // RVO } } // EudoxusCompiler } // IronAutomata
31.866038
87
0.552342
[ "object" ]
b84cd900b069e289a99f43a2d3bb18518c0e1408
2,455
cpp
C++
src/WindowOpenGl.cpp
Akaito/csaru-xapp-cpp
e44dd1e8c7de76958eeea8d7964e8242fe35f334
[ "Zlib" ]
null
null
null
src/WindowOpenGl.cpp
Akaito/csaru-xapp-cpp
e44dd1e8c7de76958eeea8d7964e8242fe35f334
[ "Zlib" ]
null
null
null
src/WindowOpenGl.cpp
Akaito/csaru-xapp-cpp
e44dd1e8c7de76958eeea8d7964e8242fe35f334
[ "Zlib" ]
null
null
null
#include "exported/WindowOpenGl.hpp" #ifdef _WIN32 # include <SDL_opengl.h> #else # include <SDL2/SDL_opengl.h> #endif extern int SDL_LOG_CATEGORY_CSARU_XAPP; namespace csaru { namespace xapp { //====================================================================== WindowOpenGl::~WindowOpenGl () { Destroy(); } //====================================================================== void WindowOpenGl::Clear () { glClearColor(m_clearColor[0], m_clearColor[1], m_clearColor[2], m_clearColor[3]); glClear(GL_COLOR_BUFFER_BIT); } //====================================================================== void WindowOpenGl::Destroy () { if (m_glContext) SDL_GL_DeleteContext(m_glContext); m_glContext = nullptr; csaru::xapp::Window::Destroy(); } //====================================================================== bool WindowOpenGl::Init (const char * title, uint32_t width, uint32_t height) { Destroy(); // Must set attributes before window creation. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); //SDL_DisplayMode currentDisplayMode; //SDL_GetCurrentDisplayMode(0, &currentDisplayMode); // create window m_window = SDL_CreateWindow( title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL ); if (!m_window) { SDL_LogError(SDL_LOG_CATEGORY_CSARU_XAPP, "SDL failed to create a window. %s\n", SDL_GetError()); return false; } m_glContext = SDL_GL_CreateContext(m_window); if (!m_glContext) { SDL_LogError(SDL_LOG_CATEGORY_CSARU_XAPP, "SDL failed to create a GL context. %s\n", SDL_GetError()); return false; } m_areaWidth = width; m_areaHeight = height; return true; } //====================================================================== void WindowOpenGl::Render () { SDL_GL_SwapWindow(m_window); } //====================================================================== void WindowOpenGl::SetClearColor (float r, float g, float b, float a) { m_clearColor[0] = r; m_clearColor[1] = g; m_clearColor[2] = b; m_clearColor[3] = a; } } // namespace csaru } // namespace xapp
28.218391
110
0.567413
[ "render" ]
b851cda3ba224b5945e391839f6fdc0c7614f5f7
3,924
hpp
C++
src/orocos_kinematics_dynamics/orocos_kdl/src/trajectory.hpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
3
2021-12-06T15:30:58.000Z
2022-03-29T13:21:40.000Z
src/orocos_kinematics_dynamics/orocos_kdl/src/trajectory.hpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
1
2021-07-08T10:26:06.000Z
2021-07-08T10:31:11.000Z
src/orocos_kinematics_dynamics/orocos_kdl/src/trajectory.hpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
1
2022-01-04T09:16:28.000Z
2022-01-04T09:16:28.000Z
/*************************************************************************** tag: Erwin Aertbelien Mon Jan 10 16:38:39 CET 2005 trajectory.h trajectory.h - description ------------------- begin : Mon January 10 2005 copyright : (C) 2005 Erwin Aertbelien email : erwin.aertbelien@mech.kuleuven.ac.be *************************************************************************** * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307 USA * * * ***************************************************************************/ /***************************************************************************** * \author * Erwin Aertbelien, Div. PMA, Dep. of Mech. Eng., K.U.Leuven * * \version * ORO_Geometry V0.2 * * \par History * - $log$ * * \par Release * $Id: trajectory.h,v 1.1.1.1.2.5 2003/07/23 16:44:25 psoetens Exp $ * $Name: $ * \todo * Peter's remark : should separate I/O from other routines in the * motion/chain directories * The problem is that the I/O uses virtual inheritance to write * the trajectories/geometries/velocityprofiles/... * Have no good solution for this, perhaps * * #ifdef's * * declaring dummy ostream/istream and change implementation file .cpp * * declaring some sort of VISITOR object (containing an ostream) , * the classes contain code to pass this object around along its children * a subroutine can then be called with overloading. * PROBLEM : if you declare a friend you have to fully declare it ==> exposing I/O with ostream/istream decl * CONSEQUENCE : everything has to be declared public. ****************************************************************************/ #ifndef TRAJECTORY_H #define TRAJECTORY_H #include "frames.hpp" #include "frames_io.hpp" #include "path.hpp" #include "velocityprofile.hpp" namespace KDL { /** * An abstract class that implements * a trajectory contains a cartesian space trajectory and an underlying * velocity profile. * @ingroup Motion */ class Trajectory { public: virtual double Duration() const = 0; // The duration of the trajectory virtual Frame Pos(double time) const = 0; // Position of the trajectory at <time>. virtual Twist Vel(double time) const = 0; // The velocity of the trajectory at <time>. virtual Twist Acc(double time) const = 0; // The acceleration of the trajectory at <time>. virtual Trajectory* Clone() const = 0; virtual void Write(std::ostream& os) const = 0; static Trajectory* Read(std::istream& is); virtual ~Trajectory() {} // note : you cannot declare this destructor abstract // it is always called by the descendant's destructor ! }; } #endif
37.018868
113
0.533894
[ "object" ]
b8525b3640e6d292a39fb6e83e277de63e221959
57,201
cpp
C++
lib/libzmq/src/socket_base.cpp
taylor-a-barnes/socket_timings
dfce53db806edf7db868d23cc2374e197b6a733a
[ "BSD-3-Clause" ]
6
2018-09-17T18:40:58.000Z
2021-08-05T20:10:31.000Z
lib/libzmq/src/socket_base.cpp
taylor-a-barnes/socket_timings
dfce53db806edf7db868d23cc2374e197b6a733a
[ "BSD-3-Clause" ]
45
2018-09-17T20:28:26.000Z
2021-08-14T19:39:30.000Z
lib/libzmq/src/socket_base.cpp
taylor-a-barnes/socket_timings
dfce53db806edf7db868d23cc2374e197b6a733a
[ "BSD-3-Clause" ]
12
2019-06-01T03:10:50.000Z
2022-02-01T02:23:23.000Z
/* Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "precompiled.hpp" #include <new> #include <string> #include <algorithm> #include "macros.hpp" #if defined ZMQ_HAVE_WINDOWS #if defined _MSC_VER #if defined _WIN32_WCE #include <cmnintrin.h> #else #include <intrin.h> #endif #endif #else #include <unistd.h> #include <ctype.h> #endif #include "socket_base.hpp" #include "tcp_listener.hpp" #include "ipc_listener.hpp" #include "tipc_listener.hpp" #include "tcp_connecter.hpp" #include "io_thread.hpp" #include "session_base.hpp" #include "config.hpp" #include "pipe.hpp" #include "err.hpp" #include "ctx.hpp" #include "likely.hpp" #include "msg.hpp" #include "address.hpp" #include "ipc_address.hpp" #include "tcp_address.hpp" #include "udp_address.hpp" #include "tipc_address.hpp" #include "mailbox.hpp" #include "mailbox_safe.hpp" #if defined ZMQ_HAVE_VMCI #include "vmci_address.hpp" #include "vmci_listener.hpp" #endif #ifdef ZMQ_HAVE_OPENPGM #include "pgm_socket.hpp" #endif #include "pair.hpp" #include "pub.hpp" #include "sub.hpp" #include "req.hpp" #include "rep.hpp" #include "pull.hpp" #include "push.hpp" #include "dealer.hpp" #include "router.hpp" #include "xpub.hpp" #include "xsub.hpp" #include "stream.hpp" #include "server.hpp" #include "client.hpp" #include "radio.hpp" #include "dish.hpp" #include "gather.hpp" #include "scatter.hpp" #include "dgram.hpp" void zmq::socket_base_t::inprocs_t::emplace (const char *endpoint_uri_, pipe_t *pipe_) { _inprocs.ZMQ_MAP_INSERT_OR_EMPLACE (std::string (endpoint_uri_), pipe_); } int zmq::socket_base_t::inprocs_t::erase_pipes ( const std::string &endpoint_uri_str_) { const std::pair<map_t::iterator, map_t::iterator> range = _inprocs.equal_range (endpoint_uri_str_); if (range.first == range.second) { errno = ENOENT; return -1; } for (map_t::iterator it = range.first; it != range.second; ++it) it->second->terminate (true); _inprocs.erase (range.first, range.second); return 0; } void zmq::socket_base_t::inprocs_t::erase_pipe (pipe_t *pipe_) { for (map_t::iterator it = _inprocs.begin (), end = _inprocs.end (); it != end; ++it) if (it->second == pipe_) { _inprocs.erase (it); break; } } bool zmq::socket_base_t::check_tag () const { return _tag == 0xbaddecaf; } bool zmq::socket_base_t::is_thread_safe () const { return _thread_safe; } zmq::socket_base_t *zmq::socket_base_t::create (int type_, class ctx_t *parent_, uint32_t tid_, int sid_) { socket_base_t *s = NULL; switch (type_) { case ZMQ_PAIR: s = new (std::nothrow) pair_t (parent_, tid_, sid_); break; case ZMQ_PUB: s = new (std::nothrow) pub_t (parent_, tid_, sid_); break; case ZMQ_SUB: s = new (std::nothrow) sub_t (parent_, tid_, sid_); break; case ZMQ_REQ: s = new (std::nothrow) req_t (parent_, tid_, sid_); break; case ZMQ_REP: s = new (std::nothrow) rep_t (parent_, tid_, sid_); break; case ZMQ_DEALER: s = new (std::nothrow) dealer_t (parent_, tid_, sid_); break; case ZMQ_ROUTER: s = new (std::nothrow) router_t (parent_, tid_, sid_); break; case ZMQ_PULL: s = new (std::nothrow) pull_t (parent_, tid_, sid_); break; case ZMQ_PUSH: s = new (std::nothrow) push_t (parent_, tid_, sid_); break; case ZMQ_XPUB: s = new (std::nothrow) xpub_t (parent_, tid_, sid_); break; case ZMQ_XSUB: s = new (std::nothrow) xsub_t (parent_, tid_, sid_); break; case ZMQ_STREAM: s = new (std::nothrow) stream_t (parent_, tid_, sid_); break; case ZMQ_SERVER: s = new (std::nothrow) server_t (parent_, tid_, sid_); break; case ZMQ_CLIENT: s = new (std::nothrow) client_t (parent_, tid_, sid_); break; case ZMQ_RADIO: s = new (std::nothrow) radio_t (parent_, tid_, sid_); break; case ZMQ_DISH: s = new (std::nothrow) dish_t (parent_, tid_, sid_); break; case ZMQ_GATHER: s = new (std::nothrow) gather_t (parent_, tid_, sid_); break; case ZMQ_SCATTER: s = new (std::nothrow) scatter_t (parent_, tid_, sid_); break; case ZMQ_DGRAM: s = new (std::nothrow) dgram_t (parent_, tid_, sid_); break; default: errno = EINVAL; return NULL; } alloc_assert (s); if (s->_mailbox == NULL) { s->_destroyed = true; LIBZMQ_DELETE (s); return NULL; } return s; } zmq::socket_base_t::socket_base_t (ctx_t *parent_, uint32_t tid_, int sid_, bool thread_safe_) : own_t (parent_, tid_), _tag (0xbaddecaf), _ctx_terminated (false), _destroyed (false), _poller (NULL), _handle (static_cast<poller_t::handle_t> (NULL)), _last_tsc (0), _ticks (0), _rcvmore (false), _monitor_socket (NULL), _monitor_events (0), _thread_safe (thread_safe_), _reaper_signaler (NULL), _sync (), _monitor_sync () { options.socket_id = sid_; options.ipv6 = (parent_->get (ZMQ_IPV6) != 0); options.linger.store (parent_->get (ZMQ_BLOCKY) ? -1 : 0); options.zero_copy = parent_->get (ZMQ_ZERO_COPY_RECV) != 0; if (_thread_safe) { _mailbox = new (std::nothrow) mailbox_safe_t (&_sync); zmq_assert (_mailbox); } else { mailbox_t *m = new (std::nothrow) mailbox_t (); zmq_assert (m); if (m->get_fd () != retired_fd) _mailbox = m; else { LIBZMQ_DELETE (m); _mailbox = NULL; } } } int zmq::socket_base_t::get_peer_state (const void *routing_id_, size_t routing_id_size_) const { LIBZMQ_UNUSED (routing_id_); LIBZMQ_UNUSED (routing_id_size_); // Only ROUTER sockets support this errno = ENOTSUP; return -1; } zmq::socket_base_t::~socket_base_t () { if (_mailbox) LIBZMQ_DELETE (_mailbox); if (_reaper_signaler) LIBZMQ_DELETE (_reaper_signaler); scoped_lock_t lock (_monitor_sync); stop_monitor (); zmq_assert (_destroyed); } zmq::i_mailbox *zmq::socket_base_t::get_mailbox () const { return _mailbox; } void zmq::socket_base_t::stop () { // Called by ctx when it is terminated (zmq_ctx_term). // 'stop' command is sent from the threads that called zmq_ctx_term to // the thread owning the socket. This way, blocking call in the // owner thread can be interrupted. send_stop (); } // TODO consider renaming protocol_ to scheme_ in conformance with RFC 3986 // terminology, but this requires extensive changes to be consistent int zmq::socket_base_t::parse_uri (const char *uri_, std::string &protocol_, std::string &path_) { zmq_assert (uri_ != NULL); std::string uri (uri_); const std::string::size_type pos = uri.find ("://"); if (pos == std::string::npos) { errno = EINVAL; return -1; } protocol_ = uri.substr (0, pos); path_ = uri.substr (pos + 3); if (protocol_.empty () || path_.empty ()) { errno = EINVAL; return -1; } return 0; } int zmq::socket_base_t::check_protocol (const std::string &protocol_) const { // First check out whether the protocol is something we are aware of. if (protocol_ != protocol_name::inproc #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS \ && !defined ZMQ_HAVE_VXWORKS && protocol_ != protocol_name::ipc #endif && protocol_ != protocol_name::tcp #if defined ZMQ_HAVE_OPENPGM // pgm/epgm transports only available if 0MQ is compiled with OpenPGM. && protocol_ != "pgm" && protocol_ != "epgm" #endif #if defined ZMQ_HAVE_TIPC // TIPC transport is only available on Linux. && protocol_ != protocol_name::tipc #endif #if defined ZMQ_HAVE_NORM && protocol_ != "norm" #endif #if defined ZMQ_HAVE_VMCI && protocol_ != protocol_name::vmci #endif && protocol_ != protocol_name::udp) { errno = EPROTONOSUPPORT; return -1; } // Check whether socket type and transport protocol match. // Specifically, multicast protocols can't be combined with // bi-directional messaging patterns (socket types). #if defined ZMQ_HAVE_OPENPGM || defined ZMQ_HAVE_NORM if ((protocol_ == "pgm" || protocol_ == "epgm" || protocol_ == "norm") && options.type != ZMQ_PUB && options.type != ZMQ_SUB && options.type != ZMQ_XPUB && options.type != ZMQ_XSUB) { errno = ENOCOMPATPROTO; return -1; } #endif if (protocol_ == protocol_name::udp && (options.type != ZMQ_DISH && options.type != ZMQ_RADIO && options.type != ZMQ_DGRAM)) { errno = ENOCOMPATPROTO; return -1; } // Protocol is available. return 0; } void zmq::socket_base_t::attach_pipe (pipe_t *pipe_, bool subscribe_to_all_, bool locally_initiated_) { // First, register the pipe so that we can terminate it later on. pipe_->set_event_sink (this); _pipes.push_back (pipe_); // Let the derived socket type know about new pipe. xattach_pipe (pipe_, subscribe_to_all_, locally_initiated_); // If the socket is already being closed, ask any new pipes to terminate // straight away. if (is_terminating ()) { register_term_acks (1); pipe_->terminate (false); } } int zmq::socket_base_t::setsockopt (int option_, const void *optval_, size_t optvallen_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); if (unlikely (_ctx_terminated)) { errno = ETERM; return -1; } // First, check whether specific socket type overloads the option. int rc = xsetsockopt (option_, optval_, optvallen_); if (rc == 0 || errno != EINVAL) { return rc; } // If the socket type doesn't support the option, pass it to // the generic option parser. rc = options.setsockopt (option_, optval_, optvallen_); update_pipe_options (option_); return rc; } int zmq::socket_base_t::getsockopt (int option_, void *optval_, size_t *optvallen_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); if (unlikely (_ctx_terminated)) { errno = ETERM; return -1; } if (option_ == ZMQ_RCVMORE) { return do_getsockopt<int> (optval_, optvallen_, _rcvmore ? 1 : 0); } if (option_ == ZMQ_FD) { if (_thread_safe) { // thread safe socket doesn't provide file descriptor errno = EINVAL; return -1; } return do_getsockopt<fd_t> ( optval_, optvallen_, (static_cast<mailbox_t *> (_mailbox))->get_fd ()); } if (option_ == ZMQ_EVENTS) { const int rc = process_commands (0, false); if (rc != 0 && (errno == EINTR || errno == ETERM)) { return -1; } errno_assert (rc == 0); return do_getsockopt<int> (optval_, optvallen_, (has_out () ? ZMQ_POLLOUT : 0) | (has_in () ? ZMQ_POLLIN : 0)); } if (option_ == ZMQ_LAST_ENDPOINT) { return do_getsockopt (optval_, optvallen_, _last_endpoint); } if (option_ == ZMQ_THREAD_SAFE) { return do_getsockopt<int> (optval_, optvallen_, _thread_safe ? 1 : 0); } return options.getsockopt (option_, optval_, optvallen_); } int zmq::socket_base_t::join (const char *group_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); return xjoin (group_); } int zmq::socket_base_t::leave (const char *group_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); return xleave (group_); } void zmq::socket_base_t::add_signaler (signaler_t *s_) { zmq_assert (_thread_safe); scoped_lock_t sync_lock (_sync); (static_cast<mailbox_safe_t *> (_mailbox))->add_signaler (s_); } void zmq::socket_base_t::remove_signaler (signaler_t *s_) { zmq_assert (_thread_safe); scoped_lock_t sync_lock (_sync); (static_cast<mailbox_safe_t *> (_mailbox))->remove_signaler (s_); } int zmq::socket_base_t::bind (const char *endpoint_uri_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); if (unlikely (_ctx_terminated)) { errno = ETERM; return -1; } // Process pending commands, if any. int rc = process_commands (0, false); if (unlikely (rc != 0)) { return -1; } // Parse endpoint_uri_ string. std::string protocol; std::string address; if (parse_uri (endpoint_uri_, protocol, address) || check_protocol (protocol)) { return -1; } if (protocol == protocol_name::inproc) { const endpoint_t endpoint = {this, options}; rc = register_endpoint (endpoint_uri_, endpoint); if (rc == 0) { connect_pending (endpoint_uri_, this); _last_endpoint.assign (endpoint_uri_); options.connected = true; } return rc; } if (protocol == "pgm" || protocol == "epgm" || protocol == "norm") { // For convenience's sake, bind can be used interchangeable with // connect for PGM, EPGM, NORM transports. rc = connect (endpoint_uri_); if (rc != -1) options.connected = true; return rc; } if (protocol == protocol_name::udp) { if (!(options.type == ZMQ_DGRAM || options.type == ZMQ_DISH)) { errno = ENOCOMPATPROTO; return -1; } // Choose the I/O thread to run the session in. io_thread_t *io_thread = choose_io_thread (options.affinity); if (!io_thread) { errno = EMTHREAD; return -1; } address_t *paddr = new (std::nothrow) address_t (protocol, address, this->get_ctx ()); alloc_assert (paddr); paddr->resolved.udp_addr = new (std::nothrow) udp_address_t (); alloc_assert (paddr->resolved.udp_addr); rc = paddr->resolved.udp_addr->resolve (address.c_str (), true, options.ipv6); if (rc != 0) { LIBZMQ_DELETE (paddr); return -1; } session_base_t *session = session_base_t::create (io_thread, true, this, options, paddr); errno_assert (session); // Create a bi-directional pipe. object_t *parents[2] = {this, session}; pipe_t *new_pipes[2] = {NULL, NULL}; int hwms[2] = {options.sndhwm, options.rcvhwm}; bool conflates[2] = {false, false}; rc = pipepair (parents, new_pipes, hwms, conflates); errno_assert (rc == 0); // Attach local end of the pipe to the socket object. attach_pipe (new_pipes[0], true, true); pipe_t *const newpipe = new_pipes[0]; // Attach remote end of the pipe to the session object later on. session->attach_pipe (new_pipes[1]); // Save last endpoint URI paddr->to_string (_last_endpoint); add_endpoint (endpoint_uri_, static_cast<own_t *> (session), newpipe); return 0; } // Remaining transports require to be run in an I/O thread, so at this // point we'll choose one. io_thread_t *io_thread = choose_io_thread (options.affinity); if (!io_thread) { errno = EMTHREAD; return -1; } if (protocol == protocol_name::tcp) { tcp_listener_t *listener = new (std::nothrow) tcp_listener_t (io_thread, this, options); alloc_assert (listener); rc = listener->set_address (address.c_str ()); if (rc != 0) { LIBZMQ_DELETE (listener); event_bind_failed (address, zmq_errno ()); return -1; } // Save last endpoint URI listener->get_address (_last_endpoint); add_endpoint (_last_endpoint.c_str (), static_cast<own_t *> (listener), NULL); options.connected = true; return 0; } #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS \ && !defined ZMQ_HAVE_VXWORKS if (protocol == protocol_name::ipc) { ipc_listener_t *listener = new (std::nothrow) ipc_listener_t (io_thread, this, options); alloc_assert (listener); int rc = listener->set_address (address.c_str ()); if (rc != 0) { LIBZMQ_DELETE (listener); event_bind_failed (address, zmq_errno ()); return -1; } // Save last endpoint URI listener->get_address (_last_endpoint); add_endpoint (_last_endpoint.c_str (), static_cast<own_t *> (listener), NULL); options.connected = true; return 0; } #endif #if defined ZMQ_HAVE_TIPC if (protocol == protocol_name::tipc) { tipc_listener_t *listener = new (std::nothrow) tipc_listener_t (io_thread, this, options); alloc_assert (listener); int rc = listener->set_address (address.c_str ()); if (rc != 0) { LIBZMQ_DELETE (listener); event_bind_failed (address, zmq_errno ()); return -1; } // Save last endpoint URI listener->get_address (_last_endpoint); add_endpoint (endpoint_uri_, static_cast<own_t *> (listener), NULL); options.connected = true; return 0; } #endif #if defined ZMQ_HAVE_VMCI if (protocol == protocol_name::vmci) { vmci_listener_t *listener = new (std::nothrow) vmci_listener_t (io_thread, this, options); alloc_assert (listener); int rc = listener->set_address (address.c_str ()); if (rc != 0) { LIBZMQ_DELETE (listener); event_bind_failed (address, zmq_errno ()); return -1; } listener->get_address (_last_endpoint); add_endpoint (_last_endpoint.c_str (), static_cast<own_t *> (listener), NULL); options.connected = true; return 0; } #endif zmq_assert (false); return -1; } int zmq::socket_base_t::connect (const char *endpoint_uri_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); if (unlikely (_ctx_terminated)) { errno = ETERM; return -1; } // Process pending commands, if any. int rc = process_commands (0, false); if (unlikely (rc != 0)) { return -1; } // Parse endpoint_uri_ string. std::string protocol; std::string address; if (parse_uri (endpoint_uri_, protocol, address) || check_protocol (protocol)) { return -1; } if (protocol == protocol_name::inproc) { // TODO: inproc connect is specific with respect to creating pipes // as there's no 'reconnect' functionality implemented. Once that // is in place we should follow generic pipe creation algorithm. // Find the peer endpoint. const endpoint_t peer = find_endpoint (endpoint_uri_); // The total HWM for an inproc connection should be the sum of // the binder's HWM and the connector's HWM. const int sndhwm = peer.socket == NULL ? options.sndhwm : options.sndhwm != 0 && peer.options.rcvhwm != 0 ? options.sndhwm + peer.options.rcvhwm : 0; const int rcvhwm = peer.socket == NULL ? options.rcvhwm : options.rcvhwm != 0 && peer.options.sndhwm != 0 ? options.rcvhwm + peer.options.sndhwm : 0; // Create a bi-directional pipe to connect the peers. object_t *parents[2] = {this, peer.socket == NULL ? this : peer.socket}; pipe_t *new_pipes[2] = {NULL, NULL}; const bool conflate = get_effective_conflate_option (options); int hwms[2] = {conflate ? -1 : sndhwm, conflate ? -1 : rcvhwm}; bool conflates[2] = {conflate, conflate}; rc = pipepair (parents, new_pipes, hwms, conflates); if (!conflate) { new_pipes[0]->set_hwms_boost (peer.options.sndhwm, peer.options.rcvhwm); new_pipes[1]->set_hwms_boost (options.sndhwm, options.rcvhwm); } errno_assert (rc == 0); if (!peer.socket) { // The peer doesn't exist yet so we don't know whether // to send the routing id message or not. To resolve this, // we always send our routing id and drop it later if // the peer doesn't expect it. send_routing_id (new_pipes[0], options); const endpoint_t endpoint = {this, options}; pend_connection (std::string (endpoint_uri_), endpoint, new_pipes); } else { // If required, send the routing id of the local socket to the peer. if (peer.options.recv_routing_id) { send_routing_id (new_pipes[0], options); } // If required, send the routing id of the peer to the local socket. if (options.recv_routing_id) { send_routing_id (new_pipes[1], peer.options); } // Attach remote end of the pipe to the peer socket. Note that peer's // seqnum was incremented in find_endpoint function. We don't need it // increased here. send_bind (peer.socket, new_pipes[1], false); } // Attach local end of the pipe to this socket object. attach_pipe (new_pipes[0], false, true); // Save last endpoint URI _last_endpoint.assign (endpoint_uri_); // remember inproc connections for disconnect _inprocs.emplace (endpoint_uri_, new_pipes[0]); options.connected = true; return 0; } const bool is_single_connect = (options.type == ZMQ_DEALER || options.type == ZMQ_SUB || options.type == ZMQ_PUB || options.type == ZMQ_REQ); if (unlikely (is_single_connect)) { if (0 != _endpoints.count (endpoint_uri_)) { // There is no valid use for multiple connects for SUB-PUB nor // DEALER-ROUTER nor REQ-REP. Multiple connects produces // nonsensical results. return 0; } } // Choose the I/O thread to run the session in. io_thread_t *io_thread = choose_io_thread (options.affinity); if (!io_thread) { errno = EMTHREAD; return -1; } address_t *paddr = new (std::nothrow) address_t (protocol, address, this->get_ctx ()); alloc_assert (paddr); // Resolve address (if needed by the protocol) if (protocol == protocol_name::tcp) { // Do some basic sanity checks on tcp:// address syntax // - hostname starts with digit or letter, with embedded '-' or '.' // - IPv6 address may contain hex chars and colons. // - IPv6 link local address may contain % followed by interface name / zone_id // (Reference: https://tools.ietf.org/html/rfc4007) // - IPv4 address may contain decimal digits and dots. // - Address must end in ":port" where port is *, or numeric // - Address may contain two parts separated by ':' // Following code is quick and dirty check to catch obvious errors, // without trying to be fully accurate. const char *check = address.c_str (); if (isalnum (*check) || isxdigit (*check) || *check == '[' || *check == ':') { check++; while (isalnum (*check) || isxdigit (*check) || *check == '.' || *check == '-' || *check == ':' || *check == '%' || *check == ';' || *check == '[' || *check == ']' || *check == '_' || *check == '*') { check++; } } // Assume the worst, now look for success rc = -1; // Did we reach the end of the address safely? if (*check == 0) { // Do we have a valid port string? (cannot be '*' in connect check = strrchr (address.c_str (), ':'); if (check) { check++; if (*check && (isdigit (*check))) rc = 0; // Valid } } if (rc == -1) { errno = EINVAL; LIBZMQ_DELETE (paddr); return -1; } // Defer resolution until a socket is opened paddr->resolved.tcp_addr = NULL; } #if !defined ZMQ_HAVE_WINDOWS && !defined ZMQ_HAVE_OPENVMS \ && !defined ZMQ_HAVE_VXWORKS else if (protocol == protocol_name::ipc) { paddr->resolved.ipc_addr = new (std::nothrow) ipc_address_t (); alloc_assert (paddr->resolved.ipc_addr); int rc = paddr->resolved.ipc_addr->resolve (address.c_str ()); if (rc != 0) { LIBZMQ_DELETE (paddr); return -1; } } #endif if (protocol == protocol_name::udp) { if (options.type != ZMQ_RADIO) { errno = ENOCOMPATPROTO; LIBZMQ_DELETE (paddr); return -1; } paddr->resolved.udp_addr = new (std::nothrow) udp_address_t (); alloc_assert (paddr->resolved.udp_addr); rc = paddr->resolved.udp_addr->resolve (address.c_str (), false, options.ipv6); if (rc != 0) { LIBZMQ_DELETE (paddr); return -1; } } // TBD - Should we check address for ZMQ_HAVE_NORM??? #ifdef ZMQ_HAVE_OPENPGM if (protocol == "pgm" || protocol == "epgm") { struct pgm_addrinfo_t *res = NULL; uint16_t port_number = 0; int rc = pgm_socket_t::init_address (address.c_str (), &res, &port_number); if (res != NULL) pgm_freeaddrinfo (res); if (rc != 0 || port_number == 0) { return -1; } } #endif #if defined ZMQ_HAVE_TIPC else if (protocol == protocol_name::tipc) { paddr->resolved.tipc_addr = new (std::nothrow) tipc_address_t (); alloc_assert (paddr->resolved.tipc_addr); int rc = paddr->resolved.tipc_addr->resolve (address.c_str ()); if (rc != 0) { LIBZMQ_DELETE (paddr); return -1; } sockaddr_tipc *saddr = (sockaddr_tipc *) paddr->resolved.tipc_addr->addr (); // Cannot connect to random Port Identity if (saddr->addrtype == TIPC_ADDR_ID && paddr->resolved.tipc_addr->is_random ()) { LIBZMQ_DELETE (paddr); errno = EINVAL; return -1; } } #endif #if defined ZMQ_HAVE_VMCI else if (protocol == protocol_name::vmci) { paddr->resolved.vmci_addr = new (std::nothrow) vmci_address_t (this->get_ctx ()); alloc_assert (paddr->resolved.vmci_addr); int rc = paddr->resolved.vmci_addr->resolve (address.c_str ()); if (rc != 0) { LIBZMQ_DELETE (paddr); return -1; } } #endif // Create session. session_base_t *session = session_base_t::create (io_thread, true, this, options, paddr); errno_assert (session); // PGM does not support subscription forwarding; ask for all data to be // sent to this pipe. (same for NORM, currently?) const bool subscribe_to_all = protocol == "pgm" || protocol == "epgm" || protocol == "norm" || protocol == protocol_name::udp; pipe_t *newpipe = NULL; if (options.immediate != 1 || subscribe_to_all) { // Create a bi-directional pipe. object_t *parents[2] = {this, session}; pipe_t *new_pipes[2] = {NULL, NULL}; const bool conflate = get_effective_conflate_option (options); int hwms[2] = {conflate ? -1 : options.sndhwm, conflate ? -1 : options.rcvhwm}; bool conflates[2] = {conflate, conflate}; rc = pipepair (parents, new_pipes, hwms, conflates); errno_assert (rc == 0); // Attach local end of the pipe to the socket object. attach_pipe (new_pipes[0], subscribe_to_all, true); newpipe = new_pipes[0]; // Attach remote end of the pipe to the session object later on. session->attach_pipe (new_pipes[1]); } // Save last endpoint URI paddr->to_string (_last_endpoint); add_endpoint (endpoint_uri_, static_cast<own_t *> (session), newpipe); return 0; } std::string zmq::socket_base_t::resolve_tcp_addr (std::string endpoint_uri_, const char *tcp_address_) { // The resolved last_endpoint is used as a key in the endpoints map. // The address passed by the user might not match in the TCP case due to // IPv4-in-IPv6 mapping (EG: tcp://[::ffff:127.0.0.1]:9999), so try to // resolve before giving up. Given at this stage we don't know whether a // socket is connected or bound, try with both. if (_endpoints.find (endpoint_uri_) == _endpoints.end ()) { tcp_address_t *tcp_addr = new (std::nothrow) tcp_address_t (); alloc_assert (tcp_addr); int rc = tcp_addr->resolve (tcp_address_, false, options.ipv6); if (rc == 0) { tcp_addr->to_string (endpoint_uri_); if (_endpoints.find (endpoint_uri_) == _endpoints.end ()) { rc = tcp_addr->resolve (tcp_address_, true, options.ipv6); if (rc == 0) { tcp_addr->to_string (endpoint_uri_); } } } LIBZMQ_DELETE (tcp_addr); } return endpoint_uri_; } void zmq::socket_base_t::add_endpoint (const char *endpoint_uri_, own_t *endpoint_, pipe_t *pipe_) { // Activate the session. Make it a child of this socket. launch_child (endpoint_); _endpoints.ZMQ_MAP_INSERT_OR_EMPLACE (std::string (endpoint_uri_), endpoint_pipe_t (endpoint_, pipe_)); } int zmq::socket_base_t::term_endpoint (const char *endpoint_uri_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); // Check whether the library haven't been shut down yet. if (unlikely (_ctx_terminated)) { errno = ETERM; return -1; } // Check whether endpoint address passed to the function is valid. if (unlikely (!endpoint_uri_)) { errno = EINVAL; return -1; } // Process pending commands, if any, since there could be pending unprocessed process_own()'s // (from launch_child() for example) we're asked to terminate now. const int rc = process_commands (0, false); if (unlikely (rc != 0)) { return -1; } // Parse endpoint_uri_ string. std::string uri_protocol; std::string uri_path; if (parse_uri (endpoint_uri_, uri_protocol, uri_path) || check_protocol (uri_protocol)) { return -1; } const std::string endpoint_uri_str = std::string (endpoint_uri_); // Disconnect an inproc socket if (uri_protocol == protocol_name::inproc) { return unregister_endpoint (endpoint_uri_str, this) == 0 ? 0 : _inprocs.erase_pipes (endpoint_uri_str); } const std::string resolved_endpoint_uri = uri_protocol == protocol_name::tcp ? resolve_tcp_addr (endpoint_uri_str, uri_path.c_str ()) : endpoint_uri_str; // Find the endpoints range (if any) corresponding to the endpoint_uri_ string. const std::pair<endpoints_t::iterator, endpoints_t::iterator> range = _endpoints.equal_range (resolved_endpoint_uri); if (range.first == range.second) { errno = ENOENT; return -1; } for (endpoints_t::iterator it = range.first; it != range.second; ++it) { // If we have an associated pipe, terminate it. if (it->second.second != NULL) it->second.second->terminate (false); term_child (it->second.first); } _endpoints.erase (range.first, range.second); return 0; } int zmq::socket_base_t::send (msg_t *msg_, int flags_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); // Check whether the library haven't been shut down yet. if (unlikely (_ctx_terminated)) { errno = ETERM; return -1; } // Check whether message passed to the function is valid. if (unlikely (!msg_ || !msg_->check ())) { errno = EFAULT; return -1; } // Process pending commands, if any. int rc = process_commands (0, true); if (unlikely (rc != 0)) { return -1; } // Clear any user-visible flags that are set on the message. msg_->reset_flags (msg_t::more); // At this point we impose the flags on the message. if (flags_ & ZMQ_SNDMORE) msg_->set_flags (msg_t::more); msg_->reset_metadata (); // Try to send the message using method in each socket class rc = xsend (msg_); if (rc == 0) { return 0; } if (unlikely (errno != EAGAIN)) { return -1; } // In case of non-blocking send we'll simply propagate // the error - including EAGAIN - up the stack. if ((flags_ & ZMQ_DONTWAIT) || options.sndtimeo == 0) { return -1; } // Compute the time when the timeout should occur. // If the timeout is infinite, don't care. int timeout = options.sndtimeo; const uint64_t end = timeout < 0 ? 0 : (_clock.now_ms () + timeout); // Oops, we couldn't send the message. Wait for the next // command, process it and try to send the message again. // If timeout is reached in the meantime, return EAGAIN. while (true) { if (unlikely (process_commands (timeout, false) != 0)) { return -1; } rc = xsend (msg_); if (rc == 0) break; if (unlikely (errno != EAGAIN)) { return -1; } if (timeout > 0) { timeout = static_cast<int> (end - _clock.now_ms ()); if (timeout <= 0) { errno = EAGAIN; return -1; } } } return 0; } int zmq::socket_base_t::recv (msg_t *msg_, int flags_) { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); // Check whether the library haven't been shut down yet. if (unlikely (_ctx_terminated)) { errno = ETERM; return -1; } // Check whether message passed to the function is valid. if (unlikely (!msg_ || !msg_->check ())) { errno = EFAULT; return -1; } // Once every inbound_poll_rate messages check for signals and process // incoming commands. This happens only if we are not polling altogether // because there are messages available all the time. If poll occurs, // ticks is set to zero and thus we avoid this code. // // Note that 'recv' uses different command throttling algorithm (the one // described above) from the one used by 'send'. This is because counting // ticks is more efficient than doing RDTSC all the time. if (++_ticks == inbound_poll_rate) { if (unlikely (process_commands (0, false) != 0)) { return -1; } _ticks = 0; } // Get the message. int rc = xrecv (msg_); if (unlikely (rc != 0 && errno != EAGAIN)) { return -1; } // If we have the message, return immediately. if (rc == 0) { extract_flags (msg_); return 0; } // If the message cannot be fetched immediately, there are two scenarios. // For non-blocking recv, commands are processed in case there's an // activate_reader command already waiting in a command pipe. // If it's not, return EAGAIN. if ((flags_ & ZMQ_DONTWAIT) || options.rcvtimeo == 0) { if (unlikely (process_commands (0, false) != 0)) { return -1; } _ticks = 0; rc = xrecv (msg_); if (rc < 0) { return rc; } extract_flags (msg_); return 0; } // Compute the time when the timeout should occur. // If the timeout is infinite, don't care. int timeout = options.rcvtimeo; const uint64_t end = timeout < 0 ? 0 : (_clock.now_ms () + timeout); // In blocking scenario, commands are processed over and over again until // we are able to fetch a message. bool block = (_ticks != 0); while (true) { if (unlikely (process_commands (block ? timeout : 0, false) != 0)) { return -1; } rc = xrecv (msg_); if (rc == 0) { _ticks = 0; break; } if (unlikely (errno != EAGAIN)) { return -1; } block = true; if (timeout > 0) { timeout = static_cast<int> (end - _clock.now_ms ()); if (timeout <= 0) { errno = EAGAIN; return -1; } } } extract_flags (msg_); return 0; } int zmq::socket_base_t::close () { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); // Remove all existing signalers for thread safe sockets if (_thread_safe) (static_cast<mailbox_safe_t *> (_mailbox))->clear_signalers (); // Mark the socket as dead _tag = 0xdeadbeef; // Transfer the ownership of the socket from this application thread // to the reaper thread which will take care of the rest of shutdown // process. send_reap (this); return 0; } bool zmq::socket_base_t::has_in () { return xhas_in (); } bool zmq::socket_base_t::has_out () { return xhas_out (); } void zmq::socket_base_t::start_reaping (poller_t *poller_) { // Plug the socket to the reaper thread. _poller = poller_; fd_t fd; if (!_thread_safe) fd = (static_cast<mailbox_t *> (_mailbox))->get_fd (); else { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); _reaper_signaler = new (std::nothrow) signaler_t (); zmq_assert (_reaper_signaler); // Add signaler to the safe mailbox fd = _reaper_signaler->get_fd (); (static_cast<mailbox_safe_t *> (_mailbox)) ->add_signaler (_reaper_signaler); // Send a signal to make sure reaper handle existing commands _reaper_signaler->send (); } _handle = _poller->add_fd (fd, this); _poller->set_pollin (_handle); // Initialise the termination and check whether it can be deallocated // immediately. terminate (); check_destroy (); } int zmq::socket_base_t::process_commands (int timeout_, bool throttle_) { if (timeout_ == 0) { // If we are asked not to wait, check whether we haven't processed // commands recently, so that we can throttle the new commands. // Get the CPU's tick counter. If 0, the counter is not available. const uint64_t tsc = zmq::clock_t::rdtsc (); // Optimised version of command processing - it doesn't have to check // for incoming commands each time. It does so only if certain time // elapsed since last command processing. Command delay varies // depending on CPU speed: It's ~1ms on 3GHz CPU, ~2ms on 1.5GHz CPU // etc. The optimisation makes sense only on platforms where getting // a timestamp is a very cheap operation (tens of nanoseconds). if (tsc && throttle_) { // Check whether TSC haven't jumped backwards (in case of migration // between CPU cores) and whether certain time have elapsed since // last command processing. If it didn't do nothing. if (tsc >= _last_tsc && tsc - _last_tsc <= max_command_delay) return 0; _last_tsc = tsc; } } // Check whether there are any commands pending for this thread. command_t cmd; int rc = _mailbox->recv (&cmd, timeout_); // Process all available commands. while (rc == 0) { cmd.destination->process_command (cmd); rc = _mailbox->recv (&cmd, 0); } if (errno == EINTR) return -1; zmq_assert (errno == EAGAIN); if (_ctx_terminated) { errno = ETERM; return -1; } return 0; } void zmq::socket_base_t::process_stop () { // Here, someone have called zmq_ctx_term while the socket was still alive. // We'll remember the fact so that any blocking call is interrupted and any // further attempt to use the socket will return ETERM. The user is still // responsible for calling zmq_close on the socket though! scoped_lock_t lock (_monitor_sync); stop_monitor (); _ctx_terminated = true; } void zmq::socket_base_t::process_bind (pipe_t *pipe_) { attach_pipe (pipe_); } void zmq::socket_base_t::process_term (int linger_) { // Unregister all inproc endpoints associated with this socket. // Doing this we make sure that no new pipes from other sockets (inproc) // will be initiated. unregister_endpoints (this); // Ask all attached pipes to terminate. for (pipes_t::size_type i = 0; i != _pipes.size (); ++i) _pipes[i]->terminate (false); register_term_acks (static_cast<int> (_pipes.size ())); // Continue the termination process immediately. own_t::process_term (linger_); } void zmq::socket_base_t::process_term_endpoint (std::string *endpoint_) { term_endpoint (endpoint_->c_str ()); delete endpoint_; } void zmq::socket_base_t::update_pipe_options (int option_) { if (option_ == ZMQ_SNDHWM || option_ == ZMQ_RCVHWM) { for (pipes_t::size_type i = 0; i != _pipes.size (); ++i) { _pipes[i]->set_hwms (options.rcvhwm, options.sndhwm); _pipes[i]->send_hwms_to_peer (options.sndhwm, options.rcvhwm); } } } void zmq::socket_base_t::process_destroy () { _destroyed = true; } int zmq::socket_base_t::xsetsockopt (int, const void *, size_t) { errno = EINVAL; return -1; } bool zmq::socket_base_t::xhas_out () { return false; } int zmq::socket_base_t::xsend (msg_t *) { errno = ENOTSUP; return -1; } bool zmq::socket_base_t::xhas_in () { return false; } int zmq::socket_base_t::xjoin (const char *group_) { LIBZMQ_UNUSED (group_); errno = ENOTSUP; return -1; } int zmq::socket_base_t::xleave (const char *group_) { LIBZMQ_UNUSED (group_); errno = ENOTSUP; return -1; } int zmq::socket_base_t::xrecv (msg_t *) { errno = ENOTSUP; return -1; } void zmq::socket_base_t::xread_activated (pipe_t *) { zmq_assert (false); } void zmq::socket_base_t::xwrite_activated (pipe_t *) { zmq_assert (false); } void zmq::socket_base_t::xhiccuped (pipe_t *) { zmq_assert (false); } void zmq::socket_base_t::in_event () { // This function is invoked only once the socket is running in the context // of the reaper thread. Process any commands from other threads/sockets // that may be available at the moment. Ultimately, the socket will // be destroyed. { scoped_optional_lock_t sync_lock (_thread_safe ? &_sync : NULL); // If the socket is thread safe we need to unsignal the reaper signaler if (_thread_safe) _reaper_signaler->recv (); process_commands (0, false); } check_destroy (); } void zmq::socket_base_t::out_event () { zmq_assert (false); } void zmq::socket_base_t::timer_event (int) { zmq_assert (false); } void zmq::socket_base_t::check_destroy () { // If the object was already marked as destroyed, finish the deallocation. if (_destroyed) { // Remove the socket from the reaper's poller. _poller->rm_fd (_handle); // Remove the socket from the context. destroy_socket (this); // Notify the reaper about the fact. send_reaped (); // Deallocate. own_t::process_destroy (); } } void zmq::socket_base_t::read_activated (pipe_t *pipe_) { xread_activated (pipe_); } void zmq::socket_base_t::write_activated (pipe_t *pipe_) { xwrite_activated (pipe_); } void zmq::socket_base_t::hiccuped (pipe_t *pipe_) { if (options.immediate == 1) pipe_->terminate (false); else // Notify derived sockets of the hiccup xhiccuped (pipe_); } void zmq::socket_base_t::pipe_terminated (pipe_t *pipe_) { // Notify the specific socket type about the pipe termination. xpipe_terminated (pipe_); // Remove pipe from inproc pipes _inprocs.erase_pipe (pipe_); // Remove the pipe from the list of attached pipes and confirm its // termination if we are already shutting down. _pipes.erase (pipe_); if (is_terminating ()) unregister_term_ack (); } void zmq::socket_base_t::extract_flags (msg_t *msg_) { // Test whether routing_id flag is valid for this socket type. if (unlikely (msg_->flags () & msg_t::routing_id)) zmq_assert (options.recv_routing_id); // Remove MORE flag. _rcvmore = (msg_->flags () & msg_t::more) != 0; } int zmq::socket_base_t::monitor (const char *endpoint_, int events_) { scoped_lock_t lock (_monitor_sync); if (unlikely (_ctx_terminated)) { errno = ETERM; return -1; } // Support deregistering monitoring endpoints as well if (endpoint_ == NULL) { stop_monitor (); return 0; } // Parse endpoint_uri_ string. std::string protocol; std::string address; if (parse_uri (endpoint_, protocol, address) || check_protocol (protocol)) return -1; // Event notification only supported over inproc:// if (protocol != protocol_name::inproc) { errno = EPROTONOSUPPORT; return -1; } // already monitoring. Stop previous monitor before starting new one. if (_monitor_socket != NULL) { stop_monitor (true); } // Register events to monitor _monitor_events = events_; _monitor_socket = zmq_socket (get_ctx (), ZMQ_PAIR); if (_monitor_socket == NULL) return -1; // Never block context termination on pending event messages int linger = 0; int rc = zmq_setsockopt (_monitor_socket, ZMQ_LINGER, &linger, sizeof (linger)); if (rc == -1) stop_monitor (false); // Spawn the monitor socket endpoint rc = zmq_bind (_monitor_socket, endpoint_); if (rc == -1) stop_monitor (false); return rc; } void zmq::socket_base_t::event_connected (const std::string &endpoint_uri_, zmq::fd_t fd_) { event (endpoint_uri_, fd_, ZMQ_EVENT_CONNECTED); } void zmq::socket_base_t::event_connect_delayed ( const std::string &endpoint_uri_, int err_) { event (endpoint_uri_, err_, ZMQ_EVENT_CONNECT_DELAYED); } void zmq::socket_base_t::event_connect_retried ( const std::string &endpoint_uri_, int interval_) { event (endpoint_uri_, interval_, ZMQ_EVENT_CONNECT_RETRIED); } void zmq::socket_base_t::event_listening (const std::string &endpoint_uri_, zmq::fd_t fd_) { event (endpoint_uri_, fd_, ZMQ_EVENT_LISTENING); } void zmq::socket_base_t::event_bind_failed (const std::string &endpoint_uri_, int err_) { event (endpoint_uri_, err_, ZMQ_EVENT_BIND_FAILED); } void zmq::socket_base_t::event_accepted (const std::string &endpoint_uri_, zmq::fd_t fd_) { event (endpoint_uri_, fd_, ZMQ_EVENT_ACCEPTED); } void zmq::socket_base_t::event_accept_failed (const std::string &endpoint_uri_, int err_) { event (endpoint_uri_, err_, ZMQ_EVENT_ACCEPT_FAILED); } void zmq::socket_base_t::event_closed (const std::string &endpoint_uri_, zmq::fd_t fd_) { event (endpoint_uri_, fd_, ZMQ_EVENT_CLOSED); } void zmq::socket_base_t::event_close_failed (const std::string &endpoint_uri_, int err_) { event (endpoint_uri_, err_, ZMQ_EVENT_CLOSE_FAILED); } void zmq::socket_base_t::event_disconnected (const std::string &endpoint_uri_, zmq::fd_t fd_) { event (endpoint_uri_, fd_, ZMQ_EVENT_DISCONNECTED); } void zmq::socket_base_t::event_handshake_failed_no_detail ( const std::string &endpoint_uri_, int err_) { event (endpoint_uri_, err_, ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL); } void zmq::socket_base_t::event_handshake_failed_protocol ( const std::string &endpoint_uri_, int err_) { event (endpoint_uri_, err_, ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL); } void zmq::socket_base_t::event_handshake_failed_auth ( const std::string &endpoint_uri_, int err_) { event (endpoint_uri_, err_, ZMQ_EVENT_HANDSHAKE_FAILED_AUTH); } void zmq::socket_base_t::event_handshake_succeeded ( const std::string &endpoint_uri_, int err_) { event (endpoint_uri_, err_, ZMQ_EVENT_HANDSHAKE_SUCCEEDED); } void zmq::socket_base_t::event (const std::string &endpoint_uri_, intptr_t value_, int type_) { scoped_lock_t lock (_monitor_sync); if (_monitor_events & type_) { monitor_event (type_, value_, endpoint_uri_); } } // Send a monitor event void zmq::socket_base_t::monitor_event (int event_, intptr_t value_, const std::string &endpoint_uri_) const { // this is a private method which is only called from // contexts where the mutex has been locked before if (_monitor_socket) { // Send event in first frame const uint16_t event = static_cast<uint16_t> (event_); const uint32_t value = static_cast<uint32_t> (value_); zmq_msg_t msg; zmq_msg_init_size (&msg, sizeof (event) + sizeof (value)); uint8_t *data = static_cast<uint8_t *> (zmq_msg_data (&msg)); // Avoid dereferencing uint32_t on unaligned address memcpy (data + 0, &event, sizeof (event)); memcpy (data + sizeof (event), &value, sizeof (value)); zmq_sendmsg (_monitor_socket, &msg, ZMQ_SNDMORE); // Send address in second frame zmq_msg_init_size (&msg, endpoint_uri_.size ()); memcpy (zmq_msg_data (&msg), endpoint_uri_.c_str (), endpoint_uri_.size ()); zmq_sendmsg (_monitor_socket, &msg, 0); } } void zmq::socket_base_t::stop_monitor (bool send_monitor_stopped_event_) { // this is a private method which is only called from // contexts where the mutex has been locked before if (_monitor_socket) { if ((_monitor_events & ZMQ_EVENT_MONITOR_STOPPED) && send_monitor_stopped_event_) monitor_event (ZMQ_EVENT_MONITOR_STOPPED, 0, ""); zmq_close (_monitor_socket); _monitor_socket = NULL; _monitor_events = 0; } } zmq::routing_socket_base_t::routing_socket_base_t (class ctx_t *parent_, uint32_t tid_, int sid_) : socket_base_t (parent_, tid_, sid_) { } zmq::routing_socket_base_t::~routing_socket_base_t () { zmq_assert (_out_pipes.empty ()); } int zmq::routing_socket_base_t::xsetsockopt (int option_, const void *optval_, size_t optvallen_) { switch (option_) { case ZMQ_CONNECT_ROUTING_ID: // TODO why isn't it possible to set an empty connect_routing_id // (which is the default value) if (optval_ && optvallen_) { _connect_routing_id.assign (static_cast<const char *> (optval_), optvallen_); return 0; } break; } errno = EINVAL; return -1; } void zmq::routing_socket_base_t::xwrite_activated (pipe_t *pipe_) { const out_pipes_t::iterator end = _out_pipes.end (); out_pipes_t::iterator it; for (it = _out_pipes.begin (); it != end; ++it) if (it->second.pipe == pipe_) break; zmq_assert (it != end); zmq_assert (!it->second.active); it->second.active = true; } std::string zmq::routing_socket_base_t::extract_connect_routing_id () { std::string res = ZMQ_MOVE (_connect_routing_id); _connect_routing_id.clear (); return res; } bool zmq::routing_socket_base_t::connect_routing_id_is_set () const { return !_connect_routing_id.empty (); } void zmq::routing_socket_base_t::add_out_pipe (blob_t routing_id_, pipe_t *pipe_) { // Add the record into output pipes lookup table const out_pipe_t outpipe = {pipe_, true}; const bool ok = _out_pipes.ZMQ_MAP_INSERT_OR_EMPLACE (ZMQ_MOVE (routing_id_), outpipe) .second; zmq_assert (ok); } bool zmq::routing_socket_base_t::has_out_pipe (const blob_t &routing_id_) const { return 0 != _out_pipes.count (routing_id_); } zmq::routing_socket_base_t::out_pipe_t * zmq::routing_socket_base_t::lookup_out_pipe (const blob_t &routing_id_) { // TODO we could probably avoid constructor a temporary blob_t to call this function out_pipes_t::iterator it = _out_pipes.find (routing_id_); return it == _out_pipes.end () ? NULL : &it->second; } const zmq::routing_socket_base_t::out_pipe_t * zmq::routing_socket_base_t::lookup_out_pipe (const blob_t &routing_id_) const { // TODO we could probably avoid constructor a temporary blob_t to call this function const out_pipes_t::const_iterator it = _out_pipes.find (routing_id_); return it == _out_pipes.end () ? NULL : &it->second; } void zmq::routing_socket_base_t::erase_out_pipe (pipe_t *pipe_) { const size_t erased = _out_pipes.erase (pipe_->get_routing_id ()); zmq_assert (erased); } zmq::routing_socket_base_t::out_pipe_t zmq::routing_socket_base_t::try_erase_out_pipe (const blob_t &routing_id_) { const out_pipes_t::iterator it = _out_pipes.find (routing_id_); out_pipe_t res = {NULL, false}; if (it != _out_pipes.end ()) { res = it->second; _out_pipes.erase (it); } return res; }
30.902755
98
0.595916
[ "object" ]
b8551bd1980cdf67276b8a3099b4baf294974700
2,992
cc
C++
garnet/public/lib/ui/geometry/cpp/formatting.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
1
2019-04-21T18:02:26.000Z
2019-04-21T18:02:26.000Z
garnet/public/lib/ui/geometry/cpp/formatting.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
garnet/public/lib/ui/geometry/cpp/formatting.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Fuchsia 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 "lib/ui/geometry/cpp/formatting.h" #include <zircon/assert.h> #include <ostream> namespace fuchsia { namespace math { std::ostream& operator<<(std::ostream& os, const Point& value) { return os << "{x=" << value.x << ", y=" << value.y << "}"; } std::ostream& operator<<(std::ostream& os, const PointF& value) { return os << "{x=" << value.x << ", y=" << value.y << "}"; } std::ostream& operator<<(std::ostream& os, const Point3F& value) { return os << "{x=" << value.x << ", y=" << value.y << ", z=" << value.z << "}"; } std::ostream& operator<<(std::ostream& os, const Rect& value) { return os << "{x=" << value.x << ", y=" << value.y << ", width=" << value.width << ", height=" << value.height << "}"; } std::ostream& operator<<(std::ostream& os, const RectF& value) { return os << "{x=" << value.x << ", y=" << value.y << ", width=" << value.width << ", height=" << value.height << "}"; } std::ostream& operator<<(std::ostream& os, const RRectF& value) { return os << "{x=" << value.x << ", y=" << value.y << ", width=" << value.width << ", height=" << value.height << ", top_left_radius_x=" << value.top_left_radius_x << ", top_left_radius_y=" << value.top_left_radius_y << ", top_right_radius_x=" << value.top_right_radius_x << ", top_right_radius_y=" << value.top_right_radius_y << ", bottom_left_radius_x=" << value.bottom_left_radius_x << ", bottom_left_radius_y=" << value.bottom_left_radius_y << ", bottom_right_radius_x=" << value.bottom_right_radius_x << ", bottom_right_radius_y=" << value.bottom_right_radius_y << "}"; } std::ostream& operator<<(std::ostream& os, const Size& value) { return os << "{width=" << value.width << ", height=" << value.height << "}"; } std::ostream& operator<<(std::ostream& os, const SizeF& value) { return os << "{width=" << value.width << ", height=" << value.height << "}"; } std::ostream& operator<<(std::ostream& os, const Inset& value) { return os << "{left=" << value.left << ", top=" << value.top << ", right=" << value.right << ", bottom=" << value.bottom << "}"; } std::ostream& operator<<(std::ostream& os, const InsetF& value) { return os << "{left=" << value.left << ", top=" << value.top << ", right=" << value.right << ", bottom=" << value.bottom << "}"; } std::ostream& operator<<(std::ostream& os, const Transform& value) { ZX_DEBUG_ASSERT(value.matrix.size() == 16); os << "["; for (size_t i = 0; i < 4; i++) { if (i != 0) os << ", "; os << "["; for (size_t j = 0; j < 4; j++) { if (j != 0) os << ", "; os << value.matrix.at(i * 4 + j); } os << "]"; } os << "]"; return os; } } // namespace math } // namespace fuchsia
34.790698
95
0.549799
[ "geometry", "transform" ]
b8558e348f534fa0a551d9c5bfb633acae8df0f0
3,456
cpp
C++
src/libQts/QtsDvdFile.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
8
2016-08-09T14:05:58.000Z
2020-09-05T14:43:36.000Z
src/libQts/QtsDvdFile.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
15
2016-08-09T14:11:21.000Z
2022-01-15T23:39:07.000Z
src/libQts/QtsDvdFile.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
1
2017-08-26T22:08:58.000Z
2017-08-26T22:08:58.000Z
//---------------------------------------------------------------------------- // // Copyright (c) 2013-2017, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // //---------------------------------------------------------------------------- // // Qts, the Qt MPEG Transport Stream library. // Define the class QtsDvdFile. // //---------------------------------------------------------------------------- #include "QtsDvdFile.h" #include "QtsDvdMedia.h" //---------------------------------------------------------------------------- // Constructor and destructor. //---------------------------------------------------------------------------- QtsDvdFile::QtsDvdFile(const QString& path, int startSector, int sizeInBytes) : _path(path), _sector(startSector), _size(sizeInBytes) { } QtsDvdFile::~QtsDvdFile() { } //---------------------------------------------------------------------------- // Get the file characteristics. //---------------------------------------------------------------------------- QString QtsDvdFile::name() const { return _path.isEmpty() ? QString() : QFileInfo(_path).fileName(); } QString QtsDvdFile::description() const { return _path.isEmpty() ? "metadata" : _path; } int QtsDvdFile::sectorCount() const { return _size / QTS_DVD_SECTOR_SIZE + int(_size % QTS_DVD_SECTOR_SIZE > 0); } bool QtsDvdFile::isVob() const { return _path.endsWith(".VOB", Qt::CaseInsensitive); } //---------------------------------------------------------------------------- // Clear the content of this object. //---------------------------------------------------------------------------- void QtsDvdFile::clear() { _path.clear(); _sector = -1; _size = 0; } //---------------------------------------------------------------------------- // Operator "less than" on QtsDvdFilePtr to sort files. //---------------------------------------------------------------------------- bool operator<(const QtsDvdFilePtr& f1, const QtsDvdFilePtr& f2) { // Null pointers preceeds everything. if (!f1.isNull() && !f2.isNull()) { return *f1 < *f2; } else { return !f2.isNull(); } }
32.603774
79
0.537905
[ "object" ]
b85cbeafcc6e9c44b2a75e00c1454faed4d04666
823
cpp
C++
src/main.cpp
Amirhosein-GPR/checkers
4e4eb1ec23e2f34a663b8b59b07babd03c7354ad
[ "MIT" ]
null
null
null
src/main.cpp
Amirhosein-GPR/checkers
4e4eb1ec23e2f34a663b8b59b07babd03c7354ad
[ "MIT" ]
null
null
null
src/main.cpp
Amirhosein-GPR/checkers
4e4eb1ec23e2f34a663b8b59b07babd03c7354ad
[ "MIT" ]
null
null
null
#include "core/Engine.hpp" void func() { } int main(int argc, char *argv[]) { Engine *engine = Engine::getInstance(); if (engine->initialize()) { Uint32 frameTicks; engine->mainTimer->start(); while (Engine::running) { engine->manageStates(); engine->frameTimer->start(); engine->update(); engine->render(); frameTicks = engine->frameTimer->getTicks(); if (frameTicks < totalTicksForEachFrame) { SDL_Delay(totalTicksForEachFrame - frameTicks); } } engine->deleteObjectsTillNow(); } else { System::logError("engine : couldn't initialize!"); } return 0; }
22.243243
67
0.482382
[ "render" ]
b85cd2568dfe42b8aab48a5c24dd647e713ddbe3
6,294
hpp
C++
include/world_model/view_port_handler.hpp
asr-ros/asr_world_model
ff4ab2e8f83212be0f3aeb0224ad892d4966befd
[ "BSD-3-Clause" ]
1
2019-10-29T13:37:29.000Z
2019-10-29T13:37:29.000Z
include/world_model/view_port_handler.hpp
asr-ros/asr_world_model
ff4ab2e8f83212be0f3aeb0224ad892d4966befd
[ "BSD-3-Clause" ]
null
null
null
include/world_model/view_port_handler.hpp
asr-ros/asr_world_model
ff4ab2e8f83212be0f3aeb0224ad892d4966befd
[ "BSD-3-Clause" ]
null
null
null
/** Copyright (c) 2016, Aumann Florian, Borella Jocelyn, Hutmacher Robin, Karrenbauer Oliver, Meißner Pascal, Schleicher Ralf, Stöckle Patrick, Trautmann Jeremias All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once // Global Inclusion #include <boost/shared_ptr.hpp> #include <vector> #include <map> // ROS Main Inclusion #include <ros/ros.h> // ROS-wide Inclusion #include <asr_msgs/AsrViewport.h> // Local Inclusion #include "asr_world_model/EmptyViewportList.h" #include "asr_world_model/GetViewportList.h" #include "asr_world_model/PushViewport.h" #include "asr_world_model/FilterViewportDependingOnAlreadyVisitedViewports.h" #include "world_model/model/settings.hpp" #include "world_model/helper/debug_helper.hpp" #include "world_model/helper/pose_helper.hpp" namespace world_model { typedef std::vector<asr_msgs::AsrViewport> ViewportList; typedef boost::shared_ptr<ViewportList> ViewportListPtr; std::ostream& operator<<(std::ostream &strm, const ViewportList &viewport_list); std::ostream& operator<<(std::ostream &strm, const ViewportListPtr &viewport_list_ptr); /*! * \brief WorldModel class provides services for adding the viewports of the next best views to a list and retrieve them. Additionally, it provides services for adding objects, detected by object localization and retrieve them. */ class ViewPortHandler { public: /* ----------------- Public members ------------------ */ // Wrapped Constants // PushViewport static const inline std::string GetPushViewportServiceName () { return "push_viewport"; } // EmptyViewportList static const inline std::string GetEmptyViewportListServiceName() { return "empty_viewport_list"; } // GetViewportList static const inline std::string GetGetViewportListServiceName() { return "get_viewport_list"; } // FilterViewportDependingOnAlreadyVisitedViewports static const inline std::string GetFilterViewportDependingOnAlreadyVisitedViewportsName() { return "filter_viewport_depending_on_already_visited_viewports"; } private: /* ----------------- Private members ------------------ */ // Vars std::size_t number_of_all_viewports; ViewportListPtr viewport_list_ptr_; DebugHelperPtr debug_helper_ptr_; PoseHelperPtr pose_helper_ptr_; SettingsPtr settings_ptr_; void filterObjectTypesOfViewport(asr_msgs::AsrViewport &viewport_to_filter, const asr_msgs::AsrViewport &filter_viewport); public: /* ----------------- Public functions ------------------ */ /*! * \brief Creates a new instance of the ViewPortHandler */ ViewPortHandler(SettingsPtr settings_ptr); /*! * \brief Removes the whole next best view viewports from list if request.object_type is * set to "all" in the other case just the viewports associated with the given object type. * \param request the associated request object of the service call * \param response the associated response object of the service * \return the success of the service call. */ bool processEmptyViewportListServiceCall(asr_world_model::EmptyViewportList::Request &request, asr_world_model::EmptyViewportList::Response &response); /*! * \brief Returns the whole list of next best view viewports if request.object_type is * set to "all" else just the subset which matches the object type given in request.object_type. * \param request the associated request object of the service call * \param response the associated response object of the service * \return the success of the service call. */ bool processGetViewportListServiceCall(asr_world_model::GetViewportList::Request &request, asr_world_model::GetViewportList::Response &response); /*! * \brief Pushes a next best view viewport to a list. * \param request the associated request object of the service call * \param response the associated response object of the service call * \return the success of the service call. */ bool processPushViewportServiceCall(asr_world_model::PushViewport::Request &request, asr_world_model::PushViewport::Response &response); /*! * \brief Filter the objects of the viewport depending on already visited viewports. * \param request the associated request object of the service call * \param response the associated response object of the service call * \return the success of the service call. */ bool processFilterViewportDependingOnAlreadyVisitedViewportsVisited(asr_world_model::FilterViewportDependingOnAlreadyVisitedViewports::Request &request, asr_world_model::FilterViewportDependingOnAlreadyVisitedViewports::Response &response); }; }
44.957143
755
0.740388
[ "object", "vector", "model" ]
b85e61c1adb691b92644cf97dca16e31fff5d868
10,863
cpp
C++
prime.cpp
NexusApplePie/ApplePie
99f10d91ae3e7fbad729e81c07c4cd69d43ffabd
[ "AML" ]
null
null
null
prime.cpp
NexusApplePie/ApplePie
99f10d91ae3e7fbad729e81c07c4cd69d43ffabd
[ "AML" ]
null
null
null
prime.cpp
NexusApplePie/ApplePie
99f10d91ae3e7fbad729e81c07c4cd69d43ffabd
[ "AML" ]
null
null
null
/******************************************************************************************* Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++ [Learn, Create, but do not Forge] Viz. http://www.opensource.org/licenses/mit-license.php *******************************************************************************************/ #include "core.h" using namespace std; namespace Core { unsigned int *primes; unsigned int *inverses; unsigned int nBitArray_Size = 1024*1024*36; mpz_t zPrimorial; unsigned int prime_limit = 71378571; unsigned int nPrimeLimit = 4194304; unsigned int nPrimorialEndPrime = 12; uint64 octuplet_origins[256] = {15760091,25658441,93625991,182403491,226449521,661972301,910935911,1042090781,1071322781,1170221861,1394025161,1459270271,1712750771, 1742638811,1935587651,2048038451,2397437501,2799645461,2843348351,3734403131,4090833821,5349522791,5379039551,5522988461,5794564661, 5950513181,6070429481,6138646511,6193303001,6394117181,6520678511,6765896981,6969026411,7219975571,7602979451,8247812381,8750853101, 9870884321,9966184841,11076719651,11234903411,11567910701,11881131791,12753314921,12848960471,12850665671,12886759001,13345214411, 13421076281,15065117141,15821203241,16206106991,16427277941,16804790531,17140322651,17383048211,18234075311,18379278761,18821455181, 18856092371,21276989801,21315831611,21803245811,22190786531,22367332061,22642418411,22784826131,22827253901,23393094071,24816950771, 24887046251,24930296381,26092031081,28657304561,28900195391,29055481571,29906747861,30332927741,30526543121,31282661141,31437430091, 31447680611,31779849371,31907755331,33081664151,33734375021,35035293101,35969034371,36551720741,37000821701,37037888801,37654490171, 38855298941,40743911051,41614070411,43298074271,43813839521,44676352991,45549998561,46961199401,47346763811,48333938111,49788942011, 49827604901,50144961941,50878435451,53001578081,54270148391,57440594201,60239937671,62184803951,63370318001,64202502431,65227645781, 65409385031,66449431661,69707273171,71750241371,73457668631,74082349331,74445418121,74760009671,75161088461,75778477121,76289638961, 77310104141,77653734071,78065091101,78525462131,79011826961,79863776801,79976720891,80041993301,80587471031,80790462281,82455937631, 83122625471,84748266131,84882447101,85544974631,86408384591,87072248561,88163200661,88436579501,88815669401,89597692181,90103909781, 91192669481,93288681371,93434383571,93487652171,93703549391,94943708591,95109448781,95391400451,96133393241,97249028951,98257943081, 100196170421,101698684931,104487717401,105510861341,106506834431,107086217081,109750518791,110327129441,111422173391,114994357391, 116632573901,117762315941,118025332961,119063726051,121317512201,123019590761,123775576271,124168028051,130683361421,131045869301, 131176761251,131484693071,132595345691,133391614241,135614688941,138478375151,139017478331,139858746941,141763537451,143258671091, 144224334251,147215781521,147332222951,148124799281,148323246341,148671287111,148719488831,148916953301,148949723381,150613299911, 153779378561,155130467951,155521458551,156146394401,156456267881,157272782741,157519407581,163899228791,164138756051,165040690931, 165792941381,165952761041,166004527301,166225007561,168626248781,169349651741,170316751721,170552481551,170587733201,170832928151, 171681030791,172892544941,173405293331,174073117061,177620195561,178242755681,180180782051,180237252311,184430028311,185515423391, 185814366581,186122739611,187735172741,187971393341,188090847011,189066712181,190192014821,192380171981,193725710021,194875423271, 198006027671,198146724311,198658763111,198869317721,199658510321,199847262731,200599766441,201708760061,202506276431,203499800501, 204503641871,206150764271,207369666851,208403006081,211925962091,214556015741,218389714001,218732226521}; inline int64 GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } unsigned long sqrtld(unsigned long N) { int b = 1; unsigned long res,s; while(1<<b<N) b+= 1; res = 1<<(b/2 + 1); for(;;) { s = (N/res + res)/2; if(s>=res) return res; res = s; } } unsigned int * make_primes(unsigned int limit) { unsigned int *primes; unsigned long i,j; unsigned long s = sqrtld(prime_limit); unsigned long n = 0; bool *bit_array_sieve = (bool*)malloc((prime_limit + 1) * sizeof(bool)); bit_array_sieve[0] = 0; bit_array_sieve[1] = 0; for(i=2; i<=prime_limit; i++) bit_array_sieve[i] = 1; j = 4; while(j<=prime_limit) { bit_array_sieve[j] = 0; j += 2; } for(i=3; i<=s; i+=2) { if(bit_array_sieve[i] == 1) { j = i * 3; while(j<=prime_limit) { bit_array_sieve[j] = 0; j += 2 * i; } } } for(i=2;i<=prime_limit;i++) if(bit_array_sieve[i]==1) n += 1; primes = (unsigned int*)malloc((n + 1) * sizeof(unsigned long)); primes[0] = n; j = 1; for(i=2;i<=prime_limit;i++) if(bit_array_sieve[i]==1) { primes[j] = i; j++; } free(bit_array_sieve); return primes; } /** Divisor bit_array_sieve for Prime Searching. **/ std::vector<unsigned int> DIVISOR_SIEVE; void InitializePrimes() { printf("\nGenerating primes...\n"); // generate prime table primes = make_primes(prime_limit); printf("\n%d primes generated\n", primes[0]); mpz_init(zPrimorial); mpz_set_ui(zPrimorial, 1); for (int i=1; i<nPrimorialEndPrime; i++) { mpz_mul_ui(zPrimorial, zPrimorial, primes[i]); } printf("\nPrimorial:"); printf("\n"); mpz_out_str(stdout, 10, zPrimorial); printf("\n"); printf("\nLast Primorial Prime = %u\n", primes[nPrimorialEndPrime-1]); printf("\nFirst Sieving Prime = %u\n", primes[nPrimorialEndPrime]); int nSize = mpz_sizeinbase(zPrimorial,2); printf("\nPrimorial Size = %d-bit\n\n", nSize); inverses=(unsigned int *) malloc((nPrimeLimit+1)*sizeof(unsigned int)); memset(inverses, 0, (nPrimeLimit+1) * sizeof(unsigned int)); mpz_t zPrime, zInverse, zResult; mpz_init(zPrime); mpz_init(zInverse); mpz_init(zResult); for(unsigned int i=nPrimorialEndPrime; i<=nPrimeLimit; i++) { mpz_set_ui(zPrime, primes[i]); int inv = mpz_invert(zResult, zPrimorial, zPrime); if (inv <= 0) { printf("\nNo Inverse for prime %u at position %u\n\n", zPrime, i); exit(0); } else { inverses[i] = mpz_get_ui(zResult); } } } /** Convert Double to unsigned int Representative. Used for encoding / decoding prime difficulty from nBits. **/ unsigned int SetBits(double nDiff) { unsigned int nBits = 10000000; nBits *= nDiff; return nBits; } /** Determines the difficulty of the Given Prime Number. Difficulty is represented as so V.X V is the whole number, or Cluster Size, X is a proportion of Fermat Remainder from last Composite Number [0 - 1] **/ double GetPrimeDifficulty(CBigNum prime, int checks) { CBigNum lastPrime = prime; CBigNum next = prime + 2; unsigned int clusterSize = 1; ///largest prime gap in cluster can be +12 ///this was determined by previously found clusters up to 17 primes for( next ; next <= lastPrime + 12; next += 2) { if(PrimeCheck(next, checks)) { lastPrime = next; ++clusterSize; } } ///calulate the rarety of cluster from proportion of fermat remainder of last prime + 2 ///keep fractional remainder in bounds of [0, 1] double fractionalRemainder = 1000000.0 / GetFractionalDifficulty(next); if(fractionalRemainder > 1.0 || fractionalRemainder < 0.0) fractionalRemainder = 0.0; return (clusterSize + fractionalRemainder); } double GetSieveDifficulty(CBigNum next, unsigned int clusterSize) { ///calulate the rarety of cluster from proportion of fermat remainder of last prime + 2 ///keep fractional remainder in bounds of [0, 1] double fractionalRemainder = 1000000.0 / GetFractionalDifficulty(next); if(fractionalRemainder > 1.0 || fractionalRemainder < 0.0) fractionalRemainder = 0.0; return (clusterSize + fractionalRemainder); } /** Gets the unsigned int representative of a decimal prime difficulty **/ unsigned int GetPrimeBits(CBigNum prime, int checks) { return SetBits(GetPrimeDifficulty(prime, checks)); } /** Breaks the remainder of last composite in Prime Cluster into an integer. Larger numbers are more rare to find, so a proportion can be determined to give decimal difficulty between whole number increases. **/ unsigned int GetFractionalDifficulty(CBigNum composite) { /** Break the remainder of Fermat test to calculate fractional difficulty [Thanks Sunny] **/ return ((composite - FermatTest(composite, 2) << 24) / composite).getuint(); } /** bit_array_sieve of Eratosthenes for Divisor Tests. Used for Searching Primes. **/ std::vector<unsigned int> Eratosthenes(int nSieveSize) { bool TABLE[nSieveSize]; for(int nIndex = 0; nIndex < nSieveSize; nIndex++) TABLE[nIndex] = false; for(int nIndex = 2; nIndex < nSieveSize; nIndex++) for(int nComposite = 2; (nComposite * nIndex) < nSieveSize; nComposite++) TABLE[nComposite * nIndex] = true; std::vector<unsigned int> PRIMES; for(int nIndex = 2; nIndex < nSieveSize; nIndex++) if(!TABLE[nIndex]) PRIMES.push_back(nIndex); printf("bit_array_sieve of Eratosthenes Generated %i Primes.\n", PRIMES.size()); return PRIMES; } /** Basic Search filter to determine if further tests should be done. **/ bool DivisorCheck(CBigNum test) { for(int index = 0; index < DIVISOR_SIEVE.size(); index++) if(test % DIVISOR_SIEVE[index] == 0) return false; return true; } /** Determines if given number is Prime. Accuracy can be determined by "checks". The default checks the NXS Network uses is 2 **/ bool PrimeCheck(CBigNum test, int checks) { /** Check C: Fermat Tests */ CBigNum n = 3; if(FermatTest(test, n) != 1) return false; return true; } /** Simple Modular Exponential Equation a^(n - 1) % n == 1 or notated in Modular Arithmetic a^(n - 1) = 1 [mod n]. a = Base or 2... 2 + checks, n is the Prime Test. Used after Miller-Rabin and Divisor tests to verify primality. **/ CBigNum FermatTest(CBigNum n, CBigNum a) { CAutoBN_CTX pctx; CBigNum e = n - 1; CBigNum r; BN_mod_exp(&r, &a, &e, &n, pctx); return r; } /** Miller-Rabin Primality Test from the OpenSSL BN Library. **/ bool Miller_Rabin(CBigNum n, int checks) { return (BN_is_prime(&n, checks, NULL, NULL, NULL) == 1); } }
36.575758
173
0.710025
[ "vector" ]
b86394579394c628a01946666dbcb79ded5d2092
49,596
cpp
C++
cplus/libcfsec/CFSecServiceTypeHBuff.cpp
msobkow/cfsec_2_13
4f5b2d82d4265e1373955a63bea4d1a9fc35a64e
[ "Apache-2.0" ]
null
null
null
cplus/libcfsec/CFSecServiceTypeHBuff.cpp
msobkow/cfsec_2_13
4f5b2d82d4265e1373955a63bea4d1a9fc35a64e
[ "Apache-2.0" ]
null
null
null
cplus/libcfsec/CFSecServiceTypeHBuff.cpp
msobkow/cfsec_2_13
4f5b2d82d4265e1373955a63bea4d1a9fc35a64e
[ "Apache-2.0" ]
null
null
null
// Description: C++18 implementation of a ServiceType history buffer object. /* * org.msscf.msscf.CFSec * * Copyright (c) 2020 Mark Stephen Sobkow * * MSS Code Factory CFSec 2.13 Security Essentials * * Copyright 2020-2021 Mark Stephen Sobkow * * This file is part of MSS Code Factory. * * MSS Code Factory is available under dual commercial license from Mark Stephen * Sobkow, or under the terms of the GNU General Public License, Version 3 * or later. * * MSS Code Factory is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MSS Code Factory 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 MSS Code Factory. If not, see <https://www.gnu.org/licenses/>. * * Donations to support MSS Code Factory can be made at * https://www.paypal.com/paypalme2/MarkSobkow * * Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing. * * Manufactured by MSS Code Factory 2.12 */ #include <cflib/ICFLibPublic.hpp> using namespace std; #include <cfsec/CFSecHPKey.hpp> #include <cfsec/CFSecServiceTypePKey.hpp> #include <cfsec/CFSecServiceTypeBuff.hpp> #include <cfsec/CFSecServiceTypeHPKey.hpp> #include <cfsec/CFSecServiceTypeHBuff.hpp> #include <cfsec/CFSecServiceTypeByUDescrIdxKey.hpp> namespace cfsec { const std::string CFSecServiceTypeHBuff::CLASS_NAME( "CFSecServiceTypeHBuff" ); CFSecServiceTypeHBuff::CFSecServiceTypeHBuff() : CFSecHPKey(), cflib::ICFLibCloneableObj() { requiredServiceTypeId = cfsec::CFSecServiceTypeBuff::SERVICETYPEID_INIT_VALUE; requiredDescription = new std::string( cfsec::CFSecServiceTypeBuff::DESCRIPTION_INIT_VALUE ); } CFSecServiceTypeHBuff::CFSecServiceTypeHBuff( const CFSecServiceTypeHBuff& src ) : CFSecHPKey(), cflib::ICFLibCloneableObj() { requiredServiceTypeId = cfsec::CFSecServiceTypeBuff::SERVICETYPEID_INIT_VALUE; requiredDescription = new std::string( cfsec::CFSecServiceTypeBuff::DESCRIPTION_INIT_VALUE ); setRequiredServiceTypeId( src.getRequiredServiceTypeId() ); setRequiredRevision( src.getRequiredRevision() ); setRequiredDescription( src.getRequiredDescription() ); } CFSecServiceTypeHBuff::~CFSecServiceTypeHBuff() { if( requiredDescription != NULL ) { delete requiredDescription; requiredDescription = NULL; } } cflib::ICFLibCloneableObj* CFSecServiceTypeHBuff::clone() { CFSecServiceTypeHBuff* copy = new CFSecServiceTypeHBuff(); *copy = *this; cflib::ICFLibCloneableObj* retval = dynamic_cast<cflib::ICFLibCloneableObj*>( copy ); return( retval ); } const int32_t CFSecServiceTypeHBuff::getRequiredServiceTypeId() const { return( requiredServiceTypeId ); } const int32_t* CFSecServiceTypeHBuff::getRequiredServiceTypeIdReference() const { return( &requiredServiceTypeId ); } void CFSecServiceTypeHBuff::setRequiredServiceTypeId( const int32_t value ) { static const std::string S_ProcName( "setRequiredServiceTypeId" ); if( value < cfsec::CFSecServiceTypeBuff::SERVICETYPEID_MIN_VALUE ) { throw cflib::CFLibArgumentUnderflowException( CLASS_NAME, S_ProcName, 1, S_VALUE, value, cfsec::CFSecServiceTypeBuff::SERVICETYPEID_MIN_VALUE ); } requiredServiceTypeId = value; } const std::string& CFSecServiceTypeHBuff::getRequiredDescription() const { return( *requiredDescription ); } const std::string* CFSecServiceTypeHBuff::getRequiredDescriptionReference() const { return( requiredDescription ); } void CFSecServiceTypeHBuff::setRequiredDescription( const std::string& value ) { static const std::string S_ProcName( "setRequiredDescription" ); if( value.length() > CFSecServiceTypeBuff::DESCRIPTION_MAX_LEN ) { throw cflib::CFLibArgumentOverflowException( CLASS_NAME, S_ProcName, 1, S_VALUE_LENGTH, value.length(), CFSecServiceTypeBuff::DESCRIPTION_MAX_LEN ); } if( requiredDescription != NULL ) { delete requiredDescription; requiredDescription = NULL; } requiredDescription = new std::string( value ); } size_t CFSecServiceTypeHBuff::hashCode() const { size_t hashCode = CFSecHPKey::hashCode(); hashCode = hashCode + getRequiredServiceTypeId(); hashCode = hashCode + cflib::CFLib::hash( getRequiredDescription() ); return( hashCode ); } CFSecServiceTypeHBuff CFSecServiceTypeHBuff::operator =( cfsec::CFSecServiceTypeBuff& src ) { setRequiredServiceTypeId( src.getRequiredServiceTypeId() ); setRequiredRevision( src.getRequiredRevision() ); setRequiredDescription( src.getRequiredDescription() ); return( *this ); } CFSecServiceTypeHBuff CFSecServiceTypeHBuff::operator =( cfsec::CFSecServiceTypeHBuff& src ) { setRequiredServiceTypeId( src.getRequiredServiceTypeId() ); setRequiredRevision( src.getRequiredRevision() ); setRequiredDescription( src.getRequiredDescription() ); return( *this ); } bool CFSecServiceTypeHBuff::operator <( const CFSecServiceTypeByUDescrIdxKey& rhs ) { if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator <( const CFSecServiceTypePKey& rhs ) { if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator <( const CFSecServiceTypeHPKey& rhs ) { if( getAuditClusterId() > rhs.getAuditClusterId() ) { return( false ); } else if( getAuditClusterId() < rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() > rhs.getAuditStamp() ) { return( false ); } else if( getAuditStamp() < rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() >= rhs.getAuditActionId() ) { return( false ); } else if( getAuditActionId() <= rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() >= rhs.getRequiredRevision() ) { return( false ); } else if( getRequiredRevision() <= rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator <( const CFSecServiceTypeHBuff& rhs ) { if( getAuditClusterId() > rhs.getAuditClusterId() ) { return( false ); } else if( getAuditClusterId() < rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() > rhs.getAuditStamp() ) { return( false ); } else if( getAuditStamp() < rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() >= rhs.getAuditActionId() ) { return( false ); } else if( getAuditActionId() <= rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() >= rhs.getRequiredRevision() ) { return( false ); } else if( getRequiredRevision() <= rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator <( const CFSecServiceTypeBuff& rhs ) { if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator <=( const CFSecServiceTypeByUDescrIdxKey& rhs ) { if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator <=( const CFSecServiceTypePKey& rhs ) { if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator <=( const CFSecServiceTypeHPKey& rhs ) { if( getAuditClusterId() > rhs.getAuditClusterId() ) { return( false ); } else if( getAuditClusterId() < rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() > rhs.getAuditStamp() ) { return( false ); } else if( getAuditStamp() < rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() > rhs.getAuditActionId() ) { return( false ); } else if( getAuditActionId() < rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() > rhs.getRequiredRevision() ) { return( false ); } else if( getRequiredRevision() < rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator <=( const CFSecServiceTypeHBuff& rhs ) { if( getAuditClusterId() > rhs.getAuditClusterId() ) { return( false ); } else if( getAuditClusterId() < rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() > rhs.getAuditStamp() ) { return( false ); } else if( getAuditStamp() < rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() > rhs.getAuditActionId() ) { return( false ); } else if( getAuditActionId() < rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() > rhs.getRequiredRevision() ) { return( false ); } else if( getRequiredRevision() < rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator <=( const CFSecServiceTypeBuff& rhs ) { if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator ==( const CFSecServiceTypeByUDescrIdxKey& rhs ) { if( getRequiredDescription() != rhs.getRequiredDescription() ) { return( false ); } return( true ); } bool CFSecServiceTypeHBuff::operator ==( const CFSecServiceTypePKey& rhs ) { if( getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( false ); } return( true ); } bool CFSecServiceTypeHBuff::operator ==( const CFSecServiceTypeHPKey& rhs ) { if( getAuditClusterId() != rhs.getAuditClusterId() ) { return( false ); } if( getAuditStamp() != rhs.getAuditStamp() ) { return( false ); } if( getAuditActionId() != rhs.getAuditActionId() ) { return( false ); } if( getRequiredRevision() != rhs.getRequiredRevision() ) { return( false ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( false ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( false ); } return( true ); } bool CFSecServiceTypeHBuff::operator ==( const CFSecServiceTypeHBuff& rhs ) { if( getAuditClusterId() != rhs.getAuditClusterId() ) { return( false ); } if( getAuditStamp() != rhs.getAuditStamp() ) { return( false ); } if( getAuditActionId() != rhs.getAuditActionId() ) { return( false ); } if( getRequiredRevision() != rhs.getRequiredRevision() ) { return( false ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( false ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( false ); } if( getRequiredDescription() != rhs.getRequiredDescription() ) { return( false ); } return( true ); } bool CFSecServiceTypeHBuff::operator ==( const CFSecServiceTypeBuff& rhs ) { if( getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( false ); } if( getRequiredDescription() != rhs.getRequiredDescription() ) { return( false ); } return( true ); } bool CFSecServiceTypeHBuff::operator !=( const CFSecServiceTypeByUDescrIdxKey& rhs ) { if( getRequiredDescription() != rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator !=( const CFSecServiceTypePKey& rhs ) { if( getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator !=( const CFSecServiceTypeHPKey& rhs ) { if( getAuditClusterId() != rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() != rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() != rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() != rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( true ); } } if( getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator !=( const CFSecServiceTypeHBuff& rhs ) { if( getAuditClusterId() != rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() != rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() != rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() != rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( true ); } } if( getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() != rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator !=( const CFSecServiceTypeBuff& rhs ) { if( getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() != rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator >=( const CFSecServiceTypeByUDescrIdxKey& rhs ) { if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator >=( const CFSecServiceTypePKey& rhs ) { if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator >=( const CFSecServiceTypeHPKey& rhs ) { if( getAuditClusterId() < rhs.getAuditClusterId() ) { return( false ); } else if( getAuditClusterId() > rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() < rhs.getAuditStamp() ) { return( false ); } else if( getAuditStamp() > rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() < rhs.getAuditActionId() ) { return( false ); } else if( getAuditActionId() > rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() < rhs.getRequiredRevision() ) { return( false ); } else if( getRequiredRevision() > rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator >=( const CFSecServiceTypeHBuff& rhs ) { if( getAuditClusterId() < rhs.getAuditClusterId() ) { return( false ); } else if( getAuditClusterId() > rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() < rhs.getAuditStamp() ) { return( false ); } else if( getAuditStamp() > rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() < rhs.getAuditActionId() ) { return( false ); } else if( getAuditActionId() > rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() < rhs.getRequiredRevision() ) { return( false ); } else if( getRequiredRevision() > rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator >=( const CFSecServiceTypeBuff& rhs ) { if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool CFSecServiceTypeHBuff::operator >( const CFSecServiceTypeByUDescrIdxKey& rhs ) { if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator >( const CFSecServiceTypePKey& rhs ) { if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator >( const CFSecServiceTypeHPKey& rhs ) { if( getAuditClusterId() < rhs.getAuditClusterId() ) { return( false ); } else if( getAuditClusterId() > rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() < rhs.getAuditStamp() ) { return( false ); } else if( getAuditStamp() > rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() < rhs.getAuditActionId() ) { return( false ); } else if( getAuditActionId() > rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() < rhs.getRequiredRevision() ) { return( false ); } else if( getRequiredRevision() > rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator >( const CFSecServiceTypeHBuff& rhs ) { if( getAuditClusterId() < rhs.getAuditClusterId() ) { return( false ); } else if( getAuditClusterId() > rhs.getAuditClusterId() ) { return( true ); } if( getAuditStamp() < rhs.getAuditStamp() ) { return( false ); } else if( getAuditStamp() > rhs.getAuditStamp() ) { return( true ); } if( getAuditActionId() < rhs.getAuditActionId() ) { return( false ); } else if( getAuditActionId() > rhs.getAuditActionId() ) { return( true ); } if( getRequiredRevision() < rhs.getRequiredRevision() ) { return( false ); } else if( getRequiredRevision() > rhs.getRequiredRevision() ) { return( true ); } if( getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool CFSecServiceTypeHBuff::operator >( const CFSecServiceTypeBuff& rhs ) { if( getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } if( getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( false ); } std::string CFSecServiceTypeHBuff::toString() { static const std::string S_Space( " " ); static const std::string S_Preamble( "<CFSecServiceTypeHBuff" ); static const std::string S_Postamble( "/>" ); static const std::string S_AuditClusterId( "AuditClusterId" ); static const std::string S_AuditStamp( "AuditStamp" ); static const std::string S_AuditActionId( "AuditActionId" ); static const std::string S_Revision( "Revision" ); static const std::string S_AuditSessionId( "AuditSessionId" ); static const std::string S_ServiceTypeId( "ServiceTypeId" ); static const std::string S_Description( "Description" ); std::string ret( S_Preamble ); ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_AuditClusterId, auditClusterId ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_AuditClusterId, auditStamp ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredInt16( &S_Space, S_AuditActionId, auditActionId ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredUuid( &S_Space, S_AuditSessionId, auditSessionId ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredInt32( &S_Space, S_ServiceTypeId, getRequiredServiceTypeId() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredInt32( &S_Space, S_Revision, getRequiredRevision() ) ); ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Description, getRequiredDescription() ) ); ret.append( S_Postamble ); return( ret ); } } namespace std { bool operator <(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeByUDescrIdxKey& rhs ) { if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool operator <(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypePKey& rhs ) { if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool operator <(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHPKey& rhs ) { if( lhs.getAuditClusterId() > rhs.getAuditClusterId() ) { return( false ); } else if( lhs.getAuditClusterId() < rhs.getAuditClusterId() ) { return( true ); } if( lhs.getAuditStamp() > rhs.getAuditStamp() ) { return( false ); } else if( lhs.getAuditStamp() < rhs.getAuditStamp() ) { return( true ); } if( lhs.getAuditActionId() > rhs.getAuditActionId() ) { return( false ); } else if( lhs.getAuditActionId() < rhs.getAuditActionId() ) { return( true ); } if( lhs.getRequiredRevision() > rhs.getRequiredRevision() ) { return( false ); } else if( lhs.getRequiredRevision() < rhs.getRequiredRevision() ) { return( true ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool operator <(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHBuff& rhs ) { if( lhs.getAuditClusterId() > rhs.getAuditClusterId() ) { return( false ); } else if( lhs.getAuditClusterId() < rhs.getAuditClusterId() ) { return( true ); } if( lhs.getAuditStamp() > rhs.getAuditStamp() ) { return( false ); } else if( lhs.getAuditStamp() < rhs.getAuditStamp() ) { return( true ); } if( lhs.getAuditActionId() > rhs.getAuditActionId() ) { return( false ); } else if( lhs.getAuditActionId() < rhs.getAuditActionId() ) { return( true ); } if( lhs.getRequiredRevision() > rhs.getRequiredRevision() ) { return( false ); } else if( lhs.getRequiredRevision() < rhs.getRequiredRevision() ) { return( true ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool operator <(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeBuff& rhs ) { if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool operator <=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeByUDescrIdxKey& rhs ) { if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool operator <=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypePKey& rhs ) { if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } return( true ); } bool operator <=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHPKey& rhs ) { if( lhs.getAuditClusterId() != rhs.getAuditClusterId() ) { return( false ); } if( lhs.getAuditStamp() != rhs.getAuditStamp() ) { return( false ); } if( lhs.getAuditActionId() != rhs.getAuditActionId() ) { return( false ); } if( lhs.getRequiredRevision() != rhs.getRequiredRevision() ) { return( false ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( false ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } return( true ); } bool operator <=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHBuff& rhs ) { if( lhs.getAuditClusterId() != rhs.getAuditClusterId() ) { return( false ); } if( lhs.getAuditStamp() != rhs.getAuditStamp() ) { return( false ); } if( lhs.getAuditActionId() != rhs.getAuditActionId() ) { return( false ); } if( lhs.getRequiredRevision() != rhs.getRequiredRevision() ) { return( false ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( false ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool operator <=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeBuff& rhs ) { if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool operator ==(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeByUDescrIdxKey& rhs ) { if( lhs.getRequiredDescription() != rhs.getRequiredDescription() ) { return( false ); } return( true ); } bool operator ==(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypePKey& rhs ) { if( lhs.getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( false ); } return( true ); } bool operator ==(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHPKey& rhs ) { if( lhs.getAuditClusterId() != rhs.getAuditClusterId() ) { return( false ); } if( lhs.getAuditStamp() != rhs.getAuditStamp() ) { return( false ); } if( lhs.getAuditActionId() != rhs.getAuditActionId() ) { return( false ); } if( lhs.getRequiredRevision() != rhs.getRequiredRevision() ) { return( false ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( false ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( false ); } return( true ); } bool operator ==(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHBuff& rhs ) { if( lhs.getAuditClusterId() != rhs.getAuditClusterId() ) { return( false ); } if( lhs.getAuditStamp() != rhs.getAuditStamp() ) { return( false ); } if( lhs.getAuditActionId() != rhs.getAuditActionId() ) { return( false ); } if( lhs.getRequiredRevision() != rhs.getRequiredRevision() ) { return( false ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( false ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( false ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( false ); } if( lhs.getRequiredDescription() != rhs.getRequiredDescription() ) { return( false ); } return( true ); } bool operator ==(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeBuff& rhs ) { if( lhs.getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( false ); } if( lhs.getRequiredDescription() != rhs.getRequiredDescription() ) { return( false ); } return( true ); } bool operator !=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeByUDescrIdxKey& rhs ) { if( lhs.getRequiredDescription() != rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool operator !=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypePKey& rhs ) { if( lhs.getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool operator !=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHPKey& rhs ) { if( lhs.getAuditClusterId() != rhs.getAuditClusterId() ) { return( true ); } if( lhs.getAuditStamp() != rhs.getAuditStamp() ) { return( true ); } if( lhs.getAuditActionId() != rhs.getAuditActionId() ) { return( true ); } if( lhs.getRequiredRevision() != rhs.getRequiredRevision() ) { return( true ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( true ); } } if( lhs.getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool operator !=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHBuff& rhs ) { if( lhs.getAuditClusterId() != rhs.getAuditClusterId() ) { return( true ); } if( lhs.getAuditStamp() != rhs.getAuditStamp() ) { return( true ); } if( lhs.getAuditActionId() != rhs.getAuditActionId() ) { return( true ); } if( lhs.getRequiredRevision() != rhs.getRequiredRevision() ) { return( true ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) != 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( true ); } } if( lhs.getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() != rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool operator !=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeBuff& rhs ) { if( lhs.getRequiredServiceTypeId() != rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() != rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool operator >=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeByUDescrIdxKey& rhs ) { if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool operator >=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypePKey& rhs ) { if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } return( true ); } bool operator >=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHPKey& rhs ) { if( lhs.getAuditClusterId() < rhs.getAuditClusterId() ) { return( false ); } else if( lhs.getAuditClusterId() > rhs.getAuditClusterId() ) { return( true ); } if( lhs.getAuditStamp() < rhs.getAuditStamp() ) { return( false ); } else if( lhs.getAuditStamp() > rhs.getAuditStamp() ) { return( true ); } if( lhs.getAuditActionId() < rhs.getAuditActionId() ) { return( false ); } else if( lhs.getAuditActionId() > rhs.getAuditActionId() ) { return( true ); } if( lhs.getRequiredRevision() < rhs.getRequiredRevision() ) { return( false ); } else if( lhs.getRequiredRevision() > rhs.getRequiredRevision() ) { return( true ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } return( true ); } bool operator >=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHBuff& rhs ) { if( lhs.getAuditClusterId() < rhs.getAuditClusterId() ) { return( false ); } else if( lhs.getAuditClusterId() > rhs.getAuditClusterId() ) { return( true ); } if( lhs.getAuditStamp() < rhs.getAuditStamp() ) { return( false ); } else if( lhs.getAuditStamp() > rhs.getAuditStamp() ) { return( true ); } if( lhs.getAuditActionId() < rhs.getAuditActionId() ) { return( false ); } else if( lhs.getAuditActionId() > rhs.getAuditActionId() ) { return( true ); } if( lhs.getRequiredRevision() < rhs.getRequiredRevision() ) { return( false ); } else if( lhs.getRequiredRevision() > rhs.getRequiredRevision() ) { return( true ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool operator >=(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeBuff& rhs ) { if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( true ); } bool operator >(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeByUDescrIdxKey& rhs ) { if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool operator >(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypePKey& rhs ) { if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool operator >(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHPKey& rhs ) { if( lhs.getAuditClusterId() < rhs.getAuditClusterId() ) { return( false ); } else if( lhs.getAuditClusterId() > rhs.getAuditClusterId() ) { return( true ); } if( lhs.getAuditStamp() < rhs.getAuditStamp() ) { return( false ); } else if( lhs.getAuditStamp() > rhs.getAuditStamp() ) { return( true ); } if( lhs.getAuditActionId() < rhs.getAuditActionId() ) { return( false ); } else if( lhs.getAuditActionId() > rhs.getAuditActionId() ) { return( true ); } if( lhs.getRequiredRevision() < rhs.getRequiredRevision() ) { return( false ); } else if( lhs.getRequiredRevision() > rhs.getRequiredRevision() ) { return( true ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } return( false ); } bool operator >(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeHBuff& rhs ) { if( lhs.getAuditClusterId() < rhs.getAuditClusterId() ) { return( false ); } else if( lhs.getAuditClusterId() > rhs.getAuditClusterId() ) { return( true ); } if( lhs.getAuditStamp() < rhs.getAuditStamp() ) { return( false ); } else if( lhs.getAuditStamp() > rhs.getAuditStamp() ) { return( true ); } if( lhs.getAuditActionId() < rhs.getAuditActionId() ) { return( false ); } else if( lhs.getAuditActionId() > rhs.getAuditActionId() ) { return( true ); } if( lhs.getRequiredRevision() < rhs.getRequiredRevision() ) { return( false ); } else if( lhs.getRequiredRevision() > rhs.getRequiredRevision() ) { return( true ); } if( lhs.getAuditSessionId() != NULL ) { if( rhs.getAuditSessionId() == NULL ) { return( true ); } const uuid_ptr_t lhuuid = lhs.getAuditSessionId(); const uuid_ptr_t rhuuid = rhs.getAuditSessionId(); if( uuid_compare( lhuuid, rhuuid ) < 0 ) { return( false ); } else if( uuid_compare( lhuuid, rhuuid ) > 0 ) { return( true ); } } else { if( rhs.getAuditSessionId() != NULL ) { return( false ); } } if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( false ); } bool operator >(const cfsec::CFSecServiceTypeHBuff& lhs, const cfsec::CFSecServiceTypeBuff& rhs ) { if( lhs.getRequiredServiceTypeId() < rhs.getRequiredServiceTypeId() ) { return( false ); } else if( lhs.getRequiredServiceTypeId() > rhs.getRequiredServiceTypeId() ) { return( true ); } if( lhs.getRequiredDescription() < rhs.getRequiredDescription() ) { return( false ); } else if( lhs.getRequiredDescription() > rhs.getRequiredDescription() ) { return( true ); } return( false ); } }
29.27745
114
0.66092
[ "object" ]
b8660696eb9d0662eeb6b486afe20b0a5b1c20a0
6,415
cpp
C++
main/src/jumpnrun/spell/Deck.cpp
wonderhorn/mkfj
18d2dd290811662d87abefe2fe2e338ba9caf8a5
[ "MIT" ]
null
null
null
main/src/jumpnrun/spell/Deck.cpp
wonderhorn/mkfj
18d2dd290811662d87abefe2fe2e338ba9caf8a5
[ "MIT" ]
null
null
null
main/src/jumpnrun/spell/Deck.cpp
wonderhorn/mkfj
18d2dd290811662d87abefe2fe2e338ba9caf8a5
[ "MIT" ]
null
null
null
#include"jumpnrun/spell/Deck.h" #include"utils/string_util.h" #include <algorithm> #include<cstdlib> using namespace jnr; using namespace spl; /* const std::vector<int> Deck::initial_deck = { spl::spellname2id("explosion"), spl::spellname2id("explosion"), spl::spellname2id("explosion"), spl::spellname2id("bullet"), spl::spellname2id("bullet"), spl::spellname2id("bullet"), spl::spellname2id("frog"), spl::spellname2id("frog"), spl::spellname2id("starshoot"), spl::spellname2id("starshoot"), spl::spellname2id("starshoot"), spl::spellname2id("lifegain20"), spl::spellname2id("lifegain20"), };*/ Card::Card() : value(-1), used(false), spell(){} Deck::Deck() : current_card(0) { auto deck_list = { spl::spellname2id("explosion"), spl::spellname2id("explosion"), spl::spellname2id("explosion"), spl::spellname2id("bullet"), spl::spellname2id("bullet"), spl::spellname2id("bullet"), spl::spellname2id("frog"), spl::spellname2id("frog"), spl::spellname2id("starshoot"), spl::spellname2id("starshoot"), spl::spellname2id("starshoot"), spl::spellname2id("lifegain20"), spl::spellname2id("lifegain20"), }; /*for (int i = 0; i < Spell::NUM_SPELL * 4; i++) { draw_counter.push_back(0); Card c; c.value = i % Spell::NUM_SPELL; c.spell = Spell::spells[c.value]; cards.push_back(c); }*/ for (int id : deck_list) { draw_counter.push_back(0); Card c; c.value = id % Spell::NUM_SPELL; c.spell = Spell::spells[c.value]; cards.push_back(c); } rest_num = cards.size(); } void Deck::initialize() { auto deck_list = { //spl::spellname2id("explosion"), //spl::spellname2id("explosion"), //spl::spellname2id("explosion"), //spl::spellname2id("bullet"), spl::spellname2id("bullet"), spl::spellname2id("bullet"), spl::spellname2id("frog"), spl::spellname2id("frog"), spl::spellname2id("starshoot"), spl::spellname2id("starshoot"), spl::spellname2id("starshoot"), //spl::spellname2id("lifegain20"), //spl::spellname2id("lifegain20"), }; draw_counter.clear(); cards.clear(); for (int id : deck_list) { draw_counter.push_back(0); Card c; c.value = id % Spell::NUM_SPELL; c.spell = Spell::spells[c.value]; cards.push_back(c); } rest_num = cards.size(); } void Deck::initialize(int num_cards) { cards.clear(); draw_counter.clear(); cards.resize(num_cards); draw_counter.resize(num_cards); for (int i = 0; i < cards.size(); i++) { draw_counter[i] = 0; } } void Deck::initialize(const std::vector<std::string>& card_ids) { cards.clear(); draw_counter.clear(); const int nc = card_ids.size() > NumHandCard() ? card_ids.size() : NumHandCard(); //const int nc = card_ids.size(); cards.resize(nc); draw_counter.resize(nc); rest_num = 0; for (int i = 0; i < card_ids.size(); i++) { if (card_ids[i].length() <= 0) { int id = -1; cards[i].value = id; cards[i].spell = jnr::spl::Spell::spells[0]; cards[i].used = true; continue; } int id = myutil::str2int(card_ids[i]); if (id >= 0) { cards[i].value = id; cards[i].spell = Spell::spells[cards[i].value]; cards[i].used = 0; rest_num++; } else { cards[i].value = id; cards[i].spell = Spell::spells[0]; cards[i].used = 1; } } //dummies for (int i = card_ids.size(); i < this->NumHandCard(); i++) { int id = -1; cards[i].value = id; cards[i].spell = jnr::spl::Spell::spells[0]; cards[i].used = true; } for (int i = 0; i < cards.size(); i++) { int id = cards[i].value; if (id >= 0) { draw_counter[i] = 00; } else { draw_counter[i] = -1; } draw_counter[i] = 00; } //dummies for (int i = card_ids.size(); i < this->NumHandCard(); i++) { draw_counter[i] = -1; } } void Deck::reset() { rest_num = 0; for (int i = 0; i < cards.size(); i++) { draw_counter[i] = 0; if(cards[i].value < 0) cards[i].used = 1; else { cards[i].spell = Spell::spells[cards[i].value]; cards[i].used = 0; rest_num++; } } for (int i = 0; i < cards.size(); i++) { draw_counter[i] = 90; } // send cards whose value == -1 to the end of the vector std::sort(cards.begin(), cards.end(), [](auto const& a, auto const& b) { return a.value > b.value; }); this->shuffle(); } void Deck::shuffle() { if (cards.size() == 0) return; for (int i = 0; i < 1000; i++) { int idx1 = rand() % cards.size(); int idx2 = rand() % cards.size(); if(cards[idx1].value >= 0 && cards[idx2].value >= 0) swap_cards(idx1, idx2); } } void Deck::swap_cards(int Card1, int Card2) { Card temp = cards[Card1]; cards[Card1] = cards[Card2]; cards[Card2] = temp; } static int countValidCards(const std::vector<jnr::Card> cards) { int count = 0; for (const auto& c : cards) count += (c.value >= 0); return count; } Spell Deck::use(int Card) { if (cards[Card].used == true) return Spell(); cards[Card].used = true; Spell rtn = cards[Card].spell; /*for(int i = Card; i < NUM_CARDS - 1; i++) { swap_cards(i, i + 1); }*/ rest_num--; const int NUM_HANDCard = NumHandCard(); const int num_cards = countValidCards(cards); if (NUM_HANDCard < cards.size()) { int next_idx = NUM_HANDCard > num_cards ? num_cards : NUM_HANDCard; swap_cards(Card, next_idx); for (int j = next_idx; j < cards.size() - 1; j++) { swap_cards(j, j + 1); int temp = draw_counter[j]; draw_counter[j] = draw_counter[j + 1]; draw_counter[j + 1] = temp; } } draw_counter[Card] = 120; return rtn; } void Deck::run() { const int NUM_HANDCard = NumHandCard(); for (int i = 0; i < cards.size(); i++) { if (draw_counter[i]) draw_counter[i]--; /* if (draw_counter[i] == 1) { if (NUM_HANDCard < cards.size()) { int next_idx = NUM_HANDCard > cards.size() - 1 ? cards.size() - 1 : NUM_HANDCard; swap_cards(i, next_idx); for (int j = next_idx; j < cards.size() - 1; j++) { swap_cards(j, j + 1); int temp = draw_counter[j]; draw_counter[j] = draw_counter[j + 1]; draw_counter[j + 1] = temp; } } }*/ } } int Deck::numValidCards()const { int num_valid_card = 0; for (int i = 0; i < cards.size(); i++) { if (cards[i].value >= 0) num_valid_card++; } return num_valid_card; } bool Deck::finished() const { int num_valid_card = 0; for (int i = 0; i < cards.size(); i++) { if (!cards[i].used) return false; if (cards[i].value >= 0) num_valid_card++; } //return num_valid_card > 0; return true; }
20.827922
85
0.61403
[ "vector" ]
b8699175e2ae09bab0915f4eb76e5cf28f0ed7f9
3,363
cpp
C++
libkineto/src/CuptiEventInterface.cpp
malfet/kineto
5b28749d8683bd235325ffa38bd551d1651ee810
[ "BSD-3-Clause" ]
null
null
null
libkineto/src/CuptiEventInterface.cpp
malfet/kineto
5b28749d8683bd235325ffa38bd551d1651ee810
[ "BSD-3-Clause" ]
null
null
null
libkineto/src/CuptiEventInterface.cpp
malfet/kineto
5b28749d8683bd235325ffa38bd551d1651ee810
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "CuptiEventInterface.h" #include <chrono> #include "Logger.h" #include "cupti_call.h" using namespace std::chrono; using std::vector; namespace KINETO_NAMESPACE { CuptiEventInterface::CuptiEventInterface(CUcontext context) : context_(context) { CUPTI_CALL(cuptiGetDeviceId(context_, (uint32_t*)&device_)); } CUpti_EventGroupSets* CuptiEventInterface::createGroupSets( vector<CUpti_EventID>& ids) { CUpti_EventGroupSets* group_sets = nullptr; CUptiResult res = CUPTI_CALL(cuptiEventGroupSetsCreate( context_, sizeof(CUpti_EventID) * ids.size(), ids.data(), &group_sets)); if (res != CUPTI_SUCCESS || group_sets == nullptr) { const char* errstr = nullptr; cuptiGetResultString(res, &errstr); throw std::system_error(EINVAL, std::generic_category(), errstr); } return group_sets; } void CuptiEventInterface::destroyGroupSets(CUpti_EventGroupSets* sets) { CUPTI_CALL(cuptiEventGroupSetsDestroy(sets)); } bool CuptiEventInterface::setContinuousMode() { CUptiResult res = CUPTI_CALL(cuptiSetEventCollectionMode( context_, CUPTI_EVENT_COLLECTION_MODE_CONTINUOUS)); return (res == CUPTI_SUCCESS); } void CuptiEventInterface::enablePerInstance(CUpti_EventGroup eventGroup) { uint32_t profile_all = 1; CUPTI_CALL(cuptiEventGroupSetAttribute( eventGroup, CUPTI_EVENT_GROUP_ATTR_PROFILE_ALL_DOMAIN_INSTANCES, sizeof(profile_all), &profile_all)); } uint32_t CuptiEventInterface::instanceCount(CUpti_EventGroup eventGroup) { uint32_t instance_count = 0; size_t s = sizeof(instance_count); CUPTI_CALL(cuptiEventGroupGetAttribute( eventGroup, CUPTI_EVENT_GROUP_ATTR_INSTANCE_COUNT, &s, &instance_count)); return instance_count; } void CuptiEventInterface::enableGroupSet(CUpti_EventGroupSet& set) { CUptiResult res = cuptiEventGroupSetEnable(&set); if (res != CUPTI_SUCCESS) { const char* errstr = nullptr; cuptiGetResultString(res, &errstr); throw std::system_error(EIO, std::generic_category(), errstr); } } void CuptiEventInterface::disableGroupSet(CUpti_EventGroupSet& set) { CUPTI_CALL(cuptiEventGroupSetDisable(&set)); } void CuptiEventInterface::readEvent( CUpti_EventGroup grp, CUpti_EventID id, vector<int64_t>& vals) { size_t s = sizeof(int64_t) * vals.size(); CUPTI_CALL(cuptiEventGroupReadEvent( grp, CUPTI_EVENT_READ_FLAG_NONE, id, &s, reinterpret_cast<uint64_t*>(vals.data()))); } vector<CUpti_EventID> CuptiEventInterface::eventsInGroup(CUpti_EventGroup grp) { uint32_t group_size = 0; size_t s = sizeof(group_size); CUPTI_CALL(cuptiEventGroupGetAttribute( grp, CUPTI_EVENT_GROUP_ATTR_NUM_EVENTS, &s, &group_size)); size_t events_size = group_size * sizeof(CUpti_EventID); vector<CUpti_EventID> res(group_size); CUPTI_CALL(cuptiEventGroupGetAttribute( grp, CUPTI_EVENT_GROUP_ATTR_EVENTS, &events_size, res.data())); return res; } CUpti_EventID CuptiEventInterface::eventId(const std::string& name) { CUpti_EventID id{0}; CUPTI_CALL(cuptiEventGetIdFromName(device_, name.c_str(), &id)); return id; } } // namespace KINETO_NAMESPACE
30.026786
80
0.753494
[ "vector" ]
b8773aa5639ad96b94d27e9d921c8c9ac3af6ffb
3,766
cpp
C++
src/cascade/cascade.cpp
JasurN/SelfDrivingCar
1929da332d7fc03c8cbed3e0d09a64ab58ad5778
[ "MIT" ]
2
2019-05-21T11:49:06.000Z
2022-03-06T04:57:04.000Z
src/cascade/cascade.cpp
JasurN/SelfDrivingCar
1929da332d7fc03c8cbed3e0d09a64ab58ad5778
[ "MIT" ]
null
null
null
src/cascade/cascade.cpp
JasurN/SelfDrivingCar
1929da332d7fc03c8cbed3e0d09a64ab58ad5778
[ "MIT" ]
null
null
null
#include <opencv2/core.hpp> #include "opencv2/opencv.hpp" #include <opencv2/highgui.hpp> #include <opencv2/videoio.hpp> #include <opencv2/objdetect.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include <raspicam/raspicam_cv.h> //tesing purpose file using namespace cv; using namespace std; int main() { raspicam::RaspiCam_Cv capture; capture.set(CV_CAP_PROP_FRAME_WIDTH, 320); capture.set(CV_CAP_PROP_FRAME_HEIGHT, 240); capture.open(); //Initialise the image as a matrix container Mat bgr; // Initialise the cascade classifier containers and load them with the .xml file you obtained from the training CascadeClassifier cascade_becareful, cascade_circle, cascade_left, cascade_stop, cascade_parking, cascade_right, cascade_forward; cascade_becareful.load("cas_becareful.xml"); cascade_circle.load("cas_circle.xml"); cascade_left.load("cas_left.xml"); cascade_stop.load("cas_stop.xml"); cascade_parking.load("cas_parking.xml"); cascade_right.load("cas_right.xml"); cascade_forward.load("cas_forward.xml"); // Container of signs vector<Rect> becareful; vector<Rect> circle; vector<Rect> left_; vector<Rect> stop_; vector<Rect> parking; vector<Rect> right_; vector<Rect> forward; while (1) { capture.grab(); //grab the scene using raspicam capture.retrieve(bgr); // retrieve the captured scene as an image and store it in matrix container if (bgr.empty()) { std::cout << "EMPTY"; } // These are detection function where you invoke the classifiers on to the frame to detect the trained elements cascade_becareful.detectMultiScale(bgr, becareful, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100)); cascade_circle.detectMultiScale(bgr, circle, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100)); cascade_left.detectMultiScale(bgr, left_, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100)); cascade_stop.detectMultiScale(bgr, stop_, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100)); cascade_parking.detectMultiScale(bgr, parking, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100)); cascade_right.detectMultiScale(bgr, right_, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100)); cascade_forward.detectMultiScale(bgr, forward, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(100, 100)); // To draw rectangles around detected objects accordingly for (unsigned i = 0; i < becareful.size(); i++) rectangle(bgr, becareful[i], Scalar(255, 0, 0), 2, 1); // for (unsigned j = 0; j < circle.size(); j++) // rectangle(bgr, circle[j], Scalar(255, 0, 0), 2, 1); // for (unsigned k = 0; k < left_.size(); k++) // rectangle(bgr, left_[k], Scalar(255, 0, 0), 2, 1); for (unsigned l = 0; l < stop_.size(); l++) rectangle(bgr, stop_[l], Scalar(255, 0, 0), 2, 1); // for (unsigned m = 0; m < parking.size(); m++) // rectangle(bgr, parking[m], Scalar(255, 0, 0), 2, 1); for (unsigned n = 0; n < right_.size(); n++) rectangle(bgr, right_[n], Scalar(255, 0, 0), 2, 1); // for (unsigned o = 0; o < forward.size(); o++) // rectangle(bgr, forward[o], Scalar(255, 0, 0), 2, 1); imshow("original", bgr); if (cvWaitKey(20) == 'q') // waitkey { capture.release(); break; } } // release the raspicam frame grabbing return 0; } //// Compile : /* g++ cascade_based_traffic_sign_raspicam.cpp -o cascade_based_traffic_signs -I/usr/local/include -L/usr/local/lib -L/opt/vc/lib -lraspicam -lraspicam_cv -lmmal -lmmal_core -lmmal_util `pkg-config --cflags --libs opencv` */
38.428571
129
0.641795
[ "vector" ]
b87a6fbcc7ccf1dae86e6e1f34e33e72a88bed9f
640
cpp
C++
920.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
920.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
920.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = uint64_t; using ll = int64_t; using ld = long double; class Solution { public: int numMusicPlaylists(int N, int L, int K) { const int mod = 1000000007; vector< vector<int> > table(L + 1, vector<int>(N + 1, 0)); table[0][0] = 1; for (int i = 1; i <= L; ++i) { for (int j = 1; j <= N; ++j) { table[i][j] = (table[i][j] + (ll)table[i - 1][j - 1] * (N - j + 1)) % mod; table[i][j] = (table[i][j] + (ll)table[i - 1][j] * max(j - K, 0)) % mod; } } return table[L][N]; } };
26.666667
90
0.457813
[ "vector" ]
b87d0e67980535051a390b1e9fa96e38d7113f75
1,774
hpp
C++
shift/parser.proto/private/shift/parser/proto/error_handler.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
2
2018-11-28T18:14:08.000Z
2020-08-06T07:44:36.000Z
shift/parser.proto/private/shift/parser/proto/error_handler.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
4
2018-11-06T21:01:05.000Z
2019-02-19T07:52:52.000Z
shift/parser.proto/private/shift/parser/proto/error_handler.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
null
null
null
#ifndef SHIFT_PARSER_PROTO_ERRORHANDLER_HPP #define SHIFT_PARSER_PROTO_ERRORHANDLER_HPP #include <algorithm> #include <string> #include <map> #include <shift/core/boost_disable_warnings.hpp> #include <boost/spirit/include/qi.hpp> #include <shift/core/boost_restore_warnings.hpp> #include <shift/core/exception.hpp> #include "shift/parser/proto/proto.hpp" #include "shift/parser/proto/error.hpp" namespace shift::parser::proto { using parse_error_message = boost::error_info<struct parse_error_message_tag, error_parse>; /// An exception type thrown if the parser reports an error. struct parse_error : virtual core::runtime_error { }; /// An error handler for the grammar parser. template <typename Iterator> struct error_handler { template <class Info> void operator()( const std::vector<std::pair<std::string, std::string>>& diagnostics, Iterator /*begin*/, Iterator /*end*/, Iterator where, Info const& info) const { using std::distance; BOOST_ASSERT(source); auto token_location = distance(source->code.cbegin(), where); auto diagnostic = std::find_if( diagnostics.begin(), diagnostics.end(), [&](const auto& pair) { return pair.first == info.tag.c_str(); }); // Throw exception because we cannot continue parsing the document. BOOST_THROW_EXCEPTION( parse_error() << parse_error_message( error_parse{(diagnostic != diagnostics.end()) ? diagnostic->second : "Expected " + info.tag, static_cast<std::size_t>( std::distance(diagnostics.begin(), diagnostic)), annotation_info(source, token_location, token_location)})); } std::shared_ptr<source_module> source; }; } #endif
30.067797
79
0.684329
[ "vector" ]
b8823311a86f2b242feae8db970c715d529c669b
1,994
cpp
C++
src/tx/tx_create_multisig_address.cpp
MinterTeam/cpp-minter
af657bb21d4b68429948f8d34fd642f874fe412e
[ "MIT" ]
7
2019-06-26T11:37:49.000Z
2020-11-04T21:47:19.000Z
src/tx/tx_create_multisig_address.cpp
MinterTeam/cpp-minter
af657bb21d4b68429948f8d34fd642f874fe412e
[ "MIT" ]
1
2020-02-29T10:41:58.000Z
2020-03-02T16:21:40.000Z
src/tx/tx_create_multisig_address.cpp
MinterTeam/cpp-minter
af657bb21d4b68429948f8d34fd642f874fe412e
[ "MIT" ]
5
2019-08-22T16:24:18.000Z
2020-03-01T15:34:08.000Z
/*! * minter_tx. * tx_create_multisig_address.cpp * * \date 2019 * \author Eduard Maximovich (edward.vstock@gmail.com) * \link https://github.com/edwardstock */ #include "minter/tx/tx_create_multisig_address.h" #include "minter/tx/tx_type.h" #include <algorithm> minter::tx_create_multisig_address::tx_create_multisig_address(std::shared_ptr<minter::tx> tx) : tx_data(std::move(tx)) { } uint16_t minter::tx_create_multisig_address::type() const { return minter::tx_create_multisig_address_type.type(); } dev::bytes minter::tx_create_multisig_address::encode() { eth::RLPStream out; eth::RLPStream lst; { lst.append(m_threshold); lst.append(m_weights); lst.append(m_addresses); out.appendList(lst); } return out.out(); } void minter::tx_create_multisig_address::decode(const dev::bytes& data) { eth::RLP rlp(data); m_threshold = (dev::bigint) rlp[0]; m_weights = rlp[1].toVector<dev::bigint>(); std::vector<dev::bytes> addresses = rlp[2].toVector<dev::bytes>(); std::for_each(addresses.begin(), addresses.end(), [this](const dev::bytes& add) { m_addresses.push_back(minter::data::address(std::move(add))); }); } unsigned minter::tx_create_multisig_address::get_threshold() const { return static_cast<unsigned>(m_threshold); } const std::vector<minter::data::address>& minter::tx_create_multisig_address::get_addresses() const { return m_addresses; } const std::vector<dev::bigint>& minter::tx_create_multisig_address::get_weights() const { return m_weights; } minter::tx_create_multisig_address& minter::tx_create_multisig_address::set_threshold(unsigned threshold) { m_threshold = dev::bigint(threshold); return *this; } minter::tx_create_multisig_address& minter::tx_create_multisig_address::add_address(const minter::address_t& address, unsigned weight) { m_addresses.push_back(address); m_weights.push_back(dev::bigint(weight)); return *this; }
28.898551
136
0.715145
[ "vector" ]
b88adaef76ef85f4cfaea6ba53be593296529feb
13,914
cpp
C++
src/library/generator.copy.cpp
kif/clFFT
abd7828e4a290896aa3c1239f6b547080041b283
[ "Apache-2.0" ]
1
2020-06-15T19:35:05.000Z
2020-06-15T19:35:05.000Z
src/library/generator.copy.cpp
kif/clFFT
abd7828e4a290896aa3c1239f6b547080041b283
[ "Apache-2.0" ]
null
null
null
src/library/generator.copy.cpp
kif/clFFT
abd7828e4a290896aa3c1239f6b547080041b283
[ "Apache-2.0" ]
null
null
null
/* ************************************************************************ * Copyright 2013 Advanced Micro Devices, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************/ #include "stdafx.h" #include <math.h> #include <list> #include "generator.stockham.h" using namespace StockhamGenerator; namespace CopyGenerator { // Copy kernel template <Precision PR> class CopyKernel { size_t N; size_t Nt; const FFTKernelGenKeyParams params; bool h2c, c2h; inline std::string OffsetCalc(const std::string &off, bool input = true) { std::string str; const size_t *pStride = input ? params.fft_inStride : params.fft_outStride; std::string batch = "batch"; switch(params.fft_DataDim) { case 5: { str += "\t{\n\tuint ocalc1 = "; str += batch; str += "%"; str += SztToStr(params.fft_N[1] * params.fft_N[2] * params.fft_N[3]); str += ";\n"; str += "\tuint ocalc0 = "; str += "ocalc1"; str += "%"; str += SztToStr(params.fft_N[1] * params.fft_N[2]); str += ";\n"; str += "\t"; str += off; str += " = "; str += "("; str += batch; str += "/"; str += SztToStr(params.fft_N[1] * params.fft_N[2] * params.fft_N[3]); str += ")*"; str += SztToStr(pStride[4]); str += " + "; str += "(ocalc1"; str += "/"; str += SztToStr(params.fft_N[1] * params.fft_N[2]); str += ")*"; str += SztToStr(pStride[3]); str += " + "; str += "(ocalc0"; str += "/"; str += SztToStr(params.fft_N[1]); str += ")*"; str += SztToStr(pStride[2]); str += " + "; str += "(ocalc0"; str += "%"; str += SztToStr(params.fft_N[1]); str += ")*"; str += SztToStr(pStride[1]); str += ";\n"; str += "\t}\n"; } break; case 4: { str += "\t{\n\tuint ocalc0 = "; str += batch; str += "%"; str += SztToStr(params.fft_N[1] * params.fft_N[2]); str += ";\n"; str += "\t"; str += off; str += " = "; str += "("; str += batch; str += "/"; str += SztToStr(params.fft_N[1] * params.fft_N[2]); str += ")*"; str += SztToStr(pStride[3]); str += " + "; str += "(ocalc0"; str += "/"; str += SztToStr(params.fft_N[1]); str += ")*"; str += SztToStr(pStride[2]); str += " + "; str += "(ocalc0"; str += "%"; str += SztToStr(params.fft_N[1]); str += ")*"; str += SztToStr(pStride[1]); str += ";\n"; str += "\t}\n"; } break; case 3: { str += "\t"; str += off; str += " = "; str += "("; str += batch; str += "/"; str += SztToStr(params.fft_N[1]); str += ")*"; str += SztToStr(pStride[2]); str += " + "; str += "("; str += batch; str += "%"; str += SztToStr(params.fft_N[1]); str += ")*"; str += SztToStr(pStride[1]); str += ";\n"; } break; case 2: { str += "\t"; str += off; str += " = "; str += batch; str += "*"; str += SztToStr(pStride[1]); str += ";\n"; } break; default: assert(false); } return str; } public: CopyKernel( const FFTKernelGenKeyParams &paramsVal) : params(paramsVal) { N = params.fft_N[0]; Nt = 1 + N/2; h2c = ( (params.fft_inputLayout == CLFFT_HERMITIAN_PLANAR) || (params.fft_inputLayout == CLFFT_HERMITIAN_INTERLEAVED) ) ? true : false; c2h = ( (params.fft_outputLayout == CLFFT_HERMITIAN_PLANAR) || (params.fft_outputLayout == CLFFT_HERMITIAN_INTERLEAVED) ) ? true : false; // We only do out-of-place copies at this point assert(params.fft_placeness == CLFFT_OUTOFPLACE); } void GenerateKernel(std::string &str) { std::string rType = RegBaseType<PR>(1); std::string r2Type = RegBaseType<PR>(2); bool inIlvd; // Input is interleaved format bool outIlvd; // Output is interleaved format inIlvd = ( (params.fft_inputLayout == CLFFT_COMPLEX_INTERLEAVED) || (params.fft_inputLayout == CLFFT_HERMITIAN_INTERLEAVED) ) ? true : false; outIlvd = ( (params.fft_outputLayout == CLFFT_COMPLEX_INTERLEAVED) || (params.fft_outputLayout == CLFFT_HERMITIAN_INTERLEAVED) ) ? true : false; // Pragma str += ClPragma<PR>(); std::string sfx = FloatSuffix<PR>(); // Copy kernel begin str += "__kernel void "; // Function name if(h2c) str += "copy_h2c"; else str += "copy_c2h"; str += "("; if(inIlvd) { str += "__global const "; str += r2Type; str += " * restrict gbIn, "; } else { str += "__global const "; str += rType; str += " * restrict gbInRe, "; str += "__global const "; str += rType; str += " * restrict gbInIm, "; } if(outIlvd) { str += "__global "; str += r2Type; str += " * restrict gbOut)\n"; } else { str += "__global "; str += rType; str += " * restrict gbOutRe, "; str += "__global "; str += rType; str += " * restrict gbOutIm)\n"; } str += "{\n"; // Initialize str += "\tuint me = get_global_id(0);\n\t"; // Declare memory pointers str += "\n\t"; str += "uint iOffset;\n\t"; str += "uint oOffset;\n\t"; // input if(inIlvd) { str += "__global "; str += r2Type; str += " *lwbIn;\n\t"; } else { str += "__global "; str += rType; str += " *lwbInRe;\n\t"; str += "__global "; str += rType; str += " *lwbInIm;\n\t"; } // output if(outIlvd) { str += "__global "; str += r2Type; str += " *lwbOut;\n"; if(h2c) { str += "\t"; str += "__global "; str += r2Type; str += " *lwbOut2;\n\n"; } } else { str += "__global "; str += rType; str += " *lwbOutRe;\n\t"; str += "__global "; str += rType; str += " *lwbOutIm;\n"; if(h2c) { str += "\t"; str += "__global "; str += rType; str += " *lwbOutRe2;\n\t"; str += "__global "; str += rType; str += " *lwbOutIm2;\n\n"; } } // Setup registers str += "\t"; str += RegBaseType<PR>(2); str += " R;\n\n"; // Setup variables str += "\tuint batch, mel, mel2;\n\t"; str += "batch = me/"; str += SztToStr(Nt); str += ";\n\t"; str += "mel = me%"; str += SztToStr(Nt); str += ";\n\t"; str += "mel2 = ("; str += SztToStr(N); str += " - mel)%"; str += SztToStr(N); str += ";\n\n"; // Setup memory pointers str += OffsetCalc("iOffset", true); str += OffsetCalc("oOffset", false); // offset strings std::string inF, inF2, outF, outF2; inF = "(mel*"; inF += SztToStr(params.fft_inStride[0]); inF += ")"; inF2 = "(mel2*"; inF2 += SztToStr(params.fft_inStride[0]); inF2 += ")"; outF = "(mel*"; outF += SztToStr(params.fft_outStride[0]); outF += ")"; outF2 = "(mel2*"; outF2 += SztToStr(params.fft_outStride[0]); outF2 += ")"; str += "\n\t"; // inputs if(inIlvd) { str += "lwbIn = gbIn + iOffset + "; str += inF; str += ";\n\t"; } else { str += "lwbInRe = gbInRe + iOffset + "; str += inF; str += ";\n\t"; str += "lwbInIm = gbInIm + iOffset + "; str += inF; str += ";\n\t"; } // outputs if(outIlvd) { str += "lwbOut = gbOut + oOffset + "; str += outF; str += ";\n"; if(h2c) { str += "\t"; str += "lwbOut2 = gbOut + oOffset + "; str += outF2; str += ";\n"; } } else { str += "lwbOutRe = gbOutRe + oOffset + "; str += outF; str += ";\n\t"; str += "lwbOutIm = gbOutIm + oOffset + "; str += outF; str += ";\n"; if(h2c) { str += "\t"; str += "lwbOutRe2 = gbOutRe + oOffset + "; str += outF2; str += ";\n\t"; str += "lwbOutIm2 = gbOutIm + oOffset + "; str += outF2; str += ";\n"; } } str += "\n\t"; // Do the copy if(c2h) { if(inIlvd) { str += "R = lwbIn[0];\n\t"; } else { str += "R.x = lwbInRe[0];\n\t"; str += "R.y = lwbInIm[0];\n\t"; } if(outIlvd) { str += "lwbOut[0] = R;\n\n"; } else { str += "lwbOutRe[0] = R.x;\n\t"; str += "lwbOutIm[0] = R.y;\n\t"; } } else { if(inIlvd) { str += "R = lwbIn[0];\n\t"; } else { str += "R.x = lwbInRe[0];\n\t"; str += "R.y = lwbInIm[0];\n\t"; } if(outIlvd) { str += "lwbOut[0] = R;\n\t"; str += "R.y = -R.y;\n\t"; str += "lwbOut2[0] = R;\n\n"; } else { str += "lwbOutRe[0] = R.x;\n\t"; str += "lwbOutIm[0] = R.y;\n\t"; str += "R.y = -R.y;\n\t"; str += "lwbOutRe2[0] = R.x;\n\t"; str += "lwbOutIm2[0] = R.y;\n\n"; } } str += "}\n"; } }; }; template<> clfftStatus FFTPlan::GetKernelGenKeyPvt<Copy> (FFTKernelGenKeyParams & params) const { // Query the devices in this context for their local memory sizes // How we generate a kernel depends on the *minimum* LDS size for all devices. // const FFTEnvelope * pEnvelope = NULL; OPENCL_V(const_cast<FFTPlan*>(this)->GetEnvelope (& pEnvelope), _T("GetEnvelope failed")); BUG_CHECK (NULL != pEnvelope); ::memset( &params, 0, sizeof( params ) ); params.fft_precision = this->precision; params.fft_placeness = this->placeness; params.fft_inputLayout = this->inputLayout; params.fft_MaxWorkGroupSize = this->envelope.limit_WorkGroupSize; ARG_CHECK (this->inStride.size() == this->outStride.size()) params.fft_outputLayout = this->outputLayout; switch (this->inStride.size()) { // 1-D array is a 2-D data structure. // 1-D unit is a special case of 1-D array. case 1: ARG_CHECK(this->length .size() > 0); ARG_CHECK(this->outStride.size() > 0); params.fft_DataDim = 2; params.fft_N[0] = this->length[0]; params.fft_inStride[0] = this->inStride[0]; params.fft_inStride[1] = this->iDist; params.fft_outStride[0] = this->outStride[0]; params.fft_outStride[1] = this->oDist; break; // 2-D array is a 3-D data structure // 2-D unit is a speical case of 2-D array. case 2: ARG_CHECK(this->length .size() > 1); ARG_CHECK(this->outStride.size() > 1); params.fft_DataDim = 3; params.fft_N[0] = this->length[0]; params.fft_N[1] = this->length[1]; params.fft_inStride[0] = this->inStride[0]; params.fft_inStride[1] = this->inStride[1]; params.fft_inStride[2] = this->iDist; params.fft_outStride[0] = this->outStride[0]; params.fft_outStride[1] = this->outStride[1]; params.fft_outStride[2] = this->oDist; break; // 3-D array is a 4-D data structure // 3-D unit is a special case of 3-D array. case 3: ARG_CHECK(this->length .size() > 2); ARG_CHECK(this->outStride.size() > 2); params.fft_DataDim = 4; params.fft_N[0] = this->length[0]; params.fft_N[1] = this->length[1]; params.fft_N[2] = this->length[2]; params.fft_inStride[0] = this->inStride[0]; params.fft_inStride[1] = this->inStride[1]; params.fft_inStride[2] = this->inStride[2]; params.fft_inStride[3] = this->iDist; params.fft_outStride[0] = this->outStride[0]; params.fft_outStride[1] = this->outStride[1]; params.fft_outStride[2] = this->outStride[2]; params.fft_outStride[3] = this->oDist; break; default: ARG_CHECK (false); } params.fft_fwdScale = this->forwardScale; params.fft_backScale = this->backwardScale; return CLFFT_SUCCESS; } template<> clfftStatus FFTPlan::GetWorkSizesPvt<Copy> (std::vector<size_t> & globalWS, std::vector<size_t> & localWS) const { FFTKernelGenKeyParams fftParams; OPENCL_V( this->GetKernelGenKeyPvt<Copy>( fftParams ), _T("GetKernelGenKey() failed!") ); size_t count = this->batchsize; switch(fftParams.fft_DataDim) { case 5: assert(false); case 4: count *= fftParams.fft_N[2]; case 3: count *= fftParams.fft_N[1]; case 2: count *= (1 + fftParams.fft_N[0]/2); break; case 1: assert(false); } globalWS.push_back( count ); localWS.push_back( 64 ); return CLFFT_SUCCESS; } template<> clfftStatus FFTPlan::GetMax1DLengthPvt<Copy> (size_t * longest) const { return FFTPlan::GetMax1DLengthPvt<Stockham>(longest); } using namespace CopyGenerator; template<> clfftStatus FFTPlan::GenerateKernelPvt<Copy>(FFTRepo& fftRepo, const cl_command_queue commQueueFFT ) const { FFTKernelGenKeyParams params; OPENCL_V( this->GetKernelGenKeyPvt<Copy> (params), _T("GetKernelGenKey() failed!") ); std::string programCode; Precision pr = (params.fft_precision == CLFFT_SINGLE) ? P_SINGLE : P_DOUBLE; switch(pr) { case P_SINGLE: { CopyKernel<P_SINGLE> kernel(params); kernel.GenerateKernel(programCode); } break; case P_DOUBLE: { CopyKernel<P_DOUBLE> kernel(params); kernel.GenerateKernel(programCode); } break; } cl_int status = CL_SUCCESS; cl_context QueueContext = NULL; status = clGetCommandQueueInfo(commQueueFFT, CL_QUEUE_CONTEXT, sizeof(cl_context), &QueueContext, NULL); OPENCL_V( status, _T( "clGetCommandQueueInfo failed" ) ); OPENCL_V( fftRepo.setProgramCode( Copy, params, programCode, QueueContext ), _T( "fftRepo.setclString() failed!" ) ); OPENCL_V( fftRepo.setProgramEntryPoints( Copy, params, "copy_c2h", "copy_h2c", QueueContext ), _T( "fftRepo.setProgramEntryPoint() failed!" ) ); return CLFFT_SUCCESS; }
28.9875
146
0.55304
[ "vector" ]
b898dd6776af7cd8f4f1addd1f10c81ffede4fad
2,929
cpp
C++
remodet_repository_wdh_part/test/testConvNHWC/src/testConvNHWC.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/test/testConvNHWC/src/testConvNHWC.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/test/testConvNHWC/src/testConvNHWC.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
#include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <utility> #include <vector> #include <map> #include <algorithm> #include <stdint.h> #include "gflags/gflags.h" #include "glog/logging.h" #include <boost/shared_ptr.hpp> #include "caffe/proto/caffe.pb.h" #include "caffe/blob.hpp" #include "caffe/util/benchmark.hpp" #include "caffe/util/io.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/rng.hpp" #include "caffe/layer.hpp" #include "caffe/filler.hpp" #include "caffe/nhwc/conv_nhwc_layer.hpp" #include "gtest/gtest.h" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" using namespace std; using namespace caffe; int main(int nargc, char** args) { // set caffe::GPU caffe::Caffe::SetDevice(0); caffe::Caffe::set_mode(caffe::Caffe::CPU); int channels = 16; //input int num_output = 32; // output int dim = 4; // size // define input & output blobs Blob<float>* input = new Blob<float>(1, dim, dim, channels); Blob<float>* output = new Blob<float>(1, dim, dim, num_output); vector<Blob<float>*> bottom_vec; vector<Blob<float>*> top_vec; // set the bottom blob data FillerParameter filler_param; filler_param.set_std(0.5); GaussianFiller<float> filler(filler_param); filler.Fill(input); // set the bottom and top data-pointer bottom_vec.push_back(input); top_vec.push_back(output); // create reorg layer LayerParameter layer_param; layer_param.set_name("ConvNHWC"); layer_param.set_type("ConvolutionNHWC"); ConvolutionParameter* conv_param = layer_param.mutable_convolution_param(); conv_param->set_kernel_h(3); conv_param->set_kernel_w(3); conv_param->set_stride_h(1); conv_param->set_stride_w(1); conv_param->set_pad_h(1); conv_param->set_pad_w(1); conv_param->set_group(1); conv_param->set_num_output(num_output); conv_param->set_engine(caffe::ConvolutionParameter_Engine_CAFFE); FillerParameter* weight_filler = conv_param->mutable_weight_filler(); weight_filler->set_type("gaussian"); weight_filler->set_std(0.01); FillerParameter* bias_filler = conv_param->mutable_bias_filler(); bias_filler->set_type("constant"); bias_filler->set_std(0); boost::shared_ptr<Layer<float> > convNHWC_layer = LayerRegistry<float>::CreateLayer(layer_param); convNHWC_layer->SetUp(bottom_vec, top_vec); convNHWC_layer->Forward(bottom_vec, top_vec); // copy diff // caffe_copy(top_vec[0]->count(), top_vec[0]->cpu_data(), top_vec[0]->mutable_cpu_diff()); // // for (int i = 0; i < top_vec[0]->count(); ++i) { // LOG(INFO) << top_vec[0]->cpu_data()[i]; // } // LOG(FATAL) << "End."; GradientChecker<float> checker(1e-4, 1e-3); checker.CheckGradientExhaustive(convNHWC_layer.get(), bottom_vec, top_vec); LOG(INFO) << "Gradient Check Finished."; return 0; }
29.585859
99
0.723455
[ "vector" ]
b89f0b4cdb8164d20b9e3841c348b7c15f8aa930
7,506
cpp
C++
src/core/Array.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
30
2020-02-09T22:30:06.000Z
2022-01-26T04:23:09.000Z
src/core/Array.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
1
2020-10-12T04:12:52.000Z
2020-12-19T07:07:51.000Z
src/core/Array.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
5
2020-02-10T02:49:13.000Z
2021-01-25T18:18:16.000Z
#include "Array.hpp" #include "GodotGlobal.hpp" #include "Variant.hpp" #include <cstdlib> #include <stdexcept> #define PY_SSIZE_T_CLEAN #include <Python.h> #include <_lib/godot/core/types.hpp> namespace godot { class Object; Array::Array() { godot::api->godot_array_new(&_godot_array); } Array::Array(const Array &other) { godot::api->godot_array_new_copy(&_godot_array, &other._godot_array); } Array &Array::operator=(const Array &other) { godot::api->godot_array_destroy(&_godot_array); godot::api->godot_array_new_copy(&_godot_array, &other._godot_array); return *this; } Array::Array(const PoolByteArray &a) { godot::api->godot_array_new_pool_byte_array(&_godot_array, (godot_pool_byte_array *)&a); } Array::Array(const PoolIntArray &a) { godot::api->godot_array_new_pool_int_array(&_godot_array, (godot_pool_int_array *)&a); } Array::Array(const PoolRealArray &a) { godot::api->godot_array_new_pool_real_array(&_godot_array, (godot_pool_real_array *)&a); } Array::Array(const PoolStringArray &a) { godot::api->godot_array_new_pool_string_array(&_godot_array, (godot_pool_string_array *)&a); } Array::Array(const PoolVector2Array &a) { godot::api->godot_array_new_pool_vector2_array(&_godot_array, (godot_pool_vector2_array *)&a); } Array::Array(const PoolVector3Array &a) { godot::api->godot_array_new_pool_vector3_array(&_godot_array, (godot_pool_vector3_array *)&a); } Array::Array(const PoolColorArray &a) { godot::api->godot_array_new_pool_color_array(&_godot_array, (godot_pool_color_array *)&a); } Variant &Array::operator[](const int idx) { godot_variant *v = godot::api->godot_array_operator_index(&_godot_array, idx); return *(Variant *)v; } Variant Array::operator[](const int idx) const { // Yes, I'm casting away the const... you can hate me now. // since the result is godot_variant *v = godot::api->godot_array_operator_index((godot_array *)&_godot_array, idx); return *(Variant *)v; } void Array::append(const Variant &v) { godot::api->godot_array_append(&_godot_array, (godot_variant *)&v); } void Array::clear() { godot::api->godot_array_clear(&_godot_array); } int Array::count(const Variant &v) { return godot::api->godot_array_count(&_godot_array, (godot_variant *)&v); } bool Array::empty() const { return godot::api->godot_array_empty(&_godot_array); } void Array::erase(const Variant &v) { godot::api->godot_array_erase(&_godot_array, (godot_variant *)&v); } Variant Array::front() const { godot_variant v = godot::api->godot_array_front(&_godot_array); return *(Variant *)&v; } Variant Array::back() const { godot_variant v = godot::api->godot_array_back(&_godot_array); return *(Variant *)&v; } int Array::find(const Variant &what, const int from) { return godot::api->godot_array_find(&_godot_array, (godot_variant *)&what, from); } int Array::find_last(const Variant &what) { return godot::api->godot_array_find_last(&_godot_array, (godot_variant *)&what); } bool Array::has(const Variant &what) const { return godot::api->godot_array_has(&_godot_array, (godot_variant *)&what); } uint32_t Array::hash() const { return godot::api->godot_array_hash(&_godot_array); } void Array::insert(const int pos, const Variant &value) { godot::api->godot_array_insert(&_godot_array, pos, (godot_variant *)&value); } void Array::invert() { godot::api->godot_array_invert(&_godot_array); } Variant Array::pop_back() { godot_variant v = godot::api->godot_array_pop_back(&_godot_array); return *(Variant *)&v; } Variant Array::pop_front() { godot_variant v = godot::api->godot_array_pop_front(&_godot_array); return *(Variant *)&v; } void Array::push_back(const Variant &v) { godot::api->godot_array_push_back(&_godot_array, (godot_variant *)&v); } void Array::push_front(const Variant &v) { godot::api->godot_array_push_front(&_godot_array, (godot_variant *)&v); } void Array::remove(const int idx) { godot::api->godot_array_remove(&_godot_array, idx); } int Array::size() const { return godot::api->godot_array_size(&_godot_array); } void Array::resize(const int size) { godot::api->godot_array_resize(&_godot_array, size); } int Array::rfind(const Variant &what, const int from) { return godot::api->godot_array_rfind(&_godot_array, (godot_variant *)&what, from); } void Array::sort() { godot::api->godot_array_sort(&_godot_array); } void Array::sort_custom(Object *obj, const String &func) { godot::api->godot_array_sort_custom(&_godot_array, (godot_object *)obj, (godot_string *)&func); } int Array::bsearch(const Variant &value, const bool before) { return godot::api->godot_array_bsearch(&_godot_array, (godot_variant *)&value, before); } int Array::bsearch_custom(const Variant &value, const Object *obj, const String &func, const bool before) { return godot::api->godot_array_bsearch_custom(&_godot_array, (godot_variant *)&value, (godot_object *)obj, (godot_string *)&func, before); } Array Array::duplicate(const bool deep) const { godot_array arr = godot::core_1_1_api->godot_array_duplicate(&_godot_array, deep); return *(Array *)&arr; } Variant Array::max() const { godot_variant v = godot::core_1_1_api->godot_array_max(&_godot_array); return *(Variant *)&v; } Variant Array::min() const { godot_variant v = godot::core_1_1_api->godot_array_min(&_godot_array); return *(Variant *)&v; } void Array::shuffle() { godot::core_1_1_api->godot_array_shuffle(&_godot_array); } Array::~Array() { godot::api->godot_array_destroy(&_godot_array); } Array::Array(const PyObject *o) { if (Py_TYPE(o) == PyGodotWrapperType_Array) { godot_array *p = _python_wrapper_to_godot_array((PyObject *)o); if (likely(p)) { godot::api->godot_array_new_copy(&_godot_array, p); } else { // raises ValueError in Cython/Python context throw std::invalid_argument("invalid Python argument"); } // TODO: Other array wrappers } else { // Not a C++ wrapper, initialize from standard Python types and protocols godot::api->godot_array_new(&_godot_array); if (PyTuple_CheckExact((PyObject *)o)) { // Tuples are faster than generic sequence protocol for (int i = 0; i < PyTuple_GET_SIZE(o); i++) { PyObject *item = PyTuple_GET_ITEM((PyObject *)o, i); append(Variant(item)); } } else if (PySequence_Check((PyObject *)o)) { for (int i = 0; i < PySequence_Length((PyObject *)o); i++) { PyObject *item = PySequence_GetItem((PyObject *)o, i); append(Variant(item)); } } else if (PyIter_Check((PyObject *)o)) { PyObject *iterator = PyObject_GetIter((PyObject *)o); PyObject *item; if (iterator) { while ((item = PyIter_Next(iterator))) { append(Variant(item)); Py_DECREF(item); } Py_DECREF(iterator); } if (PyErr_Occurred()) { PyErr_Print(); ERR_PRINT("Python Error in Array constructor"); } } } } PyObject *Array::py_tuple() const { PyObject *obj = PyTuple_New(size()); for (int i; i < size(); i++) { godot_variant *v = godot::api->godot_array_operator_index((godot_array *)&_godot_array, i); PyObject *item = *(Variant *)v; // FIXME: Check NULL pointer? PyTuple_SET_ITEM(obj, i, item); } Py_INCREF(obj); return obj; } PyObject *Array::py_list() const { PyObject *obj = PyList_New(size()); for (int i; i < size(); i++) { godot_variant *v = godot::api->godot_array_operator_index((godot_array *)&_godot_array, i); PyObject *item = *(Variant *)v; // FIXME: Check NULL pointer? PyList_SET_ITEM(obj, i, item); } Py_INCREF(obj); return obj; } } // namespace godot
27.195652
96
0.715028
[ "object" ]
b8a2aeb5bf9c5505e965059b94853e5db94de630
1,186
hpp
C++
src/base/BackedWriter.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
1,783
2018-02-28T16:28:42.000Z
2022-03-31T18:45:01.000Z
src/base/BackedWriter.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
337
2018-02-27T06:38:39.000Z
2022-03-22T02:50:58.000Z
src/base/BackedWriter.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
135
2018-04-30T14:48:36.000Z
2022-03-21T16:51:09.000Z
#ifndef __ET_BACKED_WRITER__ #define __ET_BACKED_WRITER__ #include "Headers.hpp" #include "CryptoHandler.hpp" #include "Packet.hpp" #include "SocketHandler.hpp" namespace et { enum class BackedWriterWriteState { SKIPPED = 0, // SUCCESS = 1, WROTE_WITH_FAILURE = 2 }; class BackedWriter { public: BackedWriter(shared_ptr<SocketHandler> socketHandler, shared_ptr<CryptoHandler> cryptoHandler, int socketFd); BackedWriterWriteState write(Packet packet); vector<std::string> recover(int64_t lastValidSequenceNumber); void revive(int newSocketFd); mutex& getRecoverMutex() { return recoverMutex; } inline int getSocketFd() { return socketFd; } inline void invalidateSocket() { lock_guard<std::mutex> guard(recoverMutex); socketFd = -1; } inline int64_t getSequenceNumber() { return sequenceNumber; } protected: mutex recoverMutex; shared_ptr<SocketHandler> socketHandler; shared_ptr<CryptoHandler> cryptoHandler; int socketFd; static const int MAX_BACKUP_BYTES = 64 * 1024 * 1024; std::deque<Packet> backupBuffer; int64_t backupSize; int64_t sequenceNumber; }; } // namespace et #endif // __ET_BACKED_WRITER__
22.807692
70
0.743676
[ "vector" ]
b8a8332dbb2a52b90d0355f7183876f1c971d6c1
3,747
cpp
C++
PSME/common/agent-framework/src/module/model/acl_rule.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/common/agent-framework/src/module/model/acl_rule.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
null
null
null
PSME/common/agent-framework/src/module/model/acl_rule.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/*! * @copyright * Copyright (c) 2016-2017 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ #include "agent-framework/module/utils/utils.hpp" #include "agent-framework/module/model/acl_rule.hpp" #include "agent-framework/module/constants/network.hpp" #include "agent-framework/module/constants/common.hpp" using namespace agent_framework::model; using namespace agent_framework::model::utils; const enums::Component AclRule::component = enums::Component::AclRule; const enums::CollectionName AclRule::collection_name = enums::CollectionName::AclRules; AclRule::AclRule(const std::string& parent_uuid, enums::Component parent_type) : Resource{parent_uuid, parent_type} {} AclRule::~AclRule() {} Json::Value AclRule::to_json() const { Json::Value value; value[literals::AclRule::STATUS] = get_status().to_json(); value[literals::AclRule::RULE_ID] = get_rule_id(); value[literals::AclRule::ACTION] = get_action(); value[literals::AclRule::FORWARD_MIRROR_PORT] = get_forward_mirror_port(); value[literals::AclRule::MIRRORED_PORTS] = get_mirrored_ports().to_json(); value[literals::AclRule::MIRROR_TYPE] = get_mirror_type(); value[literals::AclRule::VLAN_ID] = get_vlan_id().to_json(); value[literals::AclRule::SOURCE_IP] = get_source_ip().to_json(); value[literals::AclRule::DESTINATION_IP] = get_destination_ip().to_json(); value[literals::AclRule::SOURCE_MAC] = get_source_mac().to_json(); value[literals::AclRule::DESTINATION_MAC] = get_destination_mac().to_json(); value[literals::AclRule::SOURCE_L4_PORT] = get_source_port().to_json(); value[literals::AclRule::DESTINATION_L4_PORT] = get_destination_port().to_json(); value[literals::AclRule::PROTOCOL] = get_protocol(); value[literals::AclRule::OEM] = get_oem().to_json(); return value; } AclRule AclRule::from_json(const Json::Value& json) { AclRule rule; rule.set_status(attribute::Status::from_json(json[literals::Acl::STATUS])); rule.set_rule_id(json[literals::AclRule::RULE_ID]); rule.set_action(json[literals::AclRule::ACTION]); rule.set_forward_mirror_port( json[literals::AclRule::FORWARD_MIRROR_PORT]); rule.set_mirrored_ports(MirroredPorts::from_json( json[literals::AclRule::MIRRORED_PORTS])); rule.set_mirror_type(json[literals::AclRule::MIRROR_TYPE]); rule.set_vlan_id(VlanId::from_json(json[literals::AclRule::VLAN_ID])); rule.set_source_ip(Ip::from_json( json[literals::AclRule::SOURCE_IP])); rule.set_destination_ip(Ip::from_json( json[literals::AclRule::DESTINATION_IP])); rule.set_source_mac(Mac::from_json(json[literals::AclRule::SOURCE_MAC])); rule.set_destination_mac(Mac::from_json( json[literals::AclRule::DESTINATION_MAC])); rule.set_source_port(Port::from_json( json[literals::AclRule::SOURCE_L4_PORT])); rule.set_destination_port(Port::from_json( json[literals::AclRule::DESTINATION_L4_PORT])); rule.set_protocol(json[literals::AclRule::PROTOCOL]); rule.set_oem(attribute::Oem::from_json(json[literals::AclRule::OEM])); rule.set_resource_hash(json); return rule; }
42.101124
87
0.72885
[ "model" ]
b8ac1662a66cdf3895a7ce963314dac0c8ff2da3
23,929
cpp
C++
src/gpu/jit/conv/block_helper.cpp
intel/mkl-dnn
42a583db82325ff24e140fcbff13f720a8b164ab
[ "Apache-2.0" ]
1,327
2018-01-25T21:23:47.000Z
2020-04-03T09:39:30.000Z
src/gpu/jit/conv/block_helper.cpp
intel/mkl-dnn
42a583db82325ff24e140fcbff13f720a8b164ab
[ "Apache-2.0" ]
498
2018-01-25T00:14:48.000Z
2020-04-03T16:21:44.000Z
src/gpu/jit/conv/block_helper.cpp
intel/mkl-dnn
42a583db82325ff24e140fcbff13f720a8b164ab
[ "Apache-2.0" ]
365
2018-01-29T16:12:36.000Z
2020-04-03T08:32:27.000Z
/******************************************************************************* * Copyright 2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "gpu/jit/conv/block_helper.hpp" namespace dnnl { namespace impl { namespace gpu { namespace jit { // Helper class to assign block sizes for problem dimensions according to BMNK // block sizes. class block_assigner_t { public: block_assigner_t(const dim_info_t &bmnk_dim, const std::vector<dim_info_t *> &prb_dims) : bmnk_dim_(bmnk_dim), prb_dims_(prb_dims) { move_to_next_bmnk_level(); move_to_next_prb_dim(); } bool has_blocks() const { if (utils::one_of(level_, tile_level_t::unknown, tile_level_t::_last)) return false; if (prb_dim_idx_ >= (int)prb_dims_.size()) return false; return true; } void assign_block() { ir_assert(has_blocks()); ir_assert(rem_bmnk_dim_.is_unlimited() || rem_bmnk_dim_ > 1); ir_assert(rem_prb_dim_ > 1); // Try a shortcut path to assign all dimensions to the current tile // level at once. if (try_assign_multi_blocks()) return; dim_value_t target_dim = min(rem_bmnk_dim_, prb_dims_[prb_dim_idx_]->max_dim(level_)); int dim = compute_next_block(level_, prb_level_dim(), target_dim, bmnk_dim_.base_iter_block(), rem_prb_dim_, prb_dims_[prb_dim_idx_]->base_iter_block(), is_last_prb_dim()); if (level_ == tile_level_t::iter) { ir_assert(dim % prb_dims_[prb_dim_idx_]->base_iter_block() == 0); } // Assign the computed block size to the current problem dimension. prb_dims_[prb_dim_idx_]->set_dim(level_, dim); // Update the remaining dimensions. if (!rem_bmnk_dim_.is_unlimited()) rem_bmnk_dim_ = rem_bmnk_dim_ / dim; rem_prb_dim_ = utils::div_up(rem_prb_dim_, dim); ir_assert(rem_bmnk_dim_.is_unlimited() || rem_bmnk_dim_ >= 1); ir_assert(rem_prb_dim_ >= 1); // Move to the next BMNK tile or next problem dimension (depending on // split/fuse settings and remaining sizes). if (rem_bmnk_dim_ != 1 && rem_prb_dim_ != 1) { if (allow_fuse()) { rem_prb_dim_ = 1; } else if (prb_dims_[prb_dim_idx_]->allow_split()) { rem_bmnk_dim_ = 1; } else { rem_prb_dim_ = 1; rem_bmnk_dim_ = 1; } } if (rem_bmnk_dim_ == 1 && rem_prb_dim_ == 1) { move_to_next_bmnk_level(); move_to_next_prb_dim(); return; } if (rem_bmnk_dim_ == 1) { move_to_next_bmnk_level(); if (!prb_dims_[prb_dim_idx_]->allow_split()) { move_to_next_prb_dim(); } return; } if (rem_prb_dim_ == 1) { move_to_next_prb_dim(); if (!allow_fuse()) move_to_next_bmnk_level(); return; } ir_error_not_expected(); } private: bool allow_fuse() const { for (auto *d : prb_dims_) if (!d->allow_fuse()) return false; return true; } void move_to_next_bmnk_level() { bool found = false; int l_beg = (int)level_ + 1; int l_end = (int)tile_level_t::_last; for (int l = l_beg; l < l_end; l++) { tile_level_t level = (tile_level_t)l; if (bmnk_dim_.dim(level) != 1) { found = true; level_ = level; rem_bmnk_dim_ = bmnk_dim_.dim(level); break; } } if (!found) level_ = tile_level_t::_last; } void move_to_next_prb_dim() { bool found = false; for (int i = prb_dim_idx_ + 1; i < (int)prb_dims_.size(); i++) { if (prb_dims_[i]->size() != 1) { found = true; prb_dim_idx_ = i; rem_prb_dim_ = prb_dims_[i]->size(); break; } } if (!found) prb_dim_idx_ = (int)prb_dims_.size(); } bool is_last_prb_dim() const { if (!allow_fuse()) return true; for (int i = prb_dim_idx_ + 1; i < (int)prb_dims_.size(); i++) { auto *d = prb_dims_[i]; int max_dim = min(d->size(), d->max_dim(level_)); if (max_dim != 1) return false; } return true; } int prb_level_dim() const { int ret = 1; for (auto *d : prb_dims_) ret *= d->dim(level_); return ret; } int compute_next_block(tile_level_t level, int level_dim, dim_value_t target_dim, int target_base_blk, int dim, int base_iter_block, bool is_last_dim, double target_eff = 0.75) const { if (target_dim.is_unlimited()) return dim; bool require_pow_2 = false; if (level == tile_level_t::tg) require_pow_2 = true; if (level == tile_level_t::iter && utils::one_of(bmnk_dim_.bmnk(), 'N')) require_pow_2 = true; int step = 1; int rem_target_base_blk = 1; if (level == tile_level_t::iter) { rem_target_base_blk = target_base_blk / math::gcd(level_dim, target_base_blk); step = base_iter_block; ir_assert(rem_target_base_blk % base_iter_block == 0); if (is_last_dim) step = rem_target_base_blk; } int ret = utils::rnd_dn(target_dim, step); while (ret >= step) { bool ok = true; if (require_pow_2 && !math::is_pow2(ret)) ok = false; if (!is_last_dim) { if (ret % rem_target_base_blk != 0 && rem_target_base_blk % ret != 0) ok = false; } if (ok) { int dim_padded = utils::rnd_up(dim, ret); double eff = (double)dim / dim_padded; if (eff >= target_eff) break; } ret -= step; } if (ret == 0) ret = step; if (require_pow_2) ir_assert(math::is_pow2(ret)); if (level == tile_level_t::iter) ir_assert(ret % base_iter_block == 0); return ret; } bool is_thr_unlimited() const { if (level_ != tile_level_t::thr) return false; if (rem_bmnk_dim_.is_unlimited()) return false; if (bmnk_dim_.tg_dim() != 1) return false; return true; } bool is_iter_full_match() const { if (level_ != tile_level_t::iter) return false; int prb_total = 1; for (auto *d : prb_dims_) { if (d->iter_dim() != 1) return false; int max_iter_dim = min(d->size(), d->max_dim(tile_level_t::iter)); prb_total *= max_iter_dim; } if (rem_bmnk_dim_ != prb_total) return false; return true; } bool try_assign_multi_blocks() { // Check restrictions to apply the heuristics. if (!allow_fuse()) return false; if (!is_thr_unlimited() && !is_iter_full_match()) return false; int nprb_dims = (int)prb_dims_.size(); std::vector<int> rem_dims(nprb_dims, 1); std::vector<int> dims(nprb_dims, 1); int max_total_dim = 1; for (int i = prb_dim_idx_; i < nprb_dims; i++) { int dim = prb_dims_[i]->size(); int rem_dim = (i == prb_dim_idx_) ? (int)rem_prb_dim_ : dim; rem_dim = min(rem_dim, prb_dims_[i]->max_dim(level_)); rem_dims[i] = rem_dim; max_total_dim *= rem_dim; } bool found = false; std::function<void(int, int, double, double)> step; step = [&](int idx, int total_dim, double eff, double target_eff) { if (total_dim > rem_bmnk_dim_) return; if (eff < target_eff) return; if (idx == nprb_dims) { double min_dim_ratio = 0.5; double dim_ratio = total_dim / (double)rem_bmnk_dim_; // If all available dimensions are assigned, skip any checks. if (total_dim != max_total_dim) { // Skip if the full dimension is too small relative to the // target size. if (dim_ratio < min_dim_ratio) return; // Skip if the padding due to blocking is too large. if (eff < target_eff) return; } // Found good blocking, set the flag. found = true; return; } int dim = prb_dims_[idx]->size(); int rem_dim = rem_dims[idx]; for (int blk = rem_dim; blk >= 1; blk--) { int dim_padded = utils::rnd_up(dim, blk); double dim_eff = (double)dim / dim_padded; dims[idx] = blk; step(idx + 1, total_dim * blk, eff * dim_eff, target_eff); if (found) break; } }; if (level_ == tile_level_t::iter) { // is_iter_full_match() returned true so all dimensions can be // assigned as is. ir_assert(rem_bmnk_dim_ == max_total_dim); for (int i = prb_dim_idx_; i < nprb_dims; i++) { dims[i] = rem_dims[i]; } found = true; } else { // Try to target different efficiencies until a good blocking is // found. for (double eff = 1.0; eff >= 0.5; eff -= 0.05) { step(prb_dim_idx_, 1, 1.0, eff); if (found) break; } } ir_assert(found) << "Can't assign blocks."; for (int i = prb_dim_idx_; i < nprb_dims; i++) { prb_dims_[i]->set_dim(level_, dims[i]); } prb_dim_idx_ = nprb_dims; return true; } tile_level_t level_ = tile_level_t::unknown; dim_info_t bmnk_dim_; dim_value_t rem_bmnk_dim_; std::vector<dim_info_t *> prb_dims_; int prb_dim_idx_ = -1; dim_value_t rem_prb_dim_ = 0; }; void block_helper_t::compute() { is_frozen_ = true; ir_assert(vectorize_by_b() || vectorize_by_n()); init_bmnk_dims(); init_bmnk_blocks(); init_prb_blocks(); #ifdef GEN_CONV_DEBUG for (auto &kv : dims_) { auto &d = kv.second; const char *tags[] = {"iter", "thr", "tg"}; for (int i = min_tile_level_idx; i <= max_tile_level_idx; i++) { auto level = (tile_level_t)i; std::string env_name = d.name() + "_" + tags[i - min_tile_level_idx] + "_dim"; int env_dim = getenv_int(env_name.c_str(), -1); if (env_dim != -1) d.set_dim(level, env_dim); } } #endif // Verify blocks. for (auto &kv : dims_) { auto &d = kv.second; ir_assert(d.iter_dim() % d.base_iter_block() == 0); for (int i = min_tile_level_idx; i <= max_tile_level_idx; i++) { auto level = (tile_level_t)i; auto max_dim = d.max_dim(level); ir_assert(max_dim.is_unlimited() || d.dim(level) <= max_dim); } } for (char bmnk : {'B', 'M', 'N', 'K'}) { int iter_blk = 1; for (auto &kv : dims_) { auto &d = kv.second; if (d.bmnk() != bmnk) continue; iter_blk *= d.iter_dim(); } ir_assert(iter_blk % bmnk_dim(bmnk).base_iter_block() == 0); } // Initialize padded dim and iter block sizes. for (auto &kv : dims_) { auto &d = kv.second; padded_dim_sizes_.emplace(d.name(), d.padded_size()); iter_blocks_.emplace(d.name(), d.iter_dim()); } } void block_helper_t::init_bmnk_blocks() { int m_blk = 0; int k_blk = 0; int bn_blk = 0; int m_inst_blk = 0; int k_inst_blk = 0; int bn_inst_blk = 0; bool is_ge_hpc = (hw_cfg_.hw() >= ngen::HW::XeHPC); bool reduce_m_block = false; if (reduce_m_block_hint_set_) { reduce_m_block = reduce_m_block_hint_; } else { if (m_dim().base_iter_block() == 1) reduce_m_block = true; if (k_dim().base_iter_block() == 1) reduce_m_block = true; } if (is_tf32() && fma_kind_ != fma_kind_t::mad) reduce_m_block = true; int eu_thr_mul = (!is_ge_hpc && reduce_m_block) ? 2 : 4; #ifdef GEN_CONV_DEBUG eu_thr_mul = getenv_int("eu_thr_mul", eu_thr_mul); #endif auto &bn_dim = (vectorize_by_b() ? b_dim() : n_dim()); switch (fma_kind_) { case fma_kind_t::mad: { int max_m_iter_dim = prb_max_dim('M', tile_level_t::iter); m_inst_blk = std::min(8, utils::rnd_down_pow2(max_m_iter_dim)); bn_inst_blk = hw_cfg_.vec_size(); k_inst_blk = 1; bool use_small_m_block = hw_cfg_.hw() <= ngen::HW::XeHP && m_dim().base_iter_block() == 1; m_blk = (is_x8x8s32() || use_small_m_block ? 8 : 16); bool small_m_tg = m_dim().base_iter_block() == 1 && hw_cfg_.hw() == ngen::HW::XeHPG && !m_dim().pref_tg_block(); if (!m_dim().pref_tg_block()) m_dim().set_max_dim(tile_level_t::tg, small_m_tg ? 1 : 4); bn_blk = hw_cfg_.vec_size(); k_blk = compute_mad_k_block(); if (!allow_k_grid_slicing_ && !allow_k_tg_slicing_) { do { int est_bmn_threads = 1; est_bmn_threads *= utils::div_up(m_dim().size(), m_blk); est_bmn_threads *= utils::div_up(bn_dim.size(), bn_blk); if (est_bmn_threads >= eu_thr_mul * hw_cfg_.eu_count()) break; m_blk /= 2; m_inst_blk = std::min(m_inst_blk, m_blk); } while (m_blk > 1); } break; } case fma_kind_t::dp4a: case fma_kind_t::dpas: case fma_kind_t::dpasw: ir_assert(vectorize_by_n()) << "dpas can support N vectorization only."; m_inst_blk = 8; bn_inst_blk = 8; k_inst_blk = is_x8x8s32() ? 32 : 16; m_blk = (reduce_m_block ? 16 : 32); bn_blk = is_ge_hpc ? 64 : 32; k_blk = k_inst_blk; break; default: ir_error_not_expected(); } m_blk = math::lcm(m_blk, m_dim().base_iter_block()); k_blk = math::lcm(k_blk, k_dim().base_iter_block()); bn_blk = math::lcm(bn_blk, bn_dim.base_iter_block()); // Shrink block sizes to leverage is_iter_full_match() when applicable. const char bmnks[] = {'M', 'K', vectorize_by_b() ? 'B' : 'N'}; int *blocks[] = {&m_blk, &k_blk, &bn_blk}; int inst_blocks[] = {m_inst_blk, k_inst_blk, bn_inst_blk}; for (int i = 0; i < 3; i++) { int max_iter_dim = prb_max_dim(bmnks[i], tile_level_t::iter); int base_blk = bmnk_dim(bmnks[i]).base_iter_block(); int &blk = *blocks[i]; int inst_blk = inst_blocks[i]; if (max_iter_dim % base_blk == 0 && max_iter_dim % inst_blk == 0) { blk = std::min(blk, max_iter_dim); } ir_assert(blk % inst_blk == 0); } // Pad base iteration blocks according to instruction blocks. for (char bmnk : {'B', 'M', 'N', 'K'}) { bool is_bn = utils::one_of(bmnk, 'B', 'N'); auto &d = bmnk_dim(bmnk); if (is_bn && !vectorize_by_bmnk(bmnk)) continue; int blk = d.base_iter_block(); int inst_blk = is_bn ? bn_inst_blk : (bmnk == 'M') ? m_inst_blk : k_inst_blk; d.set_base_iter_block(math::lcm(blk, inst_blk)); } m_blk = compute_block(m_dim().size(), m_blk, m_dim().base_iter_block()); k_blk = compute_block(k_dim().size(), k_blk, k_dim().base_iter_block()); bn_blk = compute_block(bn_dim.size(), bn_blk, bn_dim.base_iter_block()); #ifdef GEN_CONV_DEBUG m_blk = getenv_int("m_iter_blk", m_blk); k_blk = getenv_int("k_iter_blk", k_blk); bn_blk = getenv_int("bn_iter_blk", bn_blk); if (vectorize_by_b()) { bn_blk = getenv_int("b_iter_blk", bn_blk); } else { bn_blk = getenv_int("n_iter_blk", bn_blk); } #endif m_dim().set_iter_dim(m_blk); bn_dim.set_iter_dim(bn_blk); k_dim().set_iter_dim(k_blk); init_k_blocking(); for (char bmnk : {'B', 'M', 'N', 'K'}) { auto &d = bmnk_dim(bmnk); ir_assert(d.iter_dim() % d.base_iter_block() == 0 || d.base_iter_block() % d.iter_dim() == 0); } // Set thread group blocks. bool with_k_tg_slicing = (k_dim().tg_dim() > 1); if (!with_k_tg_slicing) { int target_tg_size = hw_cfg_.max_tg_size(); int est_threads = 1; for (char bmnk : {'B', 'M', 'N'}) est_threads *= bmnk_dim(bmnk).grid_dim(); if (est_threads < 2 * hw_cfg_.eu_count() || hw_cfg_.hw() >= ngen::HW::XeHPC) { target_tg_size = std::min(target_tg_size, 16); } // Compute max thread group blocks, independently for each dimension. std::vector<char> tg_bmnks = {vectorize_by_b() ? 'B' : 'N', 'M'}; std::vector<int> tg_dims(tg_bmnks.size(), 1); bool any_pref_dim = false; int *split_dim_idx; for (size_t i = 0; i < tg_bmnks.size(); i++) { auto &d = bmnk_dim(tg_bmnks[i]); int i_max_tg_dim = min(target_tg_size, d.max_dim(tile_level_t::tg)); int target_blk = i_max_tg_dim * d.iter_dim(); int tg_dim = compute_block(d.size(), target_blk, d.iter_dim()) / d.iter_dim(); //restrict maximum single tg dim as max_tg size is reduced tg_dim = std::min(utils::rnd_down_pow2(tg_dim), target_tg_size / 4); tg_dims[i] = tg_dim; if (d.pref_tg_block()) { //only one preferred dim allowed assert(!any_pref_dim); any_pref_dim = true; } else { split_dim_idx = &tg_dims.at(i); } } auto total_tg_dim = [&]() { return std::accumulate( tg_dims.begin(), tg_dims.end(), 1, std::multiplies<int>()); }; auto max_tg_dim = [&]() -> int & { if (any_pref_dim && *split_dim_idx > 1) return *split_dim_idx; return *std::max_element(tg_dims.begin(), tg_dims.end()); }; // Reduce thread group size until it fits the target size. while (total_tg_dim() > target_tg_size) { max_tg_dim() /= 2; } for (size_t i = 0; i < tg_bmnks.size(); i++) { auto &d = bmnk_dim(tg_bmnks[i]); d.set_tg_dim(tg_dims[i]); } } } void block_helper_t::init_k_blocking() { // Thread and thread group dims must not be set yet. for (char bmnk : {'B', 'M', 'N', 'K'}) { auto &d = bmnk_dim(bmnk); ir_assert(d.thr_dim() == 1); ir_assert(d.tg_dim() == 1); } if (allow_k_grid_slicing_) { int est_threads = 1; for (char bmnk : {'B', 'M', 'N', 'K'}) est_threads *= bmnk_dim(bmnk).grid_dim(); int def_k_thr_dim = utils::div_up(est_threads, 2 * hw_cfg_.eu_count()); def_k_thr_dim = std::min(100, def_k_thr_dim); def_k_thr_dim = std::max(1, def_k_thr_dim); int k_thr_dim = def_k_thr_dim; #ifdef GEN_CONV_DEBUG k_thr_dim = getenv_int("k_thr_dim", k_thr_dim); #endif k_dim().set_thr_dim(k_thr_dim); return; } if (!enable_k_tg_slicing()) { k_dim().set_thr_dim(dim_value_t::unlimited()); return; } int k_nblks = utils::div_up( prb_blocked_dim('K').size(), k_dim().base_iter_block()); int tg_dim0 = min(hw_cfg_.max_tg_size(), k_dim().max_dim(tile_level_t::tg)); for (int tg_dim = tg_dim0; tg_dim >= 1; tg_dim /= 2) { if (k_nblks % tg_dim == 0) { k_dim().set_thr_dim(k_nblks / tg_dim); k_dim().set_tg_dim(tg_dim); return; } } // Couldn't enable TG slicing. k_dim().set_thr_dim(dim_value_t::unlimited()); } bool block_helper_t::enable_k_tg_slicing() const { #ifdef GEN_CONV_DEBUG int env_value = getenv_int("enable_k_tg_slicing", -1); if (env_value != -1) return (bool)env_value; #endif if (!allow_k_tg_slicing_) return false; if (m_dim().iter_dim() > 16) return false; // TG slicing is supported only when there is only one k dimension. if (prb_blocked_ndims('K') > 1) return false; // Do not enable TG slicing if there are enough non-K threads. int non_k_threads = 1; for (char bmnk : {'B', 'M', 'N'}) { auto &d = bmnk_dim(bmnk); non_k_threads *= d.grid_dim() * d.tg_dim(); } if (non_k_threads >= hw_cfg_.eu_count()) return false; // Do not enable TG slicing if reduction is small. int k_nblks = utils::div_up(k_dim().size(), k_dim().base_iter_block()); if (k_nblks < 16) return false; return true; } void block_helper_t::init_prb_blocks() { // Pad sizes to base block multiples. for (auto &kv : dims_) { auto &d = kv.second; d.set_size(utils::rnd_up(d.size(), d.base_iter_block())); } // Filter blocked dimensions and sort them according to their keys. std::vector<dim_info_t *> sorted_dims; for (auto &kv : dims_) { auto &d = kv.second; if (!d.is_blocked()) continue; sorted_dims.push_back(&d); } std::sort(sorted_dims.begin(), sorted_dims.end(), [](const dim_info_t *a, const dim_info_t *b) { if (a->order_key() == b->order_key()) { return a->name().compare(b->name()) < 0; } return a->order_key() < b->order_key(); }); for (char bmnk : {'B', 'N', 'M', 'K'}) { std::vector<dim_info_t *> cur_dims; for (auto *d : sorted_dims) { if (d->bmnk() != bmnk) continue; cur_dims.push_back(d); } ir_assert(!cur_dims.empty()); // Pad dimensions according to BMNK base block requirements. int max_iter_dim = prb_max_dim(bmnk, tile_level_t::iter); int base_blk = bmnk_dim(bmnk).base_iter_block(); if (max_iter_dim == 1 && base_blk > 1) { ir_assert(cur_dims[0]->base_iter_block() == 1); cur_dims[0]->set_size(base_blk); } block_assigner_t assigner(bmnk_dim(bmnk), cur_dims); while (assigner.has_blocks()) { assigner.assign_block(); } } } int block_helper_t::compute_mad_k_block() const { int k_base_blk = k_dim().base_iter_block(); if (k_base_blk >= 16) return k_base_blk; bool is_fused = true; int k_blocked_size = 1; for (auto &kv : dims_) { auto &d = kv.second; if (!d.is_blocked()) continue; if (d.bmnk() != 'K') continue; k_blocked_size *= d.size(); if (!d.allow_fuse()) is_fused = false; } if (!is_fused) return 16; int max_k_blk = 32; if ((k_blocked_size <= max_k_blk) && (k_blocked_size % k_dim().base_iter_block() == 0)) return k_blocked_size; return 16; } } // namespace jit } // namespace gpu } // namespace impl } // namespace dnnl
35.189706
80
0.54971
[ "vector" ]
b8ae51bf642ce0a75ea8cfe024ead1b95dd47c56
400
hpp
C++
lumino/LuminoEngine/include/LuminoEngine/Scene/MeshTilemap/MeshTileset.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
113
2020-03-05T01:27:59.000Z
2022-03-28T13:20:51.000Z
lumino/LuminoEngine/include/LuminoEngine/Scene/MeshTilemap/MeshTileset.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
35
2016-04-18T06:14:08.000Z
2020-02-09T15:51:58.000Z
lumino/LuminoEngine/include/LuminoEngine/Scene/MeshTilemap/MeshTileset.hpp
GameDevery/Lumino
abce2ddca4b7678b04dbfd0ae5348e196c3c9379
[ "MIT" ]
12
2020-12-21T12:03:59.000Z
2021-12-15T02:07:49.000Z
 #pragma once #include "Common.hpp" namespace ln { enum class PredefinedMeshAutoTilesetMesh { Uniform, // 全面均一 Wall, // 壁 }; class MeshAutoTileset : public Object { public: LN_CONSTRUCT_ACCESS: MeshAutoTileset(); bool init(); private: }; class MeshTileset : public Object { LN_OBJECT; public: LN_CONSTRUCT_ACCESS: MeshTileset(); bool init(); private: }; } // namespace ln
10.25641
40
0.6925
[ "object" ]
b8b1bbad090ae0fa735b154df1b30c132b71063d
5,614
cc
C++
src/metrics.cc
Coloquinte/minipart2
00b864bd21fab4909984aa6f5c07cae61d2c2c0a
[ "MIT" ]
1
2020-06-14T16:51:26.000Z
2020-06-14T16:51:26.000Z
src/metrics.cc
Coloquinte/minipart2
00b864bd21fab4909984aa6f5c07cae61d2c2c0a
[ "MIT" ]
null
null
null
src/metrics.cc
Coloquinte/minipart2
00b864bd21fab4909984aa6f5c07cae61d2c2c0a
[ "MIT" ]
null
null
null
// Copyright (C) 2019 Gabriel Gouvine - All Rights Reserved #include "hypergraph.hh" #include <cassert> #include <algorithm> #include <stdexcept> #include <unordered_set> #include <unordered_map> #include <cmath> using namespace std; namespace minipart { Index Hypergraph::metricsCut(const Solution &solution) const { assert (solution.nNodes() == nNodes()); assert (solution.nParts() == nParts()); assert (nHedgeWeights() == 1); Index ret = 0; for (Index hedge = 0; hedge < nHedges(); ++hedge) { if (cut(solution, hedge)) ret += hedgeWeight(hedge); } return ret; } Index Hypergraph::metricsSoed(const Solution &solution) const { assert (solution.nNodes() == nNodes()); assert (solution.nParts() == nParts()); assert (nHedgeWeights() == 1); Index ret = 0; for (Index hedge = 0; hedge < nHedges(); ++hedge) { ret += hedgeWeight(hedge) * degree(solution, hedge); } return ret; } Index Hypergraph::metricsConnectivity(const Solution &solution) const { assert (solution.nNodes() == nNodes()); assert (solution.nParts() == nParts()); assert (nHedgeWeights() == 1); Index ret = 0; for (Index hedge = 0; hedge < nHedges(); ++hedge) { ret += hedgeWeight(hedge) * (degree(solution, hedge) - 1); } return ret; } Index Hypergraph::metricsDaisyChainDistance(const Solution &solution) const { assert (solution.nNodes() == nNodes()); assert (solution.nParts() == nParts()); assert (nHedgeWeights() == 1); Index ret = 0; for (Index hedge = 0; hedge < nHedges(); ++hedge) { Index minPart = nParts() - 1; Index maxPart = 0; for (Index node : hedgeNodes(hedge)) { minPart = min(minPart, solution[node]); maxPart = max(maxPart, solution[node]); } if (minPart >= maxPart) continue; ret += hedgeWeight(hedge) * (maxPart - minPart); } return ret; } Index Hypergraph::metricsSumOverflow(const Solution &solution) const { assert (solution.nNodes() == nNodes()); assert (solution.nParts() == nParts()); assert (nNodeWeights() == 1); vector<Index> usage = metricsPartitionUsage(solution); Index ret = 0; for (int i = 0; i < nParts(); ++i) { Index ovf = usage[i] - partData_[i]; if (ovf > 0) ret += ovf; } return ret; } Index Hypergraph::metricsMaxDegree(const Solution &solution) const { vector<Index> degree = metricsPartitionDegree(solution); return *max_element(degree.begin(), degree.end()); } Index Hypergraph::metricsDaisyChainMaxDegree(const Solution &solution) const { vector<Index> degree = metricsPartitionDaisyChainDegree(solution); return *max_element(degree.begin(), degree.end()); } double Hypergraph::metricsRatioPenalty(const Solution &solution) const { vector<Index> partitionUsage = metricsPartitionUsage(solution); Index sumUsage = 0; for (Index d : partitionUsage) sumUsage += d; double normalizedUsage = ((double) sumUsage) / partitionUsage.size(); double productUsage = 1.0; for (Index d : partitionUsage) { productUsage *= (d / normalizedUsage); } // Geomean squared return 1.0 / pow(productUsage, 2.0 / partitionUsage.size()); } Index Hypergraph::metricsEmptyPartitions(const Solution &solution) const { vector<Index> partitionUsage = metricsPartitionUsage(solution); Index count = 0; for (Index d : partitionUsage) { if (d == 0) count++; } return count; } double Hypergraph::metricsRatioCut(const Solution &solution) const { return metricsCut(solution) * metricsRatioPenalty(solution); } double Hypergraph::metricsRatioSoed(const Solution &solution) const { return metricsSoed(solution) * metricsRatioPenalty(solution); } double Hypergraph::metricsRatioConnectivity(const Solution &solution) const { return metricsConnectivity(solution) * metricsRatioPenalty(solution); } double Hypergraph::metricsRatioMaxDegree(const Solution &solution) const { return metricsMaxDegree(solution) * metricsRatioPenalty(solution); } std::vector<Index> Hypergraph::metricsPartitionUsage(const Solution &solution) const { assert (solution.nNodes() == nNodes()); assert (solution.nParts() == nParts()); vector<Index> usage(nParts(), 0); for (int i = 0; i < nNodes(); ++i) { assert (solution[i] >= 0 && solution[i] < nParts()); usage[solution[i]] += nodeWeight(i); } return usage; } std::vector<Index> Hypergraph::metricsPartitionDegree(const Solution &solution) const { assert (solution.nNodes() == nNodes()); assert (solution.nParts() == nParts()); assert (nHedgeWeights() == 1); vector<Index> degree(nParts(), 0); unordered_set<Index> parts; for (int i = 0; i < nHedges(); ++i) { parts.clear(); for (Index node : hedgeNodes(i)) { parts.insert(solution[node]); } if (parts.size() > 1) { for (Index p : parts) { degree[p] += hedgeWeight(i); } } } return degree; } std::vector<Index> Hypergraph::metricsPartitionDaisyChainDegree(const Solution &solution) const { assert (solution.nNodes() == nNodes()); assert (solution.nParts() == nParts()); assert (nHedgeWeights() == 1); vector<Index> degree(nParts(), 0); unordered_set<Index> parts; for (int i = 0; i < nHedges(); ++i) { Index minPart = nParts() - 1; Index maxPart = 0; for (Index node : hedgeNodes(i)) { minPart = min(minPart, solution[node]); maxPart = max(maxPart, solution[node]); } if (minPart >= maxPart) continue; // Count twice for middle partitions for (Index p = minPart; p < maxPart; ++p) { degree[p] += hedgeWeight(i); degree[p+1] += hedgeWeight(i); } } return degree; } } // End namespace minipart
30.02139
97
0.668151
[ "vector" ]
b8b232f1a9d42277b7d8b0c1050533e2cf8e9cf9
1,757
cpp
C++
plugins/robots/common/twoDModel/src/engine/commands/createRemoveSensorImplementation.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
6
2017-07-03T13:55:35.000Z
2018-11-28T03:39:51.000Z
plugins/robots/common/twoDModel/src/engine/commands/createRemoveSensorImplementation.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
27
2017-06-29T09:36:37.000Z
2017-11-25T14:50:04.000Z
plugins/robots/common/twoDModel/src/engine/commands/createRemoveSensorImplementation.cpp
RexTremendaeMajestatis/QREAL
94786d40e84c18a4407069570588f7d2c4c63aea
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "createRemoveSensorImplementation.h" #include "twoDModel/engine/model/sensorsConfiguration.h" using namespace twoDModel; using namespace commands; CreateRemoveSensorImplementation::CreateRemoveSensorImplementation(model::SensorsConfiguration &configurator , const QString &robotModel , const kitBase::robotModel::PortInfo &port , const kitBase::robotModel::DeviceInfo &device , const QPointF &position , const qreal direction) : mConfigurator(configurator) , mRobotModel(robotModel) , mPort(port) , mDevice(device) , mPosition(position) , mDirection(direction) { connectDevicesConfigurationProvider(&mConfigurator); } void CreateRemoveSensorImplementation::create() { deviceConfigurationChanged(mRobotModel, mPort, mDevice, Reason::userAction); mConfigurator.setPosition(mPort, mPosition); mConfigurator.setDirection(mPort, mDirection); } void CreateRemoveSensorImplementation::remove() { mDevice = mConfigurator.type(mPort); mPosition = mConfigurator.position(mPort); mDirection = mConfigurator.direction(mPort); deviceConfigurationChanged(mRobotModel, mPort, kitBase::robotModel::DeviceInfo(), Reason::userAction); }
33.788462
108
0.783722
[ "model" ]
b8b31d853cf96793edb365d5dbdb8fc42626a69e
2,255
hpp
C++
Source/include/ezvcard/parameter/vcard_parameter.hpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
5
2019-10-30T06:10:10.000Z
2020-04-25T16:52:06.000Z
Source/include/ezvcard/parameter/vcard_parameter.hpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
null
null
null
Source/include/ezvcard/parameter/vcard_parameter.hpp
ProtonMail/cpp-openpgp
b47316c51357b8d15eb3bcc376ea5e59a6a9a108
[ "MIT" ]
2
2019-11-27T23:47:54.000Z
2020-01-13T16:36:03.000Z
// // vcard_parameter.hpp // OpenPGP // // Created by Yanfeng Zhang on 12/2/16. // // The MIT License // // Copyright (c) 2019 Proton Technologies AG // // 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. #ifndef vcard_parameter_hpp #define vcard_parameter_hpp #include <iostream> #include <string> #include <vector> #include "object_base.hpp" #include "vcard_version.hpp" class VCardParameter : public PMObject { protected: std::string _value; VCardParameter(const std::string& value, std::vector<VCardVersion::Ptr> support, bool preserveCase); std::vector<VCardVersion::Ptr> _supportedVersions; std::string _className() { return "VCardParameter"; } public: typedef std::shared_ptr<VCardParameter> Ptr; VCardParameter(const std::string& value, std::vector<VCardVersion::Ptr> support); ~VCardParameter(); std::string getValue(); std::vector<VCardVersion::Ptr> getSupportedVersions(); bool isSupportedBy(const VCardVersion::Ptr& version); //std::string toString(); bool equals(const VCardParameter::Ptr & rhs); }; bool operator==(const VCardParameter::Ptr& lhs, const VCardParameter::Ptr& rhs) ; #endif /* vcard_parameter_hpp */
34.166667
104
0.728603
[ "vector" ]
b8b34ceb6f988044f6b03c434c01d69bf7f42209
2,417
cpp
C++
Polygon_mesh_processing/test/Polygon_mesh_processing/remeshing_test_P_SM_OM.cpp
brucerennie/cgal
314b94aafa9b08a1d086accd2cadff1aae1b57a9
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Polygon_mesh_processing/test/Polygon_mesh_processing/remeshing_test_P_SM_OM.cpp
brucerennie/cgal
314b94aafa9b08a1d086accd2cadff1aae1b57a9
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Polygon_mesh_processing/test/Polygon_mesh_processing/remeshing_test_P_SM_OM.cpp
brucerennie/cgal
314b94aafa9b08a1d086accd2cadff1aae1b57a9
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Surface_mesh.h> #include <CGAL/Polyhedron_3.h> #include <fstream> #include <map> #include <OpenMesh/Core/IO/MeshIO.hh> #include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh> #include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh> #include <CGAL/boost/graph/graph_traits_PolyMesh_ArrayKernelT.h> #include <CGAL/boost/graph/graph_traits_TriMesh_ArrayKernelT.h> #include <CGAL/Polygon_mesh_processing/remesh.h> namespace PMP = CGAL::Polygon_mesh_processing; typedef CGAL::Exact_predicates_inexact_constructions_kernel Epic; int main() { { typedef CGAL::Surface_mesh<Epic::Point_3> SM; SM sm; std::ifstream in(CGAL::data_file_path("meshes/elephant.off")); in >> sm; PMP::isotropic_remeshing(faces(sm), 0.02, sm); std::ofstream out("sm.off"); out << sm << std::endl; } { typedef CGAL::Polyhedron_3<Epic> P; std::ifstream in(CGAL::data_file_path("meshes/elephant.off")); P p; in >> p; std::map<boost::graph_traits<P>::face_descriptor, std::size_t> fim; std::size_t fid = 0; for(const boost::graph_traits<P>::face_descriptor f : faces(p)) fim[f] = fid++; PMP::isotropic_remeshing(faces(p), 0.02, p, PMP::parameters::face_index_map(boost::make_assoc_property_map(fim))); std::ofstream out("p.off"); out << p << std::endl; } { typedef OpenMesh::PolyMesh_ArrayKernelT</* MyTraits*/> OM; OM om; OpenMesh::IO::read_mesh(om, CGAL::data_file_path("meshes/elephant.off")); om.request_face_status(); om.request_edge_status(); om.request_vertex_status(); PMP::isotropic_remeshing(faces(om), 0.02, om); om.garbage_collection(); OpenMesh::IO::write_mesh(om, "pm.off"); } { typedef OpenMesh::TriMesh_ArrayKernelT</* MyTraits*/> OM; OM om; OpenMesh::IO::read_mesh(om, CGAL::data_file_path("meshes/elephant.off")); om.request_face_status(); om.request_edge_status(); om.request_vertex_status(); PMP::isotropic_remeshing(faces(om), 0.02, om); om.garbage_collection(); OpenMesh::IO::write_mesh(om, "tm.off"); } return 0; }
27.781609
99
0.617708
[ "mesh" ]
b8b4a666393e9e311b18bbb0eb6947ec52382267
1,181
cpp
C++
51-lbs/lbs.cpp
wlep/cp-course
9e52788e8f6a76752149b74d06d0272e16c3b528
[ "MIT" ]
null
null
null
51-lbs/lbs.cpp
wlep/cp-course
9e52788e8f6a76752149b74d06d0272e16c3b528
[ "MIT" ]
null
null
null
51-lbs/lbs.cpp
wlep/cp-course
9e52788e8f6a76752149b74d06d0272e16c3b528
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int lis(vector<int> numbers, vector<int> * M, int n) { if (n == 0) return 0; int m = -1; for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) if (numbers[j] < numbers[i]) M->at(i) = max(M->at(i), 1 + M->at(j)); m = max(m, M->at(i)); } return m; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); vector<int> inc (n,1); lis(numbers, &inc, n); reverse(numbers.begin(), numbers.end()); vector<int> dec (n,1); lis(numbers, &dec, n); int max = -1; for (int i = 0; i < n; ++i) if (max < inc[i]+dec[n-i-1]-1) max = inc[i]+dec[n-i-1]-1; cout << max << endl; } return 0; }
19.683333
57
0.45724
[ "vector" ]
b8b66589122a4599cf200bc1501f90d3ba3046e8
3,192
hpp
C++
JEBMath/JEBMath/Math/Primes.hpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
1
2019-12-25T05:30:20.000Z
2019-12-25T05:30:20.000Z
JEBMath/JEBMath/Math/Primes.hpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
null
null
null
JEBMath/JEBMath/Math/Primes.hpp
jebreimo/JEBLib
9066403a9372951aa8ce4f129cd4877e2ae779ab
[ "BSD-3-Clause" ]
null
null
null
#ifndef JEB_MATH_PRIMES_HPP #define JEB_MATH_PRIMES_HPP #include <vector> #include "JEBMath/JEBMathDefinitions.hpp" namespace JEBMath { template <typename T> bool isPrime(T n) { if (n <= 1) return false; else if (n <= 3) return true; else if (n % 2 == 0) return false; T factor = 3; while (true) { if (n % factor == 0) return false; else if (n / factor <= factor) return true; factor += 2; } } template <typename T> T nextPrime(T prevPrime = 0) { if (prevPrime < 2) return 2; else if (prevPrime == 2) return 3; T prime = (prevPrime & 1) ? prevPrime + 2 : prevPrime + 1; if (prime % 3 == 0) prime += 2; T increment = (prime + 1) % 3 ? 4 : 2; while (!isPrime(prime)) { prime += increment; increment = 6 - increment; } return prime; } /** @brief Returns the nth prime where @a n is one-based. */ template <typename T> T nthPrime(T n) { T prime = 0; for (T i = 0; i < n; i++) prime = nextPrime(prime); return prime; } /** @brief Returns @a count primes starting with the @a nth prime. */ template <typename T> std::vector<T> computePrimes(T nth, T count) { std::vector<T> primes; if (count > 0) { primes.push_back(nthPrime(nth)); for (T i = 1; i < count; i++) primes.push_back(nextPrime(primes.back())); } return primes; } template <typename T> T firstFactor(T n, T minFactor = 2) { if (n < 0) return -1; else if (n <= 3) return n; if (minFactor < 2) minFactor = 2; if (n % minFactor == 0) return minFactor; minFactor |= 1; // Make sure minFactor is odd. while (true) { if (n % minFactor == 0) return minFactor; else if (n / minFactor <= minFactor) return n; minFactor += 2; } } template <typename T> class Factorizer { public: Factorizer(T value) : m_Value(value), m_Factor(0), m_Increment(2) { } T next() { if (m_Factor < 5) { if (m_Value < 0) { m_Value = -m_Value; m_Factor = (T)-1; return (T)-1; } else if (m_Value % 2 == 0) { m_Value /= 2; m_Factor = 2; return 2; } else if (m_Value % 3 == 0) { m_Value /= 3; m_Factor = 3; return 3; } m_Factor = 5; } while (m_Value % m_Factor != 0) { if (m_Value / m_Factor <= m_Factor) { m_Factor = m_Value; break; } m_Factor += m_Increment; m_Increment = 6 - m_Increment; } m_Value /= m_Factor; return m_Factor; } T currentFactor() const { return m_Factor; } T remainder() const { return m_Value; } private: T m_Value; T m_Factor; T m_Increment; }; } #endif
19.345455
66
0.470865
[ "vector" ]
b8c1b627cb4173c95c15a1914a32f2c39f7bae53
1,308
cpp
C++
ext/libigl/tutorial/708_Picking/main.cpp
liminchen/OptCuts
cb85b06ece3a6d1279863e26b5fd17a5abb0834d
[ "MIT" ]
187
2019-01-23T04:07:11.000Z
2022-03-27T03:44:58.000Z
ext/libigl/tutorial/708_Picking/main.cpp
xiaoxie5002/OptCuts
1f4168fc867f47face85fcfa3a572be98232786f
[ "MIT" ]
8
2019-03-22T13:27:38.000Z
2020-06-18T13:23:23.000Z
ext/libigl/tutorial/708_Picking/main.cpp
xiaoxie5002/OptCuts
1f4168fc867f47face85fcfa3a572be98232786f
[ "MIT" ]
34
2019-02-13T01:11:12.000Z
2022-02-28T03:29:40.000Z
#include "tutorial_shared_path.h" #include <igl/readOFF.h> #include <igl/unproject_onto_mesh.h> #include <igl/opengl/glfw/Viewer.h> #include <iostream> int main(int argc, char *argv[]) { // Mesh with per-face color Eigen::MatrixXd V, C; Eigen::MatrixXi F; // Load a mesh in OFF format igl::readOFF(TUTORIAL_SHARED_PATH "/fertility.off", V, F); // Initialize white C = Eigen::MatrixXd::Constant(F.rows(),3,1); igl::opengl::glfw::Viewer viewer; viewer.callback_mouse_down = [&V,&F,&C](igl::opengl::glfw::Viewer& viewer, int, int)->bool { int fid; Eigen::Vector3f bc; // Cast a ray in the view direction starting from the mouse position double x = viewer.current_mouse_x; double y = viewer.core.viewport(3) - viewer.current_mouse_y; if(igl::unproject_onto_mesh(Eigen::Vector2f(x,y), viewer.core.view * viewer.core.model, viewer.core.proj, viewer.core.viewport, V, F, fid, bc)) { // paint hit red C.row(fid)<<1,0,0; viewer.data().set_colors(C); return true; } return false; }; std::cout<<R"(Usage: [click] Pick face on shape )"; // Show mesh viewer.data().set_mesh(V, F); viewer.data().set_colors(C); viewer.data().show_lines = false; viewer.launch(); }
27.829787
92
0.629969
[ "mesh", "shape", "model" ]
fef610e9a0313b0df6e0998f4ebaf5e171349709
35,143
cpp
C++
code/olcSimpleEngine.cpp
solmazumut/Star-Wars-Game
439cc71756de49f7d9ef6e99df68eca412abc6b0
[ "MIT" ]
null
null
null
code/olcSimpleEngine.cpp
solmazumut/Star-Wars-Game
439cc71756de49f7d9ef6e99df68eca412abc6b0
[ "MIT" ]
null
null
null
code/olcSimpleEngine.cpp
solmazumut/Star-Wars-Game
439cc71756de49f7d9ef6e99df68eca412abc6b0
[ "MIT" ]
null
null
null
/* Object Oriented Mode ~~~~~~~~~~~~~~~~~~~~ If the olcPixelGameEngine.h is called from several sources it can cause multiple definitions of objects. To prevent this, ONLY ONE of the pathways to including this file must have OLC_PGE_APPLICATION defined before it. This prevents the definitions being duplicated. Consider the following project structure: Class1.h - Includes olcPixelGameEngine.h, overrides olc::PixelGameEngine Class1.cpp - #define OLC_PGE_APPLICATION #include "Class1.h" Class2.h - Includes Class1.h, which includes olcPixelGameEngine.h Class2.cpp - #define OLC_PGE_APPLICATION #include "Class2.h" main.cpp - Includes Class1.h and Class2.h If all of this is a bit too confusing, you can split this file in two! Everything below this comment block can go into olcPixelGameEngineOOP.cpp and everything above it can go into olcPixelGameEngineOOP.h */ #include "olcSimpleEngine.h" namespace olc { // User must override these functions as required. I have not made // them abstract because I do need a default behaviour to occur if // they are not overwritten bool PixelGameEngine::OnUserCreate() { return false; } bool PixelGameEngine::OnUserUpdate(float fElapsedTime) { return false; } bool PixelGameEngine::OnUserDestroy() { return true; } std::map<uint16_t, uint8_t> PixelGameEngine::mapKeys; olc::PixelGameEngine* olc::PGEX::pge = nullptr; //============================================================= #pragma region GameEngine //========================================================== std::string PixelGameEngine::to_string_with_precision(float a_value, int n) { std::ostringstream out; out.precision(n); out << std::fixed << a_value; return out.str(); } PixelGameEngine::PixelGameEngine() { sAppName = "Undefined"; olc::PGEX::pge = this; } olc::rcode PixelGameEngine::Construct(uint32_t screen_w, uint32_t screen_h, uint32_t pixel_w, uint32_t pixel_h) { nScreenWidth = screen_w; nScreenHeight = screen_h; nPixelWidth = pixel_w; nPixelHeight = pixel_h; fPixelX = 2.0f / (float)(nScreenWidth); fPixelY = 2.0f / (float)(nScreenHeight); if (nPixelWidth == 0 || nPixelHeight == 0 || nScreenWidth == 0 || nScreenHeight == 0) return olc::FAIL; // Load the default font sheet olc_ConstructFontSheet(); // Create a sprite that represents the primary drawing target pDefaultDrawTarget = new Sprite(nScreenWidth, nScreenHeight); SetDrawTarget(nullptr); return olc::OK; } olc::rcode PixelGameEngine::Start() { // Construct the window if (!olc_WindowCreate()) return olc::FAIL; // Load libraries required for PNG file interaction // Windows use GDI+ Gdiplus::GdiplusStartupInput startupInput; ULONG_PTR token; Gdiplus::GdiplusStartup(&token, &startupInput, NULL); // Start the thread bAtomActive = true; std::thread t = std::thread(&PixelGameEngine::EngineThread, this); //EngineThread(); // Handle Windows Message Loop MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } // Wait for thread to be exited t.join(); return olc::OK; } void PixelGameEngine::SetDrawTarget(Sprite *target) { if (target) pDrawTarget = target; else pDrawTarget = pDefaultDrawTarget; } Sprite* PixelGameEngine::GetDrawTarget() { return pDrawTarget; } int32_t PixelGameEngine::GetDrawTargetWidth() { if (pDrawTarget) return pDrawTarget->width; else return 0; } int32_t PixelGameEngine::GetDrawTargetHeight() { if (pDrawTarget) return pDrawTarget->height; else return 0; } bool PixelGameEngine::IsFocused() { return bHasInputFocus; } HWButton PixelGameEngine::GetKey(Key k) { return pKeyboardState[k]; } HWButton PixelGameEngine::GetMouse(uint32_t b) { return pMouseState[b]; } int32_t PixelGameEngine::GetMouseX() { return nMousePosX; } int32_t PixelGameEngine::GetMouseY() { return nMousePosY; } int32_t PixelGameEngine::ScreenWidth() { return nScreenWidth; } int32_t PixelGameEngine::ScreenHeight() { return nScreenHeight; } void PixelGameEngine::Draw(int32_t x, int32_t y, Pixel p) { if (!pDrawTarget) return; if (nPixelMode == Pixel::NORMAL) { pDrawTarget->SetPixel(x, y, p); return; } if (nPixelMode == Pixel::MASK) { if (p.a == 255) pDrawTarget->SetPixel(x, y, p); return; } if (nPixelMode == Pixel::ALPHA) { Pixel d = pDrawTarget->GetPixel(x, y); float a = (float)(p.a / 255.0f) * fBlendFactor; float c = 1.0f - a; float r = a * (float)p.r + c * (float)d.r; float g = a * (float)p.g + c * (float)d.g; float b = a * (float)p.b + c * (float)d.b; pDrawTarget->SetPixel(x, y, Pixel((uint8_t)r, (uint8_t)g, (uint8_t)b)); return; } if (nPixelMode == Pixel::CUSTOM) { pDrawTarget->SetPixel(x, y, funcPixelMode(x, y, p, pDrawTarget->GetPixel(x, y))); return; } } void PixelGameEngine::SetSubPixelOffset(float ox, float oy) { fSubPixelOffsetX = ox * fPixelX; fSubPixelOffsetY = oy * fPixelY; } void PixelGameEngine::DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p) { int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i; dx = x2 - x1; dy = y2 - y1; // straight lines idea by gurkanctn if (dx == 0) // Line is vertical { if (y2 < y1) std::swap(y1, y2); for (y = y1; y <= y2; y++) Draw(x1, y, p); return; } if (dy == 0) // Line is horizontal { if (x2 < x1) std::swap(x1, x2); for (x = x1; x <= x2; x++) Draw(x, y1, p); return; } // Line is Funk-aye dx1 = abs(dx); dy1 = abs(dy); px = 2 * dy1 - dx1; py = 2 * dx1 - dy1; if (dy1 <= dx1) { if (dx >= 0) { x = x1; y = y1; xe = x2; } else { x = x2; y = y2; xe = x1; } Draw(x, y, p); for (i = 0; x<xe; i++) { x = x + 1; if (px<0) px = px + 2 * dy1; else { if ((dx<0 && dy<0) || (dx>0 && dy>0)) y = y + 1; else y = y - 1; px = px + 2 * (dy1 - dx1); } Draw(x, y, p); } } else { if (dy >= 0) { x = x1; y = y1; ye = y2; } else { x = x2; y = y2; ye = y1; } Draw(x, y, p); for (i = 0; y<ye; i++) { y = y + 1; if (py <= 0) py = py + 2 * dx1; else { if ((dx<0 && dy<0) || (dx>0 && dy>0)) x = x + 1; else x = x - 1; py = py + 2 * (dx1 - dy1); } Draw(x, y, p); } } } void PixelGameEngine::DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p) { int x0 = 0; int y0 = radius; int d = 3 - 2 * radius; if (!radius) return; while (y0 >= x0) // only formulate 1/8 of circle { Draw(x - x0, y - y0, p);//upper left left Draw(x - y0, y - x0, p);//upper upper left Draw(x + y0, y - x0, p);//upper upper right Draw(x + x0, y - y0, p);//upper right right Draw(x - x0, y + y0, p);//lower left left Draw(x - y0, y + x0, p);//lower lower left Draw(x + y0, y + x0, p);//lower lower right Draw(x + x0, y + y0, p);//lower right right if (d < 0) d += 4 * x0++ + 6; else d += 4 * (x0++ - y0--) + 10; } } void PixelGameEngine::FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p) { // Taken from wikipedia int x0 = 0; int y0 = radius; int d = 3 - 2 * radius; if (!radius) return; auto drawline = [&](int sx, int ex, int ny) { for (int i = sx; i <= ex; i++) Draw(i, ny, p); }; while (y0 >= x0) { // Modified to draw scan-lines instead of edges drawline(x - x0, x + x0, y - y0); drawline(x - y0, x + y0, y - x0); drawline(x - x0, x + x0, y + y0); drawline(x - y0, x + y0, y + x0); if (d < 0) d += 4 * x0++ + 6; else d += 4 * (x0++ - y0--) + 10; } } void PixelGameEngine::DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p) { DrawLine(x, y, x + w, y, p); DrawLine(x + w, y, x + w, y + h, p); DrawLine(x + w, y + h, x, y + h, p); DrawLine(x, y + h, x, y, p); } void PixelGameEngine::Clear(Pixel p) { int pixels = GetDrawTargetWidth() * GetDrawTargetHeight(); Pixel* m = GetDrawTarget()->GetData(); for (int i = 0; i < pixels; i++) m[i] = p; } void PixelGameEngine::FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p) { int32_t x2 = x + w; int32_t y2 = y + h; if (x < 0) x = 0; if (x >= (int32_t)nScreenWidth) x = (int32_t)nScreenWidth; if (y < 0) y = 0; if (y >= (int32_t)nScreenHeight) y = (int32_t)nScreenHeight; if (x2 < 0) x2 = 0; if (x2 >= (int32_t)nScreenWidth) x2 = (int32_t)nScreenWidth; if (y2 < 0) y2 = 0; if (y2 >= (int32_t)nScreenHeight) y2 = (int32_t)nScreenHeight; for (int i = x; i < x2; i++) for (int j = y; j < y2; j++) Draw(i, j, p); } void PixelGameEngine::DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p) { DrawLine(x1, y1, x2, y2, p); DrawLine(x2, y2, x3, y3, p); DrawLine(x3, y3, x1, y1, p); } // https://www.avrfreaks.net/sites/default/files/triangles.c void PixelGameEngine::FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p) { auto SWAP = [](int &x, int &y) { int t = x; x = y; y = t; }; auto drawline = [&](int sx, int ex, int ny) { for (int i = sx; i <= ex; i++) Draw(i, ny, p); }; int t1x, t2x, y, minx, maxx, t1xp, t2xp; bool changed1 = false; bool changed2 = false; int signx1, signx2, dx1, dy1, dx2, dy2; int e1, e2; // Sort vertices if (y1>y2) { SWAP(y1, y2); SWAP(x1, x2); } if (y1>y3) { SWAP(y1, y3); SWAP(x1, x3); } if (y2>y3) { SWAP(y2, y3); SWAP(x2, x3); } t1x = t2x = x1; y = y1; // Starting points dx1 = (int)(x2 - x1); if (dx1<0) { dx1 = -dx1; signx1 = -1; } else signx1 = 1; dy1 = (int)(y2 - y1); dx2 = (int)(x3 - x1); if (dx2<0) { dx2 = -dx2; signx2 = -1; } else signx2 = 1; dy2 = (int)(y3 - y1); if (dy1 > dx1) { // swap values SWAP(dx1, dy1); changed1 = true; } if (dy2 > dx2) { // swap values SWAP(dy2, dx2); changed2 = true; } e2 = (int)(dx2 >> 1); // Flat top, just process the second half if (y1 == y2) goto next; e1 = (int)(dx1 >> 1); for (int i = 0; i < dx1;) { t1xp = 0; t2xp = 0; if (t1x<t2x) { minx = t1x; maxx = t2x; } else { minx = t2x; maxx = t1x; } // process first line until y value is about to change while (i<dx1) { i++; e1 += dy1; while (e1 >= dx1) { e1 -= dx1; if (changed1) t1xp = signx1;//t1x += signx1; else goto next1; } if (changed1) break; else t1x += signx1; } // Move line next1: // process second line until y value is about to change while (1) { e2 += dy2; while (e2 >= dx2) { e2 -= dx2; if (changed2) t2xp = signx2;//t2x += signx2; else goto next2; } if (changed2) break; else t2x += signx2; } next2: if (minx>t1x) minx = t1x; if (minx>t2x) minx = t2x; if (maxx<t1x) maxx = t1x; if (maxx<t2x) maxx = t2x; drawline(minx, maxx, y); // Draw line from min to max points found on the y // Now increase y if (!changed1) t1x += signx1; t1x += t1xp; if (!changed2) t2x += signx2; t2x += t2xp; y += 1; if (y == y2) break; } next: // Second half dx1 = (int)(x3 - x2); if (dx1<0) { dx1 = -dx1; signx1 = -1; } else signx1 = 1; dy1 = (int)(y3 - y2); t1x = x2; if (dy1 > dx1) { // swap values SWAP(dy1, dx1); changed1 = true; } else changed1 = false; e1 = (int)(dx1 >> 1); for (int i = 0; i <= dx1; i++) { t1xp = 0; t2xp = 0; if (t1x<t2x) { minx = t1x; maxx = t2x; } else { minx = t2x; maxx = t1x; } // process first line until y value is about to change while (i<dx1) { e1 += dy1; while (e1 >= dx1) { e1 -= dx1; if (changed1) { t1xp = signx1; break; }//t1x += signx1; else goto next3; } if (changed1) break; else t1x += signx1; if (i<dx1) i++; } next3: // process second line until y value is about to change while (t2x != x3) { e2 += dy2; while (e2 >= dx2) { e2 -= dx2; if (changed2) t2xp = signx2; else goto next4; } if (changed2) break; else t2x += signx2; } next4: if (minx>t1x) minx = t1x; if (minx>t2x) minx = t2x; if (maxx<t1x) maxx = t1x; if (maxx<t2x) maxx = t2x; drawline(minx, maxx, y); if (!changed1) t1x += signx1; t1x += t1xp; if (!changed2) t2x += signx2; t2x += t2xp; y += 1; if (y>y3) return; } } void PixelGameEngine::DrawSprite(int32_t x, int32_t y, std::shared_ptr <Sprite> sprite, uint32_t scale) { if (sprite == nullptr) return; if (scale > 1) { for (int32_t i = 0; i < sprite->width; i++) for (int32_t j = 0; j < sprite->height; j++) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + (i*scale) + is, y + (j*scale) + js, sprite->GetPixel(i, j)); } else { for (int32_t i = 0; i < sprite->width; i++) for (int32_t j = 0; j < sprite->height; j++) Draw(x + i, y + j, sprite->GetPixel(i, j)); } } void PixelGameEngine::DrawPartialSprite(int32_t x, int32_t y, Sprite *sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale) { if (sprite == nullptr) return; if (scale > 1) { for (int32_t i = 0; i < w; i++) for (int32_t j = 0; j < h; j++) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + (i*scale) + is, y + (j*scale) + js, sprite->GetPixel(i + ox, j + oy)); } else { for (int32_t i = 0; i < w; i++) for (int32_t j = 0; j < h; j++) Draw(x + i, y + j, sprite->GetPixel(i + ox, j + oy)); } } void PixelGameEngine::DrawString(int32_t x, int32_t y, std::string sText, Pixel col, uint32_t scale) { int32_t sx = 0; int32_t sy = 0; Pixel::Mode m = nPixelMode; if (col.ALPHA != 255) SetPixelMode(Pixel::ALPHA); else SetPixelMode(Pixel::MASK); for (auto c : sText) { if (c == '\n') { sx = 0; sy += 8 * scale; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; if (scale > 1) { for (uint32_t i = 0; i < 8; i++) for (uint32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + sx + (i*scale) + is, y + sy + (j*scale) + js, col); } else { for (uint32_t i = 0; i < 8; i++) for (uint32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0) Draw(x + sx + i, y + sy + j, col); } sx += 8 * scale; } } SetPixelMode(m); } void PixelGameEngine::SetPixelMode(Pixel::Mode m) { nPixelMode = m; } void PixelGameEngine::SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> pixelMode) { funcPixelMode = pixelMode; nPixelMode = Pixel::Mode::CUSTOM; } void PixelGameEngine::SetPixelBlend(float fBlend) { fBlendFactor = fBlend; if (fBlendFactor < 0.0f) fBlendFactor = 0.0f; if (fBlendFactor > 1.0f) fBlendFactor = 1.0f; } void PixelGameEngine::olc_UpdateMouse(int32_t x, int32_t y) { // Mouse coords come in screen space // But leave in pixel space nMousePosX = x / (int32_t)nPixelWidth; nMousePosY = y / (int32_t)nPixelHeight; if (nMousePosX >= (int32_t)nScreenWidth) nMousePosX = nScreenWidth - 1; if (nMousePosY >= (int32_t)nScreenHeight) nMousePosY = nScreenHeight - 1; if (nMousePosX < 0) nMousePosX = 0; if (nMousePosY < 0) nMousePosY = 0; } void PixelGameEngine::EngineThread() { // Start OpenGL, the context is owned by the game thread olc_OpenGLCreate(); // Create Screen Texture - disable filtering glEnable(GL_TEXTURE_2D); glGenTextures(1, &glBuffer); glBindTexture(GL_TEXTURE_2D, glBuffer); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, nScreenWidth, nScreenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, pDefaultDrawTarget->GetData()); // Create user resources as part of this thread if (!OnUserCreate()) bAtomActive = false; auto tp1 = std::chrono::system_clock::now(); auto tp2 = std::chrono::system_clock::now(); while (bAtomActive) { // Run as fast as possible while (bAtomActive) { // Handle Timing tp2 = std::chrono::system_clock::now(); std::chrono::duration<float> elapsedTime = tp2 - tp1; tp1 = tp2; // Our time per frame coefficient float fElapsedTime = elapsedTime.count(); // Handle User Input - Keyboard for (int i = 0; i < 256; i++) { pKeyboardState[i].bPressed = false; pKeyboardState[i].bReleased = false; if (pKeyNewState[i] != pKeyOldState[i]) { if (pKeyNewState[i]) { pKeyboardState[i].bPressed = !pKeyboardState[i].bHeld; pKeyboardState[i].bHeld = true; } else { pKeyboardState[i].bReleased = true; pKeyboardState[i].bHeld = false; } } pKeyOldState[i] = pKeyNewState[i]; } // Handle User Input - Mouse for (int i = 0; i < 5; i++) { pMouseState[i].bPressed = false; pMouseState[i].bReleased = false; if (pMouseNewState[i] != pMouseOldState[i]) { if (pMouseNewState[i]) { pMouseState[i].bPressed = !pMouseState[i].bHeld; pMouseState[i].bHeld = true; } else { pMouseState[i].bReleased = true; pMouseState[i].bHeld = false; } } pMouseOldState[i] = pMouseNewState[i]; } // Handle Frame Update if (!OnUserUpdate(fElapsedTime)) bAtomActive = false; // Display Graphics // TODO: This is a bit slow (especially in debug, but 100x faster in release mode???) // Copy pixel array into texture glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, nScreenWidth, nScreenHeight, GL_RGBA, GL_UNSIGNED_BYTE, pDefaultDrawTarget->GetData()); // Display texture on screen glBegin(GL_QUADS); glTexCoord2f(0.0, 1.0); glVertex3f(-1.0f + (fSubPixelOffsetX), -1.0f + (fSubPixelOffsetY), 0.0f); glTexCoord2f(0.0, 0.0); glVertex3f(-1.0f + (fSubPixelOffsetX), 1.0f + (fSubPixelOffsetY), 0.0f); glTexCoord2f(1.0, 0.0); glVertex3f(1.0f + (fSubPixelOffsetX), 1.0f + (fSubPixelOffsetY), 0.0f); glTexCoord2f(1.0, 1.0); glVertex3f(1.0f + (fSubPixelOffsetX), -1.0f + (fSubPixelOffsetY), 0.0f); glEnd(); // Present Graphics to screen SwapBuffers(glDeviceContext); // Update Title Bar fFrameTimer += fElapsedTime; nFrameCount++; if (fFrameTimer >= 1.0f) { fFrameTimer -= 1.0f; std::string sTitle = "OneLoneCoder.com - Pixel Game Engine - " + sAppName + " - FPS: " + std::to_string(nFrameCount); SetWindowText(olc_hWnd, sTitle.c_str()); nFrameCount = 0; } } // Allow the user to free resources if they have overrided the destroy function if (OnUserDestroy()) { // User has permitted destroy, so exit and clean up } else { // User denied destroy for some reason, so continue running bAtomActive = true; } } wglDeleteContext(glRenderContext); PostMessage(olc_hWnd, WM_DESTROY, 0, 0); } void PixelGameEngine::olc_ConstructFontSheet() { std::string data; data += "?Q`0001oOch0o01o@F40o0<AGD4090LAGD<090@A7ch0?00O7Q`0600>00000000"; data += "O000000nOT0063Qo4d8>?7a14Gno94AA4gno94AaOT0>o3`oO400o7QN00000400"; data += "Of80001oOg<7O7moBGT7O7lABET024@aBEd714AiOdl717a_=TH013Q>00000000"; data += "720D000V?V5oB3Q_HdUoE7a9@DdDE4A9@DmoE4A;Hg]oM4Aj8S4D84@`00000000"; data += "OaPT1000Oa`^13P1@AI[?g`1@A=[OdAoHgljA4Ao?WlBA7l1710007l100000000"; data += "ObM6000oOfMV?3QoBDD`O7a0BDDH@5A0BDD<@5A0BGeVO5ao@CQR?5Po00000000"; data += "Oc``000?Ogij70PO2D]??0Ph2DUM@7i`2DTg@7lh2GUj?0TO0C1870T?00000000"; data += "70<4001o?P<7?1QoHg43O;`h@GT0@:@LB@d0>:@hN@L0@?aoN@<0O7ao0000?000"; data += "OcH0001SOglLA7mg24TnK7ln24US>0PL24U140PnOgl0>7QgOcH0K71S0000A000"; data += "00H00000@Dm1S007@DUSg00?OdTnH7YhOfTL<7Yh@Cl0700?@Ah0300700000000"; data += "<008001QL00ZA41a@6HnI<1i@FHLM81M@@0LG81?O`0nC?Y7?`0ZA7Y300080000"; data += "O`082000Oh0827mo6>Hn?Wmo?6HnMb11MP08@C11H`08@FP0@@0004@000000000"; data += "00P00001Oab00003OcKP0006@6=PMgl<@440MglH@000000`@000001P00000000"; data += "Ob@8@@00Ob@8@Ga13R@8Mga172@8?PAo3R@827QoOb@820@0O`0007`0000007P0"; data += "O`000P08Od400g`<3V=P0G`673IP0`@3>1`00P@6O`P00g`<O`000GP800000000"; data += "?P9PL020O`<`N3R0@E4HC7b0@ET<ATB0@@l6C4B0O`H3N7b0?P01L3R000000020"; fontSprite = new olc::Sprite(128, 48); int px = 0, py = 0; for (int b = 0; b < 1024; b += 4) { uint32_t sym1 = (uint32_t)data[b + 0] - 48; uint32_t sym2 = (uint32_t)data[b + 1] - 48; uint32_t sym3 = (uint32_t)data[b + 2] - 48; uint32_t sym4 = (uint32_t)data[b + 3] - 48; uint32_t r = sym1 << 18 | sym2 << 12 | sym3 << 6 | sym4; for (int i = 0; i < 24; i++) { int k = r & (1 << i) ? 255 : 0; fontSprite->SetPixel(px, py, olc::Pixel(k, k, k, k)); if (++py == 48) { px++; py = 0; } } } } HWND PixelGameEngine::olc_WindowCreate() { WNDCLASS wc; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.hInstance = GetModuleHandle(nullptr); wc.lpfnWndProc = olc_WindowEvent; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.lpszMenuName = nullptr; wc.hbrBackground = nullptr; #ifdef UNICODE wc.lpszClassName = L"OLC_PIXEL_GAME_ENGINE"; #else wc.lpszClassName = "OLC_PIXEL_GAME_ENGINE"; #endif RegisterClass(&wc); // Define window furniture DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; DWORD dwStyle = WS_CAPTION | WS_SYSMENU | WS_VISIBLE; RECT rWndRect = { 0, 0, (LONG)nScreenWidth * (LONG)nPixelWidth, (LONG)nScreenHeight * (LONG)nPixelHeight }; // Keep client size as requested AdjustWindowRectEx(&rWndRect, dwStyle, FALSE, dwExStyle); int width = rWndRect.right - rWndRect.left; int height = rWndRect.bottom - rWndRect.top; #ifdef UNICODE olc_hWnd = CreateWindowEx(dwExStyle, L"OLC_PIXEL_GAME_ENGINE", L"", dwStyle, 30, 30, width, height, NULL, NULL, GetModuleHandle(nullptr), this); #else olc_hWnd = CreateWindowEx(dwExStyle, "OLC_PIXEL_GAME_ENGINE", "", dwStyle, 30, 30, width, height, NULL, NULL, GetModuleHandle(nullptr), this); #endif // Create Keyboard Mapping mapKeys[0x41] = Key::A; mapKeys[0x42] = Key::B; mapKeys[0x43] = Key::C; mapKeys[0x44] = Key::D; mapKeys[0x45] = Key::E; mapKeys[0x46] = Key::F; mapKeys[0x47] = Key::G; mapKeys[0x48] = Key::H; mapKeys[0x49] = Key::I; mapKeys[0x4A] = Key::J; mapKeys[0x4B] = Key::K; mapKeys[0x4C] = Key::L; mapKeys[0x4D] = Key::M; mapKeys[0x4E] = Key::N; mapKeys[0x4F] = Key::O; mapKeys[0x50] = Key::P; mapKeys[0x51] = Key::Q; mapKeys[0x52] = Key::R; mapKeys[0x53] = Key::S; mapKeys[0x54] = Key::T; mapKeys[0x55] = Key::U; mapKeys[0x56] = Key::V; mapKeys[0x57] = Key::W; mapKeys[0x58] = Key::X; mapKeys[0x59] = Key::Y; mapKeys[0x5A] = Key::Z; mapKeys[VK_F1] = Key::F1; mapKeys[VK_F2] = Key::F2; mapKeys[VK_F3] = Key::F3; mapKeys[VK_F4] = Key::F4; mapKeys[VK_F5] = Key::F5; mapKeys[VK_F6] = Key::F6; mapKeys[VK_F7] = Key::F7; mapKeys[VK_F8] = Key::F8; mapKeys[VK_F9] = Key::F9; mapKeys[VK_F10] = Key::F10; mapKeys[VK_F11] = Key::F11; mapKeys[VK_F12] = Key::F12; mapKeys[VK_DOWN] = Key::DOWN; mapKeys[VK_LEFT] = Key::LEFT; mapKeys[VK_RIGHT] = Key::RIGHT; mapKeys[VK_UP] = Key::UP; mapKeys[VK_BACK] = Key::BACK; mapKeys[VK_ESCAPE] = Key::ESCAPE; mapKeys[VK_RETURN] = Key::ENTER; mapKeys[VK_PAUSE] = Key::PAUSE; mapKeys[VK_SCROLL] = Key::SCROLL; mapKeys[VK_TAB] = Key::TAB; mapKeys[VK_DELETE] = Key::DEL; mapKeys[VK_HOME] = Key::HOME; mapKeys[VK_END] = Key::END; mapKeys[VK_PRIOR] = Key::PGUP; mapKeys[VK_NEXT] = Key::PGDN; mapKeys[VK_INSERT] = Key::INS; mapKeys[VK_SHIFT] = Key::SHIFT; mapKeys[VK_CONTROL] = Key::CTRL; mapKeys[VK_SPACE] = Key::SPACE; mapKeys[0x30] = Key::K0; mapKeys[0x31] = Key::K1; mapKeys[0x32] = Key::K2; mapKeys[0x33] = Key::K3; mapKeys[0x34] = Key::K4; mapKeys[0x35] = Key::K5; mapKeys[0x36] = Key::K6; mapKeys[0x37] = Key::K7; mapKeys[0x38] = Key::K8; mapKeys[0x39] = Key::K9; return olc_hWnd; } bool PixelGameEngine::olc_OpenGLCreate() { // Create Device Context glDeviceContext = GetDC(olc_hWnd); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pf = 0; if (!(pf = ChoosePixelFormat(glDeviceContext, &pfd))) return false; SetPixelFormat(glDeviceContext, pf, &pfd); if (!(glRenderContext = wglCreateContext(glDeviceContext))) return false; wglMakeCurrent(glDeviceContext, glRenderContext); // Remove Frame cap wglSwapInterval = (wglSwapInterval_t*)wglGetProcAddress("wglSwapIntervalEXT"); wglSwapInterval(0); return true; } // Windows Event Handler LRESULT CALLBACK PixelGameEngine::olc_WindowEvent(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static PixelGameEngine *sge; switch (uMsg) { case WM_CREATE: sge = (PixelGameEngine*)((LPCREATESTRUCT)lParam)->lpCreateParams; return 0; case WM_MOUSEMOVE: { uint16_t x = lParam & 0xFFFF; // Thanks @ForAbby (Discord) uint16_t y = (lParam >> 16) & 0xFFFF; int16_t ix = *(int16_t*)&x; int16_t iy = *(int16_t*)&y; sge->olc_UpdateMouse(ix, iy); return 0; } case WM_MOUSELEAVE: sge->bHasMouseFocus = false; case WM_SETFOCUS: sge->bHasInputFocus = true; return 0; case WM_KILLFOCUS: sge->bHasInputFocus = false; return 0; case WM_KEYDOWN: sge->pKeyNewState[mapKeys[wParam]] = true; return 0; case WM_KEYUP: sge->pKeyNewState[mapKeys[wParam]] = false; return 0; case WM_LBUTTONDOWN:sge->pMouseNewState[0] = true; return 0; case WM_LBUTTONUP: sge->pMouseNewState[0] = false; return 0; case WM_RBUTTONDOWN:sge->pMouseNewState[1] = true; return 0; case WM_RBUTTONUP: sge->pMouseNewState[1] = false; return 0; case WM_MBUTTONDOWN:sge->pMouseNewState[2] = true; return 0; case WM_MBUTTONUP: sge->pMouseNewState[2] = false; return 0; case WM_CLOSE: bAtomActive = false; return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } std::atomic<bool> PixelGameEngine::bAtomActive{ false }; #pragma endregion ////////////////////////////////////////////////////////////////// std::wstring ConvertS2W(std::string s) { int count = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); wchar_t* buffer = new wchar_t[count]; MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, count); std::wstring w(buffer); delete[] buffer; return w; delete[] buffer; } #pragma region Pixel Pixel::Pixel() { r = 0; g = 0; b = 0; a = 255; } Pixel::Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) { r = red; g = green; b = blue; a = alpha; } Pixel::Pixel(uint32_t p) { n = p; } //========================================================== #pragma endregion #pragma region Sprite Sprite::Sprite() { pColData = nullptr; width = 0; height = 0; } Sprite::Sprite(std::string sImageFile) { LoadFromFile(sImageFile); } Sprite::Sprite(std::string sImageFile, olc::ResourcePack* pack) { LoadFromPGESprFile(sImageFile, pack); } Sprite::Sprite(int32_t w, int32_t h) { if (pColData) delete[] pColData; width = w; height = h; pColData = new Pixel[width * height]; for (int32_t i = 0; i < width * height; i++) pColData[i] = Pixel(); } Sprite::~Sprite() { if (pColData) delete pColData; } olc::rcode Sprite::LoadFromPGESprFile(std::string sImageFile, olc::ResourcePack* pack) { if (pColData) delete[] pColData; auto ReadData = [&](std::istream& is) { is.read((char*)&width, sizeof(int32_t)); is.read((char*)&height, sizeof(int32_t)); pColData = new Pixel[width * height]; is.read((char*)pColData, width * height * sizeof(uint32_t)); }; // These are essentially Memory Surfaces represented by olc::Sprite // which load very fast, but are completely uncompressed if (pack == nullptr) { std::ifstream ifs; ifs.open(sImageFile, std::ifstream::binary); if (ifs.is_open()) { ReadData(ifs); return olc::OK; } else return olc::FAIL; } else { std::istream is(&(pack->GetStreamBuffer(sImageFile))); ReadData(is); } return olc::FAIL; } olc::rcode Sprite::SaveToPGESprFile(std::string sImageFile) { if (pColData == nullptr) return olc::FAIL; std::ofstream ofs; ofs.open(sImageFile, std::ifstream::binary); if (ofs.is_open()) { ofs.write((char*)&width, sizeof(int32_t)); ofs.write((char*)&height, sizeof(int32_t)); ofs.write((char*)pColData, width * height * sizeof(uint32_t)); ofs.close(); return olc::OK; } return olc::FAIL; } olc::rcode Sprite::LoadFromFile(std::string sImageFile, olc::ResourcePack* pack) { // Use GDI+ std::wstring wsImageFile; wsImageFile = ConvertS2W(sImageFile); Gdiplus::Bitmap* bmp = Gdiplus::Bitmap::FromFile(wsImageFile.c_str()); if (bmp == nullptr) return olc::NO_FILE; width = bmp->GetWidth(); height = bmp->GetHeight(); pColData = new Pixel[width * height]; for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) { Gdiplus::Color c; bmp->GetPixel(x, y, &c); SetPixel(x, y, Pixel(c.GetRed(), c.GetGreen(), c.GetBlue(), c.GetAlpha())); } delete bmp; return olc::OK; } void Sprite::SetSampleMode(olc::Sprite::Mode mode) { modeSample = mode; } Pixel Sprite::GetPixel(int32_t x, int32_t y) { if (modeSample == olc::Sprite::Mode::NORMAL) { if (x >= 0 && x < width && y >= 0 && y < height) return pColData[y * width + x]; else return Pixel(0, 0, 0, 0); } else { return pColData[abs(y % height) * width + abs(x % width)]; } } void Sprite::SetPixel(int32_t x, int32_t y, Pixel p) { if (x >= 0 && x < width && y >= 0 && y < height) pColData[y * width + x] = p; } Pixel Sprite::Sample(float x, float y) { int32_t sx = (int32_t)(x * (float)width); int32_t sy = (int32_t)(y * (float)height); return GetPixel(sx, sy); } Pixel* Sprite::GetData() { return pColData; } #pragma endregion #pragma region ResourcePack ResourcePack::ResourcePack() { } ResourcePack::~ResourcePack() { ClearPack(); } olc::rcode ResourcePack::AddToPack(std::string sFile) { std::ifstream ifs(sFile, std::ifstream::binary); if (!ifs.is_open()) return olc::FAIL; // Get File Size std::streampos p = 0; p = ifs.tellg(); ifs.seekg(0, std::ios::end); p = ifs.tellg() - p; ifs.seekg(0, std::ios::beg); // Create entry sEntry e; e.data = nullptr; e.nFileSize = p; // Read file into memory e.data = new uint8_t[e.nFileSize]; ifs.read((char*)e.data, e.nFileSize); ifs.close(); // Add To Map mapFiles[sFile] = e; return olc::OK; } olc::rcode ResourcePack::SavePack(std::string sFile) { std::ofstream ofs(sFile, std::ofstream::binary); if (!ofs.is_open()) return olc::FAIL; // 1) Write Map size_t nMapSize = mapFiles.size(); ofs.write((char*)&nMapSize, sizeof(size_t)); for (auto& e : mapFiles) { size_t nPathSize = e.first.size(); ofs.write((char*)&nPathSize, sizeof(size_t)); ofs.write(e.first.c_str(), nPathSize); ofs.write((char*)&e.second.nID, sizeof(uint32_t)); ofs.write((char*)&e.second.nFileSize, sizeof(uint32_t)); ofs.write((char*)&e.second.nFileOffset, sizeof(uint32_t)); } // 2) Write Data std::streampos offset = ofs.tellp(); for (auto& e : mapFiles) { e.second.nFileOffset = offset; ofs.write((char*)e.second.data, e.second.nFileSize); offset += e.second.nFileSize; } // 3) Rewrite Map (it has been updated with offsets now) ofs.seekp(std::ios::beg); ofs.write((char*)&nMapSize, sizeof(size_t)); for (auto& e : mapFiles) { size_t nPathSize = e.first.size(); ofs.write((char*)&nPathSize, sizeof(size_t)); ofs.write(e.first.c_str(), nPathSize); ofs.write((char*)&e.second.nID, sizeof(uint32_t)); ofs.write((char*)&e.second.nFileSize, sizeof(uint32_t)); ofs.write((char*)&e.second.nFileOffset, sizeof(uint32_t)); } ofs.close(); return olc::OK; } olc::rcode ResourcePack::LoadPack(std::string sFile) { std::ifstream ifs(sFile, std::ifstream::binary); if (!ifs.is_open()) return olc::FAIL; // 1) Read Map size_t nMapEntries; ifs.read((char*)&nMapEntries, sizeof(size_t)); for (size_t i = 0; i < nMapEntries; i++) { size_t nFilePathSize = 0; ifs.read((char*)&nFilePathSize, sizeof(size_t)); std::string sFileName(nFilePathSize, ' '); for (size_t j = 0; j < nFilePathSize; j++) sFileName[j] = ifs.get(); sEntry e; e.data = nullptr; ifs.read((char*)&e.nID, sizeof(uint32_t)); ifs.read((char*)&e.nFileSize, sizeof(uint32_t)); ifs.read((char*)&e.nFileOffset, sizeof(uint32_t)); mapFiles[sFileName] = e; } // 2) Read Data for (auto& e : mapFiles) { e.second.data = new uint8_t[e.second.nFileSize]; ifs.seekg(e.second.nFileOffset); ifs.read((char*)e.second.data, e.second.nFileSize); //e.second.setg e.second._config(); //e.second.pubsetbuf((char*)e.second.data, e.second.nFileSize); } ifs.close(); return olc::OK; } olc::ResourcePack::sEntry ResourcePack::GetStreamBuffer(std::string sFile) { return mapFiles[sFile]; } olc::rcode ResourcePack::ClearPack() { for (auto& e : mapFiles) { if (e.second.data != nullptr) delete[] e.second.data; } mapFiles.clear(); return olc::OK; } #pragma endregion }
27.759084
141
0.5944
[ "object" ]
fef618079264c440da9e159e25173b9a6a7d28c5
6,869
cpp
C++
src/vidhrdw/arcadecl.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
33
2015-08-10T11:13:47.000Z
2021-08-30T10:00:46.000Z
src/vidhrdw/arcadecl.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
13
2015-08-25T03:53:08.000Z
2022-03-30T18:02:35.000Z
src/vidhrdw/arcadecl.cpp
gameblabla/mame_nspire
83dfe1606aba906bd28608f2cb8f0754492ac3da
[ "Unlicense" ]
40
2015-08-25T05:09:21.000Z
2022-02-08T05:02:30.000Z
/*************************************************************************** Atari Arcade Classics hardware (prototypes) Note: this video hardware has some similarities to Shuuz & company The sprite offset registers are stored to 3EFF80 ****************************************************************************/ #include "driver.h" #include "machine/atarigen.h" #include "vidhrdw/generic.h" #define XCHARS 43 #define YCHARS 30 #define XDIM (XCHARS*8) #define YDIM (YCHARS*8) /************************************* * * Statics * *************************************/ static int *color_usage; /************************************* * * Prototypes * *************************************/ static const UINT8 *update_palette(void); static void mo_color_callback(const UINT16 *data, const struct rectangle *clip, void *param); static void mo_render_callback(const UINT16 *data, const struct rectangle *clip, void *param); /************************************* * * Video system start * *************************************/ int arcadecl_vh_start(void) { static struct atarigen_mo_desc mo_desc = { 256, /* maximum number of MO's */ 8, /* number of bytes per MO entry */ 2, /* number of bytes between MO words */ 0, /* ignore an entry if this word == 0xffff */ 0, 0, 0xff, /* link = (data[linkword] >> linkshift) & linkmask */ 0 /* render in reverse link order */ }; static struct atarigen_pf_desc pf_desc = { 8, 8, /* width/height of each tile */ 64, 64, /* number of tiles in each direction */ 1 /* non-scrolling */ }; /* allocate color usage */ color_usage = (int*)malloc(sizeof(int) * 256); if (!color_usage) return 1; color_usage[0] = XDIM * YDIM; memset(atarigen_playfieldram, 0, 0x20000); /* initialize the playfield */ if (atarigen_pf_init(&pf_desc)) { free(color_usage); return 1; } /* initialize the motion objects */ if (atarigen_mo_init(&mo_desc)) { atarigen_pf_free(); free(color_usage); return 1; } return 0; } /************************************* * * Video system shutdown * *************************************/ void arcadecl_vh_stop(void) { /* free data */ if (color_usage) free(color_usage); color_usage = 0; atarigen_pf_free(); atarigen_mo_free(); } /************************************* * * Playfield RAM write handler * *************************************/ WRITE_HANDLER( arcadecl_playfieldram_w ) { int oldword = READ_WORD(&atarigen_playfieldram[offset]); int newword = COMBINE_WORD(oldword, data); int x, y; if (oldword != newword) { WRITE_WORD(&atarigen_playfieldram[offset], newword); /* track color usage */ x = offset % 512; y = offset / 512; if (x < XDIM && y < YDIM) { color_usage[(oldword >> 8) & 0xff]--; color_usage[oldword & 0xff]--; color_usage[(newword >> 8) & 0xff]++; color_usage[newword & 0xff]++; } /* mark scanlines dirty */ atarigen_pf_dirty[y] = 1; } } /************************************* * * Periodic scanline updater * *************************************/ void arcadecl_scanline_update(int scanline) { /* doesn't appear to use SLIPs */ if (scanline < YDIM) atarigen_mo_update(atarigen_spriteram, 0, scanline); } /************************************* * * Main refresh * *************************************/ void arcadecl_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh) { /* remap if necessary */ if (update_palette()) memset(atarigen_pf_dirty, 1, YDIM); /* update the cached bitmap */ { int x, y; for (y = 0; y < YDIM; y++) if (atarigen_pf_dirty[y]) { int xx = 0; const UINT8 *src = &atarigen_playfieldram[512 * y]; /* regenerate the line */ for (x = 0; x < XDIM/2; x++) { int bits = READ_WORD(src); src += 2; plot_pixel(atarigen_pf_bitmap, xx++, y, Machine->pens[bits >> 8]); plot_pixel(atarigen_pf_bitmap, xx++, y, Machine->pens[bits & 0xff]); } atarigen_pf_dirty[y] = 0; } } /* copy the cached bitmap */ copybitmap(bitmap, atarigen_pf_bitmap, 0, 0, 0, 0, NULL, TRANSPARENCY_NONE, 0); /* render the motion objects */ atarigen_mo_process(mo_render_callback, bitmap); /* update onscreen messages */ atarigen_update_messages(); } /************************************* * * Palette management * *************************************/ static const UINT8 *update_palette(void) { UINT16 mo_map[16]; int i, j; /* reset color tracking */ memset(mo_map, 0, sizeof(mo_map)); palette_init_used_colors(); /* update color usage for the mo's */ atarigen_mo_process(mo_color_callback, mo_map); /* rebuild the playfield palette */ for (i = 0; i < 256; i++) if (color_usage[i]) palette_used_colors[0x000 + i] = PALETTE_COLOR_USED; /* rebuild the motion object palette */ for (i = 0; i < 16; i++) { UINT16 used = mo_map[i]; if (used) { palette_used_colors[0x100 + i * 16 + 0] = PALETTE_COLOR_TRANSPARENT; for (j = 1; j < 16; j++) if (used & (1 << j)) palette_used_colors[0x100 + i * 16 + j] = PALETTE_COLOR_USED; } } return palette_recalc(); } /************************************* * * Motion object palette * *************************************/ static void mo_color_callback(const UINT16 *data, const struct rectangle *clip, void *param) { const UINT32 *usage = Machine->gfx[0]->pen_usage; UINT16 *colormap = (UINT16*)param; int code = data[1] & 0x7fff; int color = data[2] & 0x000f; int hsize = ((data[3] >> 4) & 7) + 1; int vsize = (data[3] & 7) + 1; int tiles = hsize * vsize; UINT16 temp = 0; int i; for (i = 0; i < tiles; i++) temp |= usage[code++]; colormap[color] |= temp; } /************************************* * * Motion object rendering * *************************************/ static void mo_render_callback(const UINT16 *data, const struct rectangle *clip, void *param) { const struct GfxElement *gfx = Machine->gfx[0]; struct osd_bitmap *bitmap = (struct osd_bitmap *)param; struct rectangle pf_clip; /* extract data from the various words */ int hflip = data[1] & 0x8000; int code = data[1] & 0x7fff; int xpos = (data[2] >> 7) + 4; int color = data[2] & 0x000f; /* int priority = (data[2] >> 3) & 1;*/ int ypos = YDIM - (data[3] >> 7); int hsize = ((data[3] >> 4) & 7) + 1; int vsize = (data[3] & 7) + 1; /* adjust for height */ ypos -= vsize * 8; /* adjust the final coordinates */ xpos &= 0x1ff; ypos &= 0x1ff; if (xpos >= XDIM) xpos -= 0x200; if (ypos >= YDIM) ypos -= 0x200; /* determine the bounding box */ atarigen_mo_compute_clip_8x8(pf_clip, xpos, ypos, hsize, vsize, clip); /* draw the motion object */ atarigen_mo_draw_8x8(bitmap, gfx, code, color, hflip, 0, xpos, ypos, hsize, vsize, clip, TRANSPARENCY_PEN, 0); }
21.875796
111
0.552191
[ "render", "object" ]
fef690d55eb7dc1939ddf3612a15fa6ad146df0f
9,001
cc
C++
src/osgw/renderer.cc
CaffeineViking/lwss
bb7aef8c1b91c95b6b91ca1d22b46d2c7d6e6e62
[ "MIT" ]
44
2018-09-28T06:58:20.000Z
2022-02-22T14:08:23.000Z
src/osgw/renderer.cc
CaffeineViking/lwss
bb7aef8c1b91c95b6b91ca1d22b46d2c7d6e6e62
[ "MIT" ]
11
2018-02-11T18:49:38.000Z
2018-02-16T12:29:21.000Z
src/osgw/renderer.cc
CaffeineViking/lwss
bb7aef8c1b91c95b6b91ca1d22b46d2c7d6e6e62
[ "MIT" ]
5
2019-06-05T02:36:27.000Z
2021-09-08T09:04:54.000Z
#include <osgw/renderer.hh> namespace osgw { Renderer::Renderer(Window& window, const Parameters& parameters) : window { window }, parameters { parameters } { set_parameters(parameters); } void Renderer::clear(float r, float g, float b) { if (!window.has_context()) window.request_context(); GLenum bitfield = GL_COLOR_BUFFER_BIT; if (parameters.depth_test) bitfield |= GL_DEPTH_BUFFER_BIT; if (parameters.stencil_test) bitfield |= GL_STENCIL_BUFFER_BIT; fog_color = { r, g, b }; glClearColor(r, g, b, 1.0); glClear(bitfield); } const Renderer::Parameters& Renderer::get_parameters() const { return parameters; } void Renderer::set_parameters(const Parameters& new_parameters) { if (new_parameters.blending) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); } else glDisable(GL_BLEND); if (new_parameters.face_culling) { glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); } else glDisable(GL_CULL_FACE); if (new_parameters.depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); if (new_parameters.multisample) glEnable(GL_MULTISAMPLE); else glDisable(GL_MULTISAMPLE); if (new_parameters.stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); if (new_parameters.seamless_cubemap) glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); else glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); if (new_parameters.wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPatchParameteri(GL_PATCH_VERTICES, 4); parameters = new_parameters; } void Renderer::toggle_wireframe() { parameters.wireframe = !parameters.wireframe; if (parameters.wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } void Renderer::set_vertex_array(const VertexArray& vertex_array) { if (!is_current_vertex_array(&vertex_array)) vertex_array.bind(); current_vertex_array = &vertex_array; } void Renderer::set_shader_program(const ShaderProgram& shader_program) { if (!is_current_shader_program(&shader_program)) shader_program.use(); current_shader_program = &shader_program; } bool Renderer::is_current_vertex_array(const VertexArray* vertex_array) const { return vertex_array == current_vertex_array; } bool Renderer::is_current_shader_program(const ShaderProgram* shader_program) const { return shader_program == current_shader_program; } // Assignment of texture units is done by a ring buffer, the oldest // assigned texture is the one that is going to be replaced first!! std::size_t Renderer::assign_texture_unit(const Texture* texture) { int assigned_texture_unit { has_texture_unit(texture) }; if (assigned_texture_unit == -1) { assigned_texture_unit = current_texture_unit; current_textures[current_texture_unit] = texture; current_texture_unit = (current_texture_unit + 1) % current_textures.size(); } return static_cast<std::size_t>(assigned_texture_unit); } int Renderer::has_texture_unit(const Texture* texture) const { int texture_unit { -1 }; for (std::size_t i { 0 }; i < current_textures.size(); ++i) if (current_textures[i] == texture) texture_unit = i; return texture_unit; } // Here we assume we are limited to 16 TUs, which // is pessimistic, but common in "lower-end" GPU. std::size_t Renderer::next_texture_unit() const { return current_texture_unit; } void Renderer::setup_shader_program(ShaderProgram& shader_program) { set_shader_program(shader_program); shader_program.uniform("time", window.time()); shader_program.uniform("fog_color", fog_color); } void Renderer::setup_texture_samplers(ShaderProgram& shader_program, std::vector<Texture::Sampler>& samplers) { for (Texture::Sampler& sampler : samplers) { std::size_t texture_unit { assign_texture_unit(&sampler.texture) }; if (texture_unit != sampler.texture.active_unit()) sampler.texture.active_unit(texture_unit); shader_program.sampler(sampler.name, sampler.texture); } } void Renderer::setup_transformation_matrices(ShaderProgram& shader_program, const Camera& camera, const glm::mat4& model_matrix) { shader_program.uniform("eye_position", camera.get_position()); shader_program.uniform("look_at_point", camera.get_look_at()); shader_program.uniform4x4("projection_view", camera.get_matrix()); shader_program.uniform4x4("model", model_matrix); } void Renderer::setup_light_sources(ShaderProgram& shader_program, const std::vector<Light>& lights, const AmbientLight& ambient_light) { shader_program.uniform("ambient_light_color", ambient_light.get_color()); unsigned int current_directional_light { 0 }, current_point_light { 0 }; for (const Light& light : lights) { if (light.get_type() == Light::Type::Directional) { std::string target_array { "directional_lights[" }; auto index = std::to_string(current_directional_light); std::string target_struct { target_array + index + "]." }; shader_program.uniform(target_struct + "color", light.get_color()); shader_program.uniform(target_struct + "direction", light.get_direction()); ++current_directional_light; } else if (light.get_type() == Light::Type::Point) { std::string target_array { "point_lights[" }; auto index = std::to_string(current_directional_light); std::string target_struct { target_array + index + "]." }; shader_program.uniform(target_struct + "color", light.get_color()); shader_program.uniform(target_struct + "position", light.get_location()); shader_program.uniform(target_struct + "falloff", light.get_falloff()); ++current_point_light; } } shader_program.uniform("point_lights_size", current_point_light); shader_program.uniform("directional_lights_size", current_directional_light); } void Renderer::draw_triangles(VertexArray& vertex_array) { set_vertex_array(vertex_array); glDrawElements(GL_TRIANGLES, vertex_array.size(), GL_UNSIGNED_INT, nullptr); } void Renderer::draw_patches(VertexArray& vertex_array) { set_vertex_array(vertex_array); glDrawElements(GL_PATCHES, vertex_array.size(), GL_UNSIGNED_INT, nullptr); } void Renderer::draw(VertexArray& vertex_array, ShaderProgram& shader_program, std::vector<Texture::Sampler>& texture_samplers) { setup_shader_program(shader_program); setup_texture_samplers(shader_program, texture_samplers); if (!shader_program.has_tess_eval_shader()) draw_triangles(vertex_array); else draw_patches(vertex_array); // Checks if we'll use the tessellators. } void Renderer::draw(VertexArray& vertex_array, ShaderProgram& shader_program, std::vector<Texture::Sampler>& texture_samplers, const Camera& camera, const glm::mat4& model_matrix) { setup_shader_program(shader_program); setup_texture_samplers(shader_program, texture_samplers); setup_transformation_matrices(shader_program, camera, model_matrix); if (!shader_program.has_tess_eval_shader()) draw_triangles(vertex_array); else draw_patches(vertex_array); // Checks if we'll use the tessellators. } void Renderer::draw(VertexArray& vertex_array, ShaderProgram& shader_program, std::vector<Texture::Sampler>& texture_samplers, const Camera& camera, const glm::mat4& model_matrix, const std::vector<Light>& lights, const AmbientLight& ambient_light) { setup_shader_program(shader_program); setup_texture_samplers(shader_program, texture_samplers); setup_light_sources(shader_program, lights, ambient_light); setup_transformation_matrices(shader_program, camera, model_matrix); if (!shader_program.has_tess_eval_shader()) draw_triangles(vertex_array); else draw_patches(vertex_array); // Checks if we'll use the tessellators. } }
44.559406
115
0.660371
[ "vector", "model" ]
fef87196bfff0b0ae6855b5c735e60fe99a0a7f5
3,397
cpp
C++
aws-cpp-sdk-email/source/model/S3Action.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-email/source/model/S3Action.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-email/source/model/S3Action.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/email/model/S3Action.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace SES { namespace Model { S3Action::S3Action() : m_topicArnHasBeenSet(false), m_bucketNameHasBeenSet(false), m_objectKeyPrefixHasBeenSet(false), m_kmsKeyArnHasBeenSet(false) { } S3Action::S3Action(const XmlNode& xmlNode) : m_topicArnHasBeenSet(false), m_bucketNameHasBeenSet(false), m_objectKeyPrefixHasBeenSet(false), m_kmsKeyArnHasBeenSet(false) { *this = xmlNode; } S3Action& S3Action::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode topicArnNode = resultNode.FirstChild("TopicArn"); if(!topicArnNode.IsNull()) { m_topicArn = Aws::Utils::Xml::DecodeEscapedXmlText(topicArnNode.GetText()); m_topicArnHasBeenSet = true; } XmlNode bucketNameNode = resultNode.FirstChild("BucketName"); if(!bucketNameNode.IsNull()) { m_bucketName = Aws::Utils::Xml::DecodeEscapedXmlText(bucketNameNode.GetText()); m_bucketNameHasBeenSet = true; } XmlNode objectKeyPrefixNode = resultNode.FirstChild("ObjectKeyPrefix"); if(!objectKeyPrefixNode.IsNull()) { m_objectKeyPrefix = Aws::Utils::Xml::DecodeEscapedXmlText(objectKeyPrefixNode.GetText()); m_objectKeyPrefixHasBeenSet = true; } XmlNode kmsKeyArnNode = resultNode.FirstChild("KmsKeyArn"); if(!kmsKeyArnNode.IsNull()) { m_kmsKeyArn = Aws::Utils::Xml::DecodeEscapedXmlText(kmsKeyArnNode.GetText()); m_kmsKeyArnHasBeenSet = true; } } return *this; } void S3Action::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_topicArnHasBeenSet) { oStream << location << index << locationValue << ".TopicArn=" << StringUtils::URLEncode(m_topicArn.c_str()) << "&"; } if(m_bucketNameHasBeenSet) { oStream << location << index << locationValue << ".BucketName=" << StringUtils::URLEncode(m_bucketName.c_str()) << "&"; } if(m_objectKeyPrefixHasBeenSet) { oStream << location << index << locationValue << ".ObjectKeyPrefix=" << StringUtils::URLEncode(m_objectKeyPrefix.c_str()) << "&"; } if(m_kmsKeyArnHasBeenSet) { oStream << location << index << locationValue << ".KmsKeyArn=" << StringUtils::URLEncode(m_kmsKeyArn.c_str()) << "&"; } } void S3Action::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_topicArnHasBeenSet) { oStream << location << ".TopicArn=" << StringUtils::URLEncode(m_topicArn.c_str()) << "&"; } if(m_bucketNameHasBeenSet) { oStream << location << ".BucketName=" << StringUtils::URLEncode(m_bucketName.c_str()) << "&"; } if(m_objectKeyPrefixHasBeenSet) { oStream << location << ".ObjectKeyPrefix=" << StringUtils::URLEncode(m_objectKeyPrefix.c_str()) << "&"; } if(m_kmsKeyArnHasBeenSet) { oStream << location << ".KmsKeyArn=" << StringUtils::URLEncode(m_kmsKeyArn.c_str()) << "&"; } } } // namespace Model } // namespace SES } // namespace Aws
27.844262
135
0.68796
[ "model" ]
fef9020962b955bfecc4ef5f98f854472924a7a5
12,436
cpp
C++
arduino/opencr_arduino/opencr/libraries/OpenManipulator/src/open_manipulator/OMAPI.cpp
mkhansen-intel/OpenCR
9da4ae9fd4506df6e068c2a6d381f268a0ba371a
[ "Apache-2.0" ]
2
2021-04-27T17:09:19.000Z
2021-04-27T17:09:24.000Z
arduino/opencr_arduino/opencr/libraries/OpenManipulator/src/open_manipulator/OMAPI.cpp
mkhansen-intel/OpenCR
9da4ae9fd4506df6e068c2a6d381f268a0ba371a
[ "Apache-2.0" ]
null
null
null
arduino/opencr_arduino/opencr/libraries/OpenManipulator/src/open_manipulator/OMAPI.cpp
mkhansen-intel/OpenCR
9da4ae9fd4506df6e068c2a6d381f268a0ba371a
[ "Apache-2.0" ]
1
2019-02-03T04:49:15.000Z
2019-02-03T04:49:15.000Z
/******************************************************************************* * Copyright 2016 ROBOTIS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* Authors: Darby Lim, Hye-Jong KIM, Ryan Shim, Yong-Ho Na */ #include "../../include/open_manipulator/OMAPI.h" using namespace OPEN_MANIPULATOR; //////////////////////////////////////////////////////////////////////////// ////////////////////////////////Basic Function////////////////////////////// //////////////////////////////////////////////////////////////////////////// void Manager::addWorld(OM_MANAGER::Manipulator *manipulator, Name world_name, Name child_name, Vector3f world_position, Matrix3f world_orientation) { manipulator->addWorld(world_name, child_name, world_position, world_orientation); } void Manager::addComponent(OM_MANAGER::Manipulator *manipulator, Name my_name, Name parent_name, Name child_name, Vector3f relative_position, Matrix3f relative_orientation, Vector3f axis_of_rotation, int8_t actuator_id, float coefficient, float mass, Matrix3f inertia_tensor, Vector3f center_of_mass) { manipulator->addComponent(my_name, parent_name, child_name, relative_position, relative_orientation, axis_of_rotation, actuator_id, coefficient, mass, inertia_tensor, center_of_mass); } void Manager::addTool(OM_MANAGER::Manipulator *manipulator, Name my_name, Name parent_name, Vector3f relative_position, Matrix3f relative_orientation, int8_t tool_id, float coefficient, float mass, Matrix3f inertia_tensor, Vector3f center_of_mass) { manipulator->addTool(my_name, parent_name, relative_position, relative_orientation, tool_id, coefficient, mass, inertia_tensor, center_of_mass); } void Manager::addComponentChild(OM_MANAGER::Manipulator *manipulator, Name my_name, Name child_name) { manipulator->addComponentChild(my_name, child_name); } void Manager::checkManipulatorSetting(OM_MANAGER::Manipulator *manipulator) { manipulator->checkManipulatorSetting(); } void Manager::setWorldPose(OM_MANAGER::Manipulator *manipulator, Pose world_pose) { manipulator->setWorldPose(world_pose); } void Manager::setWorldPosition(OM_MANAGER::Manipulator *manipulator, Vector3f world_position) { manipulator->setWorldPosition(world_position); } void Manager::setWorldOrientation(OM_MANAGER::Manipulator *manipulator, Matrix3f world_orientation) { manipulator->setWorldOrientation(world_orientation); } void Manager::setWorldState(OM_MANAGER::Manipulator *manipulator, State world_state) { manipulator->setWorldState(world_state); } void Manager::setWorldVelocity(OM_MANAGER::Manipulator *manipulator, VectorXf world_velocity) { manipulator->setWorldVelocity(world_velocity); } void Manager::setWorldAcceleration(OM_MANAGER::Manipulator *manipulator, VectorXf world_acceleration) { manipulator->setWorldAcceleration(world_acceleration); } void Manager::setComponent(OM_MANAGER::Manipulator *manipulator, Name name, Component component) { manipulator->setComponent(name, component); } void Manager::setComponentPoseToWorld(OM_MANAGER::Manipulator *manipulator, Name name, Pose pose_to_world) { manipulator->setComponentPoseToWorld(name, pose_to_world); } void Manager::setComponentPositionToWorld(OM_MANAGER::Manipulator *manipulator, Name name, Vector3f position_to_world) { manipulator->setComponentPositionToWorld(name, position_to_world); } void Manager::setComponentOrientationToWorld(OM_MANAGER::Manipulator *manipulator, Name name, Matrix3f orientation_to_wolrd) { manipulator->setComponentOrientationToWorld(name, orientation_to_wolrd); } void Manager::setComponentStateToWorld(OM_MANAGER::Manipulator *manipulator, Name name, State state_to_world) { manipulator->setComponentStateToWorld(name, state_to_world); } void Manager::setComponentVelocityToWorld(OM_MANAGER::Manipulator *manipulator, Name name, VectorXf velocity) { manipulator->setComponentVelocityToWorld(name, velocity); } void Manager::setComponentAccelerationToWorld(OM_MANAGER::Manipulator *manipulator, Name name, VectorXf accelaration) { manipulator->setComponentAccelerationToWorld(name, accelaration); } void Manager::setComponentJointAngle(OM_MANAGER::Manipulator *manipulator, Name name, float angle) { manipulator->setComponentJointAngle(name, angle); } void Manager::setComponentJointVelocity(OM_MANAGER::Manipulator *manipulator, Name name, float angular_velocity) { manipulator->setComponentJointVelocity(name, angular_velocity); } void Manager::setComponentJointAcceleration(OM_MANAGER::Manipulator *manipulator, Name name, float angular_acceleration) { manipulator->setComponentJointAcceleration(name, angular_acceleration); } void Manager::setComponentToolOnOff(OM_MANAGER::Manipulator *manipulator, Name name, bool on_off) { manipulator->setComponentToolOnOff(name, on_off); } void Manager::setComponentToolValue(OM_MANAGER::Manipulator *manipulator, Name name, float actuator_value) { manipulator->setComponentToolValue(name, actuator_value); } void Manager::setAllActiveJointAngle(OM_MANAGER::Manipulator *manipulator, std::vector<float> angle_vector) { manipulator->setAllActiveJointAngle(angle_vector); } int8_t Manager::getDOF(OM_MANAGER::Manipulator *manipulator) { return manipulator->getDOF(); } int8_t Manager::getComponentSize(OM_MANAGER::Manipulator *manipulator) { return manipulator->getComponentSize(); } Name Manager::getWorldName(OM_MANAGER::Manipulator *manipulator) { return manipulator->getWorldName(); } Name Manager::getWorldChildName(OM_MANAGER::Manipulator *manipulator) { return manipulator->getWorldChildName(); } Pose Manager::getWorldPose(OM_MANAGER::Manipulator *manipulator) { return manipulator->getWorldPose(); } Vector3f Manager::getWorldPosition(OM_MANAGER::Manipulator *manipulator) { return manipulator->getWorldPosition(); } Matrix3f Manager::getWorldOrientation(OM_MANAGER::Manipulator *manipulator) { return manipulator->getWorldOrientation(); } State Manager::getWorldState(OM_MANAGER::Manipulator *manipulator) { return manipulator->getWorldState(); } VectorXf Manager::getWorldVelocity(OM_MANAGER::Manipulator *manipulator) { return manipulator->getWorldVelocity(); } VectorXf Manager::getWorldAcceleration(OM_MANAGER::Manipulator *manipulator) { return manipulator->getWorldAcceleration(); } std::map<Name, Component> Manager::getAllComponent(OM_MANAGER::Manipulator *manipulator) { return manipulator->getAllComponent(); } std::map<Name, Component>::iterator Manager::getIteratorBegin(OM_MANAGER::Manipulator *manipulator) { return manipulator->getIteratorBegin(); } std::map<Name, Component>::iterator Manager::getIteratorEnd(OM_MANAGER::Manipulator *manipulator) { return manipulator->getIteratorEnd(); } Component Manager::getComponent(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponent(name); } Name Manager::getComponentParentName(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentParentName(name); } std::vector<Name> Manager::getComponentChildName(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentChildName(name); } Pose Manager::getComponentPoseToWorld(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentPoseToWorld(name); } Vector3f Manager::getComponentPositionToWorld(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentPositionToWorld(name); } Matrix3f Manager::getComponentOrientationToWorld(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentOrientationToWorld(name); } State Manager::getComponentStateToWorld(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentStateToWorld(name); } VectorXf Manager::getComponentVelocityToWorld(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentVelocityToWorld(name); } VectorXf Manager::getComponentAccelerationToWorld(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentAccelerationToWorld(name); } Pose Manager::getComponentRelativePoseToParent(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentRelativePoseToParent(name); } Vector3f Manager::getComponentRelativePositionToParent(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentRelativePositionToParent(name); } Matrix3f Manager::getComponentRelativeOrientationToParent(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentRelativeOrientationToParent(name); } Joint Manager::getComponentJoint(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentJoint(name); } int8_t Manager::getComponentJointId(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentJointId(name); } float Manager::getComponentJointCoefficient(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentJointCoefficient(name); } Vector3f Manager::getComponentJointAxis(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentJointAxis(name); } float Manager::getComponentJointAngle(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentJointAngle(name); } std::vector<float> Manager::getAllJointAngle(OM_MANAGER::Manipulator *manipulator) { std::vector<float> joint_angle = manipulator->getAllJointAngle(); return joint_angle; } std::vector<float> Manager::getAllActiveJointAngle(OM_MANAGER::Manipulator *manipulator) { std::vector<float> joint_angle = manipulator->getAllActiveJointAngle(); return joint_angle; } float Manager::getComponentJointVelocity(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentJointVelocity(name); } float Manager::getComponentJointAcceleration(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentJointAcceleration(name); } Tool Manager::getComponentTool(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentTool(name); } int8_t Manager::getComponentToolId(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentToolId(name); } float Manager::getComponentToolCoefficient(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentToolCoefficient(name); } bool Manager::getComponentToolOnOff(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentToolOnOff(name); } float Manager::getComponentToolValue(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentToolValue(name); } float Manager::getComponentMass(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentMass(name); } Matrix3f Manager::getComponentInertiaTensor(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentInertiaTensor(name); } Vector3f Manager::getComponentCenterOfMass(OM_MANAGER::Manipulator *manipulator, Name name) { return manipulator->getComponentCenterOfMass(name); } std::vector<uint8_t> Manager::getAllActiveJointID(OM_MANAGER::Manipulator *manipulator) { return manipulator->getAllActiveJointID(); }
32.051546
185
0.748874
[ "vector" ]
fefd375c5a834313559bd3f5b415683b64af47a4
129,119
cpp
C++
t2_dll_hook_client/dll_czitin_hook/main.cpp
kubpica/T2KubsMod
bb7b25256ab1c449b085d999e9d9c1234b18cc27
[ "MIT" ]
4
2022-02-25T00:35:54.000Z
2022-03-10T20:36:03.000Z
t2_dll_hook_client/dll_czitin_hook/main.cpp
kubpica/T2KubsMod
bb7b25256ab1c449b085d999e9d9c1234b18cc27
[ "MIT" ]
null
null
null
t2_dll_hook_client/dll_czitin_hook/main.cpp
kubpica/T2KubsMod
bb7b25256ab1c449b085d999e9d9c1234b18cc27
[ "MIT" ]
null
null
null
//player #include <windows.h> #include <detours.h> #pragma comment (lib, "detours.lib") #include <iostream> #include <cstring> #include <string> #include <map> #include <sstream> #include <iomanip> #include <list> #include <Winbase.h> #include <stdlib.h> #include <time.h> #include <random> #include <chrono> #include <thread> #include <future> #include <algorithm> #include <fstream> #include "md5.h" #include <ctime> #include <stdio.h> #define CURL_STATICLIB #include "curl/curl.h" #include <iterator> //#include <cstdlib> //#include "sha256.h" #ifdef _DEBUG # define Debug(fmtstr, ...) printf(fmtstr, ##__VA_ARGS__) #pragma comment (lib, "curl/libcurl_a_debug.lib") #else //# define Debug(fmtstr, ...) #pragma comment (lib, "curl/libcurl_a.lib") #endif using namespace std; //#define ADDRESS 0x48AE90 //This is the address where our targeted function begins #define ADDRESS 0x48A7A0 //48A7A0 int myid = -1; map<int, int> frezeI; map<int, float> frezeF; map<int, string> frezeS; map<int, float> observe; map<int, float> observef; map<int, float> customDamage; map<int, float> customNode; map<string, list<pair<int, int>>> customDrop; map<int, list<pair<int, int>>> customPickup; map<int, int> customPchance; map<int, int> extraAmmo; bool czy_wyslane_join = false; map<int, int>::iterator it; list<string> dowyslania; list<string> commands; list<string> polecenia; vector<string> startingWeapons; vector<string> turokWeapons; vector<string> adonWeapons; vector<string> gantWeapons; vector<string> fleshWeapons; vector<string> purWeapons; vector<string> endWeapons; vector<string> fireWeapons; vector<string> iggyWeapons; vector<string> campWeapons; vector<string> telWeapons; map<int, string> charMOTD; char charek; std::list<string>::iterator iter; char * writable; byte dataz[] = { 0x00, 0x10, 0xFF, 0xFF }; //DWORD hackBaseAddress = {0x00000000}; DWORD hackOffsets[] = { 0x3d }; HMODULE hModule = GetModuleHandle(NULL); DWORD baseAddress = (DWORD)hModule + 0x00778550; bool czyWystartowano = false; //std::string lastcommand = " "; bool hideUnkCommandText = false; bool czyJoined = false; bool czyHostVoice = false; bool czy_sprawdzanie_voice = false; bool czy_blokada_specta = true; bool czy_unfreezeall = false; bool czy_unobserveall = false; bool czy_mozna_spect = true; bool czy_spectate_enabled = true; bool czy_setColor_enabled = false; bool czy_potwierdzenie_rejestracji = false; bool czy_zalogowany = false; bool czy_customDrops_enabled = false; //bool czy_arena = false; bool czy_ServerBotRequired = false; bool czy_ServerBot = false; bool czy_custom_damage = false; bool czy_customDrops_config = false; bool czy_customPickups_config = false; bool czy_customPickups_enabled = false; bool czy_customWeapons = false; bool czy_userBlackOil = true; bool czyInfoOil = false; int dchance = 25; //int pchance = 25; int licznik_komend = 0; std::string login; std::string password; //int ilenasekunde = 0; int status = 0; //0-observator 1-waiting4game 2-inGame bool pfmlayer = false; bool sunfirepod = false; bool czyPiorun = false; //int lokalizacja = 0; //int kierunek = 0; bool strzelRidingGun = false; bool strzel2 = false; bool strzel3 = false; bool strzel4 = false; bool strzel5 = false; bool strzelBlackOil = false; bool strzelAirStrike = false; bool razor = false; bool cbore = false; bool usypiacz = false; bool nuke = false; bool pistol = false; bool bow = false; bool tekbow = false; bool shotgun = false; int indmg1var2 = 0; int indmg1var3 = 0; bool stronaRidingGun = false; bool czyLastAmmo = false; bool czyinfo1 = false; bool czyinfo2 = false; bool czyinfo3 = false; bool czyinfo4 = false; bool czyinfoRazor = false; int czyinfoAirStrike = 0; int customWeaponId = 0; int airStrikeWith = 16; //torpedo int dinoRidingWith = 4; //chargeDart int blackOilWith = 5; //pistol bool czyTorpedoDisabledOnGround = false; int airStrikeDelay = 0; int airStrikeAmmoId = 18; //torpedo int airStrikeAmmoCost = 6; int howManyExtraNukeExplosions = 2; bool czyUserRazors = true; bool czyForceSpectNaStart = false; bool czyPobranoUstawienia = false; bool startingMaxAmmo = false; bool isTeamGameMode = false; string globalnick; string tid; float defaultDamage = -1; float defaultNode = -1; float currentfov = 0; string cfgurl = "null"; string adminPassword; string passedPassword; int(__cdecl* originalFunction)(const char *text); //Pointer to the function we are going to hook, must be declared same as original(returns double and takes double as argument) int(__cdecl* wysylaniehook)(char *text); //int __cdecl sub_4C3250(char *); int(__cdecl* wysylaniehook2)(int text1, int text2); //int __cdecl sub_48FC40(int, int) /*int(__cdecl* wysylaniehook3)(char *text1, int text2); //int __cdecl sub_4C30E0(char *, int); int(__cdecl* wysylaniehook4)(char *text1, char *text2); //int __cdecl sub_4A44D0(int, int) int(__cdecl* wysylaniehook5)(char *text); //int __cdecl sub_48A7A0(int) int(__cdecl* wysylaniehook6)(char *text); //int __cdecl sub_4A3140(int) int(__cdecl* wysylaniehook7)(char *text); //int __cdecl sub_471A30(int) int(__cdecl* wysylaniehook8)(char *text1, char *text2); //int __cdecl sub_4C9DC0(int, int)*/ int(__cdecl* SpectJoinHook)(int int1, int int2); //int __cdecl sub_485B00(int, int) int(__cdecl* startowaniehook)(); //int sub_4C0310() int(__cdecl* wydropienieBroniHook)(int var1, int var2, float var3); //int __cdecl sub_4261F0(float, int, float); int(__cdecl* podniesienieBroniHook)(int int1, int int2); //int __cdecl sub_480D80(int, int) int(__cdecl* strzal)(int var1, int var2); //int __cdecl sub_419260(float, float) int(__cdecl* damage)(int var1, int var2, int *var3, int *var4, int *var5); //int __cdecl sub_488000(int, int, int, int, int) damage int(__cdecl* indamage1)(int var1, int var2, int var3); //int __cdecl sub_419220(int, int, int) indamage1 //int(__cdecl* sfx)(__int16 var1); //int __cdecl sub_431FD0(__int16) realDzwiekCzatu //int(__cdecl* zmiananickuHook)(); //int sub_482220() int(__cdecl* TeamChangeHook)(int int1); //int __cdecl sub_485EB0(int) //int(__cdecl* zmianaKoloru)(int int1); //int __cdecl sub_486100(int) //int(__cdecl* preZmianaKoloru)(int int1, int int2); //int __cdecl sub_47FE00(int, int) //int __cdecl sub_4C4D30(int, int, int, int) //int __cdecl sub_4C6ED0(int, int) int(__cdecl* respawn)(int int1); //int __cdecl sub_425F50(int) int(__cdecl* changeChar)(int int1); //int __cdecl sub_4C9DC0(int, int) //int __cdecl sub_471A30(int) //int sub_482220() //int __cdecl sub_4C30E0(char *, int); //int __cdecl sub_4C3250(char *); //int __cdecl sub_48A7A0(int) //int __cdecl sub_4A44D0(int, int) //int __cdecl sub_4A3140(int) //int __cdecl sub_4A1ED0(int, int, int, int) //int sub_4A4C50() //int __cdecl sub_4BCBD0(HWND hDlg, int); typedef void(__cdecl* fcstr_)(char *text); fcstr_ wysylanie = (fcstr_)0x4C3250; //0x4A4C30 //typedef void(__cdecl* komunikat_)(char *text); fcstr_ komunikat = (fcstr_)0x48A7A0; typedef void(__cdecl* f1int_)(int int1); f1int_ zmianaKoloru = (f1int_)0x486100; typedef void(__cdecl* f2ints_)(int int1, int int2); f2ints_ preZmianaKoloru = (f2ints_)0x47FE00; //typedef void(__cdecl* SpectJoin_)(int int1, int int2); f2ints_ SpectJoin = (f2ints_)0x485B00; typedef void(__cdecl* f2ints1float_)(int var1, int var2, float var3); f2ints1float_ dropWeapon = (f2ints1float_)0x4261F0; typedef void(__cdecl* sfx_)(__int16 var1); sfx_ sfx = (sfx_)0x431FD0; typedef void(__cdecl* f1float_)(float float1); typedef void(__cdecl* f2floats_)(float float1, float float2); typedef void(__cdecl* fnoarg_)(); void WriteToMemory(void * addressToWrite, const void * valueToWrite, size_t byteNum) { //used to change our file access type, stores the old //access type and restores it after memory is written unsigned long OldProtection; //give that address read and write permissions and store the old permissions at oldProtection VirtualProtect(addressToWrite, byteNum, PAGE_EXECUTE_READWRITE, &OldProtection); //write the memory into the program and overwrite previous value memcpy(addressToWrite, valueToWrite, byteNum); //reset the permissions of the address back to oldProtection after writting memory VirtualProtect(addressToWrite, byteNum, OldProtection, NULL); } DWORD FindDmaAddy(int PointerLevel, DWORD Offsets[], DWORD BaseAddress) { //DEFINES OUR ADDRESS to write to //if statements are crucial to make sure that the address is valid to write //otherwise we crash. Address will not be valid when things like map changes or game loads are happening DWORD Ptr = *(DWORD*)(BaseAddress); //Base Address if (Ptr == 0) return NULL;//prevent crash //this is done to allow us to have pointers up to many levels e.g.10 for (int i = 0; i < PointerLevel; i++) { //if it = PointerLevel-1 then it reached the last element of the array //therefore check if that address plus the offset is valid and leave the loop if (i == PointerLevel - 1) { //!!make sure the last address doesnt have the asterisk on DWORD otherwise incoming crash Ptr = (DWORD)(Ptr + Offsets[i]); //Add the final offset to the pointer if (Ptr == 0) return NULL;//prevent crash //we here return early because when it hits the last element //we want to leave the loop, specially adapted for offsets of 1 return Ptr; } else { //if its just a normal offset then add it to the address Ptr = *(DWORD*)(Ptr + Offsets[i]); //Add the offsets if (Ptr == 0) return NULL;//prevent crash } } return Ptr; } void wyslij(string bigos) { if (bigos.find(" \x4/") == 0 && bigos.find("voice") == std::string::npos && bigos.find("gvoice") == std::string::npos) //czy znaleziono komende { string bigosmd5 = md5(bigos+" salt"); bigosmd5 = " h;" + bigosmd5; bigos += bigosmd5; } if(czy_ServerBot) dowyslania.push_back(bigos); } string zeranumer(int value, int digits = 2) { //const char * std::string result; while (digits-- > 0) { result += ('0' + value % 10); value /= 10; } std::reverse(result.begin(), result.end()); return result; //return result.c_str(); } void dodaj_customPickup(int main, int pick, int ammo) { if (customPickup.find(main) == customPickup.end()) { list<pair<int, int>> lista; customPickup[main] = lista; } auto it = customPickup.find(main); if (it != customPickup.end()) { std::list<pair<int, int>> *p = NULL; p = &(it->second); (*p).push_back(std::make_pair(pick, ammo)); //cout << "add cPick main: " << main << " pick: " << pick << " ammo: " << ammo << endl; } } void sendJoin() { czy_wyslane_join = true; std::mt19937 rnd(std::time(NULL)); std::uniform_real_distribution < double > dist(100, 999); //tu podajesz przedział myid = dist(rnd); std::stringstream ss; ss.str(""); ss << " \x4/99 join " << myid; wyslij(ss.str()); } void sprawdzNick() { //Sleep(500); string nick = (char*)0x00AD045C; char chars[] = "/:;\\"; //usuniecie tych znakow z nicku: for (unsigned int i = 0; i < strlen(chars); ++i) nick.erase(std::remove(nick.begin(), nick.end(), chars[i]), nick.end()); if (nick != globalnick && czyJoined) { globalnick = nick; std::stringstream ss; ss.str(""); ss << " \x4/99 cnick " << zeranumer(myid) << " " << nick; wyslij(ss.str()); } char * writable = new char[nick.size() + 1]; strcpy(writable, nick.c_str()); WriteToMemory((LPVOID)0x00AD045C, writable, strlen(writable) + 1); delete[] writable; } void forcespect(bool czy_w4game, bool czy_custom_napis, string s) { int adres = 0x00AD03D8; int var = 4198400; WriteToMemory((LPVOID)adres, &var, sizeof(var)); //printf("komenda write adres Error Code: %i\n", GetLastError()); SpectJoin(0, 1); std::stringstream ss; if (czy_w4game) { if (!czy_custom_napis) s = "WAITING FOR GAME TO JOIN"; ss.str(""); ss << " \x4/99" << " wplay " << myid; wyslij(ss.str()); ss.str(""); ss << " \x4/99" << " cstatus " << status << " 1 " << myid; wyslij(ss.str()); status = 1; } else { if (!czy_custom_napis) s = "SPECTATOR ESC FOR OPTIONS"; ss.str(""); ss << " \x4/99" << " cstatus " << status << " 0 " << myid; wyslij(ss.str()); status = 0; } char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); WriteToMemory((LPVOID)0x0051B93C, writable, strlen(writable) + 1); delete[] writable; } int wykonanie_komendy(std::string & tekst, std::string szukanaFraza) { size_t znalezionaPozycja = tekst.find(szukanaFraza); //szukanie pozycji na ktorej jest komenda if (znalezionaPozycja == std::string::npos) //czy znaleziono komende { if (tekst.find(": /login ") != std::string::npos || tekst.find(": /register ") != std::string::npos) return 1; if (tekst.find(": ") < 17) sfx(300); return 0; //jezeli nie to return } polecenia.push_back(tekst); return 1; } bool isAdmin(){ string s = md5(passedPassword + " gdfhr3tyswenxld5knoirhwlk6ns"); if (s == adminPassword) { return true; } return false; } DWORD WINAPI wykonywanie_polecen(LPVOID lpParam) { bool czySprawdzanieLicznika = false; std::stringstream ss; int* czy_w_wodzie = (int*)0x00ADC09C; bool isDiving = false; while (!czyWystartowano) Sleep(500); while (true) { Sleep(16); //for (auto it = commands.begin(); it != commands.end(); it = commands.erase(it)) { //string tekst = *it; if (currentfov > 113) { //lock fov in water on 113 max if (isDiving && *czy_w_wodzie == 0) { float temp = currentfov * 0.017444445; WriteToMemory((LPVOID)0x00508380, &temp, 4); isDiving = false; } else if (!isDiving && *czy_w_wodzie) { float temp = 113 * 0.017444445; WriteToMemory((LPVOID)0x00508380, &temp, 4); isDiving = true; } } if (!polecenia.empty()) { string tekst = polecenia.front(); polecenia.pop_front(); //komunikat("polecenie"); //cout << "polecenie: " << tekst << endl; size_t znalezionaPozycja = tekst.find(": \x4/"); //szukanie pozycji na ktorej jest komenda //commands.push_back(tekst); int pozycja = znalezionaPozycja; //jezeli znaleziono to zapisuje na ktorej pozycji do { //std::cout << "Znak zostal odnaleziony na pozycji " << znalezionaPozycja << std::endl; znalezionaPozycja = tekst.find(": \x4/", znalezionaPozycja + 1); //sprawda czy jest jakas komenda dalej (znaki zaczynajace komende) if (znalezionaPozycja != std::string::npos) { //jezeli jest dalej to zapisuje pozycje tej dalszej pozycja = znalezionaPozycja; } else break; } while (znalezionaPozycja != std::string::npos); int adres; int var; //string nick = tekst.substr(0, pozycja); tekst = tekst.substr(pozycja); int toID = atoi(tekst.substr(4).c_str()); //cout << "toID: " << toID << endl; if (toID != myid && toID != 0) { //cout << "atoi: " << dec << atoi(tekst.substr(4).c_str()) << endl; //cout << "myid: " << dec << myid << endl; continue; } if (tekst.find("gvoice") == 7 && myid != -1) { ss.str(""); ss << " \x4/99" << " voice " << myid; wyslij(ss.str()); continue; } else { if (tekst.find(" h;") == std::string::npos) continue; string md5tocheck = tekst.substr(1, tekst.find(" h;") - 1); string md5recieved = tekst.substr(tekst.find(" h;") + 3); //cout << "md5tocheck: " << md5tocheck << endl; //cout << "md5recieved: " << md5recieved << endl; //cout << "licznik_komend: " << licznik_komend << endl; bool czy_dodano_licznik = false; ss.str(""); if (md5tocheck.find("rdy") != std::string::npos || md5tocheck.find("joined ") != std::string::npos || md5tocheck.find("setCount ") != std::string::npos || toID == 0) ss << md5tocheck << " salt"; else { czy_dodano_licznik = true; licznik_komend++; ss << md5tocheck << " salt" << licznik_komend; } md5tocheck = ss.str(); //cout << "md5tocheck2: " << md5tocheck << endl; md5tocheck = md5(md5tocheck); //cout << "md5check: " << md5tocheck << endl; if (md5tocheck != md5recieved) { //cout << "sumcheck sie nie zgadza!! anuluje funkcje!" << endl; if (czy_dodano_licznik && !czySprawdzanieLicznika) { czySprawdzanieLicznika = true; licznik_komend--; cout << "!!! Command does not fit! Canceling..." << endl; cout << "Canceled command: " << tekst << endl; ss.str(""); ss << " \x4/99 checkCount " << dec << zeranumer(myid) << " " << licznik_komend; wyslij(ss.str()); } continue; } tekst = tekst.substr(0, tekst.find(" h;")); } //cout << "substr(7); " << tekst.substr(7) << endl; if (tekst.find("write") == 7) { //cout << "write" << endl; //cout << tekst.substr(15) << endl; // 15 11 // write 500 0x00 adres = (int)strtol(tekst.substr(15).c_str(), NULL, 0); //cout << hex << adres << endl; //cout << tekst.substr(26) << endl; string subtekst = tekst.substr(13); if (subtekst.find("i") == 0) { int var = atoi(tekst.substr(26).c_str()); //cout << dec << var << endl << endl; WriteToMemory((LPVOID)adres, &var, sizeof(var)); //printf("komenda write adres Error Code: %i\n", GetLastError()); } else if (subtekst.find("f") == 0) { float var = atof(tekst.substr(26).c_str()); //cout << dec << var << endl << endl; WriteToMemory((LPVOID)adres, &var, sizeof(var)); //printf("komenda write adres Error Code: %i\n", GetLastError()); } else if (subtekst.find("t") == 0 || subtekst.find("b") == 0 || subtekst.find("s") == 0) { std::string s = tekst.substr(26).c_str(); WriteToMemory((void*)adres, s.c_str(), s.size()); } continue; } if (tekst.find("read") == 7) { //cout << "read" << endl; //cout << tekst.substr(12) << endl; // 15 11 // write 500 0x00 adres = (int)strtol(tekst.substr(12).c_str(), NULL, 0); //cout << hex << adres << endl; //cout << tekst.substr(23) << endl; //var = atoi(tekst.substr(23).c_str()); //cout << dec << var << endl << endl; // ReadProcessMemory(proc, (void*)adres, &var, sizeof(var), NULL); var = *((int*)adres); ss.str(""); ss << " \x4/99" << " return " << hex << "0x" << std::setfill('0') << std::setw(8) << adres << " " << dec << zeranumer(myid) << " " << var; wyslij(ss.str()); continue; } if (tekst.find("freeze") == 7) { //cout << "freeze" << endl; //cout << tekst.substr(16) << endl; // 15 11 // write 500 0x00 adres = (int)strtol(tekst.substr(16).c_str(), NULL, 0); //cout << hex << adres << endl; //cout << tekst.substr(27) << endl; string subtekst = tekst.substr(14); if (subtekst.find("i") == 0) { int var = atoi(tekst.substr(27).c_str()); //cout << dec << var << endl << endl; //VirtualProtect((LPVOID)(adres), sizeof(var), PAGE_EXECUTE_READWRITE, 0); frezeI[adres] = var; } else if (subtekst.find("f") == 0) { int var = atof(tekst.substr(27).c_str()); //cout << dec << var << endl << endl; //VirtualProtect((LPVOID)(adres), sizeof(var), PAGE_EXECUTE_READWRITE, 0); frezeF[adres] = var; } else if (subtekst.find("t") == 0 || subtekst.find("b") == 0 || subtekst.find("s") == 0) { string s = tekst.substr(27).c_str(); //cout << dec << s << endl << endl; //VirtualProtect((LPVOID)(adres), sizeof(s), PAGE_EXECUTE_READWRITE, 0); frezeS[adres] = s; } continue; } if (tekst.find("rfreeze") == 7) { //cout << "rfreeze" << endl; //cout << tekst.substr(15) << endl; // 15 11 // write 500 0x00 adres = (int)strtol(tekst.substr(15).c_str(), NULL, 0); //cout << hex << adres << endl; //cout << tekst.substr(26) << endl; //var = atoi(tekst.substr(26).c_str()); //cout << dec << var << endl << endl; if (frezeI.count(adres)>0) frezeI.erase(adres); if (frezeF.count(adres)>0) frezeF.erase(adres); if (frezeS.count(adres)>0) frezeS.erase(adres); continue; } if (tekst.find("observe") == 7) { //cout << "observe" << endl; //cout << tekst.substr(15) << endl; // 15 11 // write 500 0x00 adres = (int)strtol(tekst.substr(15).c_str(), NULL, 0); //cout << hex << adres << endl; bool czy_read; //cout << "czy read: " << tekst.substr(26) << endl; czy_read = atoi(tekst.substr(26).c_str()); bool czy_eventf; //when true: returns event only when variable is = to some var (not always when changed) //cout << "czy eventf: " << tekst.substr(28) << endl; czy_eventf = atoi(tekst.substr(28).c_str()); if (czy_eventf) { float compareto = atof(tekst.substr(30).c_str()); observef[adres] = compareto; } else { float var = *((int*)adres); //if (observe.count(adres)>0) // observe.erase(adres); observe[adres] = var; } if (czy_read) { ss.str(""); //ss << " //" << zeranumer(myid) << " event " << hex << "0x" << std::setfill ('0') << std::setw (8) << adres << " 0 " << dec << var; ss << " \x4/99" << " event " << hex << "0x" << std::setfill('0') << std::setw(8) << adres << " 0 " << dec << zeranumer(myid) << " " << var; wyslij(ss.str()); } continue; } if (tekst.find("robserve") == 7) { //cout << "robserve" << endl; //cout << tekst.substr(16) << endl; // 15 11 // write 500 0x00 adres = (int)strtol(tekst.substr(16).c_str(), NULL, 0); //cout << hex << adres << endl; //cout << tekst.substr(27) << endl; //var = atoi(tekst.substr(27).c_str()); //cout << dec << var << endl << endl; if (observe.count(adres)>0) observe.erase(adres); if (observef.count(adres)>0) observef.erase(adres); continue; } if (tekst.find("unfreezeall") == 7) { //freze.clear(); czy_unfreezeall = true; continue; } if (tekst.find("unobserveall") == 7) { //observe.clear(); czy_unobserveall = true; continue; } if (tekst.find("news") == 7) { string s = tekst.substr(12).c_str(); char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable; if (tekst.find("news You logged in successfully.") == 7) { czy_zalogowany = true; } continue; } if (tekst.find("voice") == 7) { //int id = atoi(tekst.substr(13).c_str()); czyHostVoice = true; continue; } //cout << "tekst.find(\"play\"): " << tekst.find("play") << endl; //cout << "substr(7): " << tekst.substr(7) << endl; if (tekst.find("play") == 7) { //cout << "play" << endl; czy_mozna_spect = true; czy_blokada_specta = false; ss.str(""); ss << " \x4/99" << " cstatus " << status << " 2 " << myid; wyslij(ss.str()); status = 2; SpectJoin(1, 0); //SpectJoinHook(1, 0); string bigozz = "FAILED TO JOIN??"; char * writable = new char[bigozz.size() + 1]; strcpy(writable, bigozz.c_str()); WriteToMemory((LPVOID)0x0051B93C, writable, strlen(writable) + 1); delete[] writable; continue; } if (tekst.find("respawn") == 7) { SpectJoin(1, 0); ss.str(""); ss << " \x4/99" << " cstatus " << status << " 2 " << myid; wyslij(ss.str()); status = 2; continue; } if (tekst.find("forcespect") == 7) { bool czy_w4game = atoi(tekst.substr(18).c_str()); bool czy_custom_napis = atoi(tekst.substr(20).c_str()); string s; if (czy_custom_napis) s = tekst.substr(22).c_str(); forcespect(czy_w4game, czy_custom_napis, s); continue; } if (tekst.find("callf") == 7) { adres = (int)strtol(tekst.substr(16).c_str(), NULL, 0); string subtekst = tekst.substr(13); if (subtekst.find("na") == 0) { fnoarg_ func = (fnoarg_)adres; func(); } else if (subtekst.find("i1") == 0) { int var = 0; if (tekst.find("(") != std::string::npos) { subtekst = tekst.substr(tekst.find("(") + 1); //tekst.substr(27); subtekst = subtekst.substr(0, tekst.find(")")); var = atoi(subtekst.c_str()); } //cout << "callf i1 var: " << var << endl; f1int_ func = (f1int_)adres; func(var); } else if (subtekst.find("i2") == 0) { int var1 = 0; int var2 = 0; if (tekst.find("(") != std::string::npos) { subtekst = tekst.substr(tekst.find("(") + 1); //tekst.substr(27); subtekst = subtekst.substr(0, tekst.find(",")); var1 = atoi(subtekst.c_str()); if (tekst.find(",") != std::string::npos) { subtekst = tekst.substr(tekst.find(",") + 1); subtekst = subtekst.substr(0, tekst.find(")")); var2 = atoi(subtekst.c_str()); } } //cout << "callf i2 var1: " << var1 << " var2 : " << var2 << endl; f2ints_ func = (f2ints_)adres; func(var1, var2); } else if (subtekst.find("f1") == 0) { float var = 0; if (tekst.find("(") != std::string::npos) { subtekst = tekst.substr(tekst.find("(") + 1); //tekst.substr(27); subtekst = subtekst.substr(0, tekst.find(")")); var = atof(subtekst.c_str()); } f1float_ func = (f1float_)adres; func(var); } else if (subtekst.find("f2") == 0) { float var1 = 0; float var2 = 0; if (tekst.find("(") != std::string::npos) { subtekst = tekst.substr(tekst.find("(") + 1); //tekst.substr(27); subtekst = subtekst.substr(0, tekst.find(",")); var1 = atof(subtekst.c_str()); if (tekst.find(",") != std::string::npos) { subtekst = tekst.substr(tekst.find(",") + 1); subtekst = subtekst.substr(0, tekst.find(")")); var2 = atof(subtekst.c_str()); } } f2floats_ func = (f2floats_)adres; func(var1, var2); } else if (subtekst.find("cs") == 0) { int var = 0; if (tekst.find("(") != std::string::npos) { subtekst = tekst.substr(tekst.find("(") + 1); //tekst.substr(27); subtekst = subtekst.substr(0, tekst.find(")")); } char * writable = new char[subtekst.size() + 1]; strcpy(writable, subtekst.c_str()); fcstr_ func = (fcstr_)adres; func(writable); delete[] writable; } continue; } if (tekst.find("joined") == 8 && czy_wyslane_join) { //cout << "joined" << endl; //cout << tekst.substr(15) << endl; // 15 11 // write 500 0x00 myid = atoi(tekst.substr(15).c_str()); czyJoined = true; czy_blokada_specta = false; ss.str(""); ss << " \x4/99" << " cstatus 0 " << status << " " << myid; wyslij(ss.str()); ss.str(""); ss << " \x4/99" << " stid " << zeranumer(myid) << " " << tid; wyslij(ss.str()); string bigozz = "SPECTATOR ESC FOR OPTIONS"; char * writable = new char[bigozz.size() + 1]; strcpy(writable, bigozz.c_str()); WriteToMemory((LPVOID)0x0051B93C, writable, strlen(writable) + 1); delete[] writable; if (status == 0) komunikat("Successfully connected to server bot! Click Esc to join."); else komunikat("Successfully connected to server bot!"); globalnick = (char*)0x00AD045C; continue; } if (tekst.find("command") == 7) { string s = tekst.substr(15).c_str(); commands.push_back(s); //commands.unique(); continue; } if (tekst.find("cdamage") == 7) { //czy_custom_damage = true; int weapon = atoi(tekst.substr(15).c_str()); float damage = atof(tekst.substr(18).c_str()); if (weapon == 0) defaultDamage = damage; else customDamage[weapon] = damage; continue; } if (tekst.find("cnode") == 7) { //czy_custom_damage = true; int weapon = atoi(tekst.substr(13).c_str()); float node = atof(tekst.substr(16).c_str()); if (weapon == 0) defaultNode = node; else customNode[weapon] = node; continue; } if (tekst.find("cdrop") == 7) { czy_customDrops_config = true; string map = tekst.substr(13, tekst.find(", ")-13); int weapon = atoi(tekst.substr(tekst.find(", ")+2).c_str()); int time = atoi(tekst.substr(tekst.find(", ") + 5).c_str()); if (customDrop.find(map) == customDrop.end()) { list<pair<int, int>> lista; customDrop[map] = lista; } auto it = customDrop.find(map); if (it != customDrop.end()) { std::list<pair<int, int>> *p = NULL; p = &(it->second); (*p).push_back(std::make_pair(weapon, time)); //cout << "cdrop map: " << map << " weapon: " << weapon << " time: " << time << endl; } //customDrop[map] = std::make_pair(weapon, time); continue; } if (tekst.find("cpick") == 7) { if (!czy_customPickups_config) { czy_customPickups_config = true; customPickup.clear(); customPchance.clear(); extraAmmo.clear(); } int pred = atoi(tekst.substr(13).c_str()); int pick = atoi(tekst.substr(16).c_str()); int ammo = atoi(tekst.substr(19).c_str()); dodaj_customPickup(pred, pick, ammo); continue; } if (tekst.find("cwcfg") == 7) { int i = atoi(tekst.substr(13).c_str()); int var = atoi(tekst.substr(16).c_str()); if (i == 1) { czyTorpedoDisabledOnGround = var; } else if (i == 2) { howManyExtraNukeExplosions = var; } else if (i == 3) { airStrikeAmmoId = var; } else if (i == 4) { airStrikeAmmoCost = var; } else if (i == 5) { blackOilWith = var; } else if (i == 6) { dinoRidingWith = var; } else if (i == 7) { airStrikeWith = var; } else if (i == 8) { airStrikeDelay = var; } continue; } if (tekst.find("dchance") == 7) { //cout << "dchance tekst.substr(15).c_str(): " << tekst.substr(15).c_str() << endl; dchance = atoi(tekst.substr(15).c_str()); continue; } if (tekst.find("pchance") == 7) { //cout << "pchance tekst.substr(15).c_str(): " << tekst.substr(15).c_str() << endl; //cout << "pchance tekst.substr(18).c_str(): " << tekst.substr(18).c_str() << endl; customPchance[atoi(tekst.substr(15).c_str())] = atoi(tekst.substr(18).c_str()); continue; } if (tekst.find("pammo") == 7) { //cout << "pammo tekst.substr(13).c_str(): " << tekst.substr(13).c_str() << endl; //cout << "pammo tekst.substr(16).c_str(): " << tekst.substr(16).c_str() << endl; extraAmmo[atoi(tekst.substr(13).c_str())] = atoi(tekst.substr(16).c_str()); continue; } if (tekst.find("checknick") == 7) { sprawdzNick(); continue; } if (tekst.find("rdy") == 7 && !czyJoined) { if (czy_ServerBotRequired) { string bigozz = "CONNECTING TO SERVER BOT"; char * writable = new char[bigozz.size() + 1]; strcpy(writable, bigozz.c_str()); WriteToMemory((LPVOID)0x0051B93C, writable, strlen(writable) + 1); delete[] writable; } sendJoin(); //else wyslij(" \x4/99 block"); continue; } if (tekst.find("blspect") == 7) { czy_mozna_spect = false; continue; } if (tekst.find("unblspect") == 7) { czy_mozna_spect = true; continue; } if (tekst.find("setCount") == 7) { int liczbaKomend = atoi(tekst.substr(16).c_str()); licznik_komend = liczbaKomend; polecenia.clear(); forcespect(false, true, "Temporarily lost connection"); forcespect(true, true, "Temporarily lost connection. Joining..."); komunikat("Lost connection with bot. Reconnecting..."); czySprawdzanieLicznika = false; if (!czyPobranoUstawienia) { ss.str(""); ss << " \x4/99 sresend " << dec << zeranumer(myid); wyslij(ss.str()); } continue; } if (tekst.find("sdone") == 7) { czyPobranoUstawienia = true; continue; } //cout << "doszlo do konca znalezionaPozycja: " << znalezionaPozycja << endl; } } return S_OK; } /*Our modified function code that is going to be executed before continuing to the code of original function*/ int hookedFunction(char *text) { if (wykonanie_komendy((string)text, ": \x4/")) { //if( comand.find( ": //" ) != std::string::npos ){ //czy znaleziono komende //wykonanie_komendy( comand, ": //" ); return 0; } else { if (hideUnkCommandText) { string comand = text; if (comand.find("unrecognized command: ") == 0 || comand.find("UNKNOWN VARIABLE ") == 0 || comand.find("OUT OF RANGE: ") == 0 || comand.find("set level command only ") == 0) { hideUnkCommandText = false; return 0; } } } cout << text << endl; int zwrotek = originalFunction(text); //cout << "zwrotek1: " << zwrotek << endl; return zwrotek; //before returning to normal execution of function } int hookedFunction2(char *text) { //cout << "hookedFunction2" << endl; //cout << "hF2 text: " << text << endl; int zwrot = wysylaniehook(text); if (text[0] != ' ' || text[1] == '/') { std::stringstream ss; //cout << "tak to komenda" << endl; string command = text; //cout << "komenda: " << command << endl; //bool czy_return_zero = false; if (text[1] == '/') { command = command.substr(2); //czy_return_zero = true; } hideUnkCommandText = true; if (command.find("set weaponfov ") == 0) { if(command.length()<16) komunikat("You entered the wrong variable (Valid range is 10-90)."); else { float var = atof(command.substr(14).c_str()); //cout << "var: " << var << " substr: " << command.substr(14).c_str() << endl; if (var < 10 || var>90) { komunikat("You entered the wrong variable (Valid range is 10-90)."); } else { WriteToMemory((LPVOID)0x00523E5C, &var, 4); } } } else if (command.find("set camerafov ") == 0) { if (command.length()<16) komunikat("You entered the wrong variable (Valid range is 30-90)."); else { float var = atof(command.substr(14).c_str()); //cout << "var: " << var << " substr: " << command.substr(14).c_str() << endl; if (var < 30 || var>135) { komunikat("You entered the wrong variable (Valid range is 30-135)."); } else { currentfov = var; if (var >= 90) { if (var > 90) komunikat("Warning! FOV over 90 may be bugged!"); if (var > 113 && *((int*)0x00ADC09C)) var = 113; var *= 0.017444445; WriteToMemory((LPVOID)0x00508380, &var, 4); var = 90; } WriteToMemory((LPVOID)0x106FD408, &var, 4); } } } else if (command.find("fov ") == 0) { if (command.length()<6) komunikat("You entered the wrong variable (Valid range is 30-90)."); else { float var = atof(command.substr(4).c_str()); //cout << "var: " << var << " substr: " << command.substr(8).c_str() << endl; if (var < 30 || var>135) { komunikat("You entered the wrong variable (Valid range is 30-135)."); } else { currentfov = var; float camerafov = var; float weaponfov = var * 0.714285714; if (var >= 90) { if (var > 90) komunikat("Warning! FOV over 90 may be bugged!"); if (var > 113 && *((int*)0x00ADC09C)) camerafov = 113; camerafov = camerafov * 0.017444445; WriteToMemory((LPVOID)0x00508380, &camerafov, 4); camerafov = 90; } if (weaponfov > 90) weaponfov = 90; WriteToMemory((LPVOID)0x106FD408, &camerafov, 4); WriteToMemory((LPVOID)0x00523E5C, &weaponfov, 4); ss.str(""); ss << "camerafov has been set to " << var << " and weaponfov to " << weaponfov; char * writable = new char[ss.str().size() + 1]; strcpy(writable, ss.str().c_str()); komunikat(writable); delete[] writable; komunikat("You can use separate commands: \'set weaponfov\' and \'set camerafov\'"); } } } else if (command.find("set fov ") == 0) { if (command.length()<10) komunikat("You entered the wrong variable (Valid range is 30-90)."); else { float var = atof(command.substr(8).c_str()); //cout << "var: " << var << " substr: " << command.substr(8).c_str() << endl; if (var < 30 || var>135) { komunikat("You entered the wrong variable (Valid range is 30-135)."); } else { currentfov = var; float camerafov = var; float weaponfov = var * 0.714285714; if (var >= 90) { if (var > 90) komunikat("Warning! FOV over 90 may be bugged!"); if (var > 113 && *((int*)0x00ADC09C)) camerafov = 113; camerafov = var * 0.017444445; WriteToMemory((LPVOID)0x00508380, &camerafov, 4); camerafov = 90; } if (var > 90) weaponfov = 90; WriteToMemory((LPVOID)0x106FD408, &camerafov, 4); WriteToMemory((LPVOID)0x00523E5C, &weaponfov, 4); komunikat("You can use separate commands: \'set weaponfov\' and \'set camerafov\'"); komunikat("You can use shorter command, just: \'fov\'"); } } } else if (command.find("set level ") == 0) { if (command.length()<11) komunikat("You entered the wrong variable."); else { int var = atoi(command.substr(10).c_str()); //cout << "var: " << var << " substr: " << command.substr(8).c_str() << endl; if (var < 0 || var>99) { komunikat("You entered the wrong variable (Valid range is 0-99)."); } else { ss.str(""); ss << " \x4/99 changelvl " << dec << zeranumer(myid) << " " << dec << var; wyslij(ss.str()); //komunikat("set level 300"); } } } /*else if (command.find("drop weapon ") == 0) { if (command.length()<12) komunikat("You entered the wrong variable."); else { int var = atoi(command.substr(11).c_str()); //cout << "var: " << var << " substr: " << command.substr(8).c_str() << endl; if (var < -99 || var>99) { komunikat("You entered the wrong variable (Valid range is 0-34)."); } else { dropWeapon(0x106d1250, var, 20000); //dropWeapon(0x106d25a8, var, 20000); } } }*/ else if (command.compare("spectate") == 0 || command.compare("observe") == 0) { if (czy_mozna_spect && czy_spectate_enabled && status!=0) { string bigozz = "SPECTATOR ESC FOR OPTIONS"; char * writable = new char[bigozz.size() + 1]; strcpy(writable, bigozz.c_str()); WriteToMemory((LPVOID)0x0051B93C, writable, strlen(writable) + 1); delete[] writable; ss.str(""); ss << " \x4/99" << " cstatus " << status << " 0 " << myid; wyslij(ss.str()); status = 0; strzal(0x106d1250, 209); int adres = 0x00AD03D8; int var = 4198400; WriteToMemory((LPVOID)adres, &var, sizeof(var)); //printf("komenda write adres Error Code: %i\n", GetLastError()); SpectJoin(0, 1); char frags = *((char*)0x00AD0470); short pain = *((short*)0x00AD0472); frags -= 1; pain -= 100; if (frags < 0 || frags > 100) frags = 0; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (pain < 0) pain = 0; //cout << "frags: " << frags << endl; //cout << "pain: " << pain << endl; WriteToMemory((LPVOID)0x00AD0470, &frags, 1); WriteToMemory((LPVOID)0x00AD0472, &pain, 2); //czy_blokada_specta = true; ss.str(""); ss << " \x4/99" << " eventf " << "-1 1 " << dec << zeranumer(myid) << " " << 1; wyslij(ss.str()); } else if(!czy_spectate_enabled) komunikat("This command is disabled on this server."); else komunikat("You can't go into observer mode right now."); } else if (command.find("set color ") == 0) { if (command.length()<11) komunikat("You entered the wrong variable (Valid range is 0-8)."); else { if (czy_setColor_enabled) { int var = -1; var = atoi(command.substr(10).c_str()); if (var >= 0 && var <= 8) { //if (var == 0) var = 4294967295; //elsevar--; /* WriteToMemory((LPVOID)0x106D25A4, &var, sizeof(var)); printf("komenda set color Error Code: %i\n", GetLastError());*/ //cout << "color var przed: " << var << endl; //cout << "color var po: " << (275579872 + var * 40) << endl; int var2 = 275579296; preZmianaKoloru( (275579872 + var * 40) ,var2); var--; zmianaKoloru(var); } else { komunikat("You entered the wrong variable (Valid range is 0-8)."); komunikat("0-none 1-red 2-blue 3-green 4-yellow 5-purple 6-cyan 7-brown 8-turquoise"); } } else komunikat("Set color command is disabled on this server."); } } else if (command.compare("set color") == 0) { komunikat("0-none 1-red 2-blue 3-green 4-yellow 5-purple 6-cyan 7-brown 8-turquoise"); } else if (command.compare("oil") == 0) { if (czy_userBlackOil) { czy_userBlackOil = false; komunikat("Generation of black oil canceled. (You still will see oil produced by other players)"); } else { czy_userBlackOil = true; komunikat("Generation of black oil resumed."); } } else if (command.compare("razor") == 0) { if (czyUserRazors) { czyUserRazors = false; komunikat("Enemy razor efect has been disabled."); } else { czyUserRazors = true; komunikat("Enemy razor efect has been resumed."); } } else if (command.find("login ") == 0) { if (command.length()<14) komunikat("Correct use: login your_nickname your_password"); else { if (czy_zalogowany) { komunikat("You are already logged in."); } else { string login = command.substr(6); string password = login.substr(login.find(" ") + 1); login = login.substr(0, login.find(" ")); //cout << "login: " << login << " password: " << password << endl; string md5pass = md5(password); //cout << "md5 of '" << password << "': " << md5pass << endl; char chars[] = "\\/:*?\"<>|."; //usuniecie tych znakow z loginu: for (unsigned int i = 0; i < strlen(chars); ++i) login.erase(std::remove(login.begin(), login.end(), chars[i]), login.end()); ss.str(""); ss << " \x4/99 login " << dec << zeranumer(myid) << " " << login << " " << md5pass; wyslij(ss.str()); } } } else if (command.compare("login") == 0) { komunikat("Correct use: login your_nickname your_password"); } else if (command.find("register ") == 0) { if (command.length()<12) komunikat("Correct use: register nickname_you_want password_you_want"); else { if (czy_zalogowany) { komunikat("Please use only one account."); } else { string loginR = command.substr(9); //cout << "loginR: " << loginR << endl; password = loginR.substr(loginR.find(" ") + 1); login = loginR.substr(0, loginR.find(" ")); char chars[] = "\\/:*?\"<>|."; //usuniecie tych znakow z loginu: for (unsigned int i = 0; i < strlen(chars); ++i) login.erase(std::remove(login.begin(), login.end(), chars[i]), login.end()); if (login.length() > 16) komunikat("This nickname is too long! Max length is 16 chars."); else if (login.length() < 3) komunikat("This nickname is too short! Min length is 3 chars."); else if (password.length() > 20) komunikat("This password is too long! Max length is 20 chars."); else if (password.length() < 6) komunikat("This password is too short! Min length is 6 chars."); else { ss.str(""); ss << "Do you want to create account with nickname '" << dec << login << "' and password '" << password << "'?"; string s = ss.str(); char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); komunikat("Type 'yes' to confirm."); delete[] writable; czy_potwierdzenie_rejestracji = true; } } } } else if (command.compare("register") == 0) { komunikat("Correct use: register nickname_you_want password_you_want"); } else if ( (command.compare("yes") == 0 || command.compare("YES") == 0) && czy_potwierdzenie_rejestracji ) { czy_potwierdzenie_rejestracji = false; //cout << "login: " << login << " password: " << password << endl; string md5pass = md5(password); //cout << "md5 of '" << password << "': " << md5pass << endl; ss.str(""); ss << " \x4/99 register " << dec << zeranumer(myid) << " " << login << " " << md5pass; wyslij(ss.str()); } else if (command.find("kick ") == 0) { if (command.length()<6) komunikat("Correct use: kick player_id (type 'players' to get IDs)"); else { int id = atoi(command.substr(5).c_str()); ss.str(""); ss << " \x4/99 kick " << dec << zeranumer(myid) << " " << dec << id; wyslij(ss.str()); } } else if (command.compare("kick") == 0) { komunikat("Correct use: kick player_id (type 'players' to get IDs)"); } else if (command.find("ban ") == 0) { if (command.length()<5) komunikat("Correct use: ban player_id (type 'players' to get IDs)"); else { int id = atoi(command.substr(4).c_str()); ss.str(""); ss << " \x4/99 ban " << dec << zeranumer(myid) << " " << dec << id; wyslij(ss.str()); } } else if (command.compare("ban") == 0) { komunikat("Correct use: ban player_id (type 'players' to get IDs)"); } else if (command.compare("logins") == 0) { ss.str(""); ss << " \x4/99 idloginlist " << dec << zeranumer(myid); wyslij(ss.str()); } else if (command.compare("players") == 0) { ss.str(""); ss << " \x4/99 idlist " << dec << zeranumer(myid); wyslij(ss.str()); } else if (command.compare("pass ") == 0) { string passedPassword = command.substr(5).c_str(); } else if (command.compare("md5 ") == 0) { string s = command.substr(4).c_str(); s = md5(s + " gdfhr3tyswenxld5knoirhwlk6ns"); char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable; } else { hideUnkCommandText = false; //czy_return_zero = false; for (auto const& i : commands) { if (command.find(i) == 0) { /*if (command.size() > i.size() + 1) { int var = -1; var = atoi(command.substr(i.size() + 1).c_str()); cout << "custom commands var: " << var << endl; ss.str(""); ss << " \x4/99 cmd " << dec << zeranumer(myid) << " " << dec << var << " " << i; ss << " \x4/99 cmd " << dec << zeranumer(myid) << " " << command; wyslij(ss.str()); }*/ ss.str(""); ss << " \x4/99 cmd " << dec << zeranumer(myid) << " " << command; wyslij(ss.str()); if (text[0] != ' ') hideUnkCommandText = true; //if (text[1] == '/') czy_return_zero = true; } } } command = text; //cout << "komenda2: " << command << endl; if (text[1] == '/') { if (hideUnkCommandText) hideUnkCommandText = false; else komunikat("Command not found."); } //if (czy_return_zero) return 0; } //cout << "zwrot2: " << zwrot << endl; return zwrot; //return wysylaniehook(text); //return zwrot; } int hookedFunction3(int text1, int text2) { //ilenasekunde++; int zwrot = wysylaniehook2(text1, text2); //liczy ile znakow if (zwrot == 0 && !dowyslania.empty()) { string bigozz = dowyslania.front(); dowyslania.pop_front(); if (bigozz.length() != 0) { writable = new char[bigozz.size() + 1]; strcpy(writable, bigozz.c_str()); //std::copy(bigozz.begin(), bigozz.end(), writable); //writable[bigozz.size()] = '\0'; //cout << "Wysylanie: " << writable << endl; //02FF3C7D //WriteToMemory(0x02FF3C7D, writable, sizeof(writable)); DWORD adresik = FindDmaAddy(1, hackOffsets, baseAddress); //unsigned long OldProtection; WriteToMemory((LPVOID)(adresik - 4), &dataz, sizeof(dataz)); WriteToMemory((LPVOID)adresik, writable, strlen(writable) + 1); delete[] writable; //WriteToMemory( (LPVOID)0x02FF3C7D, &writable, sizeof(writable)); //0x00ADC88C } /*cout << "hookedFunction3" << endl; cout << "text1: " << text1 << endl; cout << "text2: " << text2 << endl;*/ //cout << "zwrot: " << zwrot << endl; //cout << "bigozz.size()+5: " << bigozz.size() + 5 << endl; return bigozz.size() + 5; } if (czy_unfreezeall) { frezeI.clear(); frezeF.clear(); frezeS.clear(); czy_unfreezeall = false; } else { for (auto it = frezeI.begin(); it != frezeI.end() && !czy_unfreezeall; it++) //for (auto const& p : freze) { WriteToMemory((LPVOID)it->first, &it->second, sizeof(it->second)); if (it == frezeI.end()) break; } for (auto it = frezeF.begin(); it != frezeF.end() && !czy_unfreezeall; it++) //for (auto const& p : freze) { WriteToMemory((LPVOID)it->first, &it->second, sizeof(it->second)); if (it == frezeF.end()) break; } for (auto it = frezeS.begin(); it != frezeS.end() && !czy_unfreezeall; it++) //for (auto const& p : freze) { WriteToMemory((LPVOID)it->first, it->second.c_str(), sizeof(it->second)); if (it == frezeS.end()) break; } } if (czy_unobserveall) { observe.clear(); observef.clear(); czy_unobserveall = false; } else { float vart; int adresik; std::stringstream ss; for (auto it = observe.begin(); it != observe.end() && !czy_unobserveall; it++) //for (auto const& p : observe) { adresik = it->first; //ReadProcessMemory(proc, (void*)p.first, &vart, sizeof(vart), NULL); vart = *((int*)adresik); if (vart != it->second) { //std::stringstream ss; //ss << " \x4/" << myid << " event " << hex << "0x" << std::setfill ('0') << std::setw (8) << p.first << " 1 " << dec << p.second; //cout << "wysylanie eventu: it->first: " << hex << it->first << " it->second: " << dec << it->second << " vart: " << vart << endl; ss.str(""); ss << " \x4/99" << " event " << hex << "0x" << std::setfill('0') << std::setw(8) << it->first << " 1 " << dec << zeranumer(myid) << " " << vart; //<< it->second; wyslij(ss.str()); //observe.erase(adresik); observe[adresik] = vart; //it = observe.begin(); } } for (auto it = observef.begin(); it != observef.end() && !czy_unobserveall; it++) //for (auto const& p : observe) { adresik = it->first; vart = *((int*)adresik); if (vart == it->second) { //cout << "wysylanie eventuf: it->first: " << hex << adresik << " it->second: " << dec << it->second << " vart: " << vart << endl; ss.str(""); ss << " \x4/99" << " eventf " << hex << "0x" << std::setfill('0') << std::setw(8) << adresik << " 1 " << dec << zeranumer(myid) << " " << vart; //<< it->second; wyslij(ss.str()); //if (observe.count(it->first)>0) it = observef.erase(it); //observef.erase(adresik); //it = observef.begin(); if (it == observef.end()) break; } } } return zwrot; } int hookedStartowanie() { int zwrot = startowaniehook(); czyWystartowano = true; //cout << "startowane zwrot: " << zwrot << endl; return zwrot; } int hookedSpectJoin(int int1, int int2) { //cout << "hookedSpectJoin" << endl; //std::cout << "int1: " << int1 << std::endl; //we can access arguments passed to original function //std::cout << "int2: " << int2 << std::endl; int zwrot = 0; std::stringstream ss; if (czy_blokada_specta) { zwrot = SpectJoinHook(0, 1); if (!czyJoined) { ss.str(""); ss << " \x4/99" << " gvoice " << myid; wyslij(ss.str()); } } else if (status == 0 && int1 == 1 && int2 == 0) { if (czy_ServerBotRequired) { if(!czyJoined) return SpectJoinHook(0, 1); czy_mozna_spect = false; string bigozz = "WAITING FOR GAME TO JOIN"; char * writable = new char[bigozz.size() + 1]; strcpy(writable, bigozz.c_str()); WriteToMemory((LPVOID)0x0051B93C, writable, strlen(writable) + 1); delete[] writable; ss.str(""); ss << " \x4/99" << " wplay " << myid; wyslij(ss.str()); ss.str(""); ss << " \x4/99" << " cstatus " << status << " 1 " << myid; wyslij(ss.str()); status = 1; zwrot = SpectJoinHook(0, 1); } else { ss.str(""); ss << " \x4/99" << " cstatus " << status << " 2 " << myid; wyslij(ss.str()); status = 2; zwrot = SpectJoinHook(int1, int2); } } else zwrot = SpectJoinHook(int1, int2); //cout << "zwrot14: " << zwrot << endl; return zwrot; //before returning to normal execution of function } int hookedTeamChange(int int1) { //cout << "hookedTeamChange" << endl; //std::cout << "int1: " << int1 << std::endl; //we can access arguments passed to original function int zwrot = 0; zwrot = TeamChangeHook(int1); //cout << "zwrotTeamChange: " << zwrot << endl; SpectJoin(1, 0); return zwrot; //before returning to normal execution of function } void dodajAmmo(int weapon, int ammo) { switch (weapon) { case 2: //bow *((short*)0x106D1B84) += ammo; //normal arrows break; case 3: //tekbow *((short*)0x106D1B86) += ammo; //explosive arrows break; case 4: //pistol *((short*)0x106D1B88) += ammo; break; case 5: //magnum *((short*)0x106D1B88) += ammo; break; case 6: //usypiacz *((short*)0x106D1B8C) += ammo; break; case 7: //chargeDart *((short*)0x106D1B8E) += ammo; break; case 8: //shotgun *((short*)0x106D1B90) += ammo; //green break; case 9: //szłeder *((short*)0x106D1B92) += ammo; //red break; case 10: //plasma *((short*)0x106D1B96) += ammo; break; case 11: //firestorm *((short*)0x106D1B96) += ammo; break; case 12: //sunfirepod *((short*)0x106D1B98) += ammo; break; case 13: //cbore *((short*)0x106D1B9A) += ammo; break; case 14: //pfm *((short*)0x106D1B9C) += ammo; break; case 15: //grenade *((short*)0x106D1B9E) += ammo; break; case 16: //scorpion *((short*)0x106D1BA0) += ammo; break; case 17: //harpoon *((short*)0x106D1BA2) += ammo; break; case 18: //torpedo *((short*)0x106D1BA4) += ammo; break; case 19: //flame *((short*)0x106D1BAC) += ammo; break; case 21: //nuke *((short*)0x106D1BB0) += ammo; break; default: break; } } void setStartingWeapons(int character = -1) { vector<string>* v; switch (character) { case 0: v = &turokWeapons; break; case 1: v = &adonWeapons; break; case 2: v = &gantWeapons; break; case 3: v = &fleshWeapons; break; case 4: v = &purWeapons; break; case 5: v = &endWeapons; break; case 6: v = &fireWeapons; break; case 7: v = &iggyWeapons; break; case 8: v = &campWeapons; break; case 9: v = &telWeapons; break; case -1: default: v = &startingWeapons; break; } for (auto const& value : *v) { int id_broni = -1; int i; short ammo = -1; if (value.find(";") != std::string::npos) { i = stoi(value.substr(0, value.find(";"))); ammo = stoi(value.substr(value.find(";") + 1)); } else i = stoi(value); byte equip = 1; if (i < 0) { i *= -1; equip = 0; } switch (i) { case 0: case 99: //remove warblade *((byte*)0x106D1BC3) = equip; break; case 1: *((byte*)0x106D1BC5) = equip; if (ammo >= 0) { *((short*)0x106D1B84) = ammo; *((short*)0x106D1B86) = ammo; } else if (startingMaxAmmo) { *((short*)0x106D1B84) = 50; *((short*)0x106D1B86) = 50; } else { *((short*)0x106D1B84) = 10; *((short*)0x106D1B86) = 10; } id_broni = 3; break; case 2: *((byte*)0x106D1BC6) = equip; if (ammo >= 0) { *((short*)0x106D1B88) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B88) = 300; else *((short*)0x106D1B88) = 50; id_broni = 4; break; case 3: *((byte*)0x106D1BC7) = equip; if (ammo >= 0) { *((short*)0x106D1B88) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B88) = 300; else *((short*)0x106D1B88) = 50; id_broni = 5; break; case 4: *((byte*)0x106D1BC9) = equip; if (ammo >= 0) { *((short*)0x106D1B8E) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B8E) = 50; else *((short*)0x106D1B8E) = 15; id_broni = 7; break; case 5: //shotgun *((byte*)0x106D1BCA) = equip; if (ammo >= 0) { *((short*)0x106D1B90) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B90) = 100; else *((short*)0x106D1B90) = 20; id_broni = 8; break; case 6: *((byte*)0x106D1BCB) = equip; if (ammo >= 0) { *((short*)0x106D1B92) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B92) = 50; else *((short*)0x106D1B92) = 15; id_broni = 9; break; case 7: *((byte*)0x106D1BCC) = equip; if (ammo >= 0) { *((short*)0x106D1B96) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B96) = 300; else *((short*)0x106D1B96) = 100; id_broni = 10; break; case 8: *((byte*)0x106D1BCD) = equip; if (ammo >= 0) { *((short*)0x106D1B96) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B96) = 300; else *((short*)0x106D1B96) = 100; id_broni = 11; break; case 9: *((byte*)0x106D1BCF) = equip; if (ammo >= 0) { *((short*)0x106D1B9A) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B9A) = 25; else *((short*)0x106D1B9A) = 5; id_broni = 13; break; case 10: *((byte*)0x106D1BD1) = equip; if (ammo >= 0) { *((short*)0x106D1B9E) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B9E) = 100; else *((short*)0x106D1B9E) = 14; id_broni = 15; break; case 11: *((byte*)0x106D1BD2) = equip; if (ammo >= 0) { *((short*)0x106D1BA0) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1BA0) = 50; else *((short*)0x106D1BA0) = 5; id_broni = 16; break; case 12: *((byte*)0x106D1BD6) = equip; if (ammo >= 0) { *((short*)0x106D1BAC) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1BAC) = 300; else *((short*)0x106D1BAC) = 100; id_broni = 19; break; case 13: *((byte*)0x106D1BD8) = equip; if (ammo >= 0) { *((short*)0x106D1BB0) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1BB0) = 10; else *((short*)0x106D1BB0) = 2; id_broni = 21; break; case 14: //tranquilizer *((byte*)0x106D1BC8) = equip; if (ammo >= 0) { *((short*)0x106D1B8C) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B8C) = 50; else *((short*)0x106D1B8C) = 15; id_broni = 6; break; case 15: //sunfirepod *((byte*)0x106D1BCE) = equip; if (ammo >= 0) { *((short*)0x106D1B98) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B98) = 300; else *((short*)0x106D1B98) = 50; id_broni = 12; break; case 16: //pfm *((byte*)0x106D1BD0) = equip; if (ammo >= 0) { *((short*)0x106D1B9C) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1B9C) = 50; else *((short*)0x106D1B9C) = 15; id_broni = 14; break; case 17: //harpoon *((byte*)0x106D1BD3) = equip; if (ammo >= 0) { *((short*)0x106D1BA2) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1BA2) = 50; else *((short*)0x106D1BA2) = 12; id_broni = 17; break; case 18: //torpedo *((byte*)0x106D1BD4) = equip; if (ammo >= 0) { *((short*)0x106D1BA4) = ammo; } else if (startingMaxAmmo) *((short*)0x106D1BA4) = 100; else *((short*)0x106D1BA4) = 30; id_broni = 18; break; case 19: //razor *((byte*)0x106D1BD7) = equip; break; } if (!startingMaxAmmo && ammo < 0 && extraAmmo.find(id_broni) != extraAmmo.end()) { dodajAmmo(id_broni, extraAmmo[id_broni]); } if (id_broni == 3 && czy_customWeapons) dodajAmmo(2, 30); } } void startingChar() { int character = *((int*)0x106D1770); setStartingWeapons(-1); setStartingWeapons(character); if (charMOTD.find(-1) != charMOTD.end()) { string s = charMOTD[-1]; char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable; } if (charMOTD.find(character) != charMOTD.end()) { string s = charMOTD[character]; char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable; } } int hookedRespawn(int int1) { int zwrot = 0; zwrot = respawn(int1); startingChar(); return zwrot; } int hookedChangeChar(int int1) { int zwrot = 0; zwrot = changeChar(int1); //cout << "change char int1: " << int1 << " zwrot: " << zwrot << endl; startingChar(); return zwrot; } int hookedWydropienieBroni(int var1, int var2, float var3) { //cout << "hookedWydropienieBroni" << endl; //std::cout << "WydropienieBroni var1: " << hex << var1 << std::endl; //we can access arguments passed to original function //std::cout << "WydropienieBroni var2: " << dec << var2 << std::endl; //std::cout << "WydropienieBroni var3: " << var3 << std::endl; //if (var1 == 0x106d1250) wydropienieBroniHook(var1, var2, var3); if (czy_customDrops_enabled) { //&& czyJoined if (czy_customDrops_config) { int wylosowana_liczba = (std::rand() % 100) + 1; //cout << "config wylosowana_liczba: " << wylosowana_liczba << endl; //cout << "dchance: " << dchance << endl; if (wylosowana_liczba <= dchance) { string level = (char*)0x005740A8; //cout << "level: " << level << endl; if (customDrop.find(level) == customDrop.end()) { //cout << "nie znaleziono takiego levela" << endl; level = "Default"; if (customDrop.find("Default") == customDrop.end()) return wydropienieBroniHook(var1, var2, var3); } //cout << "wiec Default" << endl; //cout << "customDrop[level].size(): " << customDrop[level].size() << endl; int rweapon = (std::rand() % customDrop[level].size()) + 1; //cout << "rweapon: " << rweapon << endl; int time = 20000; int i = 1; for (auto it = customDrop[level].begin(); it != customDrop[level].end(); it++) { if (i == rweapon) { rweapon = std::get<0>(*it); time = std::get<1>(*it); break; } i++; } //cout << "rweapon: " << rweapon << " time: " << time << endl; return wydropienieBroniHook(var1, rweapon, time); } } else { int wylosowana_liczba = (std::rand() % 100) + 1; //cout << "wylosowana_liczba: " << wylosowana_liczba << endl; if (wylosowana_liczba <= dchance) { int weapon = 19; if(czy_customPickups_enabled && !czy_customPickups_config) weapon = (std::rand() % 18); else weapon = (std::rand() % 14); switch (weapon) { case 0: weapon = 3; //tekbow break; case 1: weapon = 5; //magnum break; case 2: weapon = 7; //chargeDart break; case 3: weapon = 8; //shotgun break; case 4: weapon = 9; //shueder break; case 5: weapon = 10; //plasma break; case 6: weapon = 11; //firestorm break; case 7: weapon = 13; //cbore break; case 8: weapon = 15; //grenadeLauncher break; case 9: weapon = 16; //scorpionLauncher break; case 10: weapon = 17; //harpoon break; case 11: weapon = 18; //torpedo break; case 12: weapon = 20; //flameThrower break; case 13: weapon = 22; //nuke break; case 14: weapon = 18; //torpedo break; case 15: weapon = 18; //torpedo break; case 16: weapon = 18; //torpedo break; case 17: weapon = 18; //torpedo break; case 18: weapon = 18; //torpedo break; default: weapon = 19; //riding gun break; } //cout << "custom drop: " << weapon << endl; return wydropienieBroniHook(var1, weapon, var3); } } } return wydropienieBroniHook(var1, var2, var3); } int* getAmmo(int weapon) { switch (weapon) { case 2: //bow return (int*)0x106D1B84; //normal arrows case 3: //tekbow return (int*)0x106D1B86; //explosive arrows case 4: //pistol return (int*)0x106D1B88; case 5: //magnum return (int*)0x106D1B88; case 6: //usypiacz return (int*)0x106D1B8C; case 7: //chargeDart return (int*)0x106D1B8E; case 8: //shotgun return (int*)0x106D1B90; //green case 9: //szłeder return (int*)0x106D1B92; //red case 10: //plasma return (int*)0x106D1B96; case 11: //firestorm return (int*)0x106D1B96; case 12: //sunfirepod return (int*)0x106D1B98; case 13: //cbore return (int*)0x106D1B9A; case 14: //pfm return (int*)0x106D1B9C; case 15: //grenade return (int*)0x106D1B9E; case 16: //scorpion return (int*)0x106D1BA0; case 17: //harpoon return (int*)0x106D1BA2; case 18: //torpedo return (int*)0x106D1BA4; case 20: //flame return (int*)0x106D1BAC; case 22: //nuke return (int*)0x106D1BB0; default: break; } } int kto = 0x106d1250; int kto2 = 0x106d1250; int hookedStrzal(int var1, int var2) { //cout << "hookedStrzal" << endl; ////std::cout << "Strzal var1 hex: " << hex << var1 << " dec: " << dec << var1 << std::endl; //we can access arguments passed to original function //std::cout << "Strzal var2 hex: " << hex << var2 << " dec: " << dec << var2 << std::endl; if (var1 != 0x106d1250) { if (var2 == 104) { kto = var1; var1 = 0x106d1250; if (!czyinfoRazor) { czyinfoRazor = true; komunikat("Razor winds are just visual effect. Enemy razors always go to you but don't make damage (arrows do)."); komunikat("You can disable razor winds typing /razor"); } if(!czyUserRazors) return strzal(var1, 0); } else if (var2 == 10) { kto2 = var1; var1 = 0x106d1250; strzal(kto2, var2); return strzal(var1, var2); } else if (var2 == 3) { /*strzal(var1, var2); return strzal(0x106d1250, 10);*/ kto2 = var1; var1 = 0x106d1250; strzal(kto2, var2); return strzal(var1, 10); } return strzal(var1, var2); } int zwrot = 0; //if (wdamage != -1) zwrot = strzal(var1, wdamage); else { if (pfmlayer) zwrot = strzal(var1, 12); else if (sunfirepod) { zwrot = strzal(var1, 10); } else if (czyPiorun && var2 == 4) { //strzelRidingGun = true; zwrot = strzal(var1, var2); } else if (razor) { strzel2 = true; zwrot = strzal(var1, 104); } else if (cbore) { if (czy_customWeapons) strzel3 = true; zwrot = strzal(var1, var2); } else if (nuke && var2 == 21) { if (czy_customWeapons) strzel4 = true; zwrot = strzal(var1, var2); } else if (usypiacz) { strzel5 = true; zwrot = strzal(var1, 3); } else if (pistol && var2 == 5) { //if (czy_customWeapons) strzel6 = true; zwrot = strzal(var1, var2); } else if ((var2 == 16 || var2 == 231) && czyTorpedoDisabledOnGround) { int czy_w_wodzie = *((int*)0x00ADC09C); if (czy_w_wodzie == 0) zwrot = strzal(var1, 0); else zwrot = strzal(var1, var2); } else zwrot = strzal(var1, var2); if (dinoRidingWith == var2 && czy_customWeapons) { strzelRidingGun = true; } if (blackOilWith == var2 && czy_customWeapons) { if(czy_userBlackOil) strzelBlackOil = true; } if (airStrikeWith == var2 && czy_customWeapons) { int czy_w_wodzie = *((int*)0x00ADC09C); if (czy_w_wodzie == 0){ int* ammo = getAmmo(airStrikeAmmoId); int tempvar = 1; if (var2 == 16 && czyTorpedoDisabledOnGround) tempvar = 0; if (*ammo - tempvar <= 0) { *ammo = 1; czyLastAmmo = true; } strzelAirStrike = true; } } //} //cout << "Strzal zwrot: " << hex << zwrot << dec << endl; return zwrot; //before returning to normal execution of function } int hookedDamage(int var1, int var2, int *var3, int *var4, int *var5) { //cout << "hookedDamage" << endl; //std::cout << "Damage var1: " << hex << var1 << dec << endl; //" adress: " << hex << var1 << dec << std::endl; //we can access arguments passed to original function //std::cout << "Damage var2: " << var2 << std::endl; //std::cout << "Damage var3: " << *var3 << " adress: " << hex << var3 << dec << std::endl; //lokalizacja na mapie //std::cout << "Damage var4: " << *var4 << " adress: " << hex << var4 << dec << std::endl; //kierunek celowania (lotu?) //std::cout << "Damage var5: " << *var5 << " adress: " << hex << var5 << dec << std::endl; if (var2 == 104 && kto != 0x106d1250) { var1 = kto; kto = 0x106d1250; } else if ((var2 == 10 || var2 == 3) && kto2 != 0x106d1250 && var1 == 0x106d1250) { var1 = kto2; kto2 = 0x106d1250; } return damage(var1, var2, var3, var4, var5); /*int zwr = 0; zwr = damage(var1, var2, var3, var4, var5); cout << "Damage zwr: " << zwr << endl; if (var2 == 4) zwr = 1; return zwr;*/ } int hookedIndamage1(int var1, int var2, int var3) { //cout << "hookedIndamage1" << endl; //std::cout << "Indamage1 var1: " << hex << var1 << dec << endl; //" adress: " << hex << var1 << dec << std::endl; //we can access arguments passed to original function //std::cout << "Indamage1 var2: " << var2 << std::endl; //id borni //std::cout << "Indamage1 var3: " << var3 << std::endl; //pocisk/efekt int zwrot = 0; if (var3 == 104) zwrot = indamage1(var1, 21, 104); if (var1 != 0x106d1250) { //cout << "odbieram!!!!" << endl; if (var3 == 104) zwrot = indamage1(var1, 21, 104); else if (var3 == 10) zwrot = indamage1(var1, 12, 10); else if (var3 == 14) zwrot = indamage1(var1, 16, 14); else if (var3 == 16 || var3 == 231) zwrot = indamage1(var1, 18, 16); else if (var3 == 15) zwrot = indamage1(var1, 17, 15); else if (var3 == 4) zwrot = indamage1(var1, 7, 4); else if (var3 == 108 || var3 == 110 || var3 == 117) zwrot = indamage1(var1, 15, 13); else if (var3 == 12) zwrot = indamage1(var1, 14, 12); else if (var3 == 10) zwrot = indamage1(var1, 12, 10); else if (var3 == 205) zwrot = indamage1(var1, 21, 104); else if (var3 == 335) zwrot = indamage1(var1, 22, 21); else if (var3 == 3 || var3 == 111) zwrot = indamage1(var1, 6, 3); else if (var3 == 164) zwrot = indamage1(var1, 7, 4); else if (var3 == 5 || var3 == 54 || var3 == 150 || var3 == 209 || var3 == 210) zwrot = indamage1(var1, 4, 5); else if (var3 == 11) zwrot = indamage1(var1, 13, 11); else if (var3 == 21) zwrot = indamage1(var1, 22, 21); else zwrot = indamage1(var1, var2, var3); //cout << "Indamage1 zwrot: " << zwrot << endl; return zwrot; } //if (wdamage != -1) zwrot = indamage1(var1, 10, 9);else { //if (var3 == 10) zwrot = indamage1(var1, 12, 10); if (var3 == 117 || var3 == 108 || var3 == 110) zwrot = indamage1(var1, 15, 13); else if (var3 == 5 || var3 == 54 || var3 == 150 || var3 == 209 || var3 == 210) zwrot = indamage1(var1, 4, 5); else if (pfmlayer || sunfirepod || razor || cbore || usypiacz) zwrot = indamage1(var1, indmg1var2, indmg1var3); /*else if (czyPiorun) { if (var3 == 108 || var3 == 110) zwrot = indamage1(var1, 15, 13); else zwrot = indamage1(var1, var2, var3); }*/ else if (nuke) { if (var3 == 335 || var3 == 117) zwrot = indamage1(var1, 22, 21); else zwrot = indamage1(var1, var2, var3); } else zwrot = indamage1(var1, var2, var3); //indamage1(var1, var2, var3); //} //cout << "Indamage1 zwrot: " << zwrot << endl; return zwrot; //before returning to normal execution of function } int hookedPodniesienieBroni(int int1, int int2) { //cout << "hookedzmianabroni" << endl; //std::cout << "PodniesienieBroni int1: " << hex << int1 << std::endl; //we can access arguments passed to original function //std::cout << "PodniesienieBroni int2: " << dec << int2 << std::endl; int zwrot = 0; //if (numer_broni != -1) int2 = 5320896 + 24 * numer_broni; int id_broni = (int2 - 5320896) / 24; if (czy_customPickups_enabled) { //&& czyJoined //if (czy_customPickups_config) { int wylosowana_liczba = (std::rand() % 100) + 1; //cout << "config wylosowana_liczba: " << wylosowana_liczba << endl; //map<int, list<int>> customPickup; //map<int, int> customPchance; int pchance = 0; if (customPchance.find(id_broni) != customPchance.end()) pchance = customPchance[id_broni]; //cout << "pchance: " << pchance << endl; if (wylosowana_liczba <= pchance) { //cout << "customPickup[id_broni].size(): " << customPickup[id_broni].size() << endl; int rweapon = (std::rand() % customPickup[id_broni].size()) + 1; //cout << "rweapon: " << rweapon << endl; int i = 1; int ammo = 0; for (auto it = customPickup[id_broni].begin(); it != customPickup[id_broni].end(); it++) { if (i == rweapon) { rweapon = std::get<0>(*it); ammo = std::get<1>(*it); break; } i++; } //cout << "rweapon: " << rweapon << " ammo: " << ammo << endl; dodajAmmo(rweapon, ammo); int2 = 5320896 + 24 * rweapon; return podniesienieBroniHook(int1, int2); } else { if (extraAmmo.find(id_broni) != extraAmmo.end()) { dodajAmmo(id_broni, extraAmmo[id_broni]); } if(id_broni == 3 && czy_customWeapons) dodajAmmo(2, 30); else if (id_broni == 8 && czy_customWeapons) dodajAmmo(9, 3); } //} } zwrot = podniesienieBroniHook(int1, int2); //cout << "PodniesienieBroni zwrot: " << zwrot << endl; return zwrot; //before returning to normal execution of function } /*int hookedZmianaKoloru(int int1) { int zwrot = 0; cout << "ZmianaKoloru int1: " << int1 << endl; zwrot = zmianaKoloru(int1); cout << "zwrotZmianaKoloru: " << zwrot << endl; return zwrot; //before returning to normal execution of function } int hookedPreZmianaKoloru(int int1, int int2) { int zwrot = 0; cout << "PreZmianaKoloru int1: " << int1 << endl; cout << "PreZmianaKoloru int2: " << int2 << endl; int var = int1 - 275579872; if (var != 0) var /= 40; cout << "PreZmianaKoloru var: " << var << endl; int var2 = 275579296; zwrot = preZmianaKoloru(var, var2); cout << "zwrotPreZmianaKoloru: " << zwrot << endl; return zwrot; //before returning to normal execution of function }*/ void sprawdzVoice() { std::stringstream ss; std::this_thread::sleep_for(std::chrono::seconds{ 10 }); if (czyHostVoice == false) { ss.str(""); ss << " \x4/99" << " gvoice " << myid; wyslij(ss.str()); std::this_thread::sleep_for(std::chrono::seconds{ 10 }); } if (czyHostVoice == false) { ss.str(""); ss << " \x4/99" << " gvoice " << myid; wyslij(ss.str()); std::this_thread::sleep_for(std::chrono::seconds{ 5 }); } if (czyHostVoice == false) { cout << "DISCONNECTED WITH BOT! or lost connection." << endl; if (czy_ServerBotRequired) { string bigozz = "DISCONNECTED WITH BOT!"; char * writable = new char[bigozz.size() + 1]; strcpy(writable, bigozz.c_str()); WriteToMemory((LPVOID)0x0051B93C, writable, strlen(writable) + 1); delete[] writable; //wrzuc na specta int adres = 0x00AD03D8; int var = 4198400; WriteToMemory((LPVOID)adres, &var, sizeof(var)); //printf("komenda write adres Error Code: %i\n", GetLastError()); ss.str(""); ss << " \x4/99" << " cstatus " << status << " 0 " << myid; wyslij(ss.str()); status = 0; SpectJoin(0, 1); czy_blokada_specta = true; } commands.clear(); myid = -1; czy_wyslane_join = false; czyJoined = false; czy_unfreezeall = true; czy_unobserveall = true; czy_zalogowany = false; } czy_sprawdzanie_voice = false; } void placeJMP(BYTE * address, DWORD jumpTo, DWORD length) { DWORD oldProtect, newProtect, relativeAddress; VirtualProtect(address, length, PAGE_EXECUTE_READWRITE, &oldProtect); relativeAddress = (DWORD)(jumpTo - (DWORD)address) - 5; *address = 0xE9; *((DWORD *)(address + 0x1)) = relativeAddress; for (DWORD x = 0x5; x < length; x++) { *(address + x) = 0x90; } VirtualProtect(address, length, oldProtect, &newProtect); } static size_t my_write(void *buffer, size_t size, size_t nmemb, void *param) { std::string& text = *static_cast<std::string*>(param); size_t totalsize = size * nmemb; text.append(static_cast<char*>(buffer), totalsize); return totalsize; } bool readWebSite(string *result, string url) { CURL *curl; CURLcode res; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); /* Define our callback to get called when there's data to be written */ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write); /* Set a pointer to our struct to pass to the callback */ curl_easy_setopt(curl, CURLOPT_WRITEDATA, result); /* Switch on full protocol/debug output */ //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); if (CURLE_OK != res) { /* we failed */ cout << "curl error: " << res << '\n'; //std::cerr curl_global_cleanup(); return false; } } curl_global_cleanup(); return true; } void serverRules() { string rules = (char*)0x00B73874; czy_ServerBot = false; czy_ServerBotRequired = false; czy_spectate_enabled = true; czy_setColor_enabled = false; czy_customDrops_enabled = false; czy_custom_damage = false; czy_customPickups_enabled = false; czy_customWeapons = false; czyForceSpectNaStart = false; if (rules.find("\\ServerBot\\") != std::string::npos) { string subString = rules.substr(rules.find("\\ServerBot\\") + 11); //cout << "ServerBotRequiredsubString1: " << subString << endl; subString = subString.substr(0, subString.find("\\") - 1); //cout << "ServerBot: " << subString << endl; if (subString.find("TRUE") == 0 || subString.find("REQUIRED") == 0) { czy_ServerBotRequired = true; czy_ServerBot = true; } else if (subString.find("NOTREQUIRED") == 0) { czy_ServerBotRequired = false; czy_ServerBot = true; } } string lvlSet = (char*)0x00B65DD9; //cout << "levelSet: " << lvlSet << endl; if (czy_ServerBot && lvlSet.find("beta07.lsm") == std::string::npos && lvlSet.find("beta08.lsm") == std::string::npos && lvlSet.find("beta084.lsm") == std::string::npos) { WriteToMemory((void*)0x00B65DD4, "You probably have an old or different version of mod than required", 67); ShowWindow(GetConsoleWindow(), SW_SHOWMAXIMIZED); cout << "\n!!!!" << endl; cout << "Error! You probably have an old or different version of mod than required." << endl; string required = lvlSet.substr(lvlSet.find("beta"), lvlSet.find(".lsm")-lvlSet.find("beta")); cout << "Your version: beta07 Required: " << required << endl; cout << "Get new version at http://rebrand.ly/t2mod or contact me (kubpicapf@gmail.com)." << endl; cout << "!!!!\n" << endl; } else { if (rules.find("\\LvlSet\\") != std::string::npos) { string subString = rules.substr(rules.find("\\LvlSet\\") + 8); //cout << "subString1: " << subString << endl; subString = subString.substr(0, subString.find("\\") - 1); //cout << "subString2: " << subString << endl; subString += ".lsm"; //cout << "LvlSet: " << subString << endl; strcpy((char*)0x00B65DD9, subString.c_str()); } if (rules.find("\\ModSettings\\") != std::string::npos) { string subString = rules.substr(rules.find("\\ModSettings\\") + 13); //cout << "SetColsubString1: " << subString << endl; subString = subString.substr(0, subString.find("\\")); //cout << "ModSettings: " << subString << endl; //cout << "subString[0]: " << subString[0] << endl; //cout << "subString[1]: " << subString[1] << endl; if (subString[0] == '0') czy_spectate_enabled = false; if (subString[1] == '1') czy_setColor_enabled = true; if (subString[2] == '1') czy_customDrops_enabled = true; if (subString[3] == '1') czy_custom_damage = true; if (subString[4] == '1') { // useWeaponsEverywhere WriteToMemory((void*)0x0041D0C6, "\xEB", 1); } if (subString[5] == '1') { //flame thrower in water WriteToMemory((void*)0x0041D0B6, "\xEB", 1); } if (subString[6] == '1') czy_customPickups_enabled = true; if (subString[7] == '1') { czy_customWeapons = true; czyTorpedoDisabledOnGround = true; } } if (rules.find("\\GameType\\") != std::string::npos) { string subString = rules.substr(rules.find("\\GameType\\") + 10); //cout << "GameTypesubString1: " << subString << endl; subString = subString.substr(0, subString.find("\\")); //cout << "GameType: " << subString << endl; if (subString.find("Team Arena") == 0 || subString.find("Arena") == 0) czy_ServerBotRequired = false; else if (subString.find("Rok Match") == 0 || subString.find("AWR Match") == 0) { if(!czy_ServerBot) czy_setColor_enabled = true; czyForceSpectNaStart = true; } //else if (subString.find("Team Rok Match") == 0 || subString.find("Team AWR Match") == 0) czyForceSpectNaStart = false; if (subString.find("Team") != std::string::npos) isTeamGameMode = true; } if (rules.find("\\CfgURL\\") != std::string::npos) { cfgurl = rules.substr(rules.find("\\CfgURL\\") + 8); cfgurl = cfgurl.substr(0, cfgurl.find("\\")); cfgurl = cfgurl.substr(0, cfgurl.find(" ")); if (cfgurl.find("://") != std::string::npos) { cfgurl = "http://" + cfgurl; } } else if (lvlSet.find("beta07.lsm") != std::string::npos) { cfgurl = "http://rebrand.ly/t2cfg"; } if (rules.find("\\ArenaWeapons\\") != std::string::npos && rules.find("AWR") != std::string::npos) { string s = rules.substr(rules.find("\\ArenaWeapons\\") + 14); s = s.substr(0, s.find("\\")); istringstream iss(s); vector<string> tokens{ istream_iterator<string>{iss}, istream_iterator<string>{} }; for (auto const& value : tokens) { startingWeapons.push_back(value); } } } } DWORD retJMP = 0x004D6012; //string lvlSet; __declspec(naked) void myMidfuncHook() // __declspec(naked) says to the compiler that we will worry about the prolog/epilog/return of the function { __asm and ecx, 03 // do what we overwrote __asm repe movsb // do what you want now, i'll obtain data from EBX register, for example, and store it for later use //__asm mov myData, ebx //if you want to do any other calls to other functions, etc and don't need the registers/stack anymore push it //for example: __asm pushad // push all general registers __asm pushfd // push all flags // do your stuff here.. calls, calculations.. // remember, you can't do everything in a naked function, it's limited.. serverRules(); //restore stack/registers, so we don't corrupt any data and program flow continues as it should __asm popfd __asm popad // return where we left off __asm jmp[retJMP] } DWORD retJMP2 = 0x0048297E; __declspec(naked) void MidChangeNameHook() // __declspec(naked) says to the compiler that we will worry about the prolog/epilog/return of the function { __asm and ecx, 03 // do what we overwrote __asm repe movsb // do what you want now, i'll obtain data from EBX register, for example, and store it for later use //__asm mov myData, ebx //if you want to do any other calls to other functions, etc and don't need the registers/stack anymore push it //for example: __asm pushad // push all general registers __asm pushfd // push all flags // do your stuff here.. calls, calculations.. // remember, you can't do everything in a naked function, it's limited.. //lvlSet = (char*)0x00B65DD9; //cout << "MidChangeNameHook" << endl; sprawdzNick(); //restore stack/registers, so we don't corrupt any data and program flow continues as it should __asm popfd __asm popad // return where we left off __asm jmp[retJMP2] } DWORD retJMP3 = 0x004827D2; __declspec(naked) void fixSpecta() // __declspec(naked) says to the compiler that we will worry about the prolog/epilog/return of the function { __asm mov eax, 0 // do what we overwrote __asm test ah, 10 __asm jmp[retJMP3] } void zmianka() { short var = *((short*)0x106D1BE6); //cout << "zmianka var: " << var << endl; if (var == 15 && pfmlayer || var == 5 && sunfirepod || var == 10 && razor || var == 7 && czyPiorun || var == 13 && cbore || var == 9 && usypiacz || var == 22 && nuke || var == 4 && pistol || var == 3 && bow || var == 3 && tekbow || var == 8 && shotgun) { return; } //WriteToMemory((LPVOID)0x00AD4538, &var, sizeof(var)); //WriteToMemory((LPVOID)0x00AD453B, &var, sizeof(var)); customWeaponId = var; sunfirepod = false; czyPiorun = false; razor = false; pfmlayer = false; cbore = false; usypiacz = false; nuke = false; pistol = false; bow = false; tekbow = false; shotgun = false; //zm = 0; if (var == 14) { pfmlayer = true; if (!czyinfo4) { czyinfo4 = true; komunikat("Mines will spawn only for players in your rendering distance."); komunikat("Players far from you may not see some mines."); } indmg1var2 = 14; indmg1var3 = 12; short var2 = 15; WriteToMemory((LPVOID)0x106D1D8C, &var2, sizeof(var2)); } else if (var == 12) { sunfirepod = true; indmg1var2 = 12; indmg1var3 = 10; short var2 = 5; WriteToMemory((LPVOID)0x106D1D8C, &var2, sizeof(var2)); } else if (var == 21) { razor = true; indmg1var2 = 21; indmg1var3 = 104; short var2 = 10; WriteToMemory((LPVOID)0x106D1D8C, &var2, sizeof(var2)); } else if (var == 7) { czyPiorun = true; //indmg1var2 = 7; //indmg1var3 = 4; } else if (var == 13) { cbore = true; indmg1var2 = 13; indmg1var3 = 11; } else if (var == 2) { bow = true; if (!czyinfo1) { czyinfo1 = true; komunikat("Use zoom to shoot faster. [Shift]"); } short var2 = 3; WriteToMemory((LPVOID)0x106D1D8C, &var2, sizeof(var2)); } else if (var == 3) { tekbow = true; if (!czyinfo1) { czyinfo1 = true; komunikat("Use zoom to shoot faster. [Shift]"); } } else if (var == 8) { shotgun = true; if (!czyinfo2) { czyinfo2 = true; komunikat("[H] to change ammo type."); } } else if (var == 4) { pistol = true; } else if (var == 6) { usypiacz = true; if (!czyinfo3) { czyinfo3 = true; komunikat("Every shot will throw SunfirePod visible only for other players (to blind them for awhile)."); } indmg1var2 = 6; indmg1var3 = 3; short var2 = 9; WriteToMemory((LPVOID)0x106D1D8C, &var2, sizeof(var2)); } else if (var == 22) { nuke = true; } if (czy_custom_damage) { //&& czyJoined if (customDamage.find(var) != customDamage.end()) { float var2 = customDamage[var]; //cout << "zmiankaD var2: " << var2 << endl; WriteToMemory((LPVOID)0x00AD44EC, &var2, sizeof(var2)); /*ss.str(""); ss << "Weapon: " << dec << var << " damage: " << var2; string s = ss.str(); char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable;*/ } else if(defaultDamage != -1){ float var2 = defaultDamage; //var2 = customDamage[-1]; //cout << "zmiankaD var2: " << var2 << endl; WriteToMemory((LPVOID)0x00AD44EC, &var2, sizeof(var2)); } if (customNode.find(var) != customNode.end()) { float var2 = customNode[var]; //cout << "zmiankaN var2: " << var2 << endl; WriteToMemory((LPVOID)0x00AD44F0, &var2, sizeof(var2)); /*ss.str(""); ss << "Weapon: " << dec << var << " node: " << var2; string s = ss.str(); char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable;*/ } else if (defaultNode != -1) { float var2 = defaultNode; //var2 = customNode[-1]; //cout << "zmiankaN var2: " << var2 << endl; WriteToMemory((LPVOID)0x00AD44F0, &var2, sizeof(var2)); } } } DWORD retJMP4 = 0x0042693F; __declspec(naked) void midZmianaBroni() // __declspec(naked) says to the compiler that we will worry about the prolog/epilog/return of the function { __asm mov eax, [edx + 0x48] // do what we overwrote __asm mov[edi + 0x2C], eax // do what you want now, i'll obtain data from EBX register, for example, and store it for later use //__asm mov myData, ebx //if you want to do any other calls to other functions, etc and don't need the registers/stack anymore push it //for example: __asm pushad // push all general registers __asm pushfd // push all flags // do your stuff here.. calls, calculations.. // remember, you can't do everything in a naked function, it's limited.. zmianka(); //restore stack/registers, so we don't corrupt any data and program flow continues as it should __asm popfd __asm popad // return where we left off __asm jmp[retJMP4] } DWORD WINAPI custom_weapons(LPVOID lpParam) { while (1) { Sleep(16); if (strzelRidingGun) { strzelRidingGun = false; Sleep(80); if (stronaRidingGun) { stronaRidingGun = false; strzal(0x106d1250, 110); //riding gun prawe } else { stronaRidingGun = true; strzal(0x106d1250, 108); //riding gun lewe } } else if (strzel2) { strzel2 = false; Sleep(2); //Sleep(35); strzal(0x106d1250, 205); strzal(0x106d1250, 205); strzal(0x106d1250, 205); Sleep(2); strzal(0x106d1250, 205); strzal(0x106d1250, 205); strzal(0x106d1250, 205); Sleep(5); strzal(0x106d1250, 205); strzal(0x106d1250, 205); strzal(0x106d1250, 205); } else if (strzel3) { strzel3 = false; strzal(0x106d1250, 14); } else if (strzel4 && howManyExtraNukeExplosions) { strzel4 = false; Sleep(35); for (int i = 0; i < howManyExtraNukeExplosions; i++) { short* var = (short*)0x106D1BB0; *var += 1; strzal(0x106d1250, 21); Sleep(35); } } else if (strzelAirStrike) { strzelAirStrike = false; //strzal(0x106d1250, 335); if (airStrikeDelay >= 500 && czyinfoAirStrike < 3) { komunikat("Move to open space or else Katyusha rockets will kill you! (Change weapon to cancel)"); czyinfoAirStrike++; } else if (czyinfoAirStrike < 2) { komunikat("Katyusha launched! Move to open space or else rockets will kill you! (Air-strike)"); czyinfoAirStrike++; } Sleep(airStrikeDelay); short var = *((short*)0x106D1D8C); if (var == airStrikeAmmoId) { int* ammo = getAmmo(airStrikeAmmoId); int tempammo = *ammo; tempammo -= airStrikeAmmoCost; if (tempammo < 0) tempammo = 0; *ammo = tempammo; if (airStrikeDelay >= 400) komunikat("Katyusha launched! (Air-strike)"); strzal(0x106d1250, 117); Sleep(35); strzal(0x106d1250, 117); Sleep(35); strzal(0x106d1250, 117); Sleep(35); strzal(0x106d1250, 117); Sleep(35); strzal(0x106d1250, 117); Sleep(35); strzal(0x106d1250, 117); Sleep(35); strzal(0x106d1250, 117); } else { komunikat("You changed weapon - Airstrike canceled."); } if (czyLastAmmo) { czyLastAmmo = false; int* ammo = getAmmo(airStrikeAmmoId); *ammo -= 1; } } else if (strzel5) { strzel5 = false; strzal(0x106d1250, 5); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); Sleep(35); strzal(0x106d1250, 111); } else if (strzelBlackOil) { if (!czyInfoOil) { czyInfoOil = true; komunikat("Type /oil to disable generation of black oil."); } strzelBlackOil = false; strzal(0x106d1250, 54); Sleep(35); strzal(0x106d1250, 150); } } return S_OK; } void generateTID(char pathc[]) { string path = pathc; path = path.substr(0, path.find_last_of("/\\")); path = path + "\\turok2.ini"; fstream config; config.open(path, std::fstream::in); string seed = "hi"; if (!config) //if (config.good() == true) { //cout << "turok2.ini not found!" << endl; seed += "omgT2iniNOTfound"; for (int i = 0; i < 20; i++) { char losowyZnak = 'a' + (std::rand() % 26); seed += losowyZnak; } } else { string slowo; string wiersz; while (getline(config, wiersz)) { slowo = wiersz.substr(0, wiersz.find("=") + 1); //cout << slowo << endl; if (slowo == "Names=" || slowo == "Names_0=" || slowo == "Names_1=" || slowo == "Names_2=" || slowo == "Names_3=" || slowo == "Names_4=") { string temp = wiersz.substr(wiersz.find("=") + 1); seed += temp; } char losowyZnak = 'a' + (std::rand() % 26); seed += losowyZnak; slowo.clear(); wiersz.clear(); } config.close(); } //cout << "seed: " << seed << endl; tid = md5(seed); for (int i = 0; i < 5; i++) { char losowyZnak = 'a' + (std::rand() % 26); tid += losowyZnak; } } DWORD WINAPI Main_thread(LPVOID lpParam) { srand(time(NULL)); HANDLE han = GetStdHandle(STD_OUTPUT_HANDLE); WriteConsole(han, "hello", 6, new DWORD, 0); AllocConsole(); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); string version = "B0.8.4"; cout << "T2 kub's mod " << version << endl; cout << "Mod\'s website: http://rebrand.ly/t2mod" << endl; cout << "Loading... Wait..." << endl; placeJMP((BYTE*)0x00426939, (DWORD)myMidfuncHook, 6); WriteToMemory((void*)0x0041D0D8, "\xEB", 1); std::stringstream ss; ss.str(""); ss << &customWeaponId; //cout << "&customWeaponId = 0: " << ss.str() << endl; char adresWbajtach[4]; //cout << "1: " << hex << strtol(ss.str().substr(6).c_str(), NULL, 16) << endl; //cout << "2: " << strtol(ss.str().substr(4, 2).c_str(), NULL, 16) << endl; //cout << "3: " << strtol(ss.str().substr(2, 2).c_str(), NULL, 16) << endl; //cout << "4: " << strtol(ss.str().substr(0, 2).c_str(), NULL, 16) << endl; adresWbajtach[0] = strtol(ss.str().substr(6).c_str(), NULL, 16); adresWbajtach[1] = strtol(ss.str().substr(4, 2).c_str(), NULL, 16); adresWbajtach[2] = strtol(ss.str().substr(2, 2).c_str(), NULL, 16); adresWbajtach[3] = strtol(ss.str().substr(0, 2).c_str(), NULL, 16); //cout << "adresWbajtach: " << hex << (int)adresWbajtach[0] << " " << (int)adresWbajtach[1] << " " << (int)adresWbajtach[2] << " " << (int)adresWbajtach[3] << dec << endl; ss.str(""); ss << "\x0F\xBF\x0D" << adresWbajtach; WriteToMemory((void*)0x0041928D, ss.str().c_str(), 7); ss.str(""); ss << "\x0F\xBF\x15" << adresWbajtach; WriteToMemory((void*)0x004192B2, ss.str().c_str(), 7); ss.str(""); ss << "\x0F\xBF\x3D" << adresWbajtach; WriteToMemory((void*)0x0041D8CA, ss.str().c_str(), 7); ss.str(""); ss << "\x0F\xBF\x0D" << adresWbajtach; WriteToMemory((void*)0x00426C8B, ss.str().c_str(), 7); ss.str(""); ss << "\x0F\xBF\x05" << adresWbajtach; WriteToMemory((void*)0x00426AE8, ss.str().c_str(), 7); ss.str(""); ss << "\x0F\xBF\x05" << adresWbajtach; WriteToMemory((void*)0x0041DD5A, ss.str().c_str(), 7); ss.str(""); ss << "\x0F\xBF\x05" << adresWbajtach; WriteToMemory((void*)0x0041DDF2, ss.str().c_str(), 7); ss.str(""); ss << "\x0F\xBF\x15" << adresWbajtach; WriteToMemory((void*)0x00426981, ss.str().c_str(), 7); ss.str(""); ss << "\x0F\xBF\x0D" << adresWbajtach; WriteToMemory((void*)0x00426ECA, ss.str().c_str(), 7); WriteToMemory((LPVOID)0x00B723CC, "\x01", 1); customPchance[18] = 80; //dodaj_customPickup(18, 2, 30); dodaj_customPickup(18, 6, 12); dodaj_customPickup(18, 12, 200); dodaj_customPickup(18, 14, 22); dodaj_customPickup(18, 20, 0); customPchance[5] = 20; dodaj_customPickup(5, 12, 200); //customPchance[3] = 20; //dodaj_customPickup(3, 2, 30); customPchance[9] = 20; dodaj_customPickup(9, 6, 12); customPchance[15] = 20; dodaj_customPickup(15, 14, 22); customPchance[10] = 15; dodaj_customPickup(10, 20, 0); customPchance[8] = 15; dodaj_customPickup(8, 21, 1); customPchance[7] = 15; dodaj_customPickup(7, 17, 0); customPchance[13] = 15; dodaj_customPickup(13, 18, 0); extraAmmo[19] = 100; extraAmmo[5] = 150; extraAmmo[7] = 20; //extraAmmo[8] = 5; extraAmmo[9] = 6; //extraAmmo[11] = 20; extraAmmo[13] = 7; extraAmmo[21] = 1; extraAmmo[17] = 5; float camerafov1 = 73.74; float weaponfov1 = 52.6714; float maxpan = 4000; bool hideconsole = true; char pathc[MAX_PATH]; GetModuleFileNameA(hModule, pathc, sizeof(pathc)); //cout << "pathc: " << pathc << endl; string path = pathc; path = path.substr(0, path.find_last_of("/\\")); /*string satrib = "attrib -r \"" + path + "\\launcherConfig.txt\" /S /D"; //"\\*.*\" char * writablez = new char[satrib.size() + 1]; strcpy(writablez, satrib.c_str()); //cout << "writablez: " << writablez << endl; WinExec(writablez, SW_HIDE); delete[] writablez; satrib = "attrib -r \"" + path + "\" /S /D"; //"\\*.*\" writablez = new char[satrib.size() + 1]; strcpy(writablez, satrib.c_str()); //cout << "writablez: " << writablez << endl; WinExec(writablez, SW_HIDE); delete[] writablez;*/ path = path + "\\launcherConfig.txt"; //cout << "path: " << path << endl; fstream config; config.open(path, std::fstream::in | std::fstream::out); //string startParams = "-maxframerate 64 -quickmouse -exclusivemouse -AverageMouse 0"; //string exe = "Turok2MP.exe"; if (!config) //if (config.good() == true) { cout << "Config not found!" << endl; config.open(path, std::fstream::trunc | std::fstream::out); config.close(); // re-open with original flags config.open(path, std::fstream::in | std::fstream::out); //ofstream newconfig; //newconfig.open("launcherConfig.txt"); config << "ExeName=Turok2MP.exe" << endl; config << "StartupParameters=-maxframerate 64 -quickmouse -exclusivemouse -AverageMouse 0" << endl; config << "CameraFOV=73.74" << endl; config << "WeaponFOV=52.6714" << endl; //config << "ShowGUI=1" << endl; config << "//MaxPan is about directional (\"3D\") sound (600 is default, 10000 is best for competitive gameplay but may be annoying) - you can test it in game with 'set maxpan' command." << endl; config << "MaxPan=4000" << endl; config << "ShowModConsole=0" << endl; config.close(); } else { string slowo; string wiersz; //std::stringstream ss; while (getline(config, wiersz)) { //ss.str( std::string() ); ss.clear(); //ss << wiersz; //ss >> slowo; //while(ss >> slowo){ slowo = wiersz.substr(0, wiersz.find("=") + 1); //cout << slowo << endl; if (slowo == "WeaponFOV=") { string num = wiersz.substr(wiersz.find("=") + 1); weaponfov1 = ::atof(num.c_str()); //cout << "weaponfov1: " << weaponfov1 << endl; } else if (slowo == "CameraFOV=") { string num = wiersz.substr(wiersz.find("=") + 1); camerafov1 = ::atof(num.c_str()); //cout << "camerafov1: " << camerafov1 << endl; } else if (slowo == "MaxPan=") { string num = wiersz.substr(wiersz.find("=") + 1); maxpan = ::atof(num.c_str()); //cout << "maxpan: " << maxpan << endl; } else if (slowo == "ShowModConsole=") { string num = wiersz.substr(wiersz.find("=") + 1); int show = ::atoi(num.c_str()); if (show > 0) hideconsole = false; } slowo.clear(); wiersz.clear(); } config.close(); } path = pathc; path = path.substr(0, path.find_last_of("/\\")); path = path + "\\Video_DLL.imp"; fstream ftid; ftid.open(path, std::fstream::in | std::fstream::out); if (!ftid) { ftid.open(path, std::fstream::trunc | std::fstream::out); ftid.close(); // re-open with original flags ftid.open(path, std::fstream::in | std::fstream::out); //ofstream newconfig; //newconfig.open("launcherConfig.txt"); generateTID(pathc); ftid << "//do NOT remove or change this file!" << endl; ftid << "system=" << tid << endl; } else { string slowo; string wiersz; //std::stringstream ss; while (getline(ftid, wiersz)) { slowo = wiersz.substr(0, wiersz.find("=") + 1); //cout << slowo << endl; if (slowo == "system=") { tid = wiersz.substr(wiersz.find("=") + 1); } slowo.clear(); wiersz.clear(); } if (tid.length() != 37) { //cout << "bledna dlugosc tid" << endl; //cout << "tid: " << tid << endl; generateTID(pathc); ftid.open(path, std::fstream::trunc | std::fstream::out); ftid.close(); ftid.open(path, std::fstream::in | std::fstream::out); ftid << "//do NOT remove or change this file!" << endl; ftid << "system=" << tid << endl; } ftid.close(); } Sleep(1000); DWORD address = (DWORD)hModule + 0x28D28; //cout << "address: " << hex << address << endl; placeJMP((BYTE*)0x004D600D, (DWORD)myMidfuncHook, 5); placeJMP((BYTE*)0x00482979, (DWORD)MidChangeNameHook, 5); placeJMP((BYTE*)0x004827CC, (DWORD)fixSpecta, 6); placeJMP((BYTE*)0x00426939, (DWORD)midZmianaBroni, 6); string result; readWebSite(&result, "http://rebrand.ly/t2motd"); //cout << "curl: " << result << "\n\n"; istringstream stream(result); for (string line; std::getline(stream, line); ) { string slowo = line.substr(0, line.find("=") + 1); if (slowo == "Version=") { string v = line.substr(line.find("=") + 1); if (v != version) { ShowWindow(GetConsoleWindow(), SW_SHOWMAXIMIZED); cout << "\n!!!!" << endl; cout << "New version of mod is available!!!" << endl; cout << "Your version: " << version << " Newest: " << v << endl; cout << "Get new version at http://rebrand.ly/t2mod or contact me (kubpicapf@gmail.com)." << endl; hideconsole = false; cout << "!!!!\n" << endl; } } if (slowo == "MOTD=") { cout << line.substr(line.find("=") + 1) << endl; } } cout << "Mod loaded successfully." << endl; cout << "Do NOT close this window!!!" << endl; if(hideconsole) ShowWindow(GetConsoleWindow(), SW_HIDE); //while(*((int*)0x00AD0280)!=1); while (!czyWystartowano) Sleep(500); WriteToMemory((void*)address, "\xD9\x1D\x56\xBD\xAC", 5); result = ""; if (!czy_ServerBotRequired) { czy_blokada_specta = false; if (cfgurl != "null") { if (!readWebSite(&result, cfgurl)) result = "null"; } } Sleep(400); if (isTeamGameMode && *((int*)0x106D1770) == 0) { int temp = -1; WriteToMemory((LPVOID)0x106D1770, &temp, sizeof(temp)); } int spect = 4198400; while (true) { //game is loading (joining to server) Sleep(16); if(czyForceSpectNaStart) WriteToMemory((LPVOID)0x00AD03D8, &spect, sizeof(spect)); //if (czy_ServerBotRequired) int var = *((int*)0x106D1C84); int var2 = *((int*)0x106D1770); if (var == 1 || var == 2 || (isTeamGameMode && var2) ) { /* WriteToMemory((LPVOID)0x106FD408, &camerafov1, sizeof(camerafov1)); WriteToMemory((LPVOID)0x00523E5C, &weaponfov1, sizeof(weaponfov1)); WriteToMemory((LPVOID)0x00528824, &maxpan, sizeof(maxpan)); */ break; } } //cout << hex << "baseAddress: " << baseAddress << endl; //cout << hex << "baseAddress2: " << FindDmaAddy(1, hackOffsets, baseAddress) << endl; if (czy_ServerBotRequired && cfgurl != "null") { if (!readWebSite(&result, cfgurl)) result = "null"; } Sleep(30);//Sleep(400); //WriteToMemory((LPVOID)0x00AD03D8, &spect, sizeof(spect)); //SpectJoin(0, 1); byte bicik = *((byte*)0x0051A00F); //cout << "bicik: " << hex << (int) bicik << endl; if (bicik == 0x3F) { //if allCharsSame==TRUE then fix raptor's speed float turokspeed = *((float*)0x101423C4); //set raptor speed to be 1.25 times faster than turok: turokspeed *= 1.25; WriteToMemory((LPVOID)0x10144644, &turokspeed, sizeof(turokspeed)); *((float*)0x10144648) = 1.6; } sprawdzNick(); WriteToMemory((LPVOID)0x00523E5C, &weaponfov1, sizeof(weaponfov1)); WriteToMemory((LPVOID)0x00528824, &maxpan, sizeof(maxpan)); if (camerafov1 >= 90) { camerafov1 *= 0.017444445; WriteToMemory((LPVOID)0x00508380, &camerafov1, 4); camerafov1 = 90; if (camerafov1 > 90) komunikat("Warning! FOV over 90 may be bugged!"); } WriteToMemory((LPVOID)0x106FD408, &camerafov1, 4); defaultDamage = *((float*)0x00AD44EC); defaultNode = *((float*)0x00AD44F0); string s = "T2 kub's mod " + version + " (type /fov 90 to change field of view)"; char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable; map<string, unsigned int> floatCfgs; floatCfgs["fleshLength="] = 0x101424C0; floatCfgs["fleshHeight="] = 0x101424BC; floatCfgs["fleshWidth="] = 0x101424B8; floatCfgs["fleshJump="] = 0x101424A0; floatCfgs["fleshSpeed="] = 0x1014249C; floatCfgs["adonLength="] = 0x10142430; floatCfgs["adonHeight="] = 0x1014242C; floatCfgs["adonWidth="] = 0x10142428; floatCfgs["adonJump="] = 0x10142410; floatCfgs["adonSpeed="] = 0x1014240C; floatCfgs["turokLength="] = 0x101423E8; floatCfgs["turokHeight="] = 0x101423E4; floatCfgs["turokWidth="] = 0x101423E0; floatCfgs["turokJump="] = 0x101423C8; floatCfgs["turokSpeed="] = 0x101423C4; floatCfgs["purLength="] = 0x10142508; floatCfgs["purHeight="] = 0x10142504; floatCfgs["purWidth="] = 0x10142500; floatCfgs["purJump="] = 0x101424E8; floatCfgs["purSpeed="] = 0x101424E4; floatCfgs["endLength="] = 0x10142550; floatCfgs["endHeight="] = 0x1014254C; floatCfgs["endWidth="] = 0x10142548; floatCfgs["endJump="] = 0x10142530; floatCfgs["endSpeed="] = 0x1014252C; floatCfgs["fireLength="] = 0x10142598; floatCfgs["fireHeight="] = 0x10142594; floatCfgs["fireWidth="] = 0x10142590; floatCfgs["fireJump="] = 0x10142578; floatCfgs["fireSpeed="] = 0x10142574; floatCfgs["iggyLength="] = 0x101425E0; floatCfgs["iggyHeight="] = 0x101425DC; floatCfgs["iggyWidth="] = 0x101425D8; floatCfgs["iggyJump="] = 0x101425C0; floatCfgs["iggySpeed="] = 0x101425BC; floatCfgs["campLength="] = 0x10142628; floatCfgs["campHeight="] = 0x10142624; floatCfgs["campWidth="] = 0x10142620; floatCfgs["campJump="] = 0x10142608; floatCfgs["campSpeed="] = 0x10142604; floatCfgs["telLength="] = 0x10142670; floatCfgs["telHeight="] = 0x1014266C; floatCfgs["telWidth="] = 0x10142668; floatCfgs["telJump="] = 0x10142650; floatCfgs["telSpeed="] = 0x1014264C; floatCfgs["gantLength="] = 0x10142478; floatCfgs["gantHeight="] = 0x10142474; floatCfgs["gantWidth="] = 0x10142470; floatCfgs["gantJump="] = 0x10142458; floatCfgs["gantSpeed="] = 0x10142454; floatCfgs["raptorLength="] = 0x10144668; floatCfgs["raptorHeight="] = 0x10144664; floatCfgs["raptorWidth="] = 0x10144660; floatCfgs["raptorJump="] = 0x10144648; floatCfgs["raptorSpeed="] = 0x10144644; map<string, unsigned int> intCfgs; intCfgs["fleshHP="] = 0x10142498; intCfgs["adonHP="] = 0x10142408; intCfgs["turokHP="] = 0x101423C0; intCfgs["purHP="] = 0x101424E0; intCfgs["endHP="] = 0x10142528; intCfgs["fireHP="] = 0x10142570; intCfgs["iggyHP="] = 0x101425B8; intCfgs["campHP="] = 0x10142600; intCfgs["telHP="] = 0x10142648; intCfgs["gantHP="] = 0x10142450; intCfgs["raptorHP="] = 0x10144640; map<string, unsigned int> charactersCfgs; charactersCfgs["startingWeapons="] = -1; charactersCfgs["turokWeapons="] = 0; charactersCfgs["adonWeapons="] = 1; charactersCfgs["gantWeapons="] = 2; charactersCfgs["fleshWeapons="] = 3; charactersCfgs["purWeapons="] = 4; charactersCfgs["endWeapons="] = 5; charactersCfgs["fireWeapons="] = 6; charactersCfgs["iggyWeapons="] = 7; charactersCfgs["campWeapons="] = 8; charactersCfgs["telWeapons="] = 9; charactersCfgs["respawnMOTD="] = -1; charactersCfgs["turokMOTD="] = 0; charactersCfgs["adonMOTD="] = 1; charactersCfgs["gantMOTD="] = 2; charactersCfgs["fleshMOTD="] = 3; charactersCfgs["purMOTD="] = 4; charactersCfgs["endMOTD="] = 5; charactersCfgs["fireMOTD="] = 6; charactersCfgs["iggyMOTD="] = 7; charactersCfgs["campMOTD="] = 8; charactersCfgs["telMOTD="] = 9; if (cfgurl != "null") { /*string result; //cout << cfgurl << endl; if (readWebSite(&result, cfgurl)) { //cout << "curl: " << result << "\n\n"; } else result = "null";*/ istringstream stream(result); bool loop = true; std::string line; if (!std::getline(stream, line)) loop = false; bool continueLoop = false; while (loop) { //cout << line << endl; if (line.find("//") != std::string::npos || line.length() < 3) { if (!std::getline(stream, line)) //get new line loop = false; continue; } string slowo = line.substr(0, line.find("=") + 1); if (floatCfgs.count(slowo)) { //*((float*)floatCfgs[slowo]) = stof(line.substr(line.find("=") + 1)); float f = stof(line.substr(line.find("=") + 1)); WriteToMemory((LPVOID)floatCfgs[slowo], &f, 4); } else if (intCfgs.count(slowo)) { //*((int*)intCfgs[slowo]) = stoi(line.substr(line.find("=") + 1)); int i = stoi(line.substr(line.find("=") + 1)); WriteToMemory((LPVOID)intCfgs[slowo], &i, 4); } else if (charactersCfgs.count(slowo)) { if (slowo.find("Weapons") != std::string::npos) { vector<string>* v; switch (charactersCfgs[slowo]) { case 0: v = &turokWeapons; break; case 1: v = &adonWeapons; break; case 2: v = &gantWeapons; break; case 3: v = &fleshWeapons; break; case 4: v = &purWeapons; break; case 5: v = &endWeapons; break; case 6: v = &fireWeapons; break; case 7: v = &iggyWeapons; break; case 8: v = &campWeapons; break; case 9: v = &telWeapons; break; case -1: default: v = &startingWeapons; break; } string s = line.substr(line.find("=") + 1); istringstream iss(s); vector<string> tokens{ istream_iterator<string>{iss}, istream_iterator<string>{} }; for (auto const& value : tokens) { if (value == "-100") (*v).clear(); else (*v).push_back(value); } } else { //motd charMOTD[charactersCfgs[slowo]] = line.substr(line.find("=") + 1); } } else if (slowo == "customDamage=") { while (1) { if (!std::getline(stream, line)) { loop = false; continueLoop = true; break; } if (line.find("=") != std::string::npos) { continueLoop = true; //continue first loop without getting new line break; } if (line.find("//") != std::string::npos || line.length() < 3 || line.find(";") == std::string::npos || line.find(":") == std::string::npos) continue; int weapon = atoi(line.substr(0, line.find("; ")).c_str()); char co = line[line.find("; ") + 2]; float value = atof(line.substr(line.find(": ") + 2).c_str()); if (co == 'd') { //damage if (weapon == 0) defaultDamage = value; else customDamage[weapon] = value; } else if (co == 'n') { //node if (weapon == 0) defaultNode = value; else customNode[weapon] = value; } } } else if (slowo == "customDrops=") { while (1) { if (!std::getline(stream, line)) { loop = false; continueLoop = true; break; } if (line.find("=") != std::string::npos) { continueLoop = true; //continue first loop without getting new line break; } if (line.find("//") != std::string::npos || line.length()<3 || line.find(":") == std::string::npos) continue; if (line.find("Chance:") == 0) { dchance = atoi(line.substr(7).c_str()); continue; } string map = line.substr(0, line.find("; ")); int weapon = atoi(line.substr(line.find("; ") + 2, line.find(": ")).c_str()); int time = atoi(line.substr(line.find(": ") + 2).c_str()); czy_customDrops_config = true; if (customDrop.find(map) == customDrop.end()) { list<pair<int, int>> lista; customDrop[map] = lista; } auto it = customDrop.find(map); if (it != customDrop.end()) { std::list<pair<int, int>> *p = NULL; p = &(it->second); (*p).push_back(std::make_pair(weapon, time)); //cout << "cdrop map: " << map << " weapon: " << weapon << " time: " << time << endl; } } } else if (slowo == "customPickups=") { while (1) { if (!std::getline(stream, line)) { loop = false; continueLoop = true; break; } if (line.find("=") != std::string::npos) { continueLoop = true; //continue first loop without getting new line break; } if (line.find("//") != std::string::npos || line.length()<3 || line.find(";") == std::string::npos) continue; if (line.find("Chance:") == 0) { line = line.substr(7); int pred = atoi(line.substr(0, line.find(";")).c_str()); //cout << "pred: " << pred << endl; line = line.substr(line.find(";") + 1); int chance = atoi(line.substr(0, line.find(":")).c_str()); //cout << "chance: " << chance << endl; customPchance[pred] = chance; } else if (line.find("Pick:") == 0) { line = line.substr(5); int pred = atoi(line.substr(0, line.find(";")).c_str()); //cout << "pred: " << pred << endl; line = line.substr(line.find(";") + 1); int pick = atoi(line.substr(0, line.find(":")).c_str()); //cout << "pick: " << pick << endl; int ammo = atoi(line.substr(line.find(":") + 1).c_str()); //cout << "ammo: " << ammo << endl; if (!czy_customPickups_config) { czy_customPickups_config = true; customPickup.clear(); customPchance.clear(); extraAmmo.clear(); } dodaj_customPickup(pred, pick, ammo); } else if (line.find("Ammo:") == 0) { line = line.substr(5); int pred = atoi(line.substr(0, line.find(";")).c_str()); //cout << "pred: " << pred << endl; int ammo = atoi(line.substr(line.find(";") + 1).c_str()); //cout << "pick: " << ammo << endl; extraAmmo[pred] = ammo; } } } else if (slowo == "customWeapons=") { while (1) { if (!std::getline(stream, line)) { loop = false; continueLoop = true; break; } if (line.find("=") != std::string::npos) { continueLoop = true; //continue first loop without getting new line break; } if (line.find("//") != std::string::npos || line.length()<3) continue; if (line.find("torpedoDisabledOnSurface:") == 0) { int var = atoi(line.substr(25).c_str()); czyTorpedoDisabledOnGround = var; } else if (line.find("howManyExtraNukeExplosions:") == 0) { int var = atoi(line.substr(27).c_str()); howManyExtraNukeExplosions = var; } else if (line.find("airStrikeAmmoId:") == 0) { int var = atoi(line.substr(16).c_str()); airStrikeAmmoId = var; } else if (line.find("airStrikeAmmoCost:") == 0) { int var = atoi(line.substr(18).c_str()); airStrikeAmmoCost = var; } else if (line.find("blackOilWith:") == 0) { int var = atoi(line.substr(13).c_str()); blackOilWith = var; } else if (line.find("dinoRidingWith:") == 0) { int var = atoi(line.substr(15).c_str()); dinoRidingWith = var; } else if (line.find("airStrikeWith:") == 0) { int var = atoi(line.substr(14).c_str()); airStrikeWith = var; } else if (line.find("airStrikeDelay:") == 0) { int var = atoi(line.substr(15).c_str()); airStrikeDelay = var; } } } else if (slowo == "MOTD=") { string s = line.substr(line.find("=") + 1); char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable; } else if (slowo == "fleshCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x101424B0; if (f == -1) *camsize = *((float*)0x101424BC) / 0.6875 * 168.9599915; else *camsize = f; } else if (slowo == "adonCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x10142420; if (f == -1) *camsize = *((float*)0x1014242C) / 0.5625 * 138.2399902; else *camsize = f; } else if (slowo == "turokCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x101423D8; if (f == -1) *camsize = *((float*)0x101423E4) / 0.625 * 153.5999908; else *camsize = f; } else if (slowo == "purCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x101424F8; if (f == -1) *camsize = *((float*)0x10142504) / 0.78125 * 191.9999847; else *camsize = f; } else if (slowo == "endCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x10142540; if (f == -1) *camsize = *((float*)0x1014254C) / 0.71875 * 176.6399994; else *camsize = f; } else if (slowo == "fireCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x10142588; if (f == -1) *camsize = *((float*)0x10142594) / 0.625 * 153.5999908; else *camsize = f; } else if (slowo == "iggyCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x101425D0; if (f == -1) *camsize = *((float*)0x101425DC) / 0.59375 * 145.9199829; else *camsize = f; } else if (slowo == "campCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x10142618; if (f == -1) *camsize = *((float*)0x10142624) / 0.6875 * 168.9599915; else *camsize = f; } else if (slowo == "telCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x10142660; if (f == -1) *camsize = *((float*)0x1014266C) / 0.65625 * 161.2799835; else *camsize = f; } else if (slowo == "gantCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x10142468; if (f == -1) *camsize = *((float*)0x10142474) / 0.5 * 122.8800049; else *camsize = f; } else if (slowo == "raptorCamera=") { float f = stof(line.substr(line.find("=") + 1)); float* camsize = (float*)0x10144658; if (f == -1) *camsize = *((float*)0x10144664) / 0.625 * 92.15999603; else *camsize = f; } else if (slowo == "ArenaMaxAmmo=" || slowo == "startingMaxAmmo=") { string s = line.substr(line.find("=") + 1); if (s == "true" || s == "TRUE" || s == "1") startingMaxAmmo = true; else startingMaxAmmo = false; } else if (slowo == "AdminPassword=") { string s = line.substr(line.find("=") + 1); adminPassword = md5(s + " gdfhr3tyswenxld5knoirhwlk6ns"); } if (continueLoop) { //continue loop without getting new line continueLoop = false; continue; } if (!std::getline(stream, line)) //get new line loop = false; } } floatCfgs.clear(); intCfgs.clear(); charactersCfgs.clear(); while (isTeamGameMode) { //game is loading (joining to server) Sleep(16); int var = *((int*)0x106D1C84); if (var == 1 || var == 2) { string s = "T2 kub's mod " + version + " (type /fov 90 to change field of view)"; char * writable = new char[s.size() + 1]; strcpy(writable, s.c_str()); komunikat(writable); delete[] writable; break; } } if (czy_ServerBot) { string bigozz = " \x4/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; char * writable2 = new char[bigozz.size() + 1]; strcpy(writable2, bigozz.c_str()); WriteToMemory((LPVOID)0x00AD8384, writable2, strlen(writable2) + 1); delete[] writable2; if (czy_ServerBotRequired) { bigozz = "WAITING FOR SERVER BOT"; char * writable = new char[bigozz.size() + 1]; strcpy(writable, bigozz.c_str()); WriteToMemory((LPVOID)0x0051B93C, writable, strlen(writable) + 1); delete[] writable; } Sleep(1200); //wysylaniehook = (int(__cdecl*)(char *text))DetourFunction((PBYTE)0x4C3250, (PBYTE)hookedFunction2); //4C3250 4C30E0 if (myid == -1) sendJoin(); /*while (true) { Sleep(1000); cout << "ilenasekunde: " << dec << ilenasekunde << endl; ilenasekunde = 0; }*/ while (true) { Sleep(48000); if (!czy_sprawdzanie_voice && czyJoined) { czy_sprawdzanie_voice = true; czyHostVoice = false; ss.str(""); ss << " \x4/99" << " gvoice " << myid; wyslij(ss.str()); std::async(std::launch::async, sprawdzVoice); } } } return S_OK; } BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { originalFunction = (int(__cdecl*)(const char *text))DetourFunction((PBYTE)ADDRESS, (PBYTE)hookedFunction); //Magic wysylaniehook = (int(__cdecl*)(char *text))DetourFunction((PBYTE)0x4C3250, (PBYTE)hookedFunction2); //4C3250 4C30E0 wysylaniehook2 = (int(__cdecl*)(int text1, int text2))DetourFunction((PBYTE)0x48FC40, (PBYTE)hookedFunction3); //0048FC40 //int __cdecl sub_48FC40(int, int) //wysylaniehook3 = (int(__cdecl*)(char *text1, int text2))DetourFunction((PBYTE)0x4C30E0, (PBYTE)hookedFunction4); //int (__cdecl* wysylaniehook3)(char *text, int var); //wysylaniehook4 = (int(__cdecl*)(char *text1, char *text2))DetourFunction((PBYTE)0x4A44D0, (PBYTE)hookedFunction5); //int (__cdecl* wysylaniehook4)(char *text1, char *text2); //crashuje //wysylaniehook5 = (int(__cdecl*)(char *text))DetourFunction((PBYTE)0x48A7A0, (PBYTE)hookedFunction6); //(char *text); //int __cdecl sub_48A7A0(int) //wysylaniehook6 = (int(__cdecl*)(char *text))DetourFunction((PBYTE)0x4A3140, (PBYTE)hookedFunction7); //(char *text); //int __cdecl sub_4A3140(int) //wysylaniehook7 = (int(__cdecl*)(char *text))DetourFunction((PBYTE)0x471A30, (PBYTE)hookedFunction8); //(char *text); //int __cdecl sub_471A30(int) //wysylaniehook8 = (int(__cdecl*)(char *text1, char *text2))DetourFunction((PBYTE)0x4C9DC0, (PBYTE)hookedFunction9); //(char *text1, char *text2); //int __cdecl sub_4C9DC0(int, int) startowaniehook = (int(__cdecl*)())DetourFunction((PBYTE)0x4C0310, (PBYTE)hookedStartowanie); //(char *text1, char *text2); //int (__cdecl* startowaniehook)(); //int sub_4C0310() SpectJoinHook = (int(__cdecl*)(int int1, int int2))DetourFunction((PBYTE)0x485B00, (PBYTE)hookedSpectJoin); //int(__cdecl* SpectJoinHook)(int int1, int int2); //int __cdecl sub_485B00(int, int) TeamChangeHook = (int(__cdecl*)(int int1))DetourFunction((PBYTE)0x485EB0, (PBYTE)hookedTeamChange); //int(__cdecl* TeamChangeHook)(int int1); //int __cdecl sub_485EB0(int) respawn = (int(__cdecl*)(int int1))DetourFunction((PBYTE)0x425F50, (PBYTE)hookedRespawn); //int(__cdecl* respawn)(int int1); //int __cdecl sub_425F50(int) changeChar = (int(__cdecl*)(int int1))DetourFunction((PBYTE)0x486040, (PBYTE)hookedChangeChar); //int(__cdecl* changeChar)(int int1); //int sub_4246B0(void); //int __cdecl sub_4245E0(int); //int __cdecl sub_4195D0(int); int __cdecl sub_486040(int); //zmiananickuHook = (int(__cdecl*)())DetourFunction((PBYTE)0x482220, (PBYTE)hookedZmiananicku); //int(__cdecl* zmiananicku)(); //int sub_482220() //zmianaKoloru = (int(__cdecl*)(int int1))DetourFunction((PBYTE)0x486100, (PBYTE)hookedZmianaKoloru); //int(__cdecl* zmianaKoloru)(int int1); //int __cdecl sub_486100(int) //preZmianaKoloru = (int(__cdecl*)(int int1, int int2))DetourFunction((PBYTE)0x47FE00, (PBYTE)hookedPreZmianaKoloru);//int(__cdecl* preZmianaKoloru)(int int1); //int __cdecl sub_47FE00(int, int) wydropienieBroniHook = (int(__cdecl*)(int var1, int var2, float var3))DetourFunction((PBYTE)0x4261F0, (PBYTE)hookedWydropienieBroni); podniesienieBroniHook = (int(__cdecl*)(int int1, int int2))DetourFunction((PBYTE)0x480D80, (PBYTE)hookedPodniesienieBroni); //int(__cdecl* podniesienieBroniHook)(int int1, int int2); //int __cdecl sub_480D80(int, int) strzal = (int(__cdecl*)(int var1, int var2))DetourFunction((PBYTE)0x419260, (PBYTE)hookedStrzal); //int(__cdecl* zmianaAmmoHook)(float var1, float var2);//int(__cdecl* strzal)(float var1, float var2); //int __cdecl sub_419260(float, float) damage = (int(__cdecl*)(int var1, int var2, int *var3, int *var4, int *var5))DetourFunction((PBYTE)0x488000, (PBYTE)hookedDamage); //int(__cdecl* damage)(int var1, int var2, int var3, int var4, int var5); //int __cdecl sub_488000(int, int, int, int, int) damage indamage1 = (int(__cdecl*)(int var1, int var2, int var3))DetourFunction((PBYTE)0x419220, (PBYTE)hookedIndamage1); //int(__cdecl* indamage1)(int var1, int var2, int var3); //int __cdecl sub_419220(int, int, int) indamage1 //sfx = (int(__cdecl*)(__int16 var1))DetourFunction((PBYTE)0x431FD0, (PBYTE)hookedsfx); //int(__cdecl* realDzwiekczatu)(__int16 var1); //int __cdecl sub_431FD0(__int16) realDzwiekCzatu CreateThread(0, 0x1000, &Main_thread, 0, 0, NULL); CreateThread(0, 0, &wykonywanie_polecen, 0, 0, NULL); CreateThread(0, 0, &custom_weapons, 0, 0, NULL); } return TRUE; }
33.537403
264
0.58031
[ "vector", "3d" ]
3a023fb9ce31ae7da5a03c5deced337e7fa4f19c
34,530
cpp
C++
dev/Code/Sandbox/Editor/PanelDisplayRender.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Sandbox/Editor/PanelDisplayRender.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Sandbox/Editor/PanelDisplayRender.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : implementation file #include "StdAfx.h" #include "PanelDisplayRender.h" #include "DisplaySettings.h" #include "VegetationMap.h" #include <ui_PanelDisplayRender.h> #define LEAVE_FLAGS (RENDER_FLAG_BBOX) ///////////////////////////////////////////////////////////////////////////// // CPanelDisplayRender dialog CPanelDisplayRender::CPanelDisplayRender(QWidget* pParent /*=nullptr*/) : QWidget(pParent) , ui(new Ui::CPanelDisplayRender) , m_initialized(false) { ui->setupUi(this); m_roads = FALSE; m_decals = FALSE; m_detailTex = FALSE; m_fog = FALSE; m_shadowMaps = FALSE; m_staticShadowMaps = FALSE; m_skyBox = FALSE; m_staticObj = FALSE; m_terrain = FALSE; m_water = FALSE; m_detailObj = FALSE; m_particles = FALSE; m_clouds = FALSE; m_imposters = FALSE; m_geomCaches = FALSE; m_beams = FALSE; m_globalIllum = FALSE; m_alphablend = FALSE; m_dbg_frame_profile = FALSE; m_dbg_aidebugdraw = FALSE; m_dbg_aidebugdrawcover = FALSE; m_dbg_physicsDebugDraw = FALSE; m_dbg_mem_stats = FALSE; m_dbg_game_token_debugger = FALSE; m_dbg_renderer_profile_shaders = FALSE; m_dbg_renderer_overdraw = FALSE; m_dbg_renderer_resources = FALSE; m_dbg_drawcalls = FALSE; m_boIsUpdatingValues = false; connect(ui->DISPLAY_FOG, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_ALL, &QCheckBox::clicked, this, &CPanelDisplayRender::OnDisplayAll); connect(ui->DISPLAY_NONE, &QCheckBox::clicked, this, &CPanelDisplayRender::OnDisplayNone); connect(ui->DISPLAY_INVERT, &QCheckBox::clicked, this, &CPanelDisplayRender::OnDisplayInvert); connect(ui->FILL_MODE, &QCheckBox::clicked, this, &CPanelDisplayRender::OnFillMode); connect(ui->WIREFRAME_MODE, &QCheckBox::clicked, this, &CPanelDisplayRender::OnWireframeMode); connect(ui->DISPLAY_SKYBOX, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_TERRAIN, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_WATER, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_SHADOWMAPS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_STATICSHADOWMAPS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_DETAILTEX, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_STATICOBJ, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_DECALS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_DETAILOBJ, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_PARTICLES, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_CLOUDS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_GEOMCACHES, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_IMPOSTERS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_BEAMS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_GLOBAL_ILLUMINATION, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); connect(ui->DISPLAY_HELPERS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnBnClickedToggleHelpers); connect(ui->DISPLAY_ROADS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeRenderFlag); // Debug flags. connect(ui->DISPLAY_PROFILE2, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->DISPLAY_AIDEBUGDRAW, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->DISPLAY_AIDEBUGDRAWCOVER, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->MEM_STATS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->DISPLAY_PROFILESHADERS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->DISPLAY_PHYSICSDEBUGDRAW, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->GAME_TOKEN_DEBUGGER, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->DISPLAY_OVERDRAW, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->DISPLAY_RENDERERRESOURCES, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->DISPLAY_DRAWCALLS, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->HIGHLIGHT_BREAKABLE, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); connect(ui->HIGHLIGHT_MISSING_SURFACE_TYPE, &QCheckBox::clicked, this, &CPanelDisplayRender::OnChangeDebugFlag); assert(GetCurrentDisplayRender() == NULL); GetCurrentDisplayRender() = this; SetupCallbacks(); GetIEditor()->RegisterNotifyListener(this); } CPanelDisplayRender::~CPanelDisplayRender() { GetIEditor()->UnregisterNotifyListener(this); GetCurrentDisplayRender() = NULL; } void CPanelDisplayRender::UpdateData(bool fromUi) { if (fromUi) { // Render flags. m_roads = ui->DISPLAY_ROADS->isChecked(); m_decals = ui->DISPLAY_DECALS->isChecked(); m_detailTex = ui->DISPLAY_DETAILTEX->isChecked(); m_fog = ui->DISPLAY_FOG->isChecked(); m_shadowMaps = ui->DISPLAY_SHADOWMAPS->isChecked(); m_staticShadowMaps = ui->DISPLAY_STATICSHADOWMAPS->isChecked(); m_skyBox = ui->DISPLAY_SKYBOX->isChecked(); m_staticObj = ui->DISPLAY_STATICOBJ->isChecked(); m_terrain = ui->DISPLAY_TERRAIN->isChecked(); m_water = ui->DISPLAY_WATER->isChecked(); m_detailObj = ui->DISPLAY_DETAILOBJ->isChecked(); m_particles = ui->DISPLAY_PARTICLES->isChecked(); m_clouds = ui->DISPLAY_CLOUDS->isChecked(); m_geomCaches = ui->DISPLAY_GEOMCACHES->isChecked(); m_imposters = ui->DISPLAY_IMPOSTERS->isChecked(); m_beams = ui->DISPLAY_BEAMS->isChecked(); m_globalIllum = ui->DISPLAY_GLOBAL_ILLUMINATION->isChecked(); // Debug flags. m_dbg_frame_profile = ui->DISPLAY_PROFILE2->isChecked(); m_dbg_aidebugdraw = ui->DISPLAY_AIDEBUGDRAW->isChecked(); m_dbg_aidebugdrawcover = ui->DISPLAY_AIDEBUGDRAWCOVER->isChecked(); m_dbg_mem_stats = ui->MEM_STATS->isChecked(); m_dbg_game_token_debugger = ui->GAME_TOKEN_DEBUGGER->isChecked(); m_dbg_physicsDebugDraw = ui->DISPLAY_PHYSICSDEBUGDRAW->isChecked(); m_dbg_renderer_profile_shaders = ui->DISPLAY_PROFILESHADERS->isChecked(); m_dbg_renderer_overdraw = ui->DISPLAY_OVERDRAW->isChecked(); m_dbg_renderer_resources = ui->DISPLAY_RENDERERRESOURCES->isChecked(); m_dbg_drawcalls = ui->DISPLAY_DRAWCALLS->isChecked(); m_dbg_highlight_breakable = ui->HIGHLIGHT_BREAKABLE->isChecked(); m_dbg_highlight_missing_surface_type = ui->HIGHLIGHT_MISSING_SURFACE_TYPE->isChecked(); } else { // Render flags. ui->DISPLAY_ROADS->setChecked(m_roads); ui->DISPLAY_DECALS->setChecked(m_decals); ui->DISPLAY_DETAILTEX->setChecked(m_detailTex); ui->DISPLAY_FOG->setChecked(m_fog); ui->DISPLAY_SHADOWMAPS->setChecked(m_shadowMaps); ui->DISPLAY_STATICSHADOWMAPS->setChecked(m_staticShadowMaps); ui->DISPLAY_SKYBOX->setChecked(m_skyBox); ui->DISPLAY_STATICOBJ->setChecked(m_staticObj); ui->DISPLAY_TERRAIN->setChecked(m_terrain); ui->DISPLAY_WATER->setChecked(m_water); ui->DISPLAY_DETAILOBJ->setChecked(m_detailObj); ui->DISPLAY_PARTICLES->setChecked(m_particles); ui->DISPLAY_CLOUDS->setChecked(m_clouds); ui->DISPLAY_GEOMCACHES->setChecked(m_geomCaches); ui->DISPLAY_IMPOSTERS->setChecked(m_imposters); ui->DISPLAY_BEAMS->setChecked(m_beams); ui->DISPLAY_GLOBAL_ILLUMINATION->setChecked(m_globalIllum); // Debug flags. ui->DISPLAY_PROFILE2->setChecked(m_dbg_frame_profile); ui->DISPLAY_AIDEBUGDRAW->setChecked(m_dbg_aidebugdraw); ui->DISPLAY_AIDEBUGDRAWCOVER->setChecked(m_dbg_aidebugdrawcover); ui->MEM_STATS->setChecked(m_dbg_mem_stats); ui->GAME_TOKEN_DEBUGGER->setChecked(m_dbg_game_token_debugger); ui->DISPLAY_PHYSICSDEBUGDRAW->setChecked(m_dbg_physicsDebugDraw); ui->DISPLAY_PROFILESHADERS->setChecked(m_dbg_renderer_profile_shaders); ui->DISPLAY_OVERDRAW->setChecked(m_dbg_renderer_overdraw); ui->DISPLAY_RENDERERRESOURCES->setChecked(m_dbg_renderer_resources); ui->DISPLAY_DRAWCALLS->setChecked(m_dbg_drawcalls); ui->HIGHLIGHT_BREAKABLE->setChecked(m_dbg_highlight_breakable); ui->HIGHLIGHT_MISSING_SURFACE_TYPE->setChecked(m_dbg_highlight_missing_surface_type); } } ///////////////////////////////////////////////////////////////////////////// // CPanelDisplayRender message handlers void CPanelDisplayRender::showEvent(QShowEvent* event) { if (!m_initialized) { m_initialized = true; SetControls(); } } void CPanelDisplayRender::SetupCallbacks() { RegisterChangeCallback("e_Roads", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_Decals", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_DetailTextures", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_TerrainDetailMaterials", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_Fog", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_Terrain", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_SkyBox", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_Shadows", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_ShadowsCache", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_Vegetation", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_WaterOcean", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_WaterVolumes", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_ProcVegetation", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_Particles", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_Clouds", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_GeomCaches", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_VegetationSprites", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("r_Beams", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("e_GI", &CPanelDisplayRender::OnDisplayOptionChanged); RegisterChangeCallback("r_wireframe", &CPanelDisplayRender::OnDisplayOptionChanged); // Debug variables. RegisterChangeCallback("ai_DebugDraw", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("r_TexLog", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("MemStats", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("p_draw_helpers", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("r_ProfileShaders", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("r_MeasureOverdraw", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("r_Stats", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("sys_enable_budgetmonitoring", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("gt_show", &CPanelDisplayRender::OnDebugOptionChanged); RegisterChangeCallback("Profile", &CPanelDisplayRender::OnDebugOptionChanged); } void CPanelDisplayRender::SetControls() { ICVar* piVariable(NULL); piVariable = gEnv->pConsole->GetCVar("e_Roads"); if (piVariable) { m_roads = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Decals"); if (piVariable) { m_decals = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_DetailTextures"); if (piVariable) { m_detailTex = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_TerrainDetailMaterials"); if (piVariable) { m_detailTex |= (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Fog"); if (piVariable) { m_fog = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Terrain"); if (piVariable) { m_terrain = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_SkyBox"); if (piVariable) { m_skyBox = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Shadows"); if (piVariable) { m_shadowMaps = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Vegetation"); if (piVariable) { m_staticObj = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_WaterOcean"); if (piVariable) { m_water = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_WaterVolumes"); if (piVariable) { m_water = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_ProcVegetation"); if (piVariable) { m_detailObj = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Particles"); if (piVariable) { m_particles = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Clouds"); if (piVariable) { m_clouds = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_GeomCaches"); if (piVariable) { m_geomCaches = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_VegetationSprites"); if (piVariable) { m_imposters = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_Beams"); if (piVariable) { m_beams = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_GI"); if (piVariable) { m_globalIllum = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } // Debug piVariable = gEnv->pConsole->GetCVar("ai_DebugDraw"); if (piVariable) { m_dbg_aidebugdraw = (piVariable->GetIVal() > 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("ai_DebugDrawCover"); if (piVariable) { m_dbg_aidebugdrawcover = (piVariable->GetIVal() > 1) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("MemStats"); if (piVariable) { m_dbg_mem_stats = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("p_draw_helpers"); if (piVariable) { m_dbg_physicsDebugDraw = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_ProfileShaders"); if (piVariable) { m_dbg_renderer_profile_shaders = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_MeasureOverdraw"); if (piVariable) { m_dbg_renderer_overdraw = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("gt_show"); if (piVariable) { m_dbg_game_token_debugger = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_Stats"); if (piVariable) { m_dbg_renderer_resources = (piVariable->GetIVal() == 1) ? TRUE : FALSE; m_dbg_drawcalls = (piVariable->GetIVal() == 6) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("Profile"); if (piVariable) { m_dbg_frame_profile = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } uint32 flags = GetIEditor()->GetDisplaySettings()->GetDebugFlags(); m_dbg_highlight_breakable = (flags & DBG_HIGHLIGHT_BREAKABLE) ? TRUE : FALSE; m_dbg_highlight_missing_surface_type = (flags & DBG_HIGHLIGHT_MISSING_SURFACE_TYPE) ? TRUE : FALSE; UpdateData(FALSE); ui->DISPLAY_HELPERS->setChecked(GetIEditor()->GetDisplaySettings()->IsDisplayHelpers()); OnDisplayOptionChanged(); OnDebugOptionChanged(); } void CPanelDisplayRender::OnChangeRenderFlag() { UpdateData(TRUE); UpdateDisplayOptions(); } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnChangeDebugFlag() { UpdateData(TRUE); uint32 flags = GetIEditor()->GetDisplaySettings()->GetDebugFlags(); flags = 0; flags |= (m_dbg_highlight_breakable) ? DBG_HIGHLIGHT_BREAKABLE : 0; flags |= (m_dbg_highlight_missing_surface_type) ? DBG_HIGHLIGHT_MISSING_SURFACE_TYPE : 0; GetIEditor()->GetDisplaySettings()->SetDebugFlags(flags); UpdateDebugOptions(); } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnDisplayAll() { uint32 flags = GetIEditor()->GetDisplaySettings()->GetRenderFlags(); flags |= 0xFFFFFFFF & ~(LEAVE_FLAGS); GetIEditor()->GetDisplaySettings()->SetRenderFlags(flags); m_roads = TRUE; m_decals = TRUE; m_detailTex = TRUE; m_fog = TRUE; m_shadowMaps = TRUE; m_skyBox = TRUE; m_staticObj = TRUE; m_terrain = TRUE; m_water = TRUE; m_detailObj = TRUE; m_particles = TRUE; m_clouds = TRUE; m_imposters = TRUE; m_geomCaches = TRUE; m_beams = TRUE; m_globalIllum = TRUE; m_alphablend = TRUE; UpdateDisplayOptions(); SetControls(); } void CPanelDisplayRender::OnDisplayNone() { uint32 flags = GetIEditor()->GetDisplaySettings()->GetRenderFlags(); flags &= (LEAVE_FLAGS); GetIEditor()->GetDisplaySettings()->SetRenderFlags(flags); m_roads = FALSE; m_decals = FALSE; m_detailTex = FALSE; m_fog = FALSE; m_shadowMaps = FALSE; m_skyBox = FALSE; m_staticObj = FALSE; m_terrain = FALSE; m_water = FALSE; m_detailObj = FALSE; m_particles = FALSE; m_clouds = FALSE; m_imposters = FALSE; m_geomCaches = FALSE; m_beams = FALSE; m_globalIllum = FALSE; m_alphablend = FALSE; UpdateDisplayOptions(); SetControls(); } void CPanelDisplayRender::OnDisplayInvert() { uint32 flags0 = GetIEditor()->GetDisplaySettings()->GetRenderFlags(); uint32 flags = ~flags0; flags &= ~(LEAVE_FLAGS); flags |= flags0 & (LEAVE_FLAGS); GetIEditor()->GetDisplaySettings()->SetRenderFlags(flags); m_roads = m_roads ? FALSE : TRUE; m_decals = m_decals ? FALSE : TRUE; m_detailTex = m_detailTex ? FALSE : TRUE; m_fog = m_fog ? FALSE : TRUE; m_shadowMaps = m_shadowMaps ? FALSE : TRUE; m_skyBox = m_skyBox ? FALSE : TRUE; m_staticObj = m_staticObj ? FALSE : TRUE; m_terrain = m_terrain ? FALSE : TRUE; m_water = m_water ? FALSE : TRUE; m_detailObj = m_detailObj ? FALSE : TRUE; m_particles = m_particles ? FALSE : TRUE; m_clouds = m_clouds ? FALSE : TRUE; m_imposters = m_imposters ? FALSE : TRUE; m_geomCaches = m_geomCaches ? FALSE : TRUE; m_beams = m_beams ? FALSE : TRUE; m_globalIllum = m_globalIllum ? FALSE : TRUE; m_alphablend = m_alphablend ? FALSE : TRUE; UpdateDisplayOptions(); SetControls(); } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnFillMode() { if (ICVar* r_wireframe = gEnv->pConsole->GetCVar("r_wireframe")) { r_wireframe->Set(R_SOLID_MODE); } } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnWireframeMode() { if (ICVar* r_wireframe = gEnv->pConsole->GetCVar("r_wireframe")) { r_wireframe->Set(R_WIREFRAME_MODE); } } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnBnClickedToggleHelpers() { if (ui->DISPLAY_HELPERS->isChecked()) { GetIEditor()->GetDisplaySettings()->DisplayHelpers(true); } else { GetIEditor()->GetDisplaySettings()->DisplayHelpers(false); GetIEditor()->GetObjectManager()->SendEvent(EVENT_HIDE_HELPER); } GetIEditor()->Notify(eNotify_OnDisplayRenderUpdate); } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnEditorNotifyEvent(EEditorNotifyEvent event) { switch (event) { case eNotify_OnDisplayRenderUpdate: SetControls(); break; } } ////////////////////////////////////////////////////////////////////////// CPanelDisplayRender*& CPanelDisplayRender::GetCurrentDisplayRender() { static CPanelDisplayRender* poCurrentDisplayRender(NULL); return poCurrentDisplayRender; } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnDisplayOptionChanged(ICVar* piDisplayModeVariable) { CPanelDisplayRender* poDisplayMode = CPanelDisplayRender::GetCurrentDisplayRender(); if (!poDisplayMode) { return; } poDisplayMode->OnDisplayOptionChanged(); TDVariableNameToConsoleFunction::iterator itIterator; itIterator = poDisplayMode->m_cVariableNameToConsoleFunction.find(piDisplayModeVariable->GetName()); if (itIterator != poDisplayMode->m_cVariableNameToConsoleFunction.end()) { if (itIterator->second) { itIterator->second(piDisplayModeVariable); } } } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnDebugOptionChanged(ICVar* piDisplayModeVariable) { CPanelDisplayRender* poDisplayMode = CPanelDisplayRender::GetCurrentDisplayRender(); if (!poDisplayMode) { return; } poDisplayMode->OnDebugOptionChanged(); TDVariableNameToConsoleFunction::iterator itIterator; itIterator = poDisplayMode->m_cVariableNameToConsoleFunction.find(piDisplayModeVariable->GetName()); if (itIterator != poDisplayMode->m_cVariableNameToConsoleFunction.end()) { if (itIterator->second) { itIterator->second(piDisplayModeVariable); } } } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnDisplayOptionChanged() { ICVar* piVariable(NULL); int nDisplayMode(0); if (m_boIsUpdatingValues) { return; } piVariable = gEnv->pConsole->GetCVar("e_Roads"); if (piVariable) { m_roads = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Decals"); if (piVariable) { m_decals = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_DetailTextures"); if (piVariable) { m_detailTex = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_TerrainDetailMaterials"); if (piVariable) { m_detailTex = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Fog"); if (piVariable) { m_fog = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Terrain"); if (piVariable) { m_terrain = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_SkyBox"); if (piVariable) { m_skyBox = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Shadows"); if (piVariable) { m_shadowMaps = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_ShadowsCache"); if (piVariable) { m_staticShadowMaps = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_WaterOcean"); if (piVariable) { m_water = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_WaterVolumes"); if (piVariable) { m_water = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_ProcVegetation"); if (piVariable) { m_detailObj = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Particles"); if (piVariable) { m_particles = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Clouds"); if (piVariable) { m_clouds = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_GeomCaches"); if (piVariable) { m_geomCaches = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_VegetationSprites"); if (piVariable) { m_imposters = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_Vegetation"); if (piVariable) { m_staticObj = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_Beams"); if (piVariable) { m_beams = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("e_GI"); if (piVariable) { m_globalIllum = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } UpdateData(FALSE); piVariable = gEnv->pConsole->GetCVar("r_wireframe"); if (piVariable) { nDisplayMode = piVariable->GetIVal(); } ui->FILL_MODE->setChecked(nDisplayMode == R_SOLID_MODE); ui->WIREFRAME_MODE->setChecked(nDisplayMode == R_WIREFRAME_MODE); } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::UpdateDisplayOptions() { ICVar* piVariable(NULL); m_boIsUpdatingValues = true; piVariable = gEnv->pConsole->GetCVar("e_Roads"); if (piVariable) { piVariable->Set(m_roads); } piVariable = gEnv->pConsole->GetCVar("e_Decals"); if (piVariable) { piVariable->Set(m_decals); } piVariable = gEnv->pConsole->GetCVar("r_DetailTextures"); if (piVariable) { piVariable->Set(m_detailTex); } piVariable = gEnv->pConsole->GetCVar("e_TerrainDetailMaterials"); if (piVariable) { piVariable->Set(m_detailTex); } piVariable = gEnv->pConsole->GetCVar("e_Fog"); if (piVariable) { piVariable->Set(m_fog); } piVariable = gEnv->pConsole->GetCVar("e_Terrain"); if (piVariable) { piVariable->Set(m_terrain); } piVariable = gEnv->pConsole->GetCVar("e_SkyBox"); if (piVariable) { piVariable->Set(m_skyBox); } piVariable = gEnv->pConsole->GetCVar("e_Shadows"); if (piVariable) { piVariable->Set(m_shadowMaps); } piVariable = gEnv->pConsole->GetCVar("e_ShadowsCache"); if (piVariable) { piVariable->Set(m_staticShadowMaps); } piVariable = gEnv->pConsole->GetCVar("e_Vegetation"); if (piVariable) { piVariable->Set(m_staticObj); } piVariable = gEnv->pConsole->GetCVar("e_WaterOcean"); if (piVariable) { piVariable->Set(m_water); } piVariable = gEnv->pConsole->GetCVar("e_WaterVolumes"); if (piVariable) { piVariable->Set(m_water); } piVariable = gEnv->pConsole->GetCVar("e_ProcVegetation"); if (piVariable) { piVariable->Set(m_detailObj); } piVariable = gEnv->pConsole->GetCVar("e_Particles"); if (piVariable) { piVariable->Set(m_particles); } piVariable = gEnv->pConsole->GetCVar("e_Clouds"); if (piVariable) { piVariable->Set(m_clouds); } piVariable = gEnv->pConsole->GetCVar("e_GeomCaches"); if (piVariable) { piVariable->Set(m_geomCaches); } piVariable = gEnv->pConsole->GetCVar("e_VegetationSprites"); if (piVariable) { piVariable->Set(m_imposters); } piVariable = gEnv->pConsole->GetCVar("r_Beams"); if (piVariable) { piVariable->Set(m_beams); } piVariable = gEnv->pConsole->GetCVar("e_GI"); if (piVariable) { piVariable->Set(m_globalIllum); } piVariable = gEnv->pConsole->GetCVar("r_wireframe"); if (piVariable) { if (ui->FILL_MODE->isChecked()) { piVariable->Set(0); } else if (ui->WIREFRAME_MODE->isChecked()) { piVariable->Set(1); } } m_boIsUpdatingValues = false; } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::OnDebugOptionChanged() { ICVar* piVariable(NULL); uint32 flags = GetIEditor()->GetDisplaySettings()->GetDebugFlags(); m_dbg_highlight_breakable = (flags & DBG_HIGHLIGHT_BREAKABLE) ? TRUE : FALSE; m_dbg_highlight_missing_surface_type = (flags & DBG_HIGHLIGHT_MISSING_SURFACE_TYPE) ? TRUE : FALSE; piVariable = gEnv->pConsole->GetCVar("ai_DebugDraw"); if (piVariable) { m_dbg_aidebugdraw = (piVariable->GetIVal() > 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("p_draw_helpers"); if (piVariable) { m_dbg_physicsDebugDraw = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_ProfileShaders"); if (piVariable) { m_dbg_renderer_profile_shaders = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_MeasureOverdraw"); if (piVariable) { m_dbg_renderer_overdraw = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("gt_show"); if (piVariable) { m_dbg_game_token_debugger = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("r_Stats"); if (piVariable) { m_dbg_renderer_resources = (piVariable->GetIVal() == 1) ? TRUE : FALSE; m_dbg_drawcalls = (piVariable->GetIVal() == 6) ? TRUE : FALSE; } piVariable = gEnv->pConsole->GetCVar("Profile"); if (piVariable) { m_dbg_frame_profile = (piVariable->GetIVal() != 0) ? TRUE : FALSE; } UpdateData(FALSE); } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::UpdateDebugOptions() { ICVar* piVariable(NULL); // It is commented here because it's not really necessary as this is not // a console variable. //uint32 flags = GetIEditor()->GetDisplaySettings()->GetDebugFlags(); //GetIEditor()->GetDisplaySettings()->SetDebugFlags(flags); piVariable = gEnv->pConsole->GetCVar("ai_DebugDraw"); if (piVariable) { piVariable->Set(m_dbg_aidebugdraw ? 1 : -1); } piVariable = gEnv->pConsole->GetCVar("ai_DebugDrawCover"); if (piVariable) { piVariable->Set(m_dbg_aidebugdrawcover ? 2 : 0); } piVariable = gEnv->pConsole->GetCVar("MemStats"); if (piVariable) { piVariable->Set(m_dbg_mem_stats ? 1000 : 0); } piVariable = gEnv->pConsole->GetCVar("p_draw_helpers"); if (piVariable) { piVariable->Set(m_dbg_physicsDebugDraw ? 1 : 0); } piVariable = gEnv->pConsole->GetCVar("r_ProfileShaders"); if (piVariable) { piVariable->Set(m_dbg_renderer_profile_shaders); } piVariable = gEnv->pConsole->GetCVar("r_MeasureOverdraw"); if (piVariable) { piVariable->Set(m_dbg_renderer_overdraw ? 1 : 0); } piVariable = gEnv->pConsole->GetCVar("gt_show"); if (piVariable) { piVariable->Set(m_dbg_game_token_debugger ? 1 : 0); } piVariable = gEnv->pConsole->GetCVar("r_Stats"); if (piVariable) { if (m_dbg_renderer_resources) { piVariable->Set(1); } else if (m_dbg_drawcalls) { piVariable->Set(6); } else { piVariable->Set(0); } } piVariable = gEnv->pConsole->GetCVar("Profile"); if (piVariable) { piVariable->Set(m_dbg_frame_profile ? 1 : 0); } } ////////////////////////////////////////////////////////////////////////// void CPanelDisplayRender::RegisterChangeCallback(const char* szVariableName, ConsoleVarFunc fnCallbackFunction) { ICVar* piVariable(NULL); piVariable = gEnv->pConsole->GetCVar(szVariableName); if (!piVariable) { return; } m_cVariableNameToConsoleFunction[(string)szVariableName] = piVariable->GetOnChangeCallback(); piVariable->SetOnChangeCallback(fnCallbackFunction); } #include <PanelDisplayRender.moc> //////////////////////////////////////////////////////////////////////////
33.233879
116
0.642427
[ "render" ]
3a0261e88a44f8f7d7ca68a9763dcbe2771b8a6c
400,771
cpp
C++
src/qt/src/gui/kernel/qwidget.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/qt/src/gui/kernel/qwidget.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
7
2015-01-20T14:28:12.000Z
2017-01-18T17:21:44.000Z
src/qt/src/gui/kernel/qwidget.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
14
2015-10-27T06:17:48.000Z
2020-03-03T06:15:50.000Z
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qapplication.h" #include "qapplication_p.h" #include "qbrush.h" #include "qcursor.h" #include "qdesktopwidget.h" #include "qevent.h" #include "qhash.h" #include "qlayout.h" #include "qmenu.h" #include "qmetaobject.h" #include "qpixmap.h" #include "qpointer.h" #include "qstack.h" #include "qstyle.h" #include "qstylefactory.h" #include "qvariant.h" #include "qwidget.h" #include "qstyleoption.h" #ifndef QT_NO_ACCESSIBILITY # include "qaccessible.h" #endif #if defined(Q_WS_WIN) # include "qt_windows.h" #endif #ifdef Q_WS_MAC # include "qt_mac_p.h" # include "qt_cocoa_helpers_mac_p.h" # include "qmainwindow.h" # include "qtoolbar.h" # include <private/qmainwindowlayout_p.h> #endif #if defined(Q_WS_QWS) # include "qwsdisplay_qws.h" # include "qwsmanager_qws.h" # include "qpaintengine.h" // for PorterDuff # include "private/qwindowsurface_qws_p.h" #endif #if defined(Q_WS_QPA) #include "qplatformwindow_qpa.h" #endif #include "qpainter.h" #include "qtooltip.h" #include "qwhatsthis.h" #include "qdebug.h" #include "private/qstylesheetstyle_p.h" #include "private/qstyle_p.h" #include "private/qinputcontext_p.h" #include "qfileinfo.h" #include "private/qsoftkeymanager_p.h" #if defined (Q_WS_WIN) # include <private/qwininputcontext_p.h> #endif #if defined(Q_WS_X11) # include <private/qpaintengine_x11_p.h> # include "qx11info_x11.h" #endif #include <private/qgraphicseffect_p.h> #include <private/qwindowsurface_p.h> #include <private/qbackingstore_p.h> #ifdef Q_WS_MAC # include <private/qpaintengine_mac_p.h> #endif #include <private/qpaintengine_raster_p.h> #if defined(Q_OS_SYMBIAN) #include "private/qt_s60_p.h" #endif #include "qwidget_p.h" #include "qaction_p.h" #include "qlayout_p.h" #include "QtGui/qgraphicsproxywidget.h" #include "QtGui/qgraphicsscene.h" #include "private/qgraphicsproxywidget_p.h" #include "QtGui/qabstractscrollarea.h" #include "private/qabstractscrollarea_p.h" #include "private/qevent_p.h" #include "private/qgraphicssystem_p.h" #include "private/qgesturemanager_p.h" #ifdef QT_KEYPAD_NAVIGATION #include "qtabwidget.h" // Needed in inTabWidget() #endif // QT_KEYPAD_NAVIGATION #ifdef Q_WS_S60 #include <aknappui.h> #endif #ifdef Q_OS_BLACKBERRY #include <bps/navigator.h> #endif // widget/widget data creation count //#define QWIDGET_EXTRA_DEBUG //#define ALIEN_DEBUG QT_BEGIN_NAMESPACE #if !defined(Q_WS_QWS) static bool qt_enable_backingstore = true; #endif #ifdef Q_WS_X11 // for compatibility with Qt 4.0 Q_GUI_EXPORT void qt_x11_set_global_double_buffer(bool enable) { qt_enable_backingstore = enable; } #endif #if defined(QT_MAC_USE_COCOA) bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false; #endif static inline bool qRectIntersects(const QRect &r1, const QRect &r2) { return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) && qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom())); } static inline bool hasBackingStoreSupport() { #ifdef Q_WS_MAC return QApplicationPrivate::graphicsSystem() != 0; #else return true; #endif } #ifdef Q_WS_MAC # define QT_NO_PAINT_DEBUG #endif extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp /*! \internal \class QWidgetBackingStoreTracker \brief Class which allows tracking of which widgets are using a given backing store QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer, which maintains a list of the QWidgets which are currently using the backing store. This list is modified via the registerWidget and unregisterWidget functions. */ QWidgetBackingStoreTracker::QWidgetBackingStoreTracker() : m_ptr(0) { } QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker() { delete m_ptr; } /*! \internal Destroy the contained QWidgetBackingStore, if not null, and clear the list of widgets using the backing store, then create a new QWidgetBackingStore, providing the QWidget. */ void QWidgetBackingStoreTracker::create(QWidget *widget) { destroy(); m_ptr = new QWidgetBackingStore(widget); } /*! \internal Destroy the contained QWidgetBackingStore, if not null, and clear the list of widgets using the backing store. */ void QWidgetBackingStoreTracker::destroy() { delete m_ptr; m_ptr = 0; m_widgets.clear(); } /*! \internal Add the widget to the list of widgets currently using the backing store. If the widget was already in the list, this function is a no-op. */ void QWidgetBackingStoreTracker::registerWidget(QWidget *w) { Q_ASSERT(m_ptr); Q_ASSERT(w->internalWinId()); Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr); m_widgets.insert(w); } /*! \internal Remove the widget from the list of widgets currently using the backing store. If the widget was in the list, and removing it causes the list to be empty, the backing store is deleted. If the widget was not in the list, this function is a no-op. */ void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w) { if (m_widgets.remove(w) && m_widgets.isEmpty()) { delete m_ptr; m_ptr = 0; } } /*! \internal Recursively remove widget and all of its descendents. */ void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget) { unregisterWidget(widget); foreach (QObject *child, widget->children()) if (QWidget *childWidget = qobject_cast<QWidget *>(child)) unregisterWidgetSubtree(childWidget); } QWidgetPrivate::QWidgetPrivate(int version) : QObjectPrivate(version) , extra(0) , focus_next(0) , focus_prev(0) , focus_child(0) , layout(0) , needsFlush(0) , redirectDev(0) , widgetItem(0) , extraPaintEngine(0) , polished(0) , graphicsEffect(0) #if !defined(QT_NO_IM) , imHints(Qt::ImhNone) #endif , inheritedFontResolveMask(0) , inheritedPaletteResolveMask(0) , leftmargin(0) , topmargin(0) , rightmargin(0) , bottommargin(0) , leftLayoutItemMargin(0) , topLayoutItemMargin(0) , rightLayoutItemMargin(0) , bottomLayoutItemMargin(0) , hd(0) , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred) , fg_role(QPalette::NoRole) , bg_role(QPalette::NoRole) , dirtyOpaqueChildren(1) , isOpaque(0) , inDirtyList(0) , isScrolled(0) , isMoved(0) , isGLWidget(0) , usesDoubleBufferedGLContext(0) #ifndef QT_NO_IM , inheritsInputMethodHints(0) #endif , inSetParent(0) #if defined(Q_WS_X11) , picture(0) #elif defined(Q_WS_WIN) , noPaintOnScreen(0) #ifndef QT_NO_GESTURES , nativeGesturePanEnabled(0) #endif #elif defined(Q_WS_MAC) , needWindowChange(0) , window_event(0) , qd_hd(0) #elif defined(Q_OS_SYMBIAN) , symbianScreenNumber(0) , fixNativeOrientationCalled(false) , isGLGlobalShareWidget(0) #endif { if (!qApp) { qFatal("QWidget: Must construct a QApplication before a QPaintDevice"); return; } if (version != QObjectPrivateVersion) qFatal("Cannot mix incompatible Qt libraries"); isWidget = true; memset(high_attributes, 0, sizeof(high_attributes)); #if QT_MAC_USE_COCOA drawRectOriginalAdded = false; originalDrawMethod = true; changeMethods = false; isInUnifiedToolbar = false; unifiedSurface = 0; toolbar_ancestor = 0; flushRequested = false; touchEventsEnabled = false; #endif // QT_MAC_USE_COCOA #ifdef QWIDGET_EXTRA_DEBUG static int count = 0; qDebug() << "widgets" << ++count; #endif } QWidgetPrivate::~QWidgetPrivate() { #ifdef Q_OS_SYMBIAN _q_cleanupWinIds(); #endif if (widgetItem) widgetItem->wid = 0; if (extra) deleteExtra(); #ifndef QT_NO_GRAPHICSEFFECT delete graphicsEffect; #endif //QT_NO_GRAPHICSEFFECT } class QDummyWindowSurface : public QWindowSurface { public: QDummyWindowSurface(QWidget *window) : QWindowSurface(window) {} QPaintDevice *paintDevice() { return window(); } void flush(QWidget *, const QRegion &, const QPoint &) {} }; QWindowSurface *QWidgetPrivate::createDefaultWindowSurface() { Q_Q(QWidget); QWindowSurface *surface; #ifndef QT_NO_PROPERTIES if (q->property("_q_DummyWindowSurface").toBool()) { surface = new QDummyWindowSurface(q); } else #endif { if (QApplicationPrivate::graphicsSystem()) surface = QApplicationPrivate::graphicsSystem()->createWindowSurface(q); else surface = createDefaultWindowSurface_sys(); } return surface; } /*! \internal */ void QWidgetPrivate::scrollChildren(int dx, int dy) { Q_Q(QWidget); if (q->children().size() > 0) { // scroll children QPoint pd(dx, dy); QObjectList childObjects = q->children(); for (int i = 0; i < childObjects.size(); ++i) { // move all children QWidget *w = qobject_cast<QWidget*>(childObjects.at(i)); if (w && !w->isWindow()) { QPoint oldp = w->pos(); QRect r(w->pos() + pd, w->size()); w->data->crect = r; #ifndef Q_WS_QWS if (w->testAttribute(Qt::WA_WState_Created)) w->d_func()->setWSGeometry(); #endif w->d_func()->setDirtyOpaqueRegion(); QMoveEvent e(r.topLeft(), oldp); QApplication::sendEvent(w, &e); } } } } QInputContext *QWidgetPrivate::assignedInputContext() const { #ifndef QT_NO_IM const QWidget *widget = q_func(); while (widget) { if (QInputContext *qic = widget->d_func()->ic) return qic; widget = widget->parentWidget(); } #endif return 0; } QInputContext *QWidgetPrivate::inputContext() const { #ifndef QT_NO_IM if (QInputContext *qic = assignedInputContext()) return qic; return qApp->inputContext(); #else return 0; #endif } /*! This function returns the QInputContext for this widget. By default the input context is inherited from the widgets parent. For toplevels it is inherited from QApplication. You can override this and set a special input context for this widget by using the setInputContext() method. \sa setInputContext() */ QInputContext *QWidget::inputContext() { Q_D(QWidget); if (!testAttribute(Qt::WA_InputMethodEnabled)) return 0; return d->inputContext(); } /*! This function sets the input context \a context on this widget. Qt takes ownership of the given input \a context. \sa inputContext() */ void QWidget::setInputContext(QInputContext *context) { Q_D(QWidget); if (!testAttribute(Qt::WA_InputMethodEnabled)) return; #ifndef QT_NO_IM if (context == d->ic) return; if (d->ic) delete d->ic; d->ic = context; if (d->ic) d->ic->setParent(this); #endif } /*! \obsolete This function can be called on the widget that currently has focus to reset the input method operating on it. This function is providing for convenience, instead you should use \l{QInputContext::}{reset()} on the input context that was returned by inputContext(). \sa QInputContext, inputContext(), QInputContext::reset() */ void QWidget::resetInputContext() { if (!hasFocus()) return; #ifndef QT_NO_IM QInputContext *qic = this->inputContext(); if(qic) qic->reset(); #endif // QT_NO_IM } #ifdef QT_KEYPAD_NAVIGATION QPointer<QWidget> QWidgetPrivate::editingWidget; /*! Returns true if this widget currently has edit focus; otherwise false. This feature is only available in Qt for Embedded Linux. \sa setEditFocus(), QApplication::keypadNavigationEnabled() */ bool QWidget::hasEditFocus() const { const QWidget* w = this; while (w->d_func()->extra && w->d_func()->extra->focus_proxy) w = w->d_func()->extra->focus_proxy; return QWidgetPrivate::editingWidget == w; } /*! \fn void QWidget::setEditFocus(bool enable) If \a enable is true, make this widget have edit focus, in which case Qt::Key_Up and Qt::Key_Down will be delivered to the widget normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to change focus. This feature is only available in Qt for Embedded Linux and Qt for Symbian. \sa hasEditFocus(), QApplication::keypadNavigationEnabled() */ void QWidget::setEditFocus(bool on) { QWidget *f = this; while (f->d_func()->extra && f->d_func()->extra->focus_proxy) f = f->d_func()->extra->focus_proxy; if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f) QWidgetPrivate::editingWidget->setEditFocus(false); if (on && !f->hasFocus()) f->setFocus(); if ((!on && !QWidgetPrivate::editingWidget) || (on && QWidgetPrivate::editingWidget == f)) { return; } if (!on && QWidgetPrivate::editingWidget == f) { QWidgetPrivate::editingWidget = 0; QEvent event(QEvent::LeaveEditFocus); QApplication::sendEvent(f, &event); QApplication::sendEvent(f->style(), &event); } else if (on) { QWidgetPrivate::editingWidget = f; QEvent event(QEvent::EnterEditFocus); QApplication::sendEvent(f, &event); QApplication::sendEvent(f->style(), &event); } } #endif /*! \property QWidget::autoFillBackground \brief whether the widget background is filled automatically \since 4.1 If enabled, this property will cause Qt to fill the background of the widget before invoking the paint event. The color used is defined by the QPalette::Window color role from the widget's \l{QPalette}{palette}. In addition, Windows are always filled with QPalette::Window, unless the WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set. This property cannot be turned off (i.e., set to false) if a widget's parent has a static gradient for its background. \warning Use this property with caution in conjunction with \l{Qt Style Sheets}. When a widget has a style sheet with a valid background or a border-image, this property is automatically disabled. By default, this property is false. \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground, {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering} */ bool QWidget::autoFillBackground() const { Q_D(const QWidget); return d->extra && d->extra->autoFillBackground; } void QWidget::setAutoFillBackground(bool enabled) { Q_D(QWidget); if (!d->extra) d->createExtra(); if (d->extra->autoFillBackground == enabled) return; d->extra->autoFillBackground = enabled; d->updateIsOpaque(); update(); d->updateIsOpaque(); } /*! \class QWidget \brief The QWidget class is the base class of all user interface objects. \ingroup basicwidgets The widget is the atom of the user interface: it receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Every widget is rectangular, and they are sorted in a Z-order. A widget is clipped by its parent and by the widgets in front of it. A widget that is not embedded in a parent widget is called a window. Usually, windows have a frame and a title bar, although it is also possible to create windows without such decoration using suitable \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various subclasses of QDialog are the most common window types. Every widget's constructor accepts one or two standard arguments: \list 1 \i \c{QWidget *parent = 0} is the parent of the new widget. If it is 0 (the default), the new widget will be a window. If not, it will be a child of \e parent, and be constrained by \e parent's geometry (unless you specify Qt::Window as window flag). \i \c{Qt::WindowFlags f = 0} (where available) sets the window flags; the default is suitable for almost all widgets, but to get, for example, a window without a window system frame, you must use special flags. \endlist QWidget has many member functions, but some of them have little direct functionality; for example, QWidget has a font property, but never uses this itself. There are many subclasses which provide real functionality, such as QLabel, QPushButton, QListWidget, and QTabWidget. \section1 Top-Level and Child Widgets A widget without a parent widget is always an independent window (top-level widget). For these widgets, setWindowTitle() and setWindowIcon() set the title bar and icon respectively. Non-window widgets are child widgets, displayed within their parent widgets. Most widgets in Qt are mainly useful as child widgets. For example, it is possible to display a button as a top-level window, but most people prefer to put their buttons inside other widgets, such as QDialog. \image parent-child-widgets.png A parent widget containing various child widgets. The diagram above shows a QGroupBox widget being used to hold various child widgets in a layout provided by QGridLayout. The QLabel child widgets have been outlined to indicate their full sizes. If you want to use a QWidget to hold child widgets you will usually want to add a layout to the parent QWidget. See \l{Layout Management} for more information. \section1 Composite Widgets When a widget is used as a container to group a number of child widgets, it is known as a composite widget. These can be created by constructing a widget with the required visual properties - a QFrame, for example - and adding child widgets to it, usually managed by a layout. The above diagram shows such a composite widget that was created using \l{Qt Designer}. Composite widgets can also be created by subclassing a standard widget, such as QWidget or QFrame, and adding the necessary layout and child widgets in the constructor of the subclass. Many of the \l{Qt Examples} {examples provided with Qt} use this approach, and it is also covered in the Qt \l{Tutorials}. \section1 Custom Widgets and Painting Since QWidget is a subclass of QPaintDevice, subclasses can be used to display custom content that is composed using a series of painting operations with an instance of the QPainter class. This approach contrasts with the canvas-style approach used by the \l{Graphics View} {Graphics View Framework} where items are added to a scene by the application and are rendered by the framework itself. Each widget performs all painting operations from within its paintEvent() function. This is called whenever the widget needs to be redrawn, either as a result of some external change or when requested by the application. The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget can handle paint events. \section1 Size Hints and Size Policies When implementing a new widget, it is almost always useful to reimplement sizeHint() to provide a reasonable default size for the widget and to set the correct size policy with setSizePolicy(). By default, composite widgets which do not provide a size hint will be sized according to the space requirements of their child widgets. The size policy lets you supply good default behavior for the layout management system, so that other widgets can contain and manage yours easily. The default size policy indicates that the size hint represents the preferred size of the widget, and this is often good enough for many widgets. \note The size of top-level widgets are constrained to 2/3 of the desktop's height and width. You can resize() the widget manually if these bounds are inadequate. \section1 Events Widgets respond to events that are typically caused by user actions. Qt delivers events to widgets by calling specific event handler functions with instances of QEvent subclasses containing information about each event. If your widget only contains child widgets, you probably do not need to implement any event handlers. If you want to detect a mouse click in a child widget call the child's underMouse() function inside the widget's mousePressEvent(). The \l{widgets/scribble}{Scribble example} implements a wider set of events to handle mouse movement, button presses, and window resizing. You will need to supply the behavior and content for your own widgets, but here is a brief overview of the events that are relevant to QWidget, starting with the most common ones: \list \i paintEvent() is called whenever the widget needs to be repainted. Every widget displaying custom content must implement it. Painting using a QPainter can only take place in a paintEvent() or a function called by a paintEvent(). \i resizeEvent() is called when the widget has been resized. \i mousePressEvent() is called when a mouse button is pressed while the mouse cursor is inside the widget, or when the widget has grabbed the mouse using grabMouse(). Pressing the mouse without releasing it is effectively the same as calling grabMouse(). \i mouseReleaseEvent() is called when a mouse button is released. A widget receives mouse release events when it has received the corresponding mouse press event. This means that if the user presses the mouse inside \e your widget, then drags the mouse somewhere else before releasing the mouse button, \e your widget receives the release event. There is one exception: if a popup menu appears while the mouse button is held down, this popup immediately steals the mouse events. \i mouseDoubleClickEvent() is called when the user double-clicks in the widget. If the user double-clicks, the widget receives a mouse press event, a mouse release event and finally this event instead of a second mouse press event. (Some mouse move events may also be received if the mouse is not held steady during this operation.) It is \e{not possible} to distinguish a click from a double-click until the second click arrives. (This is one reason why most GUI books recommend that double-clicks be an extension of single-clicks, rather than trigger a different action.) \endlist Widgets that accept keyboard input need to reimplement a few more event handlers: \list \i keyPressEvent() is called whenever a key is pressed, and again when a key has been held down long enough for it to auto-repeat. The \key Tab and \key Shift+Tab keys are only passed to the widget if they are not used by the focus-change mechanisms. To force those keys to be processed by your widget, you must reimplement QWidget::event(). \i focusInEvent() is called when the widget gains keyboard focus (assuming you have called setFocusPolicy()). Well-behaved widgets indicate that they own the keyboard focus in a clear but discreet way. \i focusOutEvent() is called when the widget loses keyboard focus. \endlist You may be required to also reimplement some of the less common event handlers: \list \i mouseMoveEvent() is called whenever the mouse moves while a mouse button is held down. This can be useful during drag and drop operations. If you call \l{setMouseTracking()}{setMouseTracking}(true), you get mouse move events even when no buttons are held down. (See also the \l{Drag and Drop} guide.) \i keyReleaseEvent() is called whenever a key is released and while it is held down (if the key is auto-repeating). In that case, the widget will receive a pair of key release and key press event for every repeat. The \key Tab and \key Shift+Tab keys are only passed to the widget if they are not used by the focus-change mechanisms. To force those keys to be processed by your widget, you must reimplement QWidget::event(). \i wheelEvent() is called whenever the user turns the mouse wheel while the widget has the focus. \i enterEvent() is called when the mouse enters the widget's screen space. (This excludes screen space owned by any of the widget's children.) \i leaveEvent() is called when the mouse leaves the widget's screen space. If the mouse enters a child widget it will not cause a leaveEvent(). \i moveEvent() is called when the widget has been moved relative to its parent. \i closeEvent() is called when the user closes the widget (or when close() is called). \endlist There are also some rather obscure events described in the documentation for QEvent::Type. To handle these events, you need to reimplement event() directly. The default implementation of event() handles \key Tab and \key Shift+Tab (to move the keyboard focus), and passes on most of the other events to one of the more specialized handlers above. Events and the mechanism used to deliver them are covered in \l{The Event System}. \section1 Groups of Functions and Properties \table \header \i Context \i Functions and Properties \row \i Window functions \i show(), hide(), raise(), lower(), close(). \row \i Top-level windows \i \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText, \l isActiveWindow, activateWindow(), \l minimized, showMinimized(), \l maximized, showMaximized(), \l fullScreen, showFullScreen(), showNormal(). \row \i Window contents \i update(), repaint(), scroll(). \row \i Geometry \i \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(), \l sizePolicy, sizeHint(), minimumSizeHint(), updateGeometry(), layout(), \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion, adjustSize(), mapFromGlobal(), mapToGlobal(), mapFromParent(), mapToParent(), \l maximumSize, \l minimumSize, \l sizeIncrement, \l baseSize, setFixedSize() \row \i Mode \i \l visible, isVisibleTo(), \l enabled, isEnabledTo(), \l modal, isWindow(), \l mouseTracking, \l updatesEnabled, visibleRegion(). \row \i Look and feel \i style(), setStyle(), \l styleSheet, \l cursor, \l font, \l palette, backgroundRole(), setBackgroundRole(), fontInfo(), fontMetrics(). \row \i Keyboard focus functions \i \l focus, \l focusPolicy, setFocus(), clearFocus(), setTabOrder(), setFocusProxy(), focusNextChild(), focusPreviousChild(). \row \i Mouse and keyboard grabbing \i grabMouse(), releaseMouse(), grabKeyboard(), releaseKeyboard(), mouseGrabber(), keyboardGrabber(). \row \i Event handlers \i event(), mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), keyPressEvent(), keyReleaseEvent(), focusInEvent(), focusOutEvent(), wheelEvent(), enterEvent(), leaveEvent(), paintEvent(), moveEvent(), resizeEvent(), closeEvent(), dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(), dropEvent(), childEvent(), showEvent(), hideEvent(), customEvent(). changeEvent(), \row \i System functions \i parentWidget(), window(), setParent(), winId(), find(), metric(). \row \i Interactive help \i setToolTip(), setWhatsThis() \endtable \section1 Widget Style Sheets In addition to the standard widget styles for each platform, widgets can also be styled according to rules specified in a \l{styleSheet} {style sheet}. This feature enables you to customize the appearance of specific widgets to provide visual cues to users about their purpose. For example, a button could be styled in a particular way to indicate that it performs a destructive action. The use of widget style sheets is described in more detail in the \l{Qt Style Sheets} document. \section1 Transparency and Double Buffering Since Qt 4.0, QWidget automatically double-buffers its painting, so there is no need to write double-buffering code in paintEvent() to avoid flicker. Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been deprecated. Instead, the contents of parent widgets are propagated by default to each of their children as long as Qt::WA_PaintOnScreen is not set. Custom widgets can be written to take advantage of this feature by updating irregular regions (to create non-rectangular child widgets), or painting with colors that have less than full alpha component. The following diagram shows how attributes and properties of a custom widget can be fine-tuned to achieve different effects. \image propagation-custom.png In the above diagram, a semi-transparent rectangular child widget with an area removed is constructed and added to a parent widget (a QLabel showing a pixmap). Then, different properties and widget attributes are set to achieve different effects: \list \i The left widget has no additional properties or widget attributes set. This default state suits most custom widgets using transparency, are irregularly-shaped, or do not paint over their entire area with an opaque brush. \i The center widget has the \l autoFillBackground property set. This property is used with custom widgets that rely on the widget to supply a default background, and do not paint over their entire area with an opaque brush. \i The right widget has the Qt::WA_OpaquePaintEvent widget attribute set. This indicates that the widget will paint over its entire area with opaque colors. The widget's area will initially be \e{uninitialized}, represented in the diagram with a red diagonal grid pattern that shines through the overpainted area. The Qt::WA_OpaquePaintArea attribute is useful for widgets that need to paint their own specialized contents quickly and do not need a default filled background. \endlist To rapidly update custom widgets with simple background colors, such as real-time plotting or graphing widgets, it is better to define a suitable background color (using setBackgroundRole() with the QPalette::Window role), set the \l autoFillBackground property, and only implement the necessary drawing functionality in the widget's paintEvent(). To rapidly update custom widgets that constantly paint over their entire areas with opaque content, e.g., video streaming widgets, it is better to set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead associated with repainting the widget's background. If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and} the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent attribute takes precedence. Depending on your requirements, you should choose either one of them. Since Qt 4.1, the contents of parent widgets are also propagated to standard Qt widgets. This can lead to some unexpected results if the parent widget is decorated in a non-standard way, as shown in the diagram below. \image propagation-standard.png The scope for customizing the painting behavior of standard Qt widgets, without resorting to subclassing, is slightly less than that possible for custom widgets. Usually, the desired appearance of a standard widget can be achieved by setting its \l autoFillBackground property. \section1 Creating Translucent Windows Since Qt 4.5, it has been possible to create windows with translucent regions on window systems that support compositing. To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground attribute with setAttribute() and ensure that its background is painted with non-opaque colors in the regions you want to be partially transparent. Platform notes: \list \o X11: This feature relies on the use of an X server that supports ARGB visuals and a compositing window manager. \o Windows: The widget needs to have the Qt::FramelessWindowHint window flag set for the translucency to work. \endlist \section1 Native Widgets vs Alien Widgets Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing system. They do not have a native window handle associated with them. This feature significantly speeds up widget painting, resizing, and removes flicker. Should you require the old behavior with native windows, you can choose one of the following options: \list 1 \i Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment. \i Set the Qt::AA_NativeWindows attribute on your application. All widgets will be native widgets. \i Set the Qt::WA_NativeWindow attribute on widgets: The widget itself and all of its ancestors will become native (unless Qt::WA_DontCreateNativeAncestors is set). \i Call QWidget::winId to enforce a native window (this implies 3). \i Set the Qt::WA_PaintOnScreen attribute to enforce a native window (this implies 3). \endlist \sa QEvent, QPainter, QGridLayout, QBoxLayout \section1 Softkeys Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or other visual representation on the screen that is generally located next to its physical counterpart. They are most often found on mobile phone platforms. In modern touch based user interfaces it is also possible to have softkeys that do not correspond to any physical keys. Softkeys differ from other onscreen labels in that they are contextual. In Qt, contextual softkeys are added to a widget by calling addAction() and passing a \c QAction with a softkey role set on it. When the widget containing the softkey actions has focus, its softkeys should appear in the user interface. Softkeys are discovered by traversing the widget hierarchy so it is possible to define a single set of softkeys that are present at all times by calling addAction() for a given top level widget. On some platforms, this concept overlaps with \c QMenuBar such that if no other softkeys are found and the top level widget is a QMainWindow containing a QMenuBar, the menubar actions may appear on one of the softkeys. Note: Currently softkeys are only supported on the Symbian Platform. \sa addAction(), QAction, QMenuBar */ QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid /***************************************************************************** QWidget utility functions *****************************************************************************/ QRegion qt_dirtyRegion(QWidget *widget) { if (!widget) return QRegion(); QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore(); if (!bs) return QRegion(); return bs->dirtyRegion(widget); } /***************************************************************************** QWidget member functions *****************************************************************************/ /* Widget state flags: \list \i Qt::WA_WState_Created The widget has a valid winId(). \i Qt::WA_WState_Visible The widget is currently visible. \i Qt::WA_WState_Hidden The widget is hidden, i.e. it won't become visible unless you call show() on it. Qt::WA_WState_Hidden implies !Qt::WA_WState_Visible. \i Qt::WA_WState_CompressKeys Compress keyboard events. \i Qt::WA_WState_BlockUpdates Repaints and updates are disabled. \i Qt::WA_WState_InPaintEvent Currently processing a paint event. \i Qt::WA_WState_Reparented The widget has been reparented. \i Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending. \i Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops(). \endlist */ struct QWidgetExceptionCleaner { /* this cleans up when the constructor throws an exception */ static inline void cleanup(QWidget *that, QWidgetPrivate *d) { #ifdef QT_NO_EXCEPTIONS Q_UNUSED(that); Q_UNUSED(d); #else QWidgetPrivate::allWidgets->remove(that); if (d->focus_next != that) { if (d->focus_next) d->focus_next->d_func()->focus_prev = d->focus_prev; if (d->focus_prev) d->focus_prev->d_func()->focus_next = d->focus_next; } #endif } }; /*! Constructs a widget which is a child of \a parent, with widget flags set to \a f. If \a parent is 0, the new widget becomes a window. If \a parent is another widget, this widget becomes a child window inside \a parent. The new widget is deleted when its \a parent is deleted. The widget flags argument, \a f, is normally 0, but it can be set to customize the frame of a window (i.e. \a parent must be 0). To customize the frame, use a value composed from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}. If you add a child widget to an already visible widget you must explicitly show the child to make it visible. Note that the X11 version of Qt may not be able to deliver all combinations of style flags on all systems. This is because on X11, Qt can only ask the window manager, and the window manager can override the application's settings. On Windows, Qt can set whatever flags you want. \sa windowFlags */ QWidget::QWidget(QWidget *parent, Qt::WindowFlags f) : QObject(*new QWidgetPrivate, 0), QPaintDevice() { QT_TRY { d_func()->init(parent, f); } QT_CATCH(...) { QWidgetExceptionCleaner::cleanup(this, d_func()); QT_RETHROW; } } #ifdef QT3_SUPPORT /*! \overload \obsolete */ QWidget::QWidget(QWidget *parent, const char *name, Qt::WindowFlags f) : QObject(*new QWidgetPrivate, 0), QPaintDevice() { QT_TRY { d_func()->init(parent , f); setObjectName(QString::fromAscii(name)); } QT_CATCH(...) { QWidgetExceptionCleaner::cleanup(this, d_func()); QT_RETHROW; } } #endif /*! \internal */ QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f) : QObject(dd, 0), QPaintDevice() { Q_D(QWidget); QT_TRY { d->init(parent, f); } QT_CATCH(...) { QWidgetExceptionCleaner::cleanup(this, d_func()); QT_RETHROW; } } /*! \internal */ int QWidget::devType() const { return QInternal::Widget; } //### w is a "this" ptr, passed as a param because QWorkspace needs special logic void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w) { bool customize = (flags & (Qt::CustomizeWindowHint | Qt::FramelessWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)); uint type = (flags & Qt::WindowType_Mask); if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) { type = Qt::Window; flags |= Qt::Window; } if (flags & Qt::CustomizeWindowHint) { // modify window flags to make them consistent. // Only enable this on non-Mac platforms. Since the old way of doing this would // interpret WindowSystemMenuHint as a close button and we can't change that behavior // we can't just add this in. #ifndef Q_WS_MAC if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) { flags |= Qt::WindowSystemMenuHint; #else if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint)) { #endif flags |= Qt::WindowTitleHint; flags &= ~Qt::FramelessWindowHint; } } else if (customize && !(flags & Qt::FramelessWindowHint)) { // if any of the window hints that affect the titlebar are set // and the window is supposed to have frame, we add a titlebar // and system menu by default. flags |= Qt::WindowSystemMenuHint; flags |= Qt::WindowTitleHint; } if (customize) ; // don't modify window flags if the user explicitly set them. else if (type == Qt::Dialog || type == Qt::Sheet) #ifndef Q_WS_WINCE flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint; #else flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint; #endif else if (type == Qt::Tool) flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint; else flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint; } void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f) { Q_Q(QWidget); if (QApplication::type() == QApplication::Tty) qFatal("QWidget: Cannot create a QWidget when no GUI is being used"); Q_ASSERT(allWidgets); if (allWidgets) allWidgets->insert(q); QWidget *desktopWidget = 0; if (parentWidget && parentWidget->windowType() == Qt::Desktop) { desktopWidget = parentWidget; parentWidget = 0; } q->data = &data; #ifndef QT_NO_THREAD if (!parent) { Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget", "Widgets must be created in the GUI thread."); } #endif #if defined(Q_WS_X11) if (desktopWidget) { // make sure the widget is created on the same screen as the // programmer specified desktop widget xinfo = desktopWidget->d_func()->xinfo; } #elif defined(Q_OS_SYMBIAN) if (desktopWidget) { symbianScreenNumber = qt_widget_private(desktopWidget)->symbianScreenNumber; } #elif defined(Q_WS_QPA) if (desktopWidget) { int screen = desktopWidget->d_func()->topData()->screenIndex; topData()->screenIndex = screen; QPlatformIntegration *platform = QApplicationPrivate::platformIntegration(); platform->moveToScreen(q, screen); } #else Q_UNUSED(desktopWidget); #endif data.fstrut_dirty = true; data.winid = 0; data.widget_attributes = 0; data.window_flags = f; data.window_state = 0; data.focus_policy = 0; data.context_menu_policy = Qt::DefaultContextMenu; data.window_modality = Qt::NonModal; data.sizehint_forced = 0; data.is_closing = 0; data.in_show = 0; data.in_set_window_state = 0; data.in_destructor = false; // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle. if (f & Qt::MSWindowsOwnDC) q->setAttribute(Qt::WA_NativeWindow); //#ifdef Q_WS_MAC // q->setAttribute(Qt::WA_NativeWindow); //#endif q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute() adjustQuitOnCloseAttribute(); q->setAttribute(Qt::WA_WState_Hidden); //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later #ifdef Q_OS_SYMBIAN if (isGLWidget) { // Don't waste GPU mem for unnecessary large egl surface until resized by application data.crect = QRect(0,0,1,1); } else { data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,360,640); } #else data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480); #endif focus_next = focus_prev = q; if ((f & Qt::WindowType_Mask) == Qt::Desktop) q->create(); else if (parentWidget) q->setParent(parentWidget, data.window_flags); else { adjustFlags(data.window_flags, q); resolveLayoutDirection(); // opaque system background? const QBrush &background = q->palette().brush(QPalette::Window); setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque()); } data.fnt = QFont(data.fnt, q); #if defined(Q_WS_X11) data.fnt.x11SetScreen(xinfo.screen()); #endif // Q_WS_X11 q->setAttribute(Qt::WA_PendingMoveEvent); q->setAttribute(Qt::WA_PendingResizeEvent); if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances) QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter; if (QApplicationPrivate::app_compile_version < 0x040200 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation)) q->create(); QEvent e(QEvent::Create); QApplication::sendEvent(q, &e); QApplication::postEvent(q, new QEvent(QEvent::PolishRequest)); extraPaintEngine = 0; } void QWidgetPrivate::createRecursively() { Q_Q(QWidget); q->create(0, true, true); for (int i = 0; i < children.size(); ++i) { QWidget *child = qobject_cast<QWidget *>(children.at(i)); if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created)) child->d_func()->createRecursively(); } } /*! Creates a new widget window if \a window is 0, otherwise sets the widget's window to \a window. Initializes the window (sets the geometry etc.) if \a initializeWindow is true. If \a initializeWindow is false, no initialization is performed. This parameter only makes sense if \a window is a valid window. Destroys the old window if \a destroyOldWindow is true. If \a destroyOldWindow is false, you are responsible for destroying the window yourself (using platform native code). The QWidget constructor calls create(0,true,true) to create a window for this widget. */ void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow) { Q_D(QWidget); if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId()) return; if (d->data.in_destructor) return; Qt::WindowType type = windowType(); Qt::WindowFlags &flags = data->window_flags; if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) { type = Qt::Window; flags |= Qt::Window; } #ifndef Q_WS_QPA if (QWidget *parent = parentWidget()) { if (type & Qt::Window) { if (!parent->testAttribute(Qt::WA_WState_Created)) parent->createWinId(); } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId() && !testAttribute(Qt::WA_DontCreateNativeAncestors)) { // We're about to create a native child widget that doesn't have a native parent; // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors // attribute is set. d->createWinId(window); // Nothing more to do. Q_ASSERT(testAttribute(Qt::WA_WState_Created)); Q_ASSERT(internalWinId()); return; } } #endif //Q_WS_QPA #ifdef QT3_SUPPORT if (flags & Qt::WStaticContents) setAttribute(Qt::WA_StaticContents); if (flags & Qt::WDestructiveClose) setAttribute(Qt::WA_DeleteOnClose); if (flags & Qt::WShowModal) setWindowModality(Qt::ApplicationModal); if (flags & Qt::WMouseNoMask) setAttribute(Qt::WA_MouseNoMask); if (flags & Qt::WGroupLeader) setAttribute(Qt::WA_GroupLeader); if (flags & Qt::WNoMousePropagation) setAttribute(Qt::WA_NoMousePropagation); #endif static int paintOnScreenEnv = -1; if (paintOnScreenEnv == -1) paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0; if (paintOnScreenEnv == 1) setAttribute(Qt::WA_PaintOnScreen); if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows)) setAttribute(Qt::WA_NativeWindow); #ifdef ALIEN_DEBUG qDebug() << "QWidget::create:" << this << "parent:" << parentWidget() << "Alien?" << !testAttribute(Qt::WA_NativeWindow); #endif #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP) // Unregister the dropsite (if already registered) before we // re-create the widget with a native window. if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow) && d->extra && d->extra->dropTarget) { d->registerDropSite(false); } #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP) d->updateIsOpaque(); setAttribute(Qt::WA_WState_Created); // set created flag d->create_sys(window, initializeWindow, destroyOldWindow); // a real toplevel window needs a backing store if (isWindow() && windowType() != Qt::Desktop) { d->topData()->backingStore.destroy(); if (hasBackingStoreSupport()) d->topData()->backingStore.create(this); } d->setModal_sys(); if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)) setAttribute(Qt::WA_DropSiteRegistered, true); #ifdef QT_EVAL extern void qt_eval_init_widget(QWidget *w); qt_eval_init_widget(this); #endif // need to force the resting of the icon after changing parents if (testAttribute(Qt::WA_SetWindowIcon)) d->setWindowIcon_sys(true); if (isWindow() && !d->topData()->iconText.isEmpty()) d->setWindowIconText_helper(d->topData()->iconText); if (isWindow() && !d->topData()->caption.isEmpty()) d->setWindowTitle_helper(d->topData()->caption); if (windowType() != Qt::Desktop) { d->updateSystemBackground(); if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) d->setWindowIcon_sys(); } } /*! Destroys the widget. All this widget's children are deleted first. The application exits if this widget is the main widget. */ QWidget::~QWidget() { Q_D(QWidget); d->data.in_destructor = true; #if defined (QT_CHECK_STATE) if (paintingActive()) qWarning("QWidget: %s (%s) deleted while being painted", className(), name()); #endif #ifndef QT_NO_GESTURES foreach (Qt::GestureType type, d->gestureContext.keys()) ungrabGesture(type); #endif // force acceptDrops false before winId is destroyed. d->registerDropSite(false); #ifndef QT_NO_ACTION // remove all actions from this widget for (int i = 0; i < d->actions.size(); ++i) { QActionPrivate *apriv = d->actions.at(i)->d_func(); apriv->widgets.removeAll(this); } d->actions.clear(); #endif #ifndef QT_NO_SHORTCUT // Remove all shortcuts grabbed by this // widget, unless application is closing if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut)) qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence()); #endif // delete layout while we still are a valid widget delete d->layout; d->layout = 0; // Remove myself from focus list Q_ASSERT(d->focus_next->d_func()->focus_prev == this); Q_ASSERT(d->focus_prev->d_func()->focus_next == this); if (d->focus_next != this) { d->focus_next->d_func()->focus_prev = d->focus_prev; d->focus_prev->d_func()->focus_next = d->focus_next; d->focus_next = d->focus_prev = 0; } #ifdef QT3_SUPPORT if (QApplicationPrivate::main_widget == this) { // reset main widget QApplicationPrivate::main_widget = 0; QApplication::quit(); } #endif QT_TRY { clearFocus(); } QT_CATCH(...) { // swallow this problem because we are in a destructor } d->setDirtyOpaqueRegion(); if (isWindow() && isVisible() && internalWinId()) { QT_TRY { d->close_helper(QWidgetPrivate::CloseNoEvent); } QT_CATCH(...) { // if we're out of memory, at least hide the window. QT_TRY { hide(); } QT_CATCH(...) { // and if that also doesn't work, then give up } } } #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC) else if (!internalWinId() && isVisible()) { qApp->d_func()->sendSyntheticEnterLeave(this); } #elif defined(Q_WS_QWS) || defined(Q_WS_QPA) else if (isVisible()) { qApp->d_func()->sendSyntheticEnterLeave(this); } #endif #ifdef Q_OS_SYMBIAN if (d->extra && d->extra->topextra && d->extra->topextra->backingStore) { // Okay, we are about to destroy the top-level window that owns // the backing store. Make sure we delete the backing store right away // before the window handle is invalid. This is important because // the backing store will delete its window surface, which may or may // not have a reference to this widget that will be used later to // notify the window it no longer has a surface. d->extra->topextra->backingStore.destroy(); } #endif if (QWidgetBackingStore *bs = d->maybeBackingStore()) { bs->removeDirtyWidget(this); if (testAttribute(Qt::WA_StaticContents)) bs->removeStaticWidget(this); } delete d->needsFlush; d->needsFlush = 0; // set all QPointers for this object to zero if (d->hasGuards) QObjectPrivate::clearGuards(this); if (d->declarativeData) { QAbstractDeclarativeData::destroyed(d->declarativeData, this); d->declarativeData = 0; // don't activate again in ~QObject } #ifdef QT_MAC_USE_COCOA // QCocoaView holds a pointer back to this widget. Clear it now // to make sure it's not followed later on. The lifetime of the // QCocoaView might exceed the lifetime of this widget in cases // where Cocoa itself holds references to it. extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *); qt_mac_clearCocoaViewQWidgetPointers(this); #endif if (!d->children.isEmpty()) d->deleteChildren(); #ifndef QT_NO_ACCESSIBILITY QAccessible::updateAccessibility(this, 0, QAccessible::ObjectDestroyed); #endif QApplication::removePostedEvents(this); QT_TRY { destroy(); // platform-dependent cleanup } QT_CATCH(...) { // if this fails we can't do anything about it but at least we are not allowed to throw. } --QWidgetPrivate::instanceCounter; if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication QWidgetPrivate::allWidgets->remove(this); QT_TRY { QEvent e(QEvent::Destroy); QCoreApplication::sendEvent(this, &e); } QT_CATCH(const std::exception&) { // if this fails we can't do anything about it but at least we are not allowed to throw. } } int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances void QWidgetPrivate::setWinId(WId id) // set widget identifier { Q_Q(QWidget); // the user might create a widget with Qt::Desktop window // attribute (or create another QDesktopWidget instance), which // will have the same windowid (the root window id) as the // qt_desktopWidget. We should not add the second desktop widget // to the mapper. bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop; if (mapper && data.winid && !userDesktopWidget) { mapper->remove(data.winid); } const WId oldWinId = data.winid; data.winid = id; #if defined(Q_WS_X11) hd = id; // X11: hd == ident #endif if (mapper && id && !userDesktopWidget) { mapper->insert(data.winid, q); } if(oldWinId != id) { QEvent e(QEvent::WinIdChange); QCoreApplication::sendEvent(q, &e); } } void QWidgetPrivate::createTLExtra() { if (!extra) createExtra(); if (!extra->topextra) { QTLWExtra* x = extra->topextra = new QTLWExtra; x->icon = 0; x->iconPixmap = 0; x->windowSurface = 0; x->sharedPainter = 0; x->incw = x->inch = 0; x->basew = x->baseh = 0; x->frameStrut.setCoords(0, 0, 0, 0); x->normalGeometry = QRect(0,0,-1,-1); x->savedFlags = 0; x->opacity = 255; x->posFromMove = false; x->sizeAdjusted = false; x->inTopLevelResize = false; x->inRepaint = false; x->embedded = 0; #ifdef Q_WS_MAC #ifdef QT_MAC_USE_COCOA x->wasMaximized = false; #endif // QT_MAC_USE_COCOA #endif // Q_WS_MAC createTLSysExtra(); #ifdef QWIDGET_EXTRA_DEBUG static int count = 0; qDebug() << "tlextra" << ++count; #endif #if defined(Q_WS_QPA) x->platformWindow = 0; x->platformWindowFormat = QPlatformWindowFormat::defaultFormat(); x->screenIndex = 0; #endif } } /*! \internal Creates the widget extra data. */ void QWidgetPrivate::createExtra() { if (!extra) { // if not exists extra = new QWExtra; extra->glContext = 0; extra->topextra = 0; #ifndef QT_NO_GRAPHICSVIEW extra->proxyWidget = 0; #endif #ifndef QT_NO_CURSOR extra->curs = 0; #endif extra->minw = 0; extra->minh = 0; extra->maxw = QWIDGETSIZE_MAX; extra->maxh = QWIDGETSIZE_MAX; extra->customDpiX = 0; extra->customDpiY = 0; extra->explicitMinSize = 0; extra->explicitMaxSize = 0; extra->autoFillBackground = 0; extra->nativeChildrenForced = 0; extra->inRenderWithPainter = 0; extra->hasMask = 0; createSysExtra(); #ifdef QWIDGET_EXTRA_DEBUG static int count = 0; qDebug() << "extra" << ++count; #endif } } /*! \internal Deletes the widget extra data. */ void QWidgetPrivate::deleteExtra() { if (extra) { // if exists #ifndef QT_NO_CURSOR delete extra->curs; #endif deleteSysExtra(); #ifndef QT_NO_STYLE_STYLESHEET // dereference the stylesheet style if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style)) proxy->deref(); #endif if (extra->topextra) { deleteTLSysExtra(); extra->topextra->backingStore.destroy(); delete extra->topextra->icon; delete extra->topextra->iconPixmap; #if defined(Q_WS_QWS) && !defined(QT_NO_QWS_MANAGER) delete extra->topextra->qwsManager; #endif delete extra->topextra->windowSurface; delete extra->topextra; } delete extra; // extra->xic destroyed in QWidget::destroy() extra = 0; } } /* Returns true if there are widgets above this which overlap with \a rect, which is in parent's coordinate system (same as crect). */ bool QWidgetPrivate::isOverlapped(const QRect &rect) const { Q_Q(const QWidget); const QWidget *w = q; QRect r = rect; while (w) { if (w->isWindow()) return false; QWidgetPrivate *pd = w->parentWidget()->d_func(); bool above = false; for (int i = 0; i < pd->children.size(); ++i) { QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i)); if (!sibling || !sibling->isVisible() || sibling->isWindow()) continue; if (!above) { above = (sibling == w); continue; } if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) { const QWExtra *siblingExtra = sibling->d_func()->extra; if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) { continue; } return true; } } w = w->parentWidget(); r.translate(pd->data.crect.topLeft()); } return false; } void QWidgetPrivate::syncBackingStore() { if (paintOnScreen()) { repaint_sys(dirty); dirty = QRegion(); } else if (QWidgetBackingStore *bs = maybeBackingStore()) { bs->sync(); } } void QWidgetPrivate::syncBackingStore(const QRegion &region) { if (paintOnScreen()) repaint_sys(region); else if (QWidgetBackingStore *bs = maybeBackingStore()) { bs->sync(q_func(), region); } } void QWidgetPrivate::setUpdatesEnabled_helper(bool enable) { Q_Q(QWidget); if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled()) return; // nothing we can do if (enable != q->testAttribute(Qt::WA_UpdatesDisabled)) return; // nothing to do q->setAttribute(Qt::WA_UpdatesDisabled, !enable); if (enable) q->update(); Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled; for (int i = 0; i < children.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(children.at(i)); if (w && !w->isWindow() && !w->testAttribute(attribute)) w->d_func()->setUpdatesEnabled_helper(enable); } } /*! \internal Propagate this widget's palette to all children, except style sheet widgets, and windows that don't enable window propagation (palettes don't normally propagate to windows). */ void QWidgetPrivate::propagatePaletteChange() { Q_Q(QWidget); // Propagate a new inherited mask to all children. #ifndef QT_NO_GRAPHICSVIEW if (!q->parentWidget() && extra && extra->proxyWidget) { QGraphicsProxyWidget *p = extra->proxyWidget; inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve(); } else #endif //QT_NO_GRAPHICSVIEW if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) { inheritedPaletteResolveMask = 0; } int mask = data.pal.resolve() | inheritedPaletteResolveMask; QEvent pc(QEvent::PaletteChange); QApplication::sendEvent(q, &pc); for (int i = 0; i < children.size(); ++i) { QWidget *w = qobject_cast<QWidget*>(children.at(i)); if (w && !w->testAttribute(Qt::WA_StyleSheet) && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) { QWidgetPrivate *wd = w->d_func(); wd->inheritedPaletteResolveMask = mask; wd->resolvePalette(); } } #if defined(QT3_SUPPORT) q->paletteChange(q->palette()); // compatibility #endif } /* Returns the widget's clipping rectangle. */ QRect QWidgetPrivate::clipRect() const { Q_Q(const QWidget); const QWidget * w = q; if (!w->isVisible()) return QRect(); QRect r = effectiveRectFor(q->rect()); int ox = 0; int oy = 0; while (w && w->isVisible() && !w->isWindow() && w->parentWidget()) { ox -= w->x(); oy -= w->y(); w = w->parentWidget(); r &= QRect(ox, oy, w->width(), w->height()); } return r; } /* Returns the widget's clipping region (without siblings). */ QRegion QWidgetPrivate::clipRegion() const { Q_Q(const QWidget); if (!q->isVisible()) return QRegion(); QRegion r(q->rect()); const QWidget * w = q; const QWidget *ignoreUpTo; int ox = 0; int oy = 0; while (w && w->isVisible() && !w->isWindow() && w->parentWidget()) { ox -= w->x(); oy -= w->y(); ignoreUpTo = w; w = w->parentWidget(); r &= QRegion(ox, oy, w->width(), w->height()); int i = 0; while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo)) ; for ( ; i < w->d_func()->children.size(); ++i) { if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) { if(sibling->isVisible() && !sibling->isWindow()) { QRect siblingRect(ox+sibling->x(), oy+sibling->y(), sibling->width(), sibling->height()); if (qRectIntersects(siblingRect, q->rect())) r -= QRegion(siblingRect); } } } } return r; } #ifndef QT_NO_GRAPHICSEFFECT void QWidgetPrivate::invalidateGraphicsEffectsRecursively() { Q_Q(QWidget); QWidget *w = q; do { if (w->graphicsEffect()) { QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func()); if (!sourced->updateDueToGraphicsEffect) w->graphicsEffect()->source()->d_func()->invalidateCache(); } w = w->parentWidget(); } while (w); } #endif //QT_NO_GRAPHICSEFFECT void QWidgetPrivate::setDirtyOpaqueRegion() { Q_Q(QWidget); dirtyOpaqueChildren = true; #ifndef QT_NO_GRAPHICSEFFECT invalidateGraphicsEffectsRecursively(); #endif //QT_NO_GRAPHICSEFFECT if (q->isWindow()) return; QWidget *parent = q->parentWidget(); if (!parent) return; // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly? QWidgetPrivate *pd = parent->d_func(); if (!pd->dirtyOpaqueChildren) pd->setDirtyOpaqueRegion(); } const QRegion &QWidgetPrivate::getOpaqueChildren() const { if (!dirtyOpaqueChildren) return opaqueChildren; QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this); that->opaqueChildren = QRegion(); for (int i = 0; i < children.size(); ++i) { QWidget *child = qobject_cast<QWidget *>(children.at(i)); if (!child || !child->isVisible() || child->isWindow()) continue; const QPoint offset = child->geometry().topLeft(); QWidgetPrivate *childd = child->d_func(); QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren(); if (childd->extra && childd->extra->hasMask) r &= childd->extra->mask; if (r.isEmpty()) continue; r.translate(offset); that->opaqueChildren += r; } that->opaqueChildren &= q_func()->rect(); that->dirtyOpaqueChildren = false; return that->opaqueChildren; } void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const { if (children.isEmpty() || clipRect.isEmpty()) return; const QRegion &r = getOpaqueChildren(); if (!r.isEmpty()) source -= (r & clipRect); } //subtract any relatives that are higher up than me --- this is too expensive !!! void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove, bool alsoNonOpaque) const { Q_Q(const QWidget); static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt(); if (disableSubtractOpaqueSiblings || q->isWindow()) return; #ifdef QT_MAC_USE_COCOA if (q->d_func()->isInUnifiedToolbar) return; #endif // QT_MAC_USE_COCOA QRect clipBoundingRect; bool dirtyClipBoundingRect = true; QRegion parentClip; bool dirtyParentClip = true; QPoint parentOffset = data.crect.topLeft(); const QWidget *w = q; while (w) { if (w->isWindow()) break; QWidgetPrivate *pd = w->parentWidget()->d_func(); const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w)); const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect); for (int i = myIndex + 1; i < pd->children.size(); ++i) { QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i)); if (!sibling || !sibling->isVisible() || sibling->isWindow()) continue; const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect); if (!qRectIntersects(siblingGeometry, widgetGeometry)) continue; if (dirtyClipBoundingRect) { clipBoundingRect = sourceRegion.boundingRect(); dirtyClipBoundingRect = false; } if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset))) continue; if (dirtyParentClip) { parentClip = sourceRegion.translated(parentOffset); dirtyParentClip = false; } const QPoint siblingPos(sibling->data->crect.topLeft()); const QRect siblingClipRect(sibling->d_func()->clipRect()); QRegion siblingDirty(parentClip); siblingDirty &= (siblingClipRect.translated(siblingPos)); const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask && !sibling->d_func()->graphicsEffect; if (hasMask) siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos); if (siblingDirty.isEmpty()) continue; if (sibling->d_func()->isOpaque || alsoNonOpaque) { if (hasMask) { siblingDirty.translate(-parentOffset); sourceRegion -= siblingDirty; } else { sourceRegion -= siblingGeometry.translated(-parentOffset); } } else { if (hasDirtySiblingsAbove) *hasDirtySiblingsAbove = true; if (sibling->d_func()->children.isEmpty()) continue; QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren()); opaqueSiblingChildren.translate(-parentOffset + siblingPos); sourceRegion -= opaqueSiblingChildren; } if (sourceRegion.isEmpty()) return; dirtyClipBoundingRect = true; dirtyParentClip = true; } w = w->parentWidget(); parentOffset += pd->data.crect.topLeft(); dirtyParentClip = true; } } void QWidgetPrivate::clipToEffectiveMask(QRegion &region) const { Q_Q(const QWidget); const QWidget *w = q; QPoint offset; #ifndef QT_NO_GRAPHICSEFFECT if (graphicsEffect) { w = q->parentWidget(); offset -= data.crect.topLeft(); } #endif //QT_NO_GRAPHICSEFFECT while (w) { const QWidgetPrivate *wd = w->d_func(); if (wd->extra && wd->extra->hasMask) region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask; if (w->isWindow()) return; offset -= wd->data.crect.topLeft(); w = w->parentWidget(); } } bool QWidgetPrivate::paintOnScreen() const { #if defined(Q_WS_QWS) return false; #elif defined(QT_NO_BACKINGSTORE) return true; #else Q_Q(const QWidget); if (q->testAttribute(Qt::WA_PaintOnScreen) || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) { return true; } return !qt_enable_backingstore; #endif } void QWidgetPrivate::updateIsOpaque() { // hw: todo: only needed if opacity actually changed setDirtyOpaqueRegion(); #ifndef QT_NO_GRAPHICSEFFECT if (graphicsEffect) { // ### We should probably add QGraphicsEffect::isOpaque at some point. setOpaque(false); return; } #endif //QT_NO_GRAPHICSEFFECT Q_Q(QWidget); #ifdef Q_WS_X11 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) { setOpaque(false); return; } #endif #ifdef Q_WS_S60 if (q->testAttribute(Qt::WA_TranslucentBackground)) { if (q->windowType() & Qt::Dialog || q->windowType() & Qt::Popup) { if (S60->avkonComponentsSupportTransparency) { setOpaque(false); return; } } else { setOpaque(false); return; } } #endif if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) { setOpaque(true); return; } const QPalette &pal = q->palette(); if (q->autoFillBackground()) { const QBrush &autoFillBrush = pal.brush(q->backgroundRole()); if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) { setOpaque(true); return; } } if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) { #ifdef Q_WS_S60 setOpaque(true); return; #else const QBrush &windowBrush = q->palette().brush(QPalette::Window); if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) { setOpaque(true); return; } #endif } setOpaque(false); } void QWidgetPrivate::setOpaque(bool opaque) { if (isOpaque == opaque) return; isOpaque = opaque; #ifdef Q_WS_MAC macUpdateIsOpaque(); #endif #ifdef Q_WS_X11 x11UpdateIsOpaque(); #endif #ifdef Q_WS_WIN winUpdateIsOpaque(); #endif #ifdef Q_OS_SYMBIAN s60UpdateIsOpaque(); #endif } void QWidgetPrivate::updateIsTranslucent() { #ifdef Q_WS_MAC macUpdateIsOpaque(); #endif #ifdef Q_WS_X11 x11UpdateIsOpaque(); #endif #ifdef Q_WS_WIN winUpdateIsOpaque(); #endif #ifdef Q_OS_SYMBIAN s60UpdateIsOpaque(); #endif } /*! \fn void QPixmap::fill(const QWidget *widget, const QPoint &offset) Fills the pixmap with the \a widget's background color or pixmap according to the given offset. The QPoint \a offset defines a point in widget coordinates to which the pixmap's top-left pixel will be mapped to. This is only significant if the widget has a background pixmap; otherwise the pixmap will simply be filled with the background color of the widget. */ void QPixmap::fill( const QWidget *widget, const QPoint &off ) { QPainter p(this); p.translate(-off); widget->d_func()->paintBackground(&p, QRect(off, size())); } static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush) { Q_ASSERT(painter); if (brush.style() == Qt::TexturePattern) { #ifdef Q_WS_MAC // Optimize pattern filling on mac by using HITheme directly // when filling with the standard widget background. // Defined in qmacstyle_mac.cpp extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush); qt_mac_fill_background(painter, rgn, brush); #else #if !defined(QT_NO_STYLE_S60) // Defined in qs60style.cpp extern bool qt_s60_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush); if (!qt_s60_fill_background(painter, rgn, brush)) #endif // !defined(QT_NO_STYLE_S60) { const QRect rect(rgn.boundingRect()); painter->setClipRegion(rgn); painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft()); } #endif // Q_WS_MAC } else if (brush.gradient() && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) { painter->save(); painter->setClipRegion(rgn); painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush); painter->restore(); } else { const QVector<QRect> &rects = rgn.rects(); for (int i = 0; i < rects.size(); ++i) painter->fillRect(rects.at(i), brush); } } void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const { Q_Q(const QWidget); #ifndef QT_NO_SCROLLAREA bool resetBrushOrigin = false; QPointF oldBrushOrigin; //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent); if (scrollArea && scrollArea->viewport() == q) { QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data(); QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate); oldBrushOrigin = painter->brushOrigin(); resetBrushOrigin = true; painter->setBrushOrigin(-priv->contentsOffset()); } #endif // QT_NO_SCROLLAREA const QBrush autoFillBrush = q->palette().brush(q->backgroundRole()); if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) { const QBrush bg = q->palette().brush(QPalette::Window); #if defined(Q_WS_QWS) || defined(Q_WS_QPA) if (!(flags & DontSetCompositionMode)) { //copy alpha straight in QPainter::CompositionMode oldMode = painter->compositionMode(); painter->setCompositionMode(QPainter::CompositionMode_Source); fillRegion(painter, rgn, bg); painter->setCompositionMode(oldMode); } else { fillRegion(painter, rgn, bg); } #else fillRegion(painter, rgn, bg); #endif } if (q->autoFillBackground()) fillRegion(painter, rgn, autoFillBrush); if (q->testAttribute(Qt::WA_StyledBackground)) { painter->setClipRegion(rgn); QStyleOption opt; opt.initFrom(q); q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q); } #ifndef QT_NO_SCROLLAREA if (resetBrushOrigin) painter->setBrushOrigin(oldBrushOrigin); #endif // QT_NO_SCROLLAREA } /* \internal This function is called when a widget is hidden or destroyed. It resets some application global pointers that should only refer active, visible widgets. */ #ifdef Q_WS_MAC extern QPointer<QWidget> qt_button_down; #else extern QWidget *qt_button_down; #endif void QWidgetPrivate::deactivateWidgetCleanup() { Q_Q(QWidget); // If this was the active application window, reset it if (QApplication::activeWindow() == q) QApplication::setActiveWindow(0); // If the is the active mouse press widget, reset it if (q == qt_button_down) qt_button_down = 0; } /*! Returns a pointer to the widget with window identifer/handle \a id. The window identifier type depends on the underlying window system, see \c qwindowdefs.h for the actual definition. If there is no widget with this identifier, 0 is returned. */ QWidget *QWidget::find(WId id) { return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0; } /*! \fn WId QWidget::internalWinId() const \internal Returns the window system identifier of the widget, or 0 if the widget is not created yet. */ /*! \fn WId QWidget::winId() const Returns the window system identifier of the widget. Portable in principle, but if you use it you are probably about to do something non-portable. Be careful. If a widget is non-native (alien) and winId() is invoked on it, that widget will be provided a native handle. On Mac OS X, the type returned depends on which framework Qt was linked against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt is using Cocoa, {WId} is a pointer to an NSView. This value may change at run-time. An event with type QEvent::WinIdChange will be sent to the widget following a change in window system identifier. \sa find() */ WId QWidget::winId() const { if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) { #ifdef ALIEN_DEBUG qDebug() << "QWidget::winId: creating native window for" << this; #endif QWidget *that = const_cast<QWidget*>(this); #ifndef Q_WS_QPA that->setAttribute(Qt::WA_NativeWindow); #endif that->d_func()->createWinId(); return that->data->winid; } return data->winid; } void QWidgetPrivate::createWinId(WId winid) { Q_Q(QWidget); #ifdef ALIEN_DEBUG qDebug() << "QWidgetPrivate::createWinId for" << q << winid; #endif const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow); if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) { #ifndef Q_WS_QPA if (!q->isWindow()) { QWidget *parent = q->parentWidget(); QWidgetPrivate *pd = parent->d_func(); if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors)) parent->setAttribute(Qt::WA_NativeWindow); if (!parent->internalWinId()) { pd->createWinId(); } for (int i = 0; i < pd->children.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(pd->children.at(i)); if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created) || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) { if (w!=q) { w->create(); } else { w->create(winid); // if the window has already been created, we // need to raise it to its proper stacking position if (winid) w->raise(); } } } } else { q->create(); } #else Q_UNUSED(winid); q->create(); #endif //Q_WS_QPA } } /*! \internal Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system. */ void QWidget::createWinId() { Q_D(QWidget); #ifdef ALIEN_DEBUG qDebug() << "QWidget::createWinId" << this; #endif // qWarning("QWidget::createWinId is obsolete, please fix your code."); d->createWinId(); } /*! \since 4.4 Returns the effective window system identifier of the widget, i.e. the native parent's window system identifier. If the widget is native, this function returns the native widget ID. Otherwise, the window ID of the first native parent widget, i.e., the top-level widget that contains this widget, is returned. \note We recommend that you do not store this value as it is likely to change at run-time. \sa nativeParentWidget() */ WId QWidget::effectiveWinId() const { WId id = internalWinId(); if (id || !testAttribute(Qt::WA_WState_Created)) return id; QWidget *realParent = nativeParentWidget(); if (!realParent && d_func()->inSetParent) { // In transitional state. This is really just a workaround. The real problem // is that QWidgetPrivate::setParent_sys (platform specific code) first sets // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created // attribute to false. The correct way is to do it the other way around, and // in that case the Qt::WA_WState_Created logic above will kick in and // return 0 whenever the widget is in a transitional state. However, changing // the original logic for all platforms is far more intrusive and might // break existing applications. // Note: The widget can only be in a transitional state when changing its // parent -- everything else is an internal error -- hence explicitly checking // against 'inSetParent' rather than doing an unconditional return whenever // 'realParent' is 0 (which may cause strange artifacts and headache later). return 0; } // This widget *must* have a native parent widget. Q_ASSERT(realParent); Q_ASSERT(realParent->internalWinId()); return realParent->internalWinId(); } #ifndef QT_NO_STYLE_STYLESHEET /*! \property QWidget::styleSheet \brief the widget's style sheet \since 4.2 The style sheet contains a textual description of customizations to the widget's style, as described in the \l{Qt Style Sheets} document. Since Qt 4.5, Qt style sheets fully supports Mac OS X. \warning Qt style sheets are currently not supported for custom QStyle subclasses. We plan to address this in some future release. \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets} */ QString QWidget::styleSheet() const { Q_D(const QWidget); if (!d->extra) return QString(); return d->extra->styleSheet; } void QWidget::setStyleSheet(const QString& styleSheet) { Q_D(QWidget); d->createExtra(); QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style); d->extra->styleSheet = styleSheet; if (styleSheet.isEmpty()) { // stylesheet removed if (!proxy) return; d->inheritStyle(); return; } if (proxy) { // style sheet update proxy->repolish(this); return; } if (testAttribute(Qt::WA_SetStyle)) { d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true); } else { d->setStyle_helper(new QStyleSheetStyle(0), true); } } #endif // QT_NO_STYLE_STYLESHEET /*! \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style() */ QStyle *QWidget::style() const { Q_D(const QWidget); if (d->extra && d->extra->style) return d->extra->style; return QApplication::style(); } /*! Sets the widget's GUI style to \a style. The ownership of the style object is not transferred. If no style is set, the widget uses the application's style, QApplication::style() instead. Setting a widget's style has no effect on existing or future child widgets. \warning This function is particularly useful for demonstration purposes, where you want to show Qt's styling capabilities. Real applications should avoid it and use one consistent GUI style instead. \warning Qt style sheets are currently not supported for custom QStyle subclasses. We plan to address this in some future release. \sa style(), QStyle, QApplication::style(), QApplication::setStyle() */ void QWidget::setStyle(QStyle *style) { Q_D(QWidget); setAttribute(Qt::WA_SetStyle, style != 0); d->createExtra(); #ifndef QT_NO_STYLE_STYLESHEET if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) { //if for some reason someone try to set a QStyleSheetStyle, ref it //(this may happen for exemple in QButtonDialogBox which propagates its style) proxy->ref(); d->setStyle_helper(style, false); } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) { // if we have an application stylesheet or have a proxy already, propagate d->setStyle_helper(new QStyleSheetStyle(style), true); } else #endif d->setStyle_helper(style, false); } void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool #ifdef Q_WS_MAC metalHack #endif ) { Q_Q(QWidget); QStyle *oldStyle = q->style(); #ifndef QT_NO_STYLE_STYLESHEET QWeakPointer<QStyle> origStyle; #endif #ifdef Q_WS_MAC // the metalhack boolean allows Qt/Mac to do a proper re-polish depending // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever // set when changing that attribute and passes the widget's CURRENT style. // therefore no need to do a reassignment. if (!metalHack) #endif { createExtra(); #ifndef QT_NO_STYLE_STYLESHEET origStyle = extra->style.data(); #endif extra->style = newStyle; } // repolish if (q->windowType() != Qt::Desktop) { if (polished) { oldStyle->unpolish(q); #ifdef Q_WS_MAC if (metalHack) macUpdateMetalAttribute(); #endif q->style()->polish(q); #ifdef Q_WS_MAC } else if (metalHack) { macUpdateMetalAttribute(); #endif } } if (propagate) { for (int i = 0; i < children.size(); ++i) { QWidget *c = qobject_cast<QWidget*>(children.at(i)); if (c) c->d_func()->inheritStyle(); } } #ifndef QT_NO_STYLE_STYLESHEET if (!qobject_cast<QStyleSheetStyle*>(newStyle)) { if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) { cssStyle->clearWidgetFont(q); } } #endif QEvent e(QEvent::StyleChange); QApplication::sendEvent(q, &e); #ifdef QT3_SUPPORT q->styleChange(*oldStyle); #endif #ifndef QT_NO_STYLE_STYLESHEET // dereference the old stylesheet style if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data())) proxy->deref(); #endif } // Inherits style from the current parent and propagates it as necessary void QWidgetPrivate::inheritStyle() { #ifndef QT_NO_STYLE_STYLESHEET Q_Q(QWidget); QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0; if (!q->styleSheet().isEmpty()) { Q_ASSERT(proxy); proxy->repolish(q); return; } QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0); QWidget *parent = q->parentWidget(); QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0; // If we have stylesheet on app or parent has stylesheet style, we need // to be running a proxy if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) { QStyle *newStyle = parentStyle; if (q->testAttribute(Qt::WA_SetStyle)) newStyle = new QStyleSheetStyle(origStyle); else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle)) newProxy->ref(); setStyle_helper(newStyle, true); return; } // So, we have no stylesheet on parent/app and we have an empty stylesheet // we just need our original style back if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different? return; // We could have inherited the proxy from our parent (which has a custom style) // In such a case we need to start following the application style (i.e revert // the propagation behavior of QStyleSheetStyle) if (!q->testAttribute(Qt::WA_SetStyle)) origStyle = 0; setStyle_helper(origStyle, true); #endif // QT_NO_STYLE_STYLESHEET } #ifdef QT3_SUPPORT /*! \overload Sets the widget's GUI style to \a style using the QStyleFactory. */ QStyle* QWidget::setStyle(const QString &style) { QStyle *s = QStyleFactory::create(style); setStyle(s); return s; } #endif /*! \fn bool QWidget::isWindow() const Returns true if the widget is an independent window, otherwise returns false. A window is a widget that isn't visually the child of any other widget and that usually has a frame and a \l{QWidget::setWindowTitle()}{window title}. A window can have a \l{QWidget::parentWidget()}{parent widget}. It will then be grouped with its parent and deleted when the parent is deleted, minimized when the parent is minimized etc. If supported by the window manager, it will also have a common taskbar entry with its parent. QDialog and QMainWindow widgets are by default windows, even if a parent widget is specified in the constructor. This behavior is specified by the Qt::Window flag. \sa window(), isModal(), parentWidget() */ /*! \property QWidget::modal \brief whether the widget is a modal widget This property only makes sense for windows. A modal widget prevents widgets in all other windows from getting any input. By default, this property is false. \sa isWindow(), windowModality, QDialog */ /*! \property QWidget::windowModality \brief which windows are blocked by the modal widget \since 4.1 This property only makes sense for windows. A modal widget prevents widgets in other windows from getting input. The value of this property controls which windows are blocked when the widget is visible. Changing this property while the window is visible has no effect; you must hide() the widget first, then show() it again. By default, this property is Qt::NonModal. \sa isWindow(), QWidget::modal, QDialog */ Qt::WindowModality QWidget::windowModality() const { return static_cast<Qt::WindowModality>(data->window_modality); } void QWidget::setWindowModality(Qt::WindowModality windowModality) { data->window_modality = windowModality; // setModal_sys() will be called by setAttribute() setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal)); setAttribute(Qt::WA_SetWindowModality, true); } /*! \fn bool QWidget::underMouse() const Returns true if the widget is under the mouse cursor; otherwise returns false. This value is not updated properly during drag and drop operations. \sa enterEvent(), leaveEvent() */ /*! \property QWidget::minimized \brief whether this widget is minimized (iconified) This property is only relevant for windows. By default, this property is false. \sa showMinimized(), visible, show(), hide(), showNormal(), maximized */ bool QWidget::isMinimized() const { return data->window_state & Qt::WindowMinimized; } /*! Shows the widget minimized, as an icon. Calling this function only affects \l{isWindow()}{windows}. \sa showNormal(), showMaximized(), show(), hide(), isVisible(), isMinimized() */ void QWidget::showMinimized() { bool isMin = isMinimized(); if (isMin && isVisible()) return; ensurePolished(); #ifdef QT3_SUPPORT if (parent()) QApplication::sendPostedEvents(parent(), QEvent::ChildInserted); #endif if (!isMin) setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized); show(); } /*! \property QWidget::maximized \brief whether this widget is maximized This property is only relevant for windows. \note Due to limitations on some window systems, this does not always report the expected results (e.g., if the user on X11 maximizes the window via the window manager, Qt has no way of distinguishing this from any other resize). This is expected to improve as window manager protocols evolve. By default, this property is false. \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized */ bool QWidget::isMaximized() const { return data->window_state & Qt::WindowMaximized; } /*! Returns the current window state. The window state is a OR'ed combination of Qt::WindowState: Qt::WindowMinimized, Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive. \sa Qt::WindowState setWindowState() */ Qt::WindowStates QWidget::windowState() const { return Qt::WindowStates(data->window_state); } /*!\internal The function sets the window state on child widgets similar to setWindowState(). The difference is that the window state changed event has the isOverride() flag set. It exists mainly to keep Q3Workspace working. */ void QWidget::overrideWindowState(Qt::WindowStates newstate) { QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true); data->window_state = newstate; QApplication::sendEvent(this, &e); } /*! \fn void QWidget::setWindowState(Qt::WindowStates windowState) Sets the window state to \a windowState. The window state is a OR'ed combination of Qt::WindowState: Qt::WindowMinimized, Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive. If the window is not visible (i.e. isVisible() returns false), the window state will take effect when show() is called. For visible windows, the change is immediate. For example, to toggle between full-screen and normal mode, use the following code: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0 In order to restore and activate a minimized window (while preserving its maximized and/or full-screen state), use the following: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1 Calling this function will hide the widget. You must call show() to make the widget visible again. \note On some window systems Qt::WindowActive is not immediate, and may be ignored in certain cases. When the window state changes, the widget receives a changeEvent() of type QEvent::WindowStateChange. \sa Qt::WindowState windowState() */ /*! \property QWidget::fullScreen \brief whether the widget is shown in full screen mode A widget in full screen mode occupies the whole screen area and does not display window decorations, such as a title bar. By default, this property is false. \sa windowState(), minimized, maximized */ bool QWidget::isFullScreen() const { return data->window_state & Qt::WindowFullScreen; } /*! Shows the widget in full-screen mode. Calling this function only affects \l{isWindow()}{windows}. To return from full-screen mode, call showNormal(). Full-screen mode works fine under Windows, but has certain problems under X. These problems are due to limitations of the ICCCM protocol that specifies the communication between X11 clients and the window manager. ICCCM simply does not understand the concept of non-decorated full-screen windows. Therefore, the best we can do is to request a borderless window and place and resize it to fill the entire screen. Depending on the window manager, this may or may not work. The borderless window is requested using MOTIF hints, which are at least partially supported by virtually all modern window managers. An alternative would be to bypass the window manager entirely and create a window with the Qt::X11BypassWindowManagerHint flag. This has other severe problems though, like totally broken keyboard focus and very strange effects on desktop changes or when the user raises other windows. X11 window managers that follow modern post-ICCCM specifications support full-screen mode properly. \sa showNormal(), showMaximized(), show(), hide(), isVisible() */ void QWidget::showFullScreen() { #ifdef Q_WS_MAC // If the unified toolbar is enabled, we have to disable it before going fullscreen. QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this); if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) { mainWindow->setUnifiedTitleAndToolBarOnMac(false); QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout()); mainLayout->activateUnifiedToolbarAfterFullScreen = true; } #endif // Q_WS_MAC ensurePolished(); #ifdef QT3_SUPPORT if (parent()) QApplication::sendPostedEvents(parent(), QEvent::ChildInserted); #endif setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized)) | Qt::WindowFullScreen); show(); activateWindow(); } /*! Shows the widget maximized. Calling this function only affects \l{isWindow()}{windows}. On X11, this function may not work properly with certain window managers. See the \l{Window Geometry} documentation for an explanation. \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible() */ void QWidget::showMaximized() { ensurePolished(); #ifdef QT3_SUPPORT if (parent()) QApplication::sendPostedEvents(parent(), QEvent::ChildInserted); #endif setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen)) | Qt::WindowMaximized); #ifdef Q_WS_MAC // If the unified toolbar was enabled before going fullscreen, we have to enable it back. QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this); if (mainWindow) { QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout()); if (mainLayout->activateUnifiedToolbarAfterFullScreen) { mainWindow->setUnifiedTitleAndToolBarOnMac(true); mainLayout->activateUnifiedToolbarAfterFullScreen = false; } } #endif // Q_WS_MAC show(); } /*! Restores the widget after it has been maximized or minimized. Calling this function only affects \l{isWindow()}{windows}. \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible() */ void QWidget::showNormal() { ensurePolished(); #ifdef QT3_SUPPORT if (parent()) QApplication::sendPostedEvents(parent(), QEvent::ChildInserted); #endif setWindowState(windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized | Qt::WindowFullScreen)); #ifdef Q_WS_MAC // If the unified toolbar was enabled before going fullscreen, we have to enable it back. QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this); if (mainWindow) { QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout()); if (mainLayout->activateUnifiedToolbarAfterFullScreen) { mainWindow->setUnifiedTitleAndToolBarOnMac(true); mainLayout->activateUnifiedToolbarAfterFullScreen = false; } } #endif // Q_WS_MAC show(); } /*! Returns true if this widget would become enabled if \a ancestor is enabled; otherwise returns false. This is the case if neither the widget itself nor every parent up to but excluding \a ancestor has been explicitly disabled. isEnabledTo(0) is equivalent to isEnabled(). \sa setEnabled() enabled */ bool QWidget::isEnabledTo(QWidget* ancestor) const { const QWidget * w = this; while (!w->testAttribute(Qt::WA_ForceDisabled) && !w->isWindow() && w->parentWidget() && w->parentWidget() != ancestor) w = w->parentWidget(); return !w->testAttribute(Qt::WA_ForceDisabled); } #ifndef QT_NO_ACTION /*! Appends the action \a action to this widget's list of actions. All QWidgets have a list of \l{QAction}s, however they can be represented graphically in many different ways. The default use of the QAction list (as returned by actions()) is to create a context QMenu. A QWidget should only have one of each action and adding an action it already has will not cause the same action to be in the widget twice. The ownership of \a action is not transferred to this QWidget. \sa removeAction(), insertAction(), actions(), QMenu */ void QWidget::addAction(QAction *action) { insertAction(0, action); } /*! Appends the actions \a actions to this widget's list of actions. \sa removeAction(), QMenu, addAction() */ void QWidget::addActions(QList<QAction*> actions) { for(int i = 0; i < actions.count(); i++) insertAction(0, actions.at(i)); } /*! Inserts the action \a action to this widget's list of actions, before the action \a before. It appends the action if \a before is 0 or \a before is not a valid action for this widget. A QWidget should only have one of each action. \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions() */ void QWidget::insertAction(QAction *before, QAction *action) { if(!action) { qWarning("QWidget::insertAction: Attempt to insert null action"); return; } Q_D(QWidget); if(d->actions.contains(action)) removeAction(action); int pos = d->actions.indexOf(before); if (pos < 0) { before = 0; pos = d->actions.size(); } d->actions.insert(pos, action); QActionPrivate *apriv = action->d_func(); apriv->widgets.append(this); QActionEvent e(QEvent::ActionAdded, action, before); QApplication::sendEvent(this, &e); } /*! Inserts the actions \a actions to this widget's list of actions, before the action \a before. It appends the action if \a before is 0 or \a before is not a valid action for this widget. A QWidget can have at most one of each action. \sa removeAction(), QMenu, insertAction(), contextMenuPolicy */ void QWidget::insertActions(QAction *before, QList<QAction*> actions) { for(int i = 0; i < actions.count(); ++i) insertAction(before, actions.at(i)); } /*! Removes the action \a action from this widget's list of actions. \sa insertAction(), actions(), insertAction() */ void QWidget::removeAction(QAction *action) { if (!action) return; Q_D(QWidget); QActionPrivate *apriv = action->d_func(); apriv->widgets.removeAll(this); if (d->actions.removeAll(action)) { QActionEvent e(QEvent::ActionRemoved, action); QApplication::sendEvent(this, &e); } } /*! Returns the (possibly empty) list of this widget's actions. \sa contextMenuPolicy, insertAction(), removeAction() */ QList<QAction*> QWidget::actions() const { Q_D(const QWidget); return d->actions; } #endif // QT_NO_ACTION /*! \fn bool QWidget::isEnabledToTLW() const \obsolete This function is deprecated. It is equivalent to isEnabled() */ /*! \property QWidget::enabled \brief whether the widget is enabled In general an enabled widget handles keyboard and mouse events; a disabled widget does not. An exception is made with \l{QAbstractButton}. Some widgets display themselves differently when they are disabled. For example a button might draw its label grayed out. If your widget needs to know when it becomes enabled or disabled, you can use the changeEvent() with type QEvent::EnabledChange. Disabling a widget implicitly disables all its children. Enabling respectively enables all child widgets unless they have been explicitly disabled. By default, this property is true. \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent() */ void QWidget::setEnabled(bool enable) { Q_D(QWidget); setAttribute(Qt::WA_ForceDisabled, !enable); d->setEnabled_helper(enable); } void QWidgetPrivate::setEnabled_helper(bool enable) { Q_Q(QWidget); if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled()) return; // nothing we can do if (enable != q->testAttribute(Qt::WA_Disabled)) return; // nothing to do q->setAttribute(Qt::WA_Disabled, !enable); updateSystemBackground(); if (!enable && q->window()->focusWidget() == q) { bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled()); if (!parentIsEnabled || !q->focusNextChild()) q->clearFocus(); } Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled; for (int i = 0; i < children.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(children.at(i)); if (w && !w->testAttribute(attribute)) w->d_func()->setEnabled_helper(enable); } #if defined(Q_WS_X11) if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) { // enforce the windows behavior of clearing the cursor on // disabled widgets qt_x11_enforce_cursor(q); } #endif #if defined(Q_WS_MAC) setEnabled_helper_sys(enable); #endif #ifndef QT_NO_IM if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) { QWidget *focusWidget = effectiveFocusWidget(); QInputContext *qic = focusWidget->d_func()->inputContext(); if (enable) { if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) qic->setFocusWidget(focusWidget); } else { qic->reset(); qic->setFocusWidget(0); } } #endif //QT_NO_IM QEvent e(QEvent::EnabledChange); QApplication::sendEvent(q, &e); #ifdef QT3_SUPPORT q->enabledChange(!enable); // compatibility #endif } /*! \property QWidget::acceptDrops \brief whether drop events are enabled for this widget Setting this property to true announces to the system that this widget \e may be able to accept drop events. If the widget is the desktop (windowType() == Qt::Desktop), this may fail if another application is using the desktop; you can call acceptDrops() to test if this occurs. \warning Do not modify this property in a drag and drop event handler. By default, this property is false. \sa {Drag and Drop} */ bool QWidget::acceptDrops() const { return testAttribute(Qt::WA_AcceptDrops); } void QWidget::setAcceptDrops(bool on) { setAttribute(Qt::WA_AcceptDrops, on); } /*! \fn void QWidget::enabledChange(bool) \internal \obsolete */ /*! \fn void QWidget::paletteChange(const QPalette &) \internal \obsolete */ /*! \fn void QWidget::fontChange(const QFont &) \internal \obsolete */ /*! \fn void QWidget::windowActivationChange(bool) \internal \obsolete */ /*! \fn void QWidget::languageChange() \obsolete */ /*! \fn void QWidget::styleChange(QStyle& style) \internal \obsolete */ /*! Disables widget input events if \a disable is true; otherwise enables input events. See the \l enabled documentation for more information. \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent() */ void QWidget::setDisabled(bool disable) { setEnabled(!disable); } /*! \property QWidget::frameGeometry \brief geometry of the widget relative to its parent including any window frame See the \l{Window Geometry} documentation for an overview of geometry issues with windows. By default, this property contains a value that depends on the user's platform and screen geometry. \sa geometry() x() y() pos() */ QRect QWidget::frameGeometry() const { Q_D(const QWidget); if (isWindow() && ! (windowType() == Qt::Popup)) { QRect fs = d->frameStrut(); return QRect(data->crect.x() - fs.left(), data->crect.y() - fs.top(), data->crect.width() + fs.left() + fs.right(), data->crect.height() + fs.top() + fs.bottom()); } return data->crect; } /*! \property QWidget::x \brief the x coordinate of the widget relative to its parent including any window frame See the \l{Window Geometry} documentation for an overview of geometry issues with windows. By default, this property has a value of 0. \sa frameGeometry, y, pos */ int QWidget::x() const { Q_D(const QWidget); if (isWindow() && ! (windowType() == Qt::Popup)) return data->crect.x() - d->frameStrut().left(); return data->crect.x(); } /*! \property QWidget::y \brief the y coordinate of the widget relative to its parent and including any window frame See the \l{Window Geometry} documentation for an overview of geometry issues with windows. By default, this property has a value of 0. \sa frameGeometry, x, pos */ int QWidget::y() const { Q_D(const QWidget); if (isWindow() && ! (windowType() == Qt::Popup)) return data->crect.y() - d->frameStrut().top(); return data->crect.y(); } /*! \property QWidget::pos \brief the position of the widget within its parent widget If the widget is a window, the position is that of the widget on the desktop, including its frame. When changing the position, the widget, if visible, receives a move event (moveEvent()) immediately. If the widget is not currently visible, it is guaranteed to receive an event before it is shown. By default, this property contains a position that refers to the origin. \warning Calling move() or setGeometry() inside moveEvent() can lead to infinite recursion. See the \l{Window Geometry} documentation for an overview of geometry issues with windows. \sa frameGeometry, size x(), y() */ QPoint QWidget::pos() const { Q_D(const QWidget); if (isWindow() && ! (windowType() == Qt::Popup)) { QRect fs = d->frameStrut(); return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top()); } return data->crect.topLeft(); } /*! \property QWidget::geometry \brief the geometry of the widget relative to its parent and excluding the window frame When changing the geometry, the widget, if visible, receives a move event (moveEvent()) and/or a resize event (resizeEvent()) immediately. If the widget is not currently visible, it is guaranteed to receive appropriate events before it is shown. The size component is adjusted if it lies outside the range defined by minimumSize() and maximumSize(). \warning Calling setGeometry() inside resizeEvent() or moveEvent() can lead to infinite recursion. See the \l{Window Geometry} documentation for an overview of geometry issues with windows. By default, this property contains a value that depends on the user's platform and screen geometry. \sa frameGeometry(), rect(), move(), resize(), moveEvent(), resizeEvent(), minimumSize(), maximumSize() */ /*! \property QWidget::normalGeometry \brief the geometry of the widget as it will appear when shown as a normal (not maximized or full screen) top-level widget For child widgets this property always holds an empty rectangle. By default, this property contains an empty rectangle. \sa QWidget::windowState(), QWidget::geometry */ /*! \property QWidget::size \brief the size of the widget excluding any window frame If the widget is visible when it is being resized, it receives a resize event (resizeEvent()) immediately. If the widget is not currently visible, it is guaranteed to receive an event before it is shown. The size is adjusted if it lies outside the range defined by minimumSize() and maximumSize(). By default, this property contains a value that depends on the user's platform and screen geometry. \warning Calling resize() or setGeometry() inside resizeEvent() can lead to infinite recursion. \note Setting the size to \c{QSize(0, 0)} will cause the widget to not appear on screen. This also applies to windows. \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize() */ /*! \property QWidget::width \brief the width of the widget excluding any window frame See the \l{Window Geometry} documentation for an overview of geometry issues with windows. \note Do not use this function to find the width of a screen on a \l{QDesktopWidget}{multiple screen desktop}. Read \l{QDesktopWidget#Screen Geometry}{this note} for details. By default, this property contains a value that depends on the user's platform and screen geometry. \sa geometry, height, size */ /*! \property QWidget::height \brief the height of the widget excluding any window frame See the \l{Window Geometry} documentation for an overview of geometry issues with windows. \note Do not use this function to find the height of a screen on a \l{QDesktopWidget}{multiple screen desktop}. Read \l{QDesktopWidget#Screen Geometry}{this note} for details. By default, this property contains a value that depends on the user's platform and screen geometry. \sa geometry, width, size */ /*! \property QWidget::rect \brief the internal geometry of the widget excluding any window frame The rect property equals QRect(0, 0, width(), height()). See the \l{Window Geometry} documentation for an overview of geometry issues with windows. By default, this property contains a value that depends on the user's platform and screen geometry. \sa size */ QRect QWidget::normalGeometry() const { Q_D(const QWidget); if (!d->extra || !d->extra->topextra) return QRect(); if (!isMaximized() && !isFullScreen()) return geometry(); return d->topData()->normalGeometry; } /*! \property QWidget::childrenRect \brief the bounding rectangle of the widget's children Hidden children are excluded. By default, for a widget with no children, this property contains a rectangle with zero width and height located at the origin. \sa childrenRegion() geometry() */ QRect QWidget::childrenRect() const { Q_D(const QWidget); QRect r(0, 0, 0, 0); for (int i = 0; i < d->children.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(d->children.at(i)); if (w && !w->isWindow() && !w->isHidden()) r |= w->geometry(); } return r; } /*! \property QWidget::childrenRegion \brief the combined region occupied by the widget's children Hidden children are excluded. By default, for a widget with no children, this property contains an empty region. \sa childrenRect() geometry() mask() */ QRegion QWidget::childrenRegion() const { Q_D(const QWidget); QRegion r; for (int i = 0; i < d->children.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(d->children.at(i)); if (w && !w->isWindow() && !w->isHidden()) { QRegion mask = w->mask(); if (mask.isEmpty()) r |= w->geometry(); else r |= mask.translated(w->pos()); } } return r; } /*! \property QWidget::minimumSize \brief the widget's minimum size The widget cannot be resized to a smaller size than the minimum widget size. The widget's size is forced to the minimum size if the current size is smaller. The minimum size set by this function will override the minimum size defined by QLayout. In order to unset the minimum size, use a value of \c{QSize(0, 0)}. By default, this property contains a size with zero width and height. \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement */ QSize QWidget::minimumSize() const { Q_D(const QWidget); return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0); } /*! \property QWidget::maximumSize \brief the widget's maximum size in pixels The widget cannot be resized to a larger size than the maximum widget size. By default, this property contains a size in which both width and height have values of 16777215. \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size of widgets. \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement */ QSize QWidget::maximumSize() const { Q_D(const QWidget); return d->extra ? QSize(d->extra->maxw, d->extra->maxh) : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); } /*! \property QWidget::minimumWidth \brief the widget's minimum width in pixels This property corresponds to the width held by the \l minimumSize property. By default, this property has a value of 0. \sa minimumSize, minimumHeight */ /*! \property QWidget::minimumHeight \brief the widget's minimum height in pixels This property corresponds to the height held by the \l minimumSize property. By default, this property has a value of 0. \sa minimumSize, minimumWidth */ /*! \property QWidget::maximumWidth \brief the widget's maximum width in pixels This property corresponds to the width held by the \l maximumSize property. By default, this property contains a value of 16777215. \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size of widgets. \sa maximumSize, maximumHeight */ /*! \property QWidget::maximumHeight \brief the widget's maximum height in pixels This property corresponds to the height held by the \l maximumSize property. By default, this property contains a value of 16777215. \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size of widgets. \sa maximumSize, maximumWidth */ /*! \property QWidget::sizeIncrement \brief the size increment of the widget When the user resizes the window, the size will move in steps of sizeIncrement().width() pixels horizontally and sizeIncrement.height() pixels vertically, with baseSize() as the basis. Preferred widget sizes are for non-negative integers \e i and \e j: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2 Note that while you can set the size increment for all widgets, it only affects windows. By default, this property contains a size with zero width and height. \warning The size increment has no effect under Windows, and may be disregarded by the window manager on X11. \sa size, minimumSize, maximumSize */ QSize QWidget::sizeIncrement() const { Q_D(const QWidget); return (d->extra && d->extra->topextra) ? QSize(d->extra->topextra->incw, d->extra->topextra->inch) : QSize(0, 0); } /*! \property QWidget::baseSize \brief the base size of the widget The base size is used to calculate a proper widget size if the widget defines sizeIncrement(). By default, for a newly-created widget, this property contains a size with zero width and height. \sa setSizeIncrement() */ QSize QWidget::baseSize() const { Q_D(const QWidget); return (d->extra != 0 && d->extra->topextra != 0) ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh) : QSize(0, 0); } bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh) { Q_Q(QWidget); #ifdef Q_WS_QWS if (q->isWindow()) { const QRect maxWindowRect = QApplication::desktop()->availableGeometry(QApplication::desktop()->screenNumber(q)); if (!maxWindowRect.isEmpty()) { // ### This is really just a work-around. Layout shouldn't be // asking for minimum sizes bigger than the screen. if (minw > maxWindowRect.width()) minw = maxWindowRect.width(); if (minh > maxWindowRect.height()) minh = maxWindowRect.height(); } } #endif int mw = minw, mh = minh; if (mw == QWIDGETSIZE_MAX) mw = 0; if (mh == QWIDGETSIZE_MAX) mh = 0; if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) { qWarning("QWidget::setMinimumSize: (%s/%s) " "The largest allowed size is (%d,%d)", q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX); minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX); } if (minw < 0 || minh < 0) { qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) " "are not possible", q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh); minw = mw = qMax(minw, 0); minh = mh = qMax(minh, 0); } createExtra(); if (extra->minw == mw && extra->minh == mh) return false; extra->minw = mw; extra->minh = mh; extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0); return true; } /*! \overload This function corresponds to setMinimumSize(QSize(minw, minh)). Sets the minimum width to \a minw and the minimum height to \a minh. */ void QWidget::setMinimumSize(int minw, int minh) { Q_D(QWidget); if (!d->setMinimumSize_helper(minw, minh)) return; if (isWindow()) d->setConstraints_sys(); if (minw > width() || minh > height()) { bool resized = testAttribute(Qt::WA_Resized); bool maximized = isMaximized(); resize(qMax(minw,width()), qMax(minh,height())); setAttribute(Qt::WA_Resized, resized); //not a user resize if (maximized) data->window_state = data->window_state | Qt::WindowMaximized; } #ifndef QT_NO_GRAPHICSVIEW if (d->extra) { if (d->extra->proxyWidget) d->extra->proxyWidget->setMinimumSize(minw, minh); } #endif d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh); } bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh) { Q_Q(QWidget); if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) { qWarning("QWidget::setMaximumSize: (%s/%s) " "The largest allowed size is (%d,%d)", q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); maxw = qMin<int>(maxw, QWIDGETSIZE_MAX); maxh = qMin<int>(maxh, QWIDGETSIZE_MAX); } if (maxw < 0 || maxh < 0) { qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) " "are not possible", q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh); maxw = qMax(maxw, 0); maxh = qMax(maxh, 0); } createExtra(); if (extra->maxw == maxw && extra->maxh == maxh) return false; extra->maxw = maxw; extra->maxh = maxh; extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) | (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0); return true; } /*! \overload This function corresponds to setMaximumSize(QSize(\a maxw, \a maxh)). Sets the maximum width to \a maxw and the maximum height to \a maxh. */ void QWidget::setMaximumSize(int maxw, int maxh) { Q_D(QWidget); if (!d->setMaximumSize_helper(maxw, maxh)) return; if (isWindow()) d->setConstraints_sys(); if (maxw < width() || maxh < height()) { bool resized = testAttribute(Qt::WA_Resized); resize(qMin(maxw,width()), qMin(maxh,height())); setAttribute(Qt::WA_Resized, resized); //not a user resize } #ifndef QT_NO_GRAPHICSVIEW if (d->extra) { if (d->extra->proxyWidget) d->extra->proxyWidget->setMaximumSize(maxw, maxh); } #endif d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh); } /*! \overload Sets the x (width) size increment to \a w and the y (height) size increment to \a h. */ void QWidget::setSizeIncrement(int w, int h) { Q_D(QWidget); d->createTLExtra(); QTLWExtra* x = d->topData(); if (x->incw == w && x->inch == h) return; x->incw = w; x->inch = h; if (isWindow()) d->setConstraints_sys(); } /*! \overload This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets the widgets base size to width \a basew and height \a baseh. */ void QWidget::setBaseSize(int basew, int baseh) { Q_D(QWidget); d->createTLExtra(); QTLWExtra* x = d->topData(); if (x->basew == basew && x->baseh == baseh) return; x->basew = basew; x->baseh = baseh; if (isWindow()) d->setConstraints_sys(); } /*! Sets both the minimum and maximum sizes of the widget to \a s, thereby preventing it from ever growing or shrinking. This will override the default size constraints set by QLayout. To remove constraints, set the size to QWIDGETSIZE_MAX. Alternatively, if you want the widget to have a fixed size based on its contents, you can call QLayout::setSizeConstraint(QLayout::SetFixedSize); \sa maximumSize, minimumSize */ void QWidget::setFixedSize(const QSize & s) { setFixedSize(s.width(), s.height()); } /*! \fn void QWidget::setFixedSize(int w, int h) \overload Sets the width of the widget to \a w and the height to \a h. */ void QWidget::setFixedSize(int w, int h) { Q_D(QWidget); #ifdef Q_WS_QWS // temporary fix for 4.3.x. // Should move the embedded spesific contraints in setMinimumSize_helper into QLayout int tmpW = w; int tmpH = h; bool minSizeSet = d->setMinimumSize_helper(tmpW, tmpH); #else bool minSizeSet = d->setMinimumSize_helper(w, h); #endif bool maxSizeSet = d->setMaximumSize_helper(w, h); if (!minSizeSet && !maxSizeSet) return; if (isWindow()) d->setConstraints_sys(); else d->updateGeometry_helper(true); if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX) resize(w, h); } void QWidget::setMinimumWidth(int w) { Q_D(QWidget); d->createExtra(); uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0); setMinimumSize(w, minimumSize().height()); d->extra->explicitMinSize = expl; } void QWidget::setMinimumHeight(int h) { Q_D(QWidget); d->createExtra(); uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0); setMinimumSize(minimumSize().width(), h); d->extra->explicitMinSize = expl; } void QWidget::setMaximumWidth(int w) { Q_D(QWidget); d->createExtra(); uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal); setMaximumSize(w, maximumSize().height()); d->extra->explicitMaxSize = expl; } void QWidget::setMaximumHeight(int h) { Q_D(QWidget); d->createExtra(); uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical); setMaximumSize(maximumSize().width(), h); d->extra->explicitMaxSize = expl; } /*! Sets both the minimum and maximum width of the widget to \a w without changing the heights. Provided for convenience. \sa sizeHint() minimumSize() maximumSize() setFixedSize() */ void QWidget::setFixedWidth(int w) { Q_D(QWidget); d->createExtra(); uint explMin = d->extra->explicitMinSize | Qt::Horizontal; uint explMax = d->extra->explicitMaxSize | Qt::Horizontal; setMinimumSize(w, minimumSize().height()); setMaximumSize(w, maximumSize().height()); d->extra->explicitMinSize = explMin; d->extra->explicitMaxSize = explMax; } /*! Sets both the minimum and maximum heights of the widget to \a h without changing the widths. Provided for convenience. \sa sizeHint() minimumSize() maximumSize() setFixedSize() */ void QWidget::setFixedHeight(int h) { Q_D(QWidget); d->createExtra(); uint explMin = d->extra->explicitMinSize | Qt::Vertical; uint explMax = d->extra->explicitMaxSize | Qt::Vertical; setMinimumSize(minimumSize().width(), h); setMaximumSize(maximumSize().width(), h); d->extra->explicitMinSize = explMin; d->extra->explicitMaxSize = explMax; } /*! Translates the widget coordinate \a pos to the coordinate system of \a parent. The \a parent must not be 0 and must be a parent of the calling widget. \sa mapFrom() mapToParent() mapToGlobal() underMouse() */ QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const { QPoint p = pos; if (parent) { const QWidget * w = this; while (w != parent) { Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)", "parent must be in parent hierarchy"); p = w->mapToParent(p); w = w->parentWidget(); } } return p; } /*! Translates the widget coordinate \a pos from the coordinate system of \a parent to this widget's coordinate system. The \a parent must not be 0 and must be a parent of the calling widget. \sa mapTo() mapFromParent() mapFromGlobal() underMouse() */ QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const { QPoint p(pos); if (parent) { const QWidget * w = this; while (w != parent) { Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)", "parent must be in parent hierarchy"); p = w->mapFromParent(p); w = w->parentWidget(); } } return p; } /*! Translates the widget coordinate \a pos to a coordinate in the parent widget. Same as mapToGlobal() if the widget has no parent. \sa mapFromParent() mapTo() mapToGlobal() underMouse() */ QPoint QWidget::mapToParent(const QPoint &pos) const { return pos + data->crect.topLeft(); } /*! Translates the parent widget coordinate \a pos to widget coordinates. Same as mapFromGlobal() if the widget has no parent. \sa mapToParent() mapFrom() mapFromGlobal() underMouse() */ QPoint QWidget::mapFromParent(const QPoint &pos) const { return pos - data->crect.topLeft(); } /*! Returns the window for this widget, i.e. the next ancestor widget that has (or could have) a window-system frame. If the widget is a window, the widget itself is returned. Typical usage is changing the window title: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3 \sa isWindow() */ QWidget *QWidget::window() const { QWidget *w = (QWidget *)this; QWidget *p = w->parentWidget(); while (!w->isWindow() && p) { w = p; p = p->parentWidget(); } return w; } /*! \since 4.4 Returns the native parent for this widget, i.e. the next ancestor widget that has a system identifier, or 0 if it does not have any native parent. \sa effectiveWinId() */ QWidget *QWidget::nativeParentWidget() const { QWidget *parent = parentWidget(); while (parent && !parent->internalWinId()) parent = parent->parentWidget(); return parent; } /*! \fn QWidget *QWidget::topLevelWidget() const \obsolete Use window() instead. */ #ifdef QT3_SUPPORT /*! Returns the color role used for painting the widget's background. Use QPalette(backgroundRole(()) instead. */ Qt::BackgroundMode QWidget::backgroundMode() const { if (testAttribute(Qt::WA_NoSystemBackground)) return Qt::NoBackground; switch(backgroundRole()) { case QPalette::WindowText: return Qt::PaletteForeground; case QPalette::Button: return Qt::PaletteButton; case QPalette::Light: return Qt::PaletteLight; case QPalette::Midlight: return Qt::PaletteMidlight; case QPalette::Dark: return Qt::PaletteDark; case QPalette::Mid: return Qt::PaletteMid; case QPalette::Text: return Qt::PaletteText; case QPalette::BrightText: return Qt::PaletteBrightText; case QPalette::Base: return Qt::PaletteBase; case QPalette::Window: return Qt::PaletteBackground; case QPalette::Shadow: return Qt::PaletteShadow; case QPalette::Highlight: return Qt::PaletteHighlight; case QPalette::HighlightedText: return Qt::PaletteHighlightedText; case QPalette::ButtonText: return Qt::PaletteButtonText; case QPalette::Link: return Qt::PaletteLink; case QPalette::LinkVisited: return Qt::PaletteLinkVisited; default: break; } return Qt::NoBackground; } /*! \fn void QWidget::setBackgroundMode(Qt::BackgroundMode widgetBackground, Qt::BackgroundMode paletteBackground) Sets the color role used for painting the widget's background to background mode \a widgetBackground. The \a paletteBackground mode parameter is ignored. */ void QWidget::setBackgroundMode(Qt::BackgroundMode m, Qt::BackgroundMode) { Q_D(QWidget); if(m == Qt::NoBackground) { setAttribute(Qt::WA_NoSystemBackground, true); return; } setAttribute(Qt::WA_NoSystemBackground, false); d->fg_role = QPalette::NoRole; QPalette::ColorRole role = d->bg_role; switch(m) { case Qt::FixedColor: case Qt::FixedPixmap: break; case Qt::PaletteForeground: role = QPalette::WindowText; break; case Qt::PaletteButton: role = QPalette::Button; break; case Qt::PaletteLight: role = QPalette::Light; break; case Qt::PaletteMidlight: role = QPalette::Midlight; break; case Qt::PaletteDark: role = QPalette::Dark; break; case Qt::PaletteMid: role = QPalette::Mid; break; case Qt::PaletteText: role = QPalette::Text; break; case Qt::PaletteBrightText: role = QPalette::BrightText; break; case Qt::PaletteBase: role = QPalette::Base; break; case Qt::PaletteBackground: role = QPalette::Window; break; case Qt::PaletteShadow: role = QPalette::Shadow; break; case Qt::PaletteHighlight: role = QPalette::Highlight; break; case Qt::PaletteHighlightedText: role = QPalette::HighlightedText; break; case Qt::PaletteButtonText: role = QPalette::ButtonText; break; case Qt::PaletteLink: role = QPalette::Link; break; case Qt::PaletteLinkVisited: role = QPalette::LinkVisited; break; case Qt::X11ParentRelative: d->fg_role = role = QPalette::NoRole; default: break; } setBackgroundRole(role); } /*! The widget mapper is no longer part of the public API. */ QT3_SUPPORT QWidgetMapper *QWidget::wmapper() { return QWidgetPrivate::mapper; } #endif /*! Returns the background role of the widget. The background role defines the brush from the widget's \l palette that is used to render the background. If no explicit background role is set, the widget inherts its parent widget's background role. \sa setBackgroundRole(), foregroundRole() */ QPalette::ColorRole QWidget::backgroundRole() const { const QWidget *w = this; do { QPalette::ColorRole role = w->d_func()->bg_role; if (role != QPalette::NoRole) return role; if (w->isWindow() || w->windowType() == Qt::SubWindow) break; w = w->parentWidget(); } while (w); return QPalette::Window; } /*! Sets the background role of the widget to \a role. The background role defines the brush from the widget's \l palette that is used to render the background. If \a role is QPalette::NoRole, then the widget inherits its parent's background role. Note that styles are free to choose any color from the palette. You can modify the palette or set a style sheet if you don't achieve the result you want with setBackgroundRole(). \sa backgroundRole(), foregroundRole() */ void QWidget::setBackgroundRole(QPalette::ColorRole role) { Q_D(QWidget); d->bg_role = role; d->updateSystemBackground(); d->propagatePaletteChange(); d->updateIsOpaque(); } /*! Returns the foreground role. The foreground role defines the color from the widget's \l palette that is used to draw the foreground. If no explicit foreground role is set, the function returns a role that contrasts with the background role. \sa setForegroundRole(), backgroundRole() */ QPalette::ColorRole QWidget::foregroundRole() const { Q_D(const QWidget); QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role); if (rl != QPalette::NoRole) return rl; QPalette::ColorRole role = QPalette::WindowText; switch (backgroundRole()) { case QPalette::Button: role = QPalette::ButtonText; break; case QPalette::Base: role = QPalette::Text; break; case QPalette::Dark: case QPalette::Shadow: role = QPalette::Light; break; case QPalette::Highlight: role = QPalette::HighlightedText; break; case QPalette::ToolTipBase: role = QPalette::ToolTipText; break; default: ; } return role; } /*! Sets the foreground role of the widget to \a role. The foreground role defines the color from the widget's \l palette that is used to draw the foreground. If \a role is QPalette::NoRole, the widget uses a foreground role that contrasts with the background role. Note that styles are free to choose any color from the palette. You can modify the palette or set a style sheet if you don't achieve the result you want with setForegroundRole(). \sa foregroundRole(), backgroundRole() */ void QWidget::setForegroundRole(QPalette::ColorRole role) { Q_D(QWidget); d->fg_role = role; d->updateSystemBackground(); d->propagatePaletteChange(); } /*! \property QWidget::palette \brief the widget's palette This property describes the widget's palette. The palette is used by the widget's style when rendering standard components, and is available as a means to ensure that custom widgets can maintain consistency with the native platform's look and feel. It's common that different platforms, or different styles, have different palettes. When you assign a new palette to a widget, the color roles from this palette are combined with the widget's default palette to form the widget's final palette. The palette entry for the widget's background role is used to fill the widget's background (see QWidget::autoFillBackground), and the foreground role initializes QPainter's pen. The default depends on the system environment. QApplication maintains a system/theme palette which serves as a default for all widgets. There may also be special palette defaults for certain types of widgets (e.g., on Windows XP and Vista, all classes that derive from QMenuBar have a special default palette). You can also define default palettes for widgets yourself by passing a custom palette and the name of a widget to QApplication::setPalette(). Finally, the style always has the option of polishing the palette as it's assigned (see QStyle::polish()). QWidget propagates explicit palette roles from parent to child. If you assign a brush or color to a specific role on a palette and assign that palette to a widget, that role will propagate to all the widget's children, overriding any system defaults for that role. Note that palettes by default don't propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation attribute is enabled. QWidget's palette propagation is similar to its font propagation. The current style, which is used to render the content of all standard Qt widgets, is free to choose colors and brushes from the widget palette, or in some cases, to ignore the palette (partially, or completely). In particular, certain styles like GTK style, Mac style, Windows XP, and Vista style, depend on third party APIs to render the content of widgets, and these styles typically do not follow the palette. Because of this, assigning roles to a widget's palette is not guaranteed to change the appearance of the widget. Instead, you may choose to apply a \l styleSheet. You can refer to our Knowledge Base article \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more information. \warning Do not use this function in conjunction with \l{Qt Style Sheets}. When using style sheets, the palette of a widget can be customized using the "color", "background-color", "selection-color", "selection-background-color" and "alternate-background-color". \sa QApplication::palette(), QWidget::font() */ const QPalette &QWidget::palette() const { if (!isEnabled()) { data->pal.setCurrentColorGroup(QPalette::Disabled); } else if ((!isVisible() || isActiveWindow()) #if defined(Q_OS_WIN) && !defined(Q_WS_WINCE) && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this)) #endif ) { data->pal.setCurrentColorGroup(QPalette::Active); } else { #ifdef Q_WS_MAC extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp if (qt_mac_can_clickThrough(this)) data->pal.setCurrentColorGroup(QPalette::Active); else #endif data->pal.setCurrentColorGroup(QPalette::Inactive); } return data->pal; } void QWidget::setPalette(const QPalette &palette) { Q_D(QWidget); setAttribute(Qt::WA_SetPalette, palette.resolve() != 0); // Determine which palette is inherited from this widget's ancestors and // QApplication::palette, resolve this against \a palette (attributes from // the inherited palette are copied over this widget's palette). Then // propagate this palette to this widget's children. QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask); QPalette resolvedPalette = palette.resolve(naturalPalette); d->setPalette_helper(resolvedPalette); } /*! \internal Returns the palette that the widget \a w inherits from its ancestors and QApplication::palette. \a inheritedMask is the combination of the widget's ancestors palette request masks (i.e., which attributes from the parent widget's palette are implicitly imposed on this widget by the user). Note that this font does not take into account the palette set on \a w itself. */ QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const { Q_Q(const QWidget); QPalette naturalPalette = QApplication::palette(q); if (!q->testAttribute(Qt::WA_StyleSheet) && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation) #ifndef QT_NO_GRAPHICSVIEW || (extra && extra->proxyWidget) #endif //QT_NO_GRAPHICSVIEW )) { if (QWidget *p = q->parentWidget()) { if (!p->testAttribute(Qt::WA_StyleSheet)) { if (!naturalPalette.isCopyOf(QApplication::palette())) { QPalette inheritedPalette = p->palette(); inheritedPalette.resolve(inheritedMask); naturalPalette = inheritedPalette.resolve(naturalPalette); } else { naturalPalette = p->palette(); } } } #ifndef QT_NO_GRAPHICSVIEW else if (extra && extra->proxyWidget) { QPalette inheritedPalette = extra->proxyWidget->palette(); inheritedPalette.resolve(inheritedMask); naturalPalette = inheritedPalette.resolve(naturalPalette); } #endif //QT_NO_GRAPHICSVIEW } naturalPalette.resolve(0); return naturalPalette; } /*! \internal Determine which palette is inherited from this widget's ancestors and QApplication::palette, resolve this against this widget's palette (attributes from the inherited palette are copied over this widget's palette). Then propagate this palette to this widget's children. */ void QWidgetPrivate::resolvePalette() { QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask); QPalette resolvedPalette = data.pal.resolve(naturalPalette); setPalette_helper(resolvedPalette); } void QWidgetPrivate::setPalette_helper(const QPalette &palette) { Q_Q(QWidget); if (data.pal == palette && data.pal.resolve() == palette.resolve()) return; data.pal = palette; updateSystemBackground(); propagatePaletteChange(); updateIsOpaque(); q->update(); updateIsOpaque(); } /*! \property QWidget::font \brief the font currently set for the widget This property describes the widget's requested font. The font is used by the widget's style when rendering standard components, and is available as a means to ensure that custom widgets can maintain consistency with the native platform's look and feel. It's common that different platforms, or different styles, define different fonts for an application. When you assign a new font to a widget, the properties from this font are combined with the widget's default font to form the widget's final font. You can call fontInfo() to get a copy of the widget's final font. The final font is also used to initialize QPainter's font. The default depends on the system environment. QApplication maintains a system/theme font which serves as a default for all widgets. There may also be special font defaults for certain types of widgets. You can also define default fonts for widgets yourself by passing a custom font and the name of a widget to QApplication::setFont(). Finally, the font is matched against Qt's font database to find the best match. QWidget propagates explicit font properties from parent to child. If you change a specific property on a font and assign that font to a widget, that property will propagate to all the widget's children, overriding any system defaults for that property. Note that fonts by default don't propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation attribute is enabled. QWidget's font propagation is similar to its palette propagation. The current style, which is used to render the content of all standard Qt widgets, is free to choose to use the widget font, or in some cases, to ignore it (partially, or completely). In particular, certain styles like GTK style, Mac style, Windows XP, and Vista style, apply special modifications to the widget font to match the platform's native look and feel. Because of this, assigning properties to a widget's font is not guaranteed to change the appearance of the widget. Instead, you may choose to apply a \l styleSheet. \note If \l{Qt Style Sheets} are used on the same widget as setFont(), style sheets will take precedence if the settings conflict. \sa fontInfo(), fontMetrics() */ void QWidget::setFont(const QFont &font) { Q_D(QWidget); #ifndef QT_NO_STYLE_STYLESHEET const QStyleSheetStyle* style; if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) { style->saveWidgetFont(this, font); } #endif setAttribute(Qt::WA_SetFont, font.resolve() != 0); // Determine which font is inherited from this widget's ancestors and // QApplication::font, resolve this against \a font (attributes from the // inherited font are copied over). Then propagate this font to this // widget's children. QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask); QFont resolvedFont = font.resolve(naturalFont); d->setFont_helper(resolvedFont); } /* \internal Returns the font that the widget \a w inherits from its ancestors and QApplication::font. \a inheritedMask is the combination of the widget's ancestors font request masks (i.e., which attributes from the parent widget's font are implicitly imposed on this widget by the user). Note that this font does not take into account the font set on \a w itself. ### Stylesheet has a different font propagation mechanism. When a stylesheet is applied, fonts are not propagated anymore */ QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const { Q_Q(const QWidget); QFont naturalFont = QApplication::font(q); if (!q->testAttribute(Qt::WA_StyleSheet) && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation) #ifndef QT_NO_GRAPHICSVIEW || (extra && extra->proxyWidget) #endif //QT_NO_GRAPHICSVIEW )) { if (QWidget *p = q->parentWidget()) { if (!p->testAttribute(Qt::WA_StyleSheet)) { if (!naturalFont.isCopyOf(QApplication::font())) { QFont inheritedFont = p->font(); inheritedFont.resolve(inheritedMask); naturalFont = inheritedFont.resolve(naturalFont); } else { naturalFont = p->font(); } } } #ifndef QT_NO_GRAPHICSVIEW else if (extra && extra->proxyWidget) { QFont inheritedFont = extra->proxyWidget->font(); inheritedFont.resolve(inheritedMask); naturalFont = inheritedFont.resolve(naturalFont); } #endif //QT_NO_GRAPHICSVIEW } naturalFont.resolve(0); return naturalFont; } /*! \internal Determine which font is implicitly imposed on this widget by its ancestors and QApplication::font, resolve this against its own font (attributes from the implicit font are copied over). Then propagate this font to this widget's children. */ void QWidgetPrivate::resolveFont() { QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask); QFont resolvedFont = data.fnt.resolve(naturalFont); setFont_helper(resolvedFont); } /*! \internal Assign \a font to this widget, and propagate it to all children, except style sheet widgets (handled differently) and windows that don't enable window propagation. \a implicitMask is the union of all ancestor widgets' font request masks, and determines which attributes from this widget's font should propagate. */ void QWidgetPrivate::updateFont(const QFont &font) { Q_Q(QWidget); #ifndef QT_NO_STYLE_STYLESHEET const QStyleSheetStyle* cssStyle; cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0; #endif #ifdef QT3_SUPPORT QFont old = data.fnt; #endif data.fnt = QFont(font, q); #if defined(Q_WS_X11) // make sure the font set on this widget is associated with the correct screen data.fnt.x11SetScreen(xinfo.screen()); #endif // Combine new mask with natural mask and propagate to children. #ifndef QT_NO_GRAPHICSVIEW if (!q->parentWidget() && extra && extra->proxyWidget) { QGraphicsProxyWidget *p = extra->proxyWidget; inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve(); } else #endif //QT_NO_GRAPHICSVIEW if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) { inheritedFontResolveMask = 0; } uint newMask = data.fnt.resolve() | inheritedFontResolveMask; for (int i = 0; i < children.size(); ++i) { QWidget *w = qobject_cast<QWidget*>(children.at(i)); if (w) { if (0) { #ifndef QT_NO_STYLE_STYLESHEET } else if (w->testAttribute(Qt::WA_StyleSheet)) { // Style sheets follow a different font propagation scheme. if (cssStyle) cssStyle->updateStyleSheetFont(w); #endif } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) { // Propagate font changes. QWidgetPrivate *wd = w->d_func(); wd->inheritedFontResolveMask = newMask; wd->resolveFont(); } } } #ifndef QT_NO_STYLE_STYLESHEET if (cssStyle) { cssStyle->updateStyleSheetFont(q); } #endif QEvent e(QEvent::FontChange); QApplication::sendEvent(q, &e); #ifdef QT3_SUPPORT q->fontChange(old); #endif } void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction) { Q_Q(QWidget); if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft)) return; q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft)); if (!children.isEmpty()) { for (int i = 0; i < children.size(); ++i) { QWidget *w = qobject_cast<QWidget*>(children.at(i)); if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection)) w->d_func()->setLayoutDirection_helper(direction); } } QEvent e(QEvent::LayoutDirectionChange); QApplication::sendEvent(q, &e); } void QWidgetPrivate::resolveLayoutDirection() { Q_Q(const QWidget); if (!q->testAttribute(Qt::WA_SetLayoutDirection)) setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection()); } /*! \property QWidget::layoutDirection \brief the layout direction for this widget By default, this property is set to Qt::LeftToRight. When the layout direction is set on a widget, it will propagate to the widget's children, but not to a child that is a window and not to a child for which setLayoutDirection() has been explicitly called. Also, child widgets added \e after setLayoutDirection() has been called for the parent do not inherit the parent's layout direction. This method no longer affects text layout direction since Qt 4.7. \sa QApplication::layoutDirection */ void QWidget::setLayoutDirection(Qt::LayoutDirection direction) { Q_D(QWidget); if (direction == Qt::LayoutDirectionAuto) { unsetLayoutDirection(); return; } setAttribute(Qt::WA_SetLayoutDirection); d->setLayoutDirection_helper(direction); } Qt::LayoutDirection QWidget::layoutDirection() const { return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight; } void QWidget::unsetLayoutDirection() { Q_D(QWidget); setAttribute(Qt::WA_SetLayoutDirection, false); d->resolveLayoutDirection(); } /*! \fn QFontMetrics QWidget::fontMetrics() const Returns the font metrics for the widget's current font. Equivalent to QFontMetrics(widget->font()). \sa font(), fontInfo(), setFont() */ /*! \fn QFontInfo QWidget::fontInfo() const Returns the font info for the widget's current font. Equivalent to QFontInto(widget->font()). \sa font(), fontMetrics(), setFont() */ /*! \property QWidget::cursor \brief the cursor shape for this widget The mouse cursor will assume this shape when it's over this widget. See the \link Qt::CursorShape list of predefined cursor objects\endlink for a range of useful shapes. An editor widget might use an I-beam cursor: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6 If no cursor has been set, or after a call to unsetCursor(), the parent's cursor is used. By default, this property contains a cursor with the Qt::ArrowCursor shape. Some underlying window implementations will reset the cursor if it leaves a widget even if the mouse is grabbed. If you want to have a cursor set for all widgets, even when outside the window, consider QApplication::setOverrideCursor(). \sa QApplication::setOverrideCursor() */ #ifndef QT_NO_CURSOR QCursor QWidget::cursor() const { Q_D(const QWidget); if (testAttribute(Qt::WA_SetCursor)) return (d->extra && d->extra->curs) ? *d->extra->curs : QCursor(Qt::ArrowCursor); if (isWindow() || !parentWidget()) return QCursor(Qt::ArrowCursor); return parentWidget()->cursor(); } void QWidget::setCursor(const QCursor &cursor) { Q_D(QWidget); // On Mac we must set the cursor even if it is the ArrowCursor. #if !defined(Q_WS_MAC) && !defined(Q_WS_QWS) if (cursor.shape() != Qt::ArrowCursor || (d->extra && d->extra->curs)) #endif { d->createExtra(); QCursor *newCursor = new QCursor(cursor); delete d->extra->curs; d->extra->curs = newCursor; } setAttribute(Qt::WA_SetCursor); d->setCursor_sys(cursor); QEvent event(QEvent::CursorChange); QApplication::sendEvent(this, &event); } void QWidget::unsetCursor() { Q_D(QWidget); if (d->extra) { delete d->extra->curs; d->extra->curs = 0; } if (!isWindow()) setAttribute(Qt::WA_SetCursor, false); d->unsetCursor_sys(); QEvent event(QEvent::CursorChange); QApplication::sendEvent(this, &event); } #endif /*! \enum QWidget::RenderFlag This enum describes how to render the widget when calling QWidget::render(). \value DrawWindowBackground If you enable this option, the widget's background is rendered into the target even if autoFillBackground is not set. By default, this option is enabled. \value DrawChildren If you enable this option, the widget's children are rendered recursively into the target. By default, this option is enabled. \value IgnoreMask If you enable this option, the widget's QWidget::mask() is ignored when rendering into the target. By default, this option is disabled. \since 4.3 */ /*! \since 4.3 Renders the \a sourceRegion of this widget into the \a target using \a renderFlags to determine how to render. Rendering starts at \a targetOffset in the \a target. For example: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7 If \a sourceRegion is a null region, this function will use QWidget::rect() as the region, i.e. the entire widget. Ensure that you call QPainter::end() for the \a target device's active painter (if any) before rendering. For example: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer() or QGLWidget::renderPixmap() instead. */ void QWidget::render(QPaintDevice *target, const QPoint &targetOffset, const QRegion &sourceRegion, RenderFlags renderFlags) { d_func()->render(target, targetOffset, sourceRegion, renderFlags, false); } /*! \overload Renders the widget into the \a painter's QPainter::device(). Transformations and settings applied to the \a painter will be used when rendering. \note The \a painter must be active. On Mac OS X the widget will be rendered into a QPixmap and then drawn by the \a painter. \sa QPainter::device() */ void QWidget::render(QPainter *painter, const QPoint &targetOffset, const QRegion &sourceRegion, RenderFlags renderFlags) { if (!painter) { qWarning("QWidget::render: Null pointer to painter"); return; } if (!painter->isActive()) { qWarning("QWidget::render: Cannot render with an inactive painter"); return; } const qreal opacity = painter->opacity(); if (qFuzzyIsNull(opacity)) return; // Fully transparent. Q_D(QWidget); const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter; const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags) : sourceRegion; if (toBePainted.isEmpty()) return; if (!d->extra) d->createExtra(); d->extra->inRenderWithPainter = true; #ifdef Q_WS_MAC d->render_helper(painter, targetOffset, toBePainted, renderFlags); #else QPaintEngine *engine = painter->paintEngine(); Q_ASSERT(engine); QPaintEnginePrivate *enginePriv = engine->d_func(); Q_ASSERT(enginePriv); QPaintDevice *target = engine->paintDevice(); Q_ASSERT(target); // Render via a pixmap when dealing with non-opaque painters or printers. if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) { d->render_helper(painter, targetOffset, toBePainted, renderFlags); d->extra->inRenderWithPainter = false; return; } // Set new shared painter. QPainter *oldPainter = d->sharedPainter(); d->setSharedPainter(painter); // Save current system clip, viewport and transform, const QTransform oldTransform = enginePriv->systemTransform; const QRegion oldSystemClip = enginePriv->systemClip; const QRegion oldSystemViewport = enginePriv->systemViewport; // This ensures that all painting triggered by render() is clipped to the current engine clip. if (painter->hasClipping()) { const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion()); enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip); } else { enginePriv->setSystemViewport(oldSystemClip); } render(target, targetOffset, toBePainted, renderFlags); // Restore system clip, viewport and transform. enginePriv->systemClip = oldSystemClip; enginePriv->setSystemViewport(oldSystemViewport); enginePriv->setSystemTransform(oldTransform); // Restore shared painter. d->setSharedPainter(oldPainter); #endif d->extra->inRenderWithPainter = false; } /*! \brief The graphicsEffect function returns a pointer to the widget's graphics effect. If the widget has no graphics effect, 0 is returned. \since 4.6 \sa setGraphicsEffect() */ #ifndef QT_NO_GRAPHICSEFFECT QGraphicsEffect *QWidget::graphicsEffect() const { Q_D(const QWidget); return d->graphicsEffect; } #endif //QT_NO_GRAPHICSEFFECT /*! \brief The setGraphicsEffect function is for setting the widget's graphics effect. Sets \a effect as the widget's effect. If there already is an effect installed on this widget, QWidget will delete the existing effect before installing the new \a effect. If \a effect is the installed on a different widget, setGraphicsEffect() will remove the effect from the widget and install it on this widget. QWidget takes ownership of \a effect. \note This function will apply the effect on itself and all its children. \since 4.6 \sa graphicsEffect() */ #ifndef QT_NO_GRAPHICSEFFECT void QWidget::setGraphicsEffect(QGraphicsEffect *effect) { Q_D(QWidget); if (d->graphicsEffect == effect) return; if (d->graphicsEffect) { d->invalidateBuffer(rect()); delete d->graphicsEffect; d->graphicsEffect = 0; } if (effect) { // Set new effect. QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this); QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced); d->graphicsEffect = effect; effect->d_func()->setGraphicsEffectSource(source); update(); } d->updateIsOpaque(); } #endif //QT_NO_GRAPHICSEFFECT bool QWidgetPrivate::isAboutToShow() const { if (data.in_show) return true; Q_Q(const QWidget); if (q->isHidden()) return false; // The widget will be shown if any of its ancestors are about to show. QWidget *parent = q->parentWidget(); return parent ? parent->d_func()->isAboutToShow() : false; } QRegion QWidgetPrivate::prepareToRender(const QRegion &region, QWidget::RenderFlags renderFlags) { Q_Q(QWidget); const bool isVisible = q->isVisible(); // Make sure the widget is laid out correctly. if (!isVisible && !isAboutToShow()) { QWidget *topLevel = q->window(); (void)topLevel->d_func()->topData(); // Make sure we at least have top-data. topLevel->ensurePolished(); // Invalidate the layout of hidden ancestors (incl. myself) and pretend // they're not explicitly hidden. QWidget *widget = q; QWidgetList hiddenWidgets; while (widget) { if (widget->isHidden()) { widget->setAttribute(Qt::WA_WState_Hidden, false); hiddenWidgets.append(widget); if (!widget->isWindow() && widget->parentWidget()->d_func()->layout) widget->d_func()->updateGeometry_helper(true); } widget = widget->parentWidget(); } // Activate top-level layout. if (topLevel->d_func()->layout) topLevel->d_func()->layout->activate(); // Adjust size if necessary. QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData(); if (topLevelExtra && !topLevelExtra->sizeAdjusted && !topLevel->testAttribute(Qt::WA_Resized)) { topLevel->adjustSize(); topLevel->setAttribute(Qt::WA_Resized, false); } // Activate child layouts. topLevel->d_func()->activateChildLayoutsRecursively(); // We're not cheating with WA_WState_Hidden anymore. for (int i = 0; i < hiddenWidgets.size(); ++i) { QWidget *widget = hiddenWidgets.at(i); widget->setAttribute(Qt::WA_WState_Hidden); if (!widget->isWindow() && widget->parentWidget()->d_func()->layout) widget->parentWidget()->d_func()->layout->invalidate(); } } else if (isVisible) { q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true); } // Calculate the region to be painted. QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect()); if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask) toBePainted &= extra->mask; return toBePainted; } void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted, QWidget::RenderFlags renderFlags) { Q_ASSERT(painter); Q_ASSERT(!toBePainted.isEmpty()); Q_Q(QWidget); #ifndef Q_WS_MAC const QTransform originalTransform = painter->worldTransform(); const bool useDeviceCoordinates = originalTransform.isScaling(); if (!useDeviceCoordinates) { #endif // Render via a pixmap. const QRect rect = toBePainted.boundingRect(); const QSize size = rect.size(); if (size.isNull()) return; QPixmap pixmap(size); if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque) pixmap.fill(Qt::transparent); q->render(&pixmap, QPoint(), toBePainted, renderFlags); const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform); painter->setRenderHints(QPainter::SmoothPixmapTransform, true); painter->drawPixmap(targetOffset, pixmap); if (restore) painter->setRenderHints(QPainter::SmoothPixmapTransform, false); #ifndef Q_WS_MAC } else { // Render via a pixmap in device coordinates (to avoid pixmap scaling). QTransform transform = originalTransform; transform.translate(targetOffset.x(), targetOffset.y()); QPaintDevice *device = painter->device(); Q_ASSERT(device); // Calculate device rect. const QRectF rect(toBePainted.boundingRect()); QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect(); deviceRect &= QRect(0, 0, device->width(), device->height()); QPixmap pixmap(deviceRect.size()); pixmap.fill(Qt::transparent); // Create a pixmap device coordinate painter. QPainter pixmapPainter(&pixmap); pixmapPainter.setRenderHints(painter->renderHints()); transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y()); pixmapPainter.setTransform(transform); q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags); pixmapPainter.end(); // And then draw the pixmap. painter->setTransform(QTransform()); painter->drawPixmap(deviceRect.topLeft(), pixmap); painter->setTransform(originalTransform); } #endif } void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags, QPainter *sharedPainter, QWidgetBackingStore *backingStore) { if (rgn.isEmpty()) return; #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA) if (qt_mac_clearDirtyOnWidgetInsideDrawWidget) dirtyOnWidget = QRegion(); // We disable the rendering of QToolBar in the backingStore if // it's supposed to be in the unified toolbar on Mac OS X. if (backingStore && isInUnifiedToolbar) return; #endif // Q_WS_MAC && QT_MAC_USE_COCOA Q_Q(QWidget); #ifndef QT_NO_GRAPHICSEFFECT if (graphicsEffect && graphicsEffect->isEnabled()) { QGraphicsEffectSource *source = graphicsEffect->d_func()->source; QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *> (source->d_func()); if (!sourced->context) { QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore); sourced->context = &context; if (!sharedPainter) { QPaintEngine *paintEngine = pdev->paintEngine(); paintEngine->d_func()->systemClip = rgn.translated(offset); QPainter p(pdev); p.translate(offset); context.painter = &p; graphicsEffect->draw(&p); paintEngine->d_func()->systemClip = QRegion(); } else { context.painter = sharedPainter; if (sharedPainter->worldTransform() != sourced->lastEffectTransform) { sourced->invalidateCache(); sourced->lastEffectTransform = sharedPainter->worldTransform(); } sharedPainter->save(); sharedPainter->translate(offset); graphicsEffect->draw(sharedPainter); sharedPainter->restore(); } sourced->context = 0; return; } } #endif //QT_NO_GRAFFICSEFFECT const bool asRoot = flags & DrawAsRoot; const bool alsoOnScreen = flags & DrawPaintOnScreen; const bool recursive = flags & DrawRecursive; const bool alsoInvisible = flags & DrawInvisible; Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true); QRegion toBePainted(rgn); if (asRoot && !alsoInvisible) toBePainted &= clipRect(); //(rgn & visibleRegion()); if (!(flags & DontSubtractOpaqueChildren)) subtractOpaqueChildren(toBePainted, q->rect()); if (!toBePainted.isEmpty()) { bool onScreen = paintOnScreen(); if (!onScreen || alsoOnScreen) { //update the "in paint event" flag if (q->testAttribute(Qt::WA_WState_InPaintEvent)) qWarning("QWidget::repaint: Recursive repaint detected"); q->setAttribute(Qt::WA_WState_InPaintEvent); //clip away the new area #ifndef QT_NO_PAINT_DEBUG bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted); #endif QPaintEngine *paintEngine = pdev->paintEngine(); if (paintEngine) { setRedirected(pdev, -offset); #ifdef Q_WS_MAC // (Alien support) Special case for Mac when redirecting: If the paint device // is of the Widget type we need to set WA_WState_InPaintEvent since painting // outside the paint event is not supported on QWidgets. The attributeis // restored further down. if (pdev->devType() == QInternal::Widget) static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent); #endif if (sharedPainter) paintEngine->d_func()->systemClip = toBePainted; else paintEngine->d_func()->systemRect = q->data->crect; //paint the background if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground)) && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) { QPainter p(q); paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0); } if (!sharedPainter) paintEngine->d_func()->systemClip = toBePainted.translated(offset); if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) { QPainter p(q); QColor tint = q->palette().window().color(); tint.setAlphaF(qreal(.6)); p.fillRect(toBePainted.boundingRect(), tint); } } #if 0 qDebug() << "painting" << q << "opaque ==" << isOpaque(); qDebug() << "clipping to" << toBePainted << "location == " << offset << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size()); #endif //actually send the paint event QPaintEvent e(toBePainted); QCoreApplication::sendSpontaneousEvent(q, &e); #if !defined(Q_WS_QWS) && !defined(Q_WS_QPA) if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow())) backingStore->markDirtyOnScreen(toBePainted, q, offset); #endif //restore if (paintEngine) { #ifdef Q_WS_MAC if (pdev->devType() == QInternal::Widget) static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false); #endif restoreRedirected(); if (!sharedPainter) paintEngine->d_func()->systemRect = QRect(); else paintEngine->d_func()->currentClipWidget = 0; paintEngine->d_func()->systemClip = QRegion(); } q->setAttribute(Qt::WA_WState_InPaintEvent, false); if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent)) qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent"); if (paintEngine && paintEngine->autoDestruct()) { delete paintEngine; } #ifndef QT_NO_PAINT_DEBUG if (flushed) QWidgetBackingStore::unflushPaint(q, toBePainted); #endif } else if (q->isWindow()) { QPaintEngine *engine = pdev->paintEngine(); if (engine) { QPainter p(pdev); p.setClipRegion(toBePainted); const QBrush bg = q->palette().brush(QPalette::Window); if (bg.style() == Qt::TexturePattern) p.drawTiledPixmap(q->rect(), bg.texture()); else p.fillRect(q->rect(), bg); if (engine->autoDestruct()) delete engine; } } } if (recursive && !children.isEmpty()) { paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot #ifdef Q_BACKINGSTORE_SUBSURFACES , q->windowSurface() #endif , sharedPainter, backingStore); } } void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset, const QRegion &sourceRegion, QWidget::RenderFlags renderFlags, bool readyToRender) { if (!target) { qWarning("QWidget::render: null pointer to paint device"); return; } const bool inRenderWithPainter = extra && extra->inRenderWithPainter; QRegion paintRegion = !inRenderWithPainter && !readyToRender ? prepareToRender(sourceRegion, renderFlags) : sourceRegion; if (paintRegion.isEmpty()) return; #ifndef Q_WS_MAC QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0; // Use the target's shared painter if set (typically set when doing // "other->render(widget);" in the widget's paintEvent. if (target->devType() == QInternal::Widget) { QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func(); if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) { QPainter *targetPainter = targetPrivate->sharedPainter(); if (targetPainter && targetPainter->isActive()) setSharedPainter(targetPainter); } } #endif // Use the target's redirected device if set and adjust offset and paint // region accordingly. This is typically the case when people call render // from the paintEvent. QPoint offset = targetOffset; offset -= paintRegion.boundingRect().topLeft(); QPoint redirectionOffset; QPaintDevice *redirected = 0; if (target->devType() == QInternal::Widget) redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset); if (!redirected) redirected = QPainter::redirected(target, &redirectionOffset); if (redirected) { target = redirected; offset -= redirectionOffset; } if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp). if (QPaintEngine *targetEngine = target->paintEngine()) { const QRegion targetSystemClip = targetEngine->systemClip(); if (!targetSystemClip.isEmpty()) paintRegion &= targetSystemClip.translated(-offset); } } // Set backingstore flags. int flags = DrawPaintOnScreen | DrawInvisible; if (renderFlags & QWidget::DrawWindowBackground) flags |= DrawAsRoot; if (renderFlags & QWidget::DrawChildren) flags |= DrawRecursive; else flags |= DontSubtractOpaqueChildren; #if defined(Q_WS_QWS) || defined(Q_WS_QPA) flags |= DontSetCompositionMode; #endif if (target->devType() == QInternal::Printer) { QPainter p(target); render_helper(&p, targetOffset, paintRegion, renderFlags); return; } #ifndef Q_WS_MAC // Render via backingstore. drawWidget(target, paintRegion, offset, flags, sharedPainter()); // Restore shared painter. if (oldSharedPainter) setSharedPainter(oldSharedPainter); #else // Render via backingstore (no shared painter). drawWidget(target, paintRegion, offset, flags, 0); #endif } void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn, const QPoint &offset, int flags #ifdef Q_BACKINGSTORE_SUBSURFACES , const QWindowSurface *currentSurface #endif , QPainter *sharedPainter, QWidgetBackingStore *backingStore) { QWidget *w = 0; QRect boundingRect; bool dirtyBoundingRect = true; const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren); const bool excludeNativeChildren = (flags & DontDrawNativeChildren); do { QWidget *x = qobject_cast<QWidget*>(siblings.at(index)); if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow() && !(excludeNativeChildren && x->internalWinId())) { if (dirtyBoundingRect) { boundingRect = rgn.boundingRect(); dirtyBoundingRect = false; } if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) { #ifdef Q_BACKINGSTORE_SUBSURFACES if (x->windowSurface() == currentSurface) #endif { w = x; break; } } } --index; } while (index >= 0); if (!w) return; QWidgetPrivate *wd = w->d_func(); const QPoint widgetPos(w->data->crect.topLeft()); const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect; if (index > 0) { QRegion wr(rgn); if (wd->isOpaque) wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect; paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags #ifdef Q_BACKINGSTORE_SUBSURFACES , currentSurface #endif , sharedPainter, backingStore); } if (w->updatesEnabled() #ifndef QT_NO_GRAPHICSVIEW && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget) #endif //QT_NO_GRAPHICSVIEW ) { QRegion wRegion(rgn); wRegion &= wd->effectiveRectFor(w->data->crect); wRegion.translate(-widgetPos); if (hasMask) wRegion &= wd->extra->mask; wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore); } } #ifndef QT_NO_GRAPHICSEFFECT QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const { if (system != Qt::DeviceCoordinates) return m_widget->rect(); if (!context) { // Device coordinates without context not yet supported. qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context"); return QRectF(); } return context->painter->worldTransform().mapRect(m_widget->rect()); } void QWidgetEffectSourcePrivate::draw(QPainter *painter) { if (!context || context->painter != painter) { m_widget->render(painter); return; } // The region saved in the context is neither clipped to the rect // nor the mask, so we have to clip it here before calling drawWidget. QRegion toBePainted = context->rgn; toBePainted &= m_widget->rect(); QWidgetPrivate *wd = qt_widget_private(m_widget); if (wd->extra && wd->extra->hasMask) toBePainted &= wd->extra->mask; wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags, context->sharedPainter, context->backingStore); } QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset, QGraphicsEffect::PixmapPadMode mode) const { const bool deviceCoordinates = (system == Qt::DeviceCoordinates); if (!context && deviceCoordinates) { // Device coordinates without context not yet supported. qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context"); return QPixmap(); } QPoint pixmapOffset; QRectF sourceRect = m_widget->rect(); if (deviceCoordinates) { const QTransform &painterTransform = context->painter->worldTransform(); sourceRect = painterTransform.mapRect(sourceRect); pixmapOffset = painterTransform.map(pixmapOffset); } QRect effectRect; if (mode == QGraphicsEffect::PadToEffectiveBoundingRect) effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect(); else if (mode == QGraphicsEffect::PadToTransparentBorder) effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect(); else effectRect = sourceRect.toAlignedRect(); if (offset) *offset = effectRect.topLeft(); pixmapOffset -= effectRect.topLeft(); QPixmap pixmap(effectRect.size()); pixmap.fill(Qt::transparent); m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren); return pixmap; } #endif //QT_NO_GRAPHICSEFFECT #ifndef QT_NO_GRAPHICSVIEW /*! \internal Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this widget and its ancestors. The search starts at \a origin (inclusive). If successful, the function returns the proxy that embeds the widget, or 0 if no embedded widget was found. */ QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin) { if (origin) { QWExtra *extra = origin->d_func()->extra; if (extra && extra->proxyWidget) return extra->proxyWidget; return nearestGraphicsProxyWidget(origin->parentWidget()); } return 0; } #endif /*! \property QWidget::locale \brief the widget's locale \since 4.3 As long as no special locale has been set, this is either the parent's locale or (if this widget is a top level widget), the default locale. If the widget displays dates or numbers, these should be formatted using the widget's locale. \sa QLocale QLocale::setDefault() */ void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate) { Q_Q(QWidget); if (locale == loc && !forceUpdate) return; locale = loc; if (!children.isEmpty()) { for (int i = 0; i < children.size(); ++i) { QWidget *w = qobject_cast<QWidget*>(children.at(i)); if (!w) continue; if (w->testAttribute(Qt::WA_SetLocale)) continue; if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation)) continue; w->d_func()->setLocale_helper(loc, forceUpdate); } } QEvent e(QEvent::LocaleChange); QApplication::sendEvent(q, &e); } void QWidget::setLocale(const QLocale &locale) { Q_D(QWidget); setAttribute(Qt::WA_SetLocale); d->setLocale_helper(locale); } QLocale QWidget::locale() const { Q_D(const QWidget); return d->locale; } void QWidgetPrivate::resolveLocale() { Q_Q(const QWidget); if (!q->testAttribute(Qt::WA_SetLocale)) { setLocale_helper(q->isWindow() ? QLocale() : q->parentWidget()->locale()); } } void QWidget::unsetLocale() { Q_D(QWidget); setAttribute(Qt::WA_SetLocale, false); d->resolveLocale(); } static QString constructWindowTitleFromFilePath(const QString &filePath) { QFileInfo fi(filePath); QString windowTitle = fi.fileName() + QLatin1String("[*]"); #ifndef Q_WS_MAC QString appName = QApplication::applicationName(); if (!appName.isEmpty()) windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName; #endif return windowTitle; } /*! \property QWidget::windowTitle \brief the window title (caption) This property only makes sense for top-level widgets, such as windows and dialogs. If no caption has been set, the title is based of the \l windowFilePath. If neither of these is set, then the title is an empty string. If you use the \l windowModified mechanism, the window title must contain a "[*]" placeholder, which indicates where the '*' should appear. Normally, it should appear right after the file name (e.g., "document1.txt[*] - Text Editor"). If the \l windowModified property is false (the default), the placeholder is simply removed. \sa windowIcon, windowIconText, windowModified, windowFilePath */ QString QWidget::windowTitle() const { Q_D(const QWidget); if (d->extra && d->extra->topextra) { if (!d->extra->topextra->caption.isEmpty()) return d->extra->topextra->caption; if (!d->extra->topextra->filePath.isEmpty()) return constructWindowTitleFromFilePath(d->extra->topextra->filePath); } return QString(); } /*! Returns a modified window title with the [*] place holder replaced according to the rules described in QWidget::setWindowTitle This function assumes that "[*]" can be quoted by another "[*]", so it will replace two place holders by one and a single last one by either "*" or nothing depending on the modified flag. \internal */ QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget) { Q_ASSERT(widget); #ifdef QT_EVAL extern QString qt_eval_adapt_window_title(const QString &title); QString cap = qt_eval_adapt_window_title(title); #else QString cap = title; #endif if (cap.isEmpty()) return cap; QLatin1String placeHolder("[*]"); int placeHolderLength = 3; // QLatin1String doesn't have length() int index = cap.indexOf(placeHolder); // here the magic begins while (index != -1) { index += placeHolderLength; int count = 1; while (cap.indexOf(placeHolder, index) == index) { ++count; index += placeHolderLength; } if (count%2) { // odd number of [*] -> replace last one int lastIndex = cap.lastIndexOf(placeHolder, index - 1); if (widget->isWindowModified() && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget)) cap.replace(lastIndex, 3, QWidget::tr("*")); else cap.remove(lastIndex, 3); } index = cap.indexOf(placeHolder, index); } cap.replace(QLatin1String("[*][*]"), placeHolder); return cap; } void QWidgetPrivate::setWindowTitle_helper(const QString &title) { Q_Q(QWidget); if (q->testAttribute(Qt::WA_WState_Created)) setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q)); } void QWidgetPrivate::setWindowIconText_helper(const QString &title) { Q_Q(QWidget); if (q->testAttribute(Qt::WA_WState_Created)) setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q)); } void QWidget::setWindowIconText(const QString &iconText) { if (QWidget::windowIconText() == iconText) return; Q_D(QWidget); d->topData()->iconText = iconText; d->setWindowIconText_helper(iconText); QEvent e(QEvent::IconTextChange); QApplication::sendEvent(this, &e); } void QWidget::setWindowTitle(const QString &title) { if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull()) return; Q_D(QWidget); d->topData()->caption = title; d->setWindowTitle_helper(title); QEvent e(QEvent::WindowTitleChange); QApplication::sendEvent(this, &e); } /*! \property QWidget::windowIcon \brief the widget's icon This property only makes sense for windows. If no icon has been set, windowIcon() returns the application icon (QApplication::windowIcon()). \sa windowIconText, windowTitle */ QIcon QWidget::windowIcon() const { const QWidget *w = this; while (w) { const QWidgetPrivate *d = w->d_func(); if (d->extra && d->extra->topextra && d->extra->topextra->icon) return *d->extra->topextra->icon; w = w->parentWidget(); } return QApplication::windowIcon(); } void QWidgetPrivate::setWindowIcon_helper() { QEvent e(QEvent::WindowIconChange); QApplication::sendEvent(q_func(), &e); for (int i = 0; i < children.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(children.at(i)); if (w && !w->isWindow()) QApplication::sendEvent(w, &e); } } void QWidget::setWindowIcon(const QIcon &icon) { Q_D(QWidget); setAttribute(Qt::WA_SetWindowIcon, !icon.isNull()); d->createTLExtra(); if (!d->extra->topextra->icon) d->extra->topextra->icon = new QIcon(); *d->extra->topextra->icon = icon; delete d->extra->topextra->iconPixmap; d->extra->topextra->iconPixmap = 0; d->setWindowIcon_sys(); d->setWindowIcon_helper(); } /*! \property QWidget::windowIconText \brief the widget's icon text This property only makes sense for windows. If no icon text has been set, this functions returns an empty string. \sa windowIcon, windowTitle */ QString QWidget::windowIconText() const { Q_D(const QWidget); return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString(); } /*! \property QWidget::windowFilePath \since 4.4 \brief the file path associated with a widget This property only makes sense for windows. It associates a file path with a window. If you set the file path, but have not set the window title, Qt sets the window title to contain a string created using the following components. On Mac OS X: \list \o The file name of the specified path, obtained using QFileInfo::fileName(). \endlist On Windows and X11: \list \o The file name of the specified path, obtained using QFileInfo::fileName(). \o An optional \c{*} character, if the \l windowModified property is set. \o The \c{0x2014} unicode character, padded either side by spaces. \o The application name, obtained from the application's \l{QCoreApplication::}{applicationName} property. \endlist If the window title is set at any point, then the window title takes precedence and will be shown instead of the file path string. Additionally, on Mac OS X, this has an added benefit that it sets the \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon} for the window, assuming that the file path exists. If no file path is set, this property contains an empty string. By default, this property contains an empty string. \sa windowTitle, windowIcon */ QString QWidget::windowFilePath() const { Q_D(const QWidget); return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString(); } void QWidget::setWindowFilePath(const QString &filePath) { if (filePath == windowFilePath()) return; Q_D(QWidget); d->createTLExtra(); d->extra->topextra->filePath = filePath; d->setWindowFilePath_helper(filePath); } void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath) { if (extra->topextra && extra->topextra->caption.isEmpty()) { #ifdef Q_WS_MAC setWindowTitle_helper(QFileInfo(filePath).fileName()); #else Q_Q(QWidget); Q_UNUSED(filePath); setWindowTitle_helper(q->windowTitle()); #endif } #ifdef Q_WS_MAC setWindowFilePath_sys(filePath); #endif } /*! Returns the window's role, or an empty string. \sa windowIcon, windowTitle */ QString QWidget::windowRole() const { Q_D(const QWidget); return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString(); } /*! Sets the window's role to \a role. This only makes sense for windows on X11. */ void QWidget::setWindowRole(const QString &role) { #if defined(Q_WS_X11) Q_D(QWidget); d->topData()->role = role; d->setWindowRole(); #else Q_UNUSED(role) #endif } /*! \property QWidget::mouseTracking \brief whether mouse tracking is enabled for the widget If mouse tracking is disabled (the default), the widget only receives mouse move events when at least one mouse button is pressed while the mouse is being moved. If mouse tracking is enabled, the widget receives mouse move events even if no buttons are pressed. \sa mouseMoveEvent() */ /*! Sets the widget's focus proxy to widget \a w. If \a w is 0, the function resets this widget to have no focus proxy. Some widgets can "have focus", but create a child widget, such as QLineEdit, to actually handle the focus. In this case, the widget can set the line edit to be its focus proxy. setFocusProxy() sets the widget which will actually get focus when "this widget" gets it. If there is a focus proxy, setFocus() and hasFocus() operate on the focus proxy. \sa focusProxy() */ void QWidget::setFocusProxy(QWidget * w) { Q_D(QWidget); if (!w && !d->extra) return; for (QWidget* fp = w; fp; fp = fp->focusProxy()) { if (fp == this) { qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData()); return; } } d->createExtra(); d->extra->focus_proxy = w; } /*! Returns the focus proxy, or 0 if there is no focus proxy. \sa setFocusProxy() */ QWidget * QWidget::focusProxy() const { Q_D(const QWidget); return d->extra ? (QWidget *)d->extra->focus_proxy : 0; } /*! \property QWidget::focus \brief whether this widget (or its focus proxy) has the keyboard input focus By default, this property is false. \note Obtaining the value of this property for a widget is effectively equivalent to checking whether QApplication::focusWidget() refers to the widget. \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget() */ bool QWidget::hasFocus() const { const QWidget* w = this; while (w->d_func()->extra && w->d_func()->extra->focus_proxy) w = w->d_func()->extra->focus_proxy; if (QWidget *window = w->window()) { #ifndef QT_NO_GRAPHICSVIEW QWExtra *e = window->d_func()->extra; if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w) return true; #endif } return (QApplication::focusWidget() == w); } /*! Gives the keyboard input focus to this widget (or its focus proxy) if this widget or one of its parents is the \link isActiveWindow() active window\endlink. The \a reason argument will be passed into any focus event sent from this function, it is used to give an explanation of what caused the widget to get focus. If the window is not active, the widget will be given the focus when the window becomes active. First, a focus out event is sent to the focus widget (if any) to tell it that it is about to lose the focus. Then a focus in event is sent to this widget to tell it that it just received the focus. (Nothing happens if the focus in and focus out widgets are the same.) \note On embedded platforms, setFocus() will not cause an input panel to be opened by the input method. If you want this to happen, you have to send a QEvent::RequestSoftwareInputPanel event to the widget yourself. setFocus() gives focus to a widget regardless of its focus policy, but does not clear any keyboard grab (see grabKeyboard()). Be aware that if the widget is hidden, it will not accept focus until it is shown. \warning If you call setFocus() in a function which may itself be called from focusOutEvent() or focusInEvent(), you may get an infinite recursion. \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(), setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(), grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel */ void QWidget::setFocus(Qt::FocusReason reason) { if (!isEnabled()) return; QWidget *f = this; while (f->d_func()->extra && f->d_func()->extra->focus_proxy) f = f->d_func()->extra->focus_proxy; if (QApplication::focusWidget() == f #if defined(Q_WS_WIN) && GetFocus() == f->internalWinId() #endif ) return; #ifndef QT_NO_GRAPHICSVIEW QWidget *previousProxyFocus = 0; if (QWExtra *topData = window()->d_func()->extra) { if (topData->proxyWidget && topData->proxyWidget->hasFocus()) { previousProxyFocus = topData->proxyWidget->widget()->focusWidget(); if (previousProxyFocus && previousProxyFocus->focusProxy()) previousProxyFocus = previousProxyFocus->focusProxy(); if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus) return; } } #endif QWidget *w = f; if (isHidden()) { while (w && w->isHidden()) { w->d_func()->focus_child = f; w = w->isWindow() ? 0 : w->parentWidget(); } } else { while (w) { w->d_func()->focus_child = f; w = w->isWindow() ? 0 : w->parentWidget(); } } #ifndef QT_NO_GRAPHICSVIEW // Update proxy state if (QWExtra *topData = window()->d_func()->extra) { if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) { topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1; topData->proxyWidget->setFocus(reason); topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0; } } #endif if (f->isActiveWindow()) { QApplicationPrivate::setFocusWidget(f, reason); #ifndef QT_NO_ACCESSIBILITY # ifdef Q_OS_WIN // The negation of the condition in setFocus_sys if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId())) //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows # endif # ifdef Q_OS_UNIX // menus update the focus manually and this would create bogus events if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem"))) # endif QAccessible::updateAccessibility(f, 0, QAccessible::Focus); #endif #ifndef QT_NO_GRAPHICSVIEW if (QWExtra *topData = window()->d_func()->extra) { if (topData->proxyWidget) { if (previousProxyFocus && previousProxyFocus != f) { // Send event to self QFocusEvent event(QEvent::FocusOut, reason); QPointer<QWidget> that = previousProxyFocus; QApplication::sendEvent(previousProxyFocus, &event); if (that) QApplication::sendEvent(that->style(), &event); } if (!isHidden()) { #ifndef QT_NO_GRAPHICSVIEW // Update proxy state if (QWExtra *topData = window()->d_func()->extra) if (topData->proxyWidget && topData->proxyWidget->hasFocus()) topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget(); #endif // Send event to self QFocusEvent event(QEvent::FocusIn, reason); QPointer<QWidget> that = f; QApplication::sendEvent(f, &event); if (that) QApplication::sendEvent(that->style(), &event); } } } #endif } } /*! \fn void QWidget::setFocus() \overload Gives the keyboard input focus to this widget (or its focus proxy) if this widget or one of its parents is the \l{isActiveWindow()}{active window}. */ /*! Takes keyboard input focus from the widget. If the widget has active focus, a \link focusOutEvent() focus out event\endlink is sent to this widget to tell it that it is about to lose the focus. This widget must enable focus setting in order to get the keyboard input focus, i.e. it must call setFocusPolicy(). \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(), setFocusPolicy(), QApplication::focusWidget() */ void QWidget::clearFocus() { QWidget *w = this; while (w) { if (w->d_func()->focus_child == this) w->d_func()->focus_child = 0; w = w->parentWidget(); } #ifndef QT_NO_GRAPHICSVIEW QWExtra *topData = d_func()->extra; if (topData && topData->proxyWidget) topData->proxyWidget->clearFocus(); #endif if (hasFocus()) { // Update proxy state QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason); #if defined(Q_WS_WIN) if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId()) SetFocus(0); else #endif { #ifndef QT_NO_ACCESSIBILITY QAccessible::updateAccessibility(this, 0, QAccessible::Focus); #endif } } } /*! \fn bool QWidget::focusNextChild() Finds a new widget to give the keyboard focus to, as appropriate for \key Tab, and returns true if it can find a new widget, or false if it can't. \sa focusPreviousChild() */ /*! \fn bool QWidget::focusPreviousChild() Finds a new widget to give the keyboard focus to, as appropriate for \key Shift+Tab, and returns true if it can find a new widget, or false if it can't. \sa focusNextChild() */ /*! Finds a new widget to give the keyboard focus to, as appropriate for Tab and Shift+Tab, and returns true if it can find a new widget, or false if it can't. If \a next is true, this function searches forward, if \a next is false, it searches backward. Sometimes, you will want to reimplement this function. For example, a web browser might reimplement it to move its "current active link" forward or backward, and call focusNextPrevChild() only when it reaches the last or first link on the "page". Child widgets call focusNextPrevChild() on their parent widgets, but only the window that contains the child widgets decides where to redirect focus. By reimplementing this function for an object, you thus gain control of focus traversal for all child widgets. \sa focusNextChild(), focusPreviousChild() */ bool QWidget::focusNextPrevChild(bool next) { Q_D(QWidget); QWidget* p = parentWidget(); bool isSubWindow = (windowType() == Qt::SubWindow); if (!isWindow() && !isSubWindow && p) return p->focusNextPrevChild(next); #ifndef QT_NO_GRAPHICSVIEW if (d->extra && d->extra->proxyWidget) return d->extra->proxyWidget->focusNextPrevChild(next); #endif QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next); if (!w) return false; w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason); return true; } /*! Returns the last child of this widget that setFocus had been called on. For top level widgets this is the widget that will get focus in case this window gets activated This is not the same as QApplication::focusWidget(), which returns the focus widget in the currently active window. */ QWidget *QWidget::focusWidget() const { return const_cast<QWidget *>(d_func()->focus_child); } /*! Returns the next widget in this widget's focus chain. \sa previousInFocusChain() */ QWidget *QWidget::nextInFocusChain() const { return const_cast<QWidget *>(d_func()->focus_next); } /*! \brief The previousInFocusChain function returns the previous widget in this widget's focus chain. \sa nextInFocusChain() \since 4.6 */ QWidget *QWidget::previousInFocusChain() const { return const_cast<QWidget *>(d_func()->focus_prev); } /*! \property QWidget::isActiveWindow \brief whether this widget's window is the active window The active window is the window that contains the widget that has keyboard focus (The window may still have focus if it has no widgets or none of its widgets accepts keyboard focus). When popup windows are visible, this property is true for both the active window \e and for the popup. By default, this property is false. \sa activateWindow(), QApplication::activeWindow() */ bool QWidget::isActiveWindow() const { QWidget *tlw = window(); if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup))) return true; #ifndef QT_NO_GRAPHICSVIEW if (QWExtra *tlwExtra = tlw->d_func()->extra) { if (isVisible() && tlwExtra->proxyWidget) return tlwExtra->proxyWidget->isActiveWindow(); } #endif #ifdef Q_WS_MAC extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp if(qt_mac_is_macdrawer(tlw) && tlw->parentWidget() && tlw->parentWidget()->isActiveWindow()) return true; extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw)) return true; #endif if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) { if(tlw->windowType() == Qt::Tool && !tlw->isModal() && (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow())) return true; QWidget *w = QApplication::activeWindow(); while(w && tlw->windowType() == Qt::Tool && !w->isModal() && w->parentWidget()) { w = w->parentWidget()->window(); if(w == tlw) return true; } } #if defined(Q_WS_WIN32) HWND active = GetActiveWindow(); if (!tlw->testAttribute(Qt::WA_WState_Created)) return false; return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId()); #else return false; #endif } /*! Puts the \a second widget after the \a first widget in the focus order. Note that since the tab order of the \a second widget is changed, you should order a chain like this: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9 \e not like this: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10 If \a first or \a second has a focus proxy, setTabOrder() correctly substitutes the proxy. \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus} */ void QWidget::setTabOrder(QWidget* first, QWidget *second) { if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus) return; if (first->window() != second->window()) { qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window"); return; } QWidget *fp = first->focusProxy(); if (fp) { // If first is redirected, set first to the last child of first // that can take keyboard focus so that second is inserted after // that last child, and the focus order within first is (more // likely to be) preserved. QList<QWidget *> l = first->findChildren<QWidget *>(); for (int i = l.size()-1; i >= 0; --i) { QWidget * next = l.at(i); if (next->window() == fp->window()) { fp = next; if (fp->focusPolicy() != Qt::NoFocus) break; } } first = fp; } if (fp == second) return; if (QWidget *sp = second->focusProxy()) second = sp; // QWidget *fp = first->d_func()->focus_prev; QWidget *fn = first->d_func()->focus_next; if (fn == second || first == second) return; QWidget *sp = second->d_func()->focus_prev; QWidget *sn = second->d_func()->focus_next; fn->d_func()->focus_prev = second; first->d_func()->focus_next = second; second->d_func()->focus_next = fn; second->d_func()->focus_prev = first; sp->d_func()->focus_next = sn; sn->d_func()->focus_prev = sp; Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first); Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first); Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second); Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second); } /*!\internal Moves the relevant subwidgets of this widget from the \a oldtlw's tab chain to that of the new parent, if there's anything to move and we're really moving This function is called from QWidget::reparent() *after* the widget has been reparented. \sa reparent() */ void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw) { Q_Q(QWidget); if (oldtlw == q->window()) return; // nothing to do if(focus_child) focus_child->clearFocus(); // separate the focus chain into new (children of myself) and old (the rest) QWidget *firstOld = 0; //QWidget *firstNew = q; //invariant QWidget *o = 0; // last in the old list QWidget *n = q; // last in the new list bool prevWasNew = true; QWidget *w = focus_next; //Note: for efficiency, we do not maintain the list invariant inside the loop //we append items to the relevant list, and we optimize by not changing pointers //when subsequent items are going into the same list. while (w != q) { bool currentIsNew = q->isAncestorOf(w); if (currentIsNew) { if (!prevWasNew) { //prev was old -- append to new list n->d_func()->focus_next = w; w->d_func()->focus_prev = n; } n = w; } else { if (prevWasNew) { //prev was new -- append to old list, if there is one if (o) { o->d_func()->focus_next = w; w->d_func()->focus_prev = o; } else { // "create" the old list firstOld = w; } } o = w; } w = w->d_func()->focus_next; prevWasNew = currentIsNew; } //repair the old list: if (firstOld) { o->d_func()->focus_next = firstOld; firstOld->d_func()->focus_prev = o; } if (!q->isWindow()) { QWidget *topLevel = q->window(); //insert new chain into toplevel's chain QWidget *prev = topLevel->d_func()->focus_prev; topLevel->d_func()->focus_prev = n; prev->d_func()->focus_next = q; focus_prev = prev; n->d_func()->focus_next = topLevel; } else { //repair the new list n->d_func()->focus_next = q; focus_prev = n; } } /*!\internal Measures the shortest distance from a point to a rect. This function is called from QDesktopwidget::screen(QPoint) to find the closest screen for a point. In directional KeypadNavigation, it is called to find the closest widget to the current focus widget center. */ int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r) { int dx = 0; int dy = 0; if (p.x() < r.left()) dx = r.left() - p.x(); else if (p.x() > r.right()) dx = p.x() - r.right(); if (p.y() < r.top()) dy = r.top() - p.y(); else if (p.y() > r.bottom()) dy = p.y() - r.bottom(); return dx + dy; } /*! \property QWidget::frameSize \brief the size of the widget including any window frame By default, this property contains a value that depends on the user's platform and screen geometry. */ QSize QWidget::frameSize() const { Q_D(const QWidget); if (isWindow() && !(windowType() == Qt::Popup)) { QRect fs = d->frameStrut(); return QSize(data->crect.width() + fs.left() + fs.right(), data->crect.height() + fs.top() + fs.bottom()); } return data->crect.size(); } /*! \fn void QWidget::move(int x, int y) \overload This corresponds to move(QPoint(\a x, \a y)). */ void QWidget::move(const QPoint &p) { Q_D(QWidget); setAttribute(Qt::WA_Moved); if (isWindow()) d->topData()->posFromMove = true; if (testAttribute(Qt::WA_WState_Created)) { d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(), p.y() + geometry().y() - QWidget::y(), width(), height(), true); d->setDirtyOpaqueRegion(); } else { data->crect.moveTopLeft(p); // no frame yet setAttribute(Qt::WA_PendingMoveEvent); } } /*! \fn void QWidget::resize(int w, int h) \overload This corresponds to resize(QSize(\a w, \a h)). */ void QWidget::resize(const QSize &s) { Q_D(QWidget); setAttribute(Qt::WA_Resized); if (testAttribute(Qt::WA_WState_Created)) { d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false); d->setDirtyOpaqueRegion(); } else { data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize())); setAttribute(Qt::WA_PendingResizeEvent); } } void QWidget::setGeometry(const QRect &r) { Q_D(QWidget); setAttribute(Qt::WA_Resized); setAttribute(Qt::WA_Moved); if (isWindow()) d->topData()->posFromMove = false; if (testAttribute(Qt::WA_WState_Created)) { d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true); d->setDirtyOpaqueRegion(); } else { data->crect.setTopLeft(r.topLeft()); data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize())); setAttribute(Qt::WA_PendingMoveEvent); setAttribute(Qt::WA_PendingResizeEvent); } } /*! \since 4.2 Saves the current geometry and state for top-level widgets. To save the geometry when the window closes, you can implement a close event like this: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11 See the \l{Window Geometry} documentation for an overview of geometry issues with windows. Use QMainWindow::saveState() to save the geometry and the state of toolbars and dock widgets. \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState() */ QByteArray QWidget::saveGeometry() const { #ifdef QT_MAC_USE_COCOA // We check if the window was maximized during this invocation. If so, we need to record the // starting position as 0,0. Q_D(const QWidget); QRect newFramePosition = frameGeometry(); QRect newNormalPosition = normalGeometry(); if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) { // Change the starting position newFramePosition.moveTo(0, 0); newNormalPosition.moveTo(0, 0); } #endif // QT_MAC_USE_COCOA QByteArray array; QDataStream stream(&array, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_4_0); const quint32 magicNumber = 0x1D9D0CB; quint16 majorVersion = 1; quint16 minorVersion = 0; stream << magicNumber << majorVersion << minorVersion #ifdef QT_MAC_USE_COCOA << newFramePosition << newNormalPosition #else << frameGeometry() << normalGeometry() #endif // QT_MAC_USE_COCOA << qint32(QApplication::desktop()->screenNumber(this)) << quint8(windowState() & Qt::WindowMaximized) << quint8(windowState() & Qt::WindowFullScreen); return array; } /*! \since 4.2 Restores the geometry and state top-level widgets stored in the byte array \a geometry. Returns true on success; otherwise returns false. If the restored geometry is off-screen, it will be modified to be inside the available screen geometry. To restore geometry saved using QSettings, you can use code like this: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12 See the \l{Window Geometry} documentation for an overview of geometry issues with windows. Use QMainWindow::restoreState() to restore the geometry and the state of toolbars and dock widgets. \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState() */ bool QWidget::restoreGeometry(const QByteArray &geometry) { if (geometry.size() < 4) return false; QDataStream stream(geometry); stream.setVersion(QDataStream::Qt_4_0); const quint32 magicNumber = 0x1D9D0CB; quint32 storedMagicNumber; stream >> storedMagicNumber; if (storedMagicNumber != magicNumber) return false; const quint16 currentMajorVersion = 1; quint16 majorVersion = 0; quint16 minorVersion = 0; stream >> majorVersion >> minorVersion; if (majorVersion != currentMajorVersion) return false; // (Allow all minor versions.) QRect restoredFrameGeometry; QRect restoredNormalGeometry; qint32 restoredScreenNumber; quint8 maximized; quint8 fullScreen; stream >> restoredFrameGeometry >> restoredNormalGeometry >> restoredScreenNumber >> maximized >> fullScreen; const int frameHeight = 20; if (!restoredFrameGeometry.isValid()) restoredFrameGeometry = QRect(QPoint(0,0), sizeHint()); if (!restoredNormalGeometry.isValid()) restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint()); if (!restoredNormalGeometry.isValid()) { // use the widget's adjustedSize if the sizeHint() doesn't help restoredNormalGeometry.setSize(restoredNormalGeometry .size() .expandedTo(d_func()->adjustedSize())); } const QDesktopWidget * const desktop = QApplication::desktop(); if (restoredScreenNumber >= desktop->numScreens()) restoredScreenNumber = desktop->primaryScreen(); const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber); // Modify the restored geometry if we are about to restore to coordinates // that would make the window "lost". This happens if: // - The restored geometry is completely oustside the available geometry // - The title bar is outside the available geometry. // - (Mac only) The window is higher than the available geometry. It must // be possible to bring the size grip on screen by moving the window. #ifdef Q_WS_MAC restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height())); restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight)); #endif if (!restoredFrameGeometry.intersects(availableGeometry)) { restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom())); restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left())); restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right())); } restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top())); if (!restoredNormalGeometry.intersects(availableGeometry)) { restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom())); restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left())); restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right())); } restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight)); if (maximized || fullScreen) { // set geomerty before setting the window state to make // sure the window is maximized to the right screen. // Skip on windows: the window is restored into a broken // half-maximized state. #ifndef Q_WS_WIN setGeometry(restoredNormalGeometry); #endif Qt::WindowStates ws = windowState(); if (maximized) ws |= Qt::WindowMaximized; if (fullScreen) ws |= Qt::WindowFullScreen; setWindowState(ws); d_func()->topData()->normalGeometry = restoredNormalGeometry; } else { QPoint offset; #ifdef Q_WS_X11 if (isFullScreen()) offset = d_func()->topData()->fullScreenOffset; #endif setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen)); move(restoredFrameGeometry.topLeft() + offset); resize(restoredNormalGeometry.size()); } return true; } /*!\fn void QWidget::setGeometry(int x, int y, int w, int h) \overload This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)). */ /*! Sets the margins around the contents of the widget to have the sizes \a left, \a top, \a right, and \a bottom. The margins are used by the layout system, and may be used by subclasses to specify the area to draw in (e.g. excluding the frame). Changing the margins will trigger a resizeEvent(). \sa contentsRect(), getContentsMargins() */ void QWidget::setContentsMargins(int left, int top, int right, int bottom) { Q_D(QWidget); if (left == d->leftmargin && top == d->topmargin && right == d->rightmargin && bottom == d->bottommargin) return; d->leftmargin = left; d->topmargin = top; d->rightmargin = right; d->bottommargin = bottom; if (QLayout *l=d->layout) l->update(); //force activate; will do updateGeometry else updateGeometry(); // ### Qt 5: compat, remove if (isVisible()) { update(); QResizeEvent e(data->crect.size(), data->crect.size()); QApplication::sendEvent(this, &e); } else { setAttribute(Qt::WA_PendingResizeEvent, true); } QEvent e(QEvent::ContentsRectChange); QApplication::sendEvent(this, &e); } /*! \overload \since 4.6 \brief The setContentsMargins function sets the margins around the widget's contents. Sets the margins around the contents of the widget to have the sizes determined by \a margins. The margins are used by the layout system, and may be used by subclasses to specify the area to draw in (e.g. excluding the frame). Changing the margins will trigger a resizeEvent(). \sa contentsRect(), getContentsMargins() */ void QWidget::setContentsMargins(const QMargins &margins) { setContentsMargins(margins.left(), margins.top(), margins.right(), margins.bottom()); } /*! Returns the widget's contents margins for \a left, \a top, \a right, and \a bottom. \sa setContentsMargins(), contentsRect() */ void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const { Q_D(const QWidget); if (left) *left = d->leftmargin; if (top) *top = d->topmargin; if (right) *right = d->rightmargin; if (bottom) *bottom = d->bottommargin; } /*! \since 4.6 \brief The contentsMargins function returns the widget's contents margins. \sa getContentsMargins(), setContentsMargins(), contentsRect() */ QMargins QWidget::contentsMargins() const { Q_D(const QWidget); return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin); } /*! Returns the area inside the widget's margins. \sa setContentsMargins(), getContentsMargins() */ QRect QWidget::contentsRect() const { Q_D(const QWidget); return QRect(QPoint(d->leftmargin, d->topmargin), QPoint(data->crect.width() - 1 - d->rightmargin, data->crect.height() - 1 - d->bottommargin)); } /*! \fn void QWidget::customContextMenuRequested(const QPoint &pos) This signal is emitted when the widget's \l contextMenuPolicy is Qt::CustomContextMenu, and the user has requested a context menu on the widget. The position \a pos is the position of the context menu event that the widget receives. Normally this is in widget coordinates. The exception to this rule is QAbstractScrollArea and its subclasses that map the context menu event to coordinates of the \link QAbstractScrollArea::viewport() viewport() \endlink . \sa mapToGlobal() QMenu contextMenuPolicy */ /*! \property QWidget::contextMenuPolicy \brief how the widget shows a context menu The default value of this property is Qt::DefaultContextMenu, which means the contextMenuEvent() handler is called. Other values are Qt::NoContextMenu, Qt::PreventContextMenu, Qt::ActionsContextMenu, and Qt::CustomContextMenu. With Qt::CustomContextMenu, the signal customContextMenuRequested() is emitted. \sa contextMenuEvent(), customContextMenuRequested(), actions() */ Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const { return (Qt::ContextMenuPolicy)data->context_menu_policy; } void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy) { data->context_menu_policy = (uint) policy; } /*! \property QWidget::focusPolicy \brief the way the widget accepts keyboard focus The policy is Qt::TabFocus if the widget accepts keyboard focus by tabbing, Qt::ClickFocus if the widget accepts focus by clicking, Qt::StrongFocus if it accepts both, and Qt::NoFocus (the default) if it does not accept focus at all. You must enable keyboard focus for a widget if it processes keyboard events. This is normally done from the widget's constructor. For instance, the QLineEdit constructor calls setFocusPolicy(Qt::StrongFocus). If the widget has a focus proxy, then the focus policy will be propagated to it. \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled */ Qt::FocusPolicy QWidget::focusPolicy() const { return (Qt::FocusPolicy)data->focus_policy; } void QWidget::setFocusPolicy(Qt::FocusPolicy policy) { data->focus_policy = (uint) policy; Q_D(QWidget); if (d->extra && d->extra->focus_proxy) d->extra->focus_proxy->setFocusPolicy(policy); } /*! \property QWidget::updatesEnabled \brief whether updates are enabled An updates enabled widget receives paint events and has a system background; a disabled widget does not. This also implies that calling update() and repaint() has no effect if updates are disabled. By default, this property is true. setUpdatesEnabled() is normally used to disable updates for a short period of time, for instance to avoid screen flicker during large changes. In Qt, widgets normally do not generate screen flicker, but on X11 the server might erase regions on the screen when widgets get hidden before they can be replaced by other widgets. Disabling updates solves this. Example: \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13 Disabling a widget implicitly disables all its children. Enabling a widget enables all child widgets \e except top-level widgets or those that have been explicitly disabled. Re-enabling updates implicitly calls update() on the widget. \sa paintEvent() */ void QWidget::setUpdatesEnabled(bool enable) { Q_D(QWidget); setAttribute(Qt::WA_ForceUpdatesDisabled, !enable); d->setUpdatesEnabled_helper(enable); } /*! \fn void QWidget::show() Shows the widget and its child widgets. This function is equivalent to setVisible(true). \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(), showNormal(), isVisible() */ /*! \internal Makes the widget visible in the isVisible() meaning of the word. It is only called for toplevels or widgets with visible parents. */ void QWidgetPrivate::show_recursive() { Q_Q(QWidget); // polish if necessary if (!q->testAttribute(Qt::WA_WState_Created)) createRecursively(); q->ensurePolished(); #ifdef QT3_SUPPORT if(sendChildEvents) QApplication::sendPostedEvents(q, QEvent::ChildInserted); #endif if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show) q->parentWidget()->d_func()->layout->activate(); // activate our layout before we and our children become visible if (layout) layout->activate(); show_helper(); } void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates) { Q_Q(QWidget); disableUpdates = disableUpdates && q->updatesEnabled(); if (disableUpdates) q->setAttribute(Qt::WA_UpdatesDisabled); if (q->testAttribute(Qt::WA_PendingMoveEvent)) { QMoveEvent e(data.crect.topLeft(), data.crect.topLeft()); QApplication::sendEvent(q, &e); q->setAttribute(Qt::WA_PendingMoveEvent, false); } if (q->testAttribute(Qt::WA_PendingResizeEvent)) { QResizeEvent e(data.crect.size(), QSize()); QApplication::sendEvent(q, &e); q->setAttribute(Qt::WA_PendingResizeEvent, false); } if (disableUpdates) q->setAttribute(Qt::WA_UpdatesDisabled, false); if (!recursive) return; for (int i = 0; i < children.size(); ++i) { if (QWidget *child = qobject_cast<QWidget *>(children.at(i))) child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates); } } void QWidgetPrivate::activateChildLayoutsRecursively() { sendPendingMoveAndResizeEvents(false, true); for (int i = 0; i < children.size(); ++i) { QWidget *child = qobject_cast<QWidget *>(children.at(i)); if (!child || child->isHidden() || child->isWindow()) continue; child->ensurePolished(); // Activate child's layout QWidgetPrivate *childPrivate = child->d_func(); if (childPrivate->layout) childPrivate->layout->activate(); // Pretend we're visible. const bool wasVisible = child->isVisible(); if (!wasVisible) child->setAttribute(Qt::WA_WState_Visible); // Do the same for all my children. childPrivate->activateChildLayoutsRecursively(); // We're not cheating anymore. if (!wasVisible) child->setAttribute(Qt::WA_WState_Visible, false); } } void QWidgetPrivate::show_helper() { Q_Q(QWidget); data.in_show = true; // qws optimization // make sure we receive pending move and resize events sendPendingMoveAndResizeEvents(); // become visible before showing all children q->setAttribute(Qt::WA_WState_Visible); // finally show all children recursively showChildren(false); #ifdef QT3_SUPPORT if (q->parentWidget() && sendChildEvents) QApplication::sendPostedEvents(q->parentWidget(), QEvent::ChildInserted); #endif // popup handling: new popups and tools need to be raised, and // existing popups must be closed. Also propagate the current // windows's KeyboardFocusChange status. if (q->isWindow()) { if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) { q->raise(); if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange)) q->setAttribute(Qt::WA_KeyboardFocusChange); } else { while (QApplication::activePopupWidget()) { if (!QApplication::activePopupWidget()->close()) break; } } } // Automatic embedding of child windows of widgets already embedded into // QGraphicsProxyWidget when they are shown the first time. bool isEmbedded = false; #ifndef QT_NO_GRAPHICSVIEW if (q->isWindow()) { isEmbedded = q->graphicsProxyWidget() ? true : false; if (!isEmbedded && !bypassGraphicsProxyWidget(q)) { QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget()); if (ancestorProxy) { isEmbedded = true; ancestorProxy->d_func()->embedSubWindow(q); } } } #else Q_UNUSED(isEmbedded); #endif // On Windows, show the popup now so that our own focus handling // stores the correct old focus widget even if it's stolen in the // showevent #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN) if (!isEmbedded && q->windowType() == Qt::Popup) qApp->d_func()->openPopup(q); #endif // send the show event before showing the window QShowEvent showEvent; QApplication::sendEvent(q, &showEvent); if (!isEmbedded && q->isModal() && q->isWindow()) // QApplicationPrivate::enterModal *before* show, otherwise the initial // stacking might be wrong QApplicationPrivate::enterModal(q); show_sys(); #if !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN) if (!isEmbedded && q->windowType() == Qt::Popup) qApp->d_func()->openPopup(q); #endif #ifndef QT_NO_ACCESSIBILITY if (q->windowType() != Qt::ToolTip) // Tooltips are read aloud twice in MS narrator. QAccessible::updateAccessibility(q, 0, QAccessible::ObjectShow); #endif if (QApplicationPrivate::hidden_focus_widget == q) { QApplicationPrivate::hidden_focus_widget = 0; q->setFocus(Qt::OtherFocusReason); } // Process events when showing a Qt::SplashScreen widget before the event loop // is spinnning; otherwise it might not show up on particular platforms. // This makes QSplashScreen behave the same on all platforms. if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen) QApplication::processEvents(); data.in_show = false; // reset qws optimization } /*! \fn void QWidget::hide() Hides the widget. This function is equivalent to setVisible(false). \note If you are working with QDialog or its subclasses and you invoke the show() function after this function, the dialog will be displayed in its original position. \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close() */ /*!\internal */ void QWidgetPrivate::hide_helper() { Q_Q(QWidget); bool isEmbedded = false; #if !defined QT_NO_GRAPHICSVIEW isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0; #else Q_UNUSED(isEmbedded); #endif if (!isEmbedded && (q->windowType() == Qt::Popup)) qApp->d_func()->closePopup(q); // Move test modal here. Otherwise, a modal dialog could get // destroyed and we lose all access to its parent because we haven't // left modality. (Eg. modal Progress Dialog) if (!isEmbedded && q->isModal() && q->isWindow()) QApplicationPrivate::leaveModal(q); #if defined(Q_WS_WIN) if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget() && !q->parentWidget()->isHidden() && q->isActiveWindow()) q->parentWidget()->activateWindow(); // Activate parent #endif q->setAttribute(Qt::WA_Mapped, false); hide_sys(); bool wasVisible = q->testAttribute(Qt::WA_WState_Visible); if (wasVisible) { q->setAttribute(Qt::WA_WState_Visible, false); } QHideEvent hideEvent; QApplication::sendEvent(q, &hideEvent); hideChildren(false); // next bit tries to move the focus if the focus widget is now // hidden. if (wasVisible) { #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined (Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA) qApp->d_func()->sendSyntheticEnterLeave(q); #endif QWidget *fw = QApplication::focusWidget(); while (fw && !fw->isWindow()) { if (fw == q) { q->focusNextPrevChild(true); break; } fw = fw->parentWidget(); } } if (QWidgetBackingStore *bs = maybeBackingStore()) bs->removeDirtyWidget(q); #ifndef QT_NO_ACCESSIBILITY if (wasVisible) QAccessible::updateAccessibility(q, 0, QAccessible::ObjectHide); #endif } /*! \fn bool QWidget::isHidden() const Returns true if the widget is hidden, otherwise returns false. A hidden widget will only become visible when show() is called on it. It will not be automatically shown when the parent is shown. To check visibility, use !isVisible() instead (notice the exclamation mark). isHidden() implies !isVisible(), but a widget can be not visible and not hidden at the same time. This is the case for widgets that are children of widgets that are not visible. Widgets are hidden if: \list \o they were created as independent windows, \o they were created as children of visible widgets, \o hide() or setVisible(false) was called. \endlist */ void QWidget::setVisible(bool visible) { if (visible) { // show if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden)) return; Q_D(QWidget); // Designer uses a trick to make grabWidget work without showing if (!isWindow() && parentWidget() && parentWidget()->isVisible() && !parentWidget()->testAttribute(Qt::WA_WState_Created)) parentWidget()->window()->d_func()->createRecursively(); //we have to at least create toplevels before applyX11SpecificCommandLineArguments //but not children of non-visible parents QWidget *pw = parentWidget(); if (!testAttribute(Qt::WA_WState_Created) && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) { create(); } #if defined(Q_WS_X11) if (windowType() == Qt::Window) QApplicationPrivate::applyX11SpecificCommandLineArguments(this); #elif defined(Q_WS_QWS) if (windowType() == Qt::Window) QApplicationPrivate::applyQWSSpecificCommandLineArguments(this); #endif bool wasResized = testAttribute(Qt::WA_Resized); Qt::WindowStates initialWindowState = windowState(); // polish if necessary ensurePolished(); // remember that show was called explicitly setAttribute(Qt::WA_WState_ExplicitShowHide); // whether we need to inform the parent widget immediately bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden); // we are no longer hidden setAttribute(Qt::WA_WState_Hidden, false); if (needUpdateGeometry) d->updateGeometry_helper(true); #ifdef QT3_SUPPORT QApplication::sendPostedEvents(this, QEvent::ChildInserted); #endif // activate our layout before we and our children become visible if (d->layout) d->layout->activate(); if (!isWindow()) { QWidget *parent = parentWidget(); while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) { parent->d_func()->layout->activate(); if (parent->isWindow()) break; parent = parent->parentWidget(); } if (parent) parent->d_func()->setDirtyOpaqueRegion(); } // adjust size if necessary if (!wasResized && (isWindow() || !parentWidget()->d_func()->layout)) { if (isWindow()) { adjustSize(); if (windowState() != initialWindowState) setWindowState(initialWindowState); } else { adjustSize(); } setAttribute(Qt::WA_Resized, false); } setAttribute(Qt::WA_KeyboardFocusChange, false); if (isWindow() || parentWidget()->isVisible()) { // remove posted quit events when showing a new window QCoreApplication::removePostedEvents(qApp, QEvent::Quit); d->show_helper(); #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined (Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA) qApp->d_func()->sendSyntheticEnterLeave(this); #endif } QEvent showToParentEvent(QEvent::ShowToParent); QApplication::sendEvent(this, &showToParentEvent); } else { // hide if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden)) return; #if defined(Q_WS_WIN) // reset WS_DISABLED style in a Blocked window if(isWindow() && testAttribute(Qt::WA_WState_Created) && QApplicationPrivate::isBlockedByModal(this)) { LONG dwStyle = GetWindowLong(winId(), GWL_STYLE); dwStyle &= ~WS_DISABLED; SetWindowLong(winId(), GWL_STYLE, dwStyle); } #endif if (QApplicationPrivate::hidden_focus_widget == this) QApplicationPrivate::hidden_focus_widget = 0; Q_D(QWidget); // hw: The test on getOpaqueRegion() needs to be more intelligent // currently it doesn't work if the widget is hidden (the region will // be clipped). The real check should be testing the cached region // (and dirty flag) directly. if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty()) parentWidget()->d_func()->setDirtyOpaqueRegion(); setAttribute(Qt::WA_WState_Hidden); setAttribute(Qt::WA_WState_ExplicitShowHide); if (testAttribute(Qt::WA_WState_Created)) d->hide_helper(); // invalidate layout similar to updateGeometry() if (!isWindow() && parentWidget()) { if (parentWidget()->d_func()->layout) parentWidget()->d_func()->layout->invalidate(); else if (parentWidget()->isVisible()) QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest)); } QEvent hideToParentEvent(QEvent::HideToParent); QApplication::sendEvent(this, &hideToParentEvent); } } /*!\fn void QWidget::setHidden(bool hidden) Convenience function, equivalent to setVisible(!\a hidden). */ /*!\fn void QWidget::setShown(bool shown) Use setVisible(\a shown) instead. */ void QWidgetPrivate::_q_showIfNotHidden() { Q_Q(QWidget); if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) ) q->setVisible(true); } void QWidgetPrivate::showChildren(bool spontaneous) { QList<QObject*> childList = children; for (int i = 0; i < childList.size(); ++i) { QWidget *widget = qobject_cast<QWidget*>(childList.at(i)); if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden)) continue; if (spontaneous) { widget->setAttribute(Qt::WA_Mapped); widget->d_func()->showChildren(true); QShowEvent e; QApplication::sendSpontaneousEvent(widget, &e); } else { if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide)) widget->d_func()->show_recursive(); else widget->show(); } } } void QWidgetPrivate::hideChildren(bool spontaneous) { QList<QObject*> childList = children; for (int i = 0; i < childList.size(); ++i) { QWidget *widget = qobject_cast<QWidget*>(childList.at(i)); if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden)) continue; #ifdef QT_MAC_USE_COCOA // Before doing anything we need to make sure that we don't leave anything in a non-consistent state. // When hiding a widget we need to make sure that no mouse_down events are active, because // the mouse_up event will never be received by a hidden widget or one of its descendants. // The solution is simple, before going through with this we check if there are any mouse_down events in // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and // then we continue. // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the // mouse release event. There are two ways to interpret this: // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it // might be waiting for a release event that will never arrive. // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not // supposed to trigger because it is not visible. if(widget == qt_button_down) qt_button_down = 0; #endif // QT_MAC_USE_COCOA if (spontaneous) widget->setAttribute(Qt::WA_Mapped, false); else widget->setAttribute(Qt::WA_WState_Visible, false); widget->d_func()->hideChildren(spontaneous); QHideEvent e; if (spontaneous) { QApplication::sendSpontaneousEvent(widget, &e); } else { QApplication::sendEvent(widget, &e); if (widget->internalWinId() && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) { // hide_sys() on an ancestor won't have any affect on this // widget, so it needs an explicit hide_sys() of its own widget->d_func()->hide_sys(); } } #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined (Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA) qApp->d_func()->sendSyntheticEnterLeave(widget); #endif #ifndef QT_NO_ACCESSIBILITY if (!spontaneous) QAccessible::updateAccessibility(widget, 0, QAccessible::ObjectHide); #endif } } bool QWidgetPrivate::close_helper(CloseMode mode) { if (data.is_closing) return true; Q_Q(QWidget); data.is_closing = 1; QPointer<QWidget> that = q; QPointer<QWidget> parentWidget = q->parentWidget(); #ifdef QT3_SUPPORT bool isMain = (QApplicationPrivate::main_widget == q); #endif bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose); if (mode != CloseNoEvent) { QCloseEvent e; if (mode == CloseWithSpontaneousEvent) QApplication::sendSpontaneousEvent(q, &e); else QApplication::sendEvent(q, &e); if (!that.isNull() && !e.isAccepted()) { data.is_closing = 0; return false; } } if (!that.isNull() && !q->isHidden()) q->hide(); #ifdef QT3_SUPPORT if (isMain) QApplication::quit(); #endif // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible()); if (quitOnClose) { /* if there is no non-withdrawn primary window left (except the ones without QuitOnClose), we emit the lastWindowClosed signal */ QWidgetList list = QApplication::topLevelWidgets(); bool lastWindowClosed = true; for (int i = 0; i < list.size(); ++i) { QWidget *w = list.at(i); if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose)) continue; lastWindowClosed = false; break; } if (lastWindowClosed) QApplicationPrivate::emitLastWindowClosed(); } if (!that.isNull()) { data.is_closing = 0; if (q->testAttribute(Qt::WA_DeleteOnClose)) { q->setAttribute(Qt::WA_DeleteOnClose, false); q->deleteLater(); } } return true; } /*! Closes this widget. Returns true if the widget was closed; otherwise returns false. First it sends the widget a QCloseEvent. The widget is \link hide() hidden\endlink if it \link QCloseEvent::accept() accepts\endlink the close event. If it \link QCloseEvent::ignore() ignores\endlink the event, nothing happens. The default implementation of QWidget::closeEvent() accepts the close event. If the widget has the Qt::WA_DeleteOnClose flag, the widget is also deleted. A close events is delivered to the widget no matter if the widget is visible or not. The \l QApplication::lastWindowClosed() signal is emitted when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus. */ bool QWidget::close() { return d_func()->close_helper(QWidgetPrivate::CloseWithEvent); } /*! \property QWidget::visible \brief whether the widget is visible Calling setVisible(true) or show() sets the widget to visible status if all its parent widgets up to the window are visible. If an ancestor is not visible, the widget won't become visible until all its ancestors are shown. If its size or position has changed, Qt guarantees that a widget gets move and resize events just before it is shown. If the widget has not been resized yet, Qt will adjust the widget's size to a useful default using adjustSize(). Calling setVisible(false) or hide() hides a widget explicitly. An explicitly hidden widget will never become visible, even if all its ancestors become visible, unless you show it. A widget receives show and hide events when its visibility status changes. Between a hide and a show event, there is no need to waste CPU cycles preparing or displaying information to the user. A video application, for example, might simply stop generating new frames. A widget that happens to be obscured by other windows on the screen is considered to be visible. The same applies to iconified windows and windows that exist on another virtual desktop (on platforms that support this concept). A widget receives spontaneous show and hide events when its mapping status is changed by the window system, e.g. a spontaneous hide event when the user minimizes the window, and a spontaneous show event when the window is restored again. You almost never have to reimplement the setVisible() function. If you need to change some settings before a widget is shown, use showEvent() instead. If you need to do some delayed initialization use the Polish event delivered to the event() function. \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(), showEvent(), hideEvent() */ /*! Returns true if this widget would become visible if \a ancestor is shown; otherwise returns false. The true case occurs if neither the widget itself nor any parent up to but excluding \a ancestor has been explicitly hidden. This function will still return true if the widget is obscured by other windows on the screen, but could be physically visible if it or they were to be moved. isVisibleTo(0) is identical to isVisible(). \sa show() hide() isVisible() */ bool QWidget::isVisibleTo(QWidget* ancestor) const { if (!ancestor) return isVisible(); const QWidget * w = this; while (!w->isHidden() && !w->isWindow() && w->parentWidget() && w->parentWidget() != ancestor) w = w->parentWidget(); return !w->isHidden(); } #ifdef QT3_SUPPORT /*! Use visibleRegion() instead. */ QRect QWidget::visibleRect() const { return d_func()->clipRect(); } #endif /*! Returns the unobscured region where paint events can occur. For visible widgets, this is an approximation of the area not covered by other widgets; otherwise, this is an empty region. The repaint() function calls this function if necessary, so in general you do not need to call it. */ QRegion QWidget::visibleRegion() const { Q_D(const QWidget); QRect clipRect = d->clipRect(); if (clipRect.isEmpty()) return QRegion(); QRegion r(clipRect); d->subtractOpaqueChildren(r, clipRect); d->subtractOpaqueSiblings(r); #ifdef Q_WS_QWS const QWSWindowSurface *surface = static_cast<const QWSWindowSurface*>(windowSurface()); if (surface) { const QPoint offset = mapTo(surface->window(), QPoint()); r &= surface->clipRegion().translated(-offset); } #endif return r; } QSize QWidgetPrivate::adjustedSize() const { Q_Q(const QWidget); QSize s = q->sizeHint(); if (q->isWindow()) { Qt::Orientations exp; if (layout) { if (layout->hasHeightForWidth()) s.setHeight(layout->totalHeightForWidth(s.width())); exp = layout->expandingDirections(); } else { if (q->sizePolicy().hasHeightForWidth()) s.setHeight(q->heightForWidth(s.width())); exp = q->sizePolicy().expandingDirections(); } if (exp & Qt::Horizontal) s.setWidth(qMax(s.width(), 200)); if (exp & Qt::Vertical) s.setHeight(qMax(s.height(), 100)); #if defined(Q_WS_X11) QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen()); #else // all others QRect screen = QApplication::desktop()->screenGeometry(q->pos()); #endif #if defined (Q_WS_WINCE) || defined (Q_OS_SYMBIAN) s.setWidth(qMin(s.width(), screen.width())); s.setHeight(qMin(s.height(), screen.height())); #else s.setWidth(qMin(s.width(), screen.width()*2/3)); s.setHeight(qMin(s.height(), screen.height()*2/3)); #endif if (QTLWExtra *extra = maybeTopData()) extra->sizeAdjusted = true; } if (!s.isValid()) { QRect r = q->childrenRect(); // get children rectangle if (r.isNull()) return s; s = r.size() + QSize(2 * r.x(), 2 * r.y()); } return s; } /*! Adjusts the size of the widget to fit its contents. This function uses sizeHint() if it is valid, i.e., the size hint's width and height are \>= 0. Otherwise, it sets the size to the children rectangle that covers all child widgets (the union of all child widget rectangles). For windows, the screen size is also taken into account. If the sizeHint() is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding} {expanding}, the window will be at least (200, 100). The maximum size of a window is 2/3 of the screen's width and height. \sa sizeHint(), childrenRect() */ void QWidget::adjustSize() { Q_D(QWidget); ensurePolished(); QSize s = d->adjustedSize(); if (d->layout) d->layout->activate(); if (s.isValid()) resize(s); } /*! \property QWidget::sizeHint \brief the recommended size for the widget If the value of this property is an invalid size, no size is recommended. The default implementation of sizeHint() returns an invalid size if there is no layout for this widget, and returns the layout's preferred size otherwise. \sa QSize::isValid(), minimumSizeHint(), sizePolicy(), setMinimumSize(), updateGeometry() */ QSize QWidget::sizeHint() const { Q_D(const QWidget); if (d->layout) return d->layout->totalSizeHint(); return QSize(-1, -1); } /*! \property QWidget::minimumSizeHint \brief the recommended minimum size for the widget If the value of this property is an invalid size, no minimum size is recommended. The default implementation of minimumSizeHint() returns an invalid size if there is no layout for this widget, and returns the layout's minimum size otherwise. Most built-in widgets reimplement minimumSizeHint(). \l QLayout will never resize a widget to a size smaller than the minimum size hint unless minimumSize() is set or the size policy is set to QSizePolicy::Ignore. If minimumSize() is set, the minimum size hint will be ignored. \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy() */ QSize QWidget::minimumSizeHint() const { Q_D(const QWidget); if (d->layout) return d->layout->totalMinimumSize(); return QSize(-1, -1); } /*! \fn QWidget *QWidget::parentWidget() const Returns the parent of this widget, or 0 if it does not have any parent widget. */ /*! Returns true if this widget is a parent, (or grandparent and so on to any level), of the given \a child, and both widgets are within the same window; otherwise returns false. */ bool QWidget::isAncestorOf(const QWidget *child) const { while (child) { if (child == this) return true; if (child->isWindow()) return false; child = child->parentWidget(); } return false; } #if defined(Q_WS_WIN) inline void setDisabledStyle(QWidget *w, bool setStyle) { // set/reset WS_DISABLED style. if(w && w->isWindow() && w->isVisible() && w->isEnabled()) { LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE); LONG newStyle = dwStyle; if (setStyle) newStyle |= WS_DISABLED; else newStyle &= ~WS_DISABLED; if (newStyle != dwStyle) { SetWindowLong(w->winId(), GWL_STYLE, newStyle); // we might need to repaint in some situations (eg. menu) w->repaint(); } } } #endif /***************************************************************************** QWidget event handling *****************************************************************************/ /*! This is the main event handler; it handles event \a event. You can reimplement this function in a subclass, but we recommend using one of the specialized event handlers instead. Key press and release events are treated differently from other events. event() checks for Tab and Shift+Tab and tries to move the focus appropriately. If there is no widget to move the focus to (or the key press is not Tab or Shift+Tab), event() calls keyPressEvent(). Mouse and tablet event handling is also slightly special: only when the widget is \l enabled, event() will call the specialized handlers such as mousePressEvent(); otherwise it will discard the event. This function returns true if the event was recognized, otherwise it returns false. If the recognized event was accepted (see \l QEvent::accepted), any further processing such as event propagation to the parent widget stops. \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(), keyPressEvent(), keyReleaseEvent(), leaveEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(), mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(), QObject::event(), QObject::timerEvent() */ bool QWidget::event(QEvent *event) { Q_D(QWidget); // ignore mouse events when disabled if (!isEnabled()) { switch(event->type()) { case QEvent::TabletPress: case QEvent::TabletRelease: case QEvent::TabletMove: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseMove: case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: case QEvent::ContextMenu: #ifndef QT_NO_WHEELEVENT case QEvent::Wheel: #endif return false; default: break; } } switch (event->type()) { case QEvent::MouseMove: mouseMoveEvent((QMouseEvent*)event); break; case QEvent::MouseButtonPress: // Don't reset input context here. Whether reset or not is // a responsibility of input method. reset() will be // called by mouseHandler() of input method if necessary // via mousePressEvent() of text widgets. #if 0 resetInputContext(); #endif mousePressEvent((QMouseEvent*)event); break; case QEvent::MouseButtonRelease: mouseReleaseEvent((QMouseEvent*)event); break; case QEvent::MouseButtonDblClick: mouseDoubleClickEvent((QMouseEvent*)event); break; case QEvent::NonClientAreaMouseButtonPress: { QWidget* w; while ((w = QApplication::activePopupWidget()) && w != this) { w->close(); if (QApplication::activePopupWidget() == w) // widget does not want to disappear w->hide(); // hide at least } break; } #ifndef QT_NO_WHEELEVENT case QEvent::Wheel: wheelEvent((QWheelEvent*)event); break; #endif #ifndef QT_NO_TABLETEVENT case QEvent::TabletMove: case QEvent::TabletPress: case QEvent::TabletRelease: tabletEvent((QTabletEvent*)event); break; #endif #ifdef QT3_SUPPORT case QEvent::Accel: event->ignore(); return false; #endif case QEvent::KeyPress: { QKeyEvent *k = (QKeyEvent *)event; bool res = false; if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier? if (k->key() == Qt::Key_Backtab || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) res = focusNextPrevChild(false); else if (k->key() == Qt::Key_Tab) res = focusNextPrevChild(true); if (res) break; } keyPressEvent(k); #ifdef QT_KEYPAD_NAVIGATION if (!k->isAccepted() && QApplication::keypadNavigationEnabled() && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) { if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) { if (k->key() == Qt::Key_Up) res = focusNextPrevChild(false); else if (k->key() == Qt::Key_Down) res = focusNextPrevChild(true); } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) { if (k->key() == Qt::Key_Up) res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth); else if (k->key() == Qt::Key_Right) res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast); else if (k->key() == Qt::Key_Down) res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth); else if (k->key() == Qt::Key_Left) res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest); } if (res) { k->accept(); break; } } #endif #ifndef QT_NO_WHATSTHIS if (!k->isAccepted() && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1 && d->whatsThis.size()) { QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImMicroFocus).toRect().center()), d->whatsThis, this); k->accept(); } #endif } break; case QEvent::KeyRelease: keyReleaseEvent((QKeyEvent*)event); // fall through case QEvent::ShortcutOverride: break; case QEvent::InputMethod: inputMethodEvent((QInputMethodEvent *) event); break; case QEvent::PolishRequest: ensurePolished(); break; case QEvent::Polish: { style()->polish(this); setAttribute(Qt::WA_WState_Polished); if (!QApplication::font(this).isCopyOf(QApplication::font())) d->resolveFont(); if (!QApplication::palette(this).isCopyOf(QApplication::palette())) d->resolvePalette(); #ifdef QT3_SUPPORT if(d->sendChildEvents) QApplication::sendPostedEvents(this, QEvent::ChildInserted); #endif } break; case QEvent::ApplicationWindowIconChange: if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) { d->setWindowIcon_sys(); d->setWindowIcon_helper(); } break; case QEvent::FocusIn: #ifdef QT_SOFTKEYS_ENABLED QSoftKeyManager::updateSoftKeys(); #endif focusInEvent((QFocusEvent*)event); break; case QEvent::FocusOut: focusOutEvent((QFocusEvent*)event); break; case QEvent::Enter: #ifndef QT_NO_STATUSTIP if (d->statusTip.size()) { QStatusTipEvent tip(d->statusTip); QApplication::sendEvent(const_cast<QWidget *>(this), &tip); } #endif enterEvent(event); break; case QEvent::Leave: #ifndef QT_NO_STATUSTIP if (d->statusTip.size()) { QString empty; QStatusTipEvent tip(empty); QApplication::sendEvent(const_cast<QWidget *>(this), &tip); } #endif leaveEvent(event); break; case QEvent::HoverEnter: case QEvent::HoverLeave: update(); break; case QEvent::Paint: // At this point the event has to be delivered, regardless // whether the widget isVisible() or not because it // already went through the filters paintEvent((QPaintEvent*)event); break; case QEvent::Move: moveEvent((QMoveEvent*)event); break; case QEvent::Resize: resizeEvent((QResizeEvent*)event); break; case QEvent::Close: closeEvent((QCloseEvent *)event); break; #ifndef QT_NO_CONTEXTMENU case QEvent::ContextMenu: switch (data->context_menu_policy) { case Qt::PreventContextMenu: break; case Qt::DefaultContextMenu: contextMenuEvent(static_cast<QContextMenuEvent *>(event)); break; case Qt::CustomContextMenu: emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos()); break; #ifndef QT_NO_MENU case Qt::ActionsContextMenu: if (d->actions.count()) { QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(), 0, this); break; } // fall through #endif default: event->ignore(); break; } break; #endif // QT_NO_CONTEXTMENU #ifndef QT_NO_DRAGANDDROP case QEvent::Drop: dropEvent((QDropEvent*) event); break; case QEvent::DragEnter: dragEnterEvent((QDragEnterEvent*) event); break; case QEvent::DragMove: dragMoveEvent((QDragMoveEvent*) event); break; case QEvent::DragLeave: dragLeaveEvent((QDragLeaveEvent*) event); break; #endif case QEvent::Show: showEvent((QShowEvent*) event); break; case QEvent::Hide: hideEvent((QHideEvent*) event); break; case QEvent::ShowWindowRequest: if (!isHidden()) d->show_sys(); break; case QEvent::ApplicationFontChange: d->resolveFont(); break; case QEvent::ApplicationPaletteChange: if (!(windowType() == Qt::Desktop)) d->resolvePalette(); break; case QEvent::ToolBarChange: case QEvent::ActivationChange: case QEvent::EnabledChange: case QEvent::FontChange: case QEvent::StyleChange: case QEvent::PaletteChange: case QEvent::WindowTitleChange: case QEvent::IconTextChange: case QEvent::ModifiedChange: case QEvent::MouseTrackingChange: case QEvent::ParentChange: case QEvent::WindowStateChange: case QEvent::LocaleChange: case QEvent::MacSizeChange: case QEvent::ContentsRectChange: changeEvent(event); break; case QEvent::WindowActivate: case QEvent::WindowDeactivate: { #ifdef QT3_SUPPORT windowActivationChange(event->type() != QEvent::WindowActivate); #endif if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive)) update(); QList<QObject*> childList = d->children; for (int i = 0; i < childList.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(childList.at(i)); if (w && w->isVisible() && !w->isWindow()) QApplication::sendEvent(w, event); } #ifdef QT_SOFTKEYS_ENABLED if (isWindow()) QSoftKeyManager::updateSoftKeys(); #endif break; } case QEvent::LanguageChange: #ifdef QT3_SUPPORT languageChange(); #endif changeEvent(event); { QList<QObject*> childList = d->children; for (int i = 0; i < childList.size(); ++i) { QObject *o = childList.at(i); if (o) QApplication::sendEvent(o, event); } } update(); break; case QEvent::ApplicationLayoutDirectionChange: d->resolveLayoutDirection(); break; case QEvent::LayoutDirectionChange: if (d->layout) d->layout->invalidate(); update(); changeEvent(event); break; case QEvent::UpdateRequest: d->syncBackingStore(); break; case QEvent::UpdateLater: update(static_cast<QUpdateLaterEvent*>(event)->region()); break; case QEvent::WindowBlocked: case QEvent::WindowUnblocked: { QList<QObject*> childList = d->children; for (int i = 0; i < childList.size(); ++i) { QObject *o = childList.at(i); if (o && o != QApplication::activeModalWidget()) { if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) { // do not forward the event to child windows, // QApplication does this for us continue; } QApplication::sendEvent(o, event); } } #if defined(Q_WS_WIN) setDisabledStyle(this, (event->type() == QEvent::WindowBlocked)); #endif } break; #ifndef QT_NO_TOOLTIP case QEvent::ToolTip: if (!d->toolTip.isEmpty()) QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this); else event->ignore(); break; #endif #ifndef QT_NO_WHATSTHIS case QEvent::WhatsThis: if (d->whatsThis.size()) QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this); else event->ignore(); break; case QEvent::QueryWhatsThis: if (d->whatsThis.isEmpty()) event->ignore(); break; #endif #ifndef QT_NO_ACCESSIBILITY case QEvent::AccessibilityDescription: case QEvent::AccessibilityHelp: { QAccessibleEvent *ev = static_cast<QAccessibleEvent *>(event); if (ev->child()) return false; switch (ev->type()) { #ifndef QT_NO_TOOLTIP case QEvent::AccessibilityDescription: ev->setValue(d->toolTip); break; #endif #ifndef QT_NO_WHATSTHIS case QEvent::AccessibilityHelp: ev->setValue(d->whatsThis); break; #endif default: return false; } break; } #endif case QEvent::EmbeddingControl: d->topData()->frameStrut.setCoords(0 ,0, 0, 0); data->fstrut_dirty = false; #if defined(Q_WS_WIN) || defined(Q_WS_X11) d->topData()->embedded = 1; #endif break; #ifndef QT_NO_ACTION case QEvent::ActionAdded: case QEvent::ActionRemoved: case QEvent::ActionChanged: #ifdef QT_SOFTKEYS_ENABLED QSoftKeyManager::updateSoftKeys(); #endif actionEvent((QActionEvent*)event); break; #endif case QEvent::KeyboardLayoutChange: { changeEvent(event); // inform children of the change QList<QObject*> childList = d->children; for (int i = 0; i < childList.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(childList.at(i)); if (w && w->isVisible() && !w->isWindow()) QApplication::sendEvent(w, event); } break; } #ifdef Q_WS_MAC case QEvent::MacGLWindowChange: d->needWindowChange = false; break; #endif case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: { #ifndef Q_WS_MAC QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event); const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().first(); if (touchPoint.isPrimary() || touchEvent->deviceType() == QTouchEvent::TouchPad) break; // fake a mouse event! QEvent::Type eventType = QEvent::None; switch (touchEvent->type()) { case QEvent::TouchBegin: eventType = QEvent::MouseButtonPress; break; case QEvent::TouchUpdate: eventType = QEvent::MouseMove; break; case QEvent::TouchEnd: eventType = QEvent::MouseButtonRelease; break; default: Q_ASSERT(!true); break; } if (eventType == QEvent::None) break; QMouseEvent mouseEvent(eventType, touchPoint.pos().toPoint(), touchPoint.screenPos().toPoint(), Qt::LeftButton, Qt::LeftButton, touchEvent->modifiers()); (void) QApplication::sendEvent(this, &mouseEvent); #endif // Q_WS_MAC break; } #ifndef QT_NO_GESTURES case QEvent::Gesture: event->ignore(); break; #endif #ifndef QT_NO_PROPERTIES case QEvent::DynamicPropertyChange: { const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName(); if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) { uint value = property(propName.constData()).toUInt(); if (!d->extra) d->createExtra(); const char axis = propName.at(12); if (axis == 'X') d->extra->customDpiX = value; else if (axis == 'Y') d->extra->customDpiY = value; d->updateFont(d->data.fnt); } // fall through } #endif default: return QObject::event(event); } return true; } /*! This event handler can be reimplemented to handle state changes. The state being changed in this event can be retrieved through the \a event supplied. Change events include: QEvent::ToolBarChange, QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange, QEvent::StyleChange, QEvent::PaletteChange, QEvent::WindowTitleChange, QEvent::IconTextChange, QEvent::ModifiedChange, QEvent::MouseTrackingChange, QEvent::ParentChange, QEvent::WindowStateChange, QEvent::LanguageChange, QEvent::LocaleChange, QEvent::LayoutDirectionChange. */ void QWidget::changeEvent(QEvent * event) { switch(event->type()) { case QEvent::EnabledChange: update(); #ifndef QT_NO_ACCESSIBILITY QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged); #endif break; case QEvent::FontChange: case QEvent::StyleChange: { Q_D(QWidget); update(); updateGeometry(); if (d->layout) d->layout->invalidate(); #ifdef Q_WS_QWS if (isWindow()) d->data.fstrut_dirty = true; #endif break; } case QEvent::PaletteChange: update(); break; #ifdef Q_WS_MAC case QEvent::MacSizeChange: updateGeometry(); break; case QEvent::ToolTipChange: case QEvent::MouseTrackingChange: qt_mac_update_mouseTracking(this); break; #endif default: break; } } /*! This event handler, for event \a event, can be reimplemented in a subclass to receive mouse move events for the widget. If mouse tracking is switched off, mouse move events only occur if a mouse button is pressed while the mouse is being moved. If mouse tracking is switched on, mouse move events occur even if no mouse button is pressed. QMouseEvent::pos() reports the position of the mouse cursor, relative to this widget. For press and release events, the position is usually the same as the position of the last mouse move event, but it might be different if the user's hand shakes. This is a feature of the underlying window system, not Qt. If you want to show a tooltip immediately, while the mouse is moving (e.g., to get the mouse coordinates with QMouseEvent::pos() and show them as a tooltip), you must first enable mouse tracking as described above. Then, to ensure that the tooltip is updated immediately, you must call QToolTip::showText() instead of setToolTip() in your implementation of mouseMoveEvent(). \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example} */ void QWidget::mouseMoveEvent(QMouseEvent *event) { event->ignore(); } /*! This event handler, for event \a event, can be reimplemented in a subclass to receive mouse press events for the widget. If you create new widgets in the mousePressEvent() the mouseReleaseEvent() may not end up where you expect, depending on the underlying window system (or X11 window manager), the widgets' location and maybe more. The default implementation implements the closing of popup widgets when you click outside the window. For other widget types it does nothing. \sa mouseReleaseEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), event(), QMouseEvent, {Scribble Example} */ void QWidget::mousePressEvent(QMouseEvent *event) { event->ignore(); if ((windowType() == Qt::Popup)) { event->accept(); QWidget* w; while ((w = QApplication::activePopupWidget()) && w != this){ w->close(); if (QApplication::activePopupWidget() == w) // widget does not want to disappear w->hide(); // hide at least } if (!rect().contains(event->pos())){ close(); } } } /*! This event handler, for event \a event, can be reimplemented in a subclass to receive mouse release events for the widget. \sa mousePressEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), event(), QMouseEvent, {Scribble Example} */ void QWidget::mouseReleaseEvent(QMouseEvent *event) { event->ignore(); } /*! This event handler, for event \a event, can be reimplemented in a subclass to receive mouse double click events for the widget. The default implementation generates a normal mouse press event. \note The widget will also receive mouse press and mouse release events in addition to the double click event. It is up to the developer to ensure that the application interprets these events correctly. \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(), event(), QMouseEvent */ void QWidget::mouseDoubleClickEvent(QMouseEvent *event) { mousePressEvent(event); // try mouse press event } #ifndef QT_NO_WHEELEVENT /*! This event handler, for event \a event, can be reimplemented in a subclass to receive wheel events for the widget. If you reimplement this handler, it is very important that you \link QWheelEvent ignore()\endlink the event if you do not handle it, so that the widget's parent can interpret it. The default implementation ignores the event. \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(), QWheelEvent */ void QWidget::wheelEvent(QWheelEvent *event) { event->ignore(); } #endif // QT_NO_WHEELEVENT #ifndef QT_NO_TABLETEVENT /*! This event handler, for event \a event, can be reimplemented in a subclass to receive tablet events for the widget. If you reimplement this handler, it is very important that you \link QTabletEvent ignore()\endlink the event if you do not handle it, so that the widget's parent can interpret it. The default implementation ignores the event. \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(), QTabletEvent */ void QWidget::tabletEvent(QTabletEvent *event) { event->ignore(); } #endif // QT_NO_TABLETEVENT /*! This event handler, for event \a event, can be reimplemented in a subclass to receive key press events for the widget. A widget must call setFocusPolicy() to accept focus initially and have focus in order to receive a key press event. If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key. The default implementation closes popup widgets if the user presses Esc. Otherwise the event is ignored, so that the widget's parent can interpret it. Note that QKeyEvent starts with isAccepted() == true, so you do not need to call QKeyEvent::accept() - just do not call the base class implementation if you act upon the key. \sa keyReleaseEvent(), setFocusPolicy(), focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example} */ void QWidget::keyPressEvent(QKeyEvent *event) { if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) { event->accept(); close(); } else { event->ignore(); } } /*! This event handler, for event \a event, can be reimplemented in a subclass to receive key release events for the widget. A widget must \link setFocusPolicy() accept focus\endlink initially and \link hasFocus() have focus\endlink in order to receive a key release event. If you reimplement this handler, it is very important that you call the base class implementation if you do not act upon the key. The default implementation ignores the event, so that the widget's parent can interpret it. Note that QKeyEvent starts with isAccepted() == true, so you do not need to call QKeyEvent::accept() - just do not call the base class implementation if you act upon the key. \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(), focusInEvent(), focusOutEvent(), event(), QKeyEvent */ void QWidget::keyReleaseEvent(QKeyEvent *event) { event->ignore(); } /*! \fn void QWidget::focusInEvent(QFocusEvent *event) This event handler can be reimplemented in a subclass to receive keyboard focus events (focus received) for the widget. The event is passed in the \a event parameter A widget normally must setFocusPolicy() to something other than Qt::NoFocus in order to receive focus events. (Note that the application programmer can call setFocus() on any widget, even those that do not normally accept focus.) The default implementation updates the widget (except for windows that do not specify a focusPolicy()). \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(), keyReleaseEvent(), event(), QFocusEvent */ void QWidget::focusInEvent(QFocusEvent *) { if (focusPolicy() != Qt::NoFocus || !isWindow()) { update(); } } /*! \fn void QWidget::focusOutEvent(QFocusEvent *event) This event handler can be reimplemented in a subclass to receive keyboard focus events (focus lost) for the widget. The events is passed in the \a event parameter. A widget normally must setFocusPolicy() to something other than Qt::NoFocus in order to receive focus events. (Note that the application programmer can call setFocus() on any widget, even those that do not normally accept focus.) The default implementation updates the widget (except for windows that do not specify a focusPolicy()). \sa focusInEvent(), setFocusPolicy(), keyPressEvent(), keyReleaseEvent(), event(), QFocusEvent */ void QWidget::focusOutEvent(QFocusEvent *) { if (focusPolicy() != Qt::NoFocus || !isWindow()) update(); } /*! \fn void QWidget::enterEvent(QEvent *event) This event handler can be reimplemented in a subclass to receive widget enter events which are passed in the \a event parameter. An event is sent to the widget when the mouse cursor enters the widget. \sa leaveEvent(), mouseMoveEvent(), event() */ void QWidget::enterEvent(QEvent *) { } /*! \fn void QWidget::leaveEvent(QEvent *event) This event handler can be reimplemented in a subclass to receive widget leave events which are passed in the \a event parameter. A leave event is sent to the widget when the mouse cursor leaves the widget. \sa enterEvent(), mouseMoveEvent(), event() */ void QWidget::leaveEvent(QEvent *) { } /*! \fn void QWidget::paintEvent(QPaintEvent *event) This event handler can be reimplemented in a subclass to receive paint events passed in \a event. A paint event is a request to repaint all or part of a widget. It can happen for one of the following reasons: \list \o repaint() or update() was invoked, \o the widget was obscured and has now been uncovered, or \o many other reasons. \endlist Many widgets can simply repaint their entire surface when asked to, but some slow widgets need to optimize by painting only the requested region: QPaintEvent::region(). This speed optimization does not change the result, as painting is clipped to that region during event processing. QListView and QTableView do this, for example. Qt also tries to speed up painting by merging multiple paint events into one. When update() is called several times or the window system sends several paint events, Qt merges these events into one event with a larger region (see QRegion::united()). The repaint() function does not permit this optimization, so we suggest using update() whenever possible. When the paint event occurs, the update region has normally been erased, so you are painting on the widget's background. The background can be set using setBackgroundRole() and setPalette(). Since Qt 4.0, QWidget automatically double-buffers its painting, so there is no need to write double-buffering code in paintEvent() to avoid flicker. \bold{Note for the X11 platform}: It is possible to toggle global double buffering by calling \c qt_x11_set_global_double_buffer(). For example, \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14 \note Generally, you should refrain from calling update() or repaint() \bold{inside} a paintEvent(). For example, calling update() or repaint() on children inside a paintevent() results in undefined behavior; the child may or may not get a paint event. \warning If you are using a custom paint engine without Qt's backingstore, Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will never be called; the backingstore will be used instead. \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent, {Analog Clock Example} */ void QWidget::paintEvent(QPaintEvent *) { } /*! \fn void QWidget::moveEvent(QMoveEvent *event) This event handler can be reimplemented in a subclass to receive widget move events which are passed in the \a event parameter. When the widget receives this event, it is already at the new position. The old position is accessible through QMoveEvent::oldPos(). \sa resizeEvent(), event(), move(), QMoveEvent */ void QWidget::moveEvent(QMoveEvent *) { } /*! This event handler can be reimplemented in a subclass to receive widget resize events which are passed in the \a event parameter. When resizeEvent() is called, the widget already has its new geometry. The old size is accessible through QResizeEvent::oldSize(). The widget will be erased and receive a paint event immediately after processing the resize event. No drawing need be (or should be) done inside this handler. \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(), {Scribble Example} */ void QWidget::resizeEvent(QResizeEvent * /* event */) { } #ifndef QT_NO_ACTION /*! \fn void QWidget::actionEvent(QActionEvent *event) This event handler is called with the given \a event whenever the widget's actions are changed. \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent */ void QWidget::actionEvent(QActionEvent *) { } #endif /*! This event handler is called with the given \a event when Qt receives a window close request for a top-level widget from the window system. By default, the event is accepted and the widget is closed. You can reimplement this function to change the way the widget responds to window close requests. For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()} on all events. Main window applications typically use reimplementations of this function to check whether the user's work has been saved and ask for permission before closing. For example, the \l{Application Example} uses a helper function to determine whether or not to close the window: \snippet mainwindows/application/mainwindow.cpp 3 \snippet mainwindows/application/mainwindow.cpp 4 \sa event(), hide(), close(), QCloseEvent, {Application Example} */ void QWidget::closeEvent(QCloseEvent *event) { event->accept(); } #ifndef QT_NO_CONTEXTMENU /*! This event handler, for event \a event, can be reimplemented in a subclass to receive widget context menu events. The handler is called when the widget's \l contextMenuPolicy is Qt::DefaultContextMenu. The default implementation ignores the context event. See the \l QContextMenuEvent documentation for more details. \sa event(), QContextMenuEvent customContextMenuRequested() */ void QWidget::contextMenuEvent(QContextMenuEvent *event) { event->ignore(); } #endif // QT_NO_CONTEXTMENU /*! This event handler, for event \a event, can be reimplemented in a subclass to receive Input Method composition events. This handler is called when the state of the input method changes. Note that when creating custom text editing widgets, the Qt::WA_InputMethodEnabled window attribute must be set explicitly (using the setAttribute() function) in order to receive input method events. The default implementation calls event->ignore(), which rejects the Input Method event. See the \l QInputMethodEvent documentation for more details. \sa event(), QInputMethodEvent */ void QWidget::inputMethodEvent(QInputMethodEvent *event) { event->ignore(); } /*! This method is only relevant for input widgets. It is used by the input method to query a set of properties of the widget to be able to support complex input method operations as support for surrounding text and reconversions. \a query specifies which property is queried. \sa inputMethodEvent(), QInputMethodEvent, QInputContext, inputMethodHints */ QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const { switch(query) { case Qt::ImMicroFocus: return QRect(width()/2, 0, 1, height()); case Qt::ImFont: return font(); case Qt::ImAnchorPosition: // Fallback. return inputMethodQuery(Qt::ImCursorPosition); default: return QVariant(); } } /*! \property QWidget::inputMethodHints \brief What input method specific hints the widget has. This is only relevant for input widgets. It is used by the input method to retrieve hints as to how the input method should operate. For example, if the Qt::ImhFormattedNumbersOnly flag is set, the input method may change its visual components to reflect that only numbers can be entered. \note The flags are only hints, so the particular input method implementation is free to ignore them. If you want to be sure that a certain type of characters are entered, you should also set a QValidator on the widget. The default value is Qt::ImhNone. \since 4.6 \sa inputMethodQuery(), QInputContext */ Qt::InputMethodHints QWidget::inputMethodHints() const { #ifndef QT_NO_IM const QWidgetPrivate *priv = d_func(); while (priv->inheritsInputMethodHints) { priv = priv->q_func()->parentWidget()->d_func(); Q_ASSERT(priv); } return priv->imHints; #else //QT_NO_IM return 0; #endif //QT_NO_IM } void QWidget::setInputMethodHints(Qt::InputMethodHints hints) { #ifndef QT_NO_IM Q_D(QWidget); d->imHints = hints; // Optimization to update input context only it has already been created. if (d->ic || qApp->d_func()->inputContext) { QInputContext *ic = inputContext(); if (ic) ic->update(); } #endif //QT_NO_IM } #ifndef QT_NO_DRAGANDDROP /*! \fn void QWidget::dragEnterEvent(QDragEnterEvent *event) This event handler is called when a drag is in progress and the mouse enters this widget. The event is passed in the \a event parameter. If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag move events}. See the \link dnd.html Drag-and-drop documentation\endlink for an overview of how to provide drag-and-drop in your application. \sa QDrag, QDragEnterEvent */ void QWidget::dragEnterEvent(QDragEnterEvent *) { } /*! \fn void QWidget::dragMoveEvent(QDragMoveEvent *event) This event handler is called if a drag is in progress, and when any of the following conditions occur: the cursor enters this widget, the cursor moves within this widget, or a modifier key is pressed on the keyboard while this widget has the focus. The event is passed in the \a event parameter. See the \link dnd.html Drag-and-drop documentation\endlink for an overview of how to provide drag-and-drop in your application. \sa QDrag, QDragMoveEvent */ void QWidget::dragMoveEvent(QDragMoveEvent *) { } /*! \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event) This event handler is called when a drag is in progress and the mouse leaves this widget. The event is passed in the \a event parameter. See the \link dnd.html Drag-and-drop documentation\endlink for an overview of how to provide drag-and-drop in your application. \sa QDrag, QDragLeaveEvent */ void QWidget::dragLeaveEvent(QDragLeaveEvent *) { } /*! \fn void QWidget::dropEvent(QDropEvent *event) This event handler is called when the drag is dropped on this widget. The event is passed in the \a event parameter. See the \link dnd.html Drag-and-drop documentation\endlink for an overview of how to provide drag-and-drop in your application. \sa QDrag, QDropEvent */ void QWidget::dropEvent(QDropEvent *) { } #endif // QT_NO_DRAGANDDROP /*! \fn void QWidget::showEvent(QShowEvent *event) This event handler can be reimplemented in a subclass to receive widget show events which are passed in the \a event parameter. Non-spontaneous show events are sent to widgets immediately before they are shown. The spontaneous show events of windows are delivered afterwards. Note: A widget receives spontaneous show and hide events when its mapping status is changed by the window system, e.g. a spontaneous hide event when the user minimizes the window, and a spontaneous show event when the window is restored again. After receiving a spontaneous hide event, a widget is still considered visible in the sense of isVisible(). \sa visible, event(), QShowEvent */ void QWidget::showEvent(QShowEvent *) { } /*! \fn void QWidget::hideEvent(QHideEvent *event) This event handler can be reimplemented in a subclass to receive widget hide events. The event is passed in the \a event parameter. Hide events are sent to widgets immediately after they have been hidden. Note: A widget receives spontaneous show and hide events when its mapping status is changed by the window system, e.g. a spontaneous hide event when the user minimizes the window, and a spontaneous show event when the window is restored again. After receiving a spontaneous hide event, a widget is still considered visible in the sense of isVisible(). \sa visible, event(), QHideEvent */ void QWidget::hideEvent(QHideEvent *) { } /* \fn QWidget::x11Event(MSG *) This special event handler can be reimplemented in a subclass to receive native X11 events. In your reimplementation of this function, if you want to stop Qt from handling the event, return true. If you return false, this native event is passed back to Qt, which translates it into a Qt event and sends it to the widget. \note Events are only delivered to this event handler if the widget is native. \warning This function is not portable. \sa QApplication::x11EventFilter(), QWidget::winId() */ #if defined(Q_WS_MAC) /*! \fn bool QWidget::macEvent(EventHandlerCallRef caller, EventRef event) This special event handler can be reimplemented in a subclass to receive native Macintosh events. The parameters are a bit different depending if Qt is build against Carbon or Cocoa. In Carbon, \a caller and \a event are the corresponding EventHandlerCallRef and EventRef that correspond to the Carbon event handlers that are installed. In Cocoa, \a caller is always 0 and the EventRef is the EventRef generated from the NSEvent. In your reimplementation of this function, if you want to stop the event being handled by Qt, return true. If you return false, this native event is passed back to Qt, which translates the event into a Qt event and sends it to the widget. \warning This function is not portable. \warning This function was not called inside of Qt until Qt 4.4. If you need compatibility with earlier versions of Qt, consider QApplication::macEventFilter() instead. \sa QApplication::macEventFilter() */ bool QWidget::macEvent(EventHandlerCallRef, EventRef) { return false; } #endif #if defined(Q_WS_WIN) /*! This special event handler can be reimplemented in a subclass to receive native Windows events which are passed in the \a message parameter. In your reimplementation of this function, if you want to stop the event being handled by Qt, return true and set \a result to the value that the window procedure should return. If you return false, this native event is passed back to Qt, which translates the event into a Qt event and sends it to the widget. \warning This function is not portable. \sa QApplication::winEventFilter() */ bool QWidget::winEvent(MSG *message, long *result) { Q_UNUSED(message); Q_UNUSED(result); return false; } #endif #if defined(Q_WS_X11) /*! \fn bool QWidget::x11Event(XEvent *event) This special event handler can be reimplemented in a subclass to receive native X11 events passed in the \a event parameter. In your reimplementation of this function, if you want to stop Qt from handling the event, return true. If you return false, this native event is passed back to Qt, which translates it into a Qt event and sends it to the widget. \note Events are only delivered to this event handler if the widget is native. \warning This function is not portable. \sa QApplication::x11EventFilter(), QWidget::winId() */ bool QWidget::x11Event(XEvent *) { return false; } #endif #if defined(Q_WS_QWS) /*! \fn bool QWidget::qwsEvent(QWSEvent *event) This special event handler can be reimplemented in a subclass to receive native Qt for Embedded Linux events which are passed in the \a event parameter. In your reimplementation of this function, if you want to stop the event being handled by Qt, return true. If you return false, this native event is passed back to Qt, which translates the event into a Qt event and sends it to the widget. \warning This function is not portable. \sa QApplication::qwsEventFilter() */ bool QWidget::qwsEvent(QWSEvent *) { return false; } #endif /*! Ensures that the widget has been polished by QStyle (i.e., has a proper font and palette). QWidget calls this function after it has been fully constructed but before it is shown the very first time. You can call this function if you want to ensure that the widget is polished before doing an operation, e.g., the correct font size might be needed in the widget's sizeHint() reimplementation. Note that this function \e is called from the default implementation of sizeHint(). Polishing is useful for final initialization that must happen after all constructors (from base classes as well as from subclasses) have been called. If you need to change some settings when a widget is polished, reimplement event() and handle the QEvent::Polish event type. \bold{Note:} The function is declared const so that it can be called from other const functions (e.g., sizeHint()). \sa event() */ void QWidget::ensurePolished() const { Q_D(const QWidget); const QMetaObject *m = metaObject(); if (m == d->polished) return; d->polished = m; QEvent e(QEvent::Polish); QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e); // polish children after 'this' QList<QObject*> children = d->children; for (int i = 0; i < children.size(); ++i) { QObject *o = children.at(i); if(!o->isWidgetType()) continue; if (QWidget *w = qobject_cast<QWidget *>(o)) w->ensurePolished(); } if (d->parent && d->sendChildEvents) { QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this)); QCoreApplication::sendEvent(d->parent, &e); } } /*! Returns the mask currently set on a widget. If no mask is set the return value will be an empty region. \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example} */ QRegion QWidget::mask() const { Q_D(const QWidget); return d->extra ? d->extra->mask : QRegion(); } /*! Returns the layout manager that is installed on this widget, or 0 if no layout manager is installed. The layout manager sets the geometry of the widget's children that have been added to the layout. \sa setLayout(), sizePolicy(), {Layout Management} */ QLayout *QWidget::layout() const { return d_func()->layout; } /*! \fn void QWidget::setLayout(QLayout *layout) Sets the layout manager for this widget to \a layout. If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout. If \a layout is the layout manger on a different widget, setLayout() will reparent the layout and make it the layout manager for this widget. Example: \snippet examples/uitools/textfinder/textfinder.cpp 3b An alternative to calling this function is to pass this widget to the layout's constructor. The QWidget will take ownership of \a layout. \sa layout(), {Layout Management} */ void QWidget::setLayout(QLayout *l) { if (!l) { qWarning("QWidget::setLayout: Cannot set layout to 0"); return; } if (layout()) { if (layout() != l) qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a" " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(), objectName().toLocal8Bit().data()); return; } QObject *oldParent = l->parent(); if (oldParent && oldParent != this) { if (oldParent->isWidgetType()) { // Steal the layout off a widget parent. Takes effect when // morphing laid-out container widgets in Designer. QWidget *oldParentWidget = static_cast<QWidget *>(oldParent); oldParentWidget->takeLayout(); } else { qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent", l->objectName().toLocal8Bit().data(), metaObject()->className(), objectName().toLocal8Bit().data()); return; } } Q_D(QWidget); l->d_func()->topLevel = true; d->layout = l; if (oldParent != this) { l->setParent(this); l->d_func()->reparentChildWidgets(this); l->invalidate(); } if (isWindow() && d->maybeTopData()) d->topData()->sizeAdjusted = false; } /*! \fn QLayout *QWidget::takeLayout() Remove the layout from the widget. \since 4.5 */ QLayout *QWidget::takeLayout() { Q_D(QWidget); QLayout *l = layout(); if (!l) return 0; d->layout = 0; l->setParent(0); return l; } /*! \property QWidget::sizePolicy \brief the default layout behavior of the widget If there is a QLayout that manages this widget's children, the size policy specified by that layout is used. If there is no such QLayout, the result of this function is used. The default policy is Preferred/Preferred, which means that the widget can be freely resized, but prefers to be the size sizeHint() returns. Button-like widgets set the size policy to specify that they may stretch horizontally, but are fixed vertically. The same applies to lineedit controls (such as QLineEdit, QSpinBox or an editable QComboBox) and other horizontally orientated widgets (such as QProgressBar). QToolButton's are normally square, so they allow growth in both directions. Widgets that support different directions (such as QSlider, QScrollBar or QHeader) specify stretching in the respective direction only. Widgets that can provide scroll bars (usually subclasses of QScrollArea) tend to specify that they can use additional space, and that they can make do with less than sizeHint(). \sa sizeHint() QLayout QSizePolicy updateGeometry() */ QSizePolicy QWidget::sizePolicy() const { Q_D(const QWidget); return d->size_policy; } void QWidget::setSizePolicy(QSizePolicy policy) { Q_D(QWidget); setAttribute(Qt::WA_WState_OwnSizePolicy); if (policy == d->size_policy) return; d->size_policy = policy; #ifndef QT_NO_GRAPHICSVIEW if (QWExtra *extra = d->extra) { if (extra->proxyWidget) extra->proxyWidget->setSizePolicy(policy); } #endif updateGeometry(); if (isWindow() && d->maybeTopData()) d->topData()->sizeAdjusted = false; } /*! \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical) \overload Sets the size policy of the widget to \a horizontal and \a vertical, with standard stretch and no height-for-width. \sa QSizePolicy::QSizePolicy() */ /*! Returns the preferred height for this widget, given the width \a w. If this widget has a layout, the default implementation returns the layout's preferred height. if there is no layout, the default implementation returns -1 indicating that the preferred height does not depend on the width. */ int QWidget::heightForWidth(int w) const { if (layout() && layout()->hasHeightForWidth()) return layout()->totalHeightForWidth(w); return -1; } /*! \internal *virtual private* This is a bit hackish, but ideally we would have created a virtual function in the public API (however, too late...) so that subclasses could reimplement their own function. Instead we add a virtual function to QWidgetPrivate. ### Qt5: move to public class and make virtual */ bool QWidgetPrivate::hasHeightForWidth() const { return layout ? layout->hasHeightForWidth() : size_policy.hasHeightForWidth(); } /*! \fn QWidget *QWidget::childAt(int x, int y) const Returns the visible child widget at the position (\a{x}, \a{y}) in the widget's coordinate system. If there is no visible child widget at the specified position, the function returns 0. */ /*! \overload Returns the visible child widget at point \a p in the widget's own coordinate system. */ QWidget *QWidget::childAt(const QPoint &p) const { return d_func()->childAt_helper(p, false); } QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const { if (children.isEmpty()) return 0; #ifdef Q_WS_MAC Q_Q(const QWidget); // Unified tool bars on the Mac require special handling since they live outside // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q) && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac(); if (includeFrame) return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame); #endif if (!pointInsideRectAndMask(p)) return 0; return childAtRecursiveHelper(p, ignoreChildrenInDestructor); } QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const { #ifndef Q_WS_MAC Q_UNUSED(includeFrame); #endif for (int i = children.size() - 1; i >= 0; --i) { QWidget *child = qobject_cast<QWidget *>(children.at(i)); if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents) || (ignoreChildrenInDestructor && child->data->in_destructor)) { continue; } // Map the point 'p' from parent coordinates to child coordinates. QPoint childPoint = p; #ifdef Q_WS_MAC // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar. // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal // QWidget::mapFromParent won't do the trick. if (includeFrame && qobject_cast<QToolBar *>(child)) childPoint = qt_mac_nativeMapFromParent(child, p); else #endif childPoint -= child->data->crect.topLeft(); // Check if the point hits the child. if (!child->d_func()->pointInsideRectAndMask(childPoint)) continue; // Do the same for the child's descendants. if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor)) return w; // We have found our target; namely the child at position 'p'. return child; } return 0; } void QWidgetPrivate::updateGeometry_helper(bool forceUpdate) { Q_Q(QWidget); if (widgetItem) widgetItem->invalidateSizeCache(); QWidget *parent; if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) { if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) { if (parent->d_func()->layout) parent->d_func()->layout->invalidate(); else if (parent->isVisible()) QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest)); } } } /*! Notifies the layout system that this widget has changed and may need to change geometry. Call this function if the sizeHint() or sizePolicy() have changed. For explicitly hidden widgets, updateGeometry() is a no-op. The layout system will be notified as soon as the widget is shown. */ void QWidget::updateGeometry() { Q_D(QWidget); d->updateGeometry_helper(false); } /*! \property QWidget::windowFlags Window flags are a combination of a type (e.g. Qt::Dialog) and zero or more hints to the window system (e.g. Qt::FramelessWindowHint). If the widget had type Qt::Widget or Qt::SubWindow and becomes a window (Qt::Window, Qt::Dialog, etc.), it is put at position (0, 0) on the desktop. If the widget is a window and becomes a Qt::Widget or Qt::SubWindow, it is put at position (0, 0) relative to its parent widget. \note This function calls setParent() when changing the flags for a window, causing the widget to be hidden. You must call show() to make the widget visible again.. \sa windowType(), {Window Flags Example} */ void QWidget::setWindowFlags(Qt::WindowFlags flags) { if (data->window_flags == flags) return; Q_D(QWidget); if ((data->window_flags | flags) & Qt::Window) { // the old type was a window and/or the new type is a window QPoint oldPos = pos(); bool visible = isVisible(); setParent(parentWidget(), flags); // if both types are windows or neither of them are, we restore // the old position if (!((data->window_flags ^ flags) & Qt::Window) && (visible || testAttribute(Qt::WA_Moved))) { move(oldPos); } // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated. d->adjustQuitOnCloseAttribute(); } else { data->window_flags = flags; } } /*! Sets the window flags for the widget to \a flags, \e without telling the window system. \warning Do not call this function unless you really know what you're doing. \sa setWindowFlags() */ void QWidget::overrideWindowFlags(Qt::WindowFlags flags) { data->window_flags = flags; } /*! \fn Qt::WindowType QWidget::windowType() const Returns the window type of this widget. This is identical to windowFlags() & Qt::WindowType_Mask. \sa windowFlags */ /*! Sets the parent of the widget to \a parent, and resets the window flags. The widget is moved to position (0, 0) in its new parent. If the new parent widget is in a different window, the reparented widget and its children are appended to the end of the \l{setFocusPolicy()}{tab chain} of the new parent widget, in the same internal order as before. If one of the moved widgets had keyboard focus, setParent() calls clearFocus() for that widget. If the new parent widget is in the same window as the old parent, setting the parent doesn't change the tab order or keyboard focus. If the "new" parent widget is the old parent widget, this function does nothing. \note The widget becomes invisible as part of changing its parent, even if it was previously visible. You must call show() to make the widget visible again. \warning It is very unlikely that you will ever need this function. If you have a widget that changes its content dynamically, it is far easier to use \l QStackedWidget. \sa setWindowFlags() */ void QWidget::setParent(QWidget *parent) { if (parent == parentWidget()) return; setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask); } /*! \overload This function also takes widget flags, \a f as an argument. */ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f) { Q_D(QWidget); d->inSetParent = true; bool resized = testAttribute(Qt::WA_Resized); bool wasCreated = testAttribute(Qt::WA_WState_Created); QWidget *oldtlw = window(); QWidget *desktopWidget = 0; if (parent && parent->windowType() == Qt::Desktop) desktopWidget = parent; bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget; #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN) if (newParent && parent && !desktopWidget) { if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA) // On Mac, toolbars inside the unified title bar will never overlap with // siblings in the content view. So we skip enforce native siblings in that case && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow() #endif // Q_WS_MAC && QT_MAC_USE_COCOA ) parent->d_func()->enforceNativeChildren(); else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen)) setAttribute(Qt::WA_NativeWindow); } #endif if (wasCreated) { if (!testAttribute(Qt::WA_WState_Hidden)) { hide(); setAttribute(Qt::WA_WState_ExplicitShowHide, false); } if (newParent) { QEvent e(QEvent::ParentAboutToChange); QApplication::sendEvent(this, &e); } } if (newParent && isAncestorOf(focusWidget())) focusWidget()->clearFocus(); QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData(); QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStore : 0; d->setParent_sys(parent, f); QTLWExtra *topExtra = window()->d_func()->maybeTopData(); QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStore : 0; if (oldBsTracker && oldBsTracker != bsTracker) oldBsTracker->unregisterWidgetSubtree(this); if (desktopWidget) parent = 0; #ifdef Q_BACKINGSTORE_SUBSURFACES QTLWExtra *extra = d->maybeTopData(); QWindowSurface *windowSurface = (extra ? extra->windowSurface : 0); if (newParent && windowSurface) { QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore(); if (oldBs) oldBs->subSurfaces.removeAll(windowSurface); if (parent) { QWidgetBackingStore *newBs = parent->d_func()->maybeBackingStore(); if (newBs) newBs->subSurfaces.append(windowSurface); } } #endif if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) { if (newParent) oldBs->removeDirtyWidget(this); // Move the widget and all its static children from // the old backing store to the new one. oldBs->moveStaticWidgets(this); } if ((QApplicationPrivate::app_compile_version < 0x040200 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation)) && !testAttribute(Qt::WA_WState_Created)) create(); d->reparentFocusWidgets(oldtlw); setAttribute(Qt::WA_Resized, resized); if (!testAttribute(Qt::WA_StyleSheet) && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) { d->resolveFont(); d->resolvePalette(); } d->resolveLayoutDirection(); d->resolveLocale(); // Note: GL widgets under WGL or EGL will always need a ParentChange // event to handle recreation/rebinding of the GL context, hence the // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all // platforms). if (newParent #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES) || (f & Qt::MSWindowsOwnDC) #endif ) { // propagate enabled updates enabled state to non-windows if (!isWindow()) { if (!testAttribute(Qt::WA_ForceDisabled)) d->setEnabled_helper(parent ? parent->isEnabled() : true); if (!testAttribute(Qt::WA_ForceUpdatesDisabled)) d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true); } d->inheritStyle(); // send and post remaining QObject events if (parent && d->sendChildEvents) { QChildEvent e(QEvent::ChildAdded, this); QApplication::sendEvent(parent, &e); #ifdef QT3_SUPPORT if (parent->d_func()->pendingChildInsertedEvents.isEmpty()) { QApplication::postEvent(parent, new QEvent(QEvent::ChildInsertedRequest), Qt::HighEventPriority); } parent->d_func()->pendingChildInsertedEvents.append(this); #endif } //### already hidden above ---> must probably do something smart on the mac // #ifdef Q_WS_MAC // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp // if(!qt_mac_is_macdrawer(q)) //special case // q->setAttribute(Qt::WA_WState_Hidden); // #else // q->setAttribute(Qt::WA_WState_Hidden); //#endif if (parent && d->sendChildEvents && d->polished) { QChildEvent e(QEvent::ChildPolished, this); QCoreApplication::sendEvent(parent, &e); } QEvent e(QEvent::ParentChange); QApplication::sendEvent(this, &e); } if (!wasCreated) { if (isWindow() || parentWidget()->isVisible()) setAttribute(Qt::WA_WState_Hidden, true); else if (!testAttribute(Qt::WA_WState_ExplicitShowHide)) setAttribute(Qt::WA_WState_Hidden, false); } d->updateIsOpaque(); #ifndef QT_NO_GRAPHICSVIEW // Embed the widget into a proxy if the parent is embedded. // ### Doesn't handle reparenting out of an embedded widget. if (oldtlw->graphicsProxyWidget()) { if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw)) ancestorProxy->d_func()->unembedSubWindow(this); } if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) { if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent)) ancestorProxy->d_func()->embedSubWindow(this); } #endif d->inSetParent = false; } /*! Scrolls the widget including its children \a dx pixels to the right and \a dy downward. Both \a dx and \a dy may be negative. After scrolling, the widgets will receive paint events for the areas that need to be repainted. For widgets that Qt knows to be opaque, this is only the newly exposed parts. For example, if an opaque widget is scrolled 8 pixels to the left, only an 8-pixel wide stripe at the right edge needs updating. Since widgets propagate the contents of their parents by default, you need to set the \l autoFillBackground property, or use setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make a widget opaque. For widgets that use contents propagation, a scroll will cause an update of the entire scroll area. \sa {Transparency and Double Buffering} */ void QWidget::scroll(int dx, int dy) { if ((!updatesEnabled() && children().size() == 0) || !isVisible()) return; if (dx == 0 && dy == 0) return; Q_D(QWidget); #ifndef QT_NO_GRAPHICSVIEW if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) { // Graphics View maintains its own dirty region as a list of rects; // until we can connect item updates directly to the view, we must // separately add a translated dirty region. if (!d->dirty.isEmpty()) { foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects()) proxy->update(rect); } proxy->scroll(dx, dy, proxy->subWidgetRect(this)); return; } #endif d->setDirtyOpaqueRegion(); d->scroll_sys(dx, dy); } /*! \overload This version only scrolls \a r and does not move the children of the widget. If \a r is empty or invalid, the result is undefined. \sa QScrollArea */ void QWidget::scroll(int dx, int dy, const QRect &r) { if ((!updatesEnabled() && children().size() == 0) || !isVisible()) return; if (dx == 0 && dy == 0) return; Q_D(QWidget); #ifndef QT_NO_GRAPHICSVIEW if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) { // Graphics View maintains its own dirty region as a list of rects; // until we can connect item updates directly to the view, we must // separately add a translated dirty region. if (!d->dirty.isEmpty()) { foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects()) proxy->update(rect); } proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint())); return; } #endif d->scroll_sys(dx, dy, r); } /*! Repaints the widget directly by calling paintEvent() immediately, unless updates are disabled or the widget is hidden. We suggest only using repaint() if you need an immediate repaint, for example during animation. In almost all circumstances update() is better, as it permits Qt to optimize for speed and minimize flicker. \warning If you call repaint() in a function which may itself be called from paintEvent(), you may get infinite recursion. The update() function never causes recursion. \sa update(), paintEvent(), setUpdatesEnabled() */ void QWidget::repaint() { repaint(rect()); } /*! \overload This version repaints a rectangle (\a x, \a y, \a w, \a h) inside the widget. If \a w is negative, it is replaced with \c{width() - x}, and if \a h is negative, it is replaced width \c{height() - y}. */ void QWidget::repaint(int x, int y, int w, int h) { if (x > data->crect.width() || y > data->crect.height()) return; if (w < 0) w = data->crect.width() - x; if (h < 0) h = data->crect.height() - y; repaint(QRect(x, y, w, h)); } /*! \overload This version repaints a rectangle \a rect inside the widget. */ void QWidget::repaint(const QRect &rect) { Q_D(QWidget); if (testAttribute(Qt::WA_WState_ConfigPending)) { update(rect); return; } if (!isVisible() || !updatesEnabled() || rect.isEmpty()) return; if (hasBackingStoreSupport()) { #ifdef QT_MAC_USE_COCOA if (qt_widget_private(this)->isInUnifiedToolbar) { qt_widget_private(this)->unifiedSurface->renderToolbar(this, true); return; } #endif // QT_MAC_USE_COCOA QTLWExtra *tlwExtra = window()->d_func()->maybeTopData(); if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) { tlwExtra->inRepaint = true; tlwExtra->backingStore->markDirty(rect, this, true); tlwExtra->inRepaint = false; } } else { d->repaint_sys(rect); } } /*! \overload This version repaints a region \a rgn inside the widget. */ void QWidget::repaint(const QRegion &rgn) { Q_D(QWidget); if (testAttribute(Qt::WA_WState_ConfigPending)) { update(rgn); return; } if (!isVisible() || !updatesEnabled() || rgn.isEmpty()) return; if (hasBackingStoreSupport()) { #ifdef QT_MAC_USE_COCOA if (qt_widget_private(this)->isInUnifiedToolbar) { qt_widget_private(this)->unifiedSurface->renderToolbar(this, true); return; } #endif // QT_MAC_USE_COCOA QTLWExtra *tlwExtra = window()->d_func()->maybeTopData(); if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) { tlwExtra->inRepaint = true; tlwExtra->backingStore->markDirty(rgn, this, true); tlwExtra->inRepaint = false; } } else { d->repaint_sys(rgn); } } /*! Updates the widget unless updates are disabled or the widget is hidden. This function does not cause an immediate repaint; instead it schedules a paint event for processing when Qt returns to the main event loop. This permits Qt to optimize for more speed and less flicker than a call to repaint() does. Calling update() several times normally results in just one paintEvent() call. Qt normally erases the widget's area before the paintEvent() call. If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is responsible for painting all its pixels with an opaque color. \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example} */ void QWidget::update() { update(rect()); } /*! \fn void QWidget::update(int x, int y, int w, int h) \overload This version updates a rectangle (\a x, \a y, \a w, \a h) inside the widget. */ /*! \overload This version updates a rectangle \a rect inside the widget. */ void QWidget::update(const QRect &rect) { if (!isVisible() || !updatesEnabled() || rect.isEmpty()) return; if (testAttribute(Qt::WA_WState_InPaintEvent)) { QApplication::postEvent(this, new QUpdateLaterEvent(rect)); return; } if (hasBackingStoreSupport()) { #ifdef QT_MAC_USE_COCOA if (qt_widget_private(this)->isInUnifiedToolbar) { qt_widget_private(this)->unifiedSurface->renderToolbar(this, true); return; } #endif // QT_MAC_USE_COCOA QTLWExtra *tlwExtra = window()->d_func()->maybeTopData(); if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) tlwExtra->backingStore->markDirty(rect, this); } else { d_func()->repaint_sys(rect); } } /*! \overload This version repaints a region \a rgn inside the widget. */ void QWidget::update(const QRegion &rgn) { if (!isVisible() || !updatesEnabled() || rgn.isEmpty()) return; if (testAttribute(Qt::WA_WState_InPaintEvent)) { QApplication::postEvent(this, new QUpdateLaterEvent(rgn)); return; } if (hasBackingStoreSupport()) { #ifdef QT_MAC_USE_COCOA if (qt_widget_private(this)->isInUnifiedToolbar) { qt_widget_private(this)->unifiedSurface->renderToolbar(this, true); return; } #endif // QT_MAC_USE_COCOA QTLWExtra *tlwExtra = window()->d_func()->maybeTopData(); if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) tlwExtra->backingStore->markDirty(rgn, this); } else { d_func()->repaint_sys(rgn); } } #ifdef QT3_SUPPORT /*! Clear the rectangle at point (\a x, \a y) of width \a w and height \a h. \warning This is best done in a paintEvent(). */ void QWidget::erase_helper(int x, int y, int w, int h) { if (testAttribute(Qt::WA_NoSystemBackground) || testAttribute(Qt::WA_UpdatesDisabled) || !testAttribute(Qt::WA_WState_Visible)) return; if (w < 0) w = data->crect.width() - x; if (h < 0) h = data->crect.height() - y; if (w != 0 && h != 0) { QPainter p(this); p.eraseRect(QRect(x, y, w, h)); } } /*! \overload Clear the given region, \a rgn. Drawing may only take place in a QPaintEvent. Overload paintEvent() to do your erasing and call update() to schedule a replaint whenever necessary. See also QPainter. */ void QWidget::erase(const QRegion& rgn) { if (testAttribute(Qt::WA_NoSystemBackground) || testAttribute(Qt::WA_UpdatesDisabled) || !testAttribute(Qt::WA_WState_Visible)) return; QPainter p(this); p.setClipRegion(rgn); p.eraseRect(rgn.boundingRect()); } void QWidget::drawText_helper(int x, int y, const QString &str) { if(!testAttribute(Qt::WA_WState_Visible)) return; QPainter paint(this); paint.drawText(x, y, str); } /*! Closes the widget. Use the no-argument overload instead. */ bool QWidget::close(bool alsoDelete) { QPointer<QWidget> that = this; bool accepted = close(); if (alsoDelete && accepted && that) deleteLater(); return accepted; } void QWidget::setIcon(const QPixmap &i) { setWindowIcon(i); } /*! Return's the widget's icon. Use windowIcon() instead. */ const QPixmap *QWidget::icon() const { Q_D(const QWidget); return (d->extra && d->extra->topextra) ? d->extra->topextra->iconPixmap : 0; } #endif // QT3_SUPPORT /*! \internal This just sets the corresponding attribute bit to 1 or 0 */ static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data, QWidgetPrivate *d) { if (attribute < int(8*sizeof(uint))) { if (on) data->widget_attributes |= (1<<attribute); else data->widget_attributes &= ~(1<<attribute); } else { const int x = attribute - 8*sizeof(uint); const int int_off = x / (8*sizeof(uint)); if (on) d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint)))); else d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint)))); } } /*! Sets the attribute \a attribute on this widget if \a on is true; otherwise clears the attribute. \sa testAttribute() */ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on) { if (testAttribute(attribute) == on) return; Q_D(QWidget); Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8), "QWidget::setAttribute(WidgetAttribute, bool)", "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute"); #ifdef Q_WS_WIN // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0 if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) { // see qwidget_win.cpp, ::paintEngine for details paintEngine(); if (d->noPaintOnScreen) return; } #endif setAttribute_internal(attribute, on, data, d); switch (attribute) { #ifndef QT_NO_DRAGANDDROP case Qt::WA_AcceptDrops: { if (on && !testAttribute(Qt::WA_DropSiteRegistered)) setAttribute(Qt::WA_DropSiteRegistered, true); else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))) setAttribute(Qt::WA_DropSiteRegistered, false); QEvent e(QEvent::AcceptDropsChange); QApplication::sendEvent(this, &e); break; } case Qt::WA_DropSiteRegistered: { d->registerDropSite(on); for (int i = 0; i < d->children.size(); ++i) { QWidget *w = qobject_cast<QWidget *>(d->children.at(i)); if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on) w->setAttribute(Qt::WA_DropSiteRegistered, on); } break; } #endif case Qt::WA_NoChildEventsForParent: d->sendChildEvents = !on; break; case Qt::WA_NoChildEventsFromChildren: d->receiveChildEvents = !on; break; case Qt::WA_MacBrushedMetal: #ifdef Q_WS_MAC d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly. // fall through since changing the metal attribute affects the opaque size grip. case Qt::WA_MacOpaqueSizeGrip: d->macUpdateOpaqueSizeGrip(); break; case Qt::WA_MacShowFocusRect: if (hasFocus()) { clearFocus(); setFocus(); } break; case Qt::WA_Hover: qt_mac_update_mouseTracking(this); break; #endif case Qt::WA_MacAlwaysShowToolWindow: #ifdef Q_WS_MAC d->macUpdateHideOnSuspend(); #endif break; case Qt::WA_MacNormalSize: case Qt::WA_MacSmallSize: case Qt::WA_MacMiniSize: #ifdef Q_WS_MAC { // We can only have one of these set at a time const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize, Qt::WA_MacMiniSize }; for (int i = 0; i < 3; ++i) { if (MacSizes[i] != attribute) setAttribute_internal(MacSizes[i], false, data, d); } d->macUpdateSizeAttribute(); } #endif break; case Qt::WA_ShowModal: if (!on) { if (isVisible()) QApplicationPrivate::leaveModal(this); // reset modality type to Modeless when clearing WA_ShowModal data->window_modality = Qt::NonModal; } else if (data->window_modality == Qt::NonModal) { // determine the modality type if it hasn't been set prior // to setting WA_ShowModal. set the default to WindowModal // if we are the child of a group leader; otherwise use // ApplicationModal. QWidget *w = parentWidget(); if (w) w = w->window(); while (w && !w->testAttribute(Qt::WA_GroupLeader)) { w = w->parentWidget(); if (w) w = w->window(); } data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader)) ? Qt::WindowModal : Qt::ApplicationModal; // Some window managers does not allow us to enter modal after the // window is showing. Therefore, to be consistent, we cannot call // QApplicationPrivate::enterModal(this) here. The window must be // hidden before changing modality. } if (testAttribute(Qt::WA_WState_Created)) { // don't call setModal_sys() before create_sys() d->setModal_sys(); } break; case Qt::WA_MouseTracking: { QEvent e(QEvent::MouseTrackingChange); QApplication::sendEvent(this, &e); break; } case Qt::WA_NativeWindow: { #ifndef QT_NO_IM QWidget *focusWidget = d->effectiveFocusWidget(); QInputContext *ic = 0; if (on && !internalWinId() && hasFocus() && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) { ic = focusWidget->d_func()->inputContext(); if (ic) { ic->reset(); ic->setFocusWidget(0); } } if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget() #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA) // On Mac, toolbars inside the unified title bar will never overlap with // siblings in the content view. So we skip enforce native siblings in that case && !d->isInUnifiedToolbar && parentWidget()->isWindow() #endif // Q_WS_MAC && QT_MAC_USE_COCOA ) parentWidget()->d_func()->enforceNativeChildren(); if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created)) d->createWinId(); if (ic && isEnabled() && focusWidget->isEnabled() && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) { ic->setFocusWidget(focusWidget); } #endif //QT_NO_IM break; } case Qt::WA_PaintOnScreen: d->updateIsOpaque(); #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN) // Recreate the widget if it's already created as an alien widget and // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id. // So must their children. if (on) { setAttribute(Qt::WA_NativeWindow); d->enforceNativeChildren(); } #endif // fall through case Qt::WA_OpaquePaintEvent: d->updateIsOpaque(); break; case Qt::WA_NoSystemBackground: d->updateIsOpaque(); // fall through... case Qt::WA_UpdatesDisabled: d->updateSystemBackground(); break; case Qt::WA_TransparentForMouseEvents: #ifdef Q_WS_MAC d->macUpdateIgnoreMouseEvents(); #endif break; case Qt::WA_InputMethodEnabled: { #ifndef QT_NO_IM QWidget *focusWidget = d->effectiveFocusWidget(); QInputContext *ic = focusWidget->d_func()->assignedInputContext(); if (!ic && (!on || hasFocus())) ic = focusWidget->d_func()->inputContext(); if (ic) { if (on && hasFocus() && ic->focusWidget() != focusWidget && isEnabled() && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) { ic->setFocusWidget(focusWidget); } else if (!on && ic->focusWidget() == focusWidget) { ic->reset(); ic->setFocusWidget(0); } } #endif //QT_NO_IM break; } case Qt::WA_WindowPropagation: d->resolvePalette(); d->resolveFont(); d->resolveLocale(); break; #ifdef Q_WS_X11 case Qt::WA_NoX11EventCompression: if (!d->extra) d->createExtra(); d->extra->compress_events = on; break; case Qt::WA_X11OpenGLOverlay: d->updateIsOpaque(); break; case Qt::WA_X11DoNotAcceptFocus: if (testAttribute(Qt::WA_WState_Created)) d->updateX11AcceptFocus(); break; #endif case Qt::WA_DontShowOnScreen: { if (on && isVisible()) { // Make sure we keep the current state and only hide the widget // from the desktop. show_sys will only update platform specific // attributes at this point. d->hide_sys(); #ifdef Q_WS_QWS // Release the region for this window from qws if the widget has // been shown before the attribute was set. if (QWSWindowSurface *surface = static_cast<QWSWindowSurface *>(windowSurface())) { QWidget::qwsDisplay()->requestRegion(surface->winId(), surface->key(), surface->permanentState(), QRegion()); } #endif d->show_sys(); } break; } #ifdef Q_WS_X11 case Qt::WA_X11NetWmWindowTypeDesktop: case Qt::WA_X11NetWmWindowTypeDock: case Qt::WA_X11NetWmWindowTypeToolBar: case Qt::WA_X11NetWmWindowTypeMenu: case Qt::WA_X11NetWmWindowTypeUtility: case Qt::WA_X11NetWmWindowTypeSplash: case Qt::WA_X11NetWmWindowTypeDialog: case Qt::WA_X11NetWmWindowTypeDropDownMenu: case Qt::WA_X11NetWmWindowTypePopupMenu: case Qt::WA_X11NetWmWindowTypeToolTip: case Qt::WA_X11NetWmWindowTypeNotification: case Qt::WA_X11NetWmWindowTypeCombo: case Qt::WA_X11NetWmWindowTypeDND: if (testAttribute(Qt::WA_WState_Created)) d->setNetWmWindowTypes(); break; #endif case Qt::WA_StaticContents: if (QWidgetBackingStore *bs = d->maybeBackingStore()) { if (on) bs->addStaticWidget(this); else bs->removeStaticWidget(this); } break; case Qt::WA_TranslucentBackground: #if defined(Q_OS_SYMBIAN) setAttribute(Qt::WA_NoSystemBackground, on); #else if (on) { setAttribute(Qt::WA_NoSystemBackground); d->updateIsTranslucent(); } #endif break; case Qt::WA_AcceptTouchEvents: #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN) if (on) d->registerTouchWindow(); #endif break; case Qt::WA_LockPortraitOrientation: case Qt::WA_LockLandscapeOrientation: case Qt::WA_AutoOrientation: { const Qt::WidgetAttribute orientations[3] = { Qt::WA_LockPortraitOrientation, Qt::WA_LockLandscapeOrientation, Qt::WA_AutoOrientation }; if (on) { // We can only have one of these set at a time for (int i = 0; i < 3; ++i) { if (orientations[i] != attribute) setAttribute_internal(orientations[i], false, data, d); } } #ifdef Q_OS_BLACKBERRY if (testAttribute(Qt::WA_AutoOrientation)) { navigator_rotation_lock(false); } else { navigator_set_orientation_mode((testAttribute(Qt::WA_LockPortraitOrientation) ? NAVIGATOR_PORTRAIT : NAVIGATOR_LANDSCAPE), 0); navigator_rotation_lock(true); } #endif #ifdef Q_WS_S60 CAknAppUiBase* appUi = static_cast<CAknAppUiBase*>(CEikonEnv::Static()->EikAppUi()); const CAknAppUiBase::TAppUiOrientation s60orientations[] = { CAknAppUiBase::EAppUiOrientationPortrait, CAknAppUiBase::EAppUiOrientationLandscape, CAknAppUiBase::EAppUiOrientationAutomatic }; CAknAppUiBase::TAppUiOrientation s60orientation = CAknAppUiBase::EAppUiOrientationUnspecified; for (int i = 0; i < 3; ++i) { if (testAttribute(orientations[i])) { s60orientation = s60orientations[i]; break; } } QT_TRAP_THROWING(appUi->SetOrientationL(s60orientation)); S60->orientationSet = true; QSymbianControl *window = static_cast<QSymbianControl *>(internalWinId()); if (window) window->ensureFixNativeOrientation(); #endif break; } default: break; } } /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const Returns true if attribute \a attribute is set on this widget; otherwise returns false. \sa setAttribute() */ bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const { Q_D(const QWidget); const int x = attribute - 8*sizeof(uint); const int int_off = x / (8*sizeof(uint)); return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint))))); } /*! \property QWidget::windowOpacity \brief The level of opacity for the window. The valid range of opacity is from 1.0 (completely opaque) to 0.0 (completely transparent). By default the value of this property is 1.0. This feature is available on Embedded Linux, Mac OS X, Windows, and X11 platforms that support the Composite extension. This feature is not available on Windows CE. Note that under X11 you need to have a composite manager running, and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be supported by the window manager you are using. \warning Changing this property from opaque to transparent might issue a paint event that needs to be processed before the window is displayed correctly. This affects mainly the use of QPixmap::grabWindow(). Also note that semi-transparent windows update and resize significantly slower than opaque windows. \sa setMask() */ qreal QWidget::windowOpacity() const { Q_D(const QWidget); return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / qreal(255.) : qreal(1.0); } void QWidget::setWindowOpacity(qreal opacity) { Q_D(QWidget); if (!isWindow()) return; opacity = qBound(qreal(0.0), opacity, qreal(1.0)); QTLWExtra *extra = d->topData(); extra->opacity = uint(opacity * 255); setAttribute(Qt::WA_WState_WindowOpacitySet); #ifndef Q_WS_QWS if (!testAttribute(Qt::WA_WState_Created)) return; #endif #ifndef QT_NO_GRAPHICSVIEW if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) { // Avoid invalidating the cache if set. if (proxy->cacheMode() == QGraphicsItem::NoCache) proxy->update(); else if (QGraphicsScene *scene = proxy->scene()) scene->update(proxy->sceneBoundingRect()); return; } #endif d->setWindowOpacity_sys(opacity); } /*! \property QWidget::windowModified \brief whether the document shown in the window has unsaved changes A modified window is a window whose content has changed but has not been saved to disk. This flag will have different effects varied by the platform. On Mac OS X the close button will have a modified look; on other platforms, the window title will have an '*' (asterisk). The window title must contain a "[*]" placeholder, which indicates where the '*' should appear. Normally, it should appear right after the file name (e.g., "document1.txt[*] - Text Editor"). If the window isn't modified, the placeholder is simply removed. Note that if a widget is set as modified, all its ancestors will also be set as modified. However, if you call \c {setWindowModified(false)} on a widget, this will not propagate to its parent because other children of the parent might have been modified. \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example} */ bool QWidget::isWindowModified() const { return testAttribute(Qt::WA_WindowModified); } void QWidget::setWindowModified(bool mod) { Q_D(QWidget); setAttribute(Qt::WA_WindowModified, mod); #ifndef Q_WS_MAC if (!windowTitle().contains(QLatin1String("[*]")) && mod) qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder"); #endif d->setWindowTitle_helper(windowTitle()); d->setWindowIconText_helper(windowIconText()); #ifdef Q_WS_MAC d->setWindowModified_sys(mod); #endif QEvent e(QEvent::ModifiedChange); QApplication::sendEvent(this, &e); } #ifndef QT_NO_TOOLTIP /*! \property QWidget::toolTip \brief the widget's tooltip Note that by default tooltips are only shown for widgets that are children of the active window. You can change this behavior by setting the attribute Qt::WA_AlwaysShowToolTips on the \e window, not on the widget with the tooltip. If you want to control a tooltip's behavior, you can intercept the event() function and catch the QEvent::ToolTip event (e.g., if you want to customize the area for which the tooltip should be shown). By default, this property contains an empty string. \sa QToolTip statusTip whatsThis */ void QWidget::setToolTip(const QString &s) { Q_D(QWidget); d->toolTip = s; QEvent event(QEvent::ToolTipChange); QApplication::sendEvent(this, &event); } QString QWidget::toolTip() const { Q_D(const QWidget); return d->toolTip; } #endif // QT_NO_TOOLTIP #ifndef QT_NO_STATUSTIP /*! \property QWidget::statusTip \brief the widget's status tip By default, this property contains an empty string. \sa toolTip whatsThis */ void QWidget::setStatusTip(const QString &s) { Q_D(QWidget); d->statusTip = s; } QString QWidget::statusTip() const { Q_D(const QWidget); return d->statusTip; } #endif // QT_NO_STATUSTIP #ifndef QT_NO_WHATSTHIS /*! \property QWidget::whatsThis \brief the widget's What's This help text. By default, this property contains an empty string. \sa QWhatsThis QWidget::toolTip QWidget::statusTip */ void QWidget::setWhatsThis(const QString &s) { Q_D(QWidget); d->whatsThis = s; } QString QWidget::whatsThis() const { Q_D(const QWidget); return d->whatsThis; } #endif // QT_NO_WHATSTHIS #ifndef QT_NO_ACCESSIBILITY /*! \property QWidget::accessibleName \brief the widget's name as seen by assistive technologies This property is used by accessible clients to identify, find, or announce the widget for accessible clients. By default, this property contains an empty string. \sa QAccessibleInterface::text() */ void QWidget::setAccessibleName(const QString &name) { Q_D(QWidget); d->accessibleName = name; QAccessible::updateAccessibility(this, 0, QAccessible::NameChanged); } QString QWidget::accessibleName() const { Q_D(const QWidget); return d->accessibleName; } /*! \property QWidget::accessibleDescription \brief the widget's description as seen by assistive technologies By default, this property contains an empty string. \sa QAccessibleInterface::text() */ void QWidget::setAccessibleDescription(const QString &description) { Q_D(QWidget); d->accessibleDescription = description; QAccessible::updateAccessibility(this, 0, QAccessible::DescriptionChanged); } QString QWidget::accessibleDescription() const { Q_D(const QWidget); return d->accessibleDescription; } #endif // QT_NO_ACCESSIBILITY #ifndef QT_NO_SHORTCUT /*! Adds a shortcut to Qt's shortcut system that watches for the given \a key sequence in the given \a context. If the \a context is Qt::ApplicationShortcut, the shortcut applies to the application as a whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut, or to the window itself, Qt::WindowShortcut. If the same \a key sequence has been grabbed by several widgets, when the \a key sequence occurs a QEvent::Shortcut event is sent to all the widgets to which it applies in a non-deterministic order, but with the ``ambiguous'' flag set to true. \warning You should not normally need to use this function; instead create \l{QAction}s with the shortcut key sequences you require (if you also want equivalent menu options and toolbar buttons), or create \l{QShortcut}s if you just need key sequences. Both QAction and QShortcut handle all the event filtering for you, and provide signals which are triggered when the user triggers the key sequence, so are much easier to use than this low-level function. \sa releaseShortcut() setShortcutEnabled() */ int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context) { Q_ASSERT(qApp); if (key.isEmpty()) return 0; setAttribute(Qt::WA_GrabbedShortcut); return qApp->d_func()->shortcutMap.addShortcut(this, key, context); } /*! Removes the shortcut with the given \a id from Qt's shortcut system. The widget will no longer receive QEvent::Shortcut events for the shortcut's key sequence (unless it has other shortcuts with the same key sequence). \warning You should not normally need to use this function since Qt's shortcut system removes shortcuts automatically when their parent widget is destroyed. It is best to use QAction or QShortcut to handle shortcuts, since they are easier to use than this low-level function. Note also that this is an expensive operation. \sa grabShortcut() setShortcutEnabled() */ void QWidget::releaseShortcut(int id) { Q_ASSERT(qApp); if (id) qApp->d_func()->shortcutMap.removeShortcut(id, this, 0); } /*! If \a enable is true, the shortcut with the given \a id is enabled; otherwise the shortcut is disabled. \warning You should not normally need to use this function since Qt's shortcut system enables/disables shortcuts automatically as widgets become hidden/visible and gain or lose focus. It is best to use QAction or QShortcut to handle shortcuts, since they are easier to use than this low-level function. \sa grabShortcut() releaseShortcut() */ void QWidget::setShortcutEnabled(int id, bool enable) { Q_ASSERT(qApp); if (id) qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0); } /*! \since 4.2 If \a enable is true, auto repeat of the shortcut with the given \a id is enabled; otherwise it is disabled. \sa grabShortcut() releaseShortcut() */ void QWidget::setShortcutAutoRepeat(int id, bool enable) { Q_ASSERT(qApp); if (id) qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0); } #endif // QT_NO_SHORTCUT /*! Updates the widget's micro focus. \sa QInputContext */ void QWidget::updateMicroFocus() { #if !defined(QT_NO_IM) && (defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)) Q_D(QWidget); // and optimization to update input context only it has already been created. if (d->assignedInputContext() || qApp->d_func()->inputContext) { QInputContext *ic = inputContext(); if (ic) ic->update(); } #endif #ifndef QT_NO_ACCESSIBILITY if (isVisible()) { // ##### is this correct QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged); } #endif } #if defined (Q_WS_WIN) /*! Returns the window system handle of the widget, for low-level access. Using this function is not portable. An HDC acquired with getDC() has to be released with releaseDC(). \warning Using this function is not portable. */ HDC QWidget::getDC() const { Q_D(const QWidget); if (d->hd) return (HDC) d->hd; return GetDC(winId()); } /*! Releases the HDC \a hdc acquired by a previous call to getDC(). \warning Using this function is not portable. */ void QWidget::releaseDC(HDC hdc) const { Q_D(const QWidget); // If its the widgets own dc, it will be released elsewhere. If // its a different HDC we release it and issue a warning if it // fails. if (hdc != d->hd && !ReleaseDC(winId(), hdc)) qErrnoWarning("QWidget::releaseDC(): failed to release HDC"); } #else /*! Returns the window system handle of the widget, for low-level access. Using this function is not portable. The HANDLE type varies with platform; see \c qwindowdefs.h for details. */ Qt::HANDLE QWidget::handle() const { Q_D(const QWidget); if (!internalWinId() && testAttribute(Qt::WA_WState_Created)) (void)winId(); // enforce native window return d->hd; } #endif /*! Raises this widget to the top of the parent widget's stack. After this call the widget will be visually in front of any overlapping sibling widgets. \note When using activateWindow(), you can call this function to ensure that the window is stacked on top. \sa lower(), stackUnder() */ void QWidget::raise() { Q_D(QWidget); if (!isWindow()) { QWidget *p = parentWidget(); const int parentChildCount = p->d_func()->children.size(); if (parentChildCount < 2) return; const int from = p->d_func()->children.indexOf(this); Q_ASSERT(from >= 0); // Do nothing if the widget is already in correct stacking order _and_ created. if (from != parentChildCount -1) p->d_func()->children.move(from, parentChildCount - 1); if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created)) create(); else if (from == parentChildCount - 1) return; QRegion region(rect()); d->subtractOpaqueSiblings(region); d->invalidateBuffer(region); } if (testAttribute(Qt::WA_WState_Created)) d->raise_sys(); QEvent e(QEvent::ZOrderChange); QApplication::sendEvent(this, &e); } /*! Lowers the widget to the bottom of the parent widget's stack. After this call the widget will be visually behind (and therefore obscured by) any overlapping sibling widgets. \sa raise(), stackUnder() */ void QWidget::lower() { Q_D(QWidget); if (!isWindow()) { QWidget *p = parentWidget(); const int parentChildCount = p->d_func()->children.size(); if (parentChildCount < 2) return; const int from = p->d_func()->children.indexOf(this); Q_ASSERT(from >= 0); // Do nothing if the widget is already in correct stacking order _and_ created. if (from != 0) p->d_func()->children.move(from, 0); if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created)) create(); else if (from == 0) return; } if (testAttribute(Qt::WA_WState_Created)) d->lower_sys(); QEvent e(QEvent::ZOrderChange); QApplication::sendEvent(this, &e); } /*! Places the widget under \a w in the parent widget's stack. To make this work, the widget itself and \a w must be siblings. \sa raise(), lower() */ void QWidget::stackUnder(QWidget* w) { Q_D(QWidget); QWidget *p = parentWidget(); if (!w || isWindow() || p != w->parentWidget() || this == w) return; if (p) { int from = p->d_func()->children.indexOf(this); int to = p->d_func()->children.indexOf(w); Q_ASSERT(from >= 0); Q_ASSERT(to >= 0); if (from < to) --to; // Do nothing if the widget is already in correct stacking order _and_ created. if (from != to) p->d_func()->children.move(from, to); if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created)) create(); else if (from == to) return; } if (testAttribute(Qt::WA_WState_Created)) d->stackUnder_sys(w); QEvent e(QEvent::ZOrderChange); QApplication::sendEvent(this, &e); } void QWidget::styleChange(QStyle&) { } void QWidget::enabledChange(bool) { } // compat void QWidget::paletteChange(const QPalette &) { } // compat void QWidget::fontChange(const QFont &) { } // compat void QWidget::windowActivationChange(bool) { } // compat void QWidget::languageChange() { } // compat /*! \enum QWidget::BackgroundOrigin \compat \value WidgetOrigin \value ParentOrigin \value WindowOrigin \value AncestorOrigin */ /*! \fn bool QWidget::isVisibleToTLW() const Use isVisible() instead. */ /*! \fn void QWidget::iconify() Use showMinimized() instead. */ /*! \fn void QWidget::constPolish() const Use ensurePolished() instead. */ /*! \fn void QWidget::reparent(QWidget *parent, Qt::WindowFlags f, const QPoint &p, bool showIt) Use setParent() to change the parent or the widget's widget flags; use move() to move the widget, and use show() to show the widget. */ /*! \fn void QWidget::reparent(QWidget *parent, const QPoint &p, bool showIt) Use setParent() to change the parent; use move() to move the widget, and use show() to show the widget. */ /*! \fn void QWidget::recreate(QWidget *parent, Qt::WindowFlags f, const QPoint & p, bool showIt) Use setParent() to change the parent or the widget's widget flags; use move() to move the widget, and use show() to show the widget. */ /*! \fn bool QWidget::hasMouse() const Use testAttribute(Qt::WA_UnderMouse) instead. */ /*! \fn bool QWidget::ownCursor() const Use testAttribute(Qt::WA_SetCursor) instead. */ /*! \fn bool QWidget::ownFont() const Use testAttribute(Qt::WA_SetFont) instead. */ /*! \fn void QWidget::unsetFont() Use setFont(QFont()) instead. */ /*! \fn bool QWidget::ownPalette() const Use testAttribute(Qt::WA_SetPalette) instead. */ /*! \fn void QWidget::unsetPalette() Use setPalette(QPalette()) instead. */ /*! \fn void QWidget::setEraseColor(const QColor &color) Use the palette instead. \oldcode widget->setEraseColor(color); \newcode QPalette palette; palette.setColor(widget->backgroundRole(), color); widget->setPalette(palette); \endcode */ /*! \fn void QWidget::setErasePixmap(const QPixmap &pixmap) Use the palette instead. \oldcode widget->setErasePixmap(pixmap); \newcode QPalette palette; palette.setBrush(widget->backgroundRole(), QBrush(pixmap)); widget->setPalette(palette); \endcode */ /*! \fn void QWidget::setPaletteForegroundColor(const QColor &color) Use the palette directly. \oldcode widget->setPaletteForegroundColor(color); \newcode QPalette palette; palette.setColor(widget->foregroundRole(), color); widget->setPalette(palette); \endcode */ /*! \fn void QWidget::setPaletteBackgroundColor(const QColor &color) Use the palette directly. \oldcode widget->setPaletteBackgroundColor(color); \newcode QPalette palette; palette.setColor(widget->backgroundRole(), color); widget->setPalette(palette); \endcode */ /*! \fn void QWidget::setPaletteBackgroundPixmap(const QPixmap &pixmap) Use the palette directly. \oldcode widget->setPaletteBackgroundPixmap(pixmap); \newcode QPalette palette; palette.setBrush(widget->backgroundRole(), QBrush(pixmap)); widget->setPalette(palette); \endcode */ /*! \fn void QWidget::setBackgroundPixmap(const QPixmap &pixmap) Use the palette instead. \oldcode widget->setBackgroundPixmap(pixmap); \newcode QPalette palette; palette.setBrush(widget->backgroundRole(), QBrush(pixmap)); widget->setPalette(palette); \endcode */ /*! \fn void QWidget::setBackgroundColor(const QColor &color) Use the palette instead. \oldcode widget->setBackgroundColor(color); \newcode QPalette palette; palette.setColor(widget->backgroundRole(), color); widget->setPalette(palette); \endcode */ /*! \fn QColorGroup QWidget::colorGroup() const Use QColorGroup(palette()) instead. */ /*! \fn QWidget *QWidget::parentWidget(bool sameWindow) const Use the no-argument overload instead. */ /*! \fn void QWidget::setKeyCompression(bool b) Use setAttribute(Qt::WA_KeyCompression, b) instead. */ /*! \fn void QWidget::setFont(const QFont &f, bool b) Use the single-argument overload instead. */ /*! \fn void QWidget::setPalette(const QPalette &p, bool b) Use the single-argument overload instead. */ /*! \fn void QWidget::setBackgroundOrigin(BackgroundOrigin background) \obsolete */ /*! \fn BackgroundOrigin QWidget::backgroundOrigin() const \obsolete Always returns \c WindowOrigin. */ /*! \fn QPoint QWidget::backgroundOffset() const \obsolete Always returns QPoint(). */ /*! \fn void QWidget::repaint(bool b) The boolean parameter \a b is ignored. Use the no-argument overload instead. */ /*! \fn void QWidget::repaint(int x, int y, int w, int h, bool b) The boolean parameter \a b is ignored. Use the four-argument overload instead. */ /*! \fn void QWidget::repaint(const QRect &r, bool b) The boolean parameter \a b is ignored. Use the single rect-argument overload instead. */ /*! \fn void QWidget::repaint(const QRegion &rgn, bool b) The boolean parameter \a b is ignored. Use the single region-argument overload instead. */ /*! \fn void QWidget::erase() Drawing may only take place in a QPaintEvent. Overload paintEvent() to do your erasing and call update() to schedule a replaint whenever necessary. See also QPainter. */ /*! \fn void QWidget::erase(int x, int y, int w, int h) Drawing may only take place in a QPaintEvent. Overload paintEvent() to do your erasing and call update() to schedule a replaint whenever necessary. See also QPainter. */ /*! \fn void QWidget::erase(const QRect &rect) Drawing may only take place in a QPaintEvent. Overload paintEvent() to do your erasing and call update() to schedule a replaint whenever necessary. See also QPainter. */ /*! \fn void QWidget::drawText(const QPoint &p, const QString &s) Drawing may only take place in a QPaintEvent. Overload paintEvent() to do your drawing and call update() to schedule a replaint whenever necessary. See also QPainter. */ /*! \fn void QWidget::drawText(int x, int y, const QString &s) Drawing may only take place in a QPaintEvent. Overload paintEvent() to do your drawing and call update() to schedule a replaint whenever necessary. See also QPainter. */ /*! \fn QWidget *QWidget::childAt(const QPoint &p, bool includeThis) const Use the single point argument overload instead. */ /*! \fn void QWidget::setCaption(const QString &c) Use setWindowTitle() instead. */ /*! \fn void QWidget::setIcon(const QPixmap &i) Use setWindowIcon() instead. */ /*! \fn void QWidget::setIconText(const QString &it) Use setWindowIconText() instead. */ /*! \fn QString QWidget::caption() const Use windowTitle() instead. */ /*! \fn QString QWidget::iconText() const Use windowIconText() instead. */ /*! \fn bool QWidget::isTopLevel() const \obsolete Use isWindow() instead. */ /*! \fn bool QWidget::isRightToLeft() const \internal */ /*! \fn bool QWidget::isLeftToRight() const \internal */ /*! \fn void QWidget::setInputMethodEnabled(bool enabled) Use setAttribute(Qt::WA_InputMethodEnabled, \a enabled) instead. */ /*! \fn bool QWidget::isInputMethodEnabled() const Use testAttribute(Qt::WA_InputMethodEnabled) instead. */ /*! \fn void QWidget::setActiveWindow() Use activateWindow() instead. */ /*! \fn bool QWidget::isShown() const Use !isHidden() instead (notice the exclamation mark), or use isVisible() to check whether the widget is visible. */ /*! \fn bool QWidget::isDialog() const Use windowType() == Qt::Dialog instead. */ /*! \fn bool QWidget::isPopup() const Use windowType() == Qt::Popup instead. */ /*! \fn bool QWidget::isDesktop() const Use windowType() == Qt::Desktop instead. */ /*! \fn void QWidget::polish() Use ensurePolished() instead. */ /*! \fn QWidget *QWidget::childAt(int x, int y, bool includeThis) const Use the childAt() overload that doesn't have an \a includeThis parameter. \oldcode return widget->childAt(x, y, true); \newcode QWidget *child = widget->childAt(x, y, true); if (child) return child; if (widget->rect().contains(x, y)) return widget; \endcode */ /*! \fn void QWidget::setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver, bool hfw) \compat Use the \l sizePolicy property and heightForWidth() function instead. */ /*! \fn bool QWidget::isUpdatesEnabled() const \compat Use the \l updatesEnabled property instead. */ /*! \macro QWIDGETSIZE_MAX \relates QWidget Defines the maximum size for a QWidget object. The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215). \sa QWidget::setMaximumSize() */ /*! \fn QWidget::setupUi(QWidget *widget) Sets up the user interface for the specified \a widget. \note This function is available with widgets that derive from user interface descriptions created using \l{uic}. \sa {Using a Designer UI File in Your Application} */ QRect QWidgetPrivate::frameStrut() const { Q_Q(const QWidget); if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) { // x2 = x1 + w - 1, so w/h = 1 return QRect(0, 0, 1, 1); } if (data.fstrut_dirty #ifndef Q_WS_WIN // ### Fix properly for 4.3 && q->isVisible() #endif && q->testAttribute(Qt::WA_WState_Created)) const_cast<QWidgetPrivate *>(this)->updateFrameStrut(); return maybeTopData() ? maybeTopData()->frameStrut : QRect(); } #ifdef QT_KEYPAD_NAVIGATION /*! \internal Changes the focus from the current focusWidget to a widget in the \a direction. Returns true, if there was a widget in that direction */ bool QWidgetPrivate::navigateToDirection(Direction direction) { QWidget *targetWidget = widgetInNavigationDirection(direction); if (targetWidget) targetWidget->setFocus(); return (targetWidget != 0); } /*! \internal Searches for a widget that is positioned in the \a direction, starting from the current focusWidget. Returns the pointer to a found widget or 0, if there was no widget in that direction. */ QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction) { const QWidget *sourceWidget = QApplication::focusWidget(); if (!sourceWidget) return 0; const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint())); const int sourceX = (direction == DirectionNorth || direction == DirectionSouth) ? (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2) :(direction == DirectionEast ? sourceRect.right() : sourceRect.left()); const int sourceY = (direction == DirectionEast || direction == DirectionWest) ? (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2) :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top()); const QPoint sourcePoint(sourceX, sourceY); const QPoint sourceCenter = sourceRect.center(); const QWidget *sourceWindow = sourceWidget->window(); QWidget *targetWidget = 0; int shortestDistance = INT_MAX; foreach(QWidget *targetCandidate, QApplication::allWidgets()) { const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint())); // For focus proxies, the child widget handling the focus can have keypad navigation focus, // but the owner of the proxy cannot. // Additionally, empty widgets should be ignored. if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty()) continue; // Only navigate to a target widget that... if ( targetCandidate != sourceWidget // ...takes the focus, && targetCandidate->focusPolicy() & Qt::TabFocus // ...is above if DirectionNorth, && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top()) // ...is on the right if DirectionEast, && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right()) // ...is below if DirectionSouth, && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom()) // ...is on the left if DirectionWest, && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left()) // ...is enabled, && targetCandidate->isEnabled() // ...is visible, && targetCandidate->isVisible() // ...is in the same window, && targetCandidate->window() == sourceWindow) { const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect); if (targetCandidateDistance < shortestDistance) { shortestDistance = targetCandidateDistance; targetWidget = targetCandidate; } } } return targetWidget; } /*! \internal Tells us if it there is currently a reachable widget by keypad navigation in a certain \a orientation. If no navigation is possible, occurring key events in that \a orientation may be used to interact with the value in the focused widget, even though it currently has not the editFocus. \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus() */ bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation) { return orientation == Qt::Horizontal? (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast) || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest)) :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth) || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth)); } /*! \internal Checks, if the \a widget is inside a QTabWidget. If is is inside one, left/right key events will be used to switch between tabs in keypad navigation. If there is no QTabWidget, the horizontal key events can be used to interact with the value in the focused widget, even though it currently has not the editFocus. \sa QWidget::hasEditFocus() */ bool QWidgetPrivate::inTabWidget(QWidget *widget) { for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget()) if (qobject_cast<const QTabWidget*>(tabWidget)) return true; return false; } #endif /*! \preliminary \since 4.2 \obsolete Sets the window surface to be the \a surface specified. The QWidget takes will ownership of the \a surface. widget itself is deleted. */ void QWidget::setWindowSurface(QWindowSurface *surface) { // ### createWinId() ?? #ifndef Q_BACKINGSTORE_SUBSURFACES if (!isTopLevel()) return; #endif Q_D(QWidget); QTLWExtra *topData = d->topData(); if (topData->windowSurface == surface) return; QWindowSurface *oldSurface = topData->windowSurface; delete topData->windowSurface; topData->windowSurface = surface; QWidgetBackingStore *bs = d->maybeBackingStore(); if (!bs) return; if (isTopLevel()) { if (bs->windowSurface != oldSurface && bs->windowSurface != surface) delete bs->windowSurface; bs->windowSurface = surface; } #ifdef Q_BACKINGSTORE_SUBSURFACES else { bs->subSurfaces.append(surface); } bs->subSurfaces.removeOne(oldSurface); #endif } /*! \preliminary \since 4.2 Returns the QWindowSurface this widget will be drawn into. */ QWindowSurface *QWidget::windowSurface() const { Q_D(const QWidget); QTLWExtra *extra = d->maybeTopData(); if (extra && extra->windowSurface) return extra->windowSurface; QWidgetBackingStore *bs = d->maybeBackingStore(); #ifdef Q_BACKINGSTORE_SUBSURFACES if (bs && bs->subSurfaces.isEmpty()) return bs->windowSurface; if (!isTopLevel()) { const QWidget *w = parentWidget(); while (w) { QTLWExtra *extra = w->d_func()->maybeTopData(); if (extra && extra->windowSurface) return extra->windowSurface; if (w->isTopLevel()) break; w = w->parentWidget(); } } #endif // Q_BACKINGSTORE_SUBSURFACES return bs ? bs->windowSurface : 0; } void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const { if (left) *left = (int)leftLayoutItemMargin; if (top) *top = (int)topLayoutItemMargin; if (right) *right = (int)rightLayoutItemMargin; if (bottom) *bottom = (int)bottomLayoutItemMargin; } void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom) { if (leftLayoutItemMargin == left && topLayoutItemMargin == top && rightLayoutItemMargin == right && bottomLayoutItemMargin == bottom) return; Q_Q(QWidget); leftLayoutItemMargin = (signed char)left; topLayoutItemMargin = (signed char)top; rightLayoutItemMargin = (signed char)right; bottomLayoutItemMargin = (signed char)bottom; q->updateGeometry(); } void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt) { Q_Q(QWidget); QStyleOption myOpt; if (!opt) { myOpt.initFrom(q); myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary opt = &myOpt; } QRect liRect = q->style()->subElementRect(element, opt, q); if (liRect.isValid()) { leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left()); topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top()); rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right()); bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom()); } else { leftLayoutItemMargin = 0; topLayoutItemMargin = 0; rightLayoutItemMargin = 0; bottomLayoutItemMargin = 0; } } // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets. void QWidgetPrivate::adjustQuitOnCloseAttribute() { Q_Q(QWidget); if (!q->parentWidget()) { Qt::WindowType type = q->windowType(); if (type == Qt::Widget || type == Qt::SubWindow) type = Qt::Window; if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog) q->setAttribute(Qt::WA_QuitOnClose, false); } } Q_GUI_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget) { return widget->data; } Q_GUI_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget) { return widget->d_func(); } #ifndef QT_NO_GRAPHICSVIEW /*! \since 4.5 Returns the proxy widget for the corresponding embedded widget in a graphics view; otherwise returns 0. \sa QGraphicsProxyWidget::createProxyForChildWidget(), QGraphicsScene::addWidget() */ QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const { Q_D(const QWidget); if (d->extra) { return d->extra->proxyWidget; } return 0; } #endif /*! \typedef QWidgetList \relates QWidget Synonym for QList<QWidget *>. */ #ifndef QT_NO_GESTURES /*! Subscribes the widget to a given \a gesture with specific \a flags. \sa ungrabGesture(), QGestureEvent \since 4.6 */ void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags) { Q_D(QWidget); d->gestureContext.insert(gesture, flags); (void)QGestureManager::instance(); // create a gesture manager } /*! Unsubscribes the widget from a given \a gesture type \sa grabGesture(), QGestureEvent \since 4.6 */ void QWidget::ungrabGesture(Qt::GestureType gesture) { Q_D(QWidget); if (d->gestureContext.remove(gesture)) { if (QGestureManager *manager = QGestureManager::instance()) manager->cleanupCachedGestures(this, gesture); } } #endif // QT_NO_GESTURES /*! \typedef WId \relates QWidget Platform dependent window identifier. */ /*! \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows) Frees up window system resources. Destroys the widget window if \a destroyWindow is true. destroy() calls itself recursively for all the child widgets, passing \a destroySubWindows for the \a destroyWindow parameter. To have more control over destruction of subwidgets, destroy subwidgets selectively first. This function is usually called from the QWidget destructor. */ /*! \fn QPaintEngine *QWidget::paintEngine() const Returns the widget's paint engine. Note that this function should not be called explicitly by the user, since it's meant for reimplementation purposes only. The function is called by Qt internally, and the default implementation may not always return a valid pointer. */ /*! \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const Translates the widget coordinate \a pos to global screen coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give the global coordinates of the top-left pixel of the widget. \sa mapFromGlobal() mapTo() mapToParent() */ /*! \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const Translates the global screen coordinate \a pos to widget coordinates. \sa mapToGlobal() mapFrom() mapFromParent() */ /*! \fn void QWidget::grabMouse() Grabs the mouse input. This widget receives all mouse events until releaseMouse() is called; other widgets get no mouse events at all. Keyboard events are not affected. Use grabKeyboard() if you want to grab that. \warning Bugs in mouse-grabbing applications very often lock the terminal. Use this function with extreme caution, and consider using the \c -nograb command line option while debugging. It is almost never necessary to grab the mouse when using Qt, as Qt grabs and releases it sensibly. In particular, Qt grabs the mouse when a mouse button is pressed and keeps it until the last button is released. \note Only visible widgets can grab mouse input. If isVisible() returns false for a widget, that widget cannot call grabMouse(). \note \bold{(Mac OS X developers)} For \e Cocoa, calling grabMouse() on a widget only works when the mouse is inside the frame of that widget. For \e Carbon, it works outside the widget's frame as well, like for Windows and X11. \sa releaseMouse() grabKeyboard() releaseKeyboard() */ /*! \fn void QWidget::grabMouse(const QCursor &cursor) \overload grabMouse() Grabs the mouse input and changes the cursor shape. The cursor will assume shape \a cursor (for as long as the mouse focus is grabbed) and this widget will be the only one to receive mouse events until releaseMouse() is called(). \warning Grabbing the mouse might lock the terminal. \note \bold{(Mac OS X developers)} See the note in QWidget::grabMouse(). \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor() */ /*! \fn void QWidget::releaseMouse() Releases the mouse grab. \sa grabMouse(), grabKeyboard(), releaseKeyboard() */ /*! \fn void QWidget::grabKeyboard() Grabs the keyboard input. This widget receives all keyboard events until releaseKeyboard() is called; other widgets get no keyboard events at all. Mouse events are not affected. Use grabMouse() if you want to grab that. The focus widget is not affected, except that it doesn't receive any keyboard events. setFocus() moves the focus as usual, but the new focus widget receives keyboard events only after releaseKeyboard() is called. If a different widget is currently grabbing keyboard input, that widget's grab is released first. \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget() */ /*! \fn void QWidget::releaseKeyboard() Releases the keyboard grab. \sa grabKeyboard(), grabMouse(), releaseMouse() */ /*! \fn QWidget *QWidget::mouseGrabber() Returns the widget that is currently grabbing the mouse input. If no widget in this application is currently grabbing the mouse, 0 is returned. \sa grabMouse(), keyboardGrabber() */ /*! \fn QWidget *QWidget::keyboardGrabber() Returns the widget that is currently grabbing the keyboard input. If no widget in this application is currently grabbing the keyboard, 0 is returned. \sa grabMouse(), mouseGrabber() */ /*! \fn void QWidget::activateWindow() Sets the top-level widget containing this widget to be the active window. An active window is a visible top-level window that has the keyboard input focus. This function performs the same operation as clicking the mouse on the title bar of a top-level window. On X11, the result depends on the Window Manager. If you want to ensure that the window is stacked on top as well you should also call raise(). Note that the window must be visible, otherwise activateWindow() has no effect. On Windows, if you are calling this when the application is not currently the active one then it will not make it the active window. It will change the color of the taskbar entry to indicate that the window has changed in some way. This is because Microsoft does not allow an application to interrupt what the user is currently doing in another application. \sa isActiveWindow(), window(), show() */ /*! \fn int QWidget::metric(PaintDeviceMetric m) const Internal implementation of the virtual QPaintDevice::metric() function. \a m is the metric to get. */ /*! \fn void QWidget::setMask(const QRegion &region) \overload Causes only the parts of the widget which overlap \a region to be visible. If the region includes pixels outside the rect() of the widget, window system controls in that area may or may not be visible, depending on the platform. Note that this effect can be slow if the region is particularly complex. \sa windowOpacity */ void QWidget::setMask(const QRegion &newMask) { Q_D(QWidget); d->createExtra(); if (newMask == d->extra->mask) return; #ifndef QT_NO_BACKINGSTORE const QRegion oldMask(d->extra->mask); #endif d->extra->mask = newMask; d->extra->hasMask = !newMask.isEmpty(); #ifndef QT_MAC_USE_COCOA if (!testAttribute(Qt::WA_WState_Created)) return; #endif d->setMask_sys(newMask); #ifndef QT_NO_BACKINGSTORE if (!isVisible()) return; if (!d->extra->hasMask) { // Mask was cleared; update newly exposed area. QRegion expose(rect()); expose -= oldMask; if (!expose.isEmpty()) { d->setDirtyOpaqueRegion(); update(expose); } return; } if (!isWindow()) { // Update newly exposed area on the parent widget. QRegion parentExpose(rect()); parentExpose -= newMask; if (!parentExpose.isEmpty()) { d->setDirtyOpaqueRegion(); parentExpose.translate(data->crect.topLeft()); parentWidget()->update(parentExpose); } // Update newly exposed area on this widget if (!oldMask.isEmpty()) update(newMask - oldMask); } #endif } /*! \fn void QWidget::setMask(const QBitmap &bitmap) Causes only the pixels of the widget for which \a bitmap has a corresponding 1 bit to be visible. If the region includes pixels outside the rect() of the widget, window system controls in that area may or may not be visible, depending on the platform. Note that this effect can be slow if the region is particularly complex. The following code shows how an image with an alpha channel can be used to generate a mask for a widget: \snippet doc/src/snippets/widget-mask/main.cpp 0 The label shown by this code is masked using the image it contains, giving the appearance that an irregularly-shaped image is being drawn directly onto the screen. Masked widgets receive mouse events only on their visible portions. \sa clearMask(), windowOpacity(), {Shaped Clock Example} */ void QWidget::setMask(const QBitmap &bitmap) { setMask(QRegion(bitmap)); } /*! \fn void QWidget::clearMask() Removes any mask set by setMask(). \sa setMask() */ void QWidget::clearMask() { setMask(QRegion()); } /*! \fn const QX11Info &QWidget::x11Info() const Returns information about the configuration of the X display used to display the widget. \warning This function is only available on X11. */ /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const Returns the X11 Picture handle of the widget for XRender support. Use of this function is not portable. This function will return 0 if XRender support is not compiled into Qt, if the XRender extension is not supported on the X11 display, or if the handle could not be created. */ #ifdef Q_OS_SYMBIAN void QWidgetPrivate::_q_cleanupWinIds() { foreach (WId wid, widCleanupList) delete wid; widCleanupList.clear(); } #endif #if QT_MAC_USE_COCOA void QWidgetPrivate::syncUnifiedMode() { // The whole purpose of this method is to keep the unifiedToolbar in sync. // That means making sure we either exchange the drawing methods or we let // the toolbar know that it does not require to draw the baseline. Q_Q(QWidget); // This function makes sense only if this is a top level if(!q->isWindow()) return; OSWindowRef window = qt_mac_window_for(q); if(changeMethods) { // Ok, we are in documentMode. if(originalDrawMethod) qt_mac_replaceDrawRect(window, this); } else { if(!originalDrawMethod) qt_mac_replaceDrawRectOriginal(window, this); } } #endif // QT_MAC_USE_COCOA QT_END_NAMESPACE #include "moc_qwidget.cpp"
31.413309
154
0.651689
[ "geometry", "render", "object", "shape", "transform" ]
3a0874c53271f97667840f352c627ee093ba29f9
7,772
cpp
C++
src/imaging/ossimBrightnessMatch.cpp
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
251
2015-10-20T09:08:11.000Z
2022-03-22T18:16:38.000Z
src/imaging/ossimBrightnessMatch.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
73
2015-11-02T17:12:36.000Z
2021-11-15T17:41:47.000Z
src/imaging/ossimBrightnessMatch.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
146
2015-10-15T16:00:15.000Z
2022-03-22T12:37:14.000Z
//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: A brief description of the contents of the file. // //************************************************************************* // $Id: ossimBrightnessMatch.cpp 11955 2007-10-31 16:10:22Z gpotts $ #include <ossim/imaging/ossimBrightnessMatch.h> #include <ossim/imaging/ossimImageData.h> #include <ossim/imaging/ossimImageDataFactory.h> #include <ossim/base/ossimConstants.h> #include <ossim/base/ossimCommon.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimTrace.h> #include <ossim/base/ossimNormRgbVector.h> #include <ossim/base/ossimHsiVector.h> #include <ossim/base/ossimContainerProperty.h> #include <ossim/base/ossimNumericProperty.h> RTTI_DEF1(ossimBrightnessMatch, "ossimBrightnessMatch", ossimImageSourceFilter) ossimBrightnessMatch::ossimBrightnessMatch() :ossimImageSourceFilter(), theTargetBrightness(0.5), theInputBrightness(0.5) { theInputBrightness = ossim::nan(); theBrightnessContrastSource = new ossimBrightnessContrastSource; } ossimBrightnessMatch::~ossimBrightnessMatch() { } ossimRefPtr<ossimImageData> ossimBrightnessMatch::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!isSourceEnabled()) { return ossimImageSourceFilter::getTile(tileRect, resLevel); } if(theInputConnection) { if(ossim::isnan(theInputBrightness)) { computeInputBrightness(); } return theBrightnessContrastSource->getTile(tileRect, resLevel); } return 0; } void ossimBrightnessMatch::initialize() { theBrightnessContrastSource->connectMyInputTo(0, getInput()); theNormTile = 0; } void ossimBrightnessMatch::setProperty(ossimRefPtr<ossimProperty> property) { if(!property) { return; } ossimString name = property->getName(); if(name == "input_brightness") { theInputBrightness = property->valueToString().toDouble(); theBrightnessContrastSource->setBrightness(theTargetBrightness-theInputBrightness); } else if(name == "target_brightness") { theTargetBrightness = property->valueToString().toDouble(); theBrightnessContrastSource->setBrightness(theTargetBrightness-theInputBrightness); } else { ossimImageSourceFilter::setProperty(property); } } ossimRefPtr<ossimProperty> ossimBrightnessMatch::getProperty(const ossimString& name)const { if(name == "target_brightness") { ossimNumericProperty* numeric = new ossimNumericProperty(name, ossimString::toString(theTargetBrightness), 0.0, 1.0); numeric->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64); numeric->setCacheRefreshBit(); return numeric; } else if(name == "input_brightness") { ossimNumericProperty* numeric = new ossimNumericProperty(name, ossimString::toString(theInputBrightness), 0.0, 1.0); numeric->setNumericType(ossimNumericProperty::ossimNumericPropertyType_FLOAT64); numeric->setCacheRefreshBit(); return numeric; } return ossimImageSourceFilter::getProperty(name); } void ossimBrightnessMatch::getPropertyNames(std::vector<ossimString>& propertyNames)const { ossimImageSourceFilter::getPropertyNames(propertyNames); propertyNames.push_back("input_brightness"); propertyNames.push_back("target_brightness"); } bool ossimBrightnessMatch::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* input_brightness = kwl.find(prefix, "input_brightness"); const char* target_brightness = kwl.find(prefix, "target_brightness"); if(input_brightness) { theInputBrightness = ossimString(input_brightness).toDouble(); } if(target_brightness) { theTargetBrightness = ossimString(target_brightness).toDouble(); } return ossimImageSourceFilter::loadState(kwl, prefix); } bool ossimBrightnessMatch::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "input_brightness", theInputBrightness, true); kwl.add(prefix, "target_brightness", theTargetBrightness, true); return ossimImageSourceFilter::saveState(kwl, prefix); } void ossimBrightnessMatch::computeInputBrightness() { if(theInputConnection) { ossimIrect inputRect = getBoundingRect(); ossim_uint32 rlevel = 0; ossim_uint32 nlevels = getNumberOfDecimationLevels(); if(nlevels>1) { while((ossim::max(inputRect.width(), inputRect.height()) > 2048)&& (rlevel < nlevels)) { ++rlevel; inputRect = getBoundingRect(rlevel); } } ossimIpt centerPt = inputRect.midPoint(); centerPt.x -= 1024; centerPt.y -= 1024; ossimIrect reqRect(centerPt.x, centerPt.y, centerPt.x + 2047, centerPt.x + 2047); reqRect = reqRect.clipToRect(inputRect); ossimRefPtr<ossimImageData> inputTile = theInputConnection->getTile(reqRect, rlevel); if(inputTile.valid()) { theNormTile = new ossimImageData(0, OSSIM_FLOAT32, inputTile->getNumberOfBands()); theNormTile->initialize(); theNormTile->setImageRectangle(reqRect); inputTile->copyTileToNormalizedBuffer((ossim_float32*)theNormTile->getBuf()); theNormTile->setDataObjectStatus(inputTile->getDataObjectStatus()); ossim_uint32 maxIdx = theNormTile->getWidth()*theNormTile->getHeight(); ossim_float32* bands[3]; double averageI = 0.0; double count = 0.0; ossim_uint32 offset = 0; bands[0] = (ossim_float32*)theNormTile->getBuf(); if(theNormTile->getNumberOfBands()>2) { bands[1] = (ossim_float32*)theNormTile->getBuf(1); bands[2] = (ossim_float32*)theNormTile->getBuf(2); } else { bands[1] = bands[0]; bands[2] = bands[0]; } ossimHsiVector hsi; if(theNormTile->getDataObjectStatus() == OSSIM_FULL) { count = maxIdx; for(offset = 0; offset < maxIdx; ++offset) { hsi = ossimNormRgbVector(bands[0][offset], bands[1][offset], bands[2][offset]); averageI += hsi.getI(); } } else { for(offset = 0; offset < maxIdx; ++offset) { if((bands[0][offset] != 0.0)&& (bands[1][offset] != 0.0)&& (bands[2][offset] != 0.0)) { hsi = ossimNormRgbVector(bands[0][offset], bands[1][offset], bands[2][offset]); averageI += hsi.getI(); ++count; } } } theInputBrightness = averageI / count; theBrightnessContrastSource->setBrightness(theTargetBrightness-theInputBrightness); } else { theInputBrightness = .5; } } theNormTile = 0; }
31.33871
106
0.5965
[ "vector" ]
3a0adc9de38588486e3855798e031a5a198369d6
12,656
cc
C++
src/Router/mid_tier_service/service/helper_files/router_server_helper.cc
JungyeonYoon/MicroSuite
acc75468a3568bb9504841978b887a337eba889c
[ "BSD-3-Clause" ]
1
2020-10-23T13:48:45.000Z
2020-10-23T13:48:45.000Z
src/Router/mid_tier_service/service/helper_files/router_server_helper.cc
DCchico/MicroSuite
b8651e0f5b74461393140135b917243a2e853f3d
[ "BSD-3-Clause" ]
null
null
null
src/Router/mid_tier_service/service/helper_files/router_server_helper.cc
DCchico/MicroSuite
b8651e0f5b74461393140135b917243a2e853f3d
[ "BSD-3-Clause" ]
null
null
null
#include <fstream> #include <iterator> #include <sstream> #include <string> #include <sys/time.h> #include <unordered_map> #include "router_server_helper.h" void GetLookupServerIPs(const std::string &lookup_server_ips_file, std::vector<std::string>* lookup_server_ips) { std::ifstream file(lookup_server_ips_file); CHECK((file.good()), "ERROR: File containing lookup server IPs must exists\n"); std::string line = ""; for(int i = 0; std::getline(file, line); i++) { std::istringstream buffer(line); std::istream_iterator<std::string> begin(buffer), end; std::vector<std::string> tokens(begin, end); /* Tokens must contain only one IP - Each IP address must be on a different line.*/ CHECK((tokens.size() == 1), "ERROR: File must contain only one IP address per line\n"); lookup_server_ips->push_back(tokens[0]); } } void UnpackRouterServiceRequest(const router::RouterRequest &router_request, std::string* key, std::string* value, uint32_t* operation, lookup::Key* request_to_lookup_srv) { *key = router_request.key(); *value = router_request.value(); *operation = router_request.operation(); request_to_lookup_srv->set_key(*key); request_to_lookup_srv->set_value(*value); request_to_lookup_srv->set_operation(*operation); } void Merge(struct ThreadArgs* thread_args, unsigned int replication_cnt, std::string* lookup_val, uint64_t* create_lookup_srv_req_time, uint64_t* unpack_lookup_srv_resp_time, uint64_t* unpack_lookup_srv_req_time, uint64_t* lookup_srv_time, uint64_t* pack_lookup_srv_resp_time, router::LookupResponse* router_reply) { bool nack = false; for(unsigned int j = 0; j < replication_cnt; j++) { if (thread_args[j].value == "nack") { *lookup_val = "nack"; nack = true; break; } (*create_lookup_srv_req_time) += thread_args[j].lookup_srv_timing_info.create_lookup_srv_request_time; (*unpack_lookup_srv_resp_time) += thread_args[j].lookup_srv_timing_info.unpack_lookup_srv_resp_time; (*unpack_lookup_srv_req_time) += thread_args[j].lookup_srv_timing_info.unpack_lookup_srv_req_time; (*lookup_srv_time) += thread_args[j].lookup_srv_timing_info.lookup_srv_time; (*pack_lookup_srv_resp_time) += thread_args[j].lookup_srv_timing_info.pack_lookup_srv_resp_time; } if (!nack) { *lookup_val = "ack"; } router_reply->set_value(*lookup_val); (*create_lookup_srv_req_time) = (*create_lookup_srv_req_time)/replication_cnt; (*unpack_lookup_srv_resp_time) = (*unpack_lookup_srv_resp_time)/replication_cnt; (*unpack_lookup_srv_req_time) = (*unpack_lookup_srv_req_time)/replication_cnt; (*lookup_srv_time) = (*lookup_srv_time)/replication_cnt; (*pack_lookup_srv_resp_time) = (*pack_lookup_srv_resp_time)/replication_cnt; router_reply->set_create_lookup_srv_req_time(*create_lookup_srv_req_time); router_reply->set_unpack_lookup_srv_resp_time(*unpack_lookup_srv_resp_time); router_reply->set_unpack_lookup_srv_req_time(*unpack_lookup_srv_req_time); router_reply->set_lookup_srv_time(*lookup_srv_time); router_reply->set_pack_lookup_srv_resp_time(*pack_lookup_srv_resp_time); router_reply->set_number_of_lookup_servers(replication_cnt); } void MergeAndPack(const std::vector<ResponseData> &response_data, const int replication_cnt, router::LookupResponse* router_reply) { uint64_t create_lookup_srv_req_time = 0, unpack_lookup_srv_resp_time = 0, unpack_lookup_srv_req_time = 0, lookup_srv_time = 0, pack_lookup_srv_resp_time = 0; bool nack = false; std::string lookup_val = ""; for(int i = 0; i < replication_cnt; i++) { if (*(response_data[i].value) == "nack") { lookup_val = "nack"; nack = true; break; } create_lookup_srv_req_time += response_data[i].lookup_srv_timing_info->create_lookup_srv_request_time; unpack_lookup_srv_resp_time += response_data[i].lookup_srv_timing_info->unpack_lookup_srv_resp_time; unpack_lookup_srv_req_time += response_data[i].lookup_srv_timing_info->unpack_lookup_srv_req_time; lookup_srv_time += response_data[i].lookup_srv_timing_info->lookup_srv_time; pack_lookup_srv_resp_time += response_data[i].lookup_srv_timing_info->pack_lookup_srv_resp_time; } if (!nack) { lookup_val = "ack"; } router_reply->set_value(lookup_val); create_lookup_srv_req_time = create_lookup_srv_req_time/replication_cnt; unpack_lookup_srv_resp_time = unpack_lookup_srv_resp_time/replication_cnt; unpack_lookup_srv_req_time = unpack_lookup_srv_req_time/replication_cnt; lookup_srv_time = lookup_srv_time/replication_cnt; pack_lookup_srv_resp_time = pack_lookup_srv_resp_time/replication_cnt; router_reply->set_create_lookup_srv_req_time(create_lookup_srv_req_time); router_reply->set_unpack_lookup_srv_resp_time(unpack_lookup_srv_resp_time); router_reply->set_unpack_lookup_srv_req_time(unpack_lookup_srv_req_time); router_reply->set_lookup_srv_time(lookup_srv_time); router_reply->set_pack_lookup_srv_resp_time(pack_lookup_srv_resp_time); router_reply->set_number_of_lookup_servers(replication_cnt); /* Pack util info for all bucket servers. We do not want the mean because we want to know how each bucket behaves i.e does one perform worse than the others / are they uniform? */ for(int i = 0; i < replication_cnt; i++) { router::Util* lookup_srv_util = router_reply->mutable_util_response()->add_lookup_srv_util(); lookup_srv_util->set_user_time(response_data[i].lookup_srv_util->user_time); lookup_srv_util->set_system_time(response_data[i].lookup_srv_util->system_time); lookup_srv_util->set_io_time(response_data[i].lookup_srv_util->io_time); lookup_srv_util->set_idle_time(response_data[i].lookup_srv_util->idle_time); } } void InitializeTMs(const int num_tms, std::map<TMNames, TMConfig>* all_tms) { for(int i = 0; i < num_tms; i++) { switch(i) { case 0: { TMNames tm_name = sip1; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<TMNames, TMConfig>(tm_name, TMConfig(1, 0, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 1: { TMNames tm_name = sdp1_20; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<TMNames, TMConfig>(tm_name, TMConfig(1, 10, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 2: { TMNames tm_name = sdb1_50; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<TMNames, TMConfig>(tm_name, TMConfig(1, 60, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } #if 0 case 3: { TMNames tm_name = sdb30_50; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<TMNames, TMConfig>(tm_name, TMConfig(30, 50, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 4: { TMNames tm_name = sdb30_10; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<TMNames, TMConfig>(tm_name, TMConfig(30, 10, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 5: { TMNames tm_name = sdb40_30; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<TMNames, TMConfig>(tm_name, TMConfig(40, 30, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 6: { TMNames tm_name = sdb50_20; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<TMNames, TMConfig>(tm_name, TMConfig(50, 20, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 7: { TMNames tm_name = sdp1_50; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<TMNames, TMConfig>(tm_name, TMConfig(1, 50, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } #endif } } } void InitializeAsyncTMs(const int num_tms, std::map<AsyncTMNames, TMConfig>* all_tms) { for(int i = 0; i < num_tms; i++) { switch(i) { case 0: { AsyncTMNames tm_name = aip1_0_1; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<AsyncTMNames, TMConfig>(tm_name, TMConfig(1, 0, 1))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 1: { AsyncTMNames tm_name = adp1_4_1; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<AsyncTMNames, TMConfig>(tm_name, TMConfig(1, 4, 1))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 2: { AsyncTMNames tm_name = adb1_4_4; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<AsyncTMNames, TMConfig>(tm_name, TMConfig(1, 4, 4))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } } } } void InitializeFMSyncTMs(const int num_tms, std::map<FMSyncTMNames, TMConfig>* all_tms) { for(int i = 0; i < num_tms; i++) { switch(i) { case 0: { FMSyncTMNames tm_name = sdb1_1; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<FMSyncTMNames, TMConfig>(tm_name, TMConfig(1, 1, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 1: { FMSyncTMNames tm_name = sdb50_20; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<FMSyncTMNames, TMConfig>(tm_name, TMConfig(50, 20, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } case 2: { FMSyncTMNames tm_name = last_sync; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<FMSyncTMNames, TMConfig>(tm_name, TMConfig(1, 60, 0))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } } } } void InitializeFMAsyncTMs(const int num_tms, std::map<FMAsyncTMNames, TMConfig>* all_tms) { for(int i = 0; i < num_tms; i++) { switch(i) { case 0: { FMAsyncTMNames tm_name = last_async; #ifndef NODEBUG std::cout << "before assigning\n"; #endif all_tms->insert(std::pair<FMAsyncTMNames, TMConfig>(tm_name, TMConfig(1, 4, 4))); #ifndef NODEBUG std::cout << "after assigning\n"; #endif break; } } } }
34.579235
161
0.585651
[ "vector" ]
3a0ea13538452c519871581b9b098e31d8e51205
7,898
cpp
C++
src/utility/asnCertificate.cpp
kaidokert/old-esteid-stack
0391bbf600556dc8527c4f87eed2c95afc878ab4
[ "BSD-3-Clause" ]
null
null
null
src/utility/asnCertificate.cpp
kaidokert/old-esteid-stack
0391bbf600556dc8527c4f87eed2c95afc878ab4
[ "BSD-3-Clause" ]
null
null
null
src/utility/asnCertificate.cpp
kaidokert/old-esteid-stack
0391bbf600556dc8527c4f87eed2c95afc878ab4
[ "BSD-3-Clause" ]
null
null
null
/*! \file asnCertificate.cpp \copyright (c) Kaido Kert ( kaidokert@gmail.com ) \licence BSD \author $Author$ \date $Date$ */ // Revision $Revision$ #include "precompiled.h" #include "asnCertificate.h" #include <sstream> #include <time.h> #define idSubjectAltName "2.5.29.17" #define idKeyUsage "2.5.29.15" #define idExtKeyUsage "2.5.29.37" #define idCrlPoints "2.5.29.31" asnCertificate::asnCertificate(byteVec &in,std::ostream &pout): asnObject(in,pout),extensions(0) { init(); } void asnCertificate::init() { if (contents.size() != 3) throw asn_error("Certificate must consist of three elements"); asnObject * tbsCertificate = contents[0]; signatureAlgorithm = contents[1]; signatureValue = contents[2]; if (tbsCertificate->contents.size() < 7) throw asn_error("tbsCertificate must have at least 7 elements"); version = tbsCertificate->contents[0]; serialNumber = tbsCertificate->contents[1]; signatureAlg = tbsCertificate->contents[2]; issuerName = tbsCertificate->contents[3]; validityPeriod = tbsCertificate->contents[4]; if (validityPeriod->contents.size() != 2) throw asn_error("validityPeriod should have 2 members"); subjectName = tbsCertificate->contents[5]; publicKeyInfo = tbsCertificate->contents[6]; if (tbsCertificate->contents.size() >= 8) extensions = tbsCertificate->contents[7]; } std::string getAlgid(asnObject *obj) { if (obj->tag != asnObject::OBJECTIDENTIFIER) throw asn_error("expected objectidentifier"); if (obj->size < 3) throw asn_error("invalid OBJID"); byteVec body = byteVec(obj->body_start,obj->stop); unsigned char m1 = (body[0] & 0x28 ) ? 0x28 : (body[0] & 0x50 ? 0x50 : 0); if (!m1) throw asn_error("invalid OBJID byte0"); unsigned char val1 = (m1 >> 5); unsigned char val2 = body[0] & (~m1); std::ostringstream buf; buf << (int)val1 << "." << (int)val2 ; for(size_t i=1;i<body.size();i++) { int val = body[i]; while(body[i] & 0x80 && i < body.size() ) val= ((val & 0x7F) << 7) & (body[i++] & 0x7F); buf << "." << (int)val; } string objStr = buf.str(); return objStr; } asnObject *asnCertificate::findExtension(std::string ext) { if (!extensions) return 0; if (!extensions->expl_tag || extensions->tag != 3 || extensions->contents.size() != 1 ) throw "invalid extlist"; asnObject *extList = extensions->contents[0]; for (size_t i= 0;i < extList->contents.size();i++) { asnObject *pExt = extList->contents[i]; if (pExt->tag != SEQUENCE || (pExt->contents.size() != 2 && pExt->contents.size() != 3)) throw asn_error("invalid extension"); asnObject *p0 = pExt->contents[0]; string extId = getAlgid(p0); asnObject *value = pExt->contents[1]; if (pExt->contents.size() == 3 ) value = pExt->contents[2]; if (extId == ext) return value; } return 0; } string asnCertificate::getSubjectAltName() { asnObject * ext = findExtension(idSubjectAltName); if (!ext) return ""; asnObject decode(ext->body_start,ext->stop,0,bout); if (decode.tag!=SEQUENCE) throw asn_error("invalid altName"); std::string ret; for(size_t i=0; i < decode.contents.size(); i++) { ret.resize(ret.size()+ decode.contents[i]->size); copy(decode.contents[i]->body_start,decode.contents[i]->stop, ret.begin()); } return ret; } bool asnCertificate::hasExtKeyUsage() { return (0!=findExtension(idExtKeyUsage)); } bool asnCertificate::checkKeyUsage(string id) { asnObject * ext = findExtension(idExtKeyUsage); if (!ext) return false; asnObject decode(ext->body_start,ext->stop,0,bout); if (decode.tag!=SEQUENCE) throw asn_error("invalid ExtKeyUsage"); for(size_t i=0; i < decode.contents.size(); i++) { string comp = getAlgid(decode.contents[i]); if (comp == id ) return true; } return false; } const char *arrNameIds[][2] = { {"2.5.4.3","CN"}, {"2.5.4.4","SN"}, {"2.5.4.5","Serial Number"}, {"2.5.4.6","C"}, {"2.5.4.10","O"}, {"2.5.4.11","OU"}, {"2.5.4.42","G"}, }; string asnCertificate::getSubject() { string retVal; for(size_t i=0; i < subjectName->contents.size(); i++ ) { asnObject *n = subjectName->contents[i]; if (n->contents.size()!=1 ) throw asn_error("bad namevalue"); asnObject *nv = n->contents[0]; if (nv->contents.size()!=2 ) throw asn_error("bad namevalue, expecting 2 members"); string extId = getAlgid( nv->contents[0] ); int numItems = sizeof(arrNameIds) / sizeof(*arrNameIds); for(int j = 0; j < numItems; j++) { string comp(arrNameIds[j][0]); if (extId == comp) extId = arrNameIds[j][1]; } if (extId!= "CN" && extId != "SN") { //avoid UTF16 for now string val(nv->contents[1]->size ,'0'); copy( nv->contents[1]->body_start,nv->contents[1]->stop,val.begin()); retVal += " ," + extId + " = " + val; } } if (retVal.length() > 2) //remove leading , retVal.erase(0,2); return retVal; } vector<byte> getNameValue(asnObject *p,string extId) { vector<byte> retVal; for(size_t i=0; i < p->contents.size(); i++ ) { asnObject *n = p->contents[i]; if (n->contents.size()!=1 ) throw asn_error("bad namevalue"); asnObject *nv = n->contents[0]; if (nv->contents.size()!=2 ) throw asn_error("bad namevalue, expecting 2 members"); if (extId == getAlgid( nv->contents[0] )) { retVal.resize(nv->contents[1]->size); copy(nv->contents[1]->body_start,nv->contents[1]->stop,retVal.begin()); } } return retVal; } vector<byte> asnCertificate::getSubjectCN() { return getNameValue(subjectName,"2.5.4.3"); } vector<byte> asnCertificate::getSubjectO() { return getNameValue(subjectName,"2.5.4.10"); } vector<byte> asnCertificate::getSubjectOU() { return getNameValue(subjectName,"2.5.4.11"); } vector<byte> asnCertificate::getIssuerCN() { return getNameValue(issuerName,"2.5.4.3"); } vector<byte> asnCertificate::getIssuerO() { return getNameValue(issuerName,"2.5.4.10"); } vector<byte> asnCertificate::getIssuerOU() { return getNameValue(issuerName,"2.5.4.11"); } vector<byte> asnCertificate::getIssuerBlob() { return vector<byte>(issuerName->start,issuerName->stop); } vector<byte> asnCertificate::getSerialBlob() { return vector<byte>(serialNumber->body_start,serialNumber->stop); } vector<byte> asnCertificate::getSubjectBlob() { return vector<byte>(subjectName->start,subjectName->stop); } vector<byte> asnCertificate::getPubKey() { vector<byte> retVal; string comp = getAlgid(publicKeyInfo->contents[0]->contents[0]); asnObject decode( publicKeyInfo->contents[1]->body_start + 1,publicKeyInfo->contents[1]->stop,0,bout); asnObject *target = publicKeyInfo->contents[1]; retVal.resize(target->size - 1); copy(target->body_start +1 ,target->stop,retVal.begin()); return retVal; } string getDateStr(asnObject *v) { if (v->size != 13) throw asn_error("invalid date"); string val(10,'.'),a2("20"); copy(a2.begin(),a2.end(), val.begin() + 6 ); copy(v->body_start + 0,v->body_start +2, val.begin() + 8 ); copy(v->body_start + 2,v->body_start +4, val.begin() + 3); copy(v->body_start + 4,v->body_start +6, val.begin() + 0); return val; } string asnCertificate::getValidFrom() { return getDateStr(validityPeriod->contents[0]); } string asnCertificate::getValidTo() { return getDateStr(validityPeriod->contents[1]); } bool asnCertificate::isTimeValid(int numDaysFromNow) { time_t ti; struct tm mTime; time(&ti); #ifdef _WIN32 localtime_s(&mTime,&ti); #else localtime_r(&ti,&mTime); #endif mTime.tm_mday +=numDaysFromNow; time_t ttmp = mktime(&mTime); #ifdef _WIN32 localtime_s(&mTime,&ttmp); #else localtime_r(&ttmp,&mTime); #endif std::ostringstream buf; buf << std::setfill('0') << std::setw(2) << (mTime.tm_year - 100); buf << std::setfill('0') << std::setw(2) << (mTime.tm_mon + 1) ; buf << std::setfill('0') << std::setw(2) << mTime.tm_mday; string local = buf.str(),cer(13,'0'); copy(validityPeriod->contents[1]->body_start, validityPeriod->contents[1]->stop,cer.begin()); return cer > local; }
29.580524
90
0.669157
[ "vector" ]
3a123a853cdc2e16a61dd8d8e7a480afbae1e01d
5,616
hpp
C++
extras/vom/vom/acl_binding.hpp
mnaser/vpp
8934a04596d1421c35b194949b2027ca1fe71aef
[ "Apache-2.0" ]
1
2019-01-30T02:06:48.000Z
2019-01-30T02:06:48.000Z
extras/vom/vom/acl_binding.hpp
mnaser/vpp
8934a04596d1421c35b194949b2027ca1fe71aef
[ "Apache-2.0" ]
1
2021-06-02T00:52:13.000Z
2021-06-02T00:52:13.000Z
extras/vom/vom/acl_binding.hpp
mnaser/vpp
8934a04596d1421c35b194949b2027ca1fe71aef
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017 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. */ #ifndef __VOM_ACL_BINDING_H__ #define __VOM_ACL_BINDING_H__ #include <ostream> #include "vom/acl_list.hpp" #include "vom/acl_types.hpp" #include "vom/hw.hpp" #include "vom/inspect.hpp" #include "vom/interface.hpp" #include "vom/object_base.hpp" #include "vom/om.hpp" #include "vom/singular_db.hpp" #include "vom/singular_db_funcs.hpp" namespace VOM { namespace ACL { /** * A binding between an ACL and an interface. * A representation of the application of the ACL to the interface. */ template <typename LIST> class binding : public object_base { public: /** * The key for a binding is the direction and the interface */ typedef std::pair<direction_t, interface::key_t> key_t; /** * Construct a new object matching the desried state */ binding(const direction_t& direction, const interface& itf, const LIST& acl) : m_direction(direction) , m_itf(itf.singular()) , m_acl(acl.singular()) , m_binding(false) { m_evh.order(); } /** * Copy Constructor */ binding(const binding& o) : m_direction(o.m_direction) , m_itf(o.m_itf) , m_acl(o.m_acl) , m_binding(o.m_binding) { } /** * Destructor */ ~binding() { sweep(); m_db.release(std::make_pair(m_direction, m_itf->key()), this); } /** * Return the 'singular instance' of the L2 config that matches this * object */ std::shared_ptr<binding> singular() const { return find_or_add(*this); } /** * convert to string format for debug purposes */ std::string to_string() const { std::ostringstream s; s << "acl-binding:[" << m_direction.to_string() << " " << m_itf->to_string() << " " << m_acl->to_string() << " " << m_binding.to_string() << "]"; return (s.str()); } /** * Dump all bindings into the stream provided */ static void dump(std::ostream& os) { m_db.dump(os); } static dependency_t order() { return m_evh.order(); } private: /** * Class definition for listeners to OM events */ class event_handler : public OM::listener, public inspect::command_handler { public: event_handler(); virtual ~event_handler() = default; /** * Handle a populate event */ void handle_populate(const client_db::key_t& key); /** * Handle a replay event */ void handle_replay() { m_db.replay(); } /** * Show the object in the Singular DB */ void show(std::ostream& os) { db_dump(m_db, os); } /** * Get the sortable Id of the listener */ dependency_t order() const; }; /** * event_handler to register with OM */ static event_handler m_evh; /** * Enquue commonds to the VPP command Q for the update */ void update(const binding& obj); /** * Find or Add the instance in the DB */ static std::shared_ptr<binding> find_or_add(const binding& temp) { return (m_db.find_or_add( std::make_pair(temp.m_direction, temp.m_itf->key()), temp)); } /* * It's the OM class that calls singular() */ friend class VOM::OM; /** * It's the singular_db class that calls replay() */ friend class singular_db<key_t, binding>; /** * Sweep/reap the object if still stale */ void sweep(void); /** * Replay the objects state to HW */ void replay(void); /** * The direction the of the packets on which to apply the ACL * input or output */ const direction_t m_direction; /** * A reference counting pointer the interface that this L3 layer * represents. By holding the reference here, we can guarantee that * this object will outlive the interface */ const std::shared_ptr<interface> m_itf; /** * A reference counting pointer the ACL that this * interface is bound to. By holding the reference here, we can * guarantee that this object will outlive the BD. */ const std::shared_ptr<LIST> m_acl; /** * HW configuration for the binding. The bool representing the * do/don't bind. */ HW::item<bool> m_binding; /** * A map of all L2 interfaces key against the interface's handle_t */ static singular_db<key_t, binding> m_db; }; /** * Typedef the L3 binding type */ typedef binding<l3_list> l3_binding; /** * Typedef the L2 binding type */ typedef binding<l2_list> l2_binding; /** * Definition of the static Singular DB for ACL bindings */ template <typename LIST> singular_db<typename ACL::binding<LIST>::key_t, ACL::binding<LIST>> binding<LIST>::m_db; template <typename LIST> typename ACL::binding<LIST>::event_handler binding<LIST>::m_evh; namespace { const static dependency_t __attribute__((unused)) l2o = l2_binding::order(); const static dependency_t __attribute__((unused)) l3o = l3_binding::order(); }; }; std::ostream& operator<<(std::ostream& os, const std::pair<direction_t, interface::key_t>& key); }; /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "mozilla") * End: */ #endif
22.922449
80
0.658298
[ "object" ]
3a133ab05648a4870de3ebc9698a983afc7c2cb5
18,491
cc
C++
content/browser/permissions/permission_controller_impl_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/permissions/permission_controller_impl_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/permissions/permission_controller_impl_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/permissions/permission_controller_impl.h" #include <cstdlib> #include <memory> #include "base/memory/ptr_util.h" #include "base/test/mock_callback.h" #include "content/public/browser/permission_controller_delegate.h" #include "content/public/browser/permission_type.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/mock_permission_manager.h" #include "content/public/test/test_browser_context.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/web_contents_tester.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace content { namespace { using ::testing::Unused; using OverrideStatus = PermissionControllerImpl::OverrideStatus; using RequestsCallback = base::OnceCallback<void( const std::vector<blink::mojom::PermissionStatus>&)>; constexpr char kTestUrl[] = "https://google.com"; class MockManagerWithRequests : public MockPermissionManager { public: MockManagerWithRequests() {} ~MockManagerWithRequests() override {} MOCK_METHOD5( RequestPermissions, int(const std::vector<PermissionType>& permission, RenderFrameHost* render_frame_host, const GURL& requesting_origin, bool user_gesture, const base::OnceCallback<void( const std::vector<blink::mojom::PermissionStatus>&)> callback)); MOCK_METHOD2(SetPermissionOverridesForDevTools, void(const base::Optional<url::Origin>& origin, const PermissionOverrides& overrides)); MOCK_METHOD0(ResetPermissionOverridesForDevTools, void()); MOCK_METHOD2(IsPermissionOverridableByDevTools, bool(PermissionType, const base::Optional<url::Origin>&)); private: DISALLOW_COPY_AND_ASSIGN(MockManagerWithRequests); }; class PermissionControllerImplTest : public ::testing::Test { public: PermissionControllerImplTest() { browser_context_.SetPermissionControllerDelegate( std::make_unique<::testing::NiceMock<MockManagerWithRequests>>()); permission_controller_ = std::make_unique<PermissionControllerImpl>(&browser_context_); } ~PermissionControllerImplTest() override {} void SetUp() override { ON_CALL(*mock_manager(), IsPermissionOverridableByDevTools) .WillByDefault(testing::Return(true)); } PermissionControllerImpl* permission_controller() { return permission_controller_.get(); } BrowserContext* browser_context() { return &browser_context_; } MockManagerWithRequests* mock_manager() { return static_cast<MockManagerWithRequests*>( browser_context_.GetPermissionControllerDelegate()); } private: content::BrowserTaskEnvironment task_environment_; TestBrowserContext browser_context_; std::unique_ptr<PermissionControllerImpl> permission_controller_; DISALLOW_COPY_AND_ASSIGN(PermissionControllerImplTest); }; TEST_F(PermissionControllerImplTest, ResettingOverridesForwardsReset) { EXPECT_CALL(*mock_manager(), ResetPermissionOverridesForDevTools()); permission_controller()->ResetOverridesForDevTools(); } TEST_F(PermissionControllerImplTest, SettingOverridesForwardsUpdates) { auto kTestOrigin = base::make_optional(url::Origin::Create(GURL(kTestUrl))); EXPECT_CALL(*mock_manager(), SetPermissionOverridesForDevTools( kTestOrigin, testing::ElementsAre(testing::Pair( PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::GRANTED)))); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::GRANTED); } TEST_F(PermissionControllerImplTest, RequestPermissionsDelegatesIffMissingOverrides) { url::Origin kTestOrigin = url::Origin::Create(GURL(kTestUrl)); RenderViewHostTestEnabler enabler; const std::vector<PermissionType> kTypesToQuery = { PermissionType::GEOLOCATION, PermissionType::BACKGROUND_SYNC, PermissionType::MIDI_SYSEX}; // Results are defined based on assumption that same types are queried for // each test case. const struct { std::map<PermissionType, blink::mojom::PermissionStatus> overrides; std::vector<PermissionType> delegated_permissions; std::vector<blink::mojom::PermissionStatus> delegated_statuses; std::vector<blink::mojom::PermissionStatus> expected_results; bool expect_death; } kTestCases[] = { // No overrides present - all delegated. {{}, {PermissionType::GEOLOCATION, PermissionType::BACKGROUND_SYNC, PermissionType::MIDI_SYSEX}, {blink::mojom::PermissionStatus::DENIED, blink::mojom::PermissionStatus::GRANTED, blink::mojom::PermissionStatus::GRANTED}, {blink::mojom::PermissionStatus::DENIED, blink::mojom::PermissionStatus::GRANTED, blink::mojom::PermissionStatus::GRANTED}, /*expect_death=*/false}, // No delegates needed - all overridden. {{{PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::GRANTED}, {PermissionType::BACKGROUND_SYNC, blink::mojom::PermissionStatus::GRANTED}, {PermissionType::MIDI_SYSEX, blink::mojom::PermissionStatus::ASK}}, {}, {}, {blink::mojom::PermissionStatus::GRANTED, blink::mojom::PermissionStatus::GRANTED, blink::mojom::PermissionStatus::ASK}, /*expect_death=*/false}, // Some overridden, some delegated. {{{PermissionType::BACKGROUND_SYNC, blink::mojom::PermissionStatus::DENIED}}, {PermissionType::GEOLOCATION, PermissionType::MIDI_SYSEX}, {blink::mojom::PermissionStatus::GRANTED, blink::mojom::PermissionStatus::ASK}, {blink::mojom::PermissionStatus::GRANTED, blink::mojom::PermissionStatus::DENIED, blink::mojom::PermissionStatus::ASK}, /*expect_death=*/false}, // Some overridden, some delegated. {{{PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::GRANTED}, {PermissionType::BACKGROUND_SYNC, blink::mojom::PermissionStatus::DENIED}}, {PermissionType::MIDI_SYSEX}, {blink::mojom::PermissionStatus::ASK}, {blink::mojom::PermissionStatus::GRANTED, blink::mojom::PermissionStatus::DENIED, blink::mojom::PermissionStatus::ASK}, /*expect_death=*/false}, // Too many delegates (causes death). {{{PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::GRANTED}, {PermissionType::MIDI_SYSEX, blink::mojom::PermissionStatus::ASK}}, {PermissionType::BACKGROUND_SYNC}, {blink::mojom::PermissionStatus::DENIED, blink::mojom::PermissionStatus::GRANTED}, // Results don't matter because will die. {}, /*expect_death=*/true}, // Too few delegates (causes death). {{}, {PermissionType::GEOLOCATION, PermissionType::BACKGROUND_SYNC, PermissionType::MIDI_SYSEX}, {blink::mojom::PermissionStatus::GRANTED, blink::mojom::PermissionStatus::GRANTED}, // Results don't matter because will die. {}, /*expect_death=*/true}}; auto web_contents = base::WrapUnique(WebContentsTester::CreateTestWebContents( WebContents::CreateParams(browser_context(), nullptr))); RenderFrameHost* rfh = web_contents->GetMainFrame(); for (const auto& test_case : kTestCases) { // Need to reset overrides for each case to ensure delegation is as // expected. permission_controller()->ResetOverridesForDevTools(); for (const auto& permission_status_pair : test_case.overrides) { permission_controller()->SetOverrideForDevTools( kTestOrigin, permission_status_pair.first, permission_status_pair.second); } // Expect request permission call if override are missing. if (!test_case.delegated_permissions.empty()) { auto forward_callbacks = testing::WithArg<4>( [&test_case](base::OnceCallback<void( const std::vector<blink::mojom::PermissionStatus>&)> callback) { std::move(callback).Run(test_case.delegated_statuses); return 0; }); // Regular tests can set expectations. if (!test_case.expect_death) { EXPECT_CALL( *mock_manager(), RequestPermissions( testing::ElementsAreArray(test_case.delegated_permissions), rfh, kTestOrigin.GetURL(), true, testing::_)) .WillOnce(testing::Invoke(forward_callbacks)); } else { // Death tests cannot track these expectations but arguments should be // forwarded to ensure death occurs. ON_CALL(*mock_manager(), RequestPermissions( testing::ElementsAreArray(test_case.delegated_permissions), rfh, kTestOrigin.GetURL(), true, testing::_)) .WillByDefault(testing::Invoke(forward_callbacks)); } } else { // There should be no call to delegate if all overrides are defined. EXPECT_CALL(*mock_manager(), RequestPermissions).Times(0); } if (!test_case.expect_death) { base::MockCallback<RequestsCallback> callback; EXPECT_CALL(callback, Run(testing::ElementsAreArray(test_case.expected_results))); permission_controller()->RequestPermissions( kTypesToQuery, rfh, kTestOrigin.GetURL(), /*user_gesture=*/true, callback.Get()); } else { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; base::MockCallback<RequestsCallback> callback; EXPECT_DEATH_IF_SUPPORTED(permission_controller()->RequestPermissions( kTypesToQuery, rfh, kTestOrigin.GetURL(), /*user_gesture=*/true, callback.Get()), ""); } } } TEST_F(PermissionControllerImplTest, GetPermissionStatusDelegatesIffNoOverrides) { GURL kUrl = GURL(kTestUrl); url::Origin kTestOrigin = url::Origin::Create(kUrl); EXPECT_CALL(*mock_manager(), GetPermissionStatus(PermissionType::GEOLOCATION, kUrl, kUrl)) .WillOnce(testing::Return(blink::mojom::PermissionStatus::DENIED)); blink::mojom::PermissionStatus status = permission_controller()->GetPermissionStatus(PermissionType::GEOLOCATION, kUrl, kUrl); EXPECT_EQ(status, blink::mojom::PermissionStatus::DENIED); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::GRANTED); EXPECT_CALL(*mock_manager(), GetPermissionStatus(PermissionType::GEOLOCATION, kUrl, kUrl)) .Times(0); status = permission_controller()->GetPermissionStatus( PermissionType::GEOLOCATION, kUrl, kUrl); EXPECT_EQ(status, blink::mojom::PermissionStatus::GRANTED); } TEST_F(PermissionControllerImplTest, GetPermissionStatusForFrameDelegatesIffNoOverrides) { GURL kUrl = GURL(kTestUrl); url::Origin kTestOrigin = url::Origin::Create(kUrl); EXPECT_CALL(*mock_manager(), GetPermissionStatusForFrame( PermissionType::GEOLOCATION, nullptr, kUrl)) .WillOnce(testing::Return(blink::mojom::PermissionStatus::DENIED)); blink::mojom::PermissionStatus status = permission_controller()->GetPermissionStatusForFrame( PermissionType::GEOLOCATION, nullptr, kUrl); EXPECT_EQ(status, blink::mojom::PermissionStatus::DENIED); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::GRANTED); EXPECT_CALL(*mock_manager(), GetPermissionStatusForFrame( PermissionType::GEOLOCATION, nullptr, kUrl)) .Times(0); status = permission_controller()->GetPermissionStatusForFrame( PermissionType::GEOLOCATION, nullptr, kUrl); EXPECT_EQ(status, blink::mojom::PermissionStatus::GRANTED); } TEST_F(PermissionControllerImplTest, NotifyChangedSubscriptionsCallsOnChangeOnly) { using PermissionStatusCallback = base::RepeatingCallback<void(blink::mojom::PermissionStatus)>; GURL kUrl = GURL(kTestUrl); url::Origin kTestOrigin = url::Origin::Create(kUrl); // Setup. blink::mojom::PermissionStatus sync_status = permission_controller()->GetPermissionStatus( PermissionType::BACKGROUND_SYNC, kUrl, kUrl); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::DENIED); base::MockCallback<PermissionStatusCallback> geo_callback; permission_controller()->SubscribePermissionStatusChange( PermissionType::GEOLOCATION, nullptr, kUrl, geo_callback.Get()); base::MockCallback<PermissionStatusCallback> sync_callback; permission_controller()->SubscribePermissionStatusChange( PermissionType::BACKGROUND_SYNC, nullptr, kUrl, sync_callback.Get()); // Geolocation should change status, so subscriber is updated. EXPECT_CALL(geo_callback, Run(blink::mojom::PermissionStatus::ASK)); EXPECT_CALL(sync_callback, Run).Times(0); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::ASK); // Callbacks should not be called again because permission status has not // changed. permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::BACKGROUND_SYNC, sync_status); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::ASK); } TEST_F(PermissionControllerImplTest, PermissionsCannotBeOverriddenIfNotOverridable) { url::Origin kTestOrigin = url::Origin::Create(GURL(kTestUrl)); EXPECT_EQ(OverrideStatus::kOverrideSet, permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::DENIED)); // Delegate will be called, but prevents override from being set. EXPECT_CALL(*mock_manager(), IsPermissionOverridableByDevTools( PermissionType::GEOLOCATION, testing::_)) .WillOnce(testing::Return(false)); EXPECT_EQ(OverrideStatus::kOverrideNotSet, permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::ASK)); blink::mojom::PermissionStatus status = permission_controller()->GetPermissionStatus(PermissionType::GEOLOCATION, kTestOrigin.GetURL(), kTestOrigin.GetURL()); EXPECT_EQ(blink::mojom::PermissionStatus::DENIED, status); } TEST_F(PermissionControllerImplTest, GrantPermissionsReturnsStatusesBeingSetIfOverridable) { GURL kUrl(kTestUrl); url::Origin kTestOrigin = url::Origin::Create(kUrl); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::GEOLOCATION, blink::mojom::PermissionStatus::DENIED); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::MIDI, blink::mojom::PermissionStatus::ASK); permission_controller()->SetOverrideForDevTools( kTestOrigin, PermissionType::BACKGROUND_SYNC, blink::mojom::PermissionStatus::ASK); // Delegate will be called, but prevents override from being set. EXPECT_CALL(*mock_manager(), IsPermissionOverridableByDevTools( PermissionType::GEOLOCATION, testing::_)) .WillOnce(testing::Return(false)); EXPECT_CALL(*mock_manager(), IsPermissionOverridableByDevTools( PermissionType::MIDI, testing::_)) .WillOnce(testing::Return(true)); // Since one cannot be overridden, none are overridden. auto result = permission_controller()->GrantOverridesForDevTools( kTestOrigin, {PermissionType::MIDI, PermissionType::GEOLOCATION, PermissionType::BACKGROUND_SYNC}); EXPECT_EQ(OverrideStatus::kOverrideNotSet, result); // Keep original settings as before. EXPECT_EQ(blink::mojom::PermissionStatus::DENIED, permission_controller()->GetPermissionStatus( PermissionType::GEOLOCATION, kUrl, kUrl)); EXPECT_EQ(blink::mojom::PermissionStatus::ASK, permission_controller()->GetPermissionStatus(PermissionType::MIDI, kUrl, kUrl)); EXPECT_EQ(blink::mojom::PermissionStatus::ASK, permission_controller()->GetPermissionStatus( PermissionType::BACKGROUND_SYNC, kUrl, kUrl)); EXPECT_CALL(*mock_manager(), IsPermissionOverridableByDevTools( PermissionType::GEOLOCATION, testing::_)) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_manager(), IsPermissionOverridableByDevTools( PermissionType::MIDI, testing::_)) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_manager(), IsPermissionOverridableByDevTools( PermissionType::BACKGROUND_SYNC, testing::_)) .WillOnce(testing::Return(true)); // If all can be set, overrides will be stored. result = permission_controller()->GrantOverridesForDevTools( kTestOrigin, {PermissionType::MIDI, PermissionType::GEOLOCATION, PermissionType::BACKGROUND_SYNC}); EXPECT_EQ(OverrideStatus::kOverrideSet, result); EXPECT_EQ(blink::mojom::PermissionStatus::GRANTED, permission_controller()->GetPermissionStatus( PermissionType::GEOLOCATION, kUrl, kUrl)); EXPECT_EQ(blink::mojom::PermissionStatus::GRANTED, permission_controller()->GetPermissionStatus(PermissionType::MIDI, kUrl, kUrl)); EXPECT_EQ(blink::mojom::PermissionStatus::GRANTED, permission_controller()->GetPermissionStatus( PermissionType::BACKGROUND_SYNC, kUrl, kUrl)); } } // namespace } // namespace content
43.102564
80
0.691958
[ "vector" ]
3a175c11282a6a88ea71c66e446283792e795504
4,811
hpp
C++
lumino/Runtime/include/LuminoEngine/Graphics/RenderState.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
30
2016-01-24T05:35:45.000Z
2020-03-03T09:54:27.000Z
lumino/Runtime/include/LuminoEngine/Graphics/RenderState.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
35
2016-04-18T06:14:08.000Z
2020-02-09T15:51:58.000Z
lumino/Runtime/include/LuminoEngine/Graphics/RenderState.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
5
2016-04-03T02:52:05.000Z
2018-01-02T16:53:06.000Z
// Copyright (c) 2019+ lriki. Distributed under the MIT license. #pragma once #include "Common.hpp" namespace ln { /** ブレンディングの演算方法 */ enum class BlendOp : uint8_t { /** 転送元に転送先を加算する。*/ Add, /** 転送元から転送先を減算する。*/ Subtract, /** 転送先から転送元を減算する。*/ ReverseSubtract, /** 転送先と転送元から小さいほうを使用する。*/ Min, /** 転送先と転送元から大きいほうを使用する。*/ Max, }; /** ブレンディングの係数 */ enum class BlendFactor : uint8_t { /** ブレンディング係数は、(0, 0, 0, 0) */ Zero, /** ブレンディング係数は、(1, 1, 1, 1) */ One, /** ブレンディング係数は、(Rs, Gs, Bs, As) */ SourceColor, /** ブレンディング係数は、(1-Rs, 1-Gs, 1-Bs, 1-As) */ InverseSourceColor, /** ブレンディング係数は、(As, As, As, As) */ SourceAlpha, /** ブレンディング係数は、(1-As, 1-As, 1-As, 1-As) */ InverseSourceAlpha, /** ブレンディング係数は、(Rd, Gd, Bd, Ad) */ DestinationColor, /** ブレンディング係数は、(1-Rd, 1-Gd, 1-Bd, 1-Ad) */ InverseDestinationColor, /** ブレンディング係数は、(Ad, Ad, Ad, Ad) */ DestinationAlpha, /** ブレンディング係数は、(1-Ad, 1-Ad, 1-Ad, 1-Ad) */ InverseDestinationAlpha, }; /** 塗りつぶし方法 */ enum class FillMode : uint8_t { /** 面を塗りつぶす */ Solid, /** ワイヤーフレーム */ Wireframe, }; /** カリング方法 */ enum class CullMode : uint8_t { /** 両面を描画します。 */ None, /** 前向きの面を描画しません。 */ Front, /** 後ろ向きの面を描画しません。 */ Back, }; /** 比較関数 */ enum class ComparisonFunc : uint8_t { /** 常に失敗します。 */ Never, /** (新しいピクセル値 < 現在のピクセル値) 新しいピクセル値が、現在のピクセル値未満の場合に、新しいピクセル値を採用します。 */ Less, /** (新しいピクセル値 <= 現在のピクセル値) 新しいピクセル値が、現在のピクセル値以下の場合に、新しいピクセル値を採用します。 */ LessEqual, /** (新しいピクセル値 > 現在のピクセル値) 新しいピクセル値が、現在のピクセル値を超える場合に、新しいピクセル値を採用します。 */ Greater, /** (新しいピクセル値 >= 現在のピクセル値) 新しいピクセル値が、現在のピクセル値以上の場合に、新しいピクセル値を採用します。 */ GreaterEqual, /** (新しいピクセル値 == 現在のピクセル値) 新しいピクセル値が、現在のピクセル値と等しい場合に、新しいピクセル値を採用します。 */ Equal, /** (新しいピクセル値 != 現在のピクセル値) 新しいピクセル値が、現在のピクセル値と等しくない場合に、新しいピクセル値を採用します。 */ NotEqual, /** 常に成功します。 */ Always, }; /** ステンシル処理方法 */ enum class StencilOp : uint8_t { /** 既存のステンシル データを保持します。(何もしません) */ Keep, /** ステンシルデータをステンシル参照値に設定します。 */ Replace, }; /** レンダー ターゲットのブレンディングステート */ struct RenderTargetBlendDesc { /** ブレンディングの有無 (default:false) */ bool blendEnable : 1; /** 入力元の RGB に対する係数 (default: One) */ BlendFactor sourceBlend : 4; /** 出力先の RGB に対する係数 (default: Zero) */ BlendFactor destinationBlend : 4; /** RGB のブレンディング操作 (default: Add) */ BlendOp blendOp; /** 入力元のアルファ値に対する係数 (default: One) */ BlendFactor sourceBlendAlpha : 4; /** 出力先のアルファ値に対する係数 (default: Zero) */ BlendFactor destinationBlendAlpha : 4; /** アルファ値のブレンディング操作 (default: Add) */ BlendOp blendOpAlpha : 4; RenderTargetBlendDesc(); static bool equals(const RenderTargetBlendDesc& lhs, const RenderTargetBlendDesc& rhs); }; /** ブレンディングステート */ struct BlendStateDesc { static const int MaxRenderTargets = 4; /** レンダーターゲットで独立したブレンディングを有効にするには、true に設定します。(default:false) */ bool independentBlendEnable; /** レンダーターゲットごとのブレンドステートの配列です。 */ RenderTargetBlendDesc renderTargets[MaxRenderTargets]; BlendStateDesc(); static bool equals(const BlendStateDesc& lhs, const BlendStateDesc& rhs); }; /** ラスタライザステート */ struct RasterizerStateDesc { /** 塗りつぶし方法 (default:Solid) */ FillMode fillMode : 4; /** カリング方法 (default:Back) */ CullMode cullMode : 4; RasterizerStateDesc(); static bool equals(const RasterizerStateDesc& lhs, const RasterizerStateDesc& rhs); }; /** ステンシル処理 */ struct StencilOpDesc { /** ステンシルテストに失敗した場合のステンシル処理です。(default:Keep) */ StencilOp stencilFailOp : 4; /** ステンシルテストに合格で、深度テストが不合格の場合のステンシル処理です。(default:Keep) */ StencilOp stencilDepthFailOp : 4; /** ステンシルテストと深度テストに合格した場合のステンシル処理です。(default:Keep) */ StencilOp stencilPassOp : 4; /** ステンシルテストの比較関数 (default:Always) */ ComparisonFunc stencilFunc : 4; StencilOpDesc(); static bool equals(const StencilOpDesc& lhs, const StencilOpDesc& rhs); }; /** 深度ステンシルステート */ struct DepthStencilStateDesc { /** 深度テストの比較関数 (default:ComparisonFunc::LessEqual) */ ComparisonFunc depthTestFunc : 4; /** 深度書き込みの有効状態 (default:true) */ bool depthWriteEnabled : 1; /** ステンシルテストの有効状態 (default:false) */ bool stencilEnabled : 1; /** ステンシルテストの参照値 (default:0xFF) */ uint8_t stencilReferenceValue; // TODO: stencilRef は他のパラメータと比べて頻繁に変わる可能性がある。 // DepthStencilState には含めないほうがいいかもしれない。 // OMSetStencilRef、vkCmdSetStencilReference などで個別指定できる。 /** 法線がカメラの方向を向いている面のステンシル処理 */ StencilOpDesc frontFace; /** 法線がカメラと逆方向を向いている面のステンシル処理 */ StencilOpDesc backFace; DepthStencilStateDesc(); static bool equals(const DepthStencilStateDesc& lhs, const DepthStencilStateDesc& rhs); }; } // namespace ln
21.382222
88
0.647475
[ "solid" ]
3a17a50d8a0eb7c103ae964e375b25666aab8a86
2,016
cpp
C++
anycas/src/CASHelperEngineImpl.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
anycas/src/CASHelperEngineImpl.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
anycas/src/CASHelperEngineImpl.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
/** * If not stated otherwise in this file or this component's LICENSE * file the following copyright and licenses apply: * * Copyright 2021 RDK Management * * 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 <cstdio> #include "CASHelperEngineImpl.h" #include "rdk_debug.h" namespace anycas { CASHelperEngineImpl::CASHelperEngineImpl() { } CASHelperEngineImpl::~CASHelperEngineImpl() { } CASHelperEngine& CASHelperEngine::getInstance() { return CASHelperEngineImpl::getInstance(); } CASHelperEngineImpl& CASHelperEngineImpl::getInstance() { static CASHelperEngineImpl impl_; return impl_; } std::shared_ptr<CASHelperFactory> CASHelperEngineImpl::findFactory(const std::vector<uint8_t>& pat, const std::vector<uint8_t>& pmt, const std::vector<uint8_t>& cat, const CASEnvironment& env) { for (auto factory : factories_) { if (factory->isSupported(pat, pmt, cat, env)) { return factory; } } return nullptr; } std::shared_ptr<CASHelperFactory> CASHelperEngineImpl::findFactory(const std::string& ocdmSystemId, const CASEnvironment& env) { for (auto factory : factories_) { if (ocdmSystemId == factory->ocdmSystemId()) { return factory; } } return nullptr; } void CASHelperEngineImpl::registerFactory(std::shared_ptr<CASHelperFactory> factory) { factories_.push_back(factory); RDK_LOG(RDK_LOG_INFO, "LOG.RDK.ANYCAS", "[%s:%d] Registered Factory for %s, now have %d factories stored\n", __FUNCTION__, __LINE__, factory->ocdmSystemId().c_str(), factories_.size()); } } // namespace
29.647059
186
0.754464
[ "vector" ]
3a18fe70e3e2c9b7128bd156a9b2f2c8b711bd17
113,439
cpp
C++
Tests/ResultSetTest.cpp
bowlofstew/mapd-core
21fc39fab9e1dc2c1682bcf3dcc2b49d5503aea6
[ "Apache-2.0" ]
2
2017-05-08T15:46:34.000Z
2017-05-08T23:22:37.000Z
Tests/ResultSetTest.cpp
ngaut/mapd-core
21fc39fab9e1dc2c1682bcf3dcc2b49d5503aea6
[ "Apache-2.0" ]
4
2021-03-12T22:00:18.000Z
2021-03-12T22:01:09.000Z
Tests/ResultSetTest.cpp
bowlofstew/mapd-core
21fc39fab9e1dc2c1682bcf3dcc2b49d5503aea6
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017 MapD Technologies, 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 ResultSetTest.cpp * @author Alex Suhan <alex@mapd.com> * @brief Unit tests for the result set interface. * * Copyright (c) 2014 MapD Technologies, Inc. All rights reserved. */ #include "ResultSetTestUtils.h" #include "../QueryEngine/ResultRows.h" #include "../QueryEngine/ResultSet.h" #include "../QueryEngine/RuntimeFunctions.h" #include "../StringDictionary/StringDictionary.h" #include <boost/make_unique.hpp> #include <glog/logging.h> #include <gtest/gtest.h> #include <algorithm> #include <queue> #include <random> TEST(Construct, Empty) { ResultSet result_set; ASSERT_TRUE(result_set.isEmptyInitializer()); } TEST(Construct, Allocate) { std::vector<TargetInfo> target_infos; QueryMemoryDescriptor query_mem_desc{}; ResultSet result_set( target_infos, ExecutorDeviceType::CPU, query_mem_desc, std::make_shared<RowSetMemoryOwner>(), nullptr); result_set.allocateStorage(); } namespace { class NumberGenerator { public: virtual int64_t getNextValue() = 0; virtual void reset() = 0; }; class EvenNumberGenerator : public NumberGenerator { public: EvenNumberGenerator() : crt_(0) {} int64_t getNextValue() override { const auto crt = crt_; crt_ += 2; return crt; } void reset() override { crt_ = 0; } private: int64_t crt_; }; class ReverseOddOrEvenNumberGenerator : public NumberGenerator { public: ReverseOddOrEvenNumberGenerator(const int64_t init) : crt_(init), init_(init) {} int64_t getNextValue() override { const auto crt = crt_; crt_ -= 2; return crt; } void reset() override { crt_ = init_; } private: int64_t crt_; int64_t init_; }; void write_int(int8_t* slot_ptr, const int64_t v, const size_t slot_bytes) { switch (slot_bytes) { case 4: *reinterpret_cast<int32_t*>(slot_ptr) = v; break; case 8: *reinterpret_cast<int64_t*>(slot_ptr) = v; break; default: CHECK(false); } } void write_fp(int8_t* slot_ptr, const int64_t v, const size_t slot_bytes) { switch (slot_bytes) { case 4: { float fi = v; *reinterpret_cast<int32_t*>(slot_ptr) = *reinterpret_cast<const int32_t*>(may_alias_ptr(&fi)); break; } case 8: { double di = v; *reinterpret_cast<int64_t*>(slot_ptr) = *reinterpret_cast<const int64_t*>(may_alias_ptr(&di)); break; } default: CHECK(false); } } int8_t* fill_one_entry_no_collisions(int8_t* buff, const QueryMemoryDescriptor& query_mem_desc, const int64_t v, const std::vector<TargetInfo>& target_infos, const bool empty, const bool null_val = false) { size_t target_idx = 0; int8_t* slot_ptr = buff; int64_t vv = 0; for (const auto& target_info : target_infos) { CHECK_LT(target_idx, query_mem_desc.agg_col_widths.size()); const auto slot_bytes = query_mem_desc.agg_col_widths[target_idx].actual; CHECK_LE(target_info.sql_type.get_size(), slot_bytes); bool isNullable = !target_info.sql_type.get_notnull(); if (isNullable && target_info.skip_null_val && null_val) { vv = inline_int_null_val(target_info.sql_type); } else { vv = v; } if (empty) { write_int(slot_ptr, query_mem_desc.keyless_hash ? 0 : vv, slot_bytes); } else { if (target_info.sql_type.is_integer()) { write_int(slot_ptr, vv, slot_bytes); } else if (target_info.sql_type.is_string()) { write_int(slot_ptr, -(vv + 2), slot_bytes); } else { CHECK(target_info.sql_type.is_fp()); write_fp(slot_ptr, vv, slot_bytes); } } slot_ptr += slot_bytes; if (target_info.agg_kind == kAVG) { const auto count_slot_bytes = query_mem_desc.agg_col_widths[target_idx + 1].actual; if (empty) { write_int(slot_ptr, query_mem_desc.keyless_hash ? 0 : 0, count_slot_bytes); } else { if (isNullable && target_info.skip_null_val && null_val) { write_int(slot_ptr, 0, count_slot_bytes); // count of elements should be set to 0 for elements with null_val } else { write_int(slot_ptr, 1, count_slot_bytes); // count of elements in the group is 1 - good enough for testing } } slot_ptr += count_slot_bytes; } target_idx = advance_slot(target_idx, target_info, false); } return slot_ptr; } void fill_one_entry_one_col(int8_t* ptr1, const int8_t compact_sz1, int8_t* ptr2, const int8_t compact_sz2, int64_t v, const TargetInfo& target_info, const bool empty_entry, const bool null_val = false) { int64_t vv = 0; bool isNullable = !target_info.sql_type.get_notnull(); if (isNullable && target_info.skip_null_val && null_val) { vv = inline_int_null_val(target_info.sql_type); } else { if (empty_entry && (target_info.agg_kind == kAVG)) { vv = 0; } else { vv = v; } } CHECK(ptr1); switch (compact_sz1) { case 8: if (target_info.sql_type.is_fp()) { double di = vv; *reinterpret_cast<int64_t*>(ptr1) = *reinterpret_cast<const int64_t*>(may_alias_ptr(&di)); } else { *reinterpret_cast<int64_t*>(ptr1) = vv; } break; case 4: CHECK(!target_info.sql_type.is_fp()); *reinterpret_cast<int32_t*>(ptr1) = vv; break; default: CHECK(false); } if (target_info.is_agg && target_info.agg_kind == kAVG) { CHECK(ptr2); switch (compact_sz2) { case 8: *reinterpret_cast<int64_t*>(ptr2) = (empty_entry ? *ptr1 : 1); break; case 4: *reinterpret_cast<int32_t*>(ptr2) = (empty_entry ? *ptr1 : 1); break; default: CHECK(false); } } } void fill_one_entry_one_col(int64_t* value_slot, const int64_t v, const TargetInfo& target_info, const size_t entry_count, const bool empty_entry = false, const bool null_val = false) { auto ptr1 = reinterpret_cast<int8_t*>(value_slot); int8_t* ptr2{nullptr}; if (target_info.agg_kind == kAVG) { ptr2 = reinterpret_cast<int8_t*>(&value_slot[entry_count]); } fill_one_entry_one_col(ptr1, 8, ptr2, 8, v, target_info, empty_entry, null_val); } int8_t* advance_to_next_columnar_key_buff(int8_t* key_ptr, const QueryMemoryDescriptor& query_mem_desc, const size_t key_idx) { CHECK(!query_mem_desc.keyless_hash); CHECK_LT(key_idx, query_mem_desc.group_col_widths.size()); auto new_key_ptr = key_ptr + query_mem_desc.entry_count * query_mem_desc.group_col_widths[key_idx]; if (!query_mem_desc.key_column_pad_bytes.empty()) { CHECK_LT(key_idx, query_mem_desc.key_column_pad_bytes.size()); new_key_ptr += query_mem_desc.key_column_pad_bytes[key_idx]; } return new_key_ptr; } void write_key(const int64_t k, int8_t* ptr, const int8_t key_bytes) { switch (key_bytes) { case 8: { *reinterpret_cast<int64_t*>(ptr) = k; break; } case 4: { *reinterpret_cast<int32_t*>(ptr) = k; break; } default: CHECK(false); } } void fill_storage_buffer_perfect_hash_colwise(int8_t* buff, const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc, NumberGenerator& generator) { const auto key_component_count = get_key_count_for_descriptor(query_mem_desc); CHECK(query_mem_desc.output_columnar); // initialize the key buffer(s) auto col_ptr = buff; for (size_t key_idx = 0; key_idx < key_component_count; ++key_idx) { auto key_entry_ptr = col_ptr; const auto key_bytes = query_mem_desc.group_col_widths[key_idx]; CHECK_EQ(8, key_bytes); for (size_t i = 0; i < query_mem_desc.entry_count; ++i) { if (i % 2 == 0) { const auto v = generator.getNextValue(); write_key(v, key_entry_ptr, key_bytes); } else { write_key(EMPTY_KEY_64, key_entry_ptr, key_bytes); } key_entry_ptr += key_bytes; } col_ptr = advance_to_next_columnar_key_buff(col_ptr, query_mem_desc, key_idx); generator.reset(); } // initialize the value buffer(s) size_t slot_idx = 0; for (const auto& target_info : target_infos) { auto col_entry_ptr = col_ptr; const auto col_bytes = query_mem_desc.agg_col_widths[slot_idx].compact; for (size_t i = 0; i < query_mem_desc.entry_count; ++i) { int8_t* ptr2{nullptr}; if (target_info.agg_kind == kAVG) { ptr2 = col_entry_ptr + query_mem_desc.entry_count * col_bytes; } if (i % 2 == 0) { const auto gen_val = generator.getNextValue(); const auto val = target_info.sql_type.is_string() ? -(gen_val + 2) : gen_val; fill_one_entry_one_col(col_entry_ptr, col_bytes, ptr2, query_mem_desc.agg_col_widths[slot_idx + 1].compact, val, target_info, false); } else { fill_one_entry_one_col(col_entry_ptr, col_bytes, ptr2, query_mem_desc.agg_col_widths[slot_idx + 1].compact, query_mem_desc.keyless_hash ? 0 : 0xdeadbeef, target_info, true); } col_entry_ptr += col_bytes; } col_ptr = advance_to_next_columnar_target_buff(col_ptr, query_mem_desc, slot_idx); if (target_info.is_agg && target_info.agg_kind == kAVG) { col_ptr = advance_to_next_columnar_target_buff(col_ptr, query_mem_desc, slot_idx + 1); } slot_idx = advance_slot(slot_idx, target_info, false); generator.reset(); } } void fill_storage_buffer_perfect_hash_rowwise(int8_t* buff, const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc, NumberGenerator& generator) { const auto key_component_count = get_key_count_for_descriptor(query_mem_desc); CHECK(!query_mem_desc.output_columnar); auto key_buff = buff; for (size_t i = 0; i < query_mem_desc.entry_count; ++i) { if (i % 2 == 0) { const auto v = generator.getNextValue(); auto key_buff_i64 = reinterpret_cast<int64_t*>(key_buff); for (size_t key_comp_idx = 0; key_comp_idx < key_component_count; ++key_comp_idx) { *key_buff_i64++ = v; } auto entries_buff = reinterpret_cast<int8_t*>(key_buff_i64); key_buff = fill_one_entry_no_collisions(entries_buff, query_mem_desc, v, target_infos, false); } else { auto key_buff_i64 = reinterpret_cast<int64_t*>(key_buff); for (size_t key_comp_idx = 0; key_comp_idx < key_component_count; ++key_comp_idx) { *key_buff_i64++ = EMPTY_KEY_64; } auto entries_buff = reinterpret_cast<int8_t*>(key_buff_i64); key_buff = fill_one_entry_no_collisions(entries_buff, query_mem_desc, 0xdeadbeef, target_infos, true); } } } void fill_storage_buffer_baseline_colwise(int8_t* buff, const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc, NumberGenerator& generator, const size_t step) { CHECK(query_mem_desc.output_columnar); const auto key_component_count = get_key_count_for_descriptor(query_mem_desc); const auto i64_buff = reinterpret_cast<int64_t*>(buff); const auto target_slot_count = get_slot_count(target_infos); for (size_t i = 0; i < query_mem_desc.entry_count; ++i) { for (size_t key_comp_idx = 0; key_comp_idx < key_component_count; ++key_comp_idx) { i64_buff[key_offset_colwise(i, key_comp_idx, query_mem_desc.entry_count)] = EMPTY_KEY_64; } for (size_t target_slot = 0; target_slot < target_slot_count; ++target_slot) { i64_buff[slot_offset_colwise(i, target_slot, key_component_count, query_mem_desc.entry_count)] = 0xdeadbeef; } } for (size_t i = 0; i < query_mem_desc.entry_count; i += step) { const auto gen_val = generator.getNextValue(); std::vector<int64_t> key(key_component_count, gen_val); auto value_slots = get_group_value_columnar(i64_buff, query_mem_desc.entry_count, &key[0], key.size()); CHECK(value_slots); for (const auto& target_info : target_infos) { const auto val = target_info.sql_type.is_string() ? -(gen_val + step) : gen_val; fill_one_entry_one_col(value_slots, val, target_info, query_mem_desc.entry_count); value_slots += query_mem_desc.entry_count; if (target_info.agg_kind == kAVG) { value_slots += query_mem_desc.entry_count; } } } } void fill_storage_buffer_baseline_rowwise(int8_t* buff, const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc, NumberGenerator& generator, const size_t step) { const auto key_component_count = get_key_count_for_descriptor(query_mem_desc); const auto i64_buff = reinterpret_cast<int64_t*>(buff); const auto target_slot_count = get_slot_count(target_infos); for (size_t i = 0; i < query_mem_desc.entry_count; ++i) { const auto first_key_comp_offset = key_offset_rowwise(i, key_component_count, target_slot_count); for (size_t key_comp_idx = 0; key_comp_idx < key_component_count; ++key_comp_idx) { i64_buff[first_key_comp_offset + key_comp_idx] = EMPTY_KEY_64; } for (size_t target_slot = 0; target_slot < target_slot_count; ++target_slot) { i64_buff[slot_offset_rowwise(i, target_slot, key_component_count, target_slot_count)] = 0xdeadbeef; } } for (size_t i = 0; i < query_mem_desc.entry_count; i += step) { const auto v = generator.getNextValue(); std::vector<int64_t> key(key_component_count, v); auto value_slots = get_group_value(i64_buff, query_mem_desc.entry_count, &key[0], key.size(), sizeof(int64_t), key_component_count + target_slot_count, nullptr); CHECK(value_slots); fill_one_entry_baseline(value_slots, v, target_infos); } } void fill_storage_buffer(int8_t* buff, const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc, NumberGenerator& generator, const size_t step) { switch (query_mem_desc.hash_type) { case GroupByColRangeType::OneColKnownRange: case GroupByColRangeType::MultiColPerfectHash: { if (query_mem_desc.output_columnar) { fill_storage_buffer_perfect_hash_colwise(buff, target_infos, query_mem_desc, generator); } else { fill_storage_buffer_perfect_hash_rowwise(buff, target_infos, query_mem_desc, generator); } break; } case GroupByColRangeType::MultiCol: { if (query_mem_desc.output_columnar) { fill_storage_buffer_baseline_colwise(buff, target_infos, query_mem_desc, generator, step); } else { fill_storage_buffer_baseline_rowwise(buff, target_infos, query_mem_desc, generator, step); } break; } default: CHECK(false); } CHECK(buff); } // TODO(alex): allow 4 byte keys /* descriptor with small entry_count to simplify testing and debugging */ QueryMemoryDescriptor perfect_hash_one_col_desc_small(const std::vector<TargetInfo>& target_infos, const int8_t num_bytes) { QueryMemoryDescriptor query_mem_desc{}; query_mem_desc.hash_type = GroupByColRangeType::OneColKnownRange; query_mem_desc.min_val = 0; query_mem_desc.max_val = 19; query_mem_desc.has_nulls = false; query_mem_desc.group_col_widths.emplace_back(8); for (const auto& target_info : target_infos) { const auto slot_bytes = std::max(num_bytes, static_cast<int8_t>(target_info.sql_type.get_size())); if (target_info.agg_kind == kAVG) { CHECK(target_info.is_agg); query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.entry_count = query_mem_desc.max_val - query_mem_desc.min_val + 1; return query_mem_desc; } QueryMemoryDescriptor perfect_hash_one_col_desc(const std::vector<TargetInfo>& target_infos, const int8_t num_bytes, const size_t min_val, const size_t max_val) { QueryMemoryDescriptor query_mem_desc{}; query_mem_desc.hash_type = GroupByColRangeType::OneColKnownRange; query_mem_desc.min_val = min_val; query_mem_desc.max_val = max_val; query_mem_desc.has_nulls = false; query_mem_desc.group_col_widths.emplace_back(8); for (const auto& target_info : target_infos) { const auto slot_bytes = std::max(num_bytes, static_cast<int8_t>(target_info.sql_type.get_size())); if (target_info.agg_kind == kAVG) { CHECK(target_info.is_agg); query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.entry_count = query_mem_desc.max_val - query_mem_desc.min_val + 1; return query_mem_desc; } QueryMemoryDescriptor perfect_hash_two_col_desc(const std::vector<TargetInfo>& target_infos, const int8_t num_bytes) { QueryMemoryDescriptor query_mem_desc{}; query_mem_desc.hash_type = GroupByColRangeType::MultiColPerfectHash; query_mem_desc.min_val = 0; query_mem_desc.max_val = 36; query_mem_desc.has_nulls = false; query_mem_desc.group_col_widths.emplace_back(8); query_mem_desc.group_col_widths.emplace_back(8); for (const auto& target_info : target_infos) { const auto slot_bytes = std::max(num_bytes, static_cast<int8_t>(target_info.sql_type.get_size())); if (target_info.agg_kind == kAVG) { CHECK(target_info.is_agg); query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.entry_count = query_mem_desc.max_val; return query_mem_desc; } QueryMemoryDescriptor baseline_hash_two_col_desc_large(const std::vector<TargetInfo>& target_infos, const int8_t num_bytes) { QueryMemoryDescriptor query_mem_desc{}; query_mem_desc.hash_type = GroupByColRangeType::MultiCol; query_mem_desc.min_val = 0; query_mem_desc.max_val = 19; query_mem_desc.has_nulls = false; query_mem_desc.group_col_widths.emplace_back(8); query_mem_desc.group_col_widths.emplace_back(8); for (const auto& target_info : target_infos) { const auto slot_bytes = std::max(num_bytes, static_cast<int8_t>(target_info.sql_type.get_size())); if (target_info.agg_kind == kAVG) { CHECK(target_info.is_agg); query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.entry_count = query_mem_desc.max_val - query_mem_desc.min_val + 1; return query_mem_desc; } QueryMemoryDescriptor baseline_hash_two_col_desc(const std::vector<TargetInfo>& target_infos, const int8_t num_bytes) { QueryMemoryDescriptor query_mem_desc{}; query_mem_desc.hash_type = GroupByColRangeType::MultiCol; query_mem_desc.min_val = 0; query_mem_desc.max_val = 3; query_mem_desc.has_nulls = false; query_mem_desc.group_col_widths.emplace_back(8); query_mem_desc.group_col_widths.emplace_back(8); for (const auto& target_info : target_infos) { const auto slot_bytes = std::max(num_bytes, static_cast<int8_t>(target_info.sql_type.get_size())); if (target_info.agg_kind == kAVG) { CHECK(target_info.is_agg); query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.agg_col_widths.emplace_back(ColWidths{slot_bytes, slot_bytes}); } query_mem_desc.entry_count = query_mem_desc.max_val - query_mem_desc.min_val + 1; return query_mem_desc; } template <class T> const T* vptr(const TargetValue& r) { auto scalar_r = boost::get<ScalarTargetValue>(&r); CHECK(scalar_r); return boost::get<T>(scalar_r); } typedef std::vector<TargetValue> OneRow; /* This class allows to emulate and evaluate ResultSet and it's reduce function. * It creates two ResultSet equivalents, populates them with randomly generated data, * merges them into one, and provides access to the data contained in the merged set. * Comparing these data with the ones received from the ResultSet code reduce procedure * run on the same pair of the ResultSet equivalents, allows to evaluate the functionality * of the ResultSet code. */ class ResultSetEmulator { public: ResultSetEmulator(int8_t* buff1, int8_t* buff2, const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc, NumberGenerator& gen1, NumberGenerator& gen2, const size_t perc1, const size_t perc2, const size_t flow, const bool silent) : rs1_buff(buff1), rs2_buff(buff2), rs_target_infos(target_infos), rs_query_mem_desc(query_mem_desc), rs1_gen(gen1), rs2_gen(gen2), rs1_perc(perc1), rs2_perc(perc2), rs_flow(flow), rs_entry_count(query_mem_desc.entry_count), rs_silent(silent) { rs_entry_count = query_mem_desc.entry_count; // it's set to 10 in "small" query_mem_descriptor rs1_groups.resize(rs_entry_count); std::fill(rs1_groups.begin(), rs1_groups.end(), false); rs2_groups.resize(rs_entry_count); std::fill(rs2_groups.begin(), rs2_groups.end(), false); rs1_values.resize(rs_entry_count); std::fill(rs1_groups.begin(), rs1_groups.end(), 0); rs2_values.resize(rs_entry_count); std::fill(rs2_groups.begin(), rs2_groups.end(), 0); rseReducedGroups.resize(rs_entry_count); std::fill(rseReducedGroups.begin(), rseReducedGroups.end(), false); emulateResultSets(); } ~ResultSetEmulator(){}; std::queue<std::vector<int64_t>> getReferenceTable() const { return rseReducedTable; } std::vector<bool> getReferenceGroupMap() const { return rseReducedGroups; } bool getReferenceGroupMapElement(size_t idx) { CHECK_LE(idx, rseReducedGroups.size() - 1); return rseReducedGroups[idx]; } std::vector<int64_t> getReferenceRow(bool keep_row = false) { std::vector<int64_t> rse_reduced_row(rseReducedTable.front()); rseReducedTable.pop(); if (keep_row) { rseReducedTable.push(rse_reduced_row); } return rse_reduced_row; } int64_t rse_get_null_val() { int64_t null_val = 0; for (const auto& target_info : rs_target_infos) { null_val = inline_int_null_val(target_info.sql_type); break; // currently all of TargetInfo's columns used in tests have same type, so the // they all share same null_val, and that's why the first column is used here. } return null_val; } void print_rse_generated_result_sets() const; void print_merged_result_sets(const std::vector<OneRow>& result); private: void emulateResultSets(); void createResultSet(size_t rs_perc, std::vector<bool>& rs_groups); void mergeResultSets(); int8_t *rs1_buff, *rs2_buff; const std::vector<TargetInfo> rs_target_infos; const QueryMemoryDescriptor rs_query_mem_desc; NumberGenerator &rs1_gen, &rs2_gen; size_t rs1_perc, rs2_perc, rs_flow; size_t rs_entry_count; bool rs_silent; std::vector<bool> rs1_groups; // true if group is in ResultSet #1 std::vector<bool> rs2_groups; // true if group is in ResultSet #2 std::vector<bool> rseReducedGroups; // true if group is in either ResultSet #1 or ResultSet #2 std::vector<int64_t> rs1_values; // generated values for ResultSet #1 std::vector<int64_t> rs2_values; // generated values for ResultSet #2 std::queue<std::vector<int64_t>> rseReducedTable; // combined/reduced values of ResultSet #1 and ResultSet #2 void rse_fill_storage_buffer_perfect_hash_colwise(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values); void rse_fill_storage_buffer_perfect_hash_rowwise(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values); void rse_fill_storage_buffer_baseline_colwise(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values); void rse_fill_storage_buffer_baseline_rowwise(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values); void rse_fill_storage_buffer(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values); void print_emulator_diag(); int64_t rseAggregateKMIN(size_t i); int64_t rseAggregateKMAX(size_t i); int64_t rseAggregateKAVG(size_t i); int64_t rseAggregateKSUM(size_t i); int64_t rseAggregateKCOUNT(size_t i); }; /* top level module to create and fill up ResultSets as well as to generate golden values */ void ResultSetEmulator::emulateResultSets() { /* generate topology of ResultSet #1 */ if (!rs_silent) { printf("\nResultSetEmulator (ResultSet #1): "); } createResultSet(rs1_perc, rs1_groups); if (!rs_silent) { printf("\n"); for (size_t i = 0; i < rs1_groups.size(); i++) { if (rs1_groups[i]) printf("1"); else printf("0"); } } /* generate topology of ResultSet #2 */ if (!rs_silent) { printf("\nResultSetEmulator (ResultSet #2): "); } createResultSet(rs2_perc, rs2_groups); if (!rs_silent) { printf("\n"); for (size_t i = 0; i < rs2_groups.size(); i++) { if (rs2_groups[i]) printf("1"); else printf("0"); } printf("\n"); } /* populate both ResultSet's buffers with real data */ // print_emulator_diag(); rse_fill_storage_buffer(rs1_buff, rs1_gen, rs1_groups, rs1_values); // print_emulator_diag(); rse_fill_storage_buffer(rs2_buff, rs2_gen, rs2_groups, rs2_values); // print_emulator_diag(); /* merge/reduce data contained in both ResultSets and generate golden values */ mergeResultSets(); } /* generate ResultSet topology (create rs_groups and rs_groups_idx vectors) */ void ResultSetEmulator::createResultSet(size_t rs_perc, std::vector<bool>& rs_groups) { std::vector<int> rs_groups_idx; rs_groups_idx.resize(rs_entry_count); std::iota(rs_groups_idx.begin(), rs_groups_idx.end(), 0); std::random_device rs_rd; std::mt19937 rs_rand_gen(rs_rd()); std::shuffle(rs_groups_idx.begin(), rs_groups_idx.end(), rs_rand_gen); for (size_t i = 0; i < (rs_entry_count * rs_perc / 100); i++) { if (!rs_silent) { printf(" %i", rs_groups_idx[i]); } rs_groups[rs_groups_idx[i]] = true; } } /* merge/reduce data contained in both ResultSets and generate golden values */ void ResultSetEmulator::mergeResultSets() { std::vector<int64_t> rse_reduced_row; rse_reduced_row.resize(rs_target_infos.size()); for (size_t j = 0; j < rs_entry_count; j++) { // iterates through rows if (rs1_groups[j] || rs2_groups[j]) { rseReducedGroups[j] = true; for (size_t i = 0; i < rs_target_infos.size(); i++) { // iterates through columns switch (rs_target_infos[i].agg_kind) { case kMIN: { rse_reduced_row[i] = rseAggregateKMIN(j); break; } case kMAX: { rse_reduced_row[i] = rseAggregateKMAX(j); break; } case kAVG: { rse_reduced_row[i] = rseAggregateKAVG(j); break; } case kSUM: { rse_reduced_row[i] = rseAggregateKSUM(j); break; } case kCOUNT: { rse_reduced_row[i] = rseAggregateKCOUNT(j); break; } default: CHECK(false); } } rseReducedTable.push(rse_reduced_row); } } } void ResultSetEmulator::rse_fill_storage_buffer_perfect_hash_colwise(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values) { const auto key_component_count = get_key_count_for_descriptor(rs_query_mem_desc); CHECK(rs_query_mem_desc.output_columnar); // initialize the key buffer(s) auto col_ptr = buff; for (size_t key_idx = 0; key_idx < key_component_count; ++key_idx) { auto key_entry_ptr = col_ptr; const auto key_bytes = rs_query_mem_desc.group_col_widths[key_idx]; CHECK_EQ(8, key_bytes); for (size_t i = 0; i < rs_entry_count; i++) { const auto v = generator.getNextValue(); if (rs_groups[i]) { // const auto v = generator.getNextValue(); write_key(v, key_entry_ptr, key_bytes); } else { write_key(EMPTY_KEY_64, key_entry_ptr, key_bytes); } key_entry_ptr += key_bytes; } col_ptr = advance_to_next_columnar_key_buff(col_ptr, rs_query_mem_desc, key_idx); generator.reset(); } // initialize the value buffer(s) size_t slot_idx = 0; for (const auto& target_info : rs_target_infos) { auto col_entry_ptr = col_ptr; const auto col_bytes = rs_query_mem_desc.agg_col_widths[slot_idx].compact; for (size_t i = 0; i < rs_entry_count; i++) { int8_t* ptr2{nullptr}; if (target_info.agg_kind == kAVG) { ptr2 = col_entry_ptr + rs_query_mem_desc.entry_count * col_bytes; } const auto v = generator.getNextValue(); if (rs_groups[i]) { // const auto v = generator.getNextValue(); rs_values[i] = v; if (rs_flow == 2) { // null_val test-cases if (i >= rs_entry_count - 4) { // only the last four rows of RS #1 and RS #2 exersized for null_val test rs_values[i] = -1; fill_one_entry_one_col(col_entry_ptr, col_bytes, ptr2, rs_query_mem_desc.agg_col_widths[slot_idx + 1].compact, v, target_info, false, true); } else { fill_one_entry_one_col(col_entry_ptr, col_bytes, ptr2, rs_query_mem_desc.agg_col_widths[slot_idx + 1].compact, v, target_info, false, false); } } else { fill_one_entry_one_col(col_entry_ptr, col_bytes, ptr2, rs_query_mem_desc.agg_col_widths[slot_idx + 1].compact, v, target_info, false, false); } } else { if (rs_flow == 2) { // null_val test-cases if (i >= rs_entry_count - 4) { // only the last four rows of RS #1 and RS #2 exersized for null_val test rs_values[i] = -1; } fill_one_entry_one_col(col_entry_ptr, col_bytes, ptr2, rs_query_mem_desc.agg_col_widths[slot_idx + 1].compact, rs_query_mem_desc.keyless_hash ? 0 : 0xdeadbeef, target_info, true, true); } else { fill_one_entry_one_col(col_entry_ptr, col_bytes, ptr2, rs_query_mem_desc.agg_col_widths[slot_idx + 1].compact, rs_query_mem_desc.keyless_hash ? 0 : 0xdeadbeef, target_info, true, false); } } col_entry_ptr += col_bytes; } col_ptr = advance_to_next_columnar_target_buff(col_ptr, rs_query_mem_desc, slot_idx); if (target_info.is_agg && target_info.agg_kind == kAVG) { col_ptr = advance_to_next_columnar_target_buff(col_ptr, rs_query_mem_desc, slot_idx + 1); } slot_idx = advance_slot(slot_idx, target_info, false); generator.reset(); } } void ResultSetEmulator::rse_fill_storage_buffer_perfect_hash_rowwise(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values) { const auto key_component_count = get_key_count_for_descriptor(rs_query_mem_desc); CHECK(!rs_query_mem_desc.output_columnar); auto key_buff = buff; CHECK_EQ(rs_groups.size(), rs_query_mem_desc.entry_count); for (size_t i = 0; i < rs_groups.size(); i++) { const auto v = generator.getNextValue(); if (rs_groups[i]) { // const auto v = generator.getNextValue(); rs_values[i] = v; auto key_buff_i64 = reinterpret_cast<int64_t*>(key_buff); for (size_t key_comp_idx = 0; key_comp_idx < key_component_count; ++key_comp_idx) { *key_buff_i64++ = v; } auto entries_buff = reinterpret_cast<int8_t*>(key_buff_i64); if (rs_flow == 2) { // null_vall test-cases if (i >= rs_entry_count - 4) { // only the last four rows of RS #1 and RS #2 exersized for null_val test rs_values[i] = -1; key_buff = fill_one_entry_no_collisions(entries_buff, rs_query_mem_desc, v, rs_target_infos, false, true); } else { key_buff = fill_one_entry_no_collisions(entries_buff, rs_query_mem_desc, v, rs_target_infos, false, false); } } else { key_buff = fill_one_entry_no_collisions(entries_buff, rs_query_mem_desc, v, rs_target_infos, false); } } else { auto key_buff_i64 = reinterpret_cast<int64_t*>(key_buff); for (size_t key_comp_idx = 0; key_comp_idx < key_component_count; ++key_comp_idx) { *key_buff_i64++ = EMPTY_KEY_64; } auto entries_buff = reinterpret_cast<int8_t*>(key_buff_i64); if (rs_flow == 2) { // null_val test-cases if (i >= rs_entry_count - 4) { // only the last four rows of RS #1 and RS #2 exersized for null_val test rs_values[i] = -1; } key_buff = fill_one_entry_no_collisions(entries_buff, rs_query_mem_desc, 0xdeadbeef, rs_target_infos, true, true); } else { key_buff = fill_one_entry_no_collisions(entries_buff, rs_query_mem_desc, 0xdeadbeef, rs_target_infos, true); } } } } void ResultSetEmulator::rse_fill_storage_buffer_baseline_colwise(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values) { CHECK(rs_query_mem_desc.output_columnar); const auto key_component_count = get_key_count_for_descriptor(rs_query_mem_desc); const auto i64_buff = reinterpret_cast<int64_t*>(buff); for (size_t i = 0; i < rs_entry_count; i++) { for (size_t key_comp_idx = 0; key_comp_idx < key_component_count; ++key_comp_idx) { i64_buff[key_offset_colwise(i, key_comp_idx, rs_entry_count)] = EMPTY_KEY_64; } size_t target_slot = 0; int64_t init_val = 0; for (const auto& target_info : rs_target_infos) { if (!target_info.sql_type.get_notnull() && target_info.skip_null_val && (rs_flow == 2)) { // null_val support init_val = inline_int_null_val(target_info.sql_type); } else { init_val = 0xdeadbeef; } if (target_info.agg_kind != kAVG) { i64_buff[slot_offset_colwise(i, target_slot, key_component_count, rs_entry_count)] = init_val; } else { i64_buff[slot_offset_colwise(i, target_slot, key_component_count, rs_entry_count)] = 0; } target_slot++; } } for (size_t i = 0; i < rs_entry_count; i++) { const auto v = generator.getNextValue(); if (rs_groups[i]) { bool null_val = false; if ((rs_flow == 2) && (i >= rs_entry_count - 4)) { // null_val test-cases: last four rows rs_values[i] = -1; null_val = true; } else { rs_values[i] = v; } std::vector<int64_t> key(key_component_count, v); auto value_slots = get_group_value_columnar(i64_buff, rs_entry_count, &key[0], key.size()); CHECK(value_slots); for (const auto& target_info : rs_target_infos) { fill_one_entry_one_col(value_slots, v, target_info, rs_entry_count, false, null_val); value_slots += rs_entry_count; if (target_info.agg_kind == kAVG) { value_slots += rs_entry_count; } } } } } void ResultSetEmulator::rse_fill_storage_buffer_baseline_rowwise(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values) { CHECK(!rs_query_mem_desc.output_columnar); CHECK_EQ(rs_groups.size(), rs_query_mem_desc.entry_count); const auto key_component_count = get_key_count_for_descriptor(rs_query_mem_desc); const auto i64_buff = reinterpret_cast<int64_t*>(buff); const auto target_slot_count = get_slot_count(rs_target_infos); for (size_t i = 0; i < rs_entry_count; i++) { const auto first_key_comp_offset = key_offset_rowwise(i, key_component_count, target_slot_count); for (size_t key_comp_idx = 0; key_comp_idx < key_component_count; ++key_comp_idx) { i64_buff[first_key_comp_offset + key_comp_idx] = EMPTY_KEY_64; } size_t target_slot = 0; int64_t init_val = 0; for (const auto& target_info : rs_target_infos) { if (!target_info.sql_type.get_notnull() && target_info.skip_null_val && (rs_flow == 2)) { // null_val support init_val = inline_int_null_val(target_info.sql_type); } else { init_val = 0xdeadbeef; } i64_buff[slot_offset_rowwise(i, target_slot, key_component_count, target_slot_count)] = init_val; target_slot++; if (target_info.agg_kind == kAVG) { i64_buff[slot_offset_rowwise(i, target_slot, key_component_count, target_slot_count)] = 0; target_slot++; } } } for (size_t i = 0; i < rs_entry_count; i++) { const auto v = generator.getNextValue(); if (rs_groups[i]) { std::vector<int64_t> key(key_component_count, v); auto value_slots = get_group_value(i64_buff, rs_entry_count, &key[0], key.size(), sizeof(int64_t), key_component_count + target_slot_count, nullptr); CHECK(value_slots); if ((rs_flow == 2) && (i >= rs_entry_count - 4)) { // null_val test-cases: last four rows rs_values[i] = -1; fill_one_entry_baseline(value_slots, v, rs_target_infos, false, true); } else { rs_values[i] = v; fill_one_entry_baseline(value_slots, v, rs_target_infos, false, false); } } } } void ResultSetEmulator::rse_fill_storage_buffer(int8_t* buff, NumberGenerator& generator, const std::vector<bool>& rs_groups, std::vector<int64_t>& rs_values) { switch (rs_query_mem_desc.hash_type) { case GroupByColRangeType::OneColKnownRange: case GroupByColRangeType::MultiColPerfectHash: { if (rs_query_mem_desc.output_columnar) { rse_fill_storage_buffer_perfect_hash_colwise(buff, generator, rs_groups, rs_values); } else { rse_fill_storage_buffer_perfect_hash_rowwise(buff, generator, rs_groups, rs_values); } break; } case GroupByColRangeType::MultiCol: { if (rs_query_mem_desc.output_columnar) { rse_fill_storage_buffer_baseline_colwise(buff, generator, rs_groups, rs_values); } else { rse_fill_storage_buffer_baseline_rowwise(buff, generator, rs_groups, rs_values); } break; } default: CHECK(false); } CHECK(buff); } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #else #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif void ResultSetEmulator::print_emulator_diag() { if (!rs_silent) { for (size_t j = 0; j < rs_entry_count; j++) { int g1 = 0, g2 = 0; if (rs1_groups[j]) { g1 = 1; } if (rs2_groups[j]) { g2 = 1; } printf("\nGroup #%i (%i,%i): Buf1=%lld Buf2=%lld", (int)j, g1, g2, static_cast<long long>(rs1_values[j]), static_cast<long long>(rs2_values[j])); } } } #ifdef __clang__ #pragma clang diagnostic pop #else #pragma GCC diagnostic pop #endif void ResultSetEmulator::print_rse_generated_result_sets() const { printf("\nResultSet #1 Final Groups: "); for (size_t i = 0; i < rs1_groups.size(); i++) { if (rs1_groups[i]) printf("1"); else printf("0"); } printf("\nResultSet #2 Final Groups: "); for (size_t i = 0; i < rs2_groups.size(); i++) { if (rs2_groups[i]) printf("1"); else printf("0"); } printf("\n"); } void ResultSetEmulator::print_merged_result_sets(const std::vector<OneRow>& result) { printf("\n ****** KMIN_DATA_FROM_RS_MERGE_CODE ****** %i", (int)result.size()); size_t j = 0; for (const auto& row : result) { const auto ival_0 = v<int64_t>(row[0]); // kMIN const auto ival_1 = v<int64_t>(row[1]); // kMAX const auto ival_2 = v<int64_t>(row[2]); // kSUM const auto ival_3 = v<int64_t>(row[3]); // kCOUNT const auto ival_4 = v<double>(row[4]); // kAVG printf("\n Group #%i KMIN/KMAX/KSUM/KCOUNT from RS_MergeCode: %lld %lld %lld %lld %f", (int)j, static_cast<long long>(ival_0), static_cast<long long>(ival_1), static_cast<long long>(ival_2), static_cast<long long>(ival_3), ival_4); j++; } size_t active_group_count = 0; for (size_t j = 0; j < rseReducedGroups.size(); j++) { if (rseReducedGroups[j]) active_group_count++; } printf("\n\n ****** KMIN_DATA_FROM_MERGE_BUFFER_CODE ****** Total: %i, Active: %i", (int)rs_entry_count, (int)active_group_count); size_t num_groups = getReferenceTable().size(); for (size_t i = 0; i < num_groups; i++) { std::vector<int64_t> ref_row = getReferenceRow(true); int64_t ref_val_0 = ref_row[0]; // kMIN int64_t ref_val_1 = ref_row[1]; // kMAX int64_t ref_val_2 = ref_row[2]; // kSUM int64_t ref_val_3 = ref_row[3]; // kCOUNT int64_t ref_val_4 = ref_row[4]; // kAVG printf("\n Group #%i KMIN/KMAX/KSUM/KCOUNT from ReducedBuffer: %lld %lld %lld %lld %f", static_cast<int>(i), static_cast<long long>(ref_val_0), static_cast<long long>(ref_val_1), static_cast<long long>(ref_val_2), static_cast<long long>(ref_val_3), static_cast<double>(ref_val_4)); } printf("\n"); } int64_t ResultSetEmulator::rseAggregateKMIN(size_t i) { int64_t result = rse_get_null_val(); if (rs1_groups[i] && rs2_groups[i]) { if ((rs1_values[i] == -1) && (rs2_values[i] == -1)) { return result; } else { if ((rs1_values[i] != -1) && (rs2_values[i] != -1)) { result = std::min(rs1_values[i], rs2_values[i]); } else { result = std::max(rs1_values[i], rs2_values[i]); } } } else { if (rs1_groups[i]) { if (rs1_values[i] != -1) { result = rs1_values[i]; } } else { if (rs2_groups[i]) { if (rs2_values[i] != -1) { result = rs2_values[i]; } } } } return result; } int64_t ResultSetEmulator::rseAggregateKMAX(size_t i) { int64_t result = rse_get_null_val(); if (rs1_groups[i] && rs2_groups[i]) { if ((rs1_values[i] == -1) && (rs2_values[i] == -1)) { return result; } else { result = std::max(rs1_values[i], rs2_values[i]); } } else { if (rs1_groups[i]) { if (rs1_values[i] != -1) { result = rs1_values[i]; } } else { if (rs2_groups[i]) { if (rs2_values[i] != -1) { result = rs2_values[i]; } } } } return result; } int64_t ResultSetEmulator::rseAggregateKAVG(size_t i) { int64_t result = 0; int n1 = 1, n2 = 1; // for test purposes count of elements in each group is 1 (see proc "fill_one_entry_no_collisions") if (rs1_groups[i] && rs2_groups[i]) { if ((rs1_values[i] == -1) && (rs2_values[i] == -1)) { // return rse_get_null_val(); return result; } int n = 0; if (rs1_values[i] != -1) { result += rs1_values[i] / n1; n++; } if (rs2_values[i] != -1) { result += rs2_values[i] / n2; n++; } if (n > 1) { result /= n; } } else { // result = rse_get_null_val(); if (rs1_groups[i]) { if (rs1_values[i] != -1) { result = rs1_values[i] / n1; } } else { if (rs2_groups[i]) { if (rs2_values[i] != -1) { result = rs2_values[i] / n2; } } } } return result; } int64_t ResultSetEmulator::rseAggregateKSUM(size_t i) { int64_t result = 0; if (rs1_groups[i] && rs2_groups[i]) { if ((rs1_values[i] == -1) && (rs2_values[i] == -1)) { return rse_get_null_val(); } if (rs1_values[i] != -1) { result += rs1_values[i]; } if (rs2_values[i] != -1) { result += rs2_values[i]; } } else { result = rse_get_null_val(); if (rs1_groups[i]) { if (rs1_values[i] != -1) { result = rs1_values[i]; } } else { if (rs2_groups[i]) { if (rs2_values[i] != -1) { result = rs2_values[i]; } } } } return result; } int64_t ResultSetEmulator::rseAggregateKCOUNT(size_t i) { int64_t result = 0; if (rs1_groups[i] && rs2_groups[i]) { if ((rs1_values[i] == -1) && (rs2_values[i] == -1)) { return rse_get_null_val(); } if (rs1_values[i] != -1) { result += rs1_values[i]; } if (rs2_values[i] != -1) { result += rs2_values[i]; } } else { result = rse_get_null_val(); if (rs1_groups[i]) { if (rs1_values[i] != -1) { result = rs1_values[i]; } } else { if (rs2_groups[i]) { if (rs2_values[i] != -1) { result = rs2_values[i]; } } } } return result; } bool approx_eq(const double v, const double target, const double eps = 0.01) { return target - eps < v && v < target + eps; } std::shared_ptr<StringDictionary> g_sd = std::make_shared<StringDictionary>(""); void test_iterate(const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc) { SQLTypeInfo double_ti(kDOUBLE, false); auto row_set_mem_owner = std::make_shared<RowSetMemoryOwner>(); StringDictionaryProxy* sdp = row_set_mem_owner->addStringDict(g_sd, 1, g_sd->storageEntryCount()); ResultSet result_set(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr); for (size_t i = 0; i < query_mem_desc.entry_count; ++i) { sdp->getOrAddTransient(std::to_string(i)); } const auto storage = result_set.allocateStorage(); EvenNumberGenerator generator; fill_storage_buffer(storage->getUnderlyingBuffer(), target_infos, query_mem_desc, generator, 2); int64_t ref_val{0}; while (true) { const auto row = result_set.getNextRow(true, false); if (row.empty()) { break; } CHECK_EQ(target_infos.size(), row.size()); for (size_t i = 0; i < target_infos.size(); ++i) { const auto& target_info = target_infos[i]; const auto& ti = target_info.agg_kind == kAVG ? double_ti : target_info.sql_type; switch (ti.get_type()) { case kSMALLINT: case kINT: case kBIGINT: { const auto ival = v<int64_t>(row[i]); ASSERT_EQ(ref_val, ival); break; } case kDOUBLE: { const auto dval = v<double>(row[i]); ASSERT_TRUE(approx_eq(static_cast<double>(ref_val), dval)); break; } case kTEXT: { const auto sval = v<NullableString>(row[i]); ASSERT_EQ(std::to_string(ref_val), boost::get<std::string>(sval)); break; } default: CHECK(false); } } ref_val += 2; } } std::vector<TargetInfo> generate_test_target_infos() { std::vector<TargetInfo> target_infos; SQLTypeInfo int_ti(kINT, false); SQLTypeInfo double_ti(kDOUBLE, false); SQLTypeInfo null_ti(kNULLT, false); target_infos.push_back(TargetInfo{false, kMIN, int_ti, null_ti, true, false}); target_infos.push_back(TargetInfo{true, kAVG, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kSUM, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{false, kMIN, double_ti, null_ti, true, false}); { SQLTypeInfo dict_string_ti(kTEXT, false); dict_string_ti.set_compression(kENCODING_DICT); dict_string_ti.set_comp_param(1); target_infos.push_back(TargetInfo{false, kMIN, dict_string_ti, null_ti, true, false}); } return target_infos; } std::vector<TargetInfo> generate_random_groups_target_infos() { std::vector<TargetInfo> target_infos; SQLTypeInfo int_ti(kINT, true); SQLTypeInfo double_ti(kDOUBLE, true); // SQLTypeInfo null_ti(kNULLT, false); target_infos.push_back(TargetInfo{true, kMIN, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kMAX, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kSUM, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kCOUNT, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kAVG, int_ti, double_ti, true, false}); return target_infos; } std::vector<TargetInfo> generate_random_groups_nullable_target_infos() { std::vector<TargetInfo> target_infos; SQLTypeInfo int_ti(kINT, false); // SQLTypeInfo null_ti(kNULLT, false); SQLTypeInfo double_ti(kDOUBLE, false); target_infos.push_back(TargetInfo{true, kMIN, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kMAX, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kSUM, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kCOUNT, int_ti, int_ti, true, false}); target_infos.push_back(TargetInfo{true, kAVG, int_ti, double_ti, true, false}); return target_infos; } std::vector<OneRow> get_rows_sorted_by_col(ResultSet& rs, const size_t col_idx) { std::list<Analyzer::OrderEntry> order_entries; order_entries.emplace_back(1, false, false); rs.sort(order_entries, 0); std::vector<OneRow> result; while (true) { const auto row = rs.getNextRow(false, false); if (row.empty()) { break; } result.push_back(row); } return result; } void test_reduce(const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc, NumberGenerator& generator1, NumberGenerator& generator2, const int step) { SQLTypeInfo double_ti(kDOUBLE, false); const ResultSetStorage* storage1{nullptr}; const ResultSetStorage* storage2{nullptr}; const auto row_set_mem_owner = std::make_shared<RowSetMemoryOwner>(); row_set_mem_owner->addStringDict(g_sd, 1, g_sd->storageEntryCount()); const auto rs1 = boost::make_unique<ResultSet>(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr); storage1 = rs1->allocateStorage(); fill_storage_buffer(storage1->getUnderlyingBuffer(), target_infos, query_mem_desc, generator1, step); const auto rs2 = boost::make_unique<ResultSet>(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr); storage2 = rs2->allocateStorage(); fill_storage_buffer(storage2->getUnderlyingBuffer(), target_infos, query_mem_desc, generator2, step); ResultSetManager rs_manager; std::vector<ResultSet*> storage_set{rs1.get(), rs2.get()}; auto result_rs = rs_manager.reduce(storage_set); int64_t ref_val{0}; std::list<Analyzer::OrderEntry> order_entries; order_entries.emplace_back(1, false, false); result_rs->sort(order_entries, 0); while (true) { const auto row = result_rs->getNextRow(false, false); if (row.empty()) { break; } CHECK_EQ(target_infos.size(), row.size()); for (size_t i = 0; i < target_infos.size(); ++i) { const auto& target_info = target_infos[i]; const auto& ti = target_info.agg_kind == kAVG ? double_ti : target_info.sql_type; switch (ti.get_type()) { case kSMALLINT: case kINT: case kBIGINT: { const auto ival = v<int64_t>(row[i]); ASSERT_EQ((target_info.agg_kind == kSUM || target_info.agg_kind == kCOUNT) ? step * ref_val : ref_val, ival); break; } case kDOUBLE: { const auto dval = v<double>(row[i]); ASSERT_TRUE(approx_eq( static_cast<double>((target_info.agg_kind == kSUM || target_info.agg_kind == kCOUNT) ? step * ref_val : ref_val), dval)); break; } case kTEXT: break; default: CHECK(false); } } ref_val += step; } } void test_reduce_random_groups(const std::vector<TargetInfo>& target_infos, const QueryMemoryDescriptor& query_mem_desc, NumberGenerator& generator1, NumberGenerator& generator2, const int prct1, const int prct2, bool silent, const int flow = 0) { SQLTypeInfo double_ti(kDOUBLE, false); const ResultSetStorage* storage1{nullptr}; const ResultSetStorage* storage2{nullptr}; std::unique_ptr<ResultSet> rs1; std::unique_ptr<ResultSet> rs2; const auto row_set_mem_owner = std::make_shared<RowSetMemoryOwner>(); switch (query_mem_desc.hash_type) { case GroupByColRangeType::OneColKnownRange: case GroupByColRangeType::MultiColPerfectHash: { rs1.reset(new ResultSet(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr)); storage1 = rs1->allocateStorage(); rs2.reset(new ResultSet(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr)); storage2 = rs2->allocateStorage(); break; } case GroupByColRangeType::MultiCol: { rs1.reset(new ResultSet(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr)); storage1 = rs1->allocateStorage(); rs2.reset(new ResultSet(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr)); storage2 = rs2->allocateStorage(); break; } default: CHECK(false); } ResultSetEmulator* rse = new ResultSetEmulator(storage1->getUnderlyingBuffer(), storage2->getUnderlyingBuffer(), target_infos, query_mem_desc, generator1, generator2, prct1, prct2, flow, silent); if (!silent) { rse->print_rse_generated_result_sets(); } ResultSetManager rs_manager; std::vector<ResultSet*> storage_set{rs1.get(), rs2.get()}; auto result_rs = rs_manager.reduce(storage_set); std::queue<std::vector<int64_t>> ref_table = rse->getReferenceTable(); std::vector<bool> ref_group_map = rse->getReferenceGroupMap(); const auto result = get_rows_sorted_by_col(*result_rs, 0); CHECK(!result.empty()); if (!silent) { rse->print_merged_result_sets(result); } size_t row_idx = 0; int64_t ref_val = 0; for (const auto& row : result) { CHECK_EQ(target_infos.size(), row.size()); while (true) { if (row_idx >= rse->getReferenceGroupMap().size()) { LOG(FATAL) << "Number of groups in reduced result set is more than expected"; } if (rse->getReferenceGroupMapElement(row_idx)) { break; } else { row_idx++; continue; } } std::vector<int64_t> ref_row = rse->getReferenceRow(); for (size_t i = 0; i < target_infos.size(); ++i) { ref_val = ref_row[i]; const auto& target_info = target_infos[i]; const auto& ti = target_info.agg_kind == kAVG ? double_ti : target_info.sql_type; std::string p_tag(""); if (flow == 2) { // null_val test-cases p_tag += "kNULLT_"; } switch (ti.get_type()) { case kSMALLINT: case kINT: case kBIGINT: { const auto ival = v<int64_t>(row[i]); switch (target_info.agg_kind) { case kMIN: { if (!silent) { p_tag += "KMIN"; printf("\n%s row_idx = %i, ref_val = %lld, ival = %lld", p_tag.c_str(), static_cast<int>(row_idx), static_cast<long long>(ref_val), static_cast<long long>(ival)); if (ref_val != ival) { printf("%21s%s%s", "", p_tag.c_str(), " TEST FAILED!\n"); } else { printf("%21s%s%s", "", p_tag.c_str(), " TEST PASSED!\n"); } } else { ASSERT_EQ(ref_val, ival); } break; } case kMAX: { if (!silent) { p_tag += "KMAX"; printf("\n%s row_idx = %i, ref_val = %lld, ival = %lld", p_tag.c_str(), static_cast<int>(row_idx), static_cast<long long>(ref_val), static_cast<long long>(ival)); if (ref_val != ival) { printf("%21s%s%s", "", p_tag.c_str(), " TEST FAILED!\n"); } else { printf("%21s%s%s", "", p_tag.c_str(), " TEST PASSED!\n"); } } else { ASSERT_EQ(ref_val, ival); } break; } case kAVG: { if (!silent) { p_tag += "KAVG"; printf("\n%s row_idx = %i, ref_val = %lld, ival = %lld", p_tag.c_str(), static_cast<int>(row_idx), static_cast<long long>(ref_val), static_cast<long long>(ival)); if (ref_val != ival) { printf("%21s%s%s", "", p_tag.c_str(), " TEST FAILED1!\n"); } else { printf("%21s%s%s", "", p_tag.c_str(), " TEST PASSED!\n"); } } else { ASSERT_EQ(ref_val, ival); } break; } case kSUM: case kCOUNT: { if (!silent) { p_tag += "KSUM"; printf("\n%s row_idx = %i, ref_val = %lld, ival = %lld", p_tag.c_str(), static_cast<int>(row_idx), static_cast<long long>(ref_val), static_cast<long long>(ival)); if (ref_val != ival) { printf("%21s%s%s", "", p_tag.c_str(), " TEST FAILED!\n"); } else { printf("%21s%s%s", "", p_tag.c_str(), " TEST PASSED!\n"); } } else { ASSERT_EQ(ref_val, ival); } break; } default: CHECK(false); } break; } case kDOUBLE: { const auto dval = v<double>(row[i]); switch (target_info.agg_kind) { case kMIN: { if (!silent) { p_tag += "KMIN_D"; printf("\nKMIN_D row_idx = %i, ref_val = %f, dval = %f", static_cast<int>(row_idx), static_cast<double>(ref_val), dval); if (!approx_eq(static_cast<double>(ref_val), dval)) { printf("%5s%s%s", "", p_tag.c_str(), " TEST FAILED!\n"); } else { printf("%5s%s%s", "", p_tag.c_str(), " TEST PASSED!\n"); } } else { ASSERT_TRUE(approx_eq(static_cast<double>(ref_val), dval)); } break; } case kMAX: { if (!silent) { p_tag += "KMAX_D"; printf("\n%s row_idx = %i, ref_val = %f, dval = %f", p_tag.c_str(), static_cast<int>(row_idx), static_cast<double>(ref_val), dval); if (!approx_eq(static_cast<double>(ref_val), dval)) { printf("%5s%s%s", "", p_tag.c_str(), " TEST FAILED!\n"); } else { printf("%5s%s%s", "", p_tag.c_str(), " TEST PASSED!\n"); } } else { ASSERT_TRUE(approx_eq(static_cast<double>(ref_val), dval)); } break; } case kAVG: { if (!silent) { p_tag += "KAVG_D"; printf("\n%s row_idx = %i, ref_val = %f, dval = %f", p_tag.c_str(), static_cast<int>(row_idx), static_cast<double>(ref_val), dval); if (!approx_eq(static_cast<double>(ref_val), dval)) { printf("%5s%s%s", "", p_tag.c_str(), " TEST FAILED!\n"); } else { printf("%5s%s%s", "", p_tag.c_str(), " TEST PASSED!\n"); } } else { ASSERT_TRUE(approx_eq(static_cast<double>(ref_val), dval)); } break; } case kSUM: case kCOUNT: { if (!silent) { p_tag += "KSUM_D"; printf( "\n%s row_idx = %i, ref_val = %f, dval = %f", p_tag.c_str(), (int)row_idx, (double)ref_val, dval); if (!approx_eq(static_cast<double>(ref_val), dval)) { printf("%5s%s%s", "", p_tag.c_str(), " TEST FAILED!\n"); } else { printf("%5s%s%s", "", p_tag.c_str(), " TEST PASSED!\n"); } } else { ASSERT_TRUE(approx_eq(static_cast<double>(ref_val), dval)); } break; } default: CHECK(false); } break; } default: CHECK(false); } } row_idx++; } delete rse; } } // namespace TEST(Iterate, PerfectHashOneCol) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashOneCol32) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 4, 0, 99); test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashOneColColumnar) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); query_mem_desc.output_columnar = true; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashOneColColumnar32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 4, 0, 99); query_mem_desc.output_columnar = true; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashOneColKeyless) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashOneColKeyless32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 4, 0, 99); query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashOneColColumnarKeyless) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); query_mem_desc.output_columnar = true; query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashOneColColumnarKeyless32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 4, 0, 99); query_mem_desc.output_columnar = true; query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashTwoCol) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 8); test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashTwoCol32) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 4); test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashTwoColColumnar) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 8); query_mem_desc.output_columnar = true; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashTwoColColumnar32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 4); query_mem_desc.output_columnar = true; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashTwoColKeyless) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 8); query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashTwoColKeyless32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 4); query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashTwoColColumnarKeyless) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 8); query_mem_desc.output_columnar = true; query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, PerfectHashTwoColColumnarKeyless32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 4); query_mem_desc.output_columnar = true; query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; test_iterate(target_infos, query_mem_desc); } TEST(Iterate, BaselineHash) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc(target_infos, 8); test_iterate(target_infos, query_mem_desc); } TEST(Iterate, BaselineHashColumnar) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc(target_infos, 8); query_mem_desc.output_columnar = true; test_iterate(target_infos, query_mem_desc); } TEST(Reduce, PerfectHashOneCol) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashOneCol32) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 4, 0, 99); EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashOneColColumnar) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); query_mem_desc.output_columnar = true; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashOneColColumnar32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 4, 0, 99); query_mem_desc.output_columnar = true; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashOneColKeyless) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashOneColKeyless32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 4, 0, 99); query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashOneColColumnarKeyless) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); query_mem_desc.output_columnar = true; query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashOneColColumnarKeyless32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 4, 0, 99); query_mem_desc.output_columnar = true; query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashTwoCol) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 8); EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashTwoCol32) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 4); EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashTwoColColumnar) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashTwoColColumnar32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 4); query_mem_desc.output_columnar = true; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashTwoColKeyless) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 8); query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashTwoColKeyless32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 4); query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashTwoColColumnarKeyless) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 8); query_mem_desc.output_columnar = true; query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, PerfectHashTwoColColumnarKeyless32) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = perfect_hash_two_col_desc(target_infos, 4); query_mem_desc.output_columnar = true; query_mem_desc.keyless_hash = true; query_mem_desc.idx_target_as_key = 2; EvenNumberGenerator generator1; EvenNumberGenerator generator2; test_reduce(target_infos, query_mem_desc, generator1, generator2, 2); } TEST(Reduce, BaselineHash) { const auto target_infos = generate_test_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc(target_infos, 8); EvenNumberGenerator generator1; ReverseOddOrEvenNumberGenerator generator2(2 * query_mem_desc.entry_count - 1); test_reduce(target_infos, query_mem_desc, generator1, generator2, 1); } TEST(Reduce, BaselineHashColumnar) { const auto target_infos = generate_test_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator generator1; ReverseOddOrEvenNumberGenerator generator2(2 * query_mem_desc.entry_count - 1); test_reduce(target_infos, query_mem_desc, generator1, generator2, 1); } TEST(MoreReduce, MissingValues) { std::vector<TargetInfo> target_infos; SQLTypeInfo bigint_ti(kBIGINT, false); SQLTypeInfo null_ti(kNULLT, false); target_infos.push_back(TargetInfo{false, kMIN, bigint_ti, null_ti, true, false}); target_infos.push_back(TargetInfo{true, kCOUNT, bigint_ti, null_ti, true, false}); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 7, 9); query_mem_desc.keyless_hash = false; const auto row_set_mem_owner = std::make_shared<RowSetMemoryOwner>(); const auto rs1 = boost::make_unique<ResultSet>(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr); const auto storage1 = rs1->allocateStorage(); const auto rs2 = boost::make_unique<ResultSet>(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr); const auto storage2 = rs2->allocateStorage(); { auto buff1 = reinterpret_cast<int64_t*>(storage1->getUnderlyingBuffer()); buff1[0 * 3] = 7; buff1[1 * 3] = EMPTY_KEY_64; buff1[2 * 3] = EMPTY_KEY_64; buff1[0 * 3 + 1] = 7; buff1[1 * 3 + 1] = 0; buff1[2 * 3 + 1] = 0; buff1[0 * 3 + 2] = 15; buff1[1 * 3 + 2] = 0; buff1[2 * 3 + 2] = 0; } { auto buff2 = reinterpret_cast<int64_t*>(storage2->getUnderlyingBuffer()); buff2[0 * 3] = EMPTY_KEY_64; buff2[1 * 3] = EMPTY_KEY_64; buff2[2 * 3] = 9; buff2[0 * 3 + 1] = 0; buff2[1 * 3 + 1] = 0; buff2[2 * 3 + 1] = 9; buff2[0 * 3 + 2] = 0; buff2[1 * 3 + 2] = 0; buff2[2 * 3 + 2] = 5; } storage1->reduce(*storage2); { const auto row = rs1->getNextRow(false, false); CHECK_EQ(size_t(2), row.size()); ASSERT_EQ(7, v<int64_t>(row[0])); ASSERT_EQ(15, v<int64_t>(row[1])); } { const auto row = rs1->getNextRow(false, false); CHECK_EQ(size_t(2), row.size()); ASSERT_EQ(9, v<int64_t>(row[0])); ASSERT_EQ(5, v<int64_t>(row[1])); } { const auto row = rs1->getNextRow(false, false); ASSERT_EQ(size_t(0), row.size()); } } TEST(MoreReduce, MissingValuesKeyless) { std::vector<TargetInfo> target_infos; SQLTypeInfo bigint_ti(kBIGINT, false); SQLTypeInfo null_ti(kNULLT, false); target_infos.push_back(TargetInfo{false, kMIN, bigint_ti, null_ti, true, false}); target_infos.push_back(TargetInfo{true, kCOUNT, bigint_ti, null_ti, true, false}); auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 7, 9); query_mem_desc.keyless_hash = true; const auto row_set_mem_owner = std::make_shared<RowSetMemoryOwner>(); const auto rs1 = boost::make_unique<ResultSet>(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr); const auto storage1 = rs1->allocateStorage(); const auto rs2 = boost::make_unique<ResultSet>(target_infos, ExecutorDeviceType::CPU, query_mem_desc, row_set_mem_owner, nullptr); const auto storage2 = rs2->allocateStorage(); { auto buff1 = reinterpret_cast<int64_t*>(storage1->getUnderlyingBuffer()); buff1[0 * 2] = 7; buff1[1 * 2] = 0; buff1[2 * 2] = 0; buff1[0 * 2 + 1] = 15; buff1[1 * 2 + 1] = 0; buff1[2 * 2 + 1] = 0; } { auto buff2 = reinterpret_cast<int64_t*>(storage2->getUnderlyingBuffer()); buff2[0 * 2] = 0; buff2[1 * 2] = 0; buff2[2 * 2] = 9; buff2[0 * 2 + 1] = 0; buff2[1 * 2 + 1] = 0; buff2[2 * 2 + 1] = 5; } storage1->reduce(*storage2); { const auto row = rs1->getNextRow(false, false); CHECK_EQ(size_t(2), row.size()); ASSERT_EQ(7, v<int64_t>(row[0])); ASSERT_EQ(15, v<int64_t>(row[1])); } { const auto row = rs1->getNextRow(false, false); CHECK_EQ(size_t(2), row.size()); ASSERT_EQ(9, v<int64_t>(row[0])); ASSERT_EQ(5, v<int64_t>(row[1])); } { const auto row = rs1->getNextRow(false, false); ASSERT_EQ(size_t(0), row.size()); } } /* FLOW #1: Perfect_Hash_Row_Based testcases */ TEST(ReduceRandomGroups, PerfectHashOneCol_Small_2525) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); // const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_2575) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); // const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_5050) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); // const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 50, prct2 = 50; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_7525) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); // const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 75, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_25100) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); // const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_10025) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); // const auto query_mem_desc = perfect_hash_one_col_desc(target_infos, 8, 0, 99); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_9505) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 95, prct2 = 5; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_100100) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_2500) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 0; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneCol_Small_0075) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 0, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } /* FLOW #2: Non_Perfect_Hash_Row_Based testcases */ TEST(ReduceRandomGroups, BaselineHash_Large_5050) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 50, prct2 = 50; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHash_Large_7525) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 75, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHash_Large_2575) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHash_Large_1020) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 10, prct2 = 20; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHash_Large_100100) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHash_Large_2500) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 0; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHash_Large_0075) { const auto target_infos = generate_random_groups_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 0, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } /* FLOW #3: Perfect_Hash_Column_Based testcases */ TEST(ReduceRandomGroups, PerfectHashOneColColumnar_Small_5050) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 50, prct2 = 50; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_Small_25100) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_Small_10025) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_Small_100100) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_Small_2500) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 0; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_Small_0075) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 0, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } /* FLOW #4: Non_Perfect_Hash_Column_Based testcases */ TEST(ReduceRandomGroups, BaselineHashColumnar_Large_5050) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 50, prct2 = 50; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_25100) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_10025) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_100100) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_2500) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 0; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_0075) { const auto target_infos = generate_random_groups_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 0, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent); } /* FLOW #5: Perfect_Hash_Row_Based_NullVal testcases */ TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_2525) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 25; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_2575) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 75; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_5050) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 50, prct2 = 50; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_7525) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 75, prct2 = 25; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_25100) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 100; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_10025) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 25; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_100100) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 100; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_2500) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 0; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneCol_NullVal_0075) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 0, prct2 = 75; ASSERT_LE(prct1, 100); ASSERT_LE(prct2, 100); bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } /* FLOW #6: Perfect_Hash_Column_Based_NullVal testcases */ TEST(ReduceRandomGroups, PerfectHashOneColColumnar_NullVal_5050) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 50, prct2 = 50; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_NullVal_25100) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_NullVal_10025) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_NullVal_100100) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_NullVal_2500) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 0; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, PerfectHashOneColColumnar_NullVal_0075) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = perfect_hash_one_col_desc_small(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 0, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } /* FLOW #7: Non_Perfect_Hash_Row_Based_NullVal testcases */ TEST(ReduceRandomGroups, BaselineHash_Large_NullVal_5050) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 50, prct2 = 50; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHash_Large_NullVal_7525) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 75, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHash_Large_NullVal_2575) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHash_Large_NullVal_1020) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 10, prct2 = 20; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHash_Large_NullVal_100100) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHash_Large_NullVal_2500) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 0; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHash_Large_NullVal_0075) { const auto target_infos = generate_random_groups_nullable_target_infos(); const auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 0, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } /* FLOW #8: Non_Perfect_Hash_Column_Based_NullVal testcases */ TEST(ReduceRandomGroups, BaselineHashColumnar_Large_NullVal_5050) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 50, prct2 = 50; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_NullVal_25100) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_NullVal_10025) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 25; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_NullVal_100100) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 100, prct2 = 100; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_NullVal_2500) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 25, prct2 = 0; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } TEST(ReduceRandomGroups, BaselineHashColumnar_Large_NullVal_0075) { const auto target_infos = generate_random_groups_nullable_target_infos(); auto query_mem_desc = baseline_hash_two_col_desc_large(target_infos, 8); query_mem_desc.output_columnar = true; EvenNumberGenerator gen1; EvenNumberGenerator gen2; const int prct1 = 0, prct2 = 75; bool silent = false; // true/false - don't/do print diagnostic messages silent = true; test_reduce_random_groups(target_infos, query_mem_desc, gen1, gen2, prct1, prct2, silent, 2); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); auto err = RUN_ALL_TESTS(); return err; }
39.663986
119
0.666473
[ "vector" ]
3a1ba875e24a7c65cec475e2d5a872a9e1251113
2,303
hpp
C++
include/draw_functions.hpp
Andrew15-5/walk-game
550f4adeb4933fd298866cde0dd30dca11559334
[ "MIT" ]
null
null
null
include/draw_functions.hpp
Andrew15-5/walk-game
550f4adeb4933fd298866cde0dd30dca11559334
[ "MIT" ]
null
null
null
include/draw_functions.hpp
Andrew15-5/walk-game
550f4adeb4933fd298866cde0dd30dca11559334
[ "MIT" ]
null
null
null
#ifndef DRAW_FUNCTIONS_HPP #define DRAW_FUNCTIONS_HPP #include "include/vector3.hpp" #include <GL/gl.h> // =========================== Complex shapes =================================== void draw_3d_axis(); void draw_floor(Vector3 left_front, Vector3 right_back, GLuint texture_id); void draw_wall(Vector3 left_bottom, Vector3 right_top, GLuint texture_id); void draw_4_wall_room(Vector3 left_bottom_front, Vector3 right_top_back, GLuint texture_id); void draw_ceiling(Vector3 left_front, Vector3 right_back, GLuint texture_id); // what_to_draw must contain [floor, front, right, back, left, ceiling] or // equal to nullptr if everything has to be drawn. // texture_ids must contain [floor, wall, ceiling]. void draw_room( Vector3 left_bottom_front, Vector3 right_top_back, bool what_to_draw[6], GLuint texture_ids[3]); // ============================ Mesh shapes =================================== void draw_rectangle_mesh_xy( Vector3 left_bottom, Vector3 right_top, bool flip = false, GLuint *texture_id = nullptr); void draw_rectangle_mesh_xz( Vector3 left_back, Vector3 right_front, bool flip = false, GLuint *texture_id = nullptr); void draw_rectangle_mesh_yz( Vector3 bottom_front, Vector3 top_back, bool flip = false, GLuint *texture_id = nullptr); void draw_ceiling_mesh( Vector3 left_bottom_front, Vector3 right_top_back, GLuint *texture_id = nullptr); // what_to_draw must contain [floor, front, right, back, left, ceiling] or // equal to nullptr if everything has to be drawn. // texture_ids must contain [&floor, &wall, &ceiling]. void draw_room_mesh( Vector3 left_bottom_front, Vector3 right_top_back, bool what_to_draw[6], GLuint *texture_ids[3]); // =========================== Basic shapes =================================== void draw_rectangle(GLfloat width, GLfloat height, GLfloat color[3] = nullptr, GLfloat z = 0); void draw_square(GLfloat size, GLfloat color[3] = nullptr, GLfloat z = 0); void draw_parallelepiped(GLfloat width, GLfloat height, GLfloat depth, GLfloat color[3]); void draw_parallelepiped(GLfloat width, GLfloat height, GLfloat depth, GLfloat color[6][3]); void draw_cube(GLfloat size, GLfloat color[3]); void draw_cube(GLfloat size, GLfloat color[6][3]); #endif
35.984375
94
0.691272
[ "mesh" ]
3a1ed74bdc8be519619f7b88e5c2bb57b3b55860
3,334
hpp
C++
lumino/RuntimeCore/include/LuminoEngine/Engine/Diagnostics.hpp
LuminoEngine/Lumino
370db149da12abbe1c01a3a42b6caf07ca4000fe
[ "MIT" ]
113
2020-03-05T01:27:59.000Z
2022-03-28T13:20:51.000Z
lumino/RuntimeCore/include/LuminoEngine/Engine/Diagnostics.hpp
LuminoEngine/Lumino
370db149da12abbe1c01a3a42b6caf07ca4000fe
[ "MIT" ]
13
2020-03-23T20:36:44.000Z
2022-02-28T11:07:32.000Z
lumino/RuntimeCore/include/LuminoEngine/Engine/Diagnostics.hpp
LuminoEngine/Lumino
370db149da12abbe1c01a3a42b6caf07ca4000fe
[ "MIT" ]
12
2020-12-21T12:03:59.000Z
2021-12-15T02:07:49.000Z
#pragma once #include "../Reflection/Object.hpp" namespace ln { class DiagnosticsItem; class ProfilingItem; class ProfilingSection; enum class DiagnosticsLevel { Error, Warning, Info, }; class LN_API DiagnosticsManager : public Object { public: static DiagnosticsManager* activeDiagnostics(); void reportError(StringRef message); void reportWarning(StringRef message); void reportInfo(StringRef message); bool hasItems() const { return !m_items.isEmpty(); } bool hasError() const { return m_hasError; } bool hasWarning() const { return m_hasWarning; } bool succeeded() const { return !hasError(); } const List<Ref<DiagnosticsItem>>& items() const { return m_items; } ln::String toString() const; void dumpToLog() const; void registerProfilingItem(ProfilingItem* item); void setCounterValue(const ProfilingItem* key, int64_t value); void commitFrame(); LN_CONSTRUCT_ACCESS: DiagnosticsManager(); virtual ~DiagnosticsManager(); void init(); private: List<Ref<DiagnosticsItem>> m_items; bool m_hasError; bool m_hasWarning; List<Ref<ProfilingItem>> m_profilingItems; std::unordered_map<const ProfilingItem*, Ref<ProfilingSection>> m_profilingValues; /* Note: エディタとランタイム境界を考慮したプロファイリングについて InEditor で Game のプロファイリングしたいとき、Editor 側の都合で作ったリソースの量とかはプロファイリング対象としたくない。 そうすると、ドローコールの数とかを Game 内のものに限定する必要がある。 さらに大変なのが、基本的にプロファイリングの範囲としたい1フレームはpresentまでの単位となるので、InEditor に Game の View を埋め込むとどうしても分離できなくなる。 もし InEditor で Game プレビューやりたくなったら、ネイティブのウィンドウを、EditorWindow の中に埋め込んで、present をそもそも分けるような対策が必要になるかも。 */ }; class LN_API DiagnosticsItem : public Object { public: DiagnosticsLevel level() const { return m_level; } const String& message() const { return m_string; } LN_CONSTRUCT_ACCESS: DiagnosticsItem(); virtual ~DiagnosticsItem(); void init(); private: void setLevel(DiagnosticsLevel level) { m_level = level; } void setMessage(StringRef message) { m_string = message; } DiagnosticsLevel m_level; String m_string; friend class DiagnosticsManager; }; enum class ProfilingItemType { Counter, // リソース量などの値 ElapsedTimer, // 区間を指定して時間を測る }; class ProfilingItem : public Object { public: static Ref<ProfilingItem> Graphics_RenderPassCount; ProfilingItemType type() const { return m_type; } const String& name() const { return m_name; } LN_CONSTRUCT_ACCESS: ProfilingItem(); void init(ProfilingItemType type, const StringRef& name); private: ProfilingItemType m_type; String m_name; }; class ProfilingSection : public Object { public: //void begin(); //void end(); //float getElapsedSeconds() const { return static_cast<float>(m_committedTime) * 0.000000001f; } //uint64_t getElapsedNanoseconds() const { return m_committedTime; } void setValue(int64_t value) { m_value = value; } int64_t committedValue() const { return m_committedValue; } private: ProfilingSection(ProfilingItem* owner); void commitFrame(); ProfilingItem* m_owner; int64_t m_value; int64_t m_committedValue; //ElapsedTimer m_timer; //std::atomic<uint64_t> m_totalTime; //ConditionFlag m_measuring; //int m_committedFrameCount; //uint64_t m_committedTime; friend class DiagnosticsManager; }; } // namespace ln
23.478873
102
0.732454
[ "object" ]
3a26d36dc2ea6461e4a86bc113032c63eb28e1f1
12,155
cc
C++
open_spiel/game_transforms/restricted_nash_response.cc
ajain-23/open_spiel
a6a0f0129571bb6f0e6832e870e299663fb7cdd5
[ "Apache-2.0" ]
2
2020-01-24T10:04:07.000Z
2020-01-24T17:11:31.000Z
open_spiel/game_transforms/restricted_nash_response.cc
ajain-23/open_spiel
a6a0f0129571bb6f0e6832e870e299663fb7cdd5
[ "Apache-2.0" ]
18
2021-05-04T16:46:17.000Z
2021-10-11T14:46:33.000Z
open_spiel/game_transforms/restricted_nash_response.cc
ajain-23/open_spiel
a6a0f0129571bb6f0e6832e870e299663fb7cdd5
[ "Apache-2.0" ]
1
2021-08-21T17:15:51.000Z
2021-08-21T17:15:51.000Z
// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/game_transforms/restricted_nash_response.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include "open_spiel/game_parameters.h" #include "open_spiel/policy.h" #include "open_spiel/spiel.h" #include "open_spiel/spiel_globals.h" namespace open_spiel { namespace { const GameType kGameType{ /*short_name=*/"restricted_nash_response", /*long_name=*/"Restricted Nash Response Modification of a Game", GameType::Dynamics::kSequential, GameType::ChanceMode::kSampledStochastic, GameType::Information::kImperfectInformation, GameType::Utility::kGeneralSum, GameType::RewardModel::kRewards, /*max_num_players=*/100, /*min_num_players=*/1, /*provides_information_state_string=*/true, /*provides_information_state_tensor=*/true, /*provides_observation_string=*/true, /*provides_observation_tensor=*/true, {{"game", GameParameter(GameParameter::Type::kGame, /*is_mandatory=*/true)}, {"fixed_player", GameParameter(kDefaultFixedPlayer)}, {"p", GameParameter(kDefaultP)}}, /*default_loadable=*/false}; std::shared_ptr<const Game> Factory(const GameParameters& params) { return ConvertToRNR( *LoadGame(params.at("game").game_value()), ParameterValue<int>(params, "fixed_player", kDefaultFixedPlayer), ParameterValue<double>(params, "p", kDefaultP), std::make_shared<UniformPolicy>()); } REGISTER_SPIEL_GAME(kGameType, Factory); } // namespace class RestrictedNashResponseObserver : public Observer { public: RestrictedNashResponseObserver(IIGObservationType iig_obs_type) : Observer(/*has_string=*/true, /*has_tensor=*/true), iig_obs_type_(iig_obs_type) {} // Writes the complete observation in tensor form. // The supplied allocator is responsible for providing memory to write the // observation into. void WriteTensor(const State& observed_state, int player, Allocator *allocator) const override { auto& state = open_spiel::down_cast<const RestrictedNashResponseState &>( observed_state); SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, state.NumPlayers()); std::shared_ptr<const Game> original_game = state.GetOriginalGame(); GameParameters params; std::shared_ptr<Observer> observer = original_game->MakeObserver(iig_obs_type_, params); // Observing player. auto out = allocator->Get("initial_and_fixed", {2}); if (iig_obs_type_.public_info) { if (state.IsRestrictedNashResponseInitialState()) { out.at(0) = 1; } } if (iig_obs_type_.private_info == PrivateInfoType::kSinglePlayer) { if (state.IsPlayerFixed(player)) { out.at(1) = state.IsStateFixed(); } else { out.at(1) = 0; } } else if (iig_obs_type_.private_info == PrivateInfoType::kAllPlayers) { out.at(1) = state.IsStateFixed(); } observer->WriteTensor(*state.GetOriginalState(), player, allocator); } // Writes an observation in string form. It would be possible just to // turn the tensor observation into a string, but we prefer something // somewhat human-readable. std::string StringFrom(const State &observed_state, int player) const override { auto& state = open_spiel::down_cast<const RestrictedNashResponseState &>( observed_state); SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, state.NumPlayers()); std::string result; std::shared_ptr<const Game> original_game = state.GetOriginalGame(); GameParameters params; std::shared_ptr<Observer> observer = original_game->MakeObserver(iig_obs_type_, params); if (iig_obs_type_.public_info) { if (state.IsRestrictedNashResponseInitialState()) { return "Initial"; } } if (iig_obs_type_.private_info == PrivateInfoType::kSinglePlayer) { if (state.IsPlayerFixed(player)) { result += state.IsStateFixed() ? "[Rnr: fixed]" : "[Rnr: free]"; } } else if (iig_obs_type_.private_info == PrivateInfoType::kAllPlayers) { result += state.IsStateFixed() ? "[Rnr: fixed]" : "[Rnr: free]"; } result += observer->StringFrom(*state.GetOriginalState(), player); return result; } private: IIGObservationType iig_obs_type_; }; RestrictedNashResponseState::RestrictedNashResponseState( std::shared_ptr<const Game> game, std::unique_ptr<State> state, bool fixed, Player fixed_player, bool initial_state, double p, std::shared_ptr<Policy> fixed_policy) : State(std::move(game)), state_(std::move(state)), is_initial_(initial_state), fixed_(fixed), p_(p), fixed_player_(fixed_player), fixed_policy_(fixed_policy), use_fixed_policy_(fixed_policy) {} Player RestrictedNashResponseState::CurrentPlayer() const { if (is_initial_) { return kChancePlayerId; } else { if (use_fixed_policy_ && fixed_ && state_->CurrentPlayer() == fixed_player_) { return kChancePlayerId; } else { return state_->CurrentPlayer(); } } } void RestrictedNashResponseState::DoApplyAction(Action action_id) { if (is_initial_) { is_initial_ = false; fixed_ = action_id == kFixedAction; } else { state_->ApplyAction(action_id); } } void RestrictedNashResponseState::DoApplyActions( const std::vector<Action>& actions) { SPIEL_CHECK_EQ(game_->GetType().dynamics, GameType::Dynamics::kSimultaneous); SPIEL_CHECK_EQ(is_initial_, false); state_->ApplyActions(actions); } std::vector<std::pair<Action, double>> RestrictedNashResponseState::ChanceOutcomes() const { if (is_initial_) { return {{Action(kFixedAction), p_}, {Action(kFreeAction), 1 - p_}}; } else { if (state_->IsChanceNode()) { return state_->ChanceOutcomes(); } else if (use_fixed_policy_ && fixed_ && state_->CurrentPlayer() == fixed_player_) { return fixed_policy_->GetStatePolicy(*state_); } } return {}; } std::vector<Action> RestrictedNashResponseState::LegalActions() const { if (is_initial_) { return {Action(kFixedAction), Action(kFreeAction)}; } else { return state_->LegalActions(); } } std::vector<Action> RestrictedNashResponseState::LegalActions( Player player) const { // Initial state only has two actions to fixed or free tree if (is_initial_) { if (player == kChancePlayerId) { return {Action(kFixedAction), Action(kFreeAction)}; } else { return {}; } } else { if (use_fixed_policy_ && fixed_ && state_->CurrentPlayer() == fixed_player_) { // In other states if we exchanged fixed player nodes for chance node we // return action for chance player if (player == kChancePlayerId) { return state_->LegalActions(fixed_player_); } else { return {}; } } else { // Otherwise we just use original legal actions return state_->LegalActions(player); } } } std::string RestrictedNashResponseState::ActionToString( Player player, Action action_id) const { if (is_initial_) { SPIEL_CHECK_EQ(player, kChancePlayerId); return (action_id == kFixedAction ? "Fixed" : "Free"); } else { Player action_player = player; if (action_player == kChancePlayerId && use_fixed_policy_ && fixed_ && state_->CurrentPlayer() == fixed_player_) { // This is a chance node in the RNR game, but a regular player node // in the underlying game, so we need to use the player's true identity // at this node. action_player = state_->CurrentPlayer(); } return state_->ActionToString(action_player, action_id); } } std::string RestrictedNashResponseState::ToString() const { if (is_initial_) { return "Initial restricted Nash response state."; } else { std::string state_string = "Rnr state string of state in "; state_string += (fixed_ ? "fixed" : "free"); state_string += " part with underlying state:\n"; return state_string + state_->ToString(); } } bool RestrictedNashResponseState::IsTerminal() const { if (is_initial_) { return false; } else { return state_->IsTerminal(); } } std::vector<double> RestrictedNashResponseState::Returns() const { if (is_initial_) { return std::vector<double>(num_players_, 0.0); } return state_->Returns(); } // old observation API std::string RestrictedNashResponseState::InformationStateString( Player player) const { const auto& game = open_spiel::down_cast<const RestrictedNashResponseGame &>(*game_); return game.info_state_observer_->StringFrom(*this, player); } void RestrictedNashResponseState::InformationStateTensor( Player player, absl::Span<float> values) const { ContiguousAllocator allocator(values); const auto &game = open_spiel::down_cast<const RestrictedNashResponseGame &>(*game_); game.info_state_observer_->WriteTensor(*this, player, &allocator); } std::string RestrictedNashResponseState::ObservationString( Player player) const { const auto& game = open_spiel::down_cast<const RestrictedNashResponseGame &>(*game_); return game.default_observer_->StringFrom(*this, player); } void RestrictedNashResponseState::ObservationTensor( Player player, absl::Span<float> values) const { ContiguousAllocator allocator(values); const auto &game = open_spiel::down_cast<const RestrictedNashResponseGame &>(*game_); game.default_observer_->WriteTensor(*this, player, &allocator); } RestrictedNashResponseState::RestrictedNashResponseState( const RestrictedNashResponseState &other) : State(other), state_(other.state_->Clone()), is_initial_(other.is_initial_), fixed_(other.fixed_), p_(other.p_), fixed_player_(other.fixed_player_), fixed_policy_(other.fixed_policy_), use_fixed_policy_(other.use_fixed_policy_) {} std::unique_ptr<State> RestrictedNashResponseState::Clone() const { return std::unique_ptr<State>(new RestrictedNashResponseState(*this)); } namespace { GameType ConvertType(GameType type) { type.short_name = "rnr_" + type.short_name; type.long_name = "Restricted Nash Response " + type.long_name; return type; } } // namespace RestrictedNashResponseGame::RestrictedNashResponseGame( std::shared_ptr<const Game> game, Player fixed_player, double p, std::shared_ptr<Policy> fixed_policy) : WrappedGame(game, ConvertType(game->GetType()), game->GetParameters()), fixed_player_(fixed_player), p_(p), fixed_policy_(std::move(fixed_policy)) { default_observer_ = std::make_shared<RestrictedNashResponseObserver>(kDefaultObsType); info_state_observer_ = std::make_shared<RestrictedNashResponseObserver>(kInfoStateObsType); } std::shared_ptr<const Game> ConvertToRNR( const Game& game, Player fixed_player, double p, std::shared_ptr<Policy> fixed_policy) { return std::shared_ptr<const RestrictedNashResponseGame>( new RestrictedNashResponseGame(game.shared_from_this(), fixed_player, p, fixed_policy)); } // Observer creation std::shared_ptr<Observer> RestrictedNashResponseGame::MakeObserver( absl::optional<IIGObservationType> iig_obs_type, const GameParameters& params) const { if (params.empty()) { return std::make_shared<RestrictedNashResponseObserver>( iig_obs_type.value_or(kDefaultObsType)); } else { return MakeRegisteredObserver(iig_obs_type, params); } } } // namespace open_spiel
33.857939
79
0.703167
[ "vector" ]
3a2a83dacf825139febbc2de530f63aebb6589ff
19,611
cpp
C++
scr/ConvexHull/CnvH.cpp
dZh0/ConvexHull
dc8a4833143349292d700654afb0fd775e94f1d5
[ "Unlicense" ]
null
null
null
scr/ConvexHull/CnvH.cpp
dZh0/ConvexHull
dc8a4833143349292d700654afb0fd775e94f1d5
[ "Unlicense" ]
null
null
null
scr/ConvexHull/CnvH.cpp
dZh0/ConvexHull
dc8a4833143349292d700654afb0fd775e94f1d5
[ "Unlicense" ]
null
null
null
// debug dependencies #include <assert.h> // true dependencies #include <fstream> #include <queue> #include <unordered_set> #include "CnvH.h" // Creates CnvH from C-style FVector array. CnvH::CnvH(FVector const* p_arr, int _size) : CnvH::CnvH(){ collection.reserve(_size); for (int i = 0; i < _size; i++) { Add(p_arr[i]); } } // Adds a FVector to the hull. void CnvH::Add(FVector extrusion) { size_t collectionIdx = collection.size(); std::cout << "#" << collection.size() << " " << extrusion; collection.push_back(extrusion); if (extrusion == FV_ZERO) return; // Don't change geometry if vector is {0,0,0} std::queue<point> newPoints; // Points to be added during the extrusion (FiFo) std::queue<quad> newQuads; // Quads to be added during the extrusion (FiFo) std::unordered_set<size_t> moveIdx; // Unique indecis of points to be moved during the extrusion size_t newIdx = hullPoints.size(); // Keeps track of the index of the newly added points // Find if there is already a vector with the same direcion in the colection auto found = collection.begin(); while (found != collection.end()-1) { // collection.end()-1 as we already added the extrusion in the collection if (isColinear(*found, extrusion) && dot(*found, extrusion) > 0.0f) break; ++found; } if (found != collection.end()-1) { // If vector in the same direction IS found in the collection std::cout << " Move points: "; size_t foundIdx = std::distance(collection.begin(), found); for (size_t i = 0; i < hullPoints.size(); i++) { const auto& map = hullPoints[i].weight; if (map.find(foundIdx) != map.end()) { moveIdx.insert(i); } } } else { // If vector in the same direction is NOT found in the collection switch (state) { ///////////////////////////////// // Convex Hull is empty: // ///////////////////////////////// case empty: { std::cout << " Add first point: "; state = linear; newPoints.emplace(this); newIdx++; newPoints.emplace(this); moveIdx.insert(newIdx); } break; //end "case empty" ///////////////////////////////// // Convex Hull is a line: // ///////////////////////////////// case linear: { FVector hullLine = hullPoints[1].vec; if (isColinear(extrusion, hullLine)) { // If the extrusion direction is on the hull line: state = linear; std::cout << " Linear extrusion: "; // Provide the index of the furthest point on the hullLine in the extrude direction size_t endIdx = 0; float endPrj = dot(hullPoints[endIdx].vec, hullLine); for (size_t i = 1; i < hullPoints.size(); i++) { if (dot(hullPoints[i].vec, hullLine) < endPrj) { endIdx = i; endPrj = dot(hullPoints[endIdx].vec, hullLine); } } // If the selected point IS the origin: clone it and mark the cloned point for translation if (hullPoints[endIdx].vec == FV_ZERO) { newPoints.emplace(this); moveIdx.insert(newIdx); } // If the selected point is NOT the origin: mark it for translation else { moveIdx.insert(endIdx); } } else { // If the extrusion direction is NOT on the hull line: state = planar; std::cout << " Line to plane extrusion: "; // Build edge_1 from existing points (not a loop) std::list<size_t> edge_1 = { 0 }; for (size_t i = 1; i < hullPoints.size(); i++) { float iProj = dot(hullPoints[i].vec, hullLine); auto it = edge_1.begin(); while (iProj < dot(hullPoints[*it].vec, hullLine)) { ++it; if (it == edge_1.end()) break; } edge_1.insert(it, i); } // Clone the points from edge_1 to edge 2 and mark them for move std::list<size_t> edge_2; moveIdx.reserve(edge_1.size()); for (size_t i : edge_1) { edge_2.push_back(newIdx); newPoints.push(hullPoints[i]); moveIdx.insert(newIdx); newIdx++; } // Build quads betwean edge_1 and edge_2 for (auto it_1 = edge_1.begin(), it_2 = edge_2.begin(); next(it_1) != edge_1.end(); ++it_1, ++it_2) { FVector edgeVec = hullPoints[*next(it_1)].vec - hullPoints[*it_1].vec; FVector normal = norm(cross(edgeVec, extrusion)); newQuads.emplace(this, *it_1, *next(it_1), *next(it_2), *it_2, normal); } } } break; //end "case linear" ///////////////////////////////// // Convex Hull is a plane: // ///////////////////////////////// case planar: { FVector hullNormal = hullQuads[0].normal; // Select all quads: std::list<quad*> selectQuads; for (quad& q : hullQuads) { selectQuads.push_back(&q); } // Find open edges: std::list<edge> edge_1 = FindOpenEdges(selectQuads); if (dot(extrusion, hullNormal) == 0.0f) { // If the extrusion direction IS on the hull plane: state = planar; std::cout << " Planar extrude: "; // Delete edges that are not facing the extrusion direction (no longer loop) FVector direction = cross(hullNormal, extrusion); for (auto it = edge_1.begin(); it != edge_1.end();){ FVector edgeVec = hullPoints[it->pointIdx[1]].vec - hullPoints[it->pointIdx[0]].vec; if (dot(edgeVec, direction) <= 0.0f) it = edge_1.erase(it); else ++it; } // Clone the points from edge_1 to edge 2 and mark them for move std::list<edge> edge_2; moveIdx.reserve(edge_1.size() + 1); std::map<size_t, size_t> indexMap; // Keeps map of indecies from edge_1 to edge_2 for (const edge& e : edge_1) { edge e2; for (int i = 0; i < 2; i++) { auto insResult = indexMap.insert({ e.pointIdx[i],newIdx }); if (insResult.second) { e2.pointIdx[i] = newIdx; newPoints.push(hullPoints[e.pointIdx[i]]); moveIdx.insert(newIdx); newIdx++; } else { e2.pointIdx[i] = insResult.first->second; } } edge_2.push_back(e2); } // Build quads betwean edge_1 and edge_2 for (auto it_1 = edge_1.begin(), it_2 = edge_2.begin(); it_1 != edge_1.end(); ++it_1, ++it_2) { quad q = BuildQuad(*it_1, *it_2, extrusion); newQuads.push(FlipQuad(q)); } } else { // If the extrusion direction is NOT on the hull plane: state = volume; std::cout << " Plane to volume extrude: "; // As the whole hull will be cloned all new points have index = old_index + index_offset const size_t indexOffset = newIdx; // Build edge_2 edge with new incremented point indecies std::list<edge> edge_2 = edge_1; for (edge& e : edge_2) { e.pointIdx[0] += indexOffset; e.pointIdx[1] += indexOffset; } // Clone all points and mark them for moving moveIdx.reserve(hullPoints.size()); for (const point& p : hullPoints) { newPoints.push(p); moveIdx.insert(newIdx); newIdx++; } // Clone all quads of the hull, flip their normals and rebind their indecies bool isFacing = dot(extrusion, hullNormal) > 0.0f; // if the hull IS facing the direction for (quad& q : hullQuads) { quad newQ = q; if (isFacing) { q = FlipQuad(q); } // Flip the original quad else { newQ = FlipQuad(newQ); } // Flip the new quad for (int i = 0; i < 4; i++) { newQ.pointIdx[i] += indexOffset; } newQuads.push(newQ); } // Build quads betwean edge_1 and edge_2 for (auto it_1 = edge_1.begin(), it_2 = edge_2.begin(); it_1 != edge_1.end(); ++it_1, ++it_2) { //ASK: it + 1 != edges.end(); quad q = BuildQuad(*it_1, *it_2, extrusion); if (!isFacing) { q = FlipQuad(q); } newQuads.push(q); } } } break; // end "case planar" ///////////////////////////////// // Convex Hull is a 3D volume: // ///////////////////////////////// case volume: { std::cout << " Volume extrude: " << extrusion << std::endl; //Select quads facing the extrusion direction std::list<quad*> selectQuads; for (quad& q : hullQuads) { if (dot(extrusion, q.normal) > 0.0f) { // if quad IS facing the direction selectQuads.push_back(&q); } } // Find open edges: std::list<edge> edge_1 = FindOpenEdges(selectQuads); // Clone the points from edge_1 to edge 2 std::list<edge> edge_2; std::map<size_t, size_t> indexMap; // Keeps map of indecies from edge_1 to edge_2 for (const edge& e1 : edge_1) { edge e2; for (int i = 0; i < 2; i++) { auto insResult = indexMap.insert({ e1.pointIdx[i],newIdx }); if (insResult.second) { e2.pointIdx[i] = newIdx; newPoints.push(hullPoints[e1.pointIdx[i]]); newIdx++; } else { e2.pointIdx[i] = insResult.first->second; } } edge_2.push_back(e2); } // Re-bind selectQuads quads to edge_2 and mark all for move for (quad* ptr_q : selectQuads) { for (int i = 0; i < 4; i++) { auto it_found = indexMap.find(ptr_q->pointIdx[i]); if (it_found != indexMap.end()) { ptr_q->pointIdx[i] = it_found->second; } moveIdx.insert(ptr_q->pointIdx[i]); } } // Build quads betwean edge_1 and edge_2 for (auto it_1 = edge_1.begin(), it_2 = edge_2.begin(); it_1 != edge_1.end(); ++it_1, ++it_2) { newQuads.push(BuildQuad(*it_1, *it_2, extrusion)); } }break; //end "case volume" default: assert("Convex Hull state not properly defined!"); break; } } // end if vector in the same direction is NOT found in the collection /////////////////////////////////////// // Constructs the new geometry: // /////////////////////////////////////// // Add new points hullPoints.reserve(hullPoints.size() + newPoints.size()); while (!newPoints.empty()) { hullPoints.push_back(newPoints.front()); newPoints.pop(); } // Add new quads hullQuads.reserve(hullQuads.size() + newQuads.size()); while (!newQuads.empty()) { hullQuads.push_back(newQuads.front()); newQuads.pop(); } // Move points if (!moveIdx.empty()) { for (const size_t idx: moveIdx) { hullPoints[idx].vec += extrusion; auto insertRes = hullPoints[idx].weight.insert({ collectionIdx, 1.0f }); if (!insertRes.second) { // inserion failed insertRes.first->second += 1.0f; } } } std::cout << " points: " << hullPoints.size() <<" quads: " << hullQuads.size() << std::endl; } // Returns the determinant of a 3x3 matrix constructed by the column vector parameters inline float det3(FVector a, FVector b, FVector c) { return a.x*b.y*c.z + a.z*b.x*c.y + a.y*b.z*c.x - a.x*b.z*c.y - a.y*b.x*c.z - a.z*b.y*c.x; } void CnvH::Disolve(FVector vec) { point pnt(this); float scale; switch (state){ case linear: { float k; float del = 0.0f; for (const point& p : hullPoints){ float newDel = dot(vec, p.vec); if (newDel > del){ del = newDel; pnt = p; } } const float CosTolerance = 0.0f; if (abs(del / (Length(vec)*Length(pnt.vec))) < 1.0f - CosTolerance){ std::cout << vec << " does not intersect the hull!" << std::endl; return; } k = del / LengthSq(vec); scale = k; }break; case planar: { FVector normal = hullQuads[0].normal; std::list<quad*> selectQuads; for (quad& q : hullQuads) selectQuads.push_back(&q); std::list<edge> edge_1 = FindOpenEdges(selectQuads); point base = point(this); // Vector P is the projection of vec on the plane -> P = vec - n*normal // Point Q is part of the edge E1:E2 and part of line define by P -> E1 + q*(E2-E1) = k * P // -> k*vec - n*k*normal + q*(E1-E2) = E1 // and n, k, and q are real number coaficents float n, k, q, nk; FVector vBase = FV_ZERO; for (edge& e : edge_1){ FVector vE1 = hullPoints[e.pointIdx[0]].vec; FVector vE2 = hullPoints[e.pointIdx[1]].vec; float det = det3(vec, -normal, vE1 - vE2); if (det == 0.0f) continue; k = det3(vE1, -normal, vE1 - vE2) / det; nk = det3(vec, vE1, vE1 - vE2) / det; q = det3(vec, -normal, vE1) / det; if (k == 0.0f) { pnt = base; continue; } n = nk / k; if (n != 0.0f) { pnt = base; std::cout << vec << " does not intersect the hull!" << std::endl; break; } if (q >= 0.0f && q <= 1.0f){ pnt = hullPoints[e.pointIdx[0]] + q*(hullPoints[e.pointIdx[1]] - hullPoints[e.pointIdx[0]]); break; } } scale = k; } break; case volume: { // Intersection point P is part of the line vec -> P = k*vec // Intersection point P is part of the plane OAB -> P = O + m*A + n*B // -> k*vec - m*A - n*B = O // Where A and B are quad edges and O is their common point // and k, m and n are real number coaficents float k, m, n; quad* found = nullptr; for (quad& q : hullQuads) { if (dot(vec, q.normal) < 0.0f) continue; FVector vO = q.getPnt(0).vec; FVector vA = q.getPnt(1).vec - q.getPnt(0).vec; FVector vB = q.getPnt(3).vec - q.getPnt(0).vec; float det = det3(vec, -vA, -vB); if (det == 0.0f) continue; // vec lays on OAB k = det3(vO, -vA, -vB) / det; assert(k > 0.0f); // must always be true if dot(vec, q.normal) >= 0.0f m = det3(vec, vO, -vB) / det; n = det3(vec, -vA, vO) / det; if (m >= 0.0f && n >= 0.0f && m <= 1.0f && n <= 1.0f){ found = &q; pnt = (1.0f - m - n)*found->getPnt(0) + m*found->getPnt(1) + n*found->getPnt(3); break; } } if (!found){ std::cout << vec << " does not intersect the hull!" << std::endl; return; } std::list<quad*> selectQuads; for (quad& q : hullQuads) { if (q.normal == found->normal){ selectQuads.push_back(&q); } } if (selectQuads.size() > 1){ // Find open edges: std::list<edge> edge_1 = FindOpenEdges(selectQuads); point base = BasePoint(edge_1); // Intersection point P is part of the line vec -> P = k*vec // The line through P and the polygon base point intersects an edge (with end points E1 and E2) at poin Q -> // -> Q = E1 + q*(E2-E1) and P = base + p*(Q - base) // -> k*vec = base + p*(E1 + q*(E2-E1) - base) // -> base = k*vec + p*(base - E1) + p*q*(E1 - E2) // where k, p and q are real number coaficents float k, p, q, pq; FVector vBase = base.vec; for (edge& e : edge_1){ FVector vE1 = hullPoints[e.pointIdx[0]].vec; FVector vE2 = hullPoints[e.pointIdx[1]].vec; float det = det3(vec, vBase - vE1, vE1 - vE2); if (det == 0.0f) continue; k = det3(vBase, vBase - vE1, vE1 - vE2) / det; p = det3(vec, vBase, vE1 - vE2) / det; pq = det3(vec, vBase - vE1, vBase) / det; if (p == 0.0f) { pnt = base; break; } q = pq / p; assert(k >= 0.0f); if (q >= 0.0f && q <= 1.0f){ pnt = base + p*(hullPoints[e.pointIdx[0]] - base) + pq*(hullPoints[e.pointIdx[1]] - hullPoints[e.pointIdx[0]]); break; } } } scale = k; }break; default: assert("Convex Hull state not properly defined!"); break; } // scale = (scale > 1.0f) ? 1.0f : scale; pnt /= (scale < 1.0f) ? 1.0f : scale; scale = (scale > 1.0f) ? 1.0f : scale; std::cout << pnt << std::endl; std::cout << "= " << scale << " * " << vec << std::endl; } std::ofstream& operator<<(std::ofstream& ostr, const CnvH& hull){ ostr.setf(std::ios::fixed, std::ios::floatfield); ostr.setf(std::ios::showpoint); ostr << "#Vertecies" <<std::endl; for (const CnvH::point& p : hull.hullPoints) { ostr << "v " << p.vec.x << " " << p.vec.y << " " << p.vec.z << std::endl; }; ostr << "#Inecies" << std::endl; for (const CnvH::quad& q : hull.hullQuads) { ostr << "f " << q.pointIdx[0] + 1 << " " << q.pointIdx[1] + 1 << " " << q.pointIdx[2] + 1 << std::endl; ostr << "f " << q.pointIdx[0] + 1 << " " << q.pointIdx[2] + 1 << " " << q.pointIdx[3] + 1 << std::endl; } return ostr; } // Finds the open edges in selection of quads. std::list<CnvH::edge> CnvH::FindOpenEdges(std::list<quad*>& quadArray) { std::list<edge> openEdges; for (const quad* ptr_q : quadArray) { for (int i = 0; i < 4; i++) { int j = (i < 3) ? j = i + 1 : j = i - 3; edge trueEdge = { ptr_q->pointIdx[i], ptr_q->pointIdx[j] }; edge revEdge = { ptr_q->pointIdx[j], ptr_q->pointIdx[i] }; auto it_found = std::find(openEdges.begin(), openEdges.end(), revEdge); if (it_found == openEdges.end()) { openEdges.push_back(trueEdge); } else { openEdges.erase(it_found); } } } return openEdges; } // Builds a quad between 2 edges CnvH::quad CnvH::BuildQuad( edge e1, edge e2, FVector dist ) { size_t idx[4] = { e1.pointIdx[0], e1.pointIdx[1], e2.pointIdx[1], e2.pointIdx[0] }; FVector vec = hullPoints[idx[1]].vec - hullPoints[idx[0]].vec; FVector normal = norm(cross(vec, dist)); return quad(this, idx[0], idx[1], idx[2], idx[3], normal); } // Returns a quad with reverse normal CnvH::quad CnvH::FlipQuad(const quad& q) { size_t idx[4] = { q.pointIdx[0], q.pointIdx[3], q.pointIdx[2], q.pointIdx[1], }; FVector normal = q.normal * -1.0f; return quad(this, idx[0], idx[1], idx[2], idx[3], normal); } bool operator==(const CnvH::edge& A, const CnvH::edge& B) { if (&A == &B) return true; return A.pointIdx[0] == B.pointIdx[0] && A.pointIdx[1] == B.pointIdx[1]; } CnvH::point CnvH::BasePoint(const std::list<edge>& edges){ auto it = edges.begin(); point result = hullPoints[it->pointIdx[0]]; ++it; while (it != edges.end()){ result = Common(result, hullPoints[it->pointIdx[0]]); ++it; } return result; } CnvH::point CnvH::Common(const point& A, const point& B){ point result = A; auto it = result.weight.begin(); while (it != result.weight.end()) { auto found = B.weight.find(it->first); if (found != B.weight.end()) { float scale = (it->second < found->second) ? it->second : found->second; it->second = scale; result.vec -= (1.0f - scale)*collection[found->first]; ++it; } else{ result.vec -= collection[it->first]; it = result.weight.erase(it); } } return result; } CnvH::point operator*(float A, const CnvH::point& B){ CnvH::point result = B; result.vec *= A; for (auto& w : result.weight) { w.second *= A; } return result; } CnvH::point operator*(const CnvH::point& A, float B){ CnvH::point result = A; result.vec *= B; for (auto& w : result.weight) { w.second *= B; } return result; } CnvH::point operator+(const CnvH::point& A, const CnvH::point& B){ if (B.vec == FV_ZERO) return A; CnvH::point pnt = A; pnt.vec += B.vec; for (auto w : B.weight) { auto ret = pnt.weight.insert(w); if (!ret.second) { ret.first->second += w.second; if (ret.first->second == 0.0f) pnt.weight.erase(ret.first); } } return pnt; } CnvH::point operator-(const CnvH::point& A, const CnvH::point& B){ if (B.vec == FV_ZERO) return A; CnvH::point pnt = A; pnt.vec -= B.vec; for (auto w : B.weight) { w.second *= -1.0f; auto ret = pnt.weight.insert(w); if (!ret.second) { ret.first->second += w.second; if (ret.first->second == 0.0f) pnt.weight.erase(ret.first); } } return pnt; } #include <iomanip> std::ostream& operator<<(std::ostream& ostr, const CnvH::point& p){ for (auto w : p.weight){ ostr << std::fixed << std::setprecision(5); ostr << w.second << " * #" << w.first << " " << p.parent->collection[w.first] << std::endl; } return ostr; }
32.414876
131
0.57172
[ "geometry", "vector", "3d" ]
3a2c49ac099d3f7cd2d4edc18172edbc7d2492f1
68,629
cpp
C++
src/dict/new_dict_entries.cpp
wa1tnr/yaffa_samD51-exp
555f0e0bbba5c453366960d16573d368065f62f3
[ "MIT" ]
2
2019-08-29T04:14:20.000Z
2021-07-10T05:51:11.000Z
src/dict/new_dict_entries.cpp
wa1tnr/yaffa_samD51-exp
555f0e0bbba5c453366960d16573d368065f62f3
[ "MIT" ]
1
2019-08-30T01:12:05.000Z
2019-08-30T01:12:05.000Z
src/dict/new_dict_entries.cpp
wa1tnr/yaffa_samD51-exp
555f0e0bbba5c453366960d16573d368065f62f3
[ "MIT" ]
1
2019-08-30T00:13:54.000Z
2019-08-30T00:13:54.000Z
// Fri 22 Jun 18:03:52 UTC 2018 // 4737-a3b-005- // new_dict_entries.cpp // source: dict_entries.cpp // previous timestamps: // Thu 21 Jun 22:17:21 UTC 2018 // 4737-a3b-001- +dict_comments_only.cpp file // Thu 21 Jun 17:57:32 UTC 2018 // 4737-a3a-0fe- /* model - target code (in the dictionary files, elsewhere in the source tree): #if defined(INCL_THIS_WORD) || defined(XDICT) . . code . . #endif */ // SPELLING // STYLE GUIDE #ifdef NEVER_DEFINED_ANY_WHERE void myword_underscore_seps(void) { if (w > nFlashEntry) { rStack_push((cell_t) ip); ip = (cell_t *)w; } else { // sometimes there is no whitespace above the 'else' and other times, there is! function = flashDict[w - 1].function; } } #endif // PURPOSE // The purpose of this file (new_dict_entries.cpp) // ---------------------------------------------------------- // ---------------------------------------------------------- // .. is to remove comments and just show code, // where comments became unweildy. // ---------------------------------------------------------- // ---------------------------------------------------------- // In particular, to remove all word definitions for this forth, // from this file, that are suppressed by comments at the beginning // of each line of code so commented-out (the double-forward slash // comment notation). // To do this is tricky, as those definitions, as of yet unfulfilled, // must be preserved somewhere. // That somewhere is to be where they are, already -- in 'dict_entries.cpp'. // Thus, this new file (whatever it is named) will be active code, // whereas dict_entries.cpp should ideally be all dead code, or // almost all dead code. (In this instance, 'to be later revived'). // Wed 20 Jun 22:29:00 UTC 2018 // entire project. // 4737-a3a-0fb- // Wed 23 May 03:16:05 UTC 2018 // dict_entries.cpp // 4737-a3a-05p- #include <Arduino.h> #include "../../yaffa.h" #include "../../Dictionary.h" #include "./new_dict_entries.h" #include "../../b_flashdict.h" char hexBuf[17]; char* toHex( cell_t i ) { itoa( i, hexBuf, 16 ); return (char *) hexBuf; } char * fillChars( char * buf, char c, uint8_t n ) { char * p = buf; uint8_t m = n; while( m -- > 0 ) * p ++ = c; return p; } char nHexBuf[17]; char * toNHex( cell_t i, char leading, int8_t n ) { char * hex = toHex( i ); char * p = fillChars( (char *) nHexBuf, leading, n - strlen( hex ) ); strcpy( p, hex ); return (char *) nHexBuf; } void printStr( char* str ) { Serial.print( str ); } void printStr( char* str0, char* str ) { printStr( str0 ); printStr( str ); } void printHex( cell_t i ) { printStr( toHex( i ) ); } void printHex( char* str0, cell_t i ) { printStr( str0, toHex( i ) ); } void printHex(cell_t i, uint8_t n) { printStr(toNHex(i, '0', n)); } void printHex( char* str0, cell_t i, uint8_t n ) { printStr( str0 ); printHex( i, n ); } void print2Hex( char* str0, cell_t i ) { printHex( str0, i, 2 ); } void print8Hex( char* str0, cell_t i ) { printHex( str0, i, 8 ); } // const char not_done_str[] = " NOT Implemented Yet \n\r"; const char sp_str[] = " "; // does not belong here const char tab_str[] = "\t"; // does not belong here stack_t dStack; stack_t rStack; /*******************************************************************************/ /** Core Forth Words **/ /*******************************************************************************/ // nice nop: // // Dan Halbert: it's some kind of boundary condition, and your code is // somehow an exactly wrong number of bytes long. I added // this junk code // (volatile is necessary so that the loop doesn't get optimized away), // and it also compiles: // // [7:36 PM] Dan Halbert: // for (volatile int i = 1; i < 2; i++) { // // nothing // } // Serial.println(red); //#if defined(INCL_NOP_WORD) || defined(XDICT) // const char nop_str[] = "nop"; void _nop(void) { } //#endif // #if defined(INCL_NOP_WORD) || defined(XDICT) // const char here_str[] = "here"; // ( -- addr ) // addr is the data-space pointer. void _here(void) { dStack_push((size_t)pHere); } void _pHere(void) { dStack_push((size_t)&pHere); } // const char count_str[] = "count"; // ( c-addr -- c-addr+4 u ) // Return the character string specification for the counted string stored a // c-addr. c-addr+1 is the address of the first character after c-addr1. u is the // contents of the charater at c-addr, which is the length in characters of the // string at c-addr+1. void _count(void) { cell_t* addr = (cell_t*)dStack_pop(); cell_t value = *addr++; dStack_push((size_t)addr); dStack_push(value); /* samsuanchen@gmail.com 20190502 _swap(); addr = (uint8_t*)dStack_pop(); // *addr++; *addr++; *addr++; addr = addr + 3; dStack_push((size_t)addr); _swap(); */ } // const char strlen_str[] = "strlen"; void _strlen(void) { // ( c-addr == u ) // return u as the length of given string at c-addr dStack_push( (cell_t) strlen( (char*) dStack_pop() ) ); } // const char i_str[] = "i"; void _i(void) { // ( -- i ) // return i as the index of working do-loop dStack_push( rStack_peek(1) ); } // const char j_str[] = "j"; void _j(void) { // ( -- j ) // return j as the index of working outer do-loop dStack_push( rStack_peek(4) ); } // const char evaluate_str[] = "evaluate"; // ( i*x c-addr u -- j*x ) // Save the current input source specification. Store minus-one (-1) in SOURCE-ID // if it is present. Make the string described by c-addr and u both the input // source and input buffer, set >IN to zero, and interpret. When the parse area // is empty, restore the prior source specification. Other stack effects are due // to the words EVALUATEd. void _evaluate(void) { /* samsuanchen@gmail.com 20190502 char* tempSource = cpSource; char* tempSourceEnd = cpSourceEnd; char* tempToIn = cpToIn; */ rStack_push( (cell_t) cpSource ); // samsuanchen@gmail.com 20190502 rStack_push( (cell_t) cpSourceEnd ); // samsuanchen@gmail.com 20190502 rStack_push( (cell_t) cpToIn ); // samsuanchen@gmail.com 20190502 uint8_t length = dStack_pop(); cpSource = (char*)dStack_pop(); cpSourceEnd = cpSource + length; cpToIn = cpSource; interpreter(); /* samsuanchen@gmail.com 20190502 cpSource = tempSource; cpSourceEnd = tempSourceEnd; */ cpToIn = (char*) rStack_pop(); // samsuanchen@gmail.com 20190502 cpSourceEnd = (char*) rStack_pop(); // samsuanchen@gmail.com 20190502 cpSource = (char*) rStack_pop(); // samsuanchen@gmail.com 20190502 } // char execute_str[] = "execute"; // ( i*x xt -- j*x ) // stack effects are due to the word executed void _execute(void) { func function; w = dStack_pop(); if ( ( w <= 0 ) || ( ( w > nFlashEntry ) && ( w < (cell_t) &forthSpace[4] ) ) || ( w > (cell_t) pLastUserEntry->cfa ) ) { _throw(-13); return; } if (w <= nFlashEntry) { function = flashDict[w - 1].function; function(); } else { // comment: see original source for extra commented-out 1 line of code here rStack_push((cell_t) ip_begin); // CAL - Push our return address rStack_push((cell_t) ip); // CAL - Push our return address ip_begin = ip = (cell_t *)w; // set the ip to the XT (memory location) executeWord(); } } // const char word_str[] = "word"; // ( char "<chars>ccc<chars>" -- c-addr ) // Skip leading delimiters. Parse characters ccc delimited by char. An ambiguous // condition exists if the length of the parsed string is greater than the // implementation-defined length of a counted string. // // c-addr is the address of a transient region containing the parsed word as a // counted string. If the parse area was empty or contained no characters other than // the delimiter, the resulting string has a zero length. A space, not included in // the length, follows the string. A program may replace characters within the // string. // // NOTE: The requirement to follow the string with a space is obsolescent and is // included as a concession to existing programs that use CONVERT. A program shall // not depend on the existence of the space. void _word(void) { uint8_t *start, *ptr; cell_t n = 0; cDelimiter = (char)dStack_pop(); start = (uint8_t *)pHere++; ptr = (uint8_t *)pHere; while (cpToIn <= cpSourceEnd) { if (*cpToIn == cDelimiter || *cpToIn == 0) break; *ptr++ = *cpToIn++; } *ptr = 0; n = (ptr - start) - sizeof(cell_t); *((cell_t*) start) = n; // write the length byte // Serial.print("\r\n 0x"); Serial.print(*start, 16); // Serial.print(" \""); Serial.print((char*) (start+4)); // Serial.print("\" at 0x"); Serial.print((cell_t) (start+4), 16); pHere = (cell_t *)start; // reset pHere (transient memory) cpToIn++; cDelimiter = ' '; dStack_push((size_t)start); // push the c-addr onto the stack } // const char back_slash_str[] = "\\"; // ignore following chars until "\0", "\n", " \t", or " " void _back_slash(){ while (cpToIn <= cpSourceEnd) { if (*cpToIn == '\n' || *cpToIn == 0 || strncmp(cpToIn," ",2) == 0 || strncmp(cpToIn," \t",2) == 0 ) break; cpToIn++; } if ( *(cpToIn-1) == 0 ) --cpToIn; else if ( *cpToIn == ' ' ) ++cpToIn; } // const char c_comma_str[] = "c,"; // const char c_fetch_str[] = "c@"; // const char words_str[] = "words"; // see: stack_ops.cpp // const char two_fetch_str[] = "2@"; // \x40 == '@' // const char plus_store_str[] = "+!"; // const char two_store_str[] = "2!"; // const char number_sign_str[] = "#"; // ( ud1 -- ud2) // Divide ud1 by number in BASE giving quotient ud2 and remainder n. Convert // n to external form and add the resulting character to the beginning of the // pictured numeric output string. static char charset[] = "0123456789abcdefghijklmnopqrstvuwxyz"; // samsuanchen@gmail.com 20190510 void _number_sign(void) { udcell_t ud; ud = (udcell_t)dStack_pop() << sizeof(ucell_t) * 8; ud += (udcell_t)dStack_pop(); *--pPNO = charset[ud % base]; ud /= base; dStack_push((ucell_t)ud); dStack_push((ucell_t)(ud >> sizeof(ucell_t) * 8)); } // const char number_sign_gt_str[] = "#>"; // ( xd -- c-addr u) // Drop xd. Make the pictured numeric output string available as a character // string c-addr and u specify the resulting string. A program may replace // characters within the string. void _number_sign_gt(void) { _two_drop(); dStack_push((size_t)pPNO); dStack_push((size_t)strlen(pPNO)); flags &= ~NUM_PROC; } // const char number_sign_s_str[] = "#s"; // ( ud1 -- ud2) void _number_sign_s(void) { udcell_t ud; ud = (udcell_t)dStack_pop() << sizeof(ucell_t) * 8; ud += (udcell_t)dStack_pop(); while (ud) { *--pPNO = charset[ud % base]; ud /= base; } dStack_push((ucell_t)ud); dStack_push((ucell_t)(ud >> sizeof(ucell_t) * 8)); } // const char tick_str[] = "'"; // ( "<space>name" -- xt) // Skip leading space delimiters. Parse name delimited by a space. Find name and // return xt, the execution token for name. An ambiguous condition exists if // name is not found. When interpreting "' xyz EXECUTE" is equivalent to xyz. void _tick(void) { uint8_t n; if (getToken()) { w = isWord(cTokenBuffer); if (w) { dStack_push(w); return; } } _throw(-13); return; } // const char paren_str[] = "("; // ( "ccc<paren>" -- ) // imedeate // void _paren(void) { // dStack_push(')'); // _word(); // _drop(); // } // const char star_slash_str[] = "*/"; // ( n1 n2 n3 -- n4 ) // multiply n1 by n2 producing the double cell result d. Divide d by n3 // giving the single-cell quotient n4. void _star_slash(void) { cell_t n3 = dStack_pop(); cell_t n2 = dStack_pop(); cell_t n1 = dStack_pop(); dcell_t d = (dcell_t)n1 * (dcell_t)n2; dStack_push((cell_t)(d / n3)); } // const char star_slash_mod_str[] = "*/mod"; // ( n1 n2 n3 -- n4 n5) // multiply n1 by n2 producing the double cell result d. Divide d by n3 // giving the single-cell remainder n4 and quotient n5. void _star_slash_mod(void) { cell_t n3 = dStack_pop(); cell_t n2 = dStack_pop(); cell_t n1 = dStack_pop(); dcell_t d = (dcell_t)n1 * (dcell_t)n2; dStack_push((cell_t)(d % n3)); dStack_push((cell_t)(d / n3)); } // const char plus_loop_str[] = "+loop"; // Interpretation: Interpretation semantics for this word are undefined. // Compilation: (C: do-sys -- ) // Append the run-time semantics given below to the current definition. Resolve // the destination of all unresolved occurrences of LEAVE between the location // given by do-sys and the next location for a transfer of control, to execute // the words following +LOOP. // Run-Time: ( n -- )(R: loop-sys1 -- | loop-sys2 ) // An ambiguous condition exists if the loop control parameters are unavailable. // Add n to the index. If the loop index did not cross the boundary between the // loop limit minus one and the loop limit, continue execution at the beginning // of the loop. Otherwise, discard the current loop control parameters and // continue execution immediately following the loop. void _plus_loop(void) { *pHere++ = PLUS_LOOP_SYS_IDX; cell_t start_addr = dStack_pop(); *pHere++ = start_addr; cell_t* ptr = (cell_t*)start_addr; cell_t stop_addr = (cell_t)pHere; do { if (*ptr++ == LEAVE_SYS_IDX) { if (*ptr == 0) { *ptr = stop_addr; } } } while (ptr != (cell_t*)stop_addr); if ( dStack_pop() != DO_SYS) { _throw(-22); } } // const char slash_mod_str[] = "/mod"; // ( n1 n2 -- n3 n4) // divide n1 by n2 giving a single cell remainder n3 and quotient n4 void _slash_mod(void) { cell_t n2 = dStack_pop(); cell_t n1 = dStack_pop(); if (n2) { dStack_push(n1 % n2); dStack_push(n1 / n2); } else { _throw(10); } } // const char zero_less_str[] = "0<"; // ( n -- flag ) // flag is true if and only if n is less than zero. void _zero_less(void) { dStack_top(dStack_top() < 0 ? TRUE : FALSE); } // const char true_str[] = "true"; //samsuanchen@gmail.com 20190514 void _true(){ //samsuanchen@gmail.com 20190514 dStack_push(TRUE); } // const char false_str[] = "false"; //samsuanchen@gmail.com 20190514 void _false(){ //samsuanchen@gmail.com 20190514 dStack_push(FALSE); } // const char zero_str[] = "0"; //samsuanchen@gmail.com 20190514 void _zero(){ //samsuanchen@gmail.com 20190514 dStack_push(0); } // const char one_str[] = "1"; //samsuanchen@gmail.com 20190514 void _one(){ //samsuanchen@gmail.com 20190514 dStack_push(1); } // const char two_str[] = "2"; //samsuanchen@gmail.com 20190514 void _two(){ //samsuanchen@gmail.com 20190514 dStack_push(2); } // const char three_str[] = "3"; //samsuanchen@gmail.com 20190514 void _three(){ //samsuanchen@gmail.com 20190514 dStack_push(3); } // const char four_str[] = "4"; //samsuanchen@gmail.com 20190514 void _four(){ //samsuanchen@gmail.com 20190514 dStack_push(4); } // const char two_plus_str[] = "2+"; //samsuanchen@gmail.com 20190514 void _two_plus(){ //samsuanchen@gmail.com 20190514 dStack_push(dStack_pop() + 2); } // const char two_minus_str[] = "2-"; //samsuanchen@gmail.com 20190514 void _two_minus(){ //samsuanchen@gmail.com 20190514 dStack_push(dStack_pop() - 2); } // const char one_plus_str[] = "1+"; // ( n1|u1 -- n2|u2 ) // add one to n1|u1 giving sum n2|u2. void _one_plus(void) { dStack_push(dStack_pop() + 1); } // const char one_minus_str[] = "1-"; // ( n1|u1 -- n2|u2 ) subtract one to n1|u1 giving sum n2|u2. void _one_minus(void) { dStack_push(dStack_pop() - 1); } // const char two_star_str[] = "2*"; // ( x1 -- x2 ) // x2 is the result of shifting x1 one bit to toward the MSB void _two_star(void) { dStack_push(dStack_pop() << 1); } void _comma(void) { // , ( n -- ) // compile n to wordBody *pHere++ = dStack_pop(); } void _two_slash(void) { // 2/ ( n -- n/2 ) dStack_push(dStack_pop() >> 1); } void _two_drop(void) { // 2drop ( n1 n0 -- ) dStack_pop(), dStack_pop(); } void _two_dup(void) { // 2dup ( x1 x2 -- x1 x2 x1 x2 ) dStack_push(dStack_peek(1)), dStack_push(dStack_peek(1)); } // const char two_over_str[] = "2over"; void _two_over(void) { // ( x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 ) if (dStack_size() >= 4) dStack_push(dStack_peek(3)); dStack_push(dStack_peek(3)); } // const char two_swap_str[] = "2swap"; // ( x1 x2 x3 x4 -- x3 x4 x1 x2 ) void _two_swap(void) { cell_t x4 = dStack_pop(); cell_t x3 = dStack_pop(); cell_t x2 = dStack_pop(); cell_t x1 = dStack_pop(); dStack_push(x3); dStack_push(x4); dStack_push(x1); dStack_push(x2); } // const char lt_str[] = "<"; // ( n1 n2 -- flag ) void _lt(void) { if (dStack_pop() > dStack_pop()) dStack_push(TRUE); else dStack_push(FALSE); } // const char lt_number_sign_str[] = "<#"; // ( -- ) // Initialize the pictured numeric output conversion process. void _lt_number_sign(void) { pPNO = (char*)pHere + HOLD_SIZE + 1; *pPNO = '\0'; flags |= NUM_PROC; } // const char gt_str[] = ">"; // ( n1 n2 -- flag ) // flag is true if and only if n1 is greater than n2 void _gt(void) { if (dStack_pop() < dStack_pop()) dStack_push(TRUE); else dStack_push(FALSE); } // const char to_body_str[] = ">body"; // ( xt -- a-addr ) // a-addr is the data-field address corresponding to xt. An ambiguous condition // exists if xt is not for a word defined by CREATE. void _to_body(void) { cell_t* xt = (cell_t*)dStack_pop(); if ((cell_t)xt > 0xFF) { if (*xt == VARIABLE_IDX) { dStack_push((size_t)xt+4); return; } cell_t n = *xt; if(n>(cell_t)forthSpace && *(cell_t*)(n-4)==SUBROUTINE_IDX) { dStack_push((cell_t)xt+8); return; } } //dStack_push(-31); _throw(-31); } // const char to_in_str[] = ">in"; // ( -- a-addr ) void _to_in(void) { dStack_push( (size_t) &cpToIn ); } // const char to_number_str[] = ">number"; // ( ud1 c-addr1 u1 -- ud2 c-addr2 u2 ) // ud2 is the unsigned result of converting the characters within the string // specified by c-addr1 u1 into digits, using the number in BASE, and adding // each into ud1 after multiplying ud1 by the number in BASE. Conversion // continues left-to-right until a character that is not convertible, // including any “+” or “-”, is encountered or the string is entirely // converted. c-addr2 is the location of the first unconverted character or // the first character past the end of the string if the string was entirely // converted. u2 is the number of unconverted characters in the string. An // ambiguous condition exists if ud2 overflows during the conversion. void _to_number(void) { Serial.print("\r\n_to_number() "); uint8_t negate = 0; // flag if number is negative uint8_t len = (uint8_t)dStack_pop(); char* ptr = (char*)dStack_pop(); cell_t accum = dStack_pop(); // Look at the initial character, handling either '-', '$', or '%' switch (*ptr) { case '$': base = HEXIDECIMAL; goto SKIP; case '%': base = BINARY; goto SKIP; case '#': base = DECIMAL; goto SKIP; case '+': negate = 0; goto SKIP; case '-': negate = 1; SKIP: // common code to skip initial character ptr++; break; } // Iterate over rest of string, and if rest of digits are in // the valid set of characters, accumulate them. If any // invalid characters found, abort and return 0. while (len > 0) { char* pos = strchr(charset, (int)tolower(*ptr)); cell_t offset = pos - charset; if ((offset >= base) || (offset < 0)) break; // exit, We hit a non number accum = accum * base + offset; ptr++, len--; } if (negate) accum = ~accum + 1; // apply sign, if necessary dStack_push(accum); // Push the resultant number dStack_push((size_t)ptr); // Push the last convertered caharacter dStack_push(len); // push the remading length of unresolved charaters } // const char to_r_str[] = ">r"; // ( x -- ) (R: -- x ) // void _to_r(void) { // rStack_push(dStack_pop()); // } // const char question_dup_str[] = "?dup"; // ( x -- 0 | x x ) void _question_dup(void) { if (dStack_peek(0)) { dStack_push(dStack_peek(0)); } else { dStack_pop(); dStack_push(0); } } // const char abort_str[] = "abort"; // (i*x -- ) (R: j*x -- ) // Empty the data stack and preform the function of QUIT, which includes emptying // the return stack, without displaying a message. void _abort(void) { _throw(-1); } // const char abort_quote_str[] = "abort\x22"; // Interpretation: Interpretation semantics for this word are undefined. // Compilation: ( "ccc<quote>" -- ) // Parse ccc delimited by a ". Append the run-time semantics given below to the // current definition. // Runt-Time: (i*x x1 -- | i*x ) (R: j*x -- |j*x ) // Remove x1 from the stack. If any bit of x1 is not zero, display ccc and // preform an implementation-defined abort sequence that included the function // of ABORT. void _abort_quote(void) { *pHere++ = ZJUMP_IDX; dStack_push((size_t)pHere); // Push the address for our origin *pHere++ = 0; _dot_quote(); *pHere++ = LITERAL_IDX; *pHere++ = -2; *pHere++ = THROW_IDX; cell_t* orig = (cell_t*)dStack_pop(); *orig = (size_t)pHere; } // const char accept_str[] = "accept"; // ( c-addr +n1 -- +n2 ) // void _accept(void) { // cell_t length = dStack_pop(); // char* addr = (char*)dStack_pop(); // length = getLine(addr, length); // dStack_push(length); // } /******************************************************************************/ /** begin ... again **/ /** begin ... until **/ /** begin ... while ... repeat **/ /******************************************************************************/ // begin (C: -- begin-sys here ) // Run-Time: (R: -- ) void _begin(void) { // samsuanchen@gmail.com dStack_push(BEGIN_SYS); dStack_push((size_t) pHere); } // again (C: begin-sys -- ) // Run-Time: ( -- ) void _again(void) { // samsuanchen@gmail.com cell_t* beginAdr = (cell_t*) dStack_pop(); if ( dStack_pop() != BEGIN_SYS) { _throw(-22); return; } *pHere++ = JUMP_IDX; *pHere++ = (cell_t) beginAdr; } // until (C: begin-sys -- ) // Run-Time: ( flag -- ) void _until(void) { // samsuanchen@gmail.com cell_t* beginAdr = (cell_t*) dStack_pop(); if ( dStack_pop() != BEGIN_SYS) { _throw(-22); return; } *pHere++ = ZJUMP_IDX; *pHere++ = (cell_t) beginAdr; } // while (C: begin-sys -- begin-adr whie-sys ) // Run-Time: ( flag -- ) void _while(void) { _swap(); // samsuanchen@gmail.com if ( dStack_pop() != BEGIN_SYS) { _throw(-22); return; } *pHere++ = ZJUMP_IDX; dStack_push(WHILE_SYS); dStack_push((size_t) pHere++); } // repeat (C: begin-adr whie-sys -- ) // Run-Time: ( -- ) void _repeat(void) { // samsuanchen@gmail.com cell_t* whileAdr = (cell_t*) dStack_pop(); if ( dStack_pop() != WHILE_SYS) { _throw(-22); return; } *pHere++ = JUMP_IDX; *pHere++ = dStack_pop(); *whileAdr = (cell_t) pHere; } // const char align_str[] = "align"; // ( -- ) // if the data-space pointer is not aligned, reserve enough space to align it. void _align(void) { ALIGN_P(pHere); } // const char aligned_str[] = "aligned"; // ( addr -- a-addr) // a-addr is the first aligned address greater than or equal to addr. void _aligned(void) { ucell_t addr = dStack_pop(); ALIGN(addr); dStack_push(addr); } // const char base_str[] = "base"; // ( -- a-addr) void _base(void) { dStack_push((size_t)&base); } // const char begin_str[] = "begin"; // Interpretation: Interpretation semantics for this word are undefined. // Compilation: (C: -- dest ) // Put the next location for a transfer of control, dest, onto the control flow // stack. Append the run-time semantics given below to the current definition. // Run-time: ( -- ) // Continue execution. // void _begin(void) { // dStack_push((size_t)pHere); // *pHere = 0; // } // const char bl_str[] = "bl"; // ( -- char ) // char is the character value for a space. void _bl(void) { dStack_push(' '); } // const char cell_plus_str[] = "cell+"; // ( a-addr1 -- a-addr2 ) void _cell_plus(void) { dStack_push((size_t)(dStack_pop() + sizeof(cell_t))); } // const char cell_minus_str[] = "cell-"; // ( a-addr1 -- a-addr2 ) void _cell_minus(void) { dStack_push((size_t)(dStack_pop() - sizeof(cell_t))); } // const char cells_str[] = "cells"; // ( n1 -- n2 ) // n2 is the size in address units of n1 cells. void _cells(void) { dStack_push(dStack_pop()*sizeof(cell_t)); } // const char cell_div_str[] = "cell/"; // ( n1 -- n2 ) // n2 is the size in address units of n1 cells. void _cell_div(void) { dStack_push(dStack_pop()/sizeof(cell_t)); } // const char char_plus_str[] = "char+"; // ( c-addr1 -- c-addr2 ) void _char_plus(void) { dStack_push(dStack_pop() + 1); } // const char chars_str[] = "chars"; // ( n1 -- n2 ) // n2 is the size in address units of n1 characters. void _chars(void) { } // const char create_str[] = "create"; // ( "<spaces>name" -- ) // Skip leading space delimiters. Parse name delimited by a space. Create a // definition for name with the execution semantics defined below. If the data-space // pointer is not aligned, reserve enough data space to align it. The new data-space // pointer defines name's data field. CREATE does not allocate data space in name's // data field. // name EXECUTION: ( -- a-addr ) // a-addr is the address of name's data field. The execution semantics of name may // be extended by using DOES>. void _create(void) { extern userEntry_t* pNewUserEntry; extern cell_t* ip_begin;; openEntry(); *pHere++ = VARIABLE_IDX; /* samsuanchen@gmail 20190521 // *pHere++ = LITERAL_IDX; */ // Location of Data Field at the end of the definition. // *pHere++ = (size_t)pHere + 2 * sizeof(cell_t); // *pHere = EXIT_IDX; // Store an extra exit reference so // that it can be replace by a // subroutine pointer created by DOES> // pDoes = pHere; // pHere += 1; */ if (!state) endEntry(), pHere--; // Close the entry if interpreting } // const char depth_str[] = "depth"; // ( -- +n ) // +n is the number of single cells on the stack before +n was placed on it. void _depth(void) { // value -- dStack_push(dStack_size()); } // const char nip_str[] = "nip"; // ( a b -- b ) void _nip(void) { // value -- cell_t b = dStack_pop(); dStack_pop(); dStack_push(b); } // const char does_str[] = "does"; // Compilation: (C: colon-sys1 -- colon-sys2) // Run-Time: ( -- ) (R: nest-sys1 -- ) // Initiation: ( i*x -- i*x a-addr ) (R: -- next-sys2 ) void _does(void) { *pHere++ = SUBROUTINE_IDX; // Store location for a subroutine call // *pHere++ = (size_t)pHere + sizeof(cell_t); // *pHere++ = EXIT_IDX; // Start Subroutine coding } #ifndef MARKED_FOR_DELETE // const char drop_str[] = "drop"; // moved to ../kernel/drop.cpp // void _drop(void) { } #endif // const char else_str[] = "else"; // Interpretation: Undefine // Compilation: (C: orig1 -- orig2) // Run-Time: ( -- ) // void _else(void) { // cell_t* orig = (cell_t*)dStack_pop(); // *pHere++ = JUMP_IDX; // push((size_t)pHere); // Which is correct? // dStack_push((size_t)pHere++); // *orig = (size_t)pHere - (size_t)orig; // } // const char environment_str[] = "environment?"; // ( c-addr u -- false|i*x true ) // c-addr is the address of a character string and u is the string's character // count. u may have a value in the range from zero to an implementation-defined // maximum which shall not be less than 31. The character string should contain // a keyword from 3.2.6 Environmental queries or the optional word sets to to be // checked for correspondence with an attribute of the present environment. // If the system treats the attribute as unknown, the return flag is false; // otherwise, the flag is true and i*x returned is the of the type specified in // the table for the attribute queried. // void _environment(void) { // int fake = 0; // local developer idiom. Ignore. // char length = (char)dStack_pop(); // char* pStr = (char*)dStack_pop(); // if (length && length < BUFFER_SIZE) { // if (!strcmp_P(pStr, PSTR("/counted-string"))) { // dStack_push(BUFFER_SIZE); // return; // } // if (!strcmp_P(pStr, PSTR("/hold"))) { // dStack_push(HOLD_SIZE); // return; // } // if (!strcmp_P(pStr, PSTR("address-unit-bits"))) { // dStack_push(sizeof(void *) * 8); // return; // } // if (!strcmp_P(pStr, PSTR("core"))) { // dStack_push(CORE); // return; // } // if (!strcmp_P(pStr, PSTR("core-ext"))) { // dStack_push(CORE_EXT); // return; // } // if (!strcmp_P(pStr, PSTR("floored"))) { // dStack_push(FLOORED); // return; // } // if (!strcmp_P(pStr, PSTR("max-char"))) { // dStack_push(MAX_CHAR); // return; // } #if DOUBLE // if (!strcmp_P(pStr, PSTR("max-d"))) { // dStack_push(MAX_OF(dcell_t)); // return; // } #endif // if (!strcmp_P(pStr, PSTR("max-n"))) { // dStack_push(MAX_OF(cell_t)); // return; // } // if (!strcmp_P(pStr, PSTR("max-u"))) { // dStack_push(MAX_OF(ucell_t)); // return; // } #if DOUBLE // if (!strcmp_P(pStr, PSTR("max-ud"))) { // dStack_push(MAX_OF(udcell_t)); // return; // } #endif // if (!strcmp_P(pStr, PSTR("return-stack-size"))) { // dStack_push(RSTACK_SIZE); // return; // } // if (!strcmp_P(pStr, PSTR("stack-size"))) { // dStack_push(STACK_SIZE); // return; // } // } // dStack_push(-13); // _throw(); // } #ifndef MARKED_FOR_DELETE // ###bookmark Thu Jun 29 17:58:14 UTC 2017 // const char fill_str[] = "fill"; // moved to: store_fetch.cpp // void _fill(void) { } #endif // const char find_str[] = "find"; // ( c-addr -- c-addr 0 | xt 1 | xt -1) // Find the definition named in the counted string at c-addr. If the definition // is not found, return c-addr and zero. If the definition is found, return its // execution token xt. If the definition is immediate, also return one (1), // otherwise also return minus-one (-1). cell_t voc_find(cell_t* voc, char* str, cell_t len) { char* name; if(voc){ pUserEntry = (userEntry_t*) *voc; while (pUserEntry) { name = pUserEntry->name; if ( (strlen(name) == len) && (strncmp(name, str, len) == 0) ) { wordFlags = pUserEntry->flags; return (cell_t) pUserEntry->cfa; } pUserEntry = (userEntry_t*) pUserEntry->prevEntry; } return 0; } uint16_t index = nFlashEntry; while (index--) { name = (char*) flashDict[index].name; if ( (strlen(name) == len) && (strncmp(name, str, len) == 0) ) { wordFlags = flashDict[index].flags; return index + 1; } } wordFlags = 0; return 0; } cell_t find(char* str, cell_t len) { char* name; int i; cell_t* voc; // Search through user dictionaries // _cr(); for(iContext = nContext-1; iContext >= 0; iContext--){ voc = (cell_t*) context[iContext]; for(i = iContext+1; i < nContext; i++) if( voc == context[i] ) break; // voc has already been searched if( i == nContext ) { // the voc has not been searched yet w = voc_find(voc, str, len); // printStr("voc "), printHex((cell_t)voc), printStr(" w "), printHex(w), _space(); if(w) return w; } } w = wordFlags = 0; return w; } void _findFirst(void) { cell_t *cStr = (cell_t *) dStack_top(); cell_t len = *cStr; if (len <= 0) { _throw(-16); return; } if (len > BUFFER_SIZE) { _throw(-18); return; } cell_t xt = voc_find( context[nContext-1], (char*) (cStr+1), len ); if(xt) { dStack_top( xt ); dStack_push( (wordFlags & IMMEDIATE) ? 1 : -1 ); } else { dStack_push( 0 ); } } void _find(void) { // find ( cStr -- cStr 0 | xt 1 | xt -1 ) cell_t *cStr = (cell_t *) dStack_top(); cell_t len = *cStr; if (len <= 0) { _throw(-16); return; } if (len > BUFFER_SIZE) { _throw(-18); return; } cell_t xt = find( (char*) (cStr+1), len ); if(xt) { dStack_top( xt ); dStack_push( (wordFlags & IMMEDIATE) ? 1 : -1 ); } else { dStack_push( 0 ); } } // const char fm_slash_mod_str[] = "fm/mod"; // ( d1 n1 -- n2 n3 ) // Divide d1 by n1, giving the floored quotient n3 and remainder n2. void _fm_slash_mod(void) { cell_t n1 = dStack_pop(); cell_t d1 = dStack_pop(); dStack_push(d1 / n1); dStack_push(d1 % n1); } const char hold_str[] = "hold"; // ( char -- ) // add char to the beginning of the pictured numeric output string. void _hold(void) { if (flags & NUM_PROC) { *--pPNO = (char) dStack_pop(); } } // const char i_str[] = "i"; // Interpretation: undefined // Execution: ( -- n|u ) (R: loop-sys -- loop-sys ) // void _i(void) { // dStack_push(rStack_peek(1)); // } // const char if_str[] = "if"; // Compilation: (C: -- orig ) // Run-Time: ( x -- ) // void _if(void) { // *pHere++ = ZJUMP_IDX; // *pHere = 0; // dStack_push((size_t)pHere++); // } void _immediate(void) { // immediate ( -- ) // make most recent defined word as an immediate word. if (pLastUserEntry) pLastUserEntry->flags |= IMMEDIATE; } void _compileOnly(void) { // immediate ( -- ) // make most recent defined word as an immediate word. if (pLastUserEntry) pLastUserEntry->flags |= COMP_ONLY; } void _invert(void) { // invert ( n -- ~n ) // for example: make 0x1 as 0xfffffffe dStack_push(~dStack_pop()); } // const char j_str[] = "j"; // Interpretation: undefined // Execution: ( -- n|u ) (R0: loop-sys1 loop-sys2 -- loop-sys1 loop-sys2 ) // n|u is a copy of the next-outer loop index. An ambiguous condition exists // if the loop control parameters of the next-outer loop, loop-sys1, are // unavailable. // void _j(void) { // dStack_push(rStack_peek(4)); // } // const char key_str[] = "key"; // ( -- char ) void _key(void) { dStack_push(getKey()); } const char leave_str[] = "leave"; // Interpretation: undefined // Execution: ( -- ) (R: loop-sys -- ) void _leave(void) { *pHere++ = LEAVE_SYS_IDX; *pHere++ = 0; } #ifndef MARKED_FOR_DELETE // const char literal_str[] = "literal"; // moved to: ../kernel/literal.cpp // void _literal(void) { } #endif #ifndef MARKED_FOR_DELETE // const char loop_str[] = "loop"; // moved to: do_loop.cpp // void _loop(void) { } #endif // const char lshift_str[] = "lshift"; // ( x1 u -- x2 ) // x2 is x1 shifted to left by u positions. void _lshift(void) { cell_t u = dStack_pop(); cell_t x1 = dStack_pop(); dStack_push(x1 << u); } // const char m_star_str[] = "m*"; // ( n1 n2 -- d ) // d is the signed product of n1 times n2. void _m_star(void) { dStack_push(dStack_pop() * dStack_pop()); } // const char max_str[] = "max"; // ( n1 n2 -- n3 ) // n3 is the greater of of n1 or n2. // void _max(void) { // cell_t n2 = dStack_pop(); // cell_t n1 = dStack_pop(); // if (n1 > n2) dStack_push(n1); // else dStack_push(n2); // } // const char min_str[] = "min"; // ( n1 n2 -- n3 ) // n3 is the lesser of of n1 or n2. // void _min(void) { // cell_t n2 = dStack_pop(); // cell_t n1 = dStack_pop(); // if (n1 > n2) dStack_push(n2); // else dStack_push(n1); // } //const char mod_str[] = "mod"; // ( n1 n2 -- n3 ) // Divide n1 by n2 giving the remainder n3. void _mod(void) { cell_t n2 = dStack_pop(); dStack_top(dStack_top() % n2); } // const char move_str[] = "move"; // ( addr1 addr2 u -- ) // if u is greater than zero, copy the contents of u consecutive address // starting at addr1 to u consecutive address starting at addr2. void _move(void) { cell_t u = dStack_pop(); cell_t* to = (cell_t*)dStack_pop(); cell_t* from = (cell_t*)dStack_pop(); for (cell_t i = 0; i < u; i++) { *to++ = *from++; } } // const char over_str[] = "over"; // ( x1 x2 -- x1 x2 x1 ) // void _over(void) { // dStack_push(dStack_peek(1)); // } // const char postpone_str[] = "postpone"; // Compilation: ( "<spaces>name" -- ) // Skip leading space delimiters. Parse name delimited by a space. Find name. // Append the compilation semantics of name to the current definition. An // ambiguous condition exists if name is not found. void _postpone(void) { func function; if (!getToken()) { _throw(-16); return; } if (isWord(cTokenBuffer)) { if (wordFlags & COMP_ONLY) { if (w > nFlashEntry) { rStack_push(0); // Push 0 as our return address ip = (cell_t *)w; // set the ip to the XT (memory location) executeWord(); } else { function = flashDict[w - 1].function; function(); if (errorCode) return; } } else { *pHere++ = (cell_t)w; } } else { //dStack_push(-13); _throw(-13); return; } } // const char quit_str[] = "quit"; // ( -- ) (R: i*x -- ) // Empty the return stack, store zero in SOURCE-ID if it is present, // make the user input device the input source, enter interpretation state. // void _quit(void) { // rStack_clear(); // *cpToIn = 0; // Terminate buffer to stop interpreting // Serial.flush(); // } // const char r_from_str[] = "r>"; // Interpretation: undefined // Execution: ( -- x ) (R: x -- ) // move x from the return stack to the data stack. // void _r_from(void) { // dStack_push(rStack_pop()); // } // const char r_fetch_str[] = "r@"; // Interpretation: undefined // Execution: ( -- x ) (R: x -- x) // Copy x from the return stack to the data stack. // void _r_fetch(void) { // dStack_push(rStack_peek(0)); // } // const char recurse_str[] = "recurse"; // Interpretation: Interpretation semantics for this word are undefined // Compilation: ( -- ) // Append the execution semantics of the current definition to the current // definition. An ambiguous condition exists if RECURSE appends in a definition // after DOES>. void _recurse(void) { *pHere++ = (size_t)pCodeStart; } // const char repeat_str[] = "repeat"; // Interpretation: undefined // Compilation: (C: orig dest -- ) // Run-Time ( -- ) // Continue execution at the location given. // void _repeat(void) { // cell_t dest; // cell_t* orig; // *pHere++ = JUMP_IDX; // *pHere++ = dStack_pop() - (size_t)pHere; // orig = (cell_t*)dStack_pop(); // *orig = (size_t)pHere - (size_t)orig; // } // const char rshift_str[] = "rshift"; // ( x1 u -- x2 ) // x2 is x1 shifted to right by u positions. void _rshift(void) { cell_t u = dStack_pop(); cell_t x1 = dStack_pop(); dStack_push((ucell_t)x1 >> u); } // const char s_to_d_str[] = "s>d"; // ( n -- d ) void _s_to_d(void) { dStack_push( dStack_top() < 0 ? -1 : 0 ); } // const char sign_str[] = "sign"; // ( n -- ) void _sign(void) { if (flags & NUM_PROC) { cell_t sign = dStack_pop(); if (sign < 0) *--pPNO = '-'; } } // const char sm_slash_rem_str[] = "sm/rem"; // ( d1 n1 -- n2 n3 ) // Divide d1 by n1, giving the symmetric quotient n3 and remainder n2. void _sm_slash_rem(void) { cell_t n1 = dStack_pop(); cell_t d1 = dStack_pop(); dStack_push(d1 / n1); dStack_push(d1 % n1); } // 2018 May 23rd 03:12z uncommented. // const char source_str[] = "source"; // ( -- c-addr u ) // c-addr is the address of, and u is the number of characters in, the input buffer. // void _source(void) { // dStack_push((size_t)&cInputBuffer); // dStack_push(strlen(cInputBuffer)); // } // ###bookmark five-unsequenced // 2018 May 23rd 03:12z uncommented. //const char source_str[] = "source"; // ( -- c-addr u ) // c-addr is the address of, and u is the number of characters in, the input buffer. void _source(void) { dStack_push((size_t)&cInputBuffer); dStack_push(strlen(cInputBuffer)); } // const char state_str[] = "state"; // ( -- a-addr ) // a-addr is the address of the cell containing compilation state flag. void _state(void) { dStack_push((size_t)&state); } // const char then_str[] = "then"; // Interpretation: Undefine // Compilation: (C: orig -- ) // Run-Time: ( -- ) // void _then(void) { // cell_t* orig = (cell_t*)dStack_pop(); // *orig = (size_t)pHere - (size_t)orig; // } // const char u_lt_str[] = "u<"; // ( u1 u2 -- flag ) // flag is true if and only if u1 is less than u2. void _u_lt(void) { if ((ucell_t)dStack_pop() > ucell_t(dStack_pop())) dStack_push(TRUE); else dStack_push(FALSE); } // const char um_star_str[] = "um*"; // ( u1 u2 -- ud ) // multiply u1 by u2, giving the unsigned double-cell product ud void _um_star(void) { ucell_t u2 = (ucell_t)dStack_pop(); ucell_t u1 = (ucell_t)dStack_pop(); udcell_t ud = (udcell_t)u1 * (udcell_t)u2; ucell_t lsb = ud; ucell_t msb = (ud >> sizeof(ucell_t) * 8); dStack_push(lsb); dStack_push(msb); } // const char um_slash_mod_str[] = "um/mod"; // ( ud u -- ur uq ) // hex 80000011 8 10 um/mod .s <2> 1 88000001 OK.. // Divide ud by u giving quotient uq and remainder ur. void _um_slash_mod(void) { ucell_t u = dStack_pop(); //printStr("\r\n u=$"); printHex(u); ucell_t msb = dStack_pop(); ucell_t lsb = dStack_pop(); udcell_t ud = ((udcell_t) msb << 32) + lsb; //printStr(" ud=$"); printHex(msb); printHex(lsb,8); ucell_t ur = ud % u; //printStr(" ur=$"); printHex(ur); ucell_t uq = ud / u; //printStr(" uq=$"); printHex(uq); dStack_push(ur); dStack_push(uq); } // const char unloop_str[] = "unloop"; // leave // Interpretation: Undefine // Execution: ( -- )(R: loop-sys -- ) //void _unloop(void) { // rStack_pop(); // rStack_pop(); // if (rStack_pop() != LOOP_SYS) { // dStack_push(-22); // _throw(); // } //} // const char until_str[] = "until"; // Interpretation: Undefine // Compilation: (C: dest -- ) // Run-Time: ( x -- ) // void _until(void) { // *pHere++ = ZJUMP_IDX; // *pHere = dStack_pop() - (size_t)pHere; // pHere += 1; // } // ###bookmark four Thu Jun 29 18:37:12 UTC 2017 #ifndef MARKED_FOR_DELETE // const char variable_str[] = "variable"; // ( "<spaces>name" -- ) // Parse name delimited by a space. Create a definition for name with the // execution semantics defined below. Reserve one cell of data space at an // aligned address. // name Execution: ( -- a-addr ) // a-addr is the address of the reserved cell. A program is responsible for // initializing the contents of a reserved cell. // void _variable(void) { // if (flags & EXECUTE) { // dStack_push((size_t)ip++); // } else { // openEntry(); // *pHere++ = VARIABLE_IDX; // *pHere++ = 0; // endEntry(); // } // } #endif // const char while_str[] = "while"; // Interpretation: Undefine // Compilation: (C: dest -- orig dest ) // Run-Time: ( x -- ) // void _while(void) { // ucell_t dest; // ucell_t orig; // dest = dStack_pop(); // *pHere++ = ZJUMP_IDX; // orig = (size_t)pHere; // *pHere++ = 0; // dStack_push(orig); // dStack_push(dest); // } // const char left_bracket_str[] = "["; // Interpretation: undefined // Compilation: Preform the execution semantics given below // Execution: ( -- ) // Enter interpretation state. [ is an immediate word. void _left_bracket(void) { state = FALSE; } // const char bracket_tick_str[] = "[']"; // Interpretation: Interpretation semantics for this word are undefined. // Compilation: ( "<space>name" -- ) // Skip leading space delimiters. Parse name delimited by a space. Find name. // Append the run-time semantics given below to the current definition. // An ambiguous condition exist if name is not found. // Run-Time: ( -- xt ) // Place name's execution token xt on the stack. The execution token returned // by the compiled phrase "['] X" is the same value returned by "' X" outside // of compilation state. void _bracket_tick(void) { if ( ! getToken() ) { _throw( -16 ); return; } if ( ! isWord( cTokenBuffer ) ) { _throw( -13 ); return; } *pHere++ = LITERAL_IDX; *pHere++ = w; } #ifndef MARKED_FOR_DELETE // const char bracket_char_str[] = "[char]"; // Interpretation: Interpretation semantics for this word are undefined. // Compilation: ( "<space>name" -- ) // Skip leading spaces delimiters. Parse name delimited by a space. Append // the run-time semantics given below to the current definition. // Run-Time: ( -- char ) // Place char, the value of the first character of name, on the stack. void _bracket_char(void) { if (getToken()) { *pHere++ = LITERAL_IDX; *pHere++ = cTokenBuffer[0]; } else { dStack_push(-16); _throw(); } } #endif // const char right_bracket_str[] = "]"; // ( -- ) // Enter compilation state. void _right_bracket(void) { state = TRUE; } /*******************************************************************************/ /** Core Extension Set **/ /*******************************************************************************/ #ifdef CORE_EXT_SET // const char zero_not_equal_str[] = "0<>"; // ( x -- flag) // flag is true if and only if x is not equal to zero. void _zero_not_equal(void) { w = dStack_pop(); if (w == 0) dStack_push(FALSE); else dStack_push(TRUE); } // const char zero_greater_str[] = "0>"; // (n -- flag) // flag is true if and only if n is greater than zero. void _zero_greater(void) { w = dStack_pop(); if (w > 0) dStack_push(TRUE); else dStack_push(FALSE); } // const char two_to_r_str[] = "2>r"; // Interpretation: Interpretation semantics for this word are undefined. // Execution: ( x1 x2 -- ) ( R: -- x1 x2 ) // Transfer cell pair x1 x2 to the return stack. Semantically equivalent // to SWAP >R >R. void _two_to_r(void) { _swap(); _to_r(); _to_r(); } // const char two_r_from_str[] = "2r>"; // Interpretation: Interpretation semantics for this word are undefined. // Execution: ( -- x1 x2 ) ( R: x1 x2 -- ) // Transfer cell pair x1 x2 from the return stack. Semantically equivalent to // R> R> SWAP. void _two_r_from(void) { _r_from(); _r_from(); _swap(); } // const char two_r_fetch_str[] = "2r@"; // Interpretation: Interpretation semantics for this word are undefined. // Execution: ( -- x1 x2 ) ( R: x1 x2 -- x1 x2 ) // Copy cell pair x1 x2 from the return stack. Semantically equivalent to // R> R> 2DUP >R >R SWAP. void _two_r_fetch(void) { _r_from(); _r_from(); _two_dup(); _to_r(); _to_r(); _swap(); } // const char colon_noname_str[] = ":noname"; // ( C: -- colon-sys ) ( S: -- xt ) // Create an execution token xt, enter compilation state and start the current // definition, producing colon-sys. Append the initiation semantics given // below to the current definition. // The execution semantics of xt will be determined by the words compiled into // the body of the definition. This definition can be executed later by using // xt EXECUTE. // If the control-flow stack is implemented using the data stack, colon-sys // shall be the topmost item on the data stack. See 3.2.3.2 Control-flow stack. // // Initiation: ( i*x -- i*x ) ( R: -- nest-sys ) // Save implementation-dependent information nest-sys about the calling // definition. The stack effects i*x represent arguments to xt. // // xt Execution: ( i*x -- j*x ) // Execute the definition specified by xt. The stack effects i*x and j*x // represent arguments to and results from xt, respectively. //void _colon_noname(void) { // state = TRUE; // push(COLON_SYS); // openEntry(); //} // const char neq_str[] = "<>"; // (x1 x2 -- flag) // flag is true if and only if x1 is not bit-for-bit the same as x2. void _neq(void) { cell_t x2 = dStack_pop(); cell_t x1 = dStack_pop(); if (x1 != x2) dStack_push(TRUE); else dStack_push(FALSE); } // const char case_str[] = "case"; // Contributed by Craig Lindley // Interpretation semantics for this word are undefined. // Compilation: ( C: -- case-sys ) // Mark the start of the CASE ... OF ... ENDOF ... ENDCASE structure. Append the run-time // semantics given below to the current definition. // Run-time: ( -- ) // Continue execution. void _case(void) { dStack_push(CASE_SYS); dStack_push(0); // Count of of clauses } // const char of_str[] = "of"; // Contributed by Craig Lindley // Interpretation semantics for this word are undefined. // Compilation: ( C: -- of-sys ) // Put of-sys onto the control flow stack. Append the run-time semantics given below to // the current definition. The semantics are incomplete until resolved by a consumer of // of-sys such as ENDOF. // Run-time: ( x1 x2 -- | x1 ) // If the two values on the stack are not equal, discard the top value and continue execution // at the location specified by the consumer of of-sys, e.g., following the next ENDOF. // Otherwise, discard both values and continue execution in line. void _of(void) { dStack_push(dStack_pop() + 1); // Increment count of of clauses rStack_push(dStack_pop()); // Move to return stack dStack_push(OF_SYS); *pHere++ = OVER_IDX; // Postpone over *pHere++ = EQUAL_IDX; // Postpone = *pHere++ = ZJUMP_IDX; // If *pHere = 0; // Filled in by endof dStack_push((size_t) pHere++);// Push address of jump address onto control stack dStack_push(rStack_pop()); // Bring of count back } // const char endof_str[] = "endof"; // Contributed by Craig Lindley // Interpretation semantics for this word are undefined. // Compilation: ( C: case-sys1 of-sys -- case-sys2 ) // Mark the end of the OF ... ENDOF part of the CASE structure. The next location for a // transfer of control resolves the reference given by of-sys. Append the run-time semantics // given below to the current definition. Replace case-sys1 with case-sys2 on the // control-flow stack, to be resolved by ENDCASE. // Run-time: ( -- ) // Continue execution at the location specified by the consumer of case-sys2. void _endof(void) { cell_t *back, *forward; rStack_push(dStack_pop()); // Move of count to return stack // Prepare jump to endcase *pHere++ = JUMP_IDX; *pHere = 0; forward = pHere++; back = (cell_t*) dStack_pop(); // Resolve If from of //*back = (size_t) pHere - (size_t) back; *back = (size_t) pHere; if (dStack_pop() != OF_SYS) { // Make sure control structure is consistent //dStack_push(-22); _throw(-22); return; } // Place forward jump address onto control stack dStack_push((cell_t) forward); dStack_push(rStack_pop()); // Bring of count back } // const char endcase_str[] = "endcase"; // Contributed by Craig Lindley // Interpretation semantics for this word are undefined. // Compilation: ( C: case-sys -- ) // Mark the end of the CASE ... OF ... ENDOF ... ENDCASE structure. Use case-sys to resolve // the entire structure. Append the run-time semantics given below to the current definition. // Run-time: ( x -- ) // Discard the case selector x and continue execution. void _endcase(void) { cell_t *orig; // Resolve all of the jumps from of statements to here int count = dStack_pop(); for (int i = 0; i < count; i++) { orig = (cell_t *) dStack_pop(); *orig = (size_t) pHere; } *pHere++ = DROP_IDX; // Postpone drop of case selector if (dStack_pop() != CASE_SYS) { // Make sure control structure is consistent // dStack_push(-22); _throw(-22); } } #endif /*******************************************************************************/ /** Double Cell Set **/ /*******************************************************************************/ #ifdef DOUBLE_SET #endif /*******************************************************************************/ /** File: Dictionary.ino **/ /*******************************************************************************/ /** Exception Set **/ /** ainsuForth: this stays. **/ /*******************************************************************************/ #ifdef EXCEPTION_SET #endif /*******************************************************************************/ /** Facility Set **/ /*******************************************************************************/ #ifdef FACILITY_SET /* * Contributed by Andrew Holt */ // ###bookmark six-unseq // 2018 June 21: key? is not in the current forth vocabulary. //const char key_question_str[] = "key?"; void _key_question(void) { dStack_push( Serial.available() ? TRUE : FALSE ); } #endif /*******************************************************************************/ /** Local Set **/ /*******************************************************************************/ #ifdef LOCAL_SET #endif /*******************************************************************************/ /** Memory Set **/ /*******************************************************************************/ #ifdef MEMORY_SET #endif /*******************************************************************************/ /** Programming Tools Set **/ /*******************************************************************************/ #ifdef TOOLS_SET // const char dump_str[] = "dump"; // see: dump.cpp // marked for deletion: _dump(); // void _dump(void) { } cell_t* cfaToEntry(cell_t cfa) { int8_t n=8; cell_t* addr = (cell_t*) cfa; --addr; while (*(--addr) != cfa) { if(n) --n; else return 0; // } return --addr; } cell_t* wordEntry(cell_t xt) { cell_t* entry; if (xt <= nFlashEntry) entry = (cell_t*) &flashDict[xt-1]; else entry = cfaToEntry(xt); return entry; } void _showWordType(cell_t xt) { // samsuanchen@gmail.com cell_t* entry = wordEntry(xt); int flags = *((char*)(entry+2)); if (flags & SMUDGE ) Serial.print("SMUDGE " ); if (flags & COMP_ONLY) _bgBlue(),Serial.print("COMP_ONLY"),_bgBlack(),Serial.print(" "); if (flags & IMMEDIATE) _fgRed(),Serial.print("IMMEDIATE "),_fgWhite(); } bool isUserEntry(cell_t* addr) { if(addr>=pHere){ // printStr("\r\naddr>=pHere "); return false; } cell_t* prev= (cell_t*) *addr; if(prev && (prev>(addr-4) || prev<(cell_t*)forthSpace)){ // printStr("\r\nprev && (prev>(addr-4) || prev<(cell_t*)forthSpace) "); return false; } cell_t* cfa=(cell_t*) *(addr+1); if(cfa<(addr+3) || cfa>(addr+12)){ // printStr("\r\ncfa<(addr+3) || cfa>(addr+12) "); return false; } uint8_t*a=(uint8_t*)(addr+2); uint8_t flags = *a++; if(flags & 0x1f){ // printStr("\r\nflags & 0x1f "); return false; } uint8_t c; while(c=*a++) if(c<=0x20){ // printStr("\r\nc<=0x20 "); return false; } // blank or control code could not be in name if(((cell_t)(a+3)&-4)!=(cell_t)cfa){ // printStr("\r\n((cell_t)(a+3)&-4)!=(cell_t)cfa "); return false; } // next aligned cell addr should be cfa // while(a<(uint8_t*)cfa) if(*a++){ // printStr("\r\n*a++ "); // return false; } // after end of name should all be 0 until cfa return true; } void _isUserEntry(void) { cell_t* addr = (cell_t*) dStack_pop(); if(addr>=pHere) dStack_push(0), dStack_push(1); else dStack_push((cell_t) addr), dStack_push((cell_t) isUserEntry(addr)); } // const char psee_str[] = "(see)"; // ( xt -- ) need to fix con-sys and var-sys samsuanchen@gmail.com 20190508 cell_t* addrToSee; void _addrToSee(void) { dStack_push((cell_t) addrToSee); } void _psee(void) { // samsuanchen@gmail.com bool isLiteral, done; cell_t addrLmt = 0, av, *entry; if (errorCode) return; cell_t xt = dStack_pop(); Serial.print("\r\n "); _showWordType(xt); if (xt <= nFlashEntry) { Serial.print("lowLevel Rom Word "); _fgBrightYellow(); dot_name(xt); _fgWhite(); Serial.print(" (xt $"); printHex(xt); Serial.print(")\r\n HEAD "); addrToSee = entry = (cell_t*) &flashDict[xt-1]; printHex((cell_t) addrToSee); Serial.print(" "); printHex(*addrToSee,8); Serial.print(" nfa" ); addrToSee++; Serial.print("\r\n "); printHex((cell_t) addrToSee); Serial.print(" "); printHex(*addrToSee,8); Serial.print(" code"); addrToSee++; Serial.print("\r\n "); printHex((cell_t) addrToSee); Serial.print(" "); printHex(*addrToSee,8); Serial.print(" flag"); addrToSee++; // Serial.print(" (romEntry %X)", &flashDict[xt-1]); } else { Serial.print("highLevel Ram Word "); _fgBrightYellow(); dot_name(xt); _fgWhite(); Serial.print(" (xt $"); printHex(xt); Serial.print(")\r\n HEAD"); addrToSee = entry = (cell_t*) (to_name(xt)-9); // Serial.print(" (ramEntry %X)", addrToSee); Serial.print(" "); printHex((cell_t) addrToSee); Serial.print(" "); printHex(*addrToSee,8); Serial.print(" link"); addrToSee++; Serial.print("\r\n "); printHex((cell_t) addrToSee); Serial.print(" "); printHex(*addrToSee,8); Serial.print(" cfa" ); addrToSee++; Serial.print("\r\n "); printHex((cell_t) addrToSee); Serial.print(" "); printHex(*addrToSee,8); Serial.print(" name, flag"); addrToSee++; while (addrToSee<(cell_t*)xt) { Serial.print("\r\n "); printHex((cell_t) addrToSee); Serial.print(" "); printHex(*addrToSee,8); addrToSee++; } Serial.print("\r\n CODE "); do { cell_t n = *addrToSee; done = isLiteral = false; printHex((cell_t) addrToSee); Serial.print(" "); printHex(n,8); Serial.print(" "); dot_name(n); if(n>(uint)forthSpace && *(cell_t*)(n-4)==SUBROUTINE_IDX){ Serial.print("(does> "); dot_name(*(++addrToSee)); Serial.print(")\r\n BODY "); printHex((cell_t) ++addrToSee); Serial.print(" "); printHex(*addrToSee++,8); break; } switch (n) { case VARIABLE_IDX: case CONST_IDX: case VOC_SYS_IDX: Serial.print("\r\n BODY "); printHex((cell_t) ++addrToSee); Serial.print(" "); printHex(*addrToSee,8); if(n == VOC_SYS_IDX){ Serial.print("\r\n "); printHex((cell_t) ++addrToSee); Serial.print(" "); printHex(*addrToSee,8); } done = true; break; case LITERAL_IDX: // isLiteral = true; case JUMP_IDX: case ZJUMP_IDX: case LOOP_SYS_IDX: av = *++addrToSee; Serial.print(" ("); printHex(av,8); Serial.print(")"); addrLmt = ( ( n==JUMP_IDX || n==ZJUMP_IDX ) && addrLmt < av ) ? av : addrLmt; // printStr(" addrLmt "); printHex(addrLmt); break; case S_QUOTE_IDX: case DOT_QUOTE_IDX: Serial.print(sp_str); char *ptr = (char*)(++addrToSee); while (*ptr) Serial.print(*ptr++); Serial.print("\x22"); addrToSee = (cell_t *)((int)ptr&-4); // samsuanchen@gmail.com 20190503 //ALIGN_P(addrToSee); // samsuanchen@gmail.com 20190503 break; } // switch // We're done if exit code but not a literal with value of one //Serial.print(" (done "), Serial.print(done); //Serial.print(" n 0x"), Serial.print(n,16); //Serial.print(" *isLiteral "), Serial.print(isLiteral); //Serial.print(")"); done = done || ( (n == EXIT_IDX) && (addrLmt <= (cell_t) addrToSee) ); addrToSee++; if(! done) printStr("\r\n "); } while (! done); // do } // else // _space(); printHex((cell_t) addrToSee); _cr(); } const char see_str[] = "see"; // ("<spaces>name" -- ) // Display a human-readable representation of the named word's definition. The // source of the representation (object-code decompilation, source block, etc.) // and the particular form of the display in implementation defined. void _see(void) { _tick(); _psee(); } #endif /*******************************************************************************/ /** Search Set **/ /*******************************************************************************/ #ifdef SEARCH_SET #endif /*******************************************************************************/ /** String Set **/ /*******************************************************************************/ #ifdef STRING_SET #endif /********************************************************************************/ /** EEPROM Operations **/ /********************************************************************************/ #ifdef EN_EEPROM_OPS // const char eeRead_str[] = "eeRead"; void _eeprom_read(void) { // address -- value dStack_push(EEPROM.read(dStack_pop())); } // const char eeWrite_str[] = "eeWrite"; void _eeprom_write(void) { // value address -- char address; char value; address = (char) dStack_pop(); value = (char) dStack_pop(); EEPROM.write(address, value); } #endif /********************************************************************************/ /** Arduino Library Operations **/ /********************************************************************************/ //#ifdef EN_ARDUINO_OPS //const char freeMem_str[] = "freeMem"; extern unsigned int freeMem(); void _freeMem(void) { dStack_push(freeMem()); } //#endif #define EN_PIN_WRITE_MODE_READ #ifdef EN_PIN_WRITE_MODE_READ const char pinWrite_str[] = "pinWrite"; // ( u1 u2 -- ) // Write a high (1) or low (0) value to a digital pin // u1 is the pin and u2 is the value ( 1 or 0 ). To turn on the LED // attached to D13, first change its pinMode to OUTPUT. Then, // type "1 13 pinWrite". "0 13 pinWrite" will (correspondingly) turn off // the LED on D13. // Note: if you typed "hex" you must enter everything in hexadecimal // (there is no notation, just type the digits with no symbols to // mark the number base). // Thus, // hex 1 d pinMode 1 d pinWrite 7d0 delay 0 d pinWrite // will set the PinMode to OUTPUT, and pulse the LED on for 2 seconds // (0x7d0 milliseconds). // Afterwards, try // 777 dup 10 dump // just to demonstrate that data entry is currently in hexadecimal. void _pinWrite(void) { digitalWrite(dStack_pop(), dStack_pop()); // digitalWrite(13, HIGH); } const char pinMode_str[] = "pinMode"; // ( u1 u2 -- ) // Set the specified pin behavior to either an input (0) or output (1) // u1 is the pin and u2 is the mode ( 1 or 0 ). // The LED is attached to the GPIO pin assigned to D13, on most Arduino devices. // To set this port pin to an OUTPUT, type "1 13 pinMode". void _pinMode(void) { pinMode(dStack_pop(), dStack_pop()); // pinMode(13, OUTPUT); } const char pinRead_str[] = "pinRead"; void _pinRead(void) { dStack_push(digitalRead(dStack_pop())); } #endif #ifdef EN_ARDUINO_OPS // const char analogRead_str[] = "analogRead"; void _analogRead(void) { dStack_push(analogRead(dStack_pop())); } // const char analogWrite_str[] = "analogWrite"; void _analogWrite(void) { analogWrite(dStack_pop(), dStack_pop()); } // const char to_name_str[] = ">name"; void _to_name(void) { // >name ( xt -- name | 0 ) cell_t top = dStack_top(); dStack_top( top>0 ? (cell_t) to_name(top) : 0 ); } void _to_flags(void) { // >name ( xt -- name | 0 ) cell_t top = dStack_top(); dStack_top( top>0 ? (cell_t) to_flags(top) : 0 ); } #endif void _tone(void) { uint8_t pin; int freq, wait; tone( pin = dStack_pop(), freq = dStack_pop(), wait = dStack_pop()); } void _noTone(void) { uint8_t pin; noTone( pin = dStack_pop() ); } int freq[]={ // 48 keys piano frequency table 110, 117, 123, 131, 139, 147, 156, 165, 175, 185, 196, 208, 220, 233, 247, 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494, 523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988,1046,1109,1175,1245,1319,1397,1480,1568,1661 }; void _freq(void) { dStack_push( (cell_t) &freq ); } void _voc_sys(void) { if(nContext) context[nContext-1] = ip; // pfa of vocWord _exit(); } void _primitive(void) { context[nContext-1] = 0; } void _vocabulary(void) { openEntry(); // create a new vocWord *pHere++ = VOC_SYS_IDX; *pHere++ = 0; // emoty vocabulary *pHere++ = (cell_t) pLastVoc; pLastVoc = pHere-1; // pfa of this new vocWord closeEntry(); } void _lastVoc(void) { dStack_push((cell_t) pLastVoc); } void _vocs(void) { _cr(); cell_t* p = pLastVoc; while(p) { dot_name((cell_t)(p-2)); _space(); p = (cell_t*) *p; } outLen += Serial.print("primitive"); } void _context(void) { dStack_push((cell_t) &context[0]); } void _nContext(void) { dStack_push((cell_t) nContext); } void _current(void) { dStack_push((cell_t) current); } void _definitions(void) { current = context[nContext-1]; } void _also(void) { if( context[nContext-1] ) { if( nContext< 8 ) context[nContext] = context[nContext-1], nContext++; else Serial.print("\r\n context full (max 8 vocs)"); } else Serial.print("\r\n current cannot be primitive"); } void _previous(void) { if(nContext) nContext--; else Serial.print( "\r\ncontext empty" ); } void fgBrightYellowStr( char * str ) { _space(); _fgBrightYellow(); Serial.print( str ); _fgWhite(); } void printVoc( cell_t * voc ) { if( voc ) dot_name( (cell_t) (voc-1) ); else Serial.print( "primitive" ); _space(); } void _order(void) { _cr(); fgBrightYellowStr( "current " ); printVoc( current ); fgBrightYellowStr( "context " ); for(int i = nContext -1; i >= 0; i -- ) printVoc( context[i] ); } void _nRomWords(void) { dStack_push(nFlashEntry); } ///* void _pForget(void) { // ( cfa -- ) cell_t* cfa = (cell_t*) dStack_pop(); if( cfa <= (cell_t*) pFirstUserEntry->cfa ) { _throw( 0, "invalid cfa to forget" ); return; } pHere = (cell_t*) ( (cell_t) ( to_name( (cell_t) cfa ) - 9 ) ); if( current > pHere ) current = (cell_t*) pFirstUserEntry->cfa + 1; for(int i=0; i<nContext; i++) if( context[i] > pHere ) context[i] = (cell_t*) pFirstUserEntry->cfa + 1; for( cell_t* voc = pLastVoc; voc; voc = (cell_t*) * voc ) { // each vocabulary in vocs if( (voc-2) >= cfa ) { pLastVoc = (cell_t*) * voc; // remove this vocabulary } else { for( cell_t* ent = (cell_t*) * (voc-1); ent; ent = (cell_t*) * ent ) { // each word entry in vocabulary if( (cell_t*) *(ent+1) >= cfa ) { * (voc-1) = * ent; // remove this word entry } } } } } void _pad(void) { dStack_push( (cell_t) pHere + PAD_SIZE ); } //*/ /******************************************************************************/ /** YAFFA - Yet Another Forth for Arduino **/ /** **/ /** File: Dictionary.ino **/ /** Copyright (C) 2012 Stuart Wood (swood@rochester.rr.com) **/ /** **/ /** This file is part of YAFFA. **/ /** **/ /** YAFFA 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. **/ /** **/ /** YAFFA 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 YAFFA. If not, see <http://www.gnu.org/licenses/>. **/ /** **/ /******************************************************************************/
31.935319
149
0.588483
[ "object", "model" ]
3a2c65f071b65990c1edeccf2843ccaa6b4eb565
5,691
cpp
C++
GraphTheory/vertex_coloring.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
197
2018-08-19T06:49:14.000Z
2022-03-26T04:11:48.000Z
GraphTheory/vertex_coloring.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
null
null
null
GraphTheory/vertex_coloring.cpp
landcelita/algorithm
544736df6b3cbe20ec58d44d81fe9372b8acd93e
[ "CC0-1.0" ]
15
2018-09-14T09:15:12.000Z
2021-11-16T12:43:43.000Z
// // 彩色数を求める O(N2^N) のアルゴリズム // // cf. // https://drken1215.hatenablog.com/entry/2019/01/16/030000 // // verified // AOJ 2136 Webby Subway // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2136 // #include <iostream> #include <vector> #include <cmath> #include <iomanip> using namespace std; // 彩色数 long long modpow(long long a, long long n, long long MOD) { long long res = 1; while (n > 0) { if (n & 1) res = res * a % MOD; a = a * a % MOD; n >>= 1; } return res; } int chromatic_number(const vector<vector<int> > &G) { const int MOD = 1000000007; int n = (int)G.size(); vector<int> neighbor(n, 0); for (int i = 0; i < n; ++i) { int S = (1<<i); for (int j = 0; j < n; ++j) if (G[i][j]) S |= (1<<j); neighbor[i] = S; } // I[S] := #. of inndepndet subset of S vector<int> I(1<<n); I[0] = 1; for (int S = 1; S < (1<<n); ++S) { int v = __builtin_ctz(S); I[S] = I[S & ~(1<<v)] + I[S & ~neighbor[v]]; } int low = 0, high = n; while (high - low > 1) { int mid = (low + high) >> 1; // g[S] := #. of "k independent sets" which cover S just // f[S] := #. of "k independent sets" which consist of subseta of S // then // f[S] = sum_{T in S} g(T) // g[S] = sum_{T in S} (-1)^(|S|-|T|)f[T] long long g = 0; for (int S = 0; S < (1<<n); ++S) { if ((n - __builtin_popcount(S)) & 1) g -= modpow(I[S], mid, MOD); else g += modpow(I[S], mid, MOD); g = (g % MOD + MOD) % MOD; } if (g != 0) high = mid; else low = mid; } return high; } //////////////////////////// // solver //////////////////////////// using DD = double; const DD INF = 1LL<<60; // to be set appropriately const DD EPS = 1e-10; // to be set appropriately const DD PI = acos(-1.0); DD torad(int deg) {return (DD)(deg) * PI / 180;} DD todeg(DD ang) {return ang * 180 / PI;} /* Point */ struct Point { DD x, y; Point(DD x = 0.0, DD y = 0.0) : x(x), y(y) {} friend ostream& operator << (ostream &s, const Point &p) {return s << '(' << p.x << ", " << p.y << ')';} }; inline Point operator + (const Point &p, const Point &q) {return Point(p.x + q.x, p.y + q.y);} inline Point operator - (const Point &p, const Point &q) {return Point(p.x - q.x, p.y - q.y);} inline Point operator * (const Point &p, DD a) {return Point(p.x * a, p.y * a);} inline Point operator * (DD a, const Point &p) {return Point(a * p.x, a * p.y);} inline Point operator * (const Point &p, const Point &q) {return Point(p.x * q.x - p.y * q.y, p.x * q.y + p.y * q.x);} inline Point operator / (const Point &p, DD a) {return Point(p.x / a, p.y / a);} inline Point conj(const Point &p) {return Point(p.x, -p.y);} inline Point rot(const Point &p, DD ang) {return Point(cos(ang) * p.x - sin(ang) * p.y, sin(ang) * p.x + cos(ang) * p.y);} inline Point rot90(const Point &p) {return Point(-p.y, p.x);} inline DD cross(const Point &p, const Point &q) {return p.x * q.y - p.y * q.x;} inline DD dot(const Point &p, const Point &q) {return p.x * q.x + p.y * q.y;} inline DD norm(const Point &p) {return dot(p, p);} inline DD abs(const Point &p) {return sqrt(dot(p, p));} inline DD amp(const Point &p) {DD res = atan2(p.y, p.x); if (res < 0) res += PI*2; return res;} inline bool eq(const Point &p, const Point &q) {return abs(p - q) < EPS;} inline bool operator < (const Point &p, const Point &q) {return (abs(p.x - q.x) > EPS ? p.x < q.x : p.y < q.y);} inline bool operator > (const Point &p, const Point &q) {return (abs(p.x - q.x) > EPS ? p.x > q.x : p.y > q.y);} inline Point operator / (const Point &p, const Point &q) {return p * conj(q) / norm(q);} /* Line */ struct Line : vector<Point> { Line(Point a = Point(0.0, 0.0), Point b = Point(0.0, 0.0)) { this->push_back(a); this->push_back(b); } friend ostream& operator << (ostream &s, const Line &l) {return s << '{' << l[0] << ", " << l[1] << '}';} }; int ccw_for_dis(const Point &a, const Point &b, const Point &c) { if (cross(b-a, c-a) > EPS) return 1; if (cross(b-a, c-a) < -EPS) return -1; if (dot(b-a, c-a) < -EPS) return 2; if (norm(b-a) < norm(c-a) - EPS) return -2; return 0; } bool isinterPS(const Point &p, const Line &s) { return (ccw_for_dis(s[0], s[1], p) == 0); } bool isinterSS(const Line &s, const Line &t) { if (eq(s[0], s[1])) return isinterPS(s[0], t); if (eq(t[0], t[1])) return isinterPS(t[0], s); return (ccw_for_dis(s[0], s[1], t[0]) * ccw_for_dis(s[0], s[1], t[1]) <= 0 && ccw_for_dis(t[0], t[1], s[0]) * ccw_for_dis(t[0], t[1], s[1]) <= 0); } int main() { int N; while (cin >> N, N) { vector<vector<int> > G(N, vector<int>(N, 0)); vector<vector<Line> > lines(N); for (int i = 0; i < N; ++i) { int num; cin >> num; double x, y; cin >> x >> y; for (int j = 1; j < num; ++j) { double nx, ny; cin >> nx >> ny; Line l(Point(x, y), Point(nx, ny)); lines[i].push_back(l); x = nx, y = ny; } } for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { bool ok = false; for (auto li : lines[i]) { for (auto lj : lines[j]) { if (isinterSS(li, lj)) ok = true; } } if (ok) G[i][j] = G[j][i] = true; } } cout << chromatic_number(G) << endl; } }
34.91411
122
0.491829
[ "vector" ]