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
0fd3bb0714496ccf1fc91699de6392843198ef6f
758
hpp
C++
example/frame/study/sharedobjectmanager/sharedobjectmanager.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
example/frame/study/sharedobjectmanager/sharedobjectmanager.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
example/frame/study/sharedobjectmanager/sharedobjectmanager.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
#ifndef STUDY_SHAREDOBJECTMANAGER_HPP #define STUDY_SHAREDOBJECTMANAGER_HPP #include "utility/common.hpp" #include <ostream> struct WorkPoolController; struct ObjectStub; class SharedObjectManager{ public: enum{ RaiseFlag = 1, EventFlag = 2, Flag1 = 4, Flag2 = 8, Flag3 = 16, Flag4 = 32 }; SharedObjectManager(); ~SharedObjectManager(); bool start(); void insert(size_t _v); bool notify(size_t _idx, solid::uint32 _flags); bool notify(size_t _idx, solid::uint32 _flags, size_t _v); bool notifyAll(solid::uint32 _flags); bool notifyAll(solid::uint32 _flags, size_t _v); void stop(std::ostream &_ros); private: void executeObject(ObjectStub &_robj); friend struct WorkPoolController; struct Data; Data &d; }; #endif
17.227273
59
0.729551
[ "solid" ]
0fd62e6a8d46bbc16098c5b8d0719b98a908cefb
4,073
cc
C++
L1Trigger/DTTraco/src/DTTracoCand.cc
Nik-Menendez/L1Trigger
5336631cc0a517495869279ed7d3a4cac8d4e5e5
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
L1Trigger/DTTraco/src/DTTracoCand.cc
Nik-Menendez/L1Trigger
5336631cc0a517495869279ed7d3a4cac8d4e5e5
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
L1Trigger/DTTraco/src/DTTracoCand.cc
Nik-Menendez/L1Trigger
5336631cc0a517495869279ed7d3a4cac8d4e5e5
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
//------------------------------------------------- // // Class: DTTracoCand // // Description: Implementation of L1MuDTTracoChip // candidate // // // Author List: // C. Grandi // Modifications: // SV BTIC parameter from config // SV bti Trig pointer stored insted of trigdata // 22/VI/04 SV: last trigger code update // 04/XI/04 SV: bug fixed for wrong MB1 superlayer offset! // III/05 SV: NEWGEO update //---------------------------------------------------------- //----------------------- // This Class's Header -- //----------------------- #include "L1Trigger/DTTraco/interface/DTTracoCand.h" //------------------------------- // Collaborating Class Headers -- //------------------------------- #include "L1Trigger/DTBti/interface/DTBtiTrigData.h" #include "L1Trigger/DTTraco/interface/DTTracoChip.h" #include "L1TriggerConfig/DTTPGConfig/interface/DTConfigTraco.h" //--------------- // C++ Headers -- //--------------- #include <iostream> //---------------- // Constructors -- //---------------- DTTracoCand::DTTracoCand(DTTracoChip *tc, const DTBtiTrigData *btitr, int pos, int step) : _traco(tc), _btitr(btitr), _step(step), _position(pos), _usable(1) { if (pos < 1 || pos > 4 * DTConfigTraco::NBTITC) { std::cout << "DTTracoCand::DTTracoCand: wrong position: " << pos; std::cout << ", dummy coordinates set!" << std::endl; _tcX = 9999; _tcK = 9999; return; } // abs value of K in local TRACO frame (angle conversion): // for sorting the angle closest to normal of chamber // Ktr = Kbti - BTIC - KRAD _tcK = abs(btitr->K() - tc->KRad() - tc->BTIC()); // X in local TRACO frame (position conversion): Xtr = Xbti + BTIC*(i+4 or // o-4) int lstep = tc->BTIC(); _tcX = btitr->X() + lstep * ((pos <= DTConfigTraco::NBTITC) * (pos - 1 + DTConfigTraco::NBTITC) + // inner (pos > DTConfigTraco::NBTITC) * (pos - 1 - DTConfigTraco::NBTITC)); // outer // NEWGEO add phi sl offset to inner positions if (btitr->btiSL() == 1) _tcX += tc->IBTIOFF(); /* DEBUG btitr->print(); std::cout << "K in local " << tc->number() << " TRACO " << K() << std::endl; std::cout << "X in local " << tc->number() << " TRACO " << X() << " offset " << tc->IBTIOFF() << std::endl; print(); */ /* //OBSOLETE //ATTENTION!! This isn't the "real" MB-superlayer shift //because wires have been renamed/shifted in : DTTrigGeom::cellMapping(int sl, int lay, int tube) //this is a "patch" : to BE FIXED with NEW GEOMETRY! //MB1: half cell shift if(btitr->btiSL()==1 && tc->station()==1) _tcX += (int)(0.5*lstep); //MB2 // if(btitr->btiSL()==1 && tc->station()==2) // _tcX += (int)(-lstep); //std::cout << "X in local TRACO frame = " << _tcX << std::endl; //print(); */ } DTTracoCand::DTTracoCand(const DTTracoCand &tccand) : _traco(tccand._traco), _btitr(tccand._btitr), _step(tccand._step), _position(tccand._position), _usable(tccand._usable), _tcX(tccand._tcX), _tcK(tccand._tcK) {} //-------------- // Destructor -- //-------------- DTTracoCand::~DTTracoCand() {} //-------------- // Operations -- //-------------- DTTracoCand &DTTracoCand::operator=(const DTTracoCand &tccand) { if (this != &tccand) { _traco = tccand._traco; _btitr = tccand._btitr; _position = tccand._position; _step = tccand._step; _usable = tccand._usable; _tcX = tccand._tcX; _tcK = tccand._tcK; } return *this; } void DTTracoCand::print() const { // int sl = _btitr->btiSL(); std::cout << " step " << _step; std::cout << " Position " << _position; std::cout << " Code = " << _btitr->code(); std::cout << " SL = " << _btitr->btiSL(); std::cout << " N = " << _btitr->btiNumber(); std::cout << " X = " << _btitr->X(); std::cout << " K = " << _btitr->K(); std::cout << " Kr = " << _traco->KRad(); std::cout << " |K-Kr| = " << _tcK << std::endl; }
30.856061
80
0.528849
[ "geometry" ]
0fd63eccb0d52c94ff5f764ae21b8705fa40a149
6,603
cc
C++
shell/platform/windows/keyboard_key_channel_handler_unittests.cc
luoyibu/engine
e535969dbae360446faad3517e5f90ec9164d345
[ "BSD-3-Clause" ]
5,823
2015-09-20T02:43:18.000Z
2022-03-31T23:38:55.000Z
shell/platform/windows/keyboard_key_channel_handler_unittests.cc
luoyibu/engine
e535969dbae360446faad3517e5f90ec9164d345
[ "BSD-3-Clause" ]
20,081
2015-09-19T16:07:59.000Z
2022-03-31T23:33:26.000Z
shell/platform/windows/keyboard_key_channel_handler_unittests.cc
luoyibu/engine
e535969dbae360446faad3517e5f90ec9164d345
[ "BSD-3-Clause" ]
5,383
2015-09-24T22:49:53.000Z
2022-03-31T14:33:51.000Z
// Copyright 2013 The Flutter 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 "flutter/shell/platform/windows/keyboard_key_channel_handler.h" #include <memory> #include "flutter/shell/platform/common/json_message_codec.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/shell/platform/windows/testing/test_binary_messenger.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace flutter { namespace testing { namespace { static constexpr char kScanCodeKey[] = "scanCode"; static constexpr char kCharacterCodePointKey[] = "characterCodePoint"; static constexpr int kHandledScanCode = 0x14; static constexpr int kUnhandledScanCode = 0x15; static constexpr int kUnhandledScanCodeExtended = 0xe015; static std::unique_ptr<std::vector<uint8_t>> CreateResponse(bool handled) { auto response_doc = std::make_unique<rapidjson::Document>(rapidjson::kObjectType); auto& allocator = response_doc->GetAllocator(); response_doc->AddMember("handled", handled, allocator); return JsonMessageCodec::GetInstance().EncodeMessage(*response_doc); } } // namespace TEST(KeyboardKeyChannelHandlerTest, KeyboardHookHandling) { auto handled_message = CreateResponse(true); auto unhandled_message = CreateResponse(false); int received_scancode = 0; TestBinaryMessenger messenger( [&received_scancode, &handled_message, &unhandled_message]( const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) { if (channel == "flutter/keyevent") { auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage( message, message_size); received_scancode = (*message_doc)[kScanCodeKey].GetInt(); if (received_scancode == kHandledScanCode) { reply(handled_message->data(), handled_message->size()); } else { reply(unhandled_message->data(), unhandled_message->size()); } } }); KeyboardKeyChannelHandler handler(&messenger); bool last_handled = false; handler.KeyboardHook( 64, kHandledScanCode, WM_KEYDOWN, L'a', false, false, [&last_handled](bool handled) { last_handled = handled; }); EXPECT_EQ(received_scancode, kHandledScanCode); EXPECT_EQ(last_handled, true); received_scancode = 0; handler.KeyboardHook( 64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false, [&last_handled](bool handled) { last_handled = handled; }); EXPECT_EQ(received_scancode, kUnhandledScanCode); EXPECT_EQ(last_handled, false); received_scancode = 0; handler.KeyboardHook( 64, kHandledScanCode, WM_SYSKEYDOWN, L'a', false, false, [&last_handled](bool handled) { last_handled = handled; }); EXPECT_EQ(received_scancode, kHandledScanCode); EXPECT_EQ(last_handled, true); received_scancode = 0; handler.KeyboardHook( 64, kUnhandledScanCode, WM_SYSKEYDOWN, L'c', false, false, [&last_handled](bool handled) { last_handled = handled; }); EXPECT_EQ(received_scancode, kUnhandledScanCode); EXPECT_EQ(last_handled, false); } TEST(KeyboardKeyChannelHandlerTest, ExtendedKeysAreSentToRedispatch) { auto handled_message = CreateResponse(true); auto unhandled_message = CreateResponse(false); int received_scancode = 0; TestBinaryMessenger messenger( [&received_scancode, &handled_message, &unhandled_message]( const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) { if (channel == "flutter/keyevent") { auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage( message, message_size); received_scancode = (*message_doc)[kScanCodeKey].GetInt(); if (received_scancode == kHandledScanCode) { reply(handled_message->data(), handled_message->size()); } else { reply(unhandled_message->data(), unhandled_message->size()); } } }); KeyboardKeyChannelHandler handler(&messenger); bool last_handled = true; // Extended key flag is passed to redispatched events if set. handler.KeyboardHook( 64, kUnhandledScanCode, WM_KEYDOWN, L'b', true, false, [&last_handled](bool handled) { last_handled = handled; }); EXPECT_EQ(last_handled, false); EXPECT_EQ(received_scancode, kUnhandledScanCodeExtended); last_handled = true; // Extended key flag is not passed to redispatched events if not set. handler.KeyboardHook( 64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false, [&last_handled](bool handled) { last_handled = handled; }); EXPECT_EQ(last_handled, false); EXPECT_EQ(received_scancode, kUnhandledScanCode); } TEST(KeyboardKeyChannelHandlerTest, DeadKeysDoNotCrash) { bool received = false; TestBinaryMessenger messenger( [&received](const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) { if (channel == "flutter/keyevent") { auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage( message, message_size); uint32_t character = (*message_doc)[kCharacterCodePointKey].GetUint(); EXPECT_EQ(character, (uint32_t)'^'); received = true; } return true; }); KeyboardKeyChannelHandler handler(&messenger); // Extended key flag is passed to redispatched events if set. handler.KeyboardHook(0xDD, 0x1a, WM_KEYDOWN, 0x8000005E, false, false, [](bool handled) {}); // EXPECT is done during the callback above. EXPECT_TRUE(received); } TEST(KeyboardKeyChannelHandlerTest, EmptyResponsesDoNotCrash) { bool received = false; TestBinaryMessenger messenger( [&received](const std::string& channel, const uint8_t* message, size_t message_size, BinaryReply reply) { if (channel == "flutter/keyevent") { std::string empty_message = ""; std::vector<uint8_t> empty_response(empty_message.begin(), empty_message.end()); reply(empty_response.data(), empty_response.size()); received = true; } return true; }); KeyboardKeyChannelHandler handler(&messenger); handler.KeyboardHook(64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false, [](bool handled) {}); // Passes if it does not crash. EXPECT_TRUE(received); } } // namespace testing } // namespace flutter
37.305085
80
0.693473
[ "vector" ]
0fd6643020aea0644bf28a8dd3bf918853ee75e5
5,363
cpp
C++
tests/unit/serialization/polymorphic/serialization_smart_ptr_polymorphic.cpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
tests/unit/serialization/polymorphic/serialization_smart_ptr_polymorphic.cpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
tests/unit/serialization/polymorphic/serialization_smart_ptr_polymorphic.cpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2014-2015 Anton Bikineev // // 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 <iostream> #include <hpx/runtime/serialization/serialize.hpp> #include <hpx/runtime/serialization/base_object.hpp> #include <hpx/runtime/serialization/shared_ptr.hpp> #include <hpx/runtime/serialization/intrusive_ptr.hpp> #include <hpx/runtime/serialization/input_archive.hpp> #include <hpx/runtime/serialization/output_archive.hpp> #include <hpx/util/lightweight_test.hpp> // =========================shared_ptr test============================== struct A { int a; A(int a = 1): a(a) {} virtual ~A(){} virtual const char* foo() = 0; template <class Archive> void serialize(Archive& ar, unsigned) { ar & a; } HPX_SERIALIZATION_POLYMORPHIC_ABSTRACT(A); }; struct B: A { int b; B(int b = 2): b(b) {} virtual const char* foo() { return "B::foo"; } template <class Archive> void load(Archive& ar, unsigned) { ar & hpx::serialization::base_object<A>(*this); ar & b; } template <class Archive> void save(Archive& ar, unsigned) const { ar & hpx::serialization::base_object<A>(*this); ar & b; } HPX_SERIALIZATION_SPLIT_MEMBER(); HPX_SERIALIZATION_POLYMORPHIC_SPLITTED(B); }; class C: public B { friend class hpx::serialization::access; int c; template <class Archive> void serialize(Archive& ar, unsigned) { ar & hpx::serialization::base_object<B>(*this); ar & c; } HPX_SERIALIZATION_POLYMORPHIC(C) public: C(int c = 3): c(c) {} virtual const char* foo() { return "C::foo"; } int get_c() const { return c; } }; void test_shared() { boost::shared_ptr<A> ip(new C); boost::shared_ptr<A> op1; boost::shared_ptr<A> op2; { std::vector<char> buffer; hpx::serialization::output_archive oarchive(buffer); oarchive << ip << ip; hpx::serialization::input_archive iarchive(buffer); iarchive >> op1; iarchive >> op2; } HPX_TEST_NEQ(op1.get(), ip.get()); HPX_TEST_NEQ(op2.get(), ip.get()); HPX_TEST_EQ(op1.get(), op2.get()); HPX_TEST_EQ(op1->foo(), std::string("C::foo")); HPX_TEST_EQ(op2->foo(), std::string("C::foo")); HPX_TEST_EQ(static_cast<C*>(op1.get())->a, 1); HPX_TEST_EQ(static_cast<C*>(op1.get())->b, 2); HPX_TEST_EQ(static_cast<C*>(op1.get())->get_c(), 3); HPX_TEST_EQ(static_cast<C*>(op2.get())->a, 1); HPX_TEST_EQ(static_cast<C*>(op2.get())->b, 2); HPX_TEST_EQ(static_cast<C*>(op2.get())->get_c(), 3); HPX_TEST_EQ(op1.use_count(), 2); } // =========================intrusive_ptr test============================== struct D { int a; int count; D(int a = 1): a(a), count(0) {} virtual ~D(){} virtual const char* foo() = 0; private: friend class hpx::serialization::access; template <class Archive> void load(Archive& ar, unsigned) { ar & a; } template <class Archive> void save(Archive& ar, unsigned) const { ar & a; } HPX_SERIALIZATION_SPLIT_MEMBER(); HPX_SERIALIZATION_POLYMORPHIC_ABSTRACT_SPLITTED(D); }; void intrusive_ptr_add_ref(D* d) { ++d->count; } void intrusive_ptr_release(D* d) { if(--d->count == 0) { delete d; } } struct E: D { int b; E(int b = 2): b(b) {} virtual const char* foo() { return "E::foo"; } template <class Archive> void load(Archive& ar, unsigned) { ar & hpx::serialization::base_object<D>(*this); ar & b; } template <class Archive> void save(Archive& ar, unsigned) const { ar & hpx::serialization::base_object<D>(*this); ar & b; } HPX_SERIALIZATION_SPLIT_MEMBER(); HPX_SERIALIZATION_POLYMORPHIC_SPLITTED(E); }; class F: public E { friend class hpx::serialization::access; int c; template <class Archive> void serialize(Archive& ar, unsigned) { ar & hpx::serialization::base_object<E>(*this); ar & c; } HPX_SERIALIZATION_POLYMORPHIC(F) public: F(int c = 3): c(c) {} virtual const char* foo() { return "F::foo"; } int get_c() const { return c; } }; void test_intrusive() { boost::intrusive_ptr<D> ip(new F); boost::intrusive_ptr<D> op1; boost::intrusive_ptr<D> op2; { std::vector<char> buffer; hpx::serialization::output_archive oarchive(buffer); oarchive << ip << ip; hpx::serialization::input_archive iarchive(buffer); iarchive >> op1; iarchive >> op2; } HPX_TEST_NEQ(op1.get(), ip.get()); HPX_TEST_NEQ(op2.get(), ip.get()); HPX_TEST_EQ(op1.get(), op2.get()); HPX_TEST_EQ(op1->foo(), std::string("F::foo")); HPX_TEST_EQ(op2->foo(), std::string("F::foo")); HPX_TEST_EQ(static_cast<F*>(op1.get())->a, 1); HPX_TEST_EQ(static_cast<F*>(op1.get())->b, 2); HPX_TEST_EQ(static_cast<F*>(op1.get())->get_c(), 3); HPX_TEST_EQ(static_cast<F*>(op2.get())->a, 1); HPX_TEST_EQ(static_cast<F*>(op2.get())->b, 2); HPX_TEST_EQ(static_cast<F*>(op2.get())->get_c(), 3); HPX_TEST_EQ(ip->count, 1); HPX_TEST_EQ(op1->count, 2); HPX_TEST_EQ(op2->count, 2); op1.reset(); HPX_TEST_EQ(op2->count, 1); } int main() { test_shared(); test_intrusive(); return hpx::util::report_errors(); }
21.114173
80
0.611971
[ "vector" ]
0fd7d06da5caf894d064cb1f8dc2a9afd6e139f3
15,009
cpp
C++
src/aeTerrainSDF.cpp
johnhues/aether-game-utils
3b67cc77d232d43ee8c273a1db3c9373374438b2
[ "MIT" ]
4
2020-08-26T19:41:32.000Z
2021-05-09T20:54:56.000Z
src/aeTerrainSDF.cpp
johnhues/aether-game-utils
3b67cc77d232d43ee8c273a1db3c9373374438b2
[ "MIT" ]
20
2020-07-07T20:06:04.000Z
2021-02-28T23:09:18.000Z
src/aeTerrainSDF.cpp
johnhues/aether-game-utils
3b67cc77d232d43ee8c273a1db3c9373374438b2
[ "MIT" ]
1
2021-11-03T14:55:25.000Z
2021-11-03T14:55:25.000Z
//------------------------------------------------------------------------------ // aeTerrainSdf.cpp //------------------------------------------------------------------------------ // Copyright (c) 2020 John Hughes // // 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. //------------------------------------------------------------------------------ // Headers //------------------------------------------------------------------------------ #include "aeTerrain.h" namespace ae { //------------------------------------------------------------------------------ // Sdf helpers //------------------------------------------------------------------------------ inline float SdfUnion( float d1, float d2 ) { return aeMath::Min( d1, d2 ); } inline float SdfSubtraction( float d1, float d2 ) { return aeMath::Max( -d1, d2 ); } inline float SdfIntersection( float d1, float d2 ) { return aeMath::Max( d1, d2 ); } inline float SdfSmoothUnion( float d1, float d2, float k ) { float h = aeMath::Clip01( 0.5f + 0.5f * ( d2 - d1 ) / k ); return aeMath::Lerp( d2, d1, h ) - k * h * ( 1.0f - h ); } inline float SdfSmoothSubtraction( float d1, float d2, float k ) { float h = aeMath::Clip01( 0.5f - 0.5f * ( d2 + d1 ) / k ); return aeMath::Lerp( d2, -d1, h ) + k * h * ( 1.0f - h ); } //------------------------------------------------------------------------------ // Sdf member functions //------------------------------------------------------------------------------ Sdf::Sdf() : m_aabb( ae::AABB( ae::Vec3( 0.0f ), ae::Vec3( 0.0f ) ) ), m_halfSize( 0.5f ), m_localToWorld( ae::Matrix4::Identity() ), m_removeTR( ae::Matrix4::Identity() ), m_aabbPrev( ae::AABB( ae::Vec3( 0.0f ), ae::Vec3( 0.0f ) ) ) {} float Sdf::GetValue( ae::Vec3 p ) const { p = ( GetRemoveTRMatrix() * ae::Vec4( p, 1.0f ) ).GetXYZ(); float f = GetValue( p, 0 ); if ( topNoiseStrength || noiseStrength ) { float n = topNoiseScale.x * topNoiseScale.y * topNoiseScale.z; n *= noiseScale.x * noiseScale.y * noiseScale.z; // Prevent scaling to 0 which causes invalid normals if ( n < -0.0001f || 0.0001f < n ) { // Get base shape surface normal ae::Vec3 normal0; for ( int32_t i = 0; i < 3; i++ ) { ae::Vec3 nt = p; nt[ i ] += 0.025f; normal0[ i ] = GetValue( nt, 0 ); } normal0 -= ae::Vec3( f ); ae::Vec3 normal1; for ( int32_t i = 0; i < 3; i++ ) { ae::Vec3 nt = p; nt[ i ] -= 0.025f; normal1[ i ] = GetValue( nt, 0 ); } normal1 = ae::Vec3( f ) - normal1; ae::Vec3 normal = ( normal1 + normal0 ).SafeNormalizeCopy(); float vertical = ae::Max( 0.0f, normal.z ); if ( vertical && topNoiseStrength ) { float iqH = 1.0f; float iqG = exp2(-iqH); float iqf = 1.0f; float iqa = 1.0f; float iqt = 0.0f; for ( uint32_t i = 0; i < 3; i++ ) { ae::Vec3 iqx = topNoiseOffset + p * TerrainNoiseScale / ( GetHalfSize() * topNoiseScale ); iqt += iqa * noise->Get< aeMath::CosineInterpolate >( iqx * iqf ); iqf *= 2.0f; iqa *= iqG; } f += iqt * topNoiseStrength * vertical; } if ( noiseStrength ) { float iqH = 1.0f; float iqG = exp2(-iqH); float iqf = 1.0f; float iqa = 1.0f; float iqt = 0.0f; for ( uint32_t i = 0; i < 3; i++ ) { ae::Vec3 iqx = noiseOffset + p * TerrainNoiseScale / ( GetHalfSize() * noiseScale ); iqt += iqa * noise->Get< aeMath::CosineInterpolate >( iqx * iqf ); iqf *= 2.0f; iqa *= iqG; } f += iqt * noiseStrength * ( 1.0f - vertical ); } } } return f; } void Sdf::SetTransform( const ae::Matrix4& transform ) { if ( m_localToWorld == transform ) { return; } m_localToWorld = transform; // World to local with scaling removed. Translation and rotation // are handled by the base Shape. Sdf functions only need to take // object scaling into consideration. ae::Matrix4 scaledToWorld = m_localToWorld; scaledToWorld = scaledToWorld.GetScaleRemoved(); m_removeTR = scaledToWorld.GetInverse(); // Set scale of inherited Shape object m_halfSize = m_localToWorld.GetScale() * 0.5f; // Update shape world space AABB ae::Vec4 corners[] = { m_localToWorld * ae::Vec4( -0.5f, -0.5f, -0.5f, 1.0f ), m_localToWorld * ae::Vec4( 0.5f, -0.5f, -0.5f, 1.0f ), m_localToWorld * ae::Vec4( 0.5f, 0.5f, -0.5f, 1.0f ), m_localToWorld * ae::Vec4( -0.5f, 0.5f, -0.5f, 1.0f ), m_localToWorld * ae::Vec4( -0.5f, -0.5f, 0.5f, 1.0f ), m_localToWorld * ae::Vec4( 0.5f, -0.5f, 0.5f, 1.0f ), m_localToWorld * ae::Vec4( 0.5f, 0.5f, 0.5f, 1.0f ), m_localToWorld * ae::Vec4( -0.5f, 0.5f, 0.5f, 1.0f ), }; m_aabb = ae::AABB( corners[ 0 ].GetXYZ(), corners[ 1 ].GetXYZ() ); for ( uint32_t i = 2; i < countof( corners ); i++ ) { m_aabb.Expand( corners[ i ].GetXYZ() ); } } ae::Hash Sdf::GetBaseHash( ae::Hash hash ) const { hash = hash.HashBasicType( type ); hash = hash.HashBasicType( materialId ); hash = hash.HashBasicType( smoothing ); hash = hash.HashBasicType( order ); hash = hash.HashBasicType( topNoiseStrength ); hash = hash.HashBasicType( topNoiseOffset ); hash = hash.HashBasicType( topNoiseScale ); hash = hash.HashBasicType( noiseStrength ); hash = hash.HashBasicType( noiseOffset ); hash = hash.HashBasicType( noiseScale ); hash = hash.HashBasicType( m_localToWorld ); return hash; } //------------------------------------------------------------------------------ // SdfBox member functions //------------------------------------------------------------------------------ Sdf* SdfBox::Clone() const { SdfBox* box = ae::New< SdfBox >( AE_ALLOC_TAG_TERRAIN ); *box = *this; return box; } ae::Hash SdfBox::Hash( ae::Hash hash ) const { hash = GetBaseHash( hash ); hash = hash.HashBasicType( cornerRadius ); return hash; } float SdfBox::GetValue( ae::Vec3 p, int ) const { ae::Vec3 q = aeMath::Abs( p ) - ( GetHalfSize() - ae::Vec3( cornerRadius ) ); return ( aeMath::Max( q, ae::Vec3( 0.0f ) ) ).Length() + aeMath::Min( aeMath::Max( q.x, aeMath::Max( q.y, q.z ) ), 0.0f ) - cornerRadius; } //------------------------------------------------------------------------------ // SdfCylinder member functions //------------------------------------------------------------------------------ Sdf* SdfCylinder::Clone() const { SdfCylinder* cylinder = ae::New< SdfCylinder >( AE_ALLOC_TAG_TERRAIN ); *cylinder = *this; return cylinder; } ae::Hash SdfCylinder::Hash( ae::Hash hash ) const { hash = GetBaseHash( hash ); hash = hash.HashBasicType( top ); hash = hash.HashBasicType( bottom ); return hash; } float SdfCylinder::GetValue( ae::Vec3 p, int ) const { ae::Vec3 halfSize = GetHalfSize(); float scale; if ( halfSize.x > halfSize.y ) { scale = halfSize.x; p.y *= halfSize.x / halfSize.y; } else { scale = halfSize.y; p.x *= halfSize.y / halfSize.x; } float r1 = aeMath::Clip01( bottom ) * scale; float r2 = aeMath::Clip01( top ) * scale; float h = halfSize.z; ae::Vec2 q( p.GetXY().Length(), p.z ); ae::Vec2 k1(r2,h); ae::Vec2 k2(r2-r1,2.0*h); ae::Vec2 ca(q.x-aeMath::Min(q.x,(q.y<0.0)?r1:r2), aeMath::Abs(q.y)-h); ae::Vec2 cb = q - k1 + k2*aeMath::Clip01( (k1-q).Dot(k2)/k2.Dot(k2) ); float s = (cb.x<0.0 && ca.y<0.0) ? -1.0 : 1.0; return s*sqrt( aeMath::Min(ca.Dot(ca),cb.Dot(cb)) ); } //------------------------------------------------------------------------------ // SdfHeightmap member functions //------------------------------------------------------------------------------ Sdf* SdfHeightmap::Clone() const { SdfHeightmap* heightmap = ae::New< ae::SdfHeightmap >( AE_ALLOC_TAG_TERRAIN ); *heightmap = *this; return heightmap; } ae::Hash SdfHeightmap::Hash( ae::Hash hash ) const { return GetBaseHash( hash ); } float SdfHeightmap::GetValue( ae::Vec3 p, int ) const { AE_ASSERT_MSG( m_heightMap, "Heightmap image not set" ); ae::Vec3 halfSize = GetHalfSize(); ae::Vec2 p2 = ( p.GetXY() + halfSize.GetXY() ) / ( halfSize.GetXY() * 2.0f ); p2 *= ae::Vec2( m_heightMap->GetWidth(), m_heightMap->GetHeight() ); float v0 = m_heightMap->Get( p2, ae::Image::Interpolation::Cosine ).r; v0 = p.z + halfSize.z - v0 * halfSize.z * 2.0f; ae::Vec3 q = aeMath::Abs( p ) - halfSize; float v1 = ( aeMath::Max( q, ae::Vec3( 0.0f ) ) ).Length() + aeMath::Min( aeMath::Max( q.x, aeMath::Max( q.y, q.z ) ), 0.0f ); return aeMath::Max( v0, v1 ); } //------------------------------------------------------------------------------ // TerrainJob member functions //------------------------------------------------------------------------------ float TerrainJob::GetValue( ae::Vec3 pos ) const { if ( !m_shapes.Length() ) { return 0.0f; } AE_ASSERT( m_shapes[ 0 ]->IsSolid() ); float f = m_shapes[ 0 ]->GetValue( pos ) - m_p.smoothingAmount; for ( uint32_t i = 1; i < m_shapes.Length(); i++ ) { Sdf* shape = m_shapes[ i ]; if ( shape->type == Sdf::Type::Material ) { continue; } float value = shape->GetValue( pos ) - m_p.smoothingAmount; #if _AE_DEBUG_ AE_ASSERT_MSG( value == value, "SDF function returned NAN" ); #endif if ( shape->type == Sdf::Type::Union ) { f = SdfUnion( value, f ); } else if ( shape->type == Sdf::Type::Subtraction ) { f = SdfSubtraction( value, f ); } else if ( shape->type == Sdf::Type::SmoothUnion ) { f = SdfSmoothUnion( value, f, shape->smoothing ); } else if ( shape->type == Sdf::Type::SmoothSubtraction ) { f = SdfSmoothSubtraction( value, f, shape->smoothing ); } } #if _AE_DEBUG_ AE_ASSERT_MSG( f == f, "Terrain SDF function returned NAN" ); #endif return f - m_p.smoothingAmount; // @NOTE: This value isn't used directly, it populates TerrainSdfCache } //------------------------------------------------------------------------------ // TerrainSdf member functions //------------------------------------------------------------------------------ TerrainSdf::TerrainSdf( Terrain* terrain ) : m_terrain( terrain ) { aeRandom r( -1.0f, 1.0f ); ae::Scratch< aeStaticImage3D< float, TerrainNoiseSize, TerrainNoiseSize, TerrainNoiseSize > > tempScratch( AE_ALLOC_TAG_TERRAIN, 1 ); auto& temp = *tempScratch.Data(); for ( uint32_t z = 0; z < temp.GetDepth(); z++ ) for ( uint32_t y = 0; y < temp.GetHeight(); y++ ) for ( uint32_t x = 0; x < temp.GetWidth(); x++ ) { temp.Set( ae::Int3( x, y, z ), r.Get() ); } for ( uint32_t z = 0; z < noise.GetDepth(); z++ ) for ( uint32_t y = 0; y < noise.GetHeight(); y++ ) for ( uint32_t x = 0; x < noise.GetWidth(); x++ ) { noise.Set( ae::Int3( x, y, z ), temp.Get< aeMath::CosineInterpolate >( ae::Vec3( x, y, z ) / (float)TerrainNoiseScale ) ); } } ae::Vec3 TerrainJob::GetDerivative( ae::Vec3 p ) const { // https://iquilezles.org/www/articles/normalsSDF/normalsSDF.htm const float h = 0.0001f; const ae::Vec3 xyy( 1.0f, -1.0f, -1.0f ); const ae::Vec3 yyx( -1.0f, -1.0f, 1.0f ); const ae::Vec3 yxy( -1.0f, 1.0f, -1.0f ); const ae::Vec3 xxx( 1.0f, 1.0f, 1.0f ); const ae::Vec3 n = xyy * GetValue( p + xyy * h ) + yyx * GetValue( p + yyx * h ) + yxy * GetValue( p + yxy * h ) + xxx * GetValue( p + xxx * h ); return n.SafeNormalizeCopy(); } TerrainMaterialId TerrainJob::GetMaterial( ae::Vec3 pos, ae::Vec3 normal ) const { // Use the normal to nudge the material sample position to avoid aliasing TerrainMaterialId materialId = 0; for ( uint32_t i = 0; i < m_shapes.Length(); i++ ) { Sdf* shape = m_shapes[ i ]; // Nudge the sample position out of the surface for paint shapes if ( !shape->IsSolid() && shape->GetValue( pos + normal * 0.1f ) - m_p.smoothingAmount <= 0.0f ) { materialId = shape->materialId; } // Nudge the sample position into the surface for solid shapes else if ( shape->GetValue( pos - normal * 0.1f ) - m_p.smoothingAmount <= 0.0f ) { materialId = shape->materialId; } } return materialId; } void TerrainSdf::DestroySdf( Sdf* sdf ) { if ( !sdf ) { return; } m_pendingDestroy.Append( sdf ); } void TerrainSdf::UpdatePending() { // @NOTE: UpdatePending() is called when no terrain jobs are running, // so it's safe to modify the terrain shapes array // Old for ( uint32_t i = 0; i < m_pendingDestroy.Length(); i++ ) { Sdf* shape = m_pendingDestroy[ i ]; int32_t index = m_shapes.Find( shape ); AE_ASSERT( index >= 0 ); m_shapes.Remove( index ); m_terrain->m_Dirty( shape->GetAABB() ); ae::Delete( shape ); } m_pendingDestroy.Clear(); // New for ( uint32_t i = 0; i < m_pendingCreated.Length(); i++ ) { Sdf* shape = m_pendingCreated[ i ]; m_shapes.Append( shape ); m_terrain->m_Dirty( shape->GetAABB() ); shape->m_dirty = false; shape->m_aabbPrev = shape->GetAABB(); } m_pendingCreated.Clear(); } bool TerrainSdf::HasPending() const { return m_pendingCreated.Length() || m_pendingDestroy.Length(); } void TerrainSdf::RenderDebug( ae::DebugLines* debug ) { for ( uint32_t i = 0; i < m_shapes.Length(); i++ ) { ae::AABB aabb = m_shapes[ i ]->GetAABB(); aabb.Expand( kSdfBoundary ); ae::Vec3 center = ( aabb.GetMin() + aabb.GetMax() ) * 0.5f; ae::Vec3 halfSize = aabb.GetMax() - center; debug->AddAABB( center, halfSize, ae::Color::Red() ); } for ( uint32_t i = 0; i < m_pendingCreated.Length(); i++ ) { ae::AABB aabb = m_pendingCreated[ i ]->GetAABB(); aabb.Expand( kSdfBoundary ); ae::Vec3 center = ( aabb.GetMin() + aabb.GetMax() ) * 0.5f; ae::Vec3 halfSize = aabb.GetMax() - center; debug->AddAABB( center, halfSize, ae::Color::Blue() ); } } } // ae
31.399582
139
0.550603
[ "object", "shape", "transform", "solid" ]
0fe10e35dd1f7749551d24875fd54823babc4aa1
1,571
cpp
C++
Leetcode/Target Sum/Target Sum.cpp
Sloth-Panda/Data-Structure-and-Algorithms
00b74ab23cb8dfc3e96cdae80de95e985ad4a110
[ "MIT" ]
51
2021-01-14T04:05:55.000Z
2022-01-25T11:25:37.000Z
Leetcode/Target Sum/Target Sum.cpp
Sloth-Panda/Data-Structure-and-Algorithms
00b74ab23cb8dfc3e96cdae80de95e985ad4a110
[ "MIT" ]
638
2020-12-27T18:49:53.000Z
2021-11-21T05:22:52.000Z
Leetcode/Target Sum/Target Sum.cpp
Sloth-Panda/Data-Structure-and-Algorithms
00b74ab23cb8dfc3e96cdae80de95e985ad4a110
[ "MIT" ]
124
2021-01-30T06:40:20.000Z
2021-11-21T15:14:40.000Z
class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { //Finding total sum of array int arraySum = accumulate(nums.begin(), nums.end(), 0); //For invalid inputs, we return 0 if (S > arraySum || S < -arraySum || S + arraySum < 0 || (S + arraySum) % 2 == 1) { return 0; } // We get two equations here: // Lets suppose some elements have + sign and some have - sign // So overall we will get (some elements sum)1 - (some elements sum)2= S // Also, we know that (some elements sum)1 + (some elements sum)2 = arraySum // Adding these both equations, the problem is deduced to finding a subarray // whose sum is equal to (S + arraySum)/2 int subsetSum = (S + arraySum) / 2; //Finding the size of given array int n = nums.size(); //Defining dp vector and assigning 0 for base cases vector<vector<int>> dp(n + 1, vector<int>(subsetSum + 1, 0)); //We will have 1 solution for 0 sum with 0 elements dp[0][0] = 1; // Using two for loops, we are finding the answer recursively for i elements and j sum for (int i = 1; i <= n; ++i) { for (int j = 0; j <= subsetSum; ++j) { dp[i][j] = dp[i - 1][j]; if (nums[i - 1] <= j) { dp[i][j] += dp[i - 1][j - nums[i - 1]]; } } } // Our final ans will be for n elements and subsetSum as our sum return dp[n][subsetSum]; } };
41.342105
94
0.528326
[ "vector" ]
0fe1e37fbc9509b8c8c1c1ff184c1dbefe0f339d
12,281
cpp
C++
src/cdr.cpp
alex952/cdr
e8dce20c2cc635e5ad8bf16a16ec4f7d9a86ac16
[ "MIT" ]
null
null
null
src/cdr.cpp
alex952/cdr
e8dce20c2cc635e5ad8bf16a16ec4f7d9a86ac16
[ "MIT" ]
null
null
null
src/cdr.cpp
alex952/cdr
e8dce20c2cc635e5ad8bf16a16ec4f7d9a86ac16
[ "MIT" ]
null
null
null
/* * Copyright 2014-2018 Neueda Ltd. */ #include "cdr.h" namespace neueda { bool cdrItem::asString (string& value) const { char tmp[256]; switch (mType) { case CDR_STRING: value.assign (mString); return true; case CDR_DOUBLE: snprintf (tmp, sizeof tmp, "%f", mDouble); value.assign (tmp); return true; case CDR_INTEGER: snprintf (tmp, sizeof tmp, "%lld", (long long)mInteger); value.assign (tmp); return true; case CDR_DATETIME: snprintf (tmp, sizeof tmp, "%04u-%02u-%02u %02u:%02u:%02u.%04u", mDateTime.mYear, mDateTime.mMonth, mDateTime.mDay, mDateTime.mHour, mDateTime.mMinute, mDateTime.mSecond, mDateTime.mMillisecond); value.assign (tmp); return true; case CDR_ARRAY: snprintf (tmp, sizeof tmp, "<array of %zu>", mArray.size ()); value.assign (tmp); return true; default: return false; } } cdr::cdr () : mNextIndex (0) { } cdr::cdr (const cdr& obj) : mNextIndex (obj.mNextIndex), mItems (obj.mItems) { for (itemMap::iterator itr = mItems.begin(); itr != mItems.end(); ++itr) { mOrdered[itr->second.mIndex] = &itr->second; } } cdr& cdr::operator= (const cdr& obj) { if (this != &obj) { mNextIndex = obj.mNextIndex; mItems = obj.mItems; mOrdered.clear (); for (itemMap::iterator itr = mItems.begin(); itr != mItems.end(); ++itr) { mOrdered[itr->second.mIndex] = &itr->second; } } return *this; } void cdr::findInChildren (const orderedItemMap* items, const cdrKey_t& key, vector<const cdrItem*>& found) const { orderedItemMap::const_iterator it0 = items->begin (); for (; it0 != items->end (); ++it0) { if (it0->second->mKey != key) continue; const cdrItem* item = it0->second; if (it0->second->mType == CDR_ARRAY) { vector<cdr>::const_iterator it = item->mArray.begin (); for (; it != it0->second->mArray.end (); ++it) findInChildren (&it->mOrdered, key, found); } else found.push_back (item); } } void cdr::clear () { mItems.clear (); mOrdered.clear (); } size_t cdr::size () const { return mOrdered.size (); } bool cdr::contains (const cdrKey_t& key) const { return mItems.find (key) != mItems.end (); } bool cdr::isType (const cdrKey_t& key, cdrItemType type, size_t size) const { const cdrItem* item = getItem (key); if (item == NULL || item->mType != type) return false; if (type == CDR_STRING && item->mString.size () < size) return false; return true; } void cdr::setItem (const cdrKey_t& key, cdrItem& item) { item.mKey = key; item.mIndex = mNextIndex++; if (mItems.count (key) != 0) mOrdered.erase (mItems[key].mIndex); mItems[key] = item; mOrdered[item.mIndex] = &mItems[key]; } const cdrItem* cdr::getItem (const cdrKey_t& key) const { map<int64_t, cdrItem>::const_iterator it = mItems.find (key); if (it == mItems.end ()) return NULL; return &it->second; } void cdr::deleteItem (const cdrKey_t& key) { if (mItems.count (key) != 0) { mOrdered.erase (mItems[key].mIndex); mItems.erase (key); } } void cdr::setString (const cdrKey_t& key, const string& value) { cdrItem item (CDR_STRING); item.mString.assign (value); setItem (key, item); } void cdr::setString (const cdrKey_t& key, const char* fmt, ...) { char* tmp; va_list ap; va_start (ap, fmt); if (vasprintf (&tmp, fmt, ap) < 0) abort (); va_end (ap); cdrItem item (CDR_STRING); item.mString.assign (tmp); setItem (key, item); free (tmp); } bool cdr::getString (const cdrKey_t& key, string& value) const { const cdrItem* item = getItem (key); if (item == NULL) return false; return item->asString (value); } void cdr::setDouble (const cdrKey_t& key, double value) { cdrItem item (CDR_DOUBLE); item.mDouble = value; setItem (key, item); } bool cdr::getDouble (const cdrKey_t& key, double& value) const { const cdrItem* item = getItem (key); if (item == NULL) return false; if (item->mType == CDR_STRING) { char* endptr; errno = 0; double dd = strtod (item->mString.c_str (), &endptr); if (errno == ERANGE || *endptr != '\0') return false; value = dd; return true; } else if (item->mType == CDR_DOUBLE) { value = item->mDouble; return true; } return false; } void cdr::setInteger (const cdrKey_t& key, int64_t value) { cdrItem item (CDR_INTEGER); item.mInteger = value; setItem (key, item); } bool cdr::getInteger (const cdrKey_t& key, int64_t& value) const { const cdrItem* item = getItem (key); if (item == NULL) return false; if (item->mType == CDR_STRING) { char* endptr; errno = 0; int64_t ii = strtoll (item->mString.c_str (), &endptr, 0); if ((errno == ERANGE && (ii == LLONG_MIN || ii == LLONG_MAX)) || *endptr != '\0') return false; value = ii; return true; } else if (item->mType == CDR_INTEGER) { value = item->mInteger; return true; } return false; } bool cdr::getInteger (const cdrKey_t& key, uint64_t& value) const { int64_t tmp; if (!getInteger (key, tmp)) return false; value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, int32_t& value) const { int64_t tmp; if (!getInteger (key, tmp)) return false; if (tmp < INT32_MIN || tmp > INT32_MAX) return false; value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, uint32_t& value) const { int64_t tmp; if (!getInteger (key, tmp)) return false; if (tmp < 0 || tmp > UINT32_MAX) return false; value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, int16_t& value) const { int64_t tmp; if (!getInteger (key, tmp)) return false; if (tmp < INT16_MIN || tmp > INT16_MAX) return false; value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, uint8_t& value) const { int64_t tmp; if (!getInteger (key, tmp)) return false; if (tmp < 0 || tmp > UINT8_MAX) return false; value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, int8_t& value) const { int64_t tmp; if (!getInteger (key, tmp)) return false; if (tmp < INT8_MIN || tmp > INT8_MAX) return false; value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, uint16_t& value) const { int64_t tmp; if (!getInteger (key, tmp)) return false; if (tmp < 0 || tmp > UINT16_MAX) return false; value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, int64_t* value) const { int64_t tmp; if (!getInteger (key, tmp)) return false; *value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, uint64_t* value) const { uint64_t tmp; if (!getInteger (key, tmp)) return false; *value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, int32_t* value) const { int32_t tmp; if (!getInteger (key, tmp)) return false; *value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, uint32_t* value) const { uint32_t tmp; if (!getInteger (key, tmp)) return false; *value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, int16_t* value) const { int16_t tmp; if (!getInteger (key, tmp)) return false; *value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, uint8_t* value) const { uint8_t tmp; if (!getInteger (key, tmp)) return false; *value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, int8_t* value) const { int8_t tmp; if (!getInteger (key, tmp)) return false; *value = tmp; return true; } bool cdr::getInteger (const cdrKey_t& key, uint16_t* value) const { uint16_t tmp; if (!getInteger (key, tmp)) return false; *value = tmp; return true; } bool cdr::getDateTime (const cdrKey_t& key, cdrDateTime& value) const { const cdrItem* item = getItem (key); if (item == NULL || item->mType != CDR_DATETIME) return false; value = item->mDateTime; return true; } bool cdr::getDateTime (const cdrKey_t& key, time_t& value) const { tm tm; if (!getDateTime (key, tm)) return false; value = mktime (&tm); return true; } bool cdr::getDateTime (const cdrKey_t& key, tm& value) const { cdrDateTime tmp; if (!getDateTime (key, tmp)) return false; memset (&value, 0, sizeof value); value.tm_hour = tmp.mHour; value.tm_min = tmp.mMinute; value.tm_sec = tmp.mSecond; value.tm_mday = tmp.mDay; if (tmp.mMonth > 0) value.tm_mon = tmp.mMonth - 1; value.tm_year = tmp.mYear - 1900; return true; } void cdr::setDateTime (const cdrKey_t& key, const cdrDateTime& value) { cdrItem item (CDR_DATETIME); item.mDateTime = value; setItem (key, item); } void cdr::setDateTime (const cdrKey_t& key, time_t value) { tm tm; gmtime_r (&value, &tm); cdrItem item (CDR_DATETIME); item.mDateTime.mHour = tm.tm_hour; item.mDateTime.mMinute = tm.tm_min; item.mDateTime.mSecond = tm.tm_sec; item.mDateTime.mDay = tm.tm_mday; item.mDateTime.mMonth = tm.tm_mon + 1; item.mDateTime.mYear = tm.tm_year + 1900; setItem (key, item); } void cdr::emptyArray (const cdrKey_t& key) { cdrItem item (CDR_ARRAY); setItem (key, item); } void cdr::appendArray (const cdrKey_t& key, const cdr& data) { if (mItems.count (key) == 0 || mItems[key].mType != CDR_ARRAY) emptyArray (key); cdrItem* item = &mItems[key]; if (item->mType == CDR_STRING) item->mString.clear (); item->mType = CDR_ARRAY; item->mArray.push_back (data); } u_int cdr::getArraySize (const cdrKey_t& key) const { const cdrItem* item = getItem (key); if (item == NULL || item->mType != CDR_ARRAY) return 0; return item->mArray.size (); } bool cdr::getArray (const cdrKey_t& key, const cdrArray** value) const { const cdrItem* item = getItem (key); if (item == NULL || item->mType != CDR_ARRAY) return false; *value = &item->mArray; return true; } void cdr::setArray (const cdrKey_t& key, cdrArray value) { if (mItems.count (key) == 0 || mItems[key].mType != CDR_ARRAY) emptyArray (key); cdrItem* item = &mItems[key]; if (item->mType == CDR_STRING) item->mString.clear (); item->mArray = value; } vector<const cdrItem*> cdr::findAll (const cdrKey_t& key) const { vector<const cdrItem*> found; findInChildren (&mOrdered, key, found); return found; } void cdr::update (cdr& d) { for (cdr::iterator it = d.begin (); it != d.end (); ++it) { cdrItem item = it->second; this->setItem (item.mKey, item); } } string cdr::toString () const { stringstream ss; int count = 0; for (cdr::const_iterator it = begin (); it != end (); ++it) { if (count != 0) ss << ","; string value; if (!it->second.asString (value)) continue; if (it->second.mType == CDR_ARRAY) { for (cdrArray::const_iterator aIt = it->second.mArray.begin (); aIt != it->second.mArray.end (); ++aIt) { ss << it->first << "=[" << aIt->toString () << "]"; } } else ss << it->first << "=" << value; count++; } return ss.str (); } }
20.780034
75
0.568765
[ "vector" ]
0fe3563a77dccac1cd9eaa1b0b8507b0f6a0e52b
2,849
cpp
C++
applications/StructuralMechanicsApplication/tests/cpp_tests/test_solid_shell_thickness_compute_process.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/StructuralMechanicsApplication/tests/cpp_tests/test_solid_shell_thickness_compute_process.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/StructuralMechanicsApplication/tests/cpp_tests/test_solid_shell_thickness_compute_process.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: structural_mechanics_application/license.txt // // Main authors: Vicente Mataix Ferrandiz // // System includes // External includes // Project includes #include "containers/model.h" #include "testing/testing.h" #include "includes/checks.h" #include "geometries/prism_3d_6.h" /* Processes */ #include "custom_processes/solid_shell_thickness_compute_process.h" namespace Kratos { namespace Testing { typedef Node<3> NodeType; void SolidShellProcessCreateModelPart(ModelPart& ThisModelPart) { Properties::Pointer p_elem_prop = ThisModelPart.CreateNewProperties(0); // First we create the nodes NodeType::Pointer p_node_1 = ThisModelPart.CreateNewNode(1, 0.0 , 0.0 , 0.0); NodeType::Pointer p_node_2 = ThisModelPart.CreateNewNode(2, 1.0 , 0.0 , 0.0); NodeType::Pointer p_node_3 = ThisModelPart.CreateNewNode(3, 1.0 , 1.0 , 0.0); NodeType::Pointer p_node_4 = ThisModelPart.CreateNewNode(4, 0.0 , 0.0 , 1.0); NodeType::Pointer p_node_5 = ThisModelPart.CreateNewNode(5, 1.0 , 0.0 , 1.0); NodeType::Pointer p_node_6 = ThisModelPart.CreateNewNode(6, 1.0 , 1.0 , 1.0); // Now we create the "conditions" std::vector<NodeType::Pointer> element_nodes_0 (6); element_nodes_0[0] = p_node_1; element_nodes_0[1] = p_node_2; element_nodes_0[2] = p_node_3; element_nodes_0[3] = p_node_4; element_nodes_0[4] = p_node_5; element_nodes_0[5] = p_node_6; Prism3D6 <NodeType> prism_0( PointerVector<NodeType>{element_nodes_0} ); ThisModelPart.CreateNewElement("Element3D6N", 1, prism_0, p_elem_prop); } /** * Checks the correct work of the thickness compute for solid shells */ KRATOS_TEST_CASE_IN_SUITE(SolidShellThicknessCompute, KratosStructuralMechanicsFastSuite) { Model current_model; ModelPart& this_model_part = current_model.CreateModelPart("Main"); this_model_part.SetBufferSize(2); SolidShellProcessCreateModelPart(this_model_part); SolidShellThickComputeProcess thickness_process = SolidShellThickComputeProcess(this_model_part); thickness_process.Execute(); for (auto& node : this_model_part.Nodes()) KRATOS_CHECK_NEAR(node.GetValue(THICKNESS), 1.0, std::numeric_limits<double>::epsilon()); } } // namespace Testing } // namespace Kratos.
37
109
0.615655
[ "vector", "model", "solid" ]
0fe3ad9ea07e53a6c9a9f80fc38a6bf954782958
2,947
cpp
C++
Sources/Engine/Engine.cpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
Sources/Engine/Engine.cpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
Sources/Engine/Engine.cpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
#include "Engine.hpp" #include "Audio/Audio.hpp" #include "Devices/Joysticks.hpp" #include "Devices/Keyboard.hpp" #include "Devices/Mouse.hpp" #include "Devices/Window.hpp" #include "Files/Files.hpp" #include "Gizmos/Gizmos.hpp" #include "Inputs/Input.hpp" #include "Particles/Particles.hpp" #include "Graphics/Graphics.hpp" #include "Resources/Resources.hpp" #include "Scenes/Scenes.hpp" #include "Shadows/Shadows.hpp" #include "Timers/Timers.hpp" #include "Uis/Uis.hpp" #include "Config.hpp" namespace acid { Engine *Engine::Instance = nullptr; Engine::Engine(std::string argv0, bool emptyRegister) : m_argv0(std::move(argv0)), m_version{ACID_VERSION_MAJOR, ACID_VERSION_MINOR, ACID_VERSION_PATCH}, m_fpsLimit(-1.0f), m_running(true), m_elapsedUpdate(15.77ms), m_elapsedRender(-1s) { Instance = this; Log::OpenLog(Time::GetDateTime("Logs/%Y%m%d%H%M%S.txt")); #if defined(ACID_DEBUG) Log::Out("Version: ", ACID_VERSION, '\n'); Log::Out("Git: ", ACID_COMPILED_COMMIT_HASH, " on ", ACID_COMPILED_BRANCH, '\n'); Log::Out("Compiled on: ", ACID_COMPILED_SYSTEM, " from: ", ACID_COMPILED_GENERATOR, " with: ", ACID_COMPILED_COMPILER, "\n\n"); #endif // Modules are not self registering so we can ensure regular initialization order. if (!emptyRegister) { Files::Register(); Timers::Register(); Resources::Register(); Window::Register(); Audio::Register(); Joysticks::Register(); Keyboard::Register(); Mouse::Register(); Graphics::Register(); Input::Register(); Scenes::Register(); Gizmos::Register(); Particles::Register(); Shadows::Register(); Uis::Register(); } } Engine::~Engine() { Module::Registry().clear(); Log::CloseLog(); } int32_t Engine::Run() { while (m_running) { if (m_app) { if (!m_app->m_started) { m_app->Start(); m_app->m_started = true; } m_app->Update(); } m_elapsedRender.SetInterval(Time::Seconds(1.0f / m_fpsLimit)); // Always-Update. UpdateStage(Module::Stage::Always); if (m_elapsedUpdate.GetElapsed() != 0) { // Resets the timer. m_ups.Update(Time::Now()); // Pre-Update. UpdateStage(Module::Stage::Pre); // Update. UpdateStage(Module::Stage::Normal); // Post-Update. UpdateStage(Module::Stage::Post); // Updates the engines delta. m_deltaUpdate.Update(); } // Prioritize updates over rendering. //if (!Maths::AlmostEqual(m_elapsedUpdate.GetInterval().AsSeconds(), m_deltaUpdate.m_change.AsSeconds(), 0.8f)) { // continue; //} // Renders when needed. if (m_elapsedRender.GetElapsed() != 0) { // Resets the timer. m_fps.Update(Time::Now()); // Render UpdateStage(Module::Stage::Render); // Updates the render delta, and render time extension. m_deltaRender.Update(); } } return EXIT_SUCCESS; } void Engine::UpdateStage(Module::Stage stage) { for (auto &[stageIndex, module] : Module::Registry()) { if (stageIndex.first == stage) module->Update(); } } }
23.388889
128
0.680353
[ "render" ]
0fe5470d0803cf888055bcd535fed99777cdafb1
8,623
cpp
C++
core/image/image_blender.cpp
ppiecuch/gd_goost
93a3a28b8555310c6fbe44c009b905a57046290b
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
323
2020-07-14T09:57:03.000Z
2022-03-26T07:04:03.000Z
core/image/image_blender.cpp
ppiecuch/gd_goost
93a3a28b8555310c6fbe44c009b905a57046290b
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
57
2020-08-21T08:20:47.000Z
2022-03-31T23:46:17.000Z
core/image/image_blender.cpp
ppiecuch/gd_goost
93a3a28b8555310c6fbe44c009b905a57046290b
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
18
2020-09-07T14:53:24.000Z
2022-02-19T10:41:22.000Z
#include "image_blender.h" Color ImageBlender::calculate_factor(const Color &p_src, const Color &p_dst, BlendFactor p_factor) const { Color color_factor; switch (p_factor) { case FACTOR_ZERO: { color_factor = Color(0, 0, 0, 0); } break; case FACTOR_ONE: { color_factor = Color(1, 1, 1, 1); } break; case FACTOR_SRC_COLOR: { color_factor = p_src; } break; case FACTOR_ONE_MINUS_SRC_COLOR: { color_factor = Color(1, 1, 1, 1) - p_src; } break; case FACTOR_DST_COLOR: { color_factor = p_dst; } break; case FACTOR_ONE_MINUS_DST_COLOR: { color_factor = Color(1, 1, 1, 1) - p_dst; } break; case FACTOR_SRC_ALPHA: { color_factor = Color(p_src.a, p_src.a, p_src.a, p_src.a); } break; case FACTOR_ONE_MINUS_SRC_ALPHA: { color_factor = Color(1, 1, 1, 1) - Color(p_src.a, p_src.a, p_src.a, p_src.a); } break; case FACTOR_DST_ALPHA: { color_factor = Color(p_dst.a, p_dst.a, p_dst.a, p_dst.a); } break; case FACTOR_ONE_MINUS_DST_ALPHA: { color_factor = Color(1, 1, 1, 1) - Color(p_dst.a, p_dst.a, p_dst.a, p_dst.a); } break; case FACTOR_DST_ALPHA_TIMES_ONE_MINUS_SRC_ALPHA: { color_factor = Color(p_dst.a, p_dst.a, p_dst.a, p_dst.a) * (Color(1, 1, 1, 1) - Color(p_src.a, p_src.a, p_src.a, p_src.a)); } break; } return color_factor; } Color ImageBlender::blend_colors(const Color &p_src, const Color &p_dst) const { Color color; switch (rgb_equation) { case FUNC_ADD: { color = p_src * calculate_rgb_src_factor(p_src, p_dst) + p_dst * calculate_rgb_dst_factor(p_src, p_dst); } break; case FUNC_SUBTRACT: { color = p_src * calculate_rgb_src_factor(p_src, p_dst) - p_dst * calculate_rgb_dst_factor(p_src, p_dst); } break; case FUNC_REVERSE_SUBTRACT: { color = p_dst * calculate_rgb_dst_factor(p_src, p_dst) - p_src * calculate_rgb_src_factor(p_src, p_dst); } break; case FUNC_MAX: { color.r = MAX(p_src.r, p_dst.r); color.g = MAX(p_src.g, p_dst.g); color.b = MAX(p_src.b, p_dst.b); } break; case FUNC_MIN: { color.r = MIN(p_src.r, p_dst.r); color.g = MIN(p_src.g, p_dst.g); color.b = MIN(p_src.b, p_dst.b); } break; } switch (alpha_equation) { case FUNC_ADD: { color.a = (p_src * calculate_alpha_src_factor(p_src, p_dst)).a + (p_dst * calculate_alpha_dst_factor(p_src, p_dst)).a; } break; case FUNC_SUBTRACT: { color.a = (p_src * calculate_alpha_src_factor(p_src, p_dst)).a - (p_dst * calculate_alpha_dst_factor(p_src, p_dst)).a; } break; case FUNC_REVERSE_SUBTRACT: { color.a = (p_dst * calculate_alpha_dst_factor(p_src, p_dst)).a - (p_src * calculate_alpha_src_factor(p_src, p_dst)).a; } break; case FUNC_MAX: { color.a = MAX(p_src.a, p_dst.a); } break; case FUNC_MIN: { color.a = MIN(p_src.a, p_dst.a); } break; } return color; } void ImageBlender::blend_rect(const Ref<Image> p_src, const Rect2 &p_src_rect, Ref<Image> p_dst, const Point2 &p_dst_pos) const { ERR_FAIL_COND_MSG(p_dst.is_null(), "It's not a reference to a valid Image object."); ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object."); int dsize = p_dst->get_data().size(); int srcdsize = p_src->get_data().size(); ERR_FAIL_COND(dsize == 0); ERR_FAIL_COND(srcdsize == 0); ERR_FAIL_COND(p_dst->get_format() != p_src->get_format()); Rect2i clipped_src_rect = Rect2i(0, 0, p_src->get_width(), p_src->get_height()).clip(p_src_rect); if (p_dst_pos.x < 0) clipped_src_rect.position.x = ABS(p_dst_pos.x); if (p_dst_pos.y < 0) clipped_src_rect.position.y = ABS(p_dst_pos.y); if (clipped_src_rect.size.x <= 0 || clipped_src_rect.size.y <= 0) return; Point2 src_underscan = Point2(MIN(0, p_src_rect.position.x), MIN(0, p_src_rect.position.y)); Rect2i dest_rect = Rect2i(0, 0, p_dst->get_width(), p_dst->get_height()).clip(Rect2i(p_dst_pos - src_underscan, clipped_src_rect.size)); p_dst->lock(); Ref<Image> img = p_src; img->lock(); for (int i = 0; i < dest_rect.size.y; i++) { for (int j = 0; j < dest_rect.size.x; j++) { int src_x = clipped_src_rect.position.x + j; int src_y = clipped_src_rect.position.y + i; int dst_x = dest_rect.position.x + j; int dst_y = dest_rect.position.y + i; Color sc = img->get_pixel(src_x, src_y); Color dc = p_dst->get_pixel(dst_x, dst_y); p_dst->set_pixel(dst_x, dst_y, blend_colors(sc, dc)); } } img->unlock(); p_dst->unlock(); } void ImageBlender::stamp_rect(const Ref<Image> p_src, const Rect2 &p_src_rect, Ref<Image> p_dst, const Point2 &p_dst_init_pos, const Point2 &p_dst_end_pos, float p_spacing) const { ERR_FAIL_COND_MSG(p_dst.is_null(), "It's not a reference to a valid Image object."); ERR_FAIL_COND_MSG(p_src.is_null(), "It's not a reference to a valid Image object."); int dsize = p_dst->get_data().size(); int srcdsize = p_src->get_data().size(); ERR_FAIL_COND(dsize == 0); ERR_FAIL_COND(srcdsize == 0); ERR_FAIL_COND(p_dst->get_format() != p_src->get_format()); ERR_FAIL_COND(p_spacing <= 0); float semi_width = p_src_rect.get_size().width / 2; float semi_height = p_src_rect.get_size().height / 2; Point2 start_point(p_dst_init_pos.x - semi_width, p_dst_init_pos.y - semi_height); Point2 end_point(p_dst_end_pos.x - semi_width, p_dst_end_pos.y - semi_height); float delta_x = end_point.x - start_point.x; float delta_y = end_point.y - start_point.y; float distance = Math::sqrt(delta_x * delta_x + delta_y * delta_y); float step_x = 0.0; float step_y = 0.0; if (distance > 0.0) { float reciprocal_distance = 1.0 / distance; step_x = delta_x * reciprocal_distance; step_y = delta_y * reciprocal_distance; } float offset_x = 0.0; float offset_y = 0.0; do { blend_rect(p_src, p_src_rect, p_dst, Point2(start_point.x + offset_x, start_point.y + offset_y)); offset_x += step_x * p_spacing; offset_y += step_y * p_spacing; distance -= p_spacing; } while (distance >= p_spacing); } void ImageBlender::_bind_methods() { ClassDB::bind_method(D_METHOD("blend_rect", "src", "src_rect", "dst", "dst_pos"), &ImageBlender::blend_rect); ClassDB::bind_method(D_METHOD("stamp_rect", "src", "src_rect", "dst", "dst_init_pos", "dst_end_pos", "spacing"), &ImageBlender::stamp_rect); ClassDB::bind_method(D_METHOD("set_rgb_equation", "equation"), &ImageBlender::set_rgb_equation); ClassDB::bind_method(D_METHOD("get_rgb_equation"), &ImageBlender::get_rgb_equation); ClassDB::bind_method(D_METHOD("set_alpha_equation", "equation"), &ImageBlender::set_alpha_equation); ClassDB::bind_method(D_METHOD("get_alpha_equation"), &ImageBlender::get_alpha_equation); ClassDB::bind_method(D_METHOD("set_rgb_src_factor", "factor"), &ImageBlender::set_rgb_src_factor); ClassDB::bind_method(D_METHOD("get_rgb_src_factor"), &ImageBlender::get_rgb_src_factor); ClassDB::bind_method(D_METHOD("set_rgb_dst_factor", "factor"), &ImageBlender::set_rgb_dst_factor); ClassDB::bind_method(D_METHOD("get_rgb_dst_factor"), &ImageBlender::get_rgb_dst_factor); ClassDB::bind_method(D_METHOD("set_alpha_src_factor", "factor"), &ImageBlender::set_alpha_src_factor); ClassDB::bind_method(D_METHOD("get_alpha_src_factor"), &ImageBlender::get_alpha_src_factor); ClassDB::bind_method(D_METHOD("set_alpha_dst_factor", "factor"), &ImageBlender::set_alpha_dst_factor); ClassDB::bind_method(D_METHOD("get_alpha_dst_factor"), &ImageBlender::get_alpha_dst_factor); ADD_PROPERTY(PropertyInfo(Variant::INT, "rgb_equation"), "set_rgb_equation", "get_rgb_equation"); ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_equation"), "set_alpha_equation", "get_alpha_equation"); ADD_PROPERTY(PropertyInfo(Variant::INT, "rgb_src_factor"), "set_rgb_src_factor", "get_rgb_src_factor"); ADD_PROPERTY(PropertyInfo(Variant::INT, "rgb_dst_factor"), "set_rgb_dst_factor", "get_rgb_dst_factor"); ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_src_factor"), "set_alpha_src_factor", "get_alpha_src_factor"); ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_dst_factor"), "set_alpha_dst_factor", "get_alpha_dst_factor"); BIND_ENUM_CONSTANT(FUNC_ADD); BIND_ENUM_CONSTANT(FUNC_SUBTRACT); BIND_ENUM_CONSTANT(FUNC_REVERSE_SUBTRACT); BIND_ENUM_CONSTANT(FUNC_MIN); BIND_ENUM_CONSTANT(FUNC_MAX); BIND_ENUM_CONSTANT(FACTOR_ZERO); BIND_ENUM_CONSTANT(FACTOR_ONE); BIND_ENUM_CONSTANT(FACTOR_SRC_COLOR); BIND_ENUM_CONSTANT(FACTOR_ONE_MINUS_SRC_COLOR); BIND_ENUM_CONSTANT(FACTOR_DST_COLOR); BIND_ENUM_CONSTANT(FACTOR_ONE_MINUS_DST_COLOR); BIND_ENUM_CONSTANT(FACTOR_SRC_ALPHA); BIND_ENUM_CONSTANT(FACTOR_ONE_MINUS_SRC_ALPHA); BIND_ENUM_CONSTANT(FACTOR_DST_ALPHA); BIND_ENUM_CONSTANT(FACTOR_ONE_MINUS_DST_ALPHA); BIND_ENUM_CONSTANT(FACTOR_DST_ALPHA_TIMES_ONE_MINUS_SRC_ALPHA); }
39.0181
180
0.731416
[ "object" ]
0fe8ca7c7e6e06da3d2ee7c6d367d4813f621dc0
34,707
cpp
C++
ugene/src/corelibs/U2Formats/src/BedFormat.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2Formats/src/BedFormat.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2Formats/src/BedFormat.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BedFormat.h" #include "DocumentFormatUtils.h" #include <U2Core/AnnotationTableObject.h> #include <U2Core/GAutoDeleteList.h> #include <U2Core/GObjectReference.h> #include <U2Core/GObjectRelationRoles.h> #include <U2Core/IOAdapter.h> #include <U2Core/Log.h> #include <U2Core/L10n.h> #include <U2Core/TextUtils.h> #include <U2Core/U2SafePoints.h> #include <U2Core/U1AnnotationUtils.h> #include <U2Core/U2DbiUtils.h> #include <U2Core/U2OpStatus.h> #include <U2Core/U2SafePoints.h> #include <U2Core/U2SequenceUtils.h> #include <memory> namespace U2{ //------------------------------------------------------------------- // BEDLineValidateFlags //------------------------------------------------------------------- BEDLineValidateFlags::BEDLineValidateFlags() : incorrectNumberOfFields(false), emptyFields(false), incorrectCoordinates(false), incorrectScore(false), incorrectStrand(false), incorrectThickCoordinates(false), incorrectItemRgb(false), incorrectBlocks(false) { } FormatDetectionScore BEDLineValidateFlags::getFormatDetectionScore() { if (incorrectNumberOfFields || emptyFields || incorrectCoordinates) { return FormatDetection_NotMatched; } if (incorrectScore || incorrectStrand || incorrectBlocks) { return FormatDetection_LowSimilarity; } if (incorrectThickCoordinates || incorrectItemRgb) { return FormatDetection_HighSimilarity; } return FormatDetection_Matched; } //------------------------------------------------------------------- // BedFormat //------------------------------------------------------------------- const QString BedFormat::FORMAT_NAME = BedFormat::tr("BED"); const QString BedFormat::TRACK_NAME_QUALIFIER_NAME = "track_name"; const QString BedFormat::TRACK_DESCR_QUALIFIER_NAME = "track_description"; const QString BedFormat::CHROM_QUALIFIER_NAME = "chrom"; const QString BedFormat::ANNOT_QUALIFIER_NAME = "name"; const QString BedFormat::SCORE_QUALIFIER_NAME = "score"; const QString BedFormat::STRAND_QUALIFIER_NAME = "strand"; const QString BedFormat::THICK_START_QUALIFIER_NAME = "thick_start"; const QString BedFormat::THICK_END_QUALIFIER_NAME = "thick_end"; const QString BedFormat::ITEM_RGB_QUALIFIER_NAME = "item_rgb"; const QString BedFormat::BLOCK_COUNT_QUALIFIER_NAME = "block_count"; const QString BedFormat::BLOCK_SIZES_QULAIFIER_NAME = "block_sizes"; const QString BedFormat::BLOCK_STARTS_QUALIFIER_NAME = "block_starts"; BedFormat::BedFormat(QObject* p) : DocumentFormat(p, DocumentFormatFlag_SupportWriting, QStringList("bed")) { formatDescription = tr("The BED (Browser Extensible Data) format was developed by UCSC for displaying transcript structures in the genome browser."); supportedObjectTypes+=GObjectTypes::ANNOTATION_TABLE; } Document* BedFormat::loadDocument(IOAdapter* io, const U2DbiRef& dbiRef, const QVariantMap& fs, U2OpStatus& os) { CHECK_EXT(io != NULL && io->isOpen(), os.setError(L10N::badArgument("IO adapter")), NULL); QList<GObject*> objects; load(io, objects, os); CHECK_OP_EXT(os, qDeleteAll(objects), NULL); Document* doc = new Document(this, io->getFactory(), io->getURL(), dbiRef, objects); return doc; } void BedFormat::load(IOAdapter* io, QList<GObject*>& objects, U2OpStatus& os) { QString sequenceName; QString defaultAnnotName = "misc_feature"; QList<SharedAnnotationData> annotations = parseDocument(io, sequenceName, defaultAnnotName, os); foreach (SharedAnnotationData annotData, annotations) { QString annotTableName = sequenceName + FEATURES_TAG; AnnotationTableObject* annotTable = NULL; foreach (GObject* object, objects) { if (object->getGObjectName() == annotTableName) { annotTable = (AnnotationTableObject*) object; } } if (!annotTable) { annotTable = new AnnotationTableObject(annotTableName); objects.append(annotTable); } // Assume that the group name is the same as the annotation name QString groupName = defaultAnnotName; if (!AnnotationGroup::isValidGroupName(groupName, false)) { groupName = "Group"; // or set this name if the annotation name is not appropriate } annotTable->addAnnotation(new Annotation(annotData), groupName); } } /** Validate the values: they must be integer and within the bound of the region */ bool validateThickCoordinates(const QString& thickStartStr, const QString& thickEndStr, const U2Region& region) { if (thickStartStr.isEmpty() || thickEndStr.isEmpty()) { return false; } bool thickStartIsInt; bool thickEndIsInt; int thickStart = thickStartStr.toInt(&thickStartIsInt); int thickEnd = thickEndStr.toInt(&thickEndIsInt); if (!thickStartIsInt || !thickEndIsInt || (thickStart < region.startPos) || (thickEnd > region.endPos()) || (thickStart >= thickEnd)) { return false; } return true; } /** * Validate that the color is valid * If color is "0", then it is not set, otherwise it has format r,g,b * If color is valid, corresponding QColor is set. */ bool validateAnnotationColor(const QString& itemRgbStr, QColor& annotColor) { if ("0" == itemRgbStr) { return true; } QStringList rgbValues = itemRgbStr.split(","); if (3 != rgbValues.count()) { return false; } bool convertionStatusIsOk; int red = rgbValues[0].toInt(&convertionStatusIsOk); if (!convertionStatusIsOk) { return false; } int green = rgbValues[1].toInt(&convertionStatusIsOk); if (!convertionStatusIsOk) { return false; } int blue = rgbValues[2].toInt(&convertionStatusIsOk); if (!convertionStatusIsOk) { return false; } QColor color(red, green, blue); if (!color.isValid()) { return false; } annotColor = color; return true; } /** * Validate blocks (exons): * blockCount is the number of blocks. * blockSizes is a comma-separated list of the block sizes. The number of items must correspond to blockCount. * blockStarts is a comma-separated list of the block starts. All of the blockStart positions are calculated * relative to chromStart. The number of items must correspond to blockCount. * Note that the validated/calculated exons are not currently remembered. */ bool validateBlocks(const QString& blockCountStr, const QString& blockSizesStr, const QString& blockStartsStr, const U2Region& region) { bool blockCountIsInt; int blockCount = blockCountStr.toInt(&blockCountIsInt); if (!blockCountIsInt || (blockCount == 0)) { return false; } // Skipping empty parts because values can have e.g. the following format: "567, 488," (comma at the end) QStringList blockSizesStrValues = blockSizesStr.split(",", QString::SkipEmptyParts); if (blockSizesStrValues.count() != blockCount) { return false; } QStringList blockStartsStrValues = blockStartsStr.split(",", QString::SkipEmptyParts); if (blockStartsStrValues.count() != blockCount) { return false; } bool conversionIsOk; QVector<int> blockSizes; QVector<int> blockStarts; for (int i = 0; i < blockCount; ++i) { int size = blockSizesStrValues[i].toInt(&conversionIsOk); if (false == conversionIsOk) { return false; } int start = blockStartsStrValues[i].toInt(&conversionIsOk); if (false == conversionIsOk) { return false; } if (start > region.length) { return false; } } return true; } BedLineData BedFormat::parseAndValidateLine(const QString& line, int numOfFields, BEDLineValidateFlags& status) const { BedLineData parsedData; // All fields are separated by a single tab QStringList fields = line.split("\t"); // Verify that the line has the expected number of fields and they are not empty // Do not continue to validate the line if it is incorrect if (numOfFields != fields.count()) { status.incorrectNumberOfFields = true; return parsedData; } foreach (QString field, fields) { if (field.trimmed().isEmpty()) { status.emptyFields = true; return parsedData; } } // Coordinates // "start" can be zero, "end" is not included into the region bool startIsInt; bool endIsInt; int start = fields[BED_CHROM_START_INDEX].toInt(&startIsInt); int end = fields[BED_CHROM_END_INDEX].toInt(&endIsInt); if (!startIsInt || !endIsInt || (start < 0) || (start >= end)) { status.incorrectCoordinates = true; return parsedData; } // Fill in the data and continue validation even if a value is incorrect parsedData.seqName = fields[BED_CHROM_NAME_INDEX]; parsedData.region = U2Region(start, end - start); // Annotation name if (numOfFields > BED_ANNOT_NAME_INDEX) { parsedData.additionalFields[ANNOT_QUALIFIER_NAME] = fields[BED_ANNOT_NAME_INDEX]; } // Score if (numOfFields > BED_SCORE_INDEX) { QString scoreStr = fields[BED_SCORE_INDEX]; parsedData.additionalFields[SCORE_QUALIFIER_NAME] = scoreStr; // Validate the value: it should be an integer value between 0 and 1000 bool scoreIsOk; double score = scoreStr.toInt(&scoreIsOk); if (!scoreIsOk) { score = scoreStr.toDouble(&scoreIsOk); } if (scoreIsOk) { if (score < 0 || score > 1000) { status.incorrectScore = true; } } else { status.incorrectScore = true; } } // Strand (either '+' or '-') if (numOfFields > BED_STRAND_INDEX) { QString strandStr = fields[BED_STRAND_INDEX]; parsedData.additionalFields[STRAND_QUALIFIER_NAME] = strandStr; if ("+" != strandStr && "-" != strandStr) { status.incorrectStrand = true; } } // Thick coordinates if (numOfFields > BED_THICK_START_INDEX) { QString thickStartStr = fields[BED_THICK_START_INDEX]; QString thickEndStr; // If thick start is set, thick end must also be set if (numOfFields <= BED_THICK_END_INDEX) { status.incorrectThickCoordinates = true; } else { thickEndStr = fields[BED_THICK_END_INDEX]; } parsedData.additionalFields[THICK_START_QUALIFIER_NAME] = thickStartStr; parsedData.additionalFields[THICK_END_QUALIFIER_NAME] = thickEndStr; if (false == validateThickCoordinates(thickStartStr, thickEndStr, parsedData.region)) { status.incorrectThickCoordinates = true; } } // Annotation color if (numOfFields > BED_ITEM_RGB_INDEX) { QString itemRgbStr = fields[BED_ITEM_RGB_INDEX]; parsedData.additionalFields[ITEM_RGB_QUALIFIER_NAME] = itemRgbStr; if (false == validateAnnotationColor(itemRgbStr, parsedData.annotColor)) { status.incorrectItemRgb = true; } } // Blocks (i.e. exons) parameters if (numOfFields > BED_BLOCK_COUNT_INDEX) { QString blockCountStr = fields[BED_BLOCK_COUNT_INDEX]; QString blockSizesStr; QString blockStartsStr; // If they are present, then all three value must be present in a line if (numOfFields <= BED_BLOCK_SIZES_INDEX) { status.incorrectBlocks = true; } else { blockSizesStr = fields[BED_BLOCK_SIZES_INDEX]; if (numOfFields <= BED_BLOCK_STARTS_INDEX) { status.incorrectBlocks = true; } else { blockStartsStr = fields[BED_BLOCK_STARTS_INDEX]; } } parsedData.additionalFields[BLOCK_COUNT_QUALIFIER_NAME] = blockCountStr; parsedData.additionalFields[BLOCK_SIZES_QULAIFIER_NAME] = blockSizesStr; parsedData.additionalFields[BLOCK_STARTS_QUALIFIER_NAME] = blockStartsStr; // Validate the values if (false == validateBlocks(blockCountStr, blockSizesStr, blockStartsStr, parsedData.region)) { status.incorrectBlocks = true; } } return parsedData; } FormatCheckResult BedFormat::checkRawData(const QByteArray& rawData, const GUrl& /* = GUrl */) const { const char* data = rawData.constData(); int size = rawData.size(); bool hasBinaryData = TextUtils::contains(TextUtils::BINARY, data, size); if (hasBinaryData) { return FormatDetection_NotMatched; } QString dataStr(rawData); QStringList fileLines = dataStr.split("\n"); BEDLineValidateFlags validationStatus; int numToIterate; int HUGE_DATA = 65536; if (size < HUGE_DATA) { numToIterate = fileLines.size(); } else { // Skip the last line as it can be incomplete numToIterate = fileLines.size() - 1; } bool trackLineDetected = false; // A line that starts with "track" keyword must be present int numberOfFieldsPerLine = 0; bool firstAnnotLine = true; for (int i = 0; i < numToIterate; ++i) { if (!fileLines[i].trimmed().isEmpty()) { // e.g. the last line in file can be empty QString line = fileLines[i]; // Skip the header if (line.startsWith("browser")) { continue; } if (line.startsWith("track")) { trackLineDetected = true; continue; } // Validate other lines if (trackLineDetected) { // The number of fields per line is detected from the first line if (firstAnnotLine) { firstAnnotLine = false; numberOfFieldsPerLine = line.split("\t").count(); // There must be at least "chrom", "chromStart" and "chromEnd" fields if (numberOfFieldsPerLine < 3) { return FormatDetection_NotMatched; } } // Parse a line parseAndValidateLine(line, numberOfFieldsPerLine, validationStatus); } } } if (!trackLineDetected) { return FormatDetection_NotMatched; } else { return validationStatus.getFormatDetectionScore(); } } #define READ_BUFF_SIZE 4096 int readBedLine(QString &buffer, IOAdapter* io, gauto_array<char>& charbuff) { int len; buffer.clear(); do { len = io->readLine(charbuff.data, READ_BUFF_SIZE -1); charbuff.data[len] = '\0'; buffer.append(QString(charbuff.data)); } while (len == READ_BUFF_SIZE - 1); return buffer.length(); } QList<SharedAnnotationData> BedFormat::getAnnotData(IOAdapter *io, U2OpStatus &os) { std::auto_ptr<QObject> parent(new QObject()); BedFormat bedFormat(parent.get()); QString seqName; QString annotName = "misc_feature"; return bedFormat.parseDocument(io, seqName, annotName, os); } /** * Gets an attribute value in one of the following formats: * 1) name="value" * 2) name=value[SPACE CHARACTER] * If the value is found or the attribute is absent, returns true. * If the format of the value is incorrect, returns false. */ bool getAttributeValue(const QString& line, const QString& attrName, QString& attrValue) { QString attrStr= attrName + "="; int attrIndex = line.indexOf(attrStr); if (-1 == attrIndex) { // The attribute is not found return true; } int attrBeginIndex = attrIndex + attrStr.size(); if (line.size() == attrBeginIndex) { // Format is incorrect: attribute has name and assignment sign, but not the value return false; } bool parenthesisAreUsed; int attrEndIndex; if (line[attrBeginIndex] == '\"') { parenthesisAreUsed = true; attrEndIndex = line.indexOf("\"", attrBeginIndex + 1); } else { parenthesisAreUsed = false; attrEndIndex = line.indexOf(QRegExp("\\s"), attrIndex); if (-1 == attrEndIndex) { attrEndIndex = line.size(); } } if (-1 != attrEndIndex) { if (parenthesisAreUsed) { attrBeginIndex++; } attrValue = line.mid(attrBeginIndex, attrEndIndex - attrBeginIndex); return true; } else { // Format is incorrect: there is no matching end character for the attribute return false; } } /** Get name and description from the track line */ bool parseTrackLine(const QString& trackLine, QString& trackName, QString& trackDescr) { SAFE_POINT(trackLine.startsWith("track "), "Internal error while parsing track header line of a BED file:" " the line doesn't starts with 'track'!", false); bool attrFormatStatus = true; // Correct, by default attrFormatStatus = getAttributeValue(trackLine, "name", trackName); if (!attrFormatStatus) { return false; } attrFormatStatus = getAttributeValue(trackLine, "description", trackDescr); return attrFormatStatus; } QList<SharedAnnotationData> BedFormat::parseDocument( IOAdapter* io, QString& seqName, const QString& defaultAnnotName, U2OpStatus& os) { QList<SharedAnnotationData> result; int length; gauto_array<char> buff = new char[READ_BUFF_SIZE]; QString qstrbuf; bool fileIsValid = true; // Parse and validate the header: ignore lines with "browser" // Search the 'track' line and get parameters from it QString trackName; QString trackDescr; bool headerLine = true; while (headerLine && (length = readBedLine(qstrbuf, io, buff)) > 0) { if (qstrbuf.startsWith("browser")) { continue; } else if (qstrbuf.startsWith("track")) { if (false == parseTrackLine(qstrbuf, trackName, trackDescr)) { fileIsValid = false; ioLog.trace(tr("BED parsing error: incorrect format of the 'track' header line!")); } break; // Stop parsing the header when 'track' line has been detected } else { fileIsValid = false; ioLog.trace(tr("BED parsing error: unexpected line at the header of the file: '%1'!").arg(qstrbuf)); } } // Read other lines int lineNumber = 1; int numOfFieldsPerLine = 0; while ((length = readBedLine(qstrbuf, io, buff)) > 0) { // Parse and validate the line BEDLineValidateFlags validationStatus; if (1 == lineNumber) { numOfFieldsPerLine = qstrbuf.split("\t").count(); // "3" as there must be at least "chrom", "chromStart" and "chromEnd" fields if (numOfFieldsPerLine < 3) { os.setError(tr("BED parsing error: unexpected number of fields in the first annotations line!")); } } BedLineData bedLineData = parseAndValidateLine(qstrbuf, numOfFieldsPerLine, validationStatus); // Check that an annotation can be created if (true == validationStatus.incorrectNumberOfFields) { os.setError(tr("BED parsing error: incorrect number of fields at line %1!").arg(lineNumber)); return result; } if (true == validationStatus.emptyFields) { os.setError(tr("BED parsing error: a field at line %1 is empty!").arg(lineNumber)); return result; } if (true == validationStatus.incorrectCoordinates) { os.setError(tr("BED parsing error: incorrect coordinates at line %1!").arg(lineNumber)); return result; } // If file is invalid, but can be parsed an error is written to the log, // all details are written to the trace log. if (validationStatus.isFileInvalid()) { fileIsValid = false; } // Verify the sequence name (error doesn't occur, just warning) if (!seqName.isEmpty()) { if (bedLineData.seqName != seqName) { ioLog.trace(tr("BED parsing warning: different sequence names were detected" " in an input BED file. Sequence name '%1' is used.").arg(seqName)); } } else { seqName = bedLineData.seqName; } // Create the annotation SharedAnnotationData annotData(new AnnotationData()); annotData->name = defaultAnnotName; annotData->location->regions << bedLineData.region; // Add qualifiers foreach (QString qualifierName, bedLineData.additionalFields.keys()) { annotData->qualifiers.push_back( U2Qualifier(qualifierName, bedLineData.additionalFields.value(qualifierName))); } // Add a qualifier with the sequence name annotData->qualifiers.push_back(U2Qualifier(CHROM_QUALIFIER_NAME, bedLineData.seqName)); // Additionally, verify the strand information if (bedLineData.additionalFields.keys().contains(STRAND_QUALIFIER_NAME)) { if ("-" == bedLineData.additionalFields.value(STRAND_QUALIFIER_NAME)) { annotData->setStrand(U2Strand::Complementary); } } // Add track information to the qualifiers if (!trackName.isEmpty()) { annotData->qualifiers.push_back(U2Qualifier(TRACK_NAME_QUALIFIER_NAME, trackName)); } if (!trackDescr.isEmpty()) { annotData->qualifiers.push_back(U2Qualifier(TRACK_DESCR_QUALIFIER_NAME, trackDescr)); } // If there were some errors during parsing the output, write it to the log if (true == validationStatus.incorrectScore) { ioLog.trace(tr("BED parsing error: incorrect score value '%1'" " at line %2!").arg(bedLineData.additionalFields[SCORE_QUALIFIER_NAME]).arg(lineNumber)); } if (true == validationStatus.incorrectStrand) { ioLog.trace(tr("BED parsing error: incorrect strand value '%1'" " at line %2!").arg(bedLineData.additionalFields[STRAND_QUALIFIER_NAME]).arg(lineNumber)); } if (true == validationStatus.incorrectThickCoordinates) { ioLog.trace(tr("BED parsing error: incorrect thick coordinates at line %1!").arg(lineNumber)); } if (true == validationStatus.incorrectItemRgb) { ioLog.trace(tr("BED parsing error: incorrect itemRgb value '%1'" " at line %2!").arg(bedLineData.additionalFields[ITEM_RGB_QUALIFIER_NAME]).arg(lineNumber)); } if (true == validationStatus.incorrectBlocks) { ioLog.trace(tr("BED parsing error: incorrect value of the block parameters" " at line %1!").arg(lineNumber)); } // Append the result result.append(annotData); // Move to the next line lineNumber++; } if (false == fileIsValid) { ioLog.error("BED parsing error: one or more errors occurred while parsing the input file," " see TRACE log for details!"); } return result; } void BedFormat::storeDocument(Document* doc, IOAdapter* io, U2OpStatus& os) { SAFE_POINT(NULL != doc, "Internal error: NULL document was provided to BEDFormat::storeDocument!",); SAFE_POINT(NULL != io, "Internal error: NULL IO adapter was provided to BEDFormat::storeDocument!",); ioLog.trace(tr("Starting BED saving: '%1'").arg(doc->getURLString())); bool noErrorsDuringStoring = true; QList<GObject*> annotTables = doc->findGObjectByType(GObjectTypes::ANNOTATION_TABLE); QByteArray lineData; int fieldsNumberPerLine = 0; bool firstLine = true; foreach (GObject* annotTable, annotTables) { QList<Annotation*> annotationsList = (qobject_cast<AnnotationTableObject*>(annotTable))->getAnnotations(); foreach (const Annotation* annot, annotationsList) { QString annotName = annot->getAnnotationName(); if (annotName == U1AnnotationUtils::lowerCaseAnnotationName || annotName == U1AnnotationUtils::upperCaseAnnotationName) { continue; } QStringList lineFields; QVector<U2Region> annotRegions = annot->getRegions(); QVector<U2Qualifier> annotQualifiers = annot->getQualifiers(); QString chromName = annot->findFirstQualifierValue(CHROM_QUALIFIER_NAME); if (chromName.isEmpty()) { ioLog.trace(tr("BED saving error: can't save an annotation to a BED file" " - the annotation doesn't have the 'chrom' qualifier!")); noErrorsDuringStoring = false; continue; } else { lineFields << chromName; } foreach (const U2Region& region, annotRegions) { // chromStart and chromEnd lineFields << QString::number(region.startPos); lineFields << QString::number(region.endPos()); QString nameQualValue = annot->findFirstQualifierValue(ANNOT_QUALIFIER_NAME); QString scoreQualValue = annot->findFirstQualifierValue(SCORE_QUALIFIER_NAME); QString strandQualValue = annot->findFirstQualifierValue(STRAND_QUALIFIER_NAME); QString thickStartQualValue = annot->findFirstQualifierValue(THICK_START_QUALIFIER_NAME); QString thickEndQualValue = annot->findFirstQualifierValue(THICK_END_QUALIFIER_NAME); QString itemRgbQualValue = annot->findFirstQualifierValue(ITEM_RGB_QUALIFIER_NAME); QString blockCountQualValue = annot->findFirstQualifierValue(BLOCK_COUNT_QUALIFIER_NAME); QString blockSizesQualValue = annot->findFirstQualifierValue(BLOCK_SIZES_QULAIFIER_NAME); QString blockStartsQualValue = annot->findFirstQualifierValue(BLOCK_STARTS_QUALIFIER_NAME); // Write the header, detect the number of optional fields from the first annotation if (firstLine) { firstLine = false; // Header QString trackNameQualValue = annot->findFirstQualifierValue(TRACK_NAME_QUALIFIER_NAME); QString trackDescrQualValue = annot->findFirstQualifierValue(TRACK_DESCR_QUALIFIER_NAME); if (trackNameQualValue.isEmpty() || trackDescrQualValue.isEmpty()) { os.setError(tr("Unable to save annotations to a BED file," " qualifiers '%1' and '%2' are absent!")); return; } else { QString headerStr = QString("track name=\"%1\" description=\"%2\"\n").arg(trackNameQualValue).arg(trackDescrQualValue); QByteArray header = headerStr.toAscii(); qint64 len = io->writeBlock(header); if (len != header.size()) { os.setError(L10N::errorWritingFile(doc->getURLString())); return; } } // Number of optional fields // Note that the order of the optional fields is binding: // lower-numbered fields must always be populated // if higher-numbered fields are used if (nameQualValue.isEmpty()) { fieldsNumberPerLine = 3; // No default value, skip all optional fields } else { fieldsNumberPerLine = 4; // If score and strand qualifiers are not present, but further qualifiers are present, // the line is filled with values "0" and "+" (or "-" depending on the annotation strand) at these positions if (!scoreQualValue.isEmpty()) { fieldsNumberPerLine = 5; } if (!strandQualValue.isEmpty()) { fieldsNumberPerLine = 6; } // If thick coordinates qualifier are not present, the annotation // region's coordinates are used if (!thickStartQualValue.isEmpty()) { if (!thickEndQualValue.isEmpty()) { fieldsNumberPerLine = 8; } else { ioLog.trace(tr("BED saving error: incorrect thick coordinates" " in the first annotation!")); noErrorsDuringStoring = false; } } // Red color (255, 0, 0) is used by default for itemRgb if (!itemRgbQualValue.isEmpty()) { fieldsNumberPerLine = 9; } if (!blockCountQualValue.isEmpty()) { if (blockStartsQualValue.isEmpty() || blockSizesQualValue.isEmpty()) { ioLog.trace(tr("BED saving error: incorrect block fields" " in the first annotation!")); noErrorsDuringStoring = false; } else { fieldsNumberPerLine = 12; } } } ioLog.trace(tr("BED saving: detected %1 fields per line" " for file '%2'").arg(fieldsNumberPerLine).arg(doc->getURLString())); } // Append the required number of fields to the line if (fieldsNumberPerLine >= 4) { if (nameQualValue.isEmpty()) { ioLog.trace(tr("BED saving error: an annotation is expected to have '%1'" " qualifier, but it is absent! Skipping the annotation.").arg(ANNOT_QUALIFIER_NAME)); noErrorsDuringStoring = false; continue; } else { lineFields << nameQualValue; } } if (fieldsNumberPerLine >= 5) { if (scoreQualValue.isEmpty()) { lineFields << "0"; } else { lineFields << scoreQualValue; } } if (fieldsNumberPerLine >= 6) { if (strandQualValue.isEmpty()) { U2Strand strand = annot->getStrand(); if (strand == U2Strand::Complementary) { lineFields << "-"; } else { lineFields << "+"; } } else { lineFields << strandQualValue; } } if (fieldsNumberPerLine >= 8) { if (thickStartQualValue.isEmpty() || thickEndQualValue.isEmpty()) { // Write chromStart and chromEnd coordinates lineFields << QString::number(region.startPos); lineFields << QString::number(region.endPos()); } else { lineFields << thickStartQualValue; lineFields << thickEndQualValue; } } if (fieldsNumberPerLine >= 9) { if (itemRgbQualValue.isEmpty()) { lineFields << "255, 0, 0"; } else { lineFields << itemRgbQualValue; } } if (fieldsNumberPerLine >= 12) { if (blockCountQualValue.isEmpty() || blockStartsQualValue.isEmpty() || blockSizesQualValue.isEmpty()) { ioLog.trace(tr("BED saving error: an annotation is expected to have the block" " qualifiers! Skipping the annotation.")); noErrorsDuringStoring = false; continue; } else { lineFields << blockCountQualValue; lineFields << blockSizesQualValue; lineFields << blockStartsQualValue; } } // Write the line lineData = lineFields.join("\t").toAscii() + "\n"; qint64 len = io->writeBlock(lineData); if (len != lineData.size()) { os.setError(L10N::errorWritingFile(doc->getURLString())); return; } } } } if (!noErrorsDuringStoring) { ioLog.error(tr("BED saving error: one or more errors occurred while saving file '%1'," " see TRACE log for details!").arg(doc->getURLString())); } ioLog.trace(tr("Finished BED saving: '%1'").arg(doc->getURLString())); } } //namespace
36.572181
153
0.590861
[ "object" ]
0ff00d3e2c9724525864c880b59f36b7a9013caa
390
hpp
C++
include/guis/gui_tx_warning.hpp
WerWolv98/EdiZon
dc14c3abb05b6ea0d203b7741e1320aa4417c4a6
[ "MIT" ]
84
2018-09-16T01:12:25.000Z
2019-01-26T02:42:06.000Z
include/guis/gui_tx_warning.hpp
WerWolv98/EdiZon
dc14c3abb05b6ea0d203b7741e1320aa4417c4a6
[ "MIT" ]
13
2018-09-15T22:33:09.000Z
2019-01-04T22:11:21.000Z
include/guis/gui_tx_warning.hpp
WerWolv98/EdiZon
dc14c3abb05b6ea0d203b7741e1320aa4417c4a6
[ "MIT" ]
6
2018-10-01T05:38:49.000Z
2019-01-16T08:45:20.000Z
#pragma once #include "guis/gui.hpp" #include <vector> #include <unordered_map> #include <stdbool.h> class GuiTXWarning : public Gui { public: GuiTXWarning(); ~GuiTXWarning(); void update(); void draw(); void onInput(u32 kdown); void onTouch(touchPosition &touch); void onGesture(touchPosition startPosition, touchPosition endPosition, bool finish); };
19.5
87
0.692308
[ "vector" ]
0ff0b912569e0aabb4495539afe8a346b307ea42
10,897
cc
C++
ThirdParty/webrtc/src/net/dns/dns_config_service_unittest.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
8
2018-12-27T14:57:13.000Z
2021-04-07T07:03:15.000Z
ThirdParty/webrtc/src/net/dns/dns_config_service_unittest.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
1
2019-03-13T01:35:03.000Z
2020-10-08T04:13:04.000Z
ThirdParty/webrtc/src/net/dns/dns_config_service_unittest.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
9
2018-12-28T11:45:12.000Z
2021-05-11T02:15:31.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/dns/dns_config_service.h" #include "base/basictypes.h" #include "base/bind.h" #include "base/cancelable_callback.h" #include "base/location.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_split.h" #include "base/test/test_timeouts.h" #include "base/thread_task_runner_handle.h" #include "net/base/net_util.h" #include "net/dns/dns_protocol.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace { const NameServerClassifier::NameServersType kNone = NameServerClassifier::NAME_SERVERS_TYPE_NONE; const NameServerClassifier::NameServersType kGoogle = NameServerClassifier::NAME_SERVERS_TYPE_GOOGLE_PUBLIC_DNS; const NameServerClassifier::NameServersType kPrivate = NameServerClassifier::NAME_SERVERS_TYPE_PRIVATE; const NameServerClassifier::NameServersType kPublic = NameServerClassifier::NAME_SERVERS_TYPE_PUBLIC; const NameServerClassifier::NameServersType kMixed = NameServerClassifier::NAME_SERVERS_TYPE_MIXED; class NameServerClassifierTest : public testing::Test { protected: NameServerClassifier::NameServersType Classify( const std::string& servers_string) { std::vector<std::string> server_strings; base::SplitString(servers_string, ' ', &server_strings); std::vector<IPEndPoint> servers; for (std::vector<std::string>::const_iterator it = server_strings.begin(); it != server_strings.end(); ++it) { if (it->empty()) continue; IPAddressNumber address; bool parsed = ParseIPLiteralToNumber(*it, &address); EXPECT_TRUE(parsed); servers.push_back(IPEndPoint(address, dns_protocol::kDefaultPort)); } return classifier_.GetNameServersType(servers); } private: NameServerClassifier classifier_; }; TEST_F(NameServerClassifierTest, None) { EXPECT_EQ(kNone, Classify("")); } TEST_F(NameServerClassifierTest, Google) { EXPECT_EQ(kGoogle, Classify("8.8.8.8")); EXPECT_EQ(kGoogle, Classify("8.8.8.8 8.8.4.4")); EXPECT_EQ(kGoogle, Classify("2001:4860:4860::8888")); EXPECT_EQ(kGoogle, Classify("2001:4860:4860::8888 2001:4860:4860::8844")); EXPECT_EQ(kGoogle, Classify("2001:4860:4860::8888 8.8.8.8")); // Make sure nobody took any shortcuts on the IP matching: EXPECT_EQ(kPublic, Classify("8.8.8.4")); EXPECT_EQ(kPublic, Classify("8.8.4.8")); EXPECT_EQ(kPublic, Classify("2001:4860:4860::8884")); EXPECT_EQ(kPublic, Classify("2001:4860:4860::8848")); EXPECT_EQ(kPublic, Classify("2001:4860:4860::1:8888")); EXPECT_EQ(kPublic, Classify("2001:4860:4860:1::8888")); } TEST_F(NameServerClassifierTest, PrivateLocalhost) { EXPECT_EQ(kPrivate, Classify("127.0.0.1")); EXPECT_EQ(kPrivate, Classify("::1")); } TEST_F(NameServerClassifierTest, PrivateRfc1918) { EXPECT_EQ(kPrivate, Classify("10.0.0.0 10.255.255.255")); EXPECT_EQ(kPrivate, Classify("172.16.0.0 172.31.255.255")); EXPECT_EQ(kPrivate, Classify("192.168.0.0 192.168.255.255")); EXPECT_EQ(kPrivate, Classify("10.1.1.1 172.16.1.1 192.168.1.1")); } TEST_F(NameServerClassifierTest, PrivateIPv4LinkLocal) { EXPECT_EQ(kPrivate, Classify("169.254.0.0 169.254.255.255")); } TEST_F(NameServerClassifierTest, PrivateIPv6LinkLocal) { EXPECT_EQ(kPrivate, Classify("fe80:: fe80:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); } TEST_F(NameServerClassifierTest, Public) { EXPECT_EQ(kPublic, Classify("4.2.2.1")); EXPECT_EQ(kPublic, Classify("4.2.2.1 4.2.2.2")); } TEST_F(NameServerClassifierTest, Mixed) { EXPECT_EQ(kMixed, Classify("8.8.8.8 192.168.1.1")); EXPECT_EQ(kMixed, Classify("8.8.8.8 4.2.2.1")); EXPECT_EQ(kMixed, Classify("192.168.1.1 4.2.2.1")); EXPECT_EQ(kMixed, Classify("8.8.8.8 192.168.1.1 4.2.2.1")); } class DnsConfigServiceTest : public testing::Test { public: void OnConfigChanged(const DnsConfig& config) { last_config_ = config; if (quit_on_config_) base::MessageLoop::current()->Quit(); } protected: class TestDnsConfigService : public DnsConfigService { public: void ReadNow() override {} bool StartWatching() override { return true; } // Expose the protected methods to this test suite. void InvalidateConfig() { DnsConfigService::InvalidateConfig(); } void InvalidateHosts() { DnsConfigService::InvalidateHosts(); } void OnConfigRead(const DnsConfig& config) { DnsConfigService::OnConfigRead(config); } void OnHostsRead(const DnsHosts& hosts) { DnsConfigService::OnHostsRead(hosts); } void set_watch_failed(bool value) { DnsConfigService::set_watch_failed(value); } }; void WaitForConfig(base::TimeDelta timeout) { base::CancelableClosure closure(base::MessageLoop::QuitClosure()); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, closure.callback(), timeout); quit_on_config_ = true; base::MessageLoop::current()->Run(); quit_on_config_ = false; closure.Cancel(); } // Generate a config using the given seed.. DnsConfig MakeConfig(unsigned seed) { DnsConfig config; IPAddressNumber ip; CHECK(ParseIPLiteralToNumber("1.2.3.4", &ip)); config.nameservers.push_back(IPEndPoint(ip, seed & 0xFFFF)); EXPECT_TRUE(config.IsValid()); return config; } // Generate hosts using the given seed. DnsHosts MakeHosts(unsigned seed) { DnsHosts hosts; std::string hosts_content = "127.0.0.1 localhost"; hosts_content.append(seed, '1'); ParseHosts(hosts_content, &hosts); EXPECT_FALSE(hosts.empty()); return hosts; } void SetUp() override { quit_on_config_ = false; service_.reset(new TestDnsConfigService()); service_->WatchConfig(base::Bind(&DnsConfigServiceTest::OnConfigChanged, base::Unretained(this))); EXPECT_FALSE(last_config_.IsValid()); } DnsConfig last_config_; bool quit_on_config_; // Service under test. scoped_ptr<TestDnsConfigService> service_; }; } // namespace TEST_F(DnsConfigServiceTest, FirstConfig) { DnsConfig config = MakeConfig(1); service_->OnConfigRead(config); // No hosts yet, so no config. EXPECT_TRUE(last_config_.Equals(DnsConfig())); service_->OnHostsRead(config.hosts); EXPECT_TRUE(last_config_.Equals(config)); } TEST_F(DnsConfigServiceTest, Timeout) { DnsConfig config = MakeConfig(1); config.hosts = MakeHosts(1); ASSERT_TRUE(config.IsValid()); service_->OnConfigRead(config); service_->OnHostsRead(config.hosts); EXPECT_FALSE(last_config_.Equals(DnsConfig())); EXPECT_TRUE(last_config_.Equals(config)); service_->InvalidateConfig(); WaitForConfig(TestTimeouts::action_timeout()); EXPECT_FALSE(last_config_.Equals(config)); EXPECT_TRUE(last_config_.Equals(DnsConfig())); service_->OnConfigRead(config); EXPECT_FALSE(last_config_.Equals(DnsConfig())); EXPECT_TRUE(last_config_.Equals(config)); service_->InvalidateHosts(); WaitForConfig(TestTimeouts::action_timeout()); EXPECT_FALSE(last_config_.Equals(config)); EXPECT_TRUE(last_config_.Equals(DnsConfig())); DnsConfig bad_config = last_config_ = MakeConfig(0xBAD); service_->InvalidateConfig(); // We don't expect an update. This should time out. WaitForConfig(base::TimeDelta::FromMilliseconds(100) + TestTimeouts::tiny_timeout()); EXPECT_TRUE(last_config_.Equals(bad_config)) << "Unexpected change"; last_config_ = DnsConfig(); service_->OnConfigRead(config); service_->OnHostsRead(config.hosts); EXPECT_FALSE(last_config_.Equals(DnsConfig())); EXPECT_TRUE(last_config_.Equals(config)); } TEST_F(DnsConfigServiceTest, SameConfig) { DnsConfig config = MakeConfig(1); config.hosts = MakeHosts(1); service_->OnConfigRead(config); service_->OnHostsRead(config.hosts); EXPECT_FALSE(last_config_.Equals(DnsConfig())); EXPECT_TRUE(last_config_.Equals(config)); last_config_ = DnsConfig(); service_->OnConfigRead(config); EXPECT_TRUE(last_config_.Equals(DnsConfig())) << "Unexpected change"; service_->OnHostsRead(config.hosts); EXPECT_TRUE(last_config_.Equals(DnsConfig())) << "Unexpected change"; } TEST_F(DnsConfigServiceTest, DifferentConfig) { DnsConfig config1 = MakeConfig(1); DnsConfig config2 = MakeConfig(2); DnsConfig config3 = MakeConfig(1); config1.hosts = MakeHosts(1); config2.hosts = MakeHosts(1); config3.hosts = MakeHosts(2); ASSERT_TRUE(config1.EqualsIgnoreHosts(config3)); ASSERT_FALSE(config1.Equals(config2)); ASSERT_FALSE(config1.Equals(config3)); ASSERT_FALSE(config2.Equals(config3)); service_->OnConfigRead(config1); service_->OnHostsRead(config1.hosts); EXPECT_FALSE(last_config_.Equals(DnsConfig())); EXPECT_TRUE(last_config_.Equals(config1)); // It doesn't matter for this tests, but increases coverage. service_->InvalidateConfig(); service_->InvalidateHosts(); service_->OnConfigRead(config2); EXPECT_TRUE(last_config_.Equals(config1)) << "Unexpected change"; service_->OnHostsRead(config2.hosts); // Not an actual change. EXPECT_FALSE(last_config_.Equals(config1)); EXPECT_TRUE(last_config_.Equals(config2)); service_->OnConfigRead(config3); EXPECT_TRUE(last_config_.EqualsIgnoreHosts(config3)); service_->OnHostsRead(config3.hosts); EXPECT_FALSE(last_config_.Equals(config2)); EXPECT_TRUE(last_config_.Equals(config3)); } TEST_F(DnsConfigServiceTest, WatchFailure) { DnsConfig config1 = MakeConfig(1); DnsConfig config2 = MakeConfig(2); config1.hosts = MakeHosts(1); config2.hosts = MakeHosts(2); service_->OnConfigRead(config1); service_->OnHostsRead(config1.hosts); EXPECT_FALSE(last_config_.Equals(DnsConfig())); EXPECT_TRUE(last_config_.Equals(config1)); // Simulate watch failure. service_->set_watch_failed(true); service_->InvalidateConfig(); WaitForConfig(TestTimeouts::action_timeout()); EXPECT_FALSE(last_config_.Equals(config1)); EXPECT_TRUE(last_config_.Equals(DnsConfig())); DnsConfig bad_config = last_config_ = MakeConfig(0xBAD); // Actual change in config, so expect an update, but it should be empty. service_->OnConfigRead(config1); EXPECT_FALSE(last_config_.Equals(bad_config)); EXPECT_TRUE(last_config_.Equals(DnsConfig())); last_config_ = bad_config; // Actual change in config, so expect an update, but it should be empty. service_->InvalidateConfig(); service_->OnConfigRead(config2); EXPECT_FALSE(last_config_.Equals(bad_config)); EXPECT_TRUE(last_config_.Equals(DnsConfig())); last_config_ = bad_config; // No change, so no update. service_->InvalidateConfig(); service_->OnConfigRead(config2); EXPECT_TRUE(last_config_.Equals(bad_config)); } } // namespace net
32.05
78
0.732679
[ "vector" ]
0ff390e0ee04abdf75cd409cc5a133a73e52ea67
9,151
cpp
C++
exa/ScalarField.cpp
owl-project/owlExaBrick
6ea0af22f5bff1ee0620eadedf2a343ca9dc770e
[ "Apache-2.0" ]
2
2020-10-30T16:53:54.000Z
2021-04-27T15:50:45.000Z
exa/ScalarField.cpp
owl-project/owlExaBrick
6ea0af22f5bff1ee0620eadedf2a343ca9dc770e
[ "Apache-2.0" ]
null
null
null
exa/ScalarField.cpp
owl-project/owlExaBrick
6ea0af22f5bff1ee0620eadedf2a343ca9dc770e
[ "Apache-2.0" ]
null
null
null
// ======================================================================== // // Copyright 2019-2020 Ingo Wald // // // // 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 <stack> #include "ScalarField.h" namespace exa { ScalarField::SP ScalarField::load(const std::string &fieldName, const std::string &fileName) { std::ifstream scalarFile(fileName); if (!scalarFile.good()) throw std::runtime_error("error in opening scalar file " +fileName); scalarFile.seekg(0,scalarFile.end); size_t numElements = scalarFile.tellg(); scalarFile.seekg(0,scalarFile.beg); ScalarField::SP sf = std::make_shared<ScalarField>(); sf->name = fieldName; sf->value.resize(numElements); scalarFile.read((char *)sf->value.data(),sizeof(float)*numElements); #if 1 std::mutex mutex; parallel_for_blocked(0ull,sf->value.size(),1024*1024,[&](size_t begin, size_t end){ interval<float> blockRange; for (size_t i=begin;i<end;i++) { float f = sf->value[i]; blockRange.extend(f); } std::lock_guard<std::mutex> lock(mutex); sf->valueRange.extend(blockRange.lower); sf->valueRange.extend(blockRange.upper); }); #else for (auto f : sf->value) sf->valueRange.extend(f); #endif std::cout << "#exa: done loading scalar field '" << fieldName << "' from " << fileName << std::endl; std::cout << " (value range " << sf->valueRange << ")" << std::endl; return sf; } ScalarField::SP ScalarField::loadAndComputeMagnitude(const std::string &fieldName, const std::string &fnx, const std::string &fny, const std::string &fnz ) { ScalarField::SP in_x = ScalarField::load(fieldName+".x",fnx); ScalarField::SP in_y = ScalarField::load(fieldName+".y",fny); ScalarField::SP in_z = ScalarField::load(fieldName+".z",fnz); assert(in_x->value.size() == in_y->value.size()); assert(in_x->value.size() == in_z->value.size()); size_t numElements = in_x->value.size(); ScalarField::SP sf = std::make_shared<ScalarField>(); sf->name = fieldName; sf->value.resize(numElements); #if 1 std::mutex mutex; parallel_for_blocked(0ull,sf->value.size(),1024*1024,[&](size_t begin, size_t end){ interval<float> blockRange; for (size_t i=begin;i<end;i++) { float f = length(vec3f(in_x->value[i],in_y->value[i],in_z->value[i])); sf->value[i] = f; blockRange.extend(sf->value[i]); } std::lock_guard<std::mutex> lock(mutex); sf->valueRange.extend(blockRange.lower); sf->valueRange.extend(blockRange.upper); }); #else for (int i=0;i<numElements;i++) { float f = length(vec3f(in_x->value[i],in_y->value[i],in_z->value[i])); sf->value[i] = f; sf->valueRange.extend(f); } #endif std::cout << "#exa: done computing magnitude of vector field '" << fieldName << std::endl; std::cout << " (value range " << sf->valueRange << ")" << std::endl; return sf; } ScalarField::SP ScalarField::createFromExpression(const std::string &fieldName, const std::vector<ScalarField::SP> &fields, const std::vector<std::string> &tokens ) { auto trim = [](const std::string &in, char c) { std::string s = in; s.erase(s.begin(), std::find_if(s.begin(), s.end(), [c](unsigned char ch) { return ch != c; })); return s; }; auto rtrim = [](const std::string &in, char c) { std::string s = in; s.erase(std::find_if(s.rbegin(), s.rend(), [c](unsigned char ch) { return ch != c; }).base(), s.end()); return s; }; std::vector<std::string> trimmed(tokens.size()); for (size_t i=0; i<tokens.size(); ++i) { std::string token = tokens[i]; token = trim(token,'\"'); token = rtrim(token,'\"'); token = trim(token,' '); // only ' ' whitespace allowed! token = rtrim(token,' '); // only ' ' whitespace allowed! trimmed[i] = token; } size_t numElements = fields[0]->value.size(); ScalarField::SP sf = std::make_shared<ScalarField>(); sf->name = fieldName; sf->value.resize(numElements); std::mutex mutex; parallel_for_blocked(0ull,sf->value.size(),1024*1024,[&](size_t begin, size_t end){ interval<float> blockRange; for (size_t i=begin;i<end;i++) { float f = 0.f; // Postfix eval std::stack<float> st; for (size_t ti=0; ti<trimmed.size(); ++ti) { std::string token = trimmed[ti];//std::cout << token << '\n'; if (token.empty()) { std::cerr << "Empty token\n"; break; } if (token[0] == '%') { // Placeholder (%0,%1,%2,...) std::string t = trim(token,'%'); unsigned field = std::stoi(t); if (field >= fields.size()) { std::cerr << "Invalid placeholder token: " << token << '\n'; break; } st.push(fields[field]->value[i]); } else if (token == "select") { // ternary token float op2 = st.top(); st.pop(); float op1 = st.top(); st.pop(); int mask = st.top(); st.pop(); st.push(mask ? op1 : op2); } else if (token == "+" || token == "-" || token == "*" || token == "/" || token == "**" || token == "==" || token == "!=" || token == "<" || token == ">" || token == "<=" || token == ">=") { // binary tokens if (st.size() < 2) { std::cerr << "Insufficient operands for token: " << token << '\n'; break; } float op2 = st.top(); st.pop(); float op1 = st.top(); st.pop(); if (token == "+") st.push(op1+op2); else if (token == "-") st.push(op1-op2); else if (token == "*") st.push(op1*op2); else if (token == "/") st.push(op1/op2); else if (token == "**") st.push(powf(op1,op2)); else if (token == "==") st.push(op1==op2); else if (token == "!=") st.push(op1!=op2); else if (token == "<") st.push(op1<op2); else if (token == ">") st.push(op1>op2); else if (token == "<=") st.push(op1<=op2); else if (token == ">=") st.push(op1>=op2); } else if (token == "log" || token == "abs" || token == "sqrt") { if (st.size() < 1) { std::cerr << "Insufficient operands for token: " << token << '\n'; break; } float op = st.top(); st.pop(); if (token == "log") st.push(log(op)); else if (token == "abs") st.push(fabsf(op)); else if (token == "sqrt") st.push(sqrtf(op)); } else { // constant try { st.push((float)stod(token)); } catch (...) { std::cerr << "Not a floating point token: " << token << '\n'; } } } if (st.size() != 1) { std::cerr << "Invalid expression\n"; return; } f = st.top(); st.pop(); sf->value[i] = f; blockRange.extend(sf->value[i]); } std::lock_guard<std::mutex> lock(mutex); sf->valueRange.extend(blockRange.lower); sf->valueRange.extend(blockRange.upper); }); std::cout << "#exa: done computing postfix expression '" << fieldName << '\'' << std::endl; std::cout << " (value range " << sf->valueRange << ")" << std::endl; return sf; } } // ::exa
39.786957
139
0.469894
[ "vector" ]
0ff4aeeb2fa9f70a1581841b045786c3d1fd44f1
3,280
cc
C++
components/bookmarks/browser/bookmark_storage.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/bookmarks/browser/bookmark_storage.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/bookmarks/browser/bookmark_storage.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 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 "components/bookmarks/browser/bookmark_storage.h" #include <stddef.h> #include <algorithm> #include <unordered_map> #include <utility> #include "base/bind.h" #include "base/compiler_specific.h" #include "base/files/file_util.h" #include "base/guid.h" #include "base/json/json_file_value_serializer.h" #include "base/json/json_string_value_serializer.h" #include "base/numerics/safe_conversions.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "components/bookmarks/browser/bookmark_codec.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_node.h" #include "components/bookmarks/common/bookmark_constants.h" namespace bookmarks { namespace { // Extension used for backup files (copy of main file created during startup). const base::FilePath::CharType kBackupExtension[] = FILE_PATH_LITERAL("bak"); void BackupCallback(const base::FilePath& path) { base::FilePath backup_path = path.ReplaceExtension(kBackupExtension); base::CopyFile(path, backup_path); } } // namespace // static constexpr base::TimeDelta BookmarkStorage::kSaveDelay; BookmarkStorage::BookmarkStorage(BookmarkModel* model, const base::FilePath& profile_path) : model_(model), backend_task_runner_(base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN})), writer_(profile_path.Append(kBookmarksFileName), backend_task_runner_, kSaveDelay, "BookmarkStorage") {} BookmarkStorage::~BookmarkStorage() { if (writer_.HasPendingWrite()) writer_.DoScheduledWrite(); } void BookmarkStorage::ScheduleSave() { // If this is the first scheduled save, create a backup before overwriting the // JSON file. if (!backup_triggered_) { backup_triggered_ = true; backend_task_runner_->PostTask( FROM_HERE, base::BindOnce(&BackupCallback, writer_.path())); } writer_.ScheduleWriteWithBackgroundDataSerializer(this); } void BookmarkStorage::BookmarkModelDeleted() { // We need to save now as otherwise by the time SerializeData() is invoked // the model is gone. if (writer_.HasPendingWrite()) { writer_.DoScheduledWrite(); DCHECK(!writer_.HasPendingWrite()); } model_ = nullptr; } base::ImportantFileWriter::BackgroundDataProducerCallback BookmarkStorage::GetSerializedDataProducerForBackgroundSequence() { BookmarkCodec codec; base::Value value( codec.Encode(model_, model_->client()->EncodeBookmarkSyncMetadata())); return base::BindOnce( [](base::Value value, std::string* output) { // This runs on the background sequence. JSONStringValueSerializer serializer(output); serializer.set_pretty_print(true); return serializer.Serialize(value); }, std::move(value)); } bool BookmarkStorage::HasScheduledSaveForTesting() const { return writer_.HasPendingWrite(); } } // namespace bookmarks
31.538462
80
0.735061
[ "model" ]
0ffc1ae97a55c1dfd7f7683c0ed5bdd1e7fc27ca
10,922
cxx
C++
Libs/MRML/Widgets/qMRMLVolumeWidget.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Libs/MRML/Widgets/qMRMLVolumeWidget.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Libs/MRML/Widgets/qMRMLVolumeWidget.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
/*============================================================================== Program: 3D Slicer Copyright (c) Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Julien Finet, Kitware Inc. and was partially funded by NIH grant 3P41RR013218-12S1 ==============================================================================*/ // Qt includes #include <QVBoxLayout> // CTK includes #include <ctkDoubleSpinBox.h> #include <ctkRangeWidget.h> #include <ctkPopupWidget.h> #include <ctkUtils.h> // qMRML includes #include "qMRMLVolumeWidget.h" #include "qMRMLVolumeWidget_p.h" // MRML includes #include "vtkMRMLScalarVolumeNode.h" #include "vtkMRMLScalarVolumeDisplayNode.h" // VTK includes #include <vtkImageData.h> // -------------------------------------------------------------------------- qMRMLVolumeWidgetPrivate ::qMRMLVolumeWidgetPrivate(qMRMLVolumeWidget& object) : q_ptr(&object) { this->VolumeNode = nullptr; this->VolumeDisplayNode = nullptr; this->PopupWidget = nullptr; this->RangeWidget = nullptr; this->DisplayScalarRange[0] = 0; this->DisplayScalarRange[1] = 0; } // -------------------------------------------------------------------------- qMRMLVolumeWidgetPrivate::~qMRMLVolumeWidgetPrivate() { delete this->PopupWidget; this->PopupWidget = nullptr; this->RangeWidget = nullptr; } // -------------------------------------------------------------------------- void qMRMLVolumeWidgetPrivate::init() { Q_Q(qMRMLVolumeWidget); this->setParent(q); // disable as there is not MRML Node associated with the widget q->setEnabled(this->VolumeDisplayNode != nullptr); // we can't use the flag Qt::Popup as it automatically closes when there is // a click outside of the rangewidget this->PopupWidget = new ctkPopupWidget(q); this->PopupWidget->setObjectName("RangeWidgetPopup"); QPalette popupPalette = q->palette(); QColor windowColor = popupPalette.color(QPalette::Window); windowColor.setAlpha(200); QColor darkColor = popupPalette.color(QPalette::Dark); darkColor.setAlpha(200); /* QLinearGradient gradient(QPointF(0.,0.),QPointF(0.,0.5)); gradient.setCoordinateMode(QGradient::StretchToDeviceMode); gradient.setColorAt(0, windowColor); gradient.setColorAt(1, darkColor); popupPalette.setBrush(QPalette::Window, gradient); */ popupPalette.setColor(QPalette::Window, darkColor); this->PopupWidget->setPalette(popupPalette); this->PopupWidget->setAttribute(Qt::WA_TranslucentBackground, true); this->PopupWidget->setAutoShow(false); this->PopupWidget->setAutoHide(true); //this->PopupWidget->setBaseWidget(q); this->RangeWidget = new ctkRangeWidget; this->RangeWidget->minimumSpinBox()->setDecimalsOption( ctkDoubleSpinBox::DecimalsByKey|ctkDoubleSpinBox::DecimalsByShortcuts); this->RangeWidget->maximumSpinBox()->setDecimalsOption( ctkDoubleSpinBox::DecimalsByKey|ctkDoubleSpinBox::DecimalsByShortcuts); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(this->RangeWidget); this->PopupWidget->setLayout(layout); QMargins margins = layout->contentsMargins(); margins.setTop(0); layout->setContentsMargins(margins); this->RangeWidget->setSpinBoxAlignment(Qt::AlignBottom); this->RangeWidget->setRange(-1000000., 1000000.); QObject::connect(this->RangeWidget, SIGNAL(valuesChanged(double,double)), this, SLOT(setRange(double,double))); this->RangeWidget->setToolTip( qMRMLVolumeWidget::tr("Set the range boundaries to control large numbers or allow fine tuning")); this->PopupWidget->hide(); this->RangeWidget->hide(); } //------------------------------------------------------------------------------ void qMRMLVolumeWidgetPrivate ::updateRangeForVolumeDisplayNode(vtkMRMLScalarVolumeDisplayNode* dNode) { double range[2]; this->scalarRange(dNode, range); this->DisplayScalarRange[0] = range[0]; this->DisplayScalarRange[1] = range[1]; // we don't want RangeWidget to fire any signal because we don't have // a display node correctly set here (it's done ) this->RangeWidget->blockSignals(true); double interval = range[1] - range[0]; Q_ASSERT(interval >= 0.); double min, max; if (interval <= 10.) { min = qMin(-10., range[0] - 2.*interval); max = qMax(10., range[1] + 2.*interval); } else { min = qMin(-1200., range[0] - 2.*interval); max = qMax(900., range[1] + 2.*interval); } this->RangeWidget->setRange(min, max); this->RangeWidget->blockSignals(false); if (interval < 10.) { //give us some space range[0] = range[0] - interval*0.1; range[1] = range[1] + interval*0.1; } else { //give us some space range[0] = qMin(-600., range[0] - interval*0.1); range[1] = qMax(600., range[1] + interval*0.1); } bool blocked = this->blockSignals(true); this->setRange(range[0], range[1]); this->blockSignals(blocked); } // -------------------------------------------------------------------------- bool qMRMLVolumeWidgetPrivate::blockSignals(bool block) { return this->RangeWidget->blockSignals(block); } // -------------------------------------------------------------------------- void qMRMLVolumeWidgetPrivate ::scalarRange(vtkMRMLScalarVolumeDisplayNode* dNode, double range[2]) { // vtkMRMLScalarVolumeDisplayNode::GetDisplayScalarRange() can be a bit // slow if there is no input as it searches the scene for the associated // volume node. // Here we already know the volumenode so we can manually use it to // retrieve the scalar range. if (dNode && dNode->GetInputImageData()) { dNode->GetDisplayScalarRange(range); } else if (this->VolumeNode->GetImageData()) { this->VolumeNode->GetImageData()->GetScalarRange(range); } else { range[0] = 0.; range[1] = 0.; } } // -------------------------------------------------------------------------- void qMRMLVolumeWidgetPrivate::updateSingleStep(double min, double max) { double interval = max - min; int order = interval != 0. ? ctk::orderOfMagnitude(interval) : -2; int ratio = 2; double singleStep = pow(10., order - ratio); int decimals = qMax(0, -order + ratio); this->setDecimals(decimals); this->setSingleStep(singleStep); // The RangeWidget doesn't have to be as precise as the sliders/spinboxes. ratio = 1; singleStep = pow(10., order - ratio); decimals = qMax(0, -order + ratio); this->RangeWidget->setDecimals(decimals); this->RangeWidget->setSingleStep(singleStep); } // -------------------------------------------------------------------------- void qMRMLVolumeWidgetPrivate::setDecimals(int decimals) { Q_UNUSED(decimals); } // -------------------------------------------------------------------------- void qMRMLVolumeWidgetPrivate::setSingleStep(double singleStep) { Q_UNUSED(singleStep); } // -------------------------------------------------------------------------- void qMRMLVolumeWidgetPrivate::setRange(double min, double max) { this->updateSingleStep(min, max); this->RangeWidget->setValues(min, max); } // -------------------------------------------------------------------------- qMRMLVolumeWidget::qMRMLVolumeWidget(QWidget* parentWidget) : Superclass(parentWidget) , d_ptr(new qMRMLVolumeWidgetPrivate(*this)) { Q_D(qMRMLVolumeWidget); d->init(); } // -------------------------------------------------------------------------- qMRMLVolumeWidget ::qMRMLVolumeWidget(qMRMLVolumeWidgetPrivate* ptr, QWidget* parentWidget) : Superclass(parentWidget) , d_ptr(ptr) { } // -------------------------------------------------------------------------- qMRMLVolumeWidget::~qMRMLVolumeWidget() = default; // -------------------------------------------------------------------------- void qMRMLVolumeWidget ::setMRMLVolumeDisplayNode(vtkMRMLScalarVolumeDisplayNode* node) { Q_D(qMRMLVolumeWidget); if (d->VolumeDisplayNode == node) { return; } // each time the node is modified, the qt widgets are updated this->qvtkReconnect(d->VolumeDisplayNode, node, vtkCommand::ModifiedEvent, this, SLOT(updateWidgetFromMRMLDisplayNode())); d->VolumeDisplayNode = node; this->updateWidgetFromMRMLDisplayNode(); } // -------------------------------------------------------------------------- void qMRMLVolumeWidget::setMRMLVolumeNode(vtkMRMLNode* node) { this->setMRMLVolumeNode(vtkMRMLScalarVolumeNode::SafeDownCast(node)); } // -------------------------------------------------------------------------- void qMRMLVolumeWidget::setMRMLVolumeNode(vtkMRMLScalarVolumeNode* volumeNode) { Q_D(qMRMLVolumeWidget); if (volumeNode == d->VolumeNode) { return; } this->qvtkReconnect(d->VolumeNode, volumeNode, vtkCommand::ModifiedEvent, this, SLOT(updateWidgetFromMRMLVolumeNode())); d->VolumeNode = volumeNode; this->updateWidgetFromMRMLVolumeNode(); } // -------------------------------------------------------------------------- vtkMRMLScalarVolumeNode* qMRMLVolumeWidget::mrmlVolumeNode()const { Q_D(const qMRMLVolumeWidget); return d->VolumeNode; } // -------------------------------------------------------------------------- vtkMRMLScalarVolumeDisplayNode* qMRMLVolumeWidget::mrmlDisplayNode()const { Q_D(const qMRMLVolumeWidget); return d->VolumeDisplayNode; } // -------------------------------------------------------------------------- void qMRMLVolumeWidget::updateWidgetFromMRMLVolumeNode() { Q_D(qMRMLVolumeWidget); this->setEnabled(d->VolumeDisplayNode != nullptr && d->VolumeNode != nullptr); vtkMRMLScalarVolumeDisplayNode* newVolumeDisplayNode = d->VolumeNode ? vtkMRMLScalarVolumeDisplayNode::SafeDownCast( d->VolumeNode->GetVolumeDisplayNode()) : nullptr; /* if (d->VolumeNode && d->VolumeNode->GetImageData()) { this->updateRangeForVolumeDisplayNode(newVolumeDisplayNode); } */ this->setMRMLVolumeDisplayNode( newVolumeDisplayNode ); } // -------------------------------------------------------------------------- void qMRMLVolumeWidget::updateWidgetFromMRMLDisplayNode() { Q_D(qMRMLVolumeWidget); this->setEnabled(d->VolumeDisplayNode != nullptr && d->VolumeNode != nullptr); if (!d->VolumeDisplayNode) { return; } double range[2]; d->scalarRange(d->VolumeDisplayNode, range); if (range[0] != d->DisplayScalarRange[0] || range[1] != d->DisplayScalarRange[1]) { d->updateRangeForVolumeDisplayNode(d->VolumeDisplayNode); } }
31.116809
105
0.607581
[ "object", "3d" ]
0ffd0f7a16fff87727fcee16d023d924204fe66c
15,817
hpp
C++
bftengine/src/bcstatetransfer/RangeValidationTree.hpp
evdzhurov/concord-bft
2e4fdabe0228b51d4d43398158e97d4e36ff974a
[ "Apache-2.0" ]
null
null
null
bftengine/src/bcstatetransfer/RangeValidationTree.hpp
evdzhurov/concord-bft
2e4fdabe0228b51d4d43398158e97d4e36ff974a
[ "Apache-2.0" ]
null
null
null
bftengine/src/bcstatetransfer/RangeValidationTree.hpp
evdzhurov/concord-bft
2e4fdabe0228b51d4d43398158e97d4e36ff974a
[ "Apache-2.0" ]
null
null
null
// Concord // // Copyright (c) 2022 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the "License"). // You may not use this product except in compliance with the Apache 2.0 // License. // // This product may include a number of subcomponents with separate copyright // notices and license terms. Your use of these subcomponents is subject to the // terms and conditions of the subcomponent's license, as noted in the // LICENSE file. #pragma once #include <iostream> #include <vector> #include <memory> #include <unordered_map> #include <string> #include <cmath> #include <limits> #include <unordered_set> #include <cryptopp/integer.h> #include "Digest.hpp" #include "Serializable.h" #include "Logger.hpp" namespace bftEngine::bcst::impl { using RVBGroupId = uint64_t; using RVBId = uint64_t; using RVBIndex = uint64_t; // A Range Validation Tree (RVT) // // RVT is used to confirm that blocks collected from any single source (part of consensus network) during State Transfer // are valid and true. This is done by validating digest of certain blocks at frequent interval (RVB) against the tree. // RVT would be updated during checkpointing and also in the context of pruning. New nodes would be added to RVT during // checkpointing where as existing nodes would be deleted when pruning on old blocks begins. // Comment: this data structure is easy to be used to validate any type of data, not only block digests. // // Insertion and removal of nodes: // * Insertion: nodes are inserted to the right, with the next expected RVB ID by calling addRightNode. // * Removal: nodes are removed from the left, with the next expected RVB ID by calling removeLeftnode. // // Terms used throughout code - // 1. RVT_K = Maximum number of children any node can have // 2. Fetch range = Not all blocks will be validated. Only max block from given fetch range will be validated. // 3. RVB Id = Any block id in multiple of fetch range size // 4. RVB Index = RVBId / fetch range size (RVB Index must divide to a positive integer to be valid) // 5. RVB GroupIndex (RVBGroupId) = Minimum of RVBIndex of all childrens. // // Things to remember - // 1. Tree does not store RVB nodes. // 2. Only blocks at specific interval are validated to improve replica recovery time. // 3. Each node in tree is represented having type as NodeInfo. // 4. NodeVal is stored in form of CryptoPP::Integer. // // Implemention notes - // 1. APIs do not throw exception // 2. Thread safety is delegated to caller (e.g. RVBManager) // 3. Bad inputs values are asserted // class RangeValidationTree { // The next friend declerations are used strictly for testing friend class BcStTestDelegator; using NodeVal_t = CryptoPP::Integer; public: /////////////////////////// API ///////////////////////////////////// RangeValidationTree(const logging::Logger& logger, uint32_t RVT_K, uint32_t fetch_range_size, size_t value_size = 32); ~RangeValidationTree() = default; RangeValidationTree(const RangeValidationTree&) = delete; RangeValidationTree& operator=(RangeValidationTree&) = delete; // Add a node to the right of the tree. Expected id: (getMaxRvbId() + 1) * fetch_range_size // If RVB is invalid, we terminate (internal bug). void addRightNode(const RVBId id, const char* data, size_t data_size); // Remove a node from the left of the tree. Expected id: (getMinRvbId() - 1) * fetch_range_size // If RVB is invalid, we terminate (internal bug). void removeLeftNode(const RVBId id, const char* data, size_t data_size); // Return complete tree along with metadata in serialized format // In case of failure can assert std::ostringstream getSerializedRvbData() const; // Initialize metadata & build tree by deserializing input stream // If function fails, tree reset to null and returns false. // In case of failure can assert bool setSerializedRvbData(std::istringstream& iss); // Returns RVB group ids for the range [start_block_id, end_block_id] in ascending order. // In case of failure, returns an empty vector. // The blocks start/end should be RVB Block Ids. // if must_be_in_tree is true, every RVBGroupId returned in the vector is expected to be part of the tree, else all // ids are not checked against the tree. std::vector<RVBGroupId> getRvbGroupIds(RVBId start_rvb_id, RVBId end_rvb_id, bool must_be_in_tree) const; // Returns all actual childs in ascending order. In case of failure, returns empty vector. std::vector<RVBId> getRvbIds(RVBGroupId id) const; // Returns value of direct parent of RVB. In case of failure, returns empty string with size zero. std::string getDirectParentValueStr(RVBId rvb_id) const; // Return the min RVB ID in the tree. Return 0 if tree is empty. RVBId getMinRvbId() const; // Return the max RVB ID in the tree. Return 0 if tree is empty. RVBId getMaxRvbId() const; // Returns true if tree is empty. bool empty() const { return (id_to_node_.size() == 0) ? true : false; } // Returns current state of the tree. In practice: a hexadecimal format string represting the root current value. const std::string getRootCurrentValueStr() const { return root_ ? root_->current_value_.toString() : ""; } // Clear the tree void clear() noexcept; enum class LogPrintVerbosity { DETAILED, SUMMARY }; // Log tree only if total elements are less than 10K. In case of failure can assert. // SUMMARY - prints basic structure and node ids only void printToLog(LogPrintVerbosity verbosity, std::string&& user_label = "") const noexcept; // change to 3 levels // Validate structure and values inside tree. In case of failure can assert. bool validate() const noexcept; size_t totalNodes() const { return id_to_node_.size(); } size_t totalLevels() const { return root_ ? root_->info_.level() : 0; } public: struct NodeVal { static NodeVal_t kNodeValueModulo_; static NodeVal_t calcModulo(size_t val_size); NodeVal(const std::shared_ptr<char[]>&& val, size_t size); NodeVal(const char* val_ptr, size_t size); NodeVal(const NodeVal_t* val); NodeVal(const NodeVal_t& val); NodeVal(const NodeVal_t&& val); NodeVal(); NodeVal& operator+=(const NodeVal& other); NodeVal& operator-=(const NodeVal& other); bool operator!=(const NodeVal& other); bool operator==(const NodeVal& other); const NodeVal_t& getVal() const { return val_; } std::string toString() const noexcept; std::string getDecoded() const noexcept; size_t getSize() const { return val_.MinEncodedSize(); } static constexpr size_t kDigestContextOutputSize = DIGEST_SIZE; static constexpr std::array<char, kDigestContextOutputSize> initialValueZeroData{}; NodeVal_t val_; }; struct NodeInfo { NodeInfo(uint64_t node_id) : id_data_(node_id) {} NodeInfo(uint8_t l, uint64_t index) : id_data_(l, index) {} NodeInfo() = delete; bool operator<(NodeInfo& other) const noexcept { return ((level() <= other.level()) || (rvb_index() < other.rvb_index())) ? true : false; } bool operator!=(NodeInfo& other) const noexcept { return ((level() != other.level()) || (rvb_index() != other.rvb_index())) ? true : false; } std::string toString() const noexcept; static constexpr size_t kNIDBitsPerLevel = 8; static constexpr size_t kNIDBitsPerRVBIndex = ((sizeof(uint64_t) * 8) - kNIDBitsPerLevel); // 56 static constexpr size_t kMaxLevels = ((0x1 << kNIDBitsPerLevel) - 1); // 0xFF static constexpr uint64_t kLevelMask = (kMaxLevels) << kNIDBitsPerRVBIndex; // 0xFF000000 00000000 static constexpr uint64_t kRvbIndexMask = std::numeric_limits<uint64_t>::max() & (~kLevelMask); // 0x00FFFFFF FFFFFFFF union IdData { friend NodeInfo; public: IdData() = default; IdData(uint64_t node_id) : id(node_id){}; IdData(uint8_t l, uint64_t index) { bits.rvb_index = index; bits.level = l; } private: struct IdBits { uint64_t rvb_index : kNIDBitsPerRVBIndex; uint64_t level : kNIDBitsPerLevel; } bits; const uint64_t id{}; } id_data_; public: uint64_t rvb_index() const { return id_data_.bits.rvb_index; }; uint64_t level() const { return id_data_.bits.level; }; uint64_t id() const { return id_data_.id; }; static uint64_t rvb_index(uint64_t id) { return IdData(id).bits.rvb_index; } static uint8_t level(uint64_t id) { return IdData(id).bits.level; } static uint64_t id(uint8_t level, uint64_t rvb_index); // The min/max possible rvt_index of a parent childs, given one of the potential childs rvb index and level (parents // level is level+1) static inline uint64_t parentRvbIndexFromChild(uint64_t child_rvb_index, uint8_t child_level); // For a given child rvb index and child level, calculate the min rvb index of all potential siblings // All siblings must have the same parents. Not all siblings must currently be childs of that parent. static inline uint64_t minPossibleSiblingRvbIndex(uint64_t child_rvb_index, uint8_t child_level); static inline uint64_t maxPossibleSiblingRvbIndex(uint64_t child_rvb_index, uint8_t child_level); // for a give RVB index, return the next/prev one depends on level // rvb_index must be valid and fullfill : (rvb_index-1) % (RVT_K^level) == 0 static inline uint64_t nextRvbIndex(uint64_t rvb_index, uint8_t level); // caller should not call with 1st rvb_index static inline uint64_t prevRvbIndex(uint64_t rvb_index, uint8_t level); }; // NodeInfo // Each node, even 0 level nodes, holds a current value and an initial value. // // The node is constructed with an initial value: // 1) Initial value of a level 0 nodes is a function of its ID and an external (user input) message of size N. // 2) Initial value of any other value is a function of its ID and a zero message of size N. // // Initially, both current value and initial values are equal. // The tree is maintained in such way that the current value (CV) and the (IV) should have the next equation always // true for any level I>0 node in the tree: CV = IV + Sum(IV of all nodes connected directly or indirectly to that // node in lower levels) and also CV - IV = Sum(CV of all direct connected children) struct RVBNode { RVBNode(uint64_t rvb_index, const char* data, size_t data_size); RVBNode(uint8_t level, uint64_t rvb_index); RVBNode(uint64_t node_id, char* val, size_t size); void logInfoVal(const std::string& prefix = ""); const std::shared_ptr<char[]> computeNodeInitialValue(NodeInfo& node_id, const char* data, size_t data_size); NodeInfo info_; NodeVal current_value_; }; public: #pragma pack(push, 1) struct RVTMetadata { uint64_t magic_num; uint8_t version_num; uint32_t RVT_K; uint32_t fetch_range_size; size_t value_size; uint64_t root_node_id; uint64_t total_nodes; static void staticAssert() noexcept; }; #pragma pack(pop) struct SerializedRVTNode { uint64_t id; uint64_t parent_id; size_t last_insertion_index; std::deque<uint64_t> child_ids; size_t current_value_encoded_size; static void staticAssert() noexcept; }; struct RVTNode; using RVBNodePtr = std::shared_ptr<RVBNode>; using RVTNodePtr = std::shared_ptr<RVTNode>; struct RVTNode : public RVBNode { RVTNode(const RVBNodePtr& child_node); RVTNode(uint8_t level, uint64_t rvb_index); RVTNode(SerializedRVTNode& node, char* cur_val_ptr, size_t cur_value_size); static RVTNodePtr createFromSerialized(std::istringstream& is); void addValue(const NodeVal& nvalue); void substractValue(const NodeVal& nvalue); std::ostringstream serialize() const; uint64_t parent_id_; std::deque<uint64_t> child_ids_; static constexpr size_t kInsertionCounterNotInitialized_ = std::numeric_limits<size_t>::max(); size_t insertion_counter_; // When reaches RVT_K, node is considered closed. const NodeVal initial_value_; // We need to keep this value to validate node's current value size_t insertionsLeft() const { return RangeValidationTree::RVT_K - insertion_counter_; } size_t numChildren() const { return child_ids_.size(); } size_t hasNoChilds() const { return child_ids_.empty(); } size_t hasChilds() const { return !child_ids_.empty(); } const uint64_t minChildId() const { return child_ids_.front(); } const uint64_t maxChildId() const { return child_ids_.back(); } bool openForInsertion() const { return insertionsLeft() > 0; } bool openForRemoval() const { return numChildren() > 0; } void pushChildId(uint64_t id); void popChildId(uint64_t id); }; // validation functions protected: static uint64_t pow_uint(uint64_t base, uint64_t exp) noexcept; bool isValidRvbId(RVBId block_id) const noexcept; bool validateRVBGroupId(RVBGroupId rvb_group_id) const; bool validateTreeStructure() const noexcept; bool validateTreeValues() const noexcept; // Helper functions enum class NodeType { PARENT, RIGHT_SIBLING, // Sibling: must have common parent LEFT_SIBLING, LEFTMOST_SAME_LEVEL_NODE, // Same level node: we not necessarily share the same parent RIGHTMOST_SAME_LEVEL_NODE, LEFTMOST_CHILD, // Child: Must be one of my childs RIGHTMOST_CHILD, LEFTMOST_LEVEL_DOWN_NODE, // Level down node: not has to be my child. If my level is X, this nodes level is x-1. RIGHTMOST_LEVEL_DOWN_NODE }; // will never return the input node. If couldn't find such node, returns nullptr RVTNodePtr getRVTNodeByType(const RVTNodePtr& node, NodeType type) const; // tree internal manipulation functions void addRVBNode(const RVBNodePtr& node); void addInternalNode(const RVTNodePtr& node); void removeRVBNode(const RVBNodePtr& node); void addValueToInternalNodes(const RVTNodePtr& bottom_node, const NodeVal& value); void removeAndUpdateInternalNodes(const RVTNodePtr& rvt_node, const NodeVal& value); void setNewRoot(const RVTNodePtr& new_root); inline RVTNodePtr openForInsertion(uint64_t level) const; inline RVTNodePtr openForRemoval(uint64_t level) const; inline uint64_t rvbIdToIndex(RVBId rvb_id) const; // rvb_id must be valid inline uint64_t rvbIndexToId(RVBId rvb_id) const; // rvb_id must be valid enum class ArrUpdateType { ADD_NODE_TO_RIGHT, CHECK_REMOVE_NODE }; void updateOpenRvtNodeArrays(ArrUpdateType update_type, const RVTNodePtr& node); protected: // vector index represents level in tree // level 0 represents RVB node so it would always hold 0x0 std::array<RVTNodePtr, NodeInfo::kMaxLevels> rightmost_rvt_node_; std::array<RVTNodePtr, NodeInfo::kMaxLevels> leftmost_rvt_node_; std::unordered_map<uint64_t, RVTNodePtr> id_to_node_; RVTNodePtr root_{nullptr}; uint64_t min_rvb_index_{}; // RVB index is (RVB ID / fetch range size). This is the minimal index in the tree. uint64_t max_rvb_index_{}; // RVB index is (RVB ID / fetch range size). This is the maximal index in the tree. std::unordered_set<uint64_t> node_ids_to_erase_; const logging::Logger& logger_; // constants static uint32_t RVT_K; const uint32_t fetch_range_size_{}; const size_t value_size_{}; static constexpr size_t kMaxNodesToPrint{10000}; static constexpr uint8_t CHECKPOINT_PERSISTENCY_VERSION{1}; static constexpr uint8_t version_num_{CHECKPOINT_PERSISTENCY_VERSION}; static constexpr uint64_t magic_num_{0x1122334455667788}; static constexpr uint8_t kDefaultRVBLeafLevel = 0; static constexpr uint8_t kDefaultRVTLeafLevel = 1; }; using LogPrintVerbosity = RangeValidationTree::LogPrintVerbosity; } // namespace bftEngine::bcst::impl
42.404826
120
0.728267
[ "vector" ]
61367c2da0ecb0c81ae25b042cf2752d15b86cc2
2,044
cpp
C++
serialize_test.cpp
DennisZZH/Blockchain_Paxos
d9d8003d7a96c5ad17bc249ea39b50f328740c75
[ "MIT" ]
null
null
null
serialize_test.cpp
DennisZZH/Blockchain_Paxos
d9d8003d7a96c5ad17bc249ea39b50f328740c75
[ "MIT" ]
null
null
null
serialize_test.cpp
DennisZZH/Blockchain_Paxos
d9d8003d7a96c5ad17bc249ea39b50f328740c75
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include <string> #include <string.h> #include <vector> #include "Blockchain.h" using namespace std; std::vector<Transaction> Str_to_txns(std::string all_str) { std::vector<Transaction> result; char copy[all_str.length() + 1]; strcpy(copy, all_str.c_str()); std::string txn_str; int sid, rid, amt; char *token = strtok(copy, ";"); while (token != NULL) { txn_str = std::string(token); sid = txn_str[0] - '0'; rid = txn_str[1] - '0'; amt = stoi(txn_str.substr(2, txn_str.length() - 2)); result.push_back(Transaction(sid, rid, amt)); token = strtok(NULL, ";"); } return result; } std::string Txns_to_str(std::vector<Transaction> txns) { std::string txn_str = "", all_str = ""; for (int i = 0; i < txns.size(); i++) { txn_str += std::to_string(txns[i].get_sid()); txn_str += std::to_string(txns[i].get_rid()); txn_str += std::to_string(txns[i].get_amt()); txn_str += ";"; all_str += txn_str; txn_str = ""; } return all_str; } int main() { Transaction txn1(1, 2, 25); Transaction txn2(2, 3, 60); Transaction txn3(4, 5, 90); Transaction txn4(4, 2, 110); Transaction txn5(1, 5, 20); Transaction txn6(3, 4, 290); Transaction txn7(4, 2, 45); vector<Transaction> l1, l2, l3; l1.push_back(txn1); l1.push_back(txn2); l1.push_back(txn3); l2.push_back(txn4); l2.push_back(txn5); l3.push_back(txn6); l3.push_back(txn7); string s1, s2, s3; s1 = Txns_to_str(l1); s2 = Txns_to_str(l2); s3 = Txns_to_str(l3); cout << "s1 = " << s1 << endl; cout << "s2 = " << s2 << endl; cout << "s3 = " << s3 << endl; cout << endl; vector<Transaction> l4, l5, l6; l4 = Str_to_txns(s1); l5 = Str_to_txns(s2); l6 = Str_to_txns(s3); Block b1(l4); b1.print_block(); Block b2(l5); b2.print_block(); Block b3(l6); b3.print_block(); return 0; }
23.494253
60
0.565068
[ "vector" ]
6138efb846dd477099dd31031220373e7d5a9acc
29,525
cc
C++
sql/recovery.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
sql/recovery.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
sql/recovery.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2013 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 "sql/recovery.h" #include <stddef.h> #include "base/files/file_path.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "sql/connection.h" #include "sql/statement.h" #include "third_party/sqlite/sqlite3.h" #include "third_party/sqlite/src/src/recover.h" namespace sql { namespace { // This enum must match the numbering for Sqlite.RecoveryEvents in // histograms.xml. Do not reorder or remove items, only add new items before // RECOVERY_EVENT_MAX. enum RecoveryEventType { // Init() completed successfully. RECOVERY_SUCCESS_INIT = 0, // Failed to open temporary database to recover into. RECOVERY_FAILED_OPEN_TEMPORARY, // Failed to initialize recover vtable system. RECOVERY_FAILED_VIRTUAL_TABLE_INIT, // System SQLite doesn't support vtable. // This is deprecated. Chrome doesn't support using the system SQLite anymore. DEPRECATED_RECOVERY_FAILED_VIRTUAL_TABLE_SYSTEM_SQLITE, // Failed attempting to enable writable_schema. RECOVERY_FAILED_WRITABLE_SCHEMA, // Failed to attach the corrupt database to the temporary database. RECOVERY_FAILED_ATTACH, // Backup() successfully completed. RECOVERY_SUCCESS_BACKUP, // Failed sqlite3_backup_init(). Error code in Sqlite.RecoveryHandle. RECOVERY_FAILED_BACKUP_INIT, // Failed sqlite3_backup_step(). Error code in Sqlite.RecoveryStep. RECOVERY_FAILED_BACKUP_STEP, // AutoRecoverTable() successfully completed. RECOVERY_SUCCESS_AUTORECOVER, // The target table contained a type which the code is not equipped // to handle. This should only happen if things are fubar. RECOVERY_FAILED_AUTORECOVER_UNRECOGNIZED_TYPE, // The target table does not exist. RECOVERY_FAILED_AUTORECOVER_MISSING_TABLE, // The recovery virtual table creation failed. RECOVERY_FAILED_AUTORECOVER_CREATE, // Copying data from the recovery table to the target table failed. RECOVERY_FAILED_AUTORECOVER_INSERT, // Dropping the recovery virtual table failed. RECOVERY_FAILED_AUTORECOVER_DROP, // SetupMeta() successfully completed. RECOVERY_SUCCESS_SETUP_META, // Failure creating recovery meta table. RECOVERY_FAILED_META_CREATE, // GetMetaVersionNumber() successfully completed. RECOVERY_SUCCESS_META_VERSION, // Failed in querying recovery meta table. RECOVERY_FAILED_META_QUERY, // No version key in recovery meta table. RECOVERY_FAILED_META_NO_VERSION, // Automatically recovered entire database successfully. RECOVERY_SUCCESS_AUTORECOVERDB, // Database was so broken recovery couldn't be entered. RECOVERY_FAILED_AUTORECOVERDB_BEGIN, // Failed to schema from corrupt database. RECOVERY_FAILED_AUTORECOVERDB_SCHEMASELECT, // Failed to create copy of schema in recovery database. RECOVERY_FAILED_AUTORECOVERDB_SCHEMACREATE, // Failed querying tables to recover. Should be impossible. RECOVERY_FAILED_AUTORECOVERDB_NAMESELECT, // Failed to recover an individual table. RECOVERY_FAILED_AUTORECOVERDB_TABLE, // Failed to recover [sqlite_sequence] table. RECOVERY_FAILED_AUTORECOVERDB_SEQUENCE, // Failed to recover triggers or views or virtual tables. RECOVERY_FAILED_AUTORECOVERDB_AUX, // After SQLITE_NOTADB failure setting up for recovery, Delete() failed. RECOVERY_FAILED_AUTORECOVERDB_NOTADB_DELETE, // After SQLITE_NOTADB failure setting up for recovery, Delete() succeeded // then Open() failed. RECOVERY_FAILED_AUTORECOVERDB_NOTADB_REOPEN, // After SQLITE_NOTADB failure setting up for recovery, Delete() and Open() // succeeded, then querying the database failed. RECOVERY_FAILED_AUTORECOVERDB_NOTADB_QUERY, // After SQLITE_NOTADB failure setting up for recovery, the database was // successfully deleted. RECOVERY_SUCCESS_AUTORECOVERDB_NOTADB_DELETE, // Failed to find required [meta.version] information. RECOVERY_FAILED_AUTORECOVERDB_META_VERSION, // Add new items before this one, always keep this one at the end. RECOVERY_EVENT_MAX, }; void RecordRecoveryEvent(RecoveryEventType recovery_event) { UMA_HISTOGRAM_ENUMERATION("Sqlite.RecoveryEvents", recovery_event, RECOVERY_EVENT_MAX); } } // namespace // static std::unique_ptr<Recovery> Recovery::Begin(Connection* connection, const base::FilePath& db_path) { // Recovery is likely to be used in error handling. Since recovery changes // the state of the handle, protect against multiple layers attempting the // same recovery. if (!connection->is_open()) { // Warn about API mis-use. DLOG_IF(FATAL, !connection->poisoned_) << "Illegal to recover with closed database"; return std::unique_ptr<Recovery>(); } std::unique_ptr<Recovery> r(new Recovery(connection)); if (!r->Init(db_path)) { // TODO(shess): Should Init() failure result in Raze()? r->Shutdown(POISON); return std::unique_ptr<Recovery>(); } return r; } // static bool Recovery::Recovered(std::unique_ptr<Recovery> r) { return r->Backup(); } // static void Recovery::Unrecoverable(std::unique_ptr<Recovery> r) { CHECK(r->db_); // ~Recovery() will RAZE_AND_POISON. } // static void Recovery::Rollback(std::unique_ptr<Recovery> r) { // TODO(shess): HISTOGRAM to track? Or just have people crash out? // Crash and dump? r->Shutdown(POISON); } Recovery::Recovery(Connection* connection) : db_(connection), recover_db_() { // Result should keep the page size specified earlier. if (db_->page_size_) recover_db_.set_page_size(db_->page_size_); // Files with I/O errors cannot be safely memory-mapped. recover_db_.set_mmap_disabled(); // TODO(shess): This may not handle cases where the default page // size is used, but the default has changed. I do not think this // has ever happened. This could be handled by using "PRAGMA // page_size", at the cost of potential additional failure cases. } Recovery::~Recovery() { Shutdown(RAZE_AND_POISON); } bool Recovery::Init(const base::FilePath& db_path) { // Prevent the possibility of re-entering this code due to errors // which happen while executing this code. DCHECK(!db_->has_error_callback()); // Break any outstanding transactions on the original database to // prevent deadlocks reading through the attached version. // TODO(shess): A client may legitimately wish to recover from // within the transaction context, because it would potentially // preserve any in-flight changes. Unfortunately, any attach-based // system could not handle that. A system which manually queried // one database and stored to the other possibly could, but would be // more complicated. db_->RollbackAllTransactions(); // Disable exclusive locking mode so that the attached database can // access things. The locking_mode change is not active until the // next database access, so immediately force an access. Enabling // writable_schema allows processing through certain kinds of // corruption. // TODO(shess): It would be better to just close the handle, but it // is necessary for the final backup which rewrites things. It // might be reasonable to close then re-open the handle. ignore_result(db_->Execute("PRAGMA writable_schema=1")); ignore_result(db_->Execute("PRAGMA locking_mode=NORMAL")); ignore_result(db_->Execute("SELECT COUNT(*) FROM sqlite_master")); // TODO(shess): If this is a common failure case, it might be // possible to fall back to a memory database. But it probably // implies that the SQLite tmpdir logic is busted, which could cause // a variety of other random issues in our code. if (!recover_db_.OpenTemporary()) { RecordRecoveryEvent(RECOVERY_FAILED_OPEN_TEMPORARY); return false; } // Enable the recover virtual table for this connection. int rc = chrome_sqlite3_recoverVtableInit(recover_db_.db_); if (rc != SQLITE_OK) { RecordRecoveryEvent(RECOVERY_FAILED_VIRTUAL_TABLE_INIT); LOG(ERROR) << "Failed to initialize recover module: " << recover_db_.GetErrorMessage(); return false; } // Turn on |SQLITE_RecoveryMode| for the handle, which allows // reading certain broken databases. if (!recover_db_.Execute("PRAGMA writable_schema=1")) { RecordRecoveryEvent(RECOVERY_FAILED_WRITABLE_SCHEMA); return false; } if (!recover_db_.AttachDatabase(db_path, "corrupt")) { RecordRecoveryEvent(RECOVERY_FAILED_ATTACH); base::UmaHistogramSparse("Sqlite.RecoveryAttachError", recover_db_.GetErrorCode()); return false; } RecordRecoveryEvent(RECOVERY_SUCCESS_INIT); return true; } bool Recovery::Backup() { CHECK(db_); CHECK(recover_db_.is_open()); // TODO(shess): Some of the failure cases here may need further // exploration. Just as elsewhere, persistent problems probably // need to be razed, while anything which might succeed on a future // run probably should be allowed to try. But since Raze() uses the // same approach, even that wouldn't work when this code fails. // // The documentation for the backup system indicate a relatively // small number of errors are expected: // SQLITE_BUSY - cannot lock the destination database. This should // only happen if someone has another handle to the // database, Chromium generally doesn't do that. // SQLITE_LOCKED - someone locked the source database. Should be // impossible (perhaps anti-virus could?). // SQLITE_READONLY - destination is read-only. // SQLITE_IOERR - since source database is temporary, probably // indicates that the destination contains blocks // throwing errors, or gross filesystem errors. // SQLITE_NOMEM - out of memory, should be transient. // // AFAICT, SQLITE_BUSY and SQLITE_NOMEM could perhaps be considered // transient, with SQLITE_LOCKED being unclear. // // SQLITE_READONLY and SQLITE_IOERR are probably persistent, with a // strong chance that Raze() would not resolve them. If Delete() // deletes the database file, the code could then re-open the file // and attempt the backup again. // // For now, this code attempts a best effort and records histograms // to inform future development. // Backup the original db from the recovered db. const char* kMain = "main"; sqlite3_backup* backup = sqlite3_backup_init(db_->db_, kMain, recover_db_.db_, kMain); if (!backup) { RecordRecoveryEvent(RECOVERY_FAILED_BACKUP_INIT); // Error code is in the destination database handle. int err = sqlite3_extended_errcode(db_->db_); base::UmaHistogramSparse("Sqlite.RecoveryHandle", err); LOG(ERROR) << "sqlite3_backup_init() failed: " << sqlite3_errmsg(db_->db_); return false; } // -1 backs up the entire database. int rc = sqlite3_backup_step(backup, -1); int pages = sqlite3_backup_pagecount(backup); // TODO(shess): sqlite3_backup_finish() appears to allow returning a // different value from sqlite3_backup_step(). Circle back and // figure out if that can usefully inform the decision of whether to // retry or not. sqlite3_backup_finish(backup); DCHECK_GT(pages, 0); if (rc != SQLITE_DONE) { RecordRecoveryEvent(RECOVERY_FAILED_BACKUP_STEP); base::UmaHistogramSparse("Sqlite.RecoveryStep", rc); LOG(ERROR) << "sqlite3_backup_step() failed: " << sqlite3_errmsg(db_->db_); } // The destination database was locked. Give up, but leave the data // in place. Maybe it won't be locked next time. if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) { Shutdown(POISON); return false; } // Running out of memory should be transient, retry later. if (rc == SQLITE_NOMEM) { Shutdown(POISON); return false; } // TODO(shess): For now, leave the original database alone, pending // results from Sqlite.RecoveryStep. Some errors should probably // route to RAZE_AND_POISON. if (rc != SQLITE_DONE) { Shutdown(POISON); return false; } // Clean up the recovery db, and terminate the main database // connection. RecordRecoveryEvent(RECOVERY_SUCCESS_BACKUP); Shutdown(POISON); return true; } void Recovery::Shutdown(Recovery::Disposition raze) { if (!db_) return; recover_db_.Close(); if (raze == RAZE_AND_POISON) { db_->RazeAndClose(); } else if (raze == POISON) { db_->Poison(); } db_ = NULL; } bool Recovery::AutoRecoverTable(const char* table_name, size_t* rows_recovered) { // Query the info for the recovered table in database [main]. std::string query( base::StringPrintf("PRAGMA main.table_info(%s)", table_name)); Statement s(db()->GetUniqueStatement(query.c_str())); // The columns of the recover virtual table. std::vector<std::string> create_column_decls; // The columns to select from the recover virtual table when copying // to the recovered table. std::vector<std::string> insert_columns; // If PRIMARY KEY is a single INTEGER column, then it is an alias // for ROWID. The primary key can be compound, so this can only be // determined after processing all column data and tracking what is // seen. |pk_column_count| counts the columns in the primary key. // |rowid_decl| stores the ROWID version of the last INTEGER column // seen, which is at |rowid_ofs| in |create_column_decls|. size_t pk_column_count = 0; size_t rowid_ofs = 0; // Only valid if rowid_decl is set. std::string rowid_decl; // ROWID version of column |rowid_ofs|. while (s.Step()) { const std::string column_name(s.ColumnString(1)); const std::string column_type(s.ColumnString(2)); const int default_type = s.ColumnType(4); const bool default_is_null = (default_type == COLUMN_TYPE_NULL); const int pk_column = s.ColumnInt(5); // http://www.sqlite.org/pragma.html#pragma_table_info documents column 5 as // the 1-based index of the column in the primary key, otherwise 0. if (pk_column > 0) ++pk_column_count; // Construct column declaration as "name type [optional constraint]". std::string column_decl = column_name; // SQLite's affinity detection is documented at: // http://www.sqlite.org/datatype3.html#affname // The gist of it is that CHAR, TEXT, and INT use substring matches. // TODO(shess): It would be nice to unit test the type handling, // but it is not obvious to me how to write a test which would // fail appropriately when something was broken. It would have to // somehow use data which would allow detecting the various type // coercions which happen. If STRICT could be enabled, type // mismatches could be detected by which rows are filtered. if (column_type.find("INT") != std::string::npos) { if (pk_column == 1) { rowid_ofs = create_column_decls.size(); rowid_decl = column_name + " ROWID"; } column_decl += " INTEGER"; } else if (column_type.find("CHAR") != std::string::npos || column_type.find("TEXT") != std::string::npos) { column_decl += " TEXT"; } else if (column_type == "BLOB") { column_decl += " BLOB"; } else if (column_type.find("DOUB") != std::string::npos) { column_decl += " FLOAT"; } else { // TODO(shess): AFAICT, there remain: // - contains("CLOB") -> TEXT // - contains("REAL") -> FLOAT // - contains("FLOA") -> FLOAT // - other -> "NUMERIC" // Just code those in as they come up. NOTREACHED() << " Unsupported type " << column_type; RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVER_UNRECOGNIZED_TYPE); return false; } create_column_decls.push_back(column_decl); // Per the NOTE in the header file, convert NULL values to the // DEFAULT. All columns could be IFNULL(column_name,default), but // the NULL case would require special handling either way. if (default_is_null) { insert_columns.push_back(column_name); } else { // The default value appears to be pre-quoted, as if it is // literally from the sqlite_master CREATE statement. std::string default_value = s.ColumnString(4); insert_columns.push_back(base::StringPrintf( "IFNULL(%s,%s)", column_name.c_str(), default_value.c_str())); } } // Receiving no column information implies that the table doesn't exist. if (create_column_decls.empty()) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVER_MISSING_TABLE); return false; } // If the PRIMARY KEY was a single INTEGER column, convert it to ROWID. if (pk_column_count == 1 && !rowid_decl.empty()) create_column_decls[rowid_ofs] = rowid_decl; std::string recover_create(base::StringPrintf( "CREATE VIRTUAL TABLE temp.recover_%s USING recover(corrupt.%s, %s)", table_name, table_name, base::JoinString(create_column_decls, ",").c_str())); // INSERT OR IGNORE means that it will drop rows resulting from constraint // violations. INSERT OR REPLACE only handles UNIQUE constraint violations. std::string recover_insert(base::StringPrintf( "INSERT OR IGNORE INTO main.%s SELECT %s FROM temp.recover_%s", table_name, base::JoinString(insert_columns, ",").c_str(), table_name)); std::string recover_drop(base::StringPrintf( "DROP TABLE temp.recover_%s", table_name)); if (!db()->Execute(recover_create.c_str())) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVER_CREATE); return false; } if (!db()->Execute(recover_insert.c_str())) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVER_INSERT); ignore_result(db()->Execute(recover_drop.c_str())); return false; } *rows_recovered = db()->GetLastChangeCount(); // TODO(shess): Is leaving the recover table around a breaker? if (!db()->Execute(recover_drop.c_str())) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVER_DROP); return false; } RecordRecoveryEvent(RECOVERY_SUCCESS_AUTORECOVER); return true; } bool Recovery::SetupMeta() { const char kCreateSql[] = "CREATE VIRTUAL TABLE temp.recover_meta USING recover" "(" "corrupt.meta," "key TEXT NOT NULL," "value ANY" // Whatever is stored. ")"; if (!db()->Execute(kCreateSql)) { RecordRecoveryEvent(RECOVERY_FAILED_META_CREATE); return false; } RecordRecoveryEvent(RECOVERY_SUCCESS_SETUP_META); return true; } bool Recovery::GetMetaVersionNumber(int* version) { DCHECK(version); // TODO(shess): DCHECK(db()->DoesTableExist("temp.recover_meta")); // Unfortunately, DoesTableExist() queries sqlite_master, not // sqlite_temp_master. const char kVersionSql[] = "SELECT value FROM temp.recover_meta WHERE key = 'version'"; sql::Statement recovery_version(db()->GetUniqueStatement(kVersionSql)); if (!recovery_version.Step()) { if (!recovery_version.Succeeded()) { RecordRecoveryEvent(RECOVERY_FAILED_META_QUERY); } else { RecordRecoveryEvent(RECOVERY_FAILED_META_NO_VERSION); } return false; } RecordRecoveryEvent(RECOVERY_SUCCESS_META_VERSION); *version = recovery_version.ColumnInt(0); return true; } namespace { // Collect statements from [corrupt.sqlite_master.sql] which start with |prefix| // (which should be a valid SQL string ending with the space before a table // name), then apply the statements to [main]. Skip any table named // 'sqlite_sequence', as that table is created on demand by SQLite if any tables // use AUTOINCREMENT. // // Returns |true| if all of the matching items were created in the main // database. Returns |false| if an item fails on creation, or if the corrupt // database schema cannot be queried. bool SchemaCopyHelper(Connection* db, const char* prefix) { const size_t prefix_len = strlen(prefix); DCHECK_EQ(' ', prefix[prefix_len-1]); sql::Statement s(db->GetUniqueStatement( "SELECT DISTINCT sql FROM corrupt.sqlite_master " "WHERE name<>'sqlite_sequence'")); while (s.Step()) { std::string sql = s.ColumnString(0); // Skip statements that don't start with |prefix|. if (sql.compare(0, prefix_len, prefix) != 0) continue; sql.insert(prefix_len, "main."); if (!db->Execute(sql.c_str())) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_SCHEMACREATE); return false; } } if (!s.Succeeded()) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_SCHEMASELECT); return false; } return true; } } // namespace // This method is derived from SQLite's vacuum.c. VACUUM operates very // similarily, creating a new database, populating the schema, then copying the // data. // // TODO(shess): This conservatively uses Rollback() rather than Unrecoverable(). // With Rollback(), it is expected that the database will continue to generate // errors. Change the failure cases to Unrecoverable() if/when histogram // results indicate that everything is working reasonably. // // static std::unique_ptr<Recovery> Recovery::BeginRecoverDatabase( Connection* db, const base::FilePath& db_path) { std::unique_ptr<sql::Recovery> recovery = sql::Recovery::Begin(db, db_path); if (!recovery) { // Close the underlying sqlite* handle. Windows does not allow deleting // open files, and all platforms block opening a second sqlite3* handle // against a database when exclusive locking is set. db->Poison(); // Histograms from Recovery::Begin() show all current failures are in // attaching the corrupt database, with 2/3 being SQLITE_NOTADB. Don't // delete the database except for that specific failure case. { Connection probe_db; if (!probe_db.OpenInMemory() || probe_db.AttachDatabase(db_path, "corrupt") || probe_db.GetErrorCode() != SQLITE_NOTADB) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_BEGIN); return nullptr; } } // The database has invalid data in the SQLite header, so it is almost // certainly not recoverable without manual intervention (and likely not // recoverable _with_ manual intervention). Clear away the broken database. if (!sql::Connection::Delete(db_path)) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_NOTADB_DELETE); return nullptr; } // Windows deletion is complicated by file scanners and malware - sometimes // Delete() appears to succeed, even though the file remains. The following // attempts to track if this happens often enough to cause concern. { Connection probe_db; if (!probe_db.Open(db_path)) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_NOTADB_REOPEN); return nullptr; } if (!probe_db.Execute("PRAGMA auto_vacuum")) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_NOTADB_QUERY); return nullptr; } } // The rest of the recovery code could be run on the re-opened database, but // the database is empty, so there would be no point. RecordRecoveryEvent(RECOVERY_SUCCESS_AUTORECOVERDB_NOTADB_DELETE); return nullptr; } #if DCHECK_IS_ON() // This code silently fails to recover fts3 virtual tables. At this time no // browser database contain fts3 tables. Just to be safe, complain loudly if // the database contains virtual tables. // // fts3 has an [x_segdir] table containing a column [end_block INTEGER]. But // it actually stores either an integer or a text containing a pair of // integers separated by a space. AutoRecoverTable() trusts the INTEGER tag // when setting up the recover vtable, so those rows get dropped. Setting // that column to ANY may work. if (db->is_open()) { sql::Statement s(db->GetUniqueStatement( "SELECT 1 FROM sqlite_master WHERE sql LIKE 'CREATE VIRTUAL TABLE %'")); DCHECK(!s.Step()) << "Recovery of virtual tables not supported"; } #endif // TODO(shess): vacuum.c turns off checks and foreign keys. // TODO(shess): vacuum.c turns synchronous=OFF for the target. I do not fully // understand this, as the temporary db should not have a journal file at all. // Perhaps it does in case of cache spill? // Copy table schema from [corrupt] to [main]. if (!SchemaCopyHelper(recovery->db(), "CREATE TABLE ") || !SchemaCopyHelper(recovery->db(), "CREATE INDEX ") || !SchemaCopyHelper(recovery->db(), "CREATE UNIQUE INDEX ")) { // No RecordRecoveryEvent() here because SchemaCopyHelper() already did. Recovery::Rollback(std::move(recovery)); return nullptr; } // Run auto-recover against each table, skipping the sequence table. This is // necessary because table recovery can create the sequence table as a side // effect, so recovering that table inline could lead to duplicate data. { sql::Statement s(recovery->db()->GetUniqueStatement( "SELECT name FROM sqlite_master WHERE sql LIKE 'CREATE TABLE %' " "AND name!='sqlite_sequence'")); while (s.Step()) { const std::string name = s.ColumnString(0); size_t rows_recovered; if (!recovery->AutoRecoverTable(name.c_str(), &rows_recovered)) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_TABLE); Recovery::Rollback(std::move(recovery)); return nullptr; } } if (!s.Succeeded()) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_NAMESELECT); Recovery::Rollback(std::move(recovery)); return nullptr; } } // Overwrite any sequences created. if (recovery->db()->DoesTableExist("corrupt.sqlite_sequence")) { ignore_result(recovery->db()->Execute("DELETE FROM main.sqlite_sequence")); size_t rows_recovered; if (!recovery->AutoRecoverTable("sqlite_sequence", &rows_recovered)) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_SEQUENCE); Recovery::Rollback(std::move(recovery)); return nullptr; } } // Copy triggers and views directly to sqlite_master. Any tables they refer // to should already exist. char kCreateMetaItems[] = "INSERT INTO main.sqlite_master " "SELECT type, name, tbl_name, rootpage, sql " "FROM corrupt.sqlite_master WHERE type='view' OR type='trigger'"; if (!recovery->db()->Execute(kCreateMetaItems)) { RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_AUX); Recovery::Rollback(std::move(recovery)); return nullptr; } RecordRecoveryEvent(RECOVERY_SUCCESS_AUTORECOVERDB); return recovery; } void Recovery::RecoverDatabase(Connection* db, const base::FilePath& db_path) { std::unique_ptr<sql::Recovery> recovery = BeginRecoverDatabase(db, db_path); // ignore_result() because BeginRecoverDatabase() and Recovered() already // provide suitable histogram coverage. if (recovery) ignore_result(Recovery::Recovered(std::move(recovery))); } void Recovery::RecoverDatabaseWithMetaVersion(Connection* db, const base::FilePath& db_path) { std::unique_ptr<sql::Recovery> recovery = BeginRecoverDatabase(db, db_path); if (!recovery) return; int version = 0; if (!recovery->SetupMeta() || !recovery->GetMetaVersionNumber(&version)) { sql::Recovery::Unrecoverable(std::move(recovery)); RecordRecoveryEvent(RECOVERY_FAILED_AUTORECOVERDB_META_VERSION); return; } // ignore_result() because BeginRecoverDatabase() and Recovered() already // provide suitable histogram coverage. ignore_result(Recovery::Recovered(std::move(recovery))); } // static bool Recovery::ShouldRecover(int extended_error) { // Trim extended error codes. int error = extended_error & 0xFF; switch (error) { case SQLITE_NOTADB: // SQLITE_NOTADB happens if the SQLite header is broken. Some earlier // versions of SQLite return this where other versions return // SQLITE_CORRUPT, which is a recoverable case. Later versions only // return this error only in unrecoverable cases, in which case recovery // will fail with no changes to the database, so there's no harm in // attempting recovery in this case. return true; case SQLITE_CORRUPT: // SQLITE_CORRUPT generally means that the database is readable as a // SQLite database, but some inconsistency has been detected by SQLite. // In many cases the inconsistency is relatively trivial, such as if an // index refers to a row which was deleted, in which case most or even all // of the data can be recovered. This can also be reported if parts of // the file have been overwritten with garbage data, in which recovery // should be able to recover partial data. return true; // TODO(shess): Possible future options for automated fixing: // - SQLITE_CANTOPEN - delete the broken symlink or directory. // - SQLITE_PERM - permissions could be fixed. // - SQLITE_READONLY - permissions could be fixed. // - SQLITE_IOERR - rewrite using new blocks. // - SQLITE_FULL - recover in memory and rewrite subset of data. default: return false; } } } // namespace sql
36.860175
80
0.709162
[ "vector" ]
6140511842882368f53b88fcc2c80646d6db5775
3,365
cpp
C++
tests/unit/NaiveStorageTest.cpp
demmax/UniversalStorage
daa23a65b04e9eb7c205268721c286a59fb725a1
[ "MIT" ]
null
null
null
tests/unit/NaiveStorageTest.cpp
demmax/UniversalStorage
daa23a65b04e9eb7c205268721c286a59fb725a1
[ "MIT" ]
null
null
null
tests/unit/NaiveStorageTest.cpp
demmax/UniversalStorage
daa23a65b04e9eb7c205268721c286a59fb725a1
[ "MIT" ]
null
null
null
// // Created by maxon on 04.05.18. // #include <gtest/gtest.h> #include <exceptions.h> #include "NaiveStorage.h" using namespace UniversalStorage; TEST(NaiveStorageTest, SimpleSetGetCase) { size_t count = 5000; std::string file_name = "file"; std::string path = "/"; std::vector<uint8_t> vec{1, 2, 3, 4}; { NaiveStorage storage(file_name); for (int i = 0; i < count; i++) { std::vector v = vec; v.push_back(i); storage.setValue(path + std::to_string(i), v); } } { NaiveStorage storage(file_name); for (size_t i = 0; i < count; i++) { auto expected_vec = vec; expected_vec.push_back(i % 256); EXPECT_EQ(storage.getValue(path + std::to_string(i)), expected_vec); } } std::remove(file_name.c_str()); } TEST(NaiveStorageTest, ConnectingToStorageSetGetCase) { std::string file_name = "file1"; size_t count = 5000; std::string path = "/"; std::vector<uint8_t> vec{1, 2, 3, 4}; { NaiveStorage storage(file_name); for (auto i = 0u; i < count; i++) { std::vector v = vec; v.push_back(i); storage.setValue(path + std::to_string(i), v); } } { NaiveStorage storage(file_name); for (size_t i = 0u; i < count; i++) { auto expected_vec = vec; expected_vec.push_back(i % 256); EXPECT_EQ(storage.getValue(path + std::to_string(i)), expected_vec); } } std::remove(file_name.c_str()); } TEST(NaiveStorageTest, SimpleRemoveItemStorageTest) { std::string file_name = "file"; std::string path = "/"; std::vector<uint8_t> vec{1, 2, 3, 4}; { NaiveStorage storage(file_name); storage.setValue(path, vec); } { NaiveStorage storage(file_name); storage.removeValue(path); EXPECT_THROW(storage.getValue(path), NoSuchPathException); } std::remove(file_name.c_str()); } TEST(NaiveStorageTest, RemoveExactlyOneItemStorageTest) { std::string file_name = "file"; std::string path1 = "/"; std::string path2 = "/a"; std::vector<uint8_t> vec1{1, 2, 3, 4}; std::vector<uint8_t> vec2{5, 6, 7}; { NaiveStorage storage(file_name); storage.setValue(path1, vec1); storage.setValue(path2, vec2); } { NaiveStorage storage(file_name); storage.removeValue(path1); EXPECT_EQ(storage.getValue(path2), vec2); } std::remove(file_name.c_str()); } TEST(NaiveStorageTest, UnexistingItemGetCase) { std::string file_name = "file"; std::string path = "/"; NaiveStorage storage(file_name); EXPECT_THROW(storage.getValue(path), NoSuchPathException); std::remove(file_name.c_str()); } TEST(NaiveStorageTest, OverwriteItemCase) { std::string file_name = "file"; std::string path = "/"; std::vector<uint8_t> vec1{1, 2, 3, 4}; std::vector<uint8_t> vec2{100, 1, 200, 2, 230, 3}; { NaiveStorage storage(file_name); storage.setValue(path, vec1); } { NaiveStorage storage(file_name); storage.setValue(path, vec2); } { NaiveStorage storage(file_name); EXPECT_EQ(storage.getValue(path), vec2); } std::remove(file_name.c_str()); }
24.384058
80
0.586924
[ "vector" ]
6140d91f7219da553e3e369e0491743500d9e353
2,532
hpp
C++
engine/input/macos/InputSystemMacOS.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
1
2021-03-01T13:17:49.000Z
2021-03-01T13:17:49.000Z
engine/input/macos/InputSystemMacOS.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
null
null
null
engine/input/macos/InputSystemMacOS.hpp
taida957789/ouzel
a8c1cc74e6151a0f7d7d2c534f8747cba46a36af
[ "Unlicense" ]
null
null
null
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_INPUT_INPUTSYSTEMMACOS_HPP #define OUZEL_INPUT_INPUTSYSTEMMACOS_HPP #include <memory> #include <system_error> #include <unordered_map> #include <IOKit/hid/IOHIDManager.h> #if defined(__OBJC__) # import <AppKit/NSCursor.h> typedef NSCursor* NSCursorPtr; # include <GameController/GameController.h> typedef GCController* GCControllerPtr; #else # include <objc/NSObjCRuntime.h> typedef id NSCursorPtr; typedef id GCControllerPtr; #endif #include "../InputSystem.hpp" #include "../Keyboard.hpp" #include "GamepadDeviceMacOS.hpp" #include "GamepadDeviceGC.hpp" #include "GamepadDeviceIOKit.hpp" #include "MouseDeviceMacOS.hpp" namespace ouzel::input::macos { class Cursor; class InputSystem final: public input::InputSystem { public: explicit InputSystem(const std::function<std::future<bool>(const Event&)>& initCallback); ~InputSystem() override; auto getKeyboardDevice() const noexcept { return keyboardDevice.get(); } auto getMouseDevice() const noexcept { return mouseDevice.get(); } auto getTouchpadDevice() const noexcept { return touchpadDevice.get(); } void handleGamepadDiscoveryCompleted(); void handleGamepadConnected(GCControllerPtr device); void handleGamepadDisconnected(GCControllerPtr device); void handleGamepadConnected(IOHIDDeviceRef device); void handleGamepadDisconnected(IOHIDDeviceRef device); NSCursorPtr getCursor() const; private: void executeCommand(const Command& command) final; auto getNextDeviceId() noexcept { ++lastDeviceId.value; return lastDeviceId; } void startGamepadDiscovery(); void stopGamepadDiscovery(); DeviceId lastDeviceId; std::unique_ptr<KeyboardDevice> keyboardDevice; std::unique_ptr<MouseDevice> mouseDevice; std::unique_ptr<TouchpadDevice> touchpadDevice; std::unordered_map<GCControllerPtr, std::unique_ptr<GamepadDeviceGC>> gamepadDevicesGC; std::unordered_map<IOHIDDeviceRef, std::unique_ptr<GamepadDeviceIOKit>> gamepadDevicesIOKit; id connectDelegate = nil; IOHIDManagerRef hidManager = nullptr; std::vector<std::unique_ptr<Cursor>> cursors; unsigned char emptyCursorData[4] = {0, 0, 0, 0}; NSCursorPtr emptyCursor = nil; NSCursorPtr defaultCursor = nil; }; } #endif // OUZEL_INPUT_INPUTSYSTEMMACOS_HPP
30.506024
100
0.716035
[ "vector" ]
6142312d565aeffdbf669509b7d9b71966750a8a
1,263
cc
C++
ppm_output.cc
pdx-cs-se/ancient-raytracer
e7f2f963f01f4e0b642cf9120af21e63baa08e00
[ "BSD-3-Clause" ]
2
2020-05-11T06:32:33.000Z
2020-10-14T21:45:13.000Z
ppm_output.cc
pdx-cs-se/ancient-raytracer
e7f2f963f01f4e0b642cf9120af21e63baa08e00
[ "BSD-3-Clause" ]
4
2020-10-14T22:52:00.000Z
2020-10-22T02:12:06.000Z
ppm_output.cc
pdx-cs-se/ancient-raytracer
e7f2f963f01f4e0b642cf9120af21e63baa08e00
[ "BSD-3-Clause" ]
1
2020-10-21T21:16:56.000Z
2020-10-21T21:16:56.000Z
// -*- C++ -*- // PPM (rawbits) frame buffer output class - implementation // Bart 2/91 extern "C" { #include <string.h> #include <stdio.h> #ifndef __GNUC__ extern void fputc( char, FILE * ); extern void fclose( FILE * ); extern void fprintf( FILE *, const char *, ... ); #endif } #ifndef NOOUTLINE #include "render.h" ppm_output::ppm_output( char *n, int w, int h ) : output( n, (char *)".ppm", w, h ) { fprintf( outfile, "P6\n%d\n%d\n%d\n", w, h, 255 ); curx = 0; cury = 0; } // used by oldppm_output::oldppm_output ppm_output::ppm_output( char *n, char *ext, int w, int h ) : output( n, ext, w, h ) { curx = 0; cury = 0; } #endif #ifdef INLINE inline void ppm_output::flushrow( int y ) { assert( y < ysize && cury == y ); cury++; curx = 0; #if DEBUGLEVEL == 2 if( !(y % 10) ) #endif #if DEBUGLEVEL >= 2 printf( "output row: %d\n", y ); #endif } inline void ppm_output::putpixel( int x, int y, point &c ) { unsigned char r = gamma(R(c)); unsigned char g = gamma(G(c)); unsigned char b = gamma(B(c)); assert( x < xsize && curx == x && cury == y ); curx++; #if DEBUGLEVEL > 3 printf( "output: %f %f %f\n", c[0], c[1], c[2] ); #endif fputc( r, outfile ); fputc( g, outfile ); fputc( b, outfile ); } #endif
18.042857
60
0.581948
[ "render" ]
6142729bfe88839a337380954ef19f86cdf1851e
23,496
cpp
C++
Gems/ScriptCanvas/Code/Editor/View/Widgets/UnitTestPanel/UnitTestDockWidget.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2022-03-12T14:13:45.000Z
2022-03-12T14:13:45.000Z
Gems/ScriptCanvas/Code/Editor/View/Widgets/UnitTestPanel/UnitTestDockWidget.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
3
2021-09-08T03:41:27.000Z
2022-03-12T01:01:29.000Z
Gems/ScriptCanvas/Code/Editor/View/Widgets/UnitTestPanel/UnitTestDockWidget.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <QCompleter> #include <QEvent> #include <QGraphicsScene> #include <QGraphicsView> #include <QAction> #include <QMenu> #include <QMessageBox> #include <QScopedValueRollback> #include <QLineEdit> #include <QTimer> #include <QPushButton> #include <QHeaderView> #include <AzCore/Component/ComponentApplication.h> #include <AzCore/RTTI/BehaviorContext.h> #include <AzCore/UserSettings/UserSettings.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/IO/FileIO.h> #include <AzCore/Asset/AssetManager.h> #include <AzFramework/StringFunc/StringFunc.h> #include <AzToolsFramework/ToolsComponents/EditorComponentBase.h> #include <AzToolsFramework/AssetBrowser/AssetBrowserEntry.h> #include <Editor/QtMetaTypes.h> #include <Editor/Settings.h> #include <Editor/Assets/ScriptCanvasAssetHelpers.h> #include <Editor/GraphCanvas/GraphCanvasEditorNotificationBusId.h> #include <Editor/Include/ScriptCanvas/GraphCanvas/NodeDescriptorBus.h> #include <Editor/Model/UnitTestBrowserFilterModel.h> #include <Editor/Translation/TranslationHelper.h> #include <Editor/View/Widgets/PropertyGridBus.h> #include <Editor/View/Widgets/UnitTestPanel/UnitTestDockWidget.h> #include <Editor/View/Widgets/UnitTestPanel/ui_UnitTestDockWidget.h> #include <Editor/View/Widgets/UnitTestPanel/moc_UnitTestDockWidget.cpp> #include <Data/Data.h> #include <ScriptCanvas/Assets/ScriptCanvasAsset.h> #include <ScriptCanvas/Assets/ScriptCanvasAssetHandler.h> #include <ScriptCanvas/Bus/ScriptCanvasExecutionBus.h> #include <ScriptCanvas/Bus/UnitTestVerificationBus.h> #include <ScriptCanvas/Data/DataRegistry.h> #include <ScriptCanvas/GraphCanvas/NodeDescriptorBus.h> #include <LyViewPaneNames.h> namespace ScriptCanvasEditor { ///////////////////////// // ItemButtonsDelegate ///////////////////////// ItemButtonsDelegate::ItemButtonsDelegate(QObject* parent) : QStyledItemDelegate(parent) , m_editIcon(QIcon(":/ScriptCanvasEditorResources/Resources/edit_icon.png").pixmap(QSize(14, 14))) { } QPoint ItemButtonsDelegate::GetEditPosition(const QStyleOptionViewItem& option) const { return QPoint(option.rect.right() - m_editIcon.width(), option.rect.center().y() - m_editIcon.height() / 2); } QPoint ItemButtonsDelegate::GetResultsPosition(const QStyleOptionViewItem& option) const { return QPoint(option.rect.left() + m_editIcon.width() + m_leftIconPadding, option.rect.center().y() - m_editIcon.height() / 2); } void ItemButtonsDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyledItemDelegate::paint(painter, option, index); if (!index.model()->index(0, 0, index).isValid() && (option.state & QStyle::State_MouseOver)) { painter->drawPixmap(GetEditPosition(option), m_editIcon); } } bool ItemButtonsDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) { if (!index.model()->index(0, 0, index).isValid() && event->type() == QEvent::MouseButtonRelease) { QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); QRect editButtonRect = m_editIcon.rect().translated(GetEditPosition(option)); QRect resultsButtonRect = m_editIcon.rect().translated(GetResultsPosition(option)); if (editButtonRect.contains(mouseEvent->pos())) { Q_EMIT EditButtonClicked(index); } else if (resultsButtonRect.contains(mouseEvent->pos())) { Q_EMIT ResultsButtonClicked(index); } } return QStyledItemDelegate::editorEvent(event, model, option, index); } /////////////////////// // UnitTestComponent /////////////////////// void UnitTestComponent::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context); if (serializeContext) { serializeContext->Class<UnitTestComponent, GraphCanvas::GraphCanvasPropertyComponent>() ->Version(0) ; AZ::EditContext* editContext = serializeContext->GetEditContext(); if (editContext) { editContext->Class<UnitTestComponent>("Unit Test", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "Properties") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &UnitTestComponent::GetTitle) ; } } } AZ::Entity* UnitTestComponent::CreateUnitTestEntity() { AZ::Entity* entity = aznew AZ::Entity("UnitTestHelper"); entity->CreateComponent<UnitTestComponent>(); return entity; } UnitTestComponent::UnitTestComponent() : m_componentTitle("UnitTest") { } AZStd::string_view UnitTestComponent::GetTitle() { return m_componentTitle; } ///////////////////////// // UnitTestContextMenu ///////////////////////// UnitTestContextMenu::UnitTestContextMenu(UnitTestDockWidget* dockWidget, AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry* sourceEntry) : QMenu() { AZ::Uuid sourceUuid = sourceEntry->GetSourceUuid(); AZStd::string sourceDisplayName = sourceEntry->GetDisplayName().toUtf8().data(); if (dockWidget->widgetActive) { QAction* runAction = new QAction(QObject::tr("Run this test"), this); runAction->setToolTip(QObject::tr("Run this Test only.")); runAction->setStatusTip(QObject::tr("Run this Test only.")); QObject::connect(runAction, &QAction::triggered, [dockWidget, sourceUuid]() { AZStd::vector<AZ::Uuid> scriptUuids; scriptUuids.push_back(sourceUuid); dockWidget->RunTests(scriptUuids); } ); addAction(runAction); if (dockWidget->m_filter->HasTestResults(sourceUuid)) { QAction* consoleAction = new QAction(QObject::tr("View test results"), this); consoleAction->setToolTip(QObject::tr("Read Console Results for this Test.")); consoleAction->setStatusTip(QObject::tr("Read Console Results for this Test.")); QObject::connect(consoleAction, &QAction::triggered, [dockWidget, sourceUuid, sourceDisplayName]() { dockWidget->OpenTestResults(sourceUuid, sourceDisplayName); } ); addAction(consoleAction); } } QAction* openAction = new QAction(QObject::tr("Edit script"), this); openAction->setToolTip(QObject::tr("Open this Test in the Script Canvas Editor.")); openAction->setStatusTip(QObject::tr("Open this Test in the Script Canvas Editor.")); QObject::connect(openAction, &QAction::triggered, [dockWidget, sourceUuid]() { dockWidget->OpenScriptInEditor(sourceUuid); } ); addAction(openAction); } //////////////////////// // UnitTestDockWidget //////////////////////// UnitTestDockWidget::UnitTestDockWidget(QWidget* parent /*= nullptr*/) : AzQtComponents::StyledDockWidget(parent) , m_ui(new Ui::UnitTestDockWidget()) , widgetActive(true) , m_itemButtonsDelegate(new ItemButtonsDelegate(this)) { m_ui->setupUi(this); UnitTestWidgetNotificationBus::Handler::BusConnect(); m_ui->searchFilter->setClearButtonEnabled(true); QObject::connect(m_ui->searchFilter, &QLineEdit::textChanged, this, &UnitTestDockWidget::OnQuickFilterChanged); QObject::connect(m_ui->searchFilter, &QLineEdit::returnPressed, this, &UnitTestDockWidget::OnReturnPressed); m_filterTimer.setInterval(250); m_filterTimer.setSingleShot(true); m_filterTimer.stop(); QObject::connect(&m_filterTimer, &QTimer::timeout, this, &UnitTestDockWidget::UpdateSearchFilter); m_ui->testsTree->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_ui->testsTree, &QWidget::customContextMenuRequested, this, &UnitTestDockWidget::OnContextMenuRequested); connect(m_ui->closeResults, &QPushButton::clicked, this, &UnitTestDockWidget::OnCloseResultsButton); m_filter = m_ui->testsTree->m_filter; m_ui->testsTree->setItemDelegateForColumn(0, m_itemButtonsDelegate); QObject::connect(m_itemButtonsDelegate, &ItemButtonsDelegate::EditButtonClicked, this, &UnitTestDockWidget::OnEditButtonClicked); QObject::connect(m_itemButtonsDelegate, &ItemButtonsDelegate::ResultsButtonClicked, this, &UnitTestDockWidget::OnResultsButtonClicked); if (UnitTestVerificationBus::GetTotalNumOfEventHandlers() == 0) { m_ui->testResultsOutput->setPlainText(QString("WARNING: Functionality of this Widget has been limited - Script Canvas Testing Gem is not loaded!")); m_ui->runButton->setDisabled(true); widgetActive = false; } else { m_ui->consoleOutput->hide(); connect(m_ui->runButton, &QPushButton::clicked, this, &UnitTestDockWidget::OnStartTestsButton); connect(m_ui->testsTree, &QAbstractItemView::doubleClicked, this, &UnitTestDockWidget::OnRowDoubleClicked); } } UnitTestDockWidget::~UnitTestDockWidget() { GraphCanvas::AssetEditorNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); UnitTestWidgetNotificationBus::Handler::BusDisconnect(); delete m_itemButtonsDelegate; } void UnitTestDockWidget::OnCheckStateCountChange(const int count) { m_ui->label->setText(QString("Selected %1 test(s).").arg(count)); } void UnitTestDockWidget::OnContextMenuRequested(const QPoint& pos) { QModelIndex index = m_ui->testsTree->indexAt(pos); QModelIndex sourceIndex = m_filter->mapToSource(index); if (sourceIndex.isValid()) { AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry = static_cast<AzToolsFramework::AssetBrowser::AssetBrowserEntry*>(sourceIndex.internalPointer()); if (entry->GetEntryType() == AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Source) { UnitTestContextMenu menu(this, static_cast<AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry*>(entry)); menu.exec(m_ui->testsTree->viewport()->mapToGlobal(pos)); } } } void UnitTestDockWidget::OnRowDoubleClicked(QModelIndex index) { QModelIndex sourceIndex = m_filter->mapToSource(index); if (sourceIndex.isValid()) { AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry = static_cast<AzToolsFramework::AssetBrowser::AssetBrowserEntry*>(sourceIndex.internalPointer()); if (entry->GetEntryType() == AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Source) { AZStd::vector<AZ::Uuid> scriptUuids; scriptUuids.emplace_back(static_cast<AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry*>(entry)->GetSourceUuid()); RunTests(scriptUuids); } } } void UnitTestDockWidget::OnEditButtonClicked(QModelIndex index) { QModelIndex sourceIndex = m_filter->mapToSource(index); if (sourceIndex.isValid()) { AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry = static_cast<AzToolsFramework::AssetBrowser::AssetBrowserEntry*>(sourceIndex.internalPointer()); if (entry->GetEntryType() == AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Source) { AZ::Uuid sourceUuid = static_cast<AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry*>(entry)->GetSourceUuid(); OpenScriptInEditor(sourceUuid); } } } void UnitTestDockWidget::OnResultsButtonClicked(QModelIndex index) { QModelIndex sourceIndex = m_filter->mapToSource(index); if (sourceIndex.isValid()) { AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry = static_cast<AzToolsFramework::AssetBrowser::AssetBrowserEntry*>(sourceIndex.internalPointer()); if (entry->GetEntryType() == AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Source) { AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry* sourceEntry = static_cast<AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry*>(entry); AZ::Uuid sourceUuid = sourceEntry->GetSourceUuid(); AZStd::string sourceDisplayName = sourceEntry->GetDisplayName().toUtf8().data(); OpenTestResults(sourceUuid, sourceDisplayName); } } } QCheckBox* UnitTestDockWidget::GetEnabledCheckBox(ScriptCanvas::ExecutionMode mode) { switch (mode) { case ScriptCanvas::ExecutionMode::Interpreted: return m_ui->executionInterpretedEnabled; case ScriptCanvas::ExecutionMode::Native: return m_ui->executionNativeEnabled; default: AZ_Assert(false, "Unsupported type"); return nullptr; } } QLabel* UnitTestDockWidget::GetStatusLabel(ScriptCanvas::ExecutionMode mode) { switch (mode) { case ScriptCanvas::ExecutionMode::Interpreted: return m_ui->labelInterpretedStatus; case ScriptCanvas::ExecutionMode::Native: return m_ui->labelNativeStatus; default: AZ_Assert(false, "Unsupported type"); return nullptr; } } void UnitTestDockWidget::ClearSearchFilter() { { QSignalBlocker blocker(m_ui->searchFilter); m_ui->searchFilter->setText(""); } UpdateSearchFilter(); } void UnitTestDockWidget::UpdateSearchFilter() { m_ui->testsTree->SetSearchFilter(m_ui->searchFilter->userInputText()); } void UnitTestDockWidget::OnReturnPressed() { UpdateSearchFilter(); } void UnitTestDockWidget::OnQuickFilterChanged(const QString& text) { if(text.isEmpty()) { //If filter was cleared, update immediately UpdateSearchFilter(); return; } m_filterTimer.stop(); m_filterTimer.start(); } void UnitTestDockWidget::OnStartTestsButton() { AZStd::vector<AZ::Uuid> scriptUuids; m_filter->GetCheckedScriptsUuidsList(scriptUuids); ClearSearchFilter(); RunTests(scriptUuids); } void UnitTestDockWidget::OnCloseResultsButton() { m_ui->consoleOutput->hide(); } void UnitTestDockWidget::OpenScriptInEditor(AZ::Uuid sourceUuid) { AzToolsFramework::OpenViewPane(LyViewPane::ScriptCanvas); AZ::Data::AssetId sourceAssetId(sourceUuid, 0); AZ::Outcome<int, AZStd::string> openOutcome = AZ::Failure(AZStd::string()); GeneralRequestBus::BroadcastResult(openOutcome, &GeneralRequests::OpenScriptCanvasAssetId, sourceAssetId); if (!openOutcome) { AZ_Warning("Script Canvas", openOutcome, "%s", openOutcome.GetError().data()); } } void UnitTestDockWidget::OpenTestResults(AZ::Uuid sourceUuid, AZStd::string_view sourceDisplayName) { if (m_filter->HasTestResults(sourceUuid)) { m_ui->testResultsLabel->setText(QString("Test Results | %1").arg(sourceDisplayName.data())); m_ui->testResultsOutput->setPlainText(QString(m_filter->GetTestResult(sourceUuid)->m_consoleOutput.c_str())); m_ui->consoleOutput->show(); } } QString ModeToString(ScriptCanvas::ExecutionMode mode) { using namespace ScriptCanvas; switch (mode) { case ExecutionMode::Interpreted: return QString("Interpreted"); case ExecutionMode::Native: return QString("Native"); default: return QString("<invalid>"); } } bool UnitTestDockWidget::IsModeEnabled(ScriptCanvas::ExecutionMode mode) { return GetEnabledCheckBox(mode)->checkState() == Qt::Checked; } void UnitTestDockWidget::RunTests(const AZStd::vector<AZ::Uuid>& scriptUuids) { AZStd::vector<ScriptCanvas::ExecutionMode> activeModes; auto executionModes = { ExecutionMode::Interpreted, ExecutionMode::Native }; for (auto mode : executionModes) { if (IsModeEnabled(mode)) { activeModes.push_back(mode); } else { GetStatusLabel(mode)->setText(ModeToString(mode) + QString(" not running")); } } if (activeModes.empty() || scriptUuids.empty()) { m_ui->consoleOutput->hide(); m_filter->FlushLatestTestRun(); return; } else { AZ::SystemTickBus::Handler::BusConnect(); m_ui->label->setText(QString("Starting %1 tests.").arg(scriptUuids.size())); m_filter->FlushLatestTestRun(); m_filter->TestsStart(); m_ui->consoleOutput->hide(); for (size_t modeIndex = 0; modeIndex < activeModes.size(); ++modeIndex) { auto mode = activeModes[modeIndex]; GetStatusLabel(mode)->setText(QString("Starting %1 tests.").arg(scriptUuids.size())); for (const AZ::Uuid& scriptUuid : scriptUuids) { const SourceAssetBrowserEntry* sourceBrowserEntry = SourceAssetBrowserEntry::GetSourceByUuid(scriptUuid); if (sourceBrowserEntry == nullptr) { AZ_Error("Script Canvas", false, "The source asset file with ID: %s was not found", scriptUuid.ToString<AZStd::string>().c_str()); continue; } AZ::Data::AssetInfo assetInfo; if (AssetHelpers::GetAssetInfo(sourceBrowserEntry->GetFullPath(), assetInfo)) { auto asset = AZ::Data::AssetManager::Instance().GetAsset(assetInfo.m_assetId, azrtti_typeid<ScriptCanvasAsset>(), AZ::Data::AssetLoadBehavior::PreLoad); asset.BlockUntilLoadComplete(); if (asset.IsReady()) { RunTestGraph(asset, mode); } } } } } } void UnitTestDockWidget::OnTestsComplete() { AZ::SystemTickBus::Handler::BusDisconnect(); QString testCompletionString; const int nativeMode = static_cast<int>(ExecutionMode::Native); if (m_testMetrics[nativeMode].m_graphsTested > 0) { testCompletionString = ModeToString(ExecutionMode::Native); testCompletionString += QString(": "); testCompletionString += QString("Attempted %1 test(s) - %2 Succeeded, %3 Failed, %4 Failed to Compile") .arg(m_testMetrics[nativeMode].m_graphsTested) .arg(m_testMetrics[nativeMode].m_success) .arg(m_testMetrics[nativeMode].m_failures) .arg(m_testMetrics[nativeMode].m_compilationFailures); GetStatusLabel(ExecutionMode::Native)->setText(testCompletionString); } const int interpretedMode = static_cast<int>(ExecutionMode::Interpreted); if (m_testMetrics[interpretedMode].m_graphsTested > 0) { testCompletionString = ModeToString(ExecutionMode::Interpreted); testCompletionString += QString(": "); testCompletionString += QString("Attempted %1 test(s) - %2 Succeeded, %3 Failed, %4 Failed to Compile") .arg(m_testMetrics[interpretedMode].m_graphsTested) .arg(m_testMetrics[interpretedMode].m_success) .arg(m_testMetrics[interpretedMode].m_failures) .arg(m_testMetrics[interpretedMode].m_compilationFailures); GetStatusLabel(ExecutionMode::Interpreted)->setText(testCompletionString); } m_filter->TestsEnd(); m_ui->label->setText(QString("Finished")); m_testMetrics[nativeMode].Clear(); m_testMetrics[interpretedMode].Clear(); } void UnitTestDockWidget::RunTestGraph(AZ::Data::Asset<AZ::Data::AssetData> asset, ScriptCanvas::ExecutionMode mode) { Reporter reporter; UnitTestWidgetNotificationBus::Broadcast(&UnitTestWidgetNotifications::OnTestStart, asset.GetId().m_guid); ScriptCanvasExecutionBus::BroadcastResult(reporter, &ScriptCanvasExecutionRequests::RunAssetGraph, asset, mode); UnitTestResult testResult; UnitTestVerificationBus::BroadcastResult(testResult, &UnitTestVerificationRequests::Verify, reporter); UnitTestWidgetNotificationBus::Broadcast(&UnitTestWidgetNotifications::OnTestResult, asset.GetId().m_guid, testResult); m_pendingTests.Add(asset.GetId(), mode); ++m_testMetrics[static_cast<int>(mode)].m_graphsTested; if (testResult.m_compiled) { if (testResult.m_completed) { ++m_testMetrics[static_cast<int>(mode)].m_success; } else { ++m_testMetrics[static_cast<int>(mode)].m_failures; } } else { ++m_testMetrics[static_cast<int>(mode)].m_compilationFailures; } m_pendingTests.Complete(asset.GetId(), mode); } void UnitTestDockWidget::OnSystemTick() { if (m_pendingTests.IsFinished()) { OnTestsComplete(); } } void UnitTestDockWidget::PendingTests::Add(AZ::Data::AssetId assetId, ExecutionMode mode) { m_pendingTests.push_back(AZStd::make_pair(assetId, mode)); } void UnitTestDockWidget::PendingTests::Complete(AZ::Data::AssetId assetId, ExecutionMode mode) { AZStd::erase_if(m_pendingTests, [assetId, mode](const AZStd::pair<AZ::Data::AssetId, ExecutionMode>& pending) { return (assetId == pending.first && mode == pending.second); }); } bool UnitTestDockWidget::PendingTests::IsFinished() const { return m_pendingTests.empty(); } }
36.598131
176
0.631427
[ "vector", "model", "3d" ]
61450b804b09d752e1be5f6d71dd80f3f8bbbd52
10,169
cpp
C++
CarreGameEngine/CarreGameEngine/src/GameControlEngine.cpp
CordellSmith/ICT397Carre
5241a01f6443df8296344ae79e34bc1b1ac08441
[ "MIT" ]
1
2018-03-13T06:16:47.000Z
2018-03-13T06:16:47.000Z
CarreGameEngine/CarreGameEngine/src/GameControlEngine.cpp
CordellSmith/ICT397Carre
5241a01f6443df8296344ae79e34bc1b1ac08441
[ "MIT" ]
3
2018-03-29T15:31:15.000Z
2018-05-15T05:54:55.000Z
CarreGameEngine/CarreGameEngine/src/GameControlEngine.cpp
CordellSmith/ICT397Carre
5241a01f6443df8296344ae79e34bc1b1ac08441
[ "MIT" ]
null
null
null
#include "..\headers\GameControlEngine.h" #include "GL/glew.h" int randPositions[20]; int randRotations[20]; const int GameControlEngine::RunEngine() { Initialize(); GameLoop(); // NOTE: return 0 automatically calls ~GameControlEngine() which calls Destroy() // This results in a crash on the second run through when trying to access/delete data already deleted //Destroy(); return 0; } void GameControlEngine::Initialize() { // Initialize from script ScriptManager::Instance().LoadWindowInitLua(ScreenWidth, ScreenHeight, screenTitle, fullScreen); ScriptManager::Instance().LoadCamInitLua( m_camera->GetPosition(), m_camera->GetYaw(), m_camera->GetPitch(), m_camera->GetFov(), m_camera->GetNearPlane(), m_camera->GetFarPlane()); ScriptManager::Instance().LoadModelsInitLua(m_allModelsData, m_modelsData); ScriptManager::Instance().LoadHeightmapsInitLua(m_allHeightmapsData, m_heightmapsData); // Exit if error creating window if (!m_windowManager || m_windowManager->Initialize(ScreenWidth, ScreenHeight, screenTitle, fullScreen) != 0) exit(-1); // Create viewport glViewport(0, 0, ScreenWidth, ScreenHeight); // Enable depth testing glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Initialize gameworld m_gameWorld = new GameWorld(); // Initialize camera perspective and position m_camera->SetPerspective(glm::radians(m_camera->GetFov()), ScreenWidth / (float)ScreenHeight, m_camera->GetNearPlane(), m_camera->GetFarPlane()); m_camera->PositionCamera(m_camera->GetPosition().x, m_camera->GetPosition().y, m_camera->GetPosition().z, m_camera->GetYaw(), glm::radians(m_camera->GetPitch())); // Create new player player = new Player("Player"); /**********************************Loading of all heightfields at once**************************************/ // Get iterator to start of heightfields map std::unordered_map<std::string, HeightmapsData>::iterator itHeightfields = m_allHeightmapsData.begin(); // BruteForce variable Bruteforce* bfHeightfield; // Initialize all heightfields in map while (itHeightfields != m_allHeightmapsData.end()) { // Create new BruteForce bfHeightfield = new Bruteforce((*itHeightfields).second.modelScales[0], (*itHeightfields).second.modelScales[1], (*itHeightfields).second.modelScales[2]); // Initialize data from map and push to terrains vector bfHeightfield->LoadHeightfield((*itHeightfields).second.filePath, (*itHeightfields).second.fileSize); bfHeightfield->GenerateTerrain(TextureManager::Instance().GetTextureID((*itHeightfields).second.texFilePath), (*itHeightfields).second.texFilePath); bfHeightfield->SetPosition(glm::vec3((*itHeightfields).second.modelPositions[0], (*itHeightfields).second.modelPositions[1], (*itHeightfields).second.modelPositions[2])); m_terrains.push_back(bfHeightfield); // Move camera to be on top of terrain if ((*itHeightfields).first == "terrain") { //m_camera->SetPosition(glm::vec3(m_camera->GetPosition().x, bfHeightfield->GetAverageHeight(m_camera->GetPosition().x, m_camera->GetPosition().z), m_camera->GetPosition().z)); } // Increment iterator itHeightfields++; } /**********************************Loading of all heightfields at once**************************************/ // Pass camera into gameworld m_gameWorld->SetCamera(m_camera); // Initialize asset factory m_assetFactory = new GameAssetFactory(); // Initialize physics engine m_physicsWorld = new PhysicsEngine(); /* When creating .raw files in Gimp. Make sure the file is Grey-scale when creating and when exporting, make sure to select raw image format (.data) and Planar (RRR GGG BBB). Then you can just rename the .data extension to .raw and its all good to go! */ /********************Loading of all models at once*******************/ // Create asset IGameAsset* modelAsset; //std::vector<ComputerAI*> m_allAI; ComputerAI* modelAI; // Asset xyz scale and pos float assetScaleXYZ[3]; float assetPosXYZ[3]; // Get iterator to start of models map std::unordered_map<std::string, ModelsData>::iterator itModels = m_allModelsData.begin(); // Loop through map until all models created while (itModels != m_allModelsData.end()) { // For each different type of model that isn't the player model if ((*itModels).first != "player") { // For each model of same type for (int k = 0; k < (*itModels).second.modelPositions.size(); k++) { // Get scales for (int j = 0; j < (*itModels).second.modelScales[k].size(); j++) { assetScaleXYZ[j] = (*itModels).second.modelScales[k][j]; } // Get positions for (int j = 0; j < (*itModels).second.modelPositions[k].size(); j++) { assetPosXYZ[j] = (*itModels).second.modelPositions[k][j]; } // Create name asset data and add to asset map modelAsset = m_assetFactory->CreateAsset(ASS_OBJECT, (*itModels).first); modelAsset->LoadFromFilePath((*itModels).second.filePath); modelAsset->AddTexutre(TextureManager::Instance().GetTextureID((*itModels).second.texFilePath), (*itModels).second.texFilePath); modelAsset->SetScale(glm::vec3(assetScaleXYZ[0], assetScaleXYZ[1], assetScaleXYZ[2])); modelAsset->SetPosition(glm::vec3(assetPosXYZ[0], assetPosXYZ[1], assetPosXYZ[2])); // If AI model, make AI for it if ((*itModels).second.isAI[k]) { // Create new computerAI and push to vector storing them modelAI = new ComputerAI(glm::vec3((*itModels).second.modelPositions[k][0], (*itModels).second.modelPositions[k][1], (*itModels).second.modelPositions[k][2])); m_allAI.push_back(modelAI); modelAsset->SetAI(modelAI); std::cout << "Model loaded" << std::endl; } m_assetFactory->AddAsset(modelAsset); } } // Player model else if ((*itModels).first == "player") { for (int k = 0; k < (*itModels).second.modelPositions.size(); k++) { // Get scales for (int j = 0; j < (*itModels).second.modelScales[k].size(); j++) { assetScaleXYZ[j] = (*itModels).second.modelScales[k][j]; } // Get positions for (int j = 0; j < (*itModels).second.modelPositions[k].size(); j++) { assetPosXYZ[j] = (*itModels).second.modelPositions[k][j]; } } // Initialize player model player->LoadFromFilePath((*itModels).second.filePath); player->SetPosition(glm::vec3(assetPosXYZ[0], assetPosXYZ[1], assetPosXYZ[2])); player->SetScale(glm::vec3(assetScaleXYZ[0], assetScaleXYZ[1], assetScaleXYZ[2])); } // Increment iterator itModels++; } /********************Loading of all models at once*******************/ m_windowManager->GetInputManager()->SetPlayer(player); /********************AI Testing*******************/ /*ComputerAI* p = new ComputerAI(); for (int i = 0; i < 1000; i++) p->Update(); getchar();*/ /********************AI Testing*******************/ for (int i = 0; i < 15; i++) { int randNum1 = rand() % (6000 - 0 + 1) + 0; int randNum2 = rand() % (360 - 1 + 1) + 1; randPositions[i] = randNum1; randRotations[i] = randNum2; } // Physics engine initialization InitializePhysics(); // Initialize the game world, pass in terrain, assets and physics engine *** Can be reworked *** m_gameWorld->SetTerrains(m_terrains); m_gameWorld->Init(player, m_assetFactory->GetAssets()); m_gameWorld->SetAI(m_allAI); m_gameWorld->SetPhysicsWorld(m_physicsWorld, m_collisionBodyPos); } void GameControlEngine::GameLoop() { while (m_windowManager->ProcessInput(true)) { // Use our TimeManager singleton to calculate our framerate every frame TimeManager::Instance().CalculateFrameRate(true); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Update the game world m_gameWorld->Update(); // Swap buffers m_windowManager->SwapTheBuffers(); } } float RandomPos() { return rand() % (4000 - 0 + 1) + 0; } void GameControlEngine::InitializePhysics() { // Create camera rigid body to collide with objects glm::vec3 camerPos(player->GetPosition()); btVector3 bt_cameraPos(camerPos.x, camerPos.y, camerPos.z); m_physicsWorld->CreatePlayerControlledRigidBody(bt_cameraPos); m_collisionBodyPos.push_back(bt_cameraPos); // Add player (taxi) to the rigid bodies glm::vec3 playerPos(m_camera->GetPosition()); btVector3 bt_playerPos(playerPos.x, playerPos.y, playerPos.z); m_collisionBodyPos.push_back(bt_playerPos); int i = 1; int numOfRocks = 10; int numOfKnights = 20; // Loop through map and add all assets to the collision body list std::multimap<std::string, IGameAsset*>::const_iterator itr; for (itr = m_assetFactory->GetAssets().begin(); itr != m_assetFactory->GetAssets().end(); itr++) { btVector3 randomPos; float tempX, tempY, tempZ; if (itr->second->GetAssetName() == "knight") { for (int j = 0; j < numOfKnights; j++) { tempX = itr->second->GetPosition().x + RandomPos(); tempZ = itr->second->GetPosition().z + RandomPos(); tempY = m_terrains[0]->GetAverageHeight(tempX, tempZ) + 100; randomPos = btVector3(tempX, tempY, tempZ); m_physicsWorld->CreateStaticRigidBody(randomPos, "knight"); m_collisionBodyPos.push_back(randomPos); } } if (itr->second->GetAssetName() == "rock") { for (int j = 0; j < numOfRocks; j++) { tempX = itr->second->GetPosition().x + RandomPos(); tempZ = itr->second->GetPosition().z + RandomPos(); tempY = m_terrains[0]->GetAverageHeight(tempX, tempZ) + 100; randomPos = btVector3(tempX, tempY, tempZ); m_physicsWorld->CreateStaticRigidBody(randomPos, "rock"); m_collisionBodyPos.push_back(randomPos); } } } // *** Can this be changed to the terrain mesh? *** // Create static rigid body (floor) //m_physicsWorld->CreateStaticRigidBody(); //m_collisionBodyPos->push_back(btVector3(0.0, 0.0, 0.0)); // Activate all rigid body objects m_physicsWorld->ActivateAllObjects(); } void GameControlEngine::Destroy() { // Destroy game world m_gameWorld->Destroy(); // Delete window if (m_windowManager) { m_windowManager->Destroy(); delete m_windowManager; m_windowManager = nullptr; } // Delete camera if (m_camera) { delete m_camera; m_camera = nullptr; } }
31.977987
179
0.682466
[ "mesh", "vector", "model" ]
614611f91ef222bf5b648adad15732437e84d70e
3,359
hpp
C++
nheqminer/3rdparty/boost/compute/algorithm/inner_product.hpp
EuroLine/nheqminer
81c7ef889bb502d16f7d1e7ef020d0592f8af945
[ "MIT" ]
886
2016-10-20T20:59:59.000Z
2022-03-12T07:47:52.000Z
ios/Pods/boost-for-react-native/boost/compute/algorithm/inner_product.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
369
2016-10-21T07:42:54.000Z
2020-11-19T10:49:29.000Z
ios/Pods/boost-for-react-native/boost/compute/algorithm/inner_product.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
534
2016-10-20T21:00:00.000Z
2022-03-29T10:02:27.000Z
//---------------------------------------------------------------------------// // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com> // // 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 // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #ifndef BOOST_COMPUTE_ALGORITHM_INNER_PRODUCT_HPP #define BOOST_COMPUTE_ALGORITHM_INNER_PRODUCT_HPP #include <boost/compute/system.hpp> #include <boost/compute/functional.hpp> #include <boost/compute/command_queue.hpp> #include <boost/compute/algorithm/accumulate.hpp> #include <boost/compute/container/vector.hpp> #include <boost/compute/iterator/transform_iterator.hpp> #include <boost/compute/iterator/zip_iterator.hpp> #include <boost/compute/functional/detail/unpack.hpp> namespace boost { namespace compute { /// Returns the inner product of the elements in the range /// [\p first1, \p last1) with the elements in the range beginning /// at \p first2. template<class InputIterator1, class InputIterator2, class T> inline T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, command_queue &queue = system::default_queue()) { typedef typename std::iterator_traits<InputIterator1>::value_type input_type; ptrdiff_t n = std::distance(first1, last1); return ::boost::compute::accumulate( ::boost::compute::make_transform_iterator( ::boost::compute::make_zip_iterator( boost::make_tuple(first1, first2) ), detail::unpack(multiplies<input_type>()) ), ::boost::compute::make_transform_iterator( ::boost::compute::make_zip_iterator( boost::make_tuple(last1, first2 + n) ), detail::unpack(multiplies<input_type>()) ), init, queue ); } /// \overload template<class InputIterator1, class InputIterator2, class T, class BinaryAccumulateFunction, class BinaryTransformFunction> inline T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryAccumulateFunction accumulate_function, BinaryTransformFunction transform_function, command_queue &queue = system::default_queue()) { typedef typename std::iterator_traits<InputIterator1>::value_type value_type; size_t count = detail::iterator_range_size(first1, last1); vector<value_type> result(count, queue.get_context()); transform(first1, last1, first2, result.begin(), transform_function, queue); return ::boost::compute::accumulate(result.begin(), result.end(), init, accumulate_function, queue); } } // end compute namespace } // end boost namespace #endif // BOOST_COMPUTE_ALGORITHM_INNER_PRODUCT_HPP
35.734043
81
0.592438
[ "vector", "transform" ]
61464c9af9c307250025faa98c814eadc6fb8c08
18,249
cc
C++
atom/browser/native_window_win.cc
cybernetics/atom-shell
66ab12738931b7ea971f9f109264f1b0cbe2eac8
[ "MIT" ]
1
2019-04-22T08:48:46.000Z
2019-04-22T08:48:46.000Z
atom/browser/native_window_win.cc
cybernetics/atom-shell
66ab12738931b7ea971f9f109264f1b0cbe2eac8
[ "MIT" ]
null
null
null
atom/browser/native_window_win.cc
cybernetics/atom-shell
66ab12738931b7ea971f9f109264f1b0cbe2eac8
[ "MIT" ]
null
null
null
// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/native_window_win.h" #include <shobjidl.h> #include <string> #include <vector> #include "atom/browser/api/atom_api_menu.h" #include "atom/browser/ui/win/menu_2.h" #include "atom/browser/ui/win/native_menu_win.h" #include "atom/common/draggable_region.h" #include "atom/common/options_switches.h" #include "base/strings/utf_string_conversions.h" #include "base/win/scoped_comptr.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "native_mate/dictionary.h" #include "ui/gfx/image/image.h" #include "ui/gfx/path.h" #include "ui/base/models/simple_menu_model.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/native_widget_win.h" #include "ui/views/window/client_view.h" #include "ui/views/window/native_frame_view.h" namespace atom { namespace { const int kResizeInsideBoundsSize = 5; const int kResizeAreaCornerSize = 16; // Returns true if |possible_parent| is a parent window of |child|. bool IsParent(gfx::NativeView child, gfx::NativeView possible_parent) { if (!child) return false; if (::GetWindow(child, GW_OWNER) == possible_parent) return true; gfx::NativeView parent = ::GetParent(child); while (parent) { if (possible_parent == parent) return true; parent = ::GetParent(parent); } return false; } // Wrapper of NativeWidgetWin to handle WM_MENUCOMMAND messages, which are // triggered by window menus. class MenuCommandNativeWidget : public views::NativeWidgetWin { public: explicit MenuCommandNativeWidget(NativeWindowWin* delegate) : views::NativeWidgetWin(delegate->window()), delegate_(delegate) {} virtual ~MenuCommandNativeWidget() {} protected: virtual bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) OVERRIDE { if (message == WM_MENUCOMMAND) { delegate_->OnMenuCommand(w_param, reinterpret_cast<HMENU>(l_param)); *result = 0; return true; } else { return false; } } private: NativeWindowWin* delegate_; DISALLOW_COPY_AND_ASSIGN(MenuCommandNativeWidget); }; class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, NativeWindowWin* contents_view) : views::ClientView(widget, contents_view) { } virtual ~NativeWindowClientView() {} virtual bool CanClose() OVERRIDE { static_cast<NativeWindowWin*>(contents_view())->CloseWebContents(); return false; } private: DISALLOW_COPY_AND_ASSIGN(NativeWindowClientView); }; class NativeWindowFrameView : public views::NativeFrameView { public: explicit NativeWindowFrameView(views::Widget* frame, NativeWindowWin* shell) : NativeFrameView(frame), shell_(shell) { } virtual ~NativeWindowFrameView() {} virtual gfx::Size GetMinimumSize() OVERRIDE { return shell_->GetMinimumSize(); } virtual gfx::Size GetMaximumSize() OVERRIDE { return shell_->GetMaximumSize(); } private: NativeWindowWin* shell_; DISALLOW_COPY_AND_ASSIGN(NativeWindowFrameView); }; class NativeWindowFramelessView : public views::NonClientFrameView { public: explicit NativeWindowFramelessView(views::Widget* frame, NativeWindowWin* shell) : frame_(frame), shell_(shell) { } virtual ~NativeWindowFramelessView() {} // views::NonClientFrameView implementations: virtual gfx::Rect NativeWindowFramelessView::GetBoundsForClientView() const OVERRIDE { return bounds(); } virtual gfx::Rect NativeWindowFramelessView::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const OVERRIDE { gfx::Rect window_bounds = client_bounds; // Enforce minimum size (1, 1) in case that client_bounds is passed with // empty size. This could occur when the frameless window is being // initialized. if (window_bounds.IsEmpty()) { window_bounds.set_width(1); window_bounds.set_height(1); } return window_bounds; } virtual int NonClientHitTest(const gfx::Point& point) OVERRIDE { if (frame_->IsFullscreen()) return HTCLIENT; // Check the frame first, as we allow a small area overlapping the contents // to be used for resize handles. bool can_ever_resize = frame_->widget_delegate() ? frame_->widget_delegate()->CanResize() : false; // Don't allow overlapping resize handles when the window is maximized or // fullscreen, as it can't be resized in those states. int resize_border = frame_->IsMaximized() || frame_->IsFullscreen() ? 0 : kResizeInsideBoundsSize; int frame_component = GetHTComponentForFrame(point, resize_border, resize_border, kResizeAreaCornerSize, kResizeAreaCornerSize, can_ever_resize); if (frame_component != HTNOWHERE) return frame_component; // Check for possible draggable region in the client area for the frameless // window. if (shell_->draggable_region() && shell_->draggable_region()->contains(point.x(), point.y())) return HTCAPTION; int client_component = frame_->client_view()->NonClientHitTest(point); if (client_component != HTNOWHERE) return client_component; // Caption is a safe default. return HTCAPTION; } virtual void GetWindowMask(const gfx::Size& size, gfx::Path* window_mask) OVERRIDE {} virtual void ResetWindowControls() OVERRIDE {} virtual void UpdateWindowIcon() OVERRIDE {} virtual void UpdateWindowTitle() OVERRIDE {} // views::View implementations: virtual gfx::Size NativeWindowFramelessView::GetPreferredSize() OVERRIDE { gfx::Size pref = frame_->client_view()->GetPreferredSize(); gfx::Rect bounds(0, 0, pref.width(), pref.height()); return frame_->non_client_view()->GetWindowBoundsForClientBounds( bounds).size(); } virtual gfx::Size GetMinimumSize() OVERRIDE { return shell_->GetMinimumSize(); } virtual gfx::Size GetMaximumSize() OVERRIDE { return shell_->GetMaximumSize(); } private: views::Widget* frame_; NativeWindowWin* shell_; DISALLOW_COPY_AND_ASSIGN(NativeWindowFramelessView); }; } // namespace NativeWindowWin::NativeWindowWin(content::WebContents* web_contents, const mate::Dictionary& options) : NativeWindow(web_contents, options), window_(new views::Widget), web_view_(inspectable_web_contents_view()->GetView()), use_content_size_(false), resizable_(true) { options.Get(switches::kResizable, &resizable_); views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); params.delegate = this; params.native_widget = new MenuCommandNativeWidget(this); params.remove_standard_frame = !has_frame_; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; window_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_NATIVE); window_->Init(params); views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this); int width = 800, height = 600; options.Get(switches::kWidth, &width); options.Get(switches::kHeight, &height); gfx::Size size(width, height); options.Get(switches::kUseContentSize, &use_content_size_); if (has_frame_ && use_content_size_) ClientAreaSizeToWindowSize(&size); window_->CenterWindow(size); window_->UpdateWindowIcon(); OnViewWasResized(); } NativeWindowWin::~NativeWindowWin() { views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this); } void NativeWindowWin::Close() { window_->Close(); } void NativeWindowWin::CloseImmediately() { window_->CloseNow(); } void NativeWindowWin::Move(const gfx::Rect& bounds) { window_->SetBounds(bounds); } void NativeWindowWin::Focus(bool focus) { if (focus) window_->Activate(); else window_->Deactivate(); } bool NativeWindowWin::IsFocused() { return window_->IsActive(); } void NativeWindowWin::Show() { window_->Show(); } void NativeWindowWin::Hide() { window_->Hide(); } void NativeWindowWin::Maximize() { window_->Maximize(); } void NativeWindowWin::Unmaximize() { window_->Restore(); } bool NativeWindowWin::IsMaximized() { return window_->IsMaximized(); } bool NativeWindowWin::IsVisible() { return window_->IsVisible(); } void NativeWindowWin::Minimize() { window_->Minimize(); } void NativeWindowWin::Restore() { window_->Restore(); } void NativeWindowWin::SetFullscreen(bool fullscreen) { window_->SetFullscreen(fullscreen); } bool NativeWindowWin::IsFullscreen() { return window_->IsFullscreen(); } void NativeWindowWin::SetSize(const gfx::Size& size) { window_->SetSize(size); } gfx::Size NativeWindowWin::GetSize() { return window_->GetWindowBoundsInScreen().size(); } void NativeWindowWin::SetContentSize(const gfx::Size& size) { gfx::Size resized(size); ClientAreaSizeToWindowSize(&resized); SetSize(resized); } gfx::Size NativeWindowWin::GetContentSize() { return window_->GetClientAreaBoundsInScreen().size(); } void NativeWindowWin::SetMinimumSize(const gfx::Size& size) { minimum_size_ = size; } gfx::Size NativeWindowWin::GetMinimumSize() { return minimum_size_; } void NativeWindowWin::SetMaximumSize(const gfx::Size& size) { maximum_size_ = size; } gfx::Size NativeWindowWin::GetMaximumSize() { return maximum_size_; } void NativeWindowWin::SetResizable(bool resizable) { resizable_ = resizable; // WS_MAXIMIZEBOX => Maximize/Minimize button // WS_THICKFRAME => Resize handle DWORD style = ::GetWindowLong(GetNativeWindow(), GWL_STYLE); if (resizable) style |= WS_MAXIMIZEBOX | WS_THICKFRAME; else style &= ~(WS_MAXIMIZEBOX | WS_THICKFRAME); ::SetWindowLong(GetNativeWindow(), GWL_STYLE, style); } bool NativeWindowWin::IsResizable() { return resizable_; } void NativeWindowWin::SetAlwaysOnTop(bool top) { window_->SetAlwaysOnTop(top); } bool NativeWindowWin::IsAlwaysOnTop() { DWORD style = ::GetWindowLong(window_->GetNativeView(), GWL_EXSTYLE); return style & WS_EX_TOPMOST; } void NativeWindowWin::Center() { window_->CenterWindow(GetSize()); } void NativeWindowWin::SetPosition(const gfx::Point& position) { window_->SetBounds(gfx::Rect(position, GetSize())); } gfx::Point NativeWindowWin::GetPosition() { return window_->GetWindowBoundsInScreen().origin(); } void NativeWindowWin::SetTitle(const std::string& title) { title_ = UTF8ToUTF16(title); window_->UpdateWindowTitle(); } std::string NativeWindowWin::GetTitle() { return UTF16ToUTF8(title_); } void NativeWindowWin::FlashFrame(bool flash) { window_->FlashFrame(flash); } void NativeWindowWin::SetSkipTaskbar(bool skip) { base::win::ScopedComPtr<ITaskbarList> taskbar; if (FAILED(taskbar.CreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER)) || FAILED(taskbar->HrInit())) return; if (skip) taskbar->DeleteTab(GetNativeWindow()); else taskbar->AddTab(GetNativeWindow()); } void NativeWindowWin::SetKiosk(bool kiosk) { SetFullscreen(kiosk); } bool NativeWindowWin::IsKiosk() { return IsFullscreen(); } gfx::NativeWindow NativeWindowWin::GetNativeWindow() { return window_->GetNativeView(); } void NativeWindowWin::OnMenuCommand(int position, HMENU menu) { DCHECK(menu_); menu_->wrapper()->OnMenuCommand(position, menu); } void NativeWindowWin::SetMenu(ui::MenuModel* menu_model) { menu_.reset(new atom::Menu2(menu_model, true)); menu_->UpdateStates(); ::SetMenu(GetNativeWindow(), menu_->GetNativeMenu()); RegisterAccelerators(); // Resize the window so SetMenu won't change client area size. if (use_content_size_) { gfx::Size size = GetSize(); size.set_height(size.height() + GetSystemMetrics(SM_CYMENU)); SetSize(size); } } void NativeWindowWin::UpdateDraggableRegions( const std::vector<DraggableRegion>& regions) { if (has_frame_) return; SkRegion* draggable_region = new SkRegion; // By default, the whole window is non-draggable. We need to explicitly // include those draggable regions. for (std::vector<DraggableRegion>::const_iterator iter = regions.begin(); iter != regions.end(); ++iter) { const DraggableRegion& region = *iter; draggable_region->op( region.bounds.x(), region.bounds.y(), region.bounds.right(), region.bounds.bottom(), region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op); } draggable_region_.reset(draggable_region); OnViewWasResized(); } void NativeWindowWin::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (event.type == WebKit::WebInputEvent::RawKeyDown) { ui::Accelerator accelerator( static_cast<ui::KeyboardCode>(event.windowsKeyCode), content::GetModifiersFromNativeWebKeyboardEvent(event)); if (GetFocusManager()->ProcessAccelerator(accelerator)) { return; } } // Any unhandled keyboard/character messages should be defproced. // This allows stuff like F10, etc to work correctly. DefWindowProc(event.os_event.hwnd, event.os_event.message, event.os_event.wParam, event.os_event.lParam); } void NativeWindowWin::Layout() { DCHECK(web_view_); web_view_->SetBounds(0, 0, width(), height()); OnViewWasResized(); } void NativeWindowWin::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (details.is_add && details.child == this) AddChildView(web_view_); } bool NativeWindowWin::AcceleratorPressed( const ui::Accelerator& accelerator) { return accelerator_util::TriggerAcceleratorTableCommand( &accelerator_table_, accelerator); } void NativeWindowWin::DeleteDelegate() { NotifyWindowClosed(); } views::View* NativeWindowWin::GetInitiallyFocusedView() { return inspectable_web_contents_view()->GetWebView(); } bool NativeWindowWin::CanResize() const { return resizable_; } bool NativeWindowWin::CanMaximize() const { return resizable_; } string16 NativeWindowWin::GetWindowTitle() const { return title_; } bool NativeWindowWin::ShouldHandleSystemCommands() const { return true; } gfx::ImageSkia NativeWindowWin::GetWindowAppIcon() { if (icon_) return *(icon_->ToImageSkia()); else return gfx::ImageSkia(); } gfx::ImageSkia NativeWindowWin::GetWindowIcon() { return GetWindowAppIcon(); } views::Widget* NativeWindowWin::GetWidget() { return window_.get(); } const views::Widget* NativeWindowWin::GetWidget() const { return window_.get(); } views::ClientView* NativeWindowWin::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, this); } views::NonClientFrameView* NativeWindowWin::CreateNonClientFrameView( views::Widget* widget) { if (has_frame_) return new NativeWindowFrameView(widget, this); return new NativeWindowFramelessView(widget, this); } void NativeWindowWin::OnNativeFocusChange(gfx::NativeView focused_before, gfx::NativeView focused_now) { gfx::NativeView this_window = GetWidget()->GetNativeView(); if (IsParent(focused_now, this_window)) return; if (focused_now == this_window) NotifyWindowFocus(); else if (focused_before == this_window) NotifyWindowBlur(); } void NativeWindowWin::ClientAreaSizeToWindowSize(gfx::Size* size) { gfx::Size window = window_->GetWindowBoundsInScreen().size(); gfx::Size client = window_->GetClientAreaBoundsInScreen().size(); size->set_width(size->width() + window.width() - client.width()); size->set_height(size->height() + window.height() - client.height()); } void NativeWindowWin::OnViewWasResized() { // Set the window shape of the RWHV. gfx::Size sz = web_view_->size(); int height = sz.height(), width = sz.width(); gfx::Path path; path.addRect(0, 0, width, height); SetWindowRgn(web_contents()->GetView()->GetNativeView(), path.CreateNativeRegion(), 1); SkRegion* rgn = new SkRegion; if (!window_->IsFullscreen() && !window_->IsMaximized()) { if (draggable_region()) rgn->op(*draggable_region(), SkRegion::kUnion_Op); if (!has_frame_ && CanResize()) { rgn->op(0, 0, width, kResizeInsideBoundsSize, SkRegion::kUnion_Op); rgn->op(0, 0, kResizeInsideBoundsSize, height, SkRegion::kUnion_Op); rgn->op(width - kResizeInsideBoundsSize, 0, width, height, SkRegion::kUnion_Op); rgn->op(0, height - kResizeInsideBoundsSize, width, height, SkRegion::kUnion_Op); } } content::WebContents* web_contents = GetWebContents(); if (web_contents->GetRenderViewHost()->GetView()) web_contents->GetRenderViewHost()->GetView()->SetClickthroughRegion(rgn); } void NativeWindowWin::RegisterAccelerators() { views::FocusManager* focus_manager = GetFocusManager(); accelerator_table_.clear(); focus_manager->UnregisterAccelerators(this); accelerator_util::GenerateAcceleratorTable(&accelerator_table_, menu_->model()); accelerator_util::AcceleratorTable::const_iterator iter; for (iter = accelerator_table_.begin(); iter != accelerator_table_.end(); ++iter) { focus_manager->RegisterAccelerator( iter->first, ui::AcceleratorManager::kNormalPriority, this); } } // static NativeWindow* NativeWindow::Create(content::WebContents* web_contents, const mate::Dictionary& options) { return new NativeWindowWin(web_contents, options); } } // namespace atom
28.648352
79
0.701518
[ "shape", "vector", "model" ]
61490d428712d4bae4867a55f5180bc2b7719aa8
4,428
cc
C++
components/browsing_data/core/counters/passwords_counter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/browsing_data/core/counters/passwords_counter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/browsing_data/core/counters/passwords_counter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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 "components/browsing_data/core/counters/passwords_counter.h" #include <algorithm> #include <memory> #include <utility> #include "base/bind.h" #include "components/browsing_data/core/pref_names.h" #include "components/password_manager/core/browser/password_manager_util.h" #include "components/password_manager/core/browser/password_store.h" #include "components/sync/driver/sync_service.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "url/gurl.h" namespace { bool IsPasswordSyncEnabled(const syncer::SyncService* sync_service) { if (!sync_service) return false; return password_manager_util::GetPasswordSyncState(sync_service) != password_manager::SyncState::NOT_SYNCING; } } // namespace namespace browsing_data { // PasswordsCounter::PasswordsResult ---------------------------------- PasswordsCounter::PasswordsResult::PasswordsResult( const BrowsingDataCounter* source, BrowsingDataCounter::ResultInt value, bool sync_enabled, std::vector<std::string> domain_examples) : SyncResult(source, value, sync_enabled), domain_examples_(std::move(domain_examples)) {} PasswordsCounter::PasswordsResult::~PasswordsResult() {} PasswordsCounter::PasswordsCounter( scoped_refptr<password_manager::PasswordStore> store, syncer::SyncService* sync_service) : store_(store), sync_tracker_(this, sync_service) { DCHECK(store_); } PasswordsCounter::~PasswordsCounter() { store_->RemoveObserver(this); } void PasswordsCounter::OnInitialized() { sync_tracker_.OnInitialized(base::BindRepeating(&IsPasswordSyncEnabled)); store_->AddObserver(this); } const char* PasswordsCounter::GetPrefName() const { return browsing_data::prefs::kDeletePasswords; } void PasswordsCounter::Count() { CancelAllRequests(); domain_examples_.clear(); // TODO(msramek): We don't actually need the logins themselves, just their // count. Consider implementing |PasswordStore::CountAutofillableLogins|. // This custom request should also allow us to specify the time range, so that // we can use it to filter the login creation date in the database. store_->GetAutofillableLogins(this); } std::unique_ptr<PasswordsCounter::PasswordsResult> PasswordsCounter::MakeResult() { return std::make_unique<PasswordsCounter::PasswordsResult>( this, num_passwords_, is_sync_active(), domain_examples_); } void PasswordsCounter::OnGetPasswordStoreResults( std::vector<std::unique_ptr<autofill::PasswordForm>> results) { base::Time start = GetPeriodStart(); base::Time end = GetPeriodEnd(); results.erase( std::remove_if( results.begin(), results.end(), [start, end](const std::unique_ptr<autofill::PasswordForm>& form) { return (form->date_created < start || form->date_created >= end); }), results.end()); num_passwords_ = results.size(); std::sort(results.begin(), results.end(), [](const std::unique_ptr<autofill::PasswordForm>& a, const std::unique_ptr<autofill::PasswordForm>& b) { return a->times_used > b->times_used; }); std::vector<std::string> sorted_domains; for (const auto& result : results) { std::string domain = net::registry_controlled_domains::GetDomainAndRegistry( result->origin, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); if (domain.empty()) domain = result->origin.host(); sorted_domains.emplace_back(domain); } // Only consecutive duplicates are removed below. Since we're only listing two // example domains, this guarantees that the two examples given will not be // the same, but there may still be duplicate domains stored in the // sorted_domains vector. sorted_domains.erase( std::unique(sorted_domains.begin(), sorted_domains.end()), sorted_domains.end()); if (sorted_domains.size() > 0) { domain_examples_.emplace_back(sorted_domains[0]); } if (sorted_domains.size() > 1) { domain_examples_.emplace_back(sorted_domains[1]); } ReportResult(MakeResult()); } void PasswordsCounter::OnLoginsChanged( const password_manager::PasswordStoreChangeList& changes) { Restart(); } } // namespace browsing_data
34.59375
80
0.728094
[ "vector" ]
614af728cf8636a4ca1ddcd2b683cab91327aa13
324
cc
C++
leetcode/easy/2011.cc
yuriserka/cp02hero
89dfdf64247c8fd3a8da78aaa31405527a61c603
[ "MIT" ]
null
null
null
leetcode/easy/2011.cc
yuriserka/cp02hero
89dfdf64247c8fd3a8da78aaa31405527a61c603
[ "MIT" ]
null
null
null
leetcode/easy/2011.cc
yuriserka/cp02hero
89dfdf64247c8fd3a8da78aaa31405527a61c603
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/final-value-of-variable-after-performing-operations/ #include <bits/stdc++.h> using namespace std; class Solution { public: int finalValueAfterOperations(vector<string>& operations) { int x = 0; for (const auto& op : operations) (op[1] == '+') ? ++x : --x; return x; } };
23.142857
85
0.654321
[ "vector" ]
614d1459bbd874e26d63f82d0651b054d4f868d7
3,786
cpp
C++
leetcode/editor/cn/146-lru-cache.cpp
xutengx/data-structure
cdc2fa24000377357c4f2d6ece83261ff4213d4c
[ "MIT" ]
null
null
null
leetcode/editor/cn/146-lru-cache.cpp
xutengx/data-structure
cdc2fa24000377357c4f2d6ece83261ff4213d4c
[ "MIT" ]
null
null
null
leetcode/editor/cn/146-lru-cache.cpp
xutengx/data-structure
cdc2fa24000377357c4f2d6ece83261ff4213d4c
[ "MIT" ]
null
null
null
//请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。 // // 实现 LRUCache 类: // // // // // LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存 // int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。 // void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 //key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。 // // // 函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。 // // // // // // 示例: // // //输入 //["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"] //[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]] //输出 //[null, null, null, 1, null, -1, null, -1, 3, 4] // //解释 //LRUCache lRUCache = new LRUCache(2); //lRUCache.put(1, 1); // 缓存是 {1=1} //lRUCache.put(2, 2); // 缓存是 {1=1, 2=2} //lRUCache.get(1); // 返回 1 //lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3} //lRUCache.get(2); // 返回 -1 (未找到) //lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3} //lRUCache.get(1); // 返回 -1 (未找到) //lRUCache.get(3); // 返回 3 //lRUCache.get(4); // 返回 4 // // // // // 提示: // // // 1 <= capacity <= 3000 // 0 <= key <= 10000 // 0 <= value <= 10⁵ // 最多调用 2 * 10⁵ 次 get 和 put // // Related Topics 设计 哈希表 链表 双向链表 👍 1824 👎 0 #include "iostream" #include "cassert" #include "vector" #include "string" #include "functional" #include "unordered_map" #include "list" using namespace std; //leetcode submit region begin(Prohibit modification and deletion) class LRUCache { public: LRUCache(int capacity) { size = capacity; head->next = tail; tail->prev = head; } int get(int key) { if (map->count(key) == 0) { return -1; } ListNode *value = map->at(key); move2Head(value); return value->val; } void put(int key, int value) { // 已存在则更新 if (map->count(key) != 0) { ListNode *&pNode = map->at(key); pNode->val = value; move2Head(pNode); return; } // 已满则先删除 if (map->size() == size) { int k = removeTail(); map->erase(k); } // 加入 auto *node = new ListNode; node->key = key; node->val = value; move2Head(node); map->insert(unordered_map<int, ListNode *>::value_type(key, node)); } private: // 容量 int size; // 双向链表节点 struct ListNode { int key = -1; int val = -1; ListNode *prev = nullptr; ListNode *next = nullptr; }; // 链表头 ListNode *head = new ListNode; ListNode *tail = new ListNode; // hash map unordered_map<int, ListNode *> *map = new unordered_map<int, ListNode *>; void move2Head(ListNode *node) { ListNode *prevNode = node->prev; ListNode *nextNode = node->next; if (prevNode != nullptr && nextNode != nullptr) { prevNode->next = nextNode; nextNode->prev = prevNode; } ListNode *headNextNode = head->next; head->next = node; node->prev = head; node->next = headNextNode; headNextNode->prev = node; } int removeTail() { ListNode *node = tail->prev; ListNode *prevNode = node->prev; prevNode->next = tail; tail->prev = prevNode; return node->key; } }; /** * Your LRUCache object will be instantiated and called as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */ //leetcode submit region end(Prohibit modification and deletion) int main() { LRUCache solution(2); solution.put(2, 1); solution.put(1, 1); solution.put(2, 3); solution.put(4, 1); assert(solution.get(1) == -1); assert(solution.get(2) == 3); // return 0; }
21.634286
78
0.534073
[ "object", "vector" ]
614eba67c3233c8f520ed9b5ab0cf39e1063207c
1,157
cpp
C++
camera_projection_measurement.cpp
kamnxt/lab-pose-estimation
e48406afea91235c127cd9aa4ccbf8cb375182b5
[ "BSD-3-Clause" ]
null
null
null
camera_projection_measurement.cpp
kamnxt/lab-pose-estimation
e48406afea91235c127cd9aa4ccbf8cb375182b5
[ "BSD-3-Clause" ]
1
2022-03-18T07:57:36.000Z
2022-03-18T07:57:36.000Z
camera_projection_measurement.cpp
kamnxt/lab-pose-estimation
e48406afea91235c127cd9aa4ccbf8cb375182b5
[ "BSD-3-Clause" ]
2
2022-03-18T07:52:12.000Z
2022-03-18T08:08:59.000Z
#include "camera_projection_measurement.h" CameraProjectionMeasurement::CameraProjectionMeasurement( const Eigen::Vector2d& normalized_plane_point, const Eigen::Vector3d& world_point) : world_point_{world_point} , normalized_plane_point_{normalized_plane_point} { } LinearizedCameraProjectionMeasurement CameraProjectionMeasurement::linearize(const Sophus::SE3d& current_state) const { // TODO 7.1: Use current_state (T_w_c) and world_point_ (x_w) to predict x_c. // Transform world point to camera coordinate frame based on current state estimate. Eigen::Vector3d x_c_pred; // TODO 7.2: Use x_c_pred to predict x_n. // Predict normalized image coordinate based on current state estimate. Eigen::Vector2d x_n_pred; // Construct linearization object. LinearizedCameraProjectionMeasurement linearization; // TODO 7.3: Use normalized_plane_point_ to compute the measurement error. // Compute measurement error. linearization.b; // = ? // TODO 7.4: Use the predicted x_c_pred and x_n_pred to compute the measurement Jacobian. // Compute measurement Jacobian. linearization.A; // = ? return linearization; }
33.057143
117
0.773552
[ "object", "transform" ]
61516a713a5c882ce55c0596d2c01113c14c7af0
982
cpp
C++
src/gvertexarrayrender.cpp
wqking/gincu
dd9d83cc75561d873fc396d009436ba07219ff4d
[ "Apache-2.0" ]
51
2017-02-01T14:50:03.000Z
2022-01-14T11:19:51.000Z
src/gvertexarrayrender.cpp
wqking/gincu
dd9d83cc75561d873fc396d009436ba07219ff4d
[ "Apache-2.0" ]
null
null
null
src/gvertexarrayrender.cpp
wqking/gincu
dd9d83cc75561d873fc396d009436ba07219ff4d
[ "Apache-2.0" ]
9
2018-07-20T07:47:39.000Z
2020-10-31T16:26:08.000Z
#include "gincu/gvertexarrayrender.h" #include "gincu/grendercontext.h" namespace gincu { GVertexArrayRender::GVertexArrayRender() : primitive(), vertexArray(), texture() { } GVertexArrayRender::GVertexArrayRender(const GPrimitive primitive, const GVertexArray & vertexArray) : primitive(primitive), vertexArray(vertexArray), texture() { } GVertexArrayRender::GVertexArrayRender(const GPrimitive primitive, const GVertexArray & vertexArray, const GTexture & texture) : primitive(primitive), vertexArray(vertexArray), texture(texture) { } void drawRender(const GVertexArrayRender & render, GRenderContext * renderContext, const GMatrix44 & matrix, const GRenderInfo * renderInfo) { renderContext->draw(render.getVertexArray(), render.getPrimitive(), render.getTexture(), matrix, renderInfo); } GSize getRenderSize(const GVertexArrayRender & render) { return getSize(render.getVertexArray().getBoundingRect()); } } //namespace gincu
27.277778
141
0.757637
[ "render" ]
61541530f409ec7205c8d87830326f95b8df283a
404
cpp
C++
InterviewBit/Extras/AggressiveCows.cpp
CRAZYGEEKS04/competitive-programming-1
f27b8a718761b7bfeb8ff9e294398ca1a294cb5d
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
InterviewBit/Extras/AggressiveCows.cpp
gauravsingh58/competitive-programming
fa5548f435cdf2aa059e1d6ab733885790c6a592
[ "MIT" ]
1
2020-10-10T16:14:54.000Z
2020-10-10T16:14:54.000Z
InterviewBit/Extras/AggressiveCows.cpp
gauravsingh58/competitive-programming
fa5548f435cdf2aa059e1d6ab733885790c6a592
[ "MIT" ]
2
2021-01-23T14:35:48.000Z
2021-03-15T05:04:24.000Z
int Solution::solve(vector<int> &A, int B) { int n = A.size(); sort(A.begin(), A.end()); int ans = 0, lo = 0, hi = A[n - 1]; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int fi = A[0], temp = 1; for (int i = 1; i < n; i++) { if (A[i] - fi >= mid) { temp++; fi = A[i]; } } if (temp < B) { hi = mid - 1; } else { ans = mid; lo = mid + 1; } } return ans; }
16.16
44
0.415842
[ "vector" ]
6157b6c70d227c0c0b0fc0191fe0c0af79531b1e
4,526
cpp
C++
DSP/HW3/mydisambig.cpp
r07922003/NTU
4414b656643bc0079c12617190fa2a519d2331f8
[ "MIT" ]
null
null
null
DSP/HW3/mydisambig.cpp
r07922003/NTU
4414b656643bc0079c12617190fa2a519d2331f8
[ "MIT" ]
null
null
null
DSP/HW3/mydisambig.cpp
r07922003/NTU
4414b656643bc0079c12617190fa2a519d2331f8
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <stdio.h> #include <vector> #include "Ngram.h" using namespace std ; FILE *open_or_die( const char *filename, const char *ht ) { FILE *fp = fopen( filename, ht ); if( fp == NULL ){ perror(filename); exit(1); } return fp; } // Get P(W2 | W1) -- bigram double getBigramProb(const char *w1, const char *w2, Vocab &voc , Ngram &lm) { VocabIndex wid1 = voc.getIndex(w1); VocabIndex wid2 = voc.getIndex(w2); if (strcmp(w1, "<unk>") == 0){ wid1 = Vocab_None; } if(wid1 == Vocab_None) //OOV wid1 = voc.getIndex(Vocab_Unknown); if(wid2 == Vocab_None) //OOV wid2 = voc.getIndex(Vocab_Unknown); VocabIndex context[] = { wid1, Vocab_None }; return lm.wordProb( wid2, context); } int main(int argc, char *argv[]) { VocabIndex viterbi_map[8700][87]; int ch_0 = -93; // 注音的ch[0] int ch_1[37] = {116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -72, -71, -70, -85, -84, -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73}; vector<string> mapTable[37]; // save[八 匕 卜 不 卞 巴 比 丙 包 北 半 叭 布...]... //cmd: ./mydisambig -text testdata/$$i.txt -map $(TO) -lm $(LM) -order 2 result2/$$i.txt char *test_name = argv[2]; //get test file arguments char* map_name = argv[4]; //get map file arguments char* lm_name = argv[6]; //get lm file arguments int order = atoi(argv[8]); //get order num char* out_name =argv[9]; //get output file arguments ifstream file(test_name); //開啟testdata ifstream map(map_name); //開啟mapdata ofstream out(out_name); //ofstream out("output.txt"); //debug用 char ch[2]; //宣告國字兩個char string str; string cancel; //get ㄅ [八 匕 卜 不 卞 巴 比 丙 包 北 半 叭 布...] ㄅ後面的那些字------------------------------------------ while(map >> ch){ /*注音 int(ch[0])皆是-93 ch[1] 注音對照如下: ㄅ ㄆ ㄇ ㄈ ㄉ ㄊ ㄋ ㄌ ㄍ ㄎ ㄏ ㄐ ㄑ ㄒ ㄓ ㄔ ㄕ ㄖ ㄗ ㄘ ㄙ ㄧ ㄨ ㄩ ㄚ ㄛ ㄜ ㄝ ㄞ ㄟ ㄠ ㄡ ㄢ ㄣ ㄤ ㄥ ㄦ 116 117 118 119 120 121 122 123 124 125 126 -95 -94 -93 -92 -91 -90 -89 -88 -87 -86 -72 -71 -70 -85 -84 -83 -82 -81 -80 -79 -78 -77 -76 -75 -74 -73*/ //cout <<int(ch[0]) <<" " <<int(ch[1]) <<endl; if (int(ch[0]) == ch_0){ for (int i=0; i<37; i++){ if ((int)ch[1] == ch_1[i]){ getline(map,str); istringstream sss(str); string temp; while(sss >> temp){ mapTable[i].push_back(temp); } break; } } } else{ getline(map,cancel); } } /* debug//印出map for(int i=0;i<37;i++){ for(int j=0;j <mapTable[i].size();j++){ out <<mapTable[i][j]; } out <<endl; } */ map.close(); //-map 結束------------------------------------------------------------------------------------------------------- Vocab voc; Ngram lm( voc, order ); { File lmFile( lm_name, "r" ); lm.read(lmFile); lmFile.close(); } //------------------------------------------------------------------------------------------------------------------ char tmp[1000]; char *nowWord; while(file.getline(tmp, sizeof(tmp))){ istringstream sss(tmp); string temp; out <<"<s> "; while(sss >> temp){ if(int(temp[0])==ch_0 ){ for (int i=0; i<37; i++){ if ((int)temp[1] == ch_1[i]){ out << mapTable[i][0] <<" "; } } } else{ out <<temp <<" "; } } /* for(int i=0;i<sizeof(tmp);i++){ if(i==0){ out <<"<s> "; } if(tmp[i] != ' ' && tmp[i+1] != ' '){ if(int(tmp[i])==ch_0 ){ for (int j=0; j<37; j++){ if ((int)tmp[i+1] == ch_1[j]){ out << mapTable[j][0] <<" "; } } } } } */ out <<"</s>" <<endl; } }
32.561151
206
0.402121
[ "vector" ]
6158002b08c0c5c74dbaaeeb1d94a1a7388d350a
11,682
cpp
C++
torchrec/inference/src/BatchingQueue.cpp
samiwilf/torchrec
50ff0973d5d01ec80fe36ba5f1d524c92c799836
[ "BSD-3-Clause" ]
1
2022-03-07T09:06:11.000Z
2022-03-07T09:06:11.000Z
torchrec/inference/src/BatchingQueue.cpp
samiwilf/torchrec
50ff0973d5d01ec80fe36ba5f1d524c92c799836
[ "BSD-3-Clause" ]
null
null
null
torchrec/inference/src/BatchingQueue.cpp
samiwilf/torchrec
50ff0973d5d01ec80fe36ba5f1d524c92c799836
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and 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 "torchrec/inference/BatchingQueue.h" #include <chrono> #include <memory> #include <optional> #include <stdexcept> #include <string> #include <thread> #include <unordered_map> #include <ATen/Functions.h> // @manual #include <ATen/core/Dict.h> #include <ATen/core/interned_strings.h> #include <ATen/record_function.h> // @manual #include <c10/core/Device.h> #include <c10/core/DeviceType.h> #include <c10/cuda/CUDAFunctions.h> #include <c10/cuda/CUDAGuard.h> #include <c10/cuda/CUDAStream.h> #include <fmt/format.h> #include <folly/ExceptionString.h> #include <folly/Lazy.h> #include <folly/MPMCQueue.h> #include <folly/Range.h> #include <folly/executors/CPUThreadPoolExecutor.h> #include <folly/io/Cursor.h> #include <glog/logging.h> #include "torchrec/inference/Exception.h" #include "torchrec/inference/Observer.h" #include "torchrec/inference/ResourceManager.h" #include "torchrec/inference/Types.h" using namespace std::chrono_literals; DEFINE_bool( batching_queue_use_high_pri_stream, false, "Use high priority CUDA stream in batching"); namespace torchrec { namespace { std::chrono::milliseconds getTimeElapsedMS( std::chrono::steady_clock::time_point startTime) { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - startTime); } } // namespace size_t PredictionBatch::size() const { size_t size = 0; for (auto& iter : forwardArgs) { size += iter.value().storage().nbytes(); } return size; } BatchingQueue::BatchingQueue( std::vector<BatchQueueCb> cbs, const Config& config, int worldSize, std::unique_ptr<IBatchingQueueObserver> observer, std::shared_ptr<ResourceManager> resourceManager) : config_(config), cbs_(std::move(cbs)), stopping_(false), worldSize_(worldSize), observer_(std::move(observer)), resourceManager_(std::move(resourceManager)) { CHECK(observer_ != nullptr); for (const auto& [_, metadata] : config_.batchingMetadata) { if (batchingFuncs_.count(metadata.type) > 0) { continue; } batchingFuncs_[metadata.type] = TorchRecBatchingFuncRegistry()->Create(metadata.type); } for (int i = 0; i < worldSize_; i++) { auto queue = std::make_shared<folly::MPMCQueue<BatchingQueueEntry>>( folly::MPMCQueue<BatchingQueueEntry>(1000)); batchingQueues_.push_back(std::move(queue)); } rejectionExecutor_ = std::make_unique<folly::CPUThreadPoolExecutor>( config_.numExceptionThreads); batchingThread_ = std::thread([&] { folly::setThreadName("CreateBatch"); createBatch(); }); for (int i = 0; i < worldSize_; ++i) { for (int j = 0; j < config_.numMemPinnerThreads; ++j) { memPinnerThreads_.emplace_back([&, i, j] { c10::InferenceMode guard; folly::setThreadName(fmt::format("MemoryPinner-{}-GPU-{}", j, i)); pinMemory(i); }); } } } void BatchingQueue::add( std::shared_ptr<PredictionRequest> request, folly::Promise<std::unique_ptr<PredictionResponse>> promise) { CHECK_GT(request->batch_size, 0); const auto addedTime = std::chrono::steady_clock::now(); requestQueue_.withWLock([request = std::move(request), promise = std::move(promise), addedTime = addedTime](auto& queue) mutable { const auto batchSize = request->batch_size; queue.push(QueryQueueEntry{ std::move(request), RequestContext{batchSize, std::move(promise)}, addedTime}); }); } void BatchingQueue::stop() { stopping_ = true; // TODO: properly drain the queue before stopping the threads. batchingThread_.join(); for (auto& thread : memPinnerThreads_) { thread.join(); } } void BatchingQueue::createBatch() { std::optional<std::chrono::time_point<std::chrono::steady_clock>> startTime; size_t batchSize = 0; std::vector<std::shared_ptr<PredictionRequest>> requests; std::vector<RequestContext> contexts; int roundRobinIdx = 0; while (!stopping_) { bool full = false; requestQueue_.withWLock([&](auto& queue) { while (!queue.empty()) { auto& front = queue.front(); if (std::chrono::steady_clock::now() - front.addedTime >= config_.queueTimeout) { observer_->addBatchingQueueTimeoutCount(1); rejectionExecutor_->add( [promise = std::move(front.context.promise)]() mutable { handleRequestException(promise, "Batching queue timeout"); }); queue.pop(); continue; } if (!startTime) { startTime = front.addedTime; } if (batchSize + front.request->batch_size > config_.maxBatchSize) { full = true; break; } auto& context = contexts.emplace_back(std::move(front.context)); requests.push_back(std::move(front.request)); batchSize += requests.back()->batch_size; queue.pop(); } }); if (full || (startTime && (std::chrono::steady_clock::now() - *startTime >= config_.batchingInterval))) { batchingQueues_[roundRobinIdx++]->blockingWrite(BatchingQueueEntry{ .requests = std::move(requests), .contexts = std::move(contexts), .addedTime = *startTime}); observer_->addRequestsCount(requests.size()); observer_->recordBatchCreationLatency( getTimeElapsedMS(*startTime).count()); startTime.reset(); batchSize = 0; roundRobinIdx %= worldSize_; requests.clear(); contexts.clear(); } if (!full) { /* sleep override */ std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } } void BatchingQueue::pinMemory(int gpuIdx) { at::cuda::CUDAGuard deviceGuard(gpuIdx); at::cuda::CUDAStreamGuard streamGuard(at::cuda::getStreamFromPool( /* isHighPriority */ FLAGS_batching_queue_use_high_pri_stream)); if (config_.warmupFn) { config_.warmupFn(); } while (!stopping_) { BatchingQueueEntry entry; if (!batchingQueues_[gpuIdx]->tryReadUntil( std::chrono::steady_clock::now() + 10ms, entry)) { continue; } auto& requests = entry.requests; auto& contexts = entry.contexts; try { if (!requests.empty() || !contexts.empty()) { RECORD_USER_SCOPE("PinMemory"); // Combine data. size_t combinedBatchSize = 0; for (auto i : c10::irange(requests.size())) { combinedBatchSize += requests[i]->batch_size; } auto batchOffsetsLazy = folly::lazy<std::function<at::Tensor()>>([&]() -> at::Tensor { size_t batchSize = 0; auto batchOffsets = at::empty( {static_cast<long>(requests.size() + 1)}, at::TensorOptions().dtype(at::kInt).pinned_memory(true)); auto batchOffsetsAcc = batchOffsets.accessor<int32_t, 1>(); batchOffsetsAcc[0] = 0; for (auto i : c10::irange(requests.size())) { batchSize += requests[i]->batch_size; batchOffsetsAcc[i + 1] = batchSize; } return batchOffsets; }); auto batchItemsLazy = folly::lazy<std::function<at::Tensor()>>([&]() -> at::Tensor { auto batchItems = at::empty( {static_cast<int64_t>(combinedBatchSize)}, at::TensorOptions().dtype(at::kInt).pinned_memory(true)); auto batchItemsAcc = batchItems.accessor<int32_t, 1>(); auto batchOffsetsAcc = batchOffsetsLazy().accessor<int32_t, 1>(); for (auto i = 0; i < requests.size(); ++i) { auto start = batchOffsetsAcc[i]; auto end = batchOffsetsAcc[i + 1]; for (auto j = start; j < end; ++j) { batchItemsAcc[j] = i; } } return batchItems; }); c10::Dict<std::string, at::Tensor> forwardArgs; auto combineForwardArgs = [&](std::unordered_map<std::string, at::Tensor> map) { for (auto& [key, value] : map) { CHECK(!forwardArgs.contains(key)); forwardArgs.insert(key, std::move(value)); } }; auto elapsed = getTimeElapsedMS(entry.addedTime); observer_->recordBatchingQueueLatency(elapsed.count()); if (resourceManager_ != nullptr) { auto slack = std::chrono::duration_cast<std::chrono::milliseconds>( config_.queueTimeout - elapsed); auto gpuFree = slack.count() > 0 ? resourceManager_->occupyDevice(gpuIdx, slack) : false; if (!gpuFree) { // A device could not be chosen in time. Time out. observer_->addGPUBusyCount(1); rejectionExecutor_->add([ctxs = std::move(contexts)]() mutable { handleBatchException( ctxs, "All GPUs are busy. Batching queue timeout."); }); continue; } } // When resourceManagerGuard goes out of scope, the number of // oustanding batches associated with a gpu is decremented. Should be // defined before batching functions are called in case they throw // an exception. auto resourceManagerGuard = resourceManager_ != nullptr ? std::make_unique<ResourceManagerGuard>(resourceManager_, gpuIdx) : nullptr; for (auto& [featureName, metadata] : config_.batchingMetadata) { const auto batchingFuncStart = std::chrono::steady_clock::now(); combineForwardArgs(batchingFuncs_[metadata.type]->batch( featureName, requests, combinedBatchSize, batchOffsetsLazy, metadata.device == "cpu" ? c10::Device(c10::kCPU) : c10::Device(c10::kCUDA, gpuIdx), batchItemsLazy)); observer_->recordBatchingFuncLatency( getTimeElapsedMS(batchingFuncStart).count(), metadata.type); } // The batch is moved to the GPUExecutor, which can either // throw an exception or complete the batch. Move resourceManagerGuard // with the batch so when all references to the batch go to 0, // num outstanding requests for the gpu decrements. auto batch = std::make_shared<PredictionBatch>( combinedBatchSize, std::move(forwardArgs), std::move(contexts), std::move(resourceManagerGuard)); auto createEvent = [&]() { return Event( std::make_unique<at::cuda::CUDAEvent>( cudaEventBlockingSync | cudaEventDisableTiming) .release(), [](at::cuda::CUDAEvent* event) { delete event; }); }; batch->event = config_.eventCreationFn ? config_.eventCreationFn(gpuIdx) : createEvent(); batch->event->record(); observer_->observeBatchCompletion(batch->size(), batch->batchSize); cbs_[gpuIdx](batch); } } catch (const std::exception& ex) { LOG(FATAL) << "Error batching requests, ex: " << folly::exceptionStr(ex); } } } BatchingQueue::~BatchingQueue() { stop(); } } // namespace torchrec
33.282051
80
0.606317
[ "vector" ]
615ced0a0715b75d29dafd1352da84620eabd0c4
560
hh
C++
include/idf/UsbHagstromKEUSB36FS.hh
greck2908/IDF
0882cc35d88b96b0aea55e112060779654f040a6
[ "NASA-1.3" ]
84
2016-06-15T21:26:02.000Z
2022-03-12T15:09:57.000Z
include/idf/UsbHagstromKEUSB36FS.hh
greck2908/IDF
0882cc35d88b96b0aea55e112060779654f040a6
[ "NASA-1.3" ]
44
2016-10-19T17:35:01.000Z
2022-03-11T17:20:51.000Z
include/idf/UsbHagstromKEUSB36FS.hh
greck2908/IDF
0882cc35d88b96b0aea55e112060779654f040a6
[ "NASA-1.3" ]
46
2016-06-25T00:18:52.000Z
2019-12-19T11:13:15.000Z
/* PURPOSE: LIBRARY DEPENDENCIES: ( (idf/UsbHagstromKEUSB36FS.cpp) ) */ /** * @trick_parse{everything} * @trick_link_dependency{idf/UsbHagstromKEUSB36FS.cpp} */ #ifndef USB_HAGSTROM_KEUSB36FS_HH #define USB_HAGSTROM_KEUSB36FS_HH #include "idf/UsbDevice.hh" #include "idf/HagstromKEUSB36.hh" namespace idf { /** USB HagstromKEUSB36FS board */ class UsbHagstromKEUSB36FS : public UsbDevice, public HagstromKEUSB36 { public: /** constructor */ UsbHagstromKEUSB36FS(); void decode(const std::vector<unsigned char>& data); }; } #endif
15.555556
71
0.732143
[ "vector" ]
616203f5e279ca60aed1d3ad84de40f0ef442f14
11,770
cpp
C++
libs/bloom_filter/test/counting_bloom_filter-pass.cpp
tetzank/boost-bloom-filters
7c6717f403c041a092187568908f3661782ddb24
[ "BSL-1.0" ]
15
2016-10-18T16:05:37.000Z
2022-01-23T03:01:42.000Z
libs/bloom_filter/test/counting_bloom_filter-pass.cpp
tetzank/boost-bloom-filters
7c6717f403c041a092187568908f3661782ddb24
[ "BSL-1.0" ]
null
null
null
libs/bloom_filter/test/counting_bloom_filter-pass.cpp
tetzank/boost-bloom-filters
7c6717f403c041a092187568908f3661782ddb24
[ "BSL-1.0" ]
12
2016-04-15T18:17:24.000Z
2020-04-16T06:29:58.000Z
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Alejandro Cabrera 2011. // 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) // // See http://www.boost.org/libs/bloom_filter for documentation. // ////////////////////////////////////////////////////////////////////////////// #define BOOST_TEST_DYN_LINK 1 #define BOOST_TEST_MODULE "Boost Bloom Filter" 1 #include <boost/bloom_filter/counting_bloom_filter.hpp> #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include <boost/bloom_filter/detail/exceptions.hpp> #include <boost/cstdint.hpp> using boost::bloom_filters::counting_bloom_filter; using boost::bloom_filters::detail::bin_underflow_exception; using boost::bloom_filters::detail::bin_overflow_exception; using boost::bloom_filters::boost_hash; BOOST_AUTO_TEST_CASE(allBitsPerBinCompile) { counting_bloom_filter<size_t, 2, 1> bloom1; counting_bloom_filter<size_t, 2, 2> bloom2; counting_bloom_filter<size_t, 2, 4> bloom4; counting_bloom_filter<size_t, 2, 8> bloom8; counting_bloom_filter<size_t, 2, 16> bloom16; counting_bloom_filter<size_t, 2, 32> bloom32; } BOOST_AUTO_TEST_CASE(allReasonableBlockTypesCompile) { typedef boost::mpl::vector<boost_hash<int, 0> > default_hash; counting_bloom_filter<int, 2, 2, default_hash, unsigned char> a; counting_bloom_filter<int, 2, 2, default_hash, unsigned short> b; counting_bloom_filter<int, 2, 2, default_hash, unsigned int> c; counting_bloom_filter<int, 2, 2, default_hash, unsigned long> d; counting_bloom_filter<int, 2, 2, default_hash, size_t> e; counting_bloom_filter<int, 2, 2, default_hash, uint8_t> aa; counting_bloom_filter<int, 2, 2, default_hash, uint16_t> ab; counting_bloom_filter<int, 2, 2, default_hash, uint32_t> ac; counting_bloom_filter<int, 2, 2, default_hash, uintmax_t> ad; } BOOST_AUTO_TEST_CASE(defaultConstructor) { typedef boost::mpl::vector< boost_hash<int, 13>, boost_hash<int, 17>, boost_hash<int, 19> > BoostHashFunctions; counting_bloom_filter<int, 2> bloom1; counting_bloom_filter<int, 2, 1> bloom2; counting_bloom_filter<int, 2, 2, BoostHashFunctions> bloom3; counting_bloom_filter<int, 2, 4, BoostHashFunctions, unsigned char> bloom4; } BOOST_AUTO_TEST_CASE(countSingle) { counting_bloom_filter<int, 2> bloom; bloom.insert(1); BOOST_CHECK_EQUAL(bloom.count(), 1ul); bloom.remove(1); BOOST_CHECK_EQUAL(bloom.count(), 0ul); } #include <iostream> BOOST_AUTO_TEST_CASE(countMulti) { counting_bloom_filter<int, 100> bloom_default; counting_bloom_filter<int, 100, 1> bloom1; counting_bloom_filter<int, 100, 2> bloom2; counting_bloom_filter<int, 100, 8> bloom8; counting_bloom_filter<int, 100, 16> bloom16; counting_bloom_filter<int, 100, 32> bloom32; for (size_t i = 0; i < 100; ++i) { bloom_default.insert(i); bloom1.insert(i); bloom2.insert(i); bloom8.insert(i); bloom16.insert(i); bloom32.insert(i); } BOOST_CHECK_EQUAL(bloom_default.count(), 100ul); BOOST_CHECK_EQUAL(bloom1.count(), 100ul); BOOST_CHECK_EQUAL(bloom2.count(), 100ul); BOOST_CHECK_EQUAL(bloom8.count(), 100ul); BOOST_CHECK_EQUAL(bloom16.count(), 100ul); BOOST_CHECK_EQUAL(bloom32.count(), 100ul); for (size_t i = 0; i < 100; ++i) { bloom_default.insert(i); bloom2.insert(i); bloom8.insert(i); bloom16.insert(i); bloom32.insert(i); } BOOST_CHECK_EQUAL(bloom_default.count(), 100ul); BOOST_CHECK_EQUAL(bloom2.count(), 100ul); BOOST_CHECK_EQUAL(bloom8.count(), 100ul); BOOST_CHECK_EQUAL(bloom16.count(), 100ul); BOOST_CHECK_EQUAL(bloom32.count(), 100ul); for (size_t i = 0; i < 100; ++i) { bloom_default.remove(i); bloom2.remove(i); bloom8.remove(i); bloom16.remove(i); bloom32.remove(i); } BOOST_CHECK_EQUAL(bloom_default.count(), 100ul); BOOST_CHECK_EQUAL(bloom2.count(), 100ul); BOOST_CHECK_EQUAL(bloom8.count(), 100ul); BOOST_CHECK_EQUAL(bloom16.count(), 100ul); BOOST_CHECK_EQUAL(bloom32.count(), 100ul); for (size_t i = 0; i < 100; ++i) { bloom_default.remove(i); bloom1.remove(i); bloom2.remove(i); bloom8.remove(i); bloom16.remove(i); bloom32.remove(i); } BOOST_CHECK_EQUAL(bloom_default.count(), 0ul); BOOST_CHECK_EQUAL(bloom1.count(), 0ul); BOOST_CHECK_EQUAL(bloom2.count(), 0ul); BOOST_CHECK_EQUAL(bloom8.count(), 0ul); BOOST_CHECK_EQUAL(bloom16.count(), 0ul); BOOST_CHECK_EQUAL(bloom32.count(), 0ul); } BOOST_AUTO_TEST_CASE(rangeConstructor) { int elems[5] = {1,2,3,4,5}; counting_bloom_filter<int, 5> bloom(elems, elems+5); BOOST_CHECK_EQUAL(bloom.count(), 5ul); } #ifndef BOOST_NO_0X_HDR_INITIALIZER_LIST BOOST_AUTO_TEST_CASE(initListConstructor) { counting_bloom_filter<int, 5> bloom = {1,2,3,4,5}; BOOST_CHECK_EQUAL(bloom.count(), 5ul); } #endif BOOST_AUTO_TEST_CASE(copyConstructor) { int elems[5] = {1,2,3,4,5}; counting_bloom_filter<int, 5> bloom1(elems, elems+5); counting_bloom_filter<int, 5> bloom2(bloom1); BOOST_CHECK_EQUAL(bloom1.count(), bloom2.count()); } BOOST_AUTO_TEST_CASE(assignment) { counting_bloom_filter<int, 200> bloom1; counting_bloom_filter<int, 200> bloom2; for (size_t i = 0; i < 200; ++i) { bloom1.insert(i); BOOST_CHECK_EQUAL(bloom1.probably_contains(i), true); } bloom2 = bloom1; for (size_t i = 0; i < 200; ++i) { BOOST_CHECK_EQUAL(bloom2.probably_contains(i), true); } } BOOST_AUTO_TEST_CASE(bit_capacity) { counting_bloom_filter<size_t, 8> bloom_8; counting_bloom_filter<size_t, 256> bloom_256; counting_bloom_filter<size_t, 2048> bloom_2048; BOOST_CHECK_EQUAL(bloom_8.bit_capacity(), 8ul * bloom_8.bits_per_bin()); BOOST_CHECK_EQUAL(bloom_256.bit_capacity(), 256ul * bloom_256.bits_per_bin()); BOOST_CHECK_EQUAL(bloom_2048.bit_capacity(), 2048ul * bloom_2048.bits_per_bin()); } BOOST_AUTO_TEST_CASE(empty) { counting_bloom_filter<size_t, 2> bloom; BOOST_CHECK_EQUAL(bloom.empty(), true); bloom.insert(1); BOOST_CHECK_EQUAL(bloom.empty(), false); bloom.clear(); BOOST_CHECK_EQUAL(bloom.empty(), true); } BOOST_AUTO_TEST_CASE(numHashFunctions) { counting_bloom_filter<size_t, 1> bloom_1; counting_bloom_filter<size_t, 1, 1, boost::mpl::vector< boost_hash<size_t, 1>, boost_hash<size_t, 2> > > bloom_2; counting_bloom_filter<size_t, 1, 1, boost::mpl::vector< boost_hash<size_t, 1>, boost_hash<size_t, 2>, boost_hash<size_t, 3>, boost_hash<size_t, 4>, boost_hash<size_t, 5>, boost_hash<size_t, 6>, boost_hash<size_t, 7> > > bloom_7; BOOST_CHECK_EQUAL(bloom_1.num_hash_functions(), 1ul); BOOST_CHECK_EQUAL(bloom_2.num_hash_functions(), 2ul); BOOST_CHECK_EQUAL(bloom_7.num_hash_functions(), 7ul); } BOOST_AUTO_TEST_CASE(falsePositiveRate) { counting_bloom_filter<size_t, 64> bloom; BOOST_CHECK_EQUAL(bloom.false_positive_rate(), 0.0); bloom.insert(1); BOOST_CHECK_CLOSE(bloom.false_positive_rate(), 0.015504, .01); bloom.insert(2); BOOST_CHECK_CLOSE(bloom.false_positive_rate(), 0.030768, .01); bloom.insert(3); BOOST_CHECK_CLOSE(bloom.false_positive_rate(), 0.045794, .01); bloom.insert(4); BOOST_CHECK_CLOSE(bloom.false_positive_rate(), 0.060588, .01); bloom.insert(5); BOOST_CHECK_CLOSE(bloom.false_positive_rate(), 0.075151, .01); bloom.insert(6); BOOST_CHECK_CLOSE(bloom.false_positive_rate(), 0.089491, .01); for (size_t i = 7; i < 128; ++i) bloom.insert(i); BOOST_CHECK_GE(bloom.false_positive_rate(), 0.6); BOOST_CHECK_LE(bloom.false_positive_rate(), 1.0); } BOOST_AUTO_TEST_CASE(probably_contains) { counting_bloom_filter<size_t, 2> bloom; bloom.insert(1); BOOST_CHECK_EQUAL(bloom.probably_contains(1), true); BOOST_CHECK_EQUAL(bloom.count(), 1ul); } BOOST_AUTO_TEST_CASE(doesNotContain) { counting_bloom_filter<size_t, 2> bloom; BOOST_CHECK_EQUAL(bloom.probably_contains(1), false); } BOOST_AUTO_TEST_CASE(insertNoFalseNegatives) { counting_bloom_filter<size_t, 100> bloom; for (size_t i = 0; i < 100; ++i) { bloom.insert(i); BOOST_CHECK_EQUAL(bloom.probably_contains(i), true); } } BOOST_AUTO_TEST_CASE(insertOverflowExceptionThrown) { counting_bloom_filter<size_t, 2, 1> bloom; bool exception_occurred = false; bloom.insert(1); BOOST_CHECK_EQUAL(bloom.probably_contains(1), true); try { bloom.insert(1); } catch (bin_overflow_exception e) { exception_occurred = true; } BOOST_CHECK_EQUAL(exception_occurred, true); BOOST_CHECK_EQUAL(bloom.probably_contains(1), true); } BOOST_AUTO_TEST_CASE(removeUnderflowExceptionThrown) { counting_bloom_filter<size_t, 2, 1> bloom; bool exception_occurred = false; try { bloom.remove(1); } catch (bin_underflow_exception e) { exception_occurred = true; } BOOST_CHECK_EQUAL(exception_occurred, true); BOOST_CHECK_EQUAL(bloom.probably_contains(1), false); } BOOST_AUTO_TEST_CASE(insertOverflowException4bit) { counting_bloom_filter<size_t, 2> bloom; bool exception_occurred = false; try { for (size_t i = 0; i < (1ul << bloom.bits_per_bin()); ++i) bloom.insert(1); } catch (bin_overflow_exception e) { exception_occurred = true; } BOOST_CHECK_EQUAL(exception_occurred, true); BOOST_CHECK_EQUAL(bloom.probably_contains(1), true); } BOOST_AUTO_TEST_CASE(rangeInsert) { int elems[5] = {1,2,3,4,5}; counting_bloom_filter<size_t, 5> bloom; bloom.insert(elems, elems+5); BOOST_CHECK_EQUAL(bloom.count(), 5ul); } BOOST_AUTO_TEST_CASE(_remove) { counting_bloom_filter<size_t, 1> bloom; bloom.insert(1); bloom.remove(1); BOOST_CHECK_EQUAL(bloom.count(), 0ul); } BOOST_AUTO_TEST_CASE(removeMulti) { counting_bloom_filter<size_t, 100> bloom; for (size_t i = 0; i < 100; ++i) { bloom.insert(i); bloom.remove(i); BOOST_CHECK_EQUAL(bloom.count(), 0ul); } } BOOST_AUTO_TEST_CASE(rangeRemove) { size_t arr[] = {1,2,3,4,5}; counting_bloom_filter<size_t, 5> bloom; bloom.insert(arr, arr+5); bloom.remove(arr, arr+5); BOOST_CHECK_EQUAL(bloom.count(), 0ul); } BOOST_AUTO_TEST_CASE(clear) { counting_bloom_filter<size_t, 1000> bloom; for (size_t i = 0; i < 1000; ++i) bloom.insert(i); bloom.clear(); BOOST_CHECK_EQUAL(bloom.probably_contains(1), false); BOOST_CHECK_EQUAL(bloom.count(), 0ul); } struct SwapFixture { SwapFixture() { for (size_t i = 0; i < 5; ++i) elems[i] = i+1; bloom1.insert(elems, elems+2); bloom2.insert(elems+2, elems+5); } size_t elems[5]; counting_bloom_filter<size_t, 5> bloom1; counting_bloom_filter<size_t, 5> bloom2; }; BOOST_FIXTURE_TEST_CASE(memberSwap, SwapFixture) { bloom1.swap(bloom2); BOOST_CHECK_EQUAL(bloom1.count(), 3ul); BOOST_CHECK_EQUAL(bloom2.count(), 2ul); } BOOST_FIXTURE_TEST_CASE(globalSwap, SwapFixture) { swap(bloom1, bloom2); BOOST_CHECK_EQUAL(bloom1.count(), 3ul); BOOST_CHECK_EQUAL(bloom2.count(), 2ul); } struct PairwiseOpsFixture { PairwiseOpsFixture() {} counting_bloom_filter<size_t, 300> bloom1; counting_bloom_filter<size_t, 300> bloom2; counting_bloom_filter<size_t, 300> bloom_result; }; BOOST_FIXTURE_TEST_CASE(equalityOperator, PairwiseOpsFixture) { BOOST_CHECK_EQUAL(bloom1 == bloom2, true); bloom1.insert(1); BOOST_CHECK_EQUAL(bloom1 == bloom2, false); bloom2.insert(1); BOOST_CHECK_EQUAL(bloom1 == bloom2, true); } BOOST_FIXTURE_TEST_CASE(inequalityOperator, PairwiseOpsFixture) { BOOST_CHECK_EQUAL(bloom1 != bloom2, false); bloom1.insert(1); BOOST_CHECK_EQUAL(bloom1 != bloom2, true); bloom2.insert(1); BOOST_CHECK_EQUAL(bloom1 != bloom2, false); }
26.933638
78
0.715718
[ "vector" ]
616b66d6abedfebc5a7d0e0b8b9d4e9a19670f94
16,171
cpp
C++
tools/clang/lib/SPIRV/AlignmentSizeCalculator.cpp
ppuspu/DirectXShaderCompiler
cf789666578a1f8d56730ab7c4b2ca7d4c216beb
[ "NCSA" ]
1,095
2019-05-07T14:48:04.000Z
2022-03-30T04:29:58.000Z
tools/clang/lib/SPIRV/AlignmentSizeCalculator.cpp
ppuspu/DirectXShaderCompiler
cf789666578a1f8d56730ab7c4b2ca7d4c216beb
[ "NCSA" ]
2,214
2019-05-06T22:22:53.000Z
2022-03-31T19:38:50.000Z
tools/clang/lib/SPIRV/AlignmentSizeCalculator.cpp
ppuspu/DirectXShaderCompiler
cf789666578a1f8d56730ab7c4b2ca7d4c216beb
[ "NCSA" ]
269
2019-05-07T11:59:04.000Z
2022-03-30T08:41:50.000Z
//===--- AlignmentSizeCalculator.cpp -- Alignemnt And Size Calc --*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "AlignmentSizeCalculator.h" #include "clang/AST/Attr.h" namespace { /// The alignment for 4-component float vectors. constexpr uint32_t kStd140Vec4Alignment = 16u; /// Rounds the given value up to the given power of 2. inline uint32_t roundToPow2(uint32_t val, uint32_t pow2) { assert(pow2 != 0); return (val + pow2 - 1) & ~(pow2 - 1); } /// Returns true if the given vector type (of the given size) crosses the /// 4-component vector boundary if placed at the given offset. bool improperStraddle(clang::QualType type, int size, int offset) { assert(clang::spirv::isVectorType(type)); return size <= 16 ? offset / 16 != (offset + size - 1) / 16 : offset % 16 != 0; } } // end anonymous namespace namespace clang { namespace spirv { void AlignmentSizeCalculator::alignUsingHLSLRelaxedLayout( QualType fieldType, uint32_t fieldSize, uint32_t fieldAlignment, uint32_t *currentOffset) { QualType vecElemType = {}; const bool fieldIsVecType = isVectorType(fieldType, &vecElemType); // Adjust according to HLSL relaxed layout rules. // Aligning vectors as their element types so that we can pack a float // and a float3 tightly together. if (fieldIsVecType) { uint32_t scalarAlignment = 0; std::tie(scalarAlignment, std::ignore) = getAlignmentAndSize( vecElemType, SpirvLayoutRule::Void, /*isRowMajor*/ llvm::None, nullptr); if (scalarAlignment <= 4) fieldAlignment = scalarAlignment; } *currentOffset = roundToPow2(*currentOffset, fieldAlignment); // Adjust according to HLSL relaxed layout rules. // Bump to 4-component vector alignment if there is a bad straddle if (fieldIsVecType && improperStraddle(fieldType, fieldSize, *currentOffset)) { fieldAlignment = kStd140Vec4Alignment; *currentOffset = roundToPow2(*currentOffset, fieldAlignment); } } std::pair<uint32_t, uint32_t> AlignmentSizeCalculator::getAlignmentAndSize( QualType type, SpirvLayoutRule rule, llvm::Optional<bool> isRowMajor, uint32_t *stride) { // std140 layout rules: // 1. If the member is a scalar consuming N basic machine units, the base // alignment is N. // // 2. If the member is a two- or four-component vector with components // consuming N basic machine units, the base alignment is 2N or 4N, // respectively. // // 3. If the member is a three-component vector with components consuming N // basic machine units, the base alignment is 4N. // // 4. If the member is an array of scalars or vectors, the base alignment and // array stride are set to match the base alignment of a single array // element, according to rules (1), (2), and (3), and rounded up to the // base alignment of a vec4. The array may have padding at the end; the // base offset of the member following the array is rounded up to the next // multiple of the base alignment. // // 5. If the member is a column-major matrix with C columns and R rows, the // matrix is stored identically to an array of C column vectors with R // components each, according to rule (4). // // 6. If the member is an array of S column-major matrices with C columns and // R rows, the matrix is stored identically to a row of S X C column // vectors with R components each, according to rule (4). // // 7. If the member is a row-major matrix with C columns and R rows, the // matrix is stored identically to an array of R row vectors with C // components each, according to rule (4). // // 8. If the member is an array of S row-major matrices with C columns and R // rows, the matrix is stored identically to a row of S X R row vectors // with C components each, according to rule (4). // // 9. If the member is a structure, the base alignment of the structure is N, // where N is the largest base alignment value of any of its members, and // rounded up to the base alignment of a vec4. The individual members of // this substructure are then assigned offsets by applying this set of // rules recursively, where the base offset of the first member of the // sub-structure is equal to the aligned offset of the structure. The // structure may have padding at the end; the base offset of the member // following the sub-structure is rounded up to the next multiple of the // base alignment of the structure. // // 10. If the member is an array of S structures, the S elements of the array // are laid out in order, according to rule (9). // // This method supports multiple layout rules, all of them modifying the // std140 rules listed above: // // std430: // - Array base alignment and stride does not need to be rounded up to a // multiple of 16. // - Struct base alignment does not need to be rounded up to a multiple of 16. // // Relaxed std140/std430: // - Vector base alignment is set as its element type's base alignment. // // FxcCTBuffer: // - Vector base alignment is set as its element type's base alignment. // - Arrays/structs do not need to have padding at the end; arrays/structs do // not affect the base offset of the member following them. // - For typeNxM matrix, if M > 1, // - It must be alinged to 16 bytes. // - Its size must be (16 * (M - 1)) + N * sizeof(type). // - We have the same rule for column_major typeNxM and row_major typeMxN. // // FxcSBuffer: // - Vector/matrix/array base alignment is set as its element type's base // alignment. // - Struct base alignment is set as the maximum of its component's // alignment. // - Size of vector/matrix/array is set as the number of its elements times // the size of its element. // - Size of struct must be aligned to its alignment. const auto desugaredType = desugarType(type, &isRowMajor); if (desugaredType != type) { auto result = getAlignmentAndSize(desugaredType, rule, isRowMajor, stride); return result; } if (isEnumType(type)) type = astContext.IntTy; { // Rule 1 QualType ty = {}; if (isScalarType(type, &ty)) if (const auto *builtinType = ty->getAs<BuiltinType>()) switch (builtinType->getKind()) { case BuiltinType::Bool: case BuiltinType::Int: case BuiltinType::UInt: case BuiltinType::Float: return {4, 4}; case BuiltinType::Double: case BuiltinType::LongLong: case BuiltinType::ULongLong: return {8, 8}; case BuiltinType::Min12Int: case BuiltinType::Min16Int: case BuiltinType::Min16UInt: case BuiltinType::Min16Float: case BuiltinType::Min10Float: { if (spvOptions.enable16BitTypes) return {2, 2}; else return {4, 4}; } // the 'Half' enum always represents 16-bit floats. // int16_t and uint16_t map to Short and UShort. case BuiltinType::Short: case BuiltinType::UShort: case BuiltinType::Half: return {2, 2}; // 'HalfFloat' always represents 32-bit floats. case BuiltinType::HalfFloat: return {4, 4}; default: emitError("alignment and size calculation for type %0 unimplemented") << type; return {0, 0}; } } // FxcCTBuffer for typeNxM matrix where M > 1, // - It must be alinged to 16 bytes. // - Its size must be (16 * (M - 1)) + N * sizeof(type). // - We have the same rule for column_major typeNxM and row_major typeMxN. if (rule == SpirvLayoutRule::FxcCTBuffer && hlsl::IsHLSLMatType(type)) { uint32_t rowCount = 0, colCount = 0; hlsl::GetHLSLMatRowColCount(type, rowCount, colCount); if (!useRowMajor(isRowMajor, type)) std::swap(rowCount, colCount); if (colCount > 1) { auto elemType = hlsl::GetHLSLMatElementType(type); uint32_t alignment = 0, size = 0; std::tie(alignment, size) = getAlignmentAndSize(elemType, rule, isRowMajor, stride); alignment = roundToPow2(alignment * (rowCount == 3 ? 4 : rowCount), kStd140Vec4Alignment); *stride = alignment; return {alignment, 16 * (colCount - 1) + rowCount * size}; } } { // Rule 2 and 3 QualType elemType = {}; uint32_t elemCount = {}; if (isVectorType(type, &elemType, &elemCount)) { uint32_t alignment = 0, size = 0; std::tie(alignment, size) = getAlignmentAndSize(elemType, rule, isRowMajor, stride); // Use element alignment for fxc rules and VK_EXT_scalar_block_layout if (rule != SpirvLayoutRule::FxcCTBuffer && rule != SpirvLayoutRule::FxcSBuffer && rule != SpirvLayoutRule::Scalar) alignment = (elemCount == 3 ? 4 : elemCount) * size; return {alignment, elemCount * size}; } } { // Rule 5 and 7 QualType elemType = {}; uint32_t rowCount = 0, colCount = 0; if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) { uint32_t alignment = 0, size = 0; std::tie(alignment, size) = getAlignmentAndSize(elemType, rule, isRowMajor, stride); // Matrices are treated as arrays of vectors: // The base alignment and array stride are set to match the base alignment // of a single array element, according to rules 1, 2, and 3, and rounded // up to the base alignment of a vec4. bool rowMajor = useRowMajor(isRowMajor, type); const uint32_t vecStorageSize = rowMajor ? rowCount : colCount; if (rule == SpirvLayoutRule::FxcSBuffer || rule == SpirvLayoutRule::Scalar) { *stride = vecStorageSize * size; // Use element alignment for fxc structured buffers and // VK_EXT_scalar_block_layout return {alignment, rowCount * colCount * size}; } alignment *= (vecStorageSize == 3 ? 4 : vecStorageSize); if (rule == SpirvLayoutRule::GLSLStd140 || rule == SpirvLayoutRule::RelaxedGLSLStd140 || rule == SpirvLayoutRule::FxcCTBuffer) { alignment = roundToPow2(alignment, kStd140Vec4Alignment); } *stride = alignment; size = (rowMajor ? colCount : rowCount) * alignment; return {alignment, size}; } } // Rule 9 if (const auto *structType = type->getAs<RecordType>()) { bool hasBaseStructs = type->getAsCXXRecordDecl() && type->getAsCXXRecordDecl()->getNumBases() > 0; // Special case for handling empty structs, whose size is 0 and has no // requirement over alignment (thus 1). if (structType->getDecl()->field_empty() && !hasBaseStructs) return {1, 0}; uint32_t maxAlignment = 0; uint32_t structSize = 0; // If this struct is derived from some other structs, place an implicit // field at the very beginning for the base struct. if (const auto *cxxDecl = dyn_cast<CXXRecordDecl>(structType->getDecl())) { for (const auto base : cxxDecl->bases()) { uint32_t memberAlignment = 0, memberSize = 0; std::tie(memberAlignment, memberSize) = getAlignmentAndSize(base.getType(), rule, isRowMajor, stride); if (rule == SpirvLayoutRule::RelaxedGLSLStd140 || rule == SpirvLayoutRule::RelaxedGLSLStd430 || rule == SpirvLayoutRule::FxcCTBuffer) { alignUsingHLSLRelaxedLayout(base.getType(), memberSize, memberAlignment, &structSize); } else { structSize = roundToPow2(structSize, memberAlignment); } // The base alignment of the structure is N, where N is the largest // base alignment value of any of its members... maxAlignment = std::max(maxAlignment, memberAlignment); structSize += memberSize; } } for (const auto *field : structType->getDecl()->fields()) { uint32_t memberAlignment = 0, memberSize = 0; std::tie(memberAlignment, memberSize) = getAlignmentAndSize(field->getType(), rule, isRowMajor, stride); if (rule == SpirvLayoutRule::RelaxedGLSLStd140 || rule == SpirvLayoutRule::RelaxedGLSLStd430 || rule == SpirvLayoutRule::FxcCTBuffer) { alignUsingHLSLRelaxedLayout(field->getType(), memberSize, memberAlignment, &structSize); } else { structSize = roundToPow2(structSize, memberAlignment); } // Reset the current offset to the one specified in the source code // if exists. It's debatable whether we should do sanity check here. // If the developers want manually control the layout, we leave // everything to them. if (const auto *offsetAttr = field->getAttr<VKOffsetAttr>()) { structSize = offsetAttr->getOffset(); } // The base alignment of the structure is N, where N is the largest // base alignment value of any of its members... maxAlignment = std::max(maxAlignment, memberAlignment); structSize += memberSize; } if (rule == SpirvLayoutRule::Scalar) { // A structure has a scalar alignment equal to the largest scalar // alignment of any of its members in VK_EXT_scalar_block_layout. return {maxAlignment, structSize}; } if (rule == SpirvLayoutRule::GLSLStd140 || rule == SpirvLayoutRule::RelaxedGLSLStd140 || rule == SpirvLayoutRule::FxcCTBuffer) { // ... and rounded up to the base alignment of a vec4. maxAlignment = roundToPow2(maxAlignment, kStd140Vec4Alignment); } if (rule != SpirvLayoutRule::FxcCTBuffer) { // The base offset of the member following the sub-structure is rounded // up to the next multiple of the base alignment of the structure. structSize = roundToPow2(structSize, maxAlignment); } return {maxAlignment, structSize}; } // Rule 4, 6, 8, and 10 if (const auto *arrayType = astContext.getAsConstantArrayType(type)) { const auto elemCount = arrayType->getSize().getZExtValue(); uint32_t alignment = 0, size = 0; std::tie(alignment, size) = getAlignmentAndSize(arrayType->getElementType(), rule, isRowMajor, stride); if (rule == SpirvLayoutRule::FxcSBuffer || rule == SpirvLayoutRule::Scalar) { *stride = size; // Use element alignment for fxc structured buffers and // VK_EXT_scalar_block_layout return {alignment, size * elemCount}; } if (rule == SpirvLayoutRule::GLSLStd140 || rule == SpirvLayoutRule::RelaxedGLSLStd140 || rule == SpirvLayoutRule::FxcCTBuffer) { // The base alignment and array stride are set to match the base alignment // of a single array element, according to rules 1, 2, and 3, and rounded // up to the base alignment of a vec4. alignment = roundToPow2(alignment, kStd140Vec4Alignment); } if (rule == SpirvLayoutRule::FxcCTBuffer) { // In fxc cbuffer/tbuffer packing rules, arrays does not affect the data // packing after it. But we still need to make sure paddings are inserted // internally if necessary. *stride = roundToPow2(size, alignment); size += *stride * (elemCount - 1); } else { // Need to round size up considering stride for scalar types size = roundToPow2(size, alignment); *stride = size; // Use size instead of alignment here for Rule 10 size *= elemCount; // The base offset of the member following the array is rounded up to the // next multiple of the base alignment. size = roundToPow2(size, alignment); } return {alignment, size}; } emitError("alignment and size calculation for type %0 unimplemented") << type; return {0, 0}; } } // namespace spirv } // namespace clang
40.126551
80
0.648383
[ "vector" ]
616de389df06c66866fdede7a800631109593708
26,594
cpp
C++
inetsrv/msmq/src/setup/mqupgrd/creatobj.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/msmq/src/setup/mqupgrd/creatobj.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/msmq/src/setup/mqupgrd/creatobj.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999 Microsoft Corporation Module Name: creatobj.cpp Abstract: Create msmqConfiguration object, first time msmq service boot after setup. Author: Doron Juster (DoronJ) 08-Mar-1999 ilan herbst (ilanh) 27-Aug-2000 --*/ #include "stdh.h" #include <mqupgrd.h> #include <autorel.h> #include <mqprops.h> #include <mqsec.h> #include <mqnames.h> #include "..\..\ds\h\mqdsname.h" #include <ad.h> #include "Ev.h" #include "creatobj.tmh" static WCHAR *s_FN=L"mqupgrd/creatobj"; //+------------------------------------------------ // // HRESULT _UpdateMachineSecurityReg() // // Write security properties if newly created // msmqConfiguration object in local registry. // //+------------------------------------------------ static HRESULT _UpdateMachineSecurityReg( IN WCHAR *pwszMachineName, IN PSID pUserSid, IN GUID *pMachineGuid ) { // // cache machine account sid in registry. // PROPID propidSid = PROPID_COM_SID; MQPROPVARIANT PropVarSid; PropVarSid.vt = VT_NULL; PropVarSid.blob.pBlobData = NULL; AP<BYTE> pSid; HRESULT hr = ADGetObjectProperties( eCOMPUTER, NULL, // pwcsDomainController false, // fServerName pwszMachineName, 1, &propidSid, &PropVarSid ); if (FAILED(hr)) { return LogHR(hr, s_FN, 20); } pSid = PropVarSid.blob.pBlobData; ASSERT(IsValidSid(pSid)); DWORD dwSize = GetLengthSid(pSid); DWORD dwType = REG_BINARY; LONG rc = SetFalconKeyValue( MACHINE_ACCOUNT_REGNAME, &dwType, pSid, &dwSize ); ASSERT(rc == ERROR_SUCCESS); if (rc != ERROR_SUCCESS) { return LogHR(HRESULT_FROM_WIN32(rc), s_FN, 30); } MQSec_UpdateLocalMachineSid(pSid); // // Write security descriptor of msmqConfiguration in Registry. // PSECURITY_DESCRIPTOR pSD; DWORD dwSDSize; P<BYTE> pReleaseSD = NULL ; SECURITY_INFORMATION RequestedInformation = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; // // The cached security descriptor in registry is in NT4 format. // For that reason we use PROPID_QM_SECURITY. // PROPVARIANT varSD; varSD.vt = VT_NULL; hr = ADGetObjectSecurityGuid( eMACHINE, NULL, // pwcsDomainController false, // fServerName pMachineGuid, RequestedInformation, PROPID_QM_SECURITY, &varSD ); if (hr == MQDS_OBJECT_NOT_FOUND) { // // This may happen because of replication delay. // Create a default security descriptor and cache it in registry. // Anyway, each time the msmq service boot it updates this value. // // Build a security descriptor that include only owner and group. // Owner is needed to build the DACL. // pSD = NULL; P<BYTE> pDefaultSD = NULL; hr = MQSec_GetDefaultSecDescriptor( MQDS_MACHINE, (PSECURITY_DESCRIPTOR*) &pDefaultSD, FALSE, /*fImpersonate*/ NULL, DACL_SECURITY_INFORMATION, e_UseDefaultDacl ); if (FAILED(hr)) { return LogHR(hr, s_FN, 50); } PSID pOwner = NULL; BOOL bOwnerDefaulted = FALSE ; BOOL bRet = GetSecurityDescriptorOwner( pDefaultSD, &pOwner, &bOwnerDefaulted ); ASSERT(bRet); PSID pWorldSid = MQSec_GetWorldSid(); PSID pComputerSid = pSid; // // Build the default machine DACL. // DWORD dwAclSize = sizeof(ACL) + (3 * (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD))) + GetLengthSid(pWorldSid) + GetLengthSid(pComputerSid) + GetLengthSid(pOwner); if (pUserSid) { dwAclSize += (sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) + GetLengthSid(pUserSid); } AP<char> DACL_buff = new char[dwAclSize]; PACL pDacl = (PACL)(char*)DACL_buff; InitializeAcl(pDacl, dwAclSize, ACL_REVISION); DWORD dwWorldAccess = MQSEC_MACHINE_WORLD_RIGHTS; BOOL fAdd = AddAccessAllowedAce( pDacl, ACL_REVISION, dwWorldAccess, pWorldSid ); ASSERT(fAdd); // // Add the owner with full control. // fAdd = AddAccessAllowedAce( pDacl, ACL_REVISION, MQSEC_MACHINE_GENERIC_ALL, pOwner ); ASSERT(fAdd); // // Add the computer account. // fAdd = AddAccessAllowedAce( pDacl, ACL_REVISION, MQSEC_MACHINE_SELF_RIGHTS, pComputerSid ); ASSERT(fAdd); if (pUserSid) { fAdd = AddAccessAllowedAce( pDacl, ACL_REVISION, MQSEC_MACHINE_GENERIC_ALL, pUserSid ); ASSERT(fAdd); } // // build absolute security descriptor. // SECURITY_DESCRIPTOR sd; InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); bRet = SetSecurityDescriptorOwner(&sd, pOwner, bOwnerDefaulted); ASSERT(bRet); PSID pGroup = NULL; BOOL bGroupDefaulted = FALSE; bRet = GetSecurityDescriptorGroup( pDefaultSD, &pGroup, &bGroupDefaulted ); ASSERT(bRet && IsValidSid(pGroup)); bRet = SetSecurityDescriptorGroup(&sd, pGroup, bGroupDefaulted); ASSERT(bRet); bRet = SetSecurityDescriptorDacl(&sd, TRUE, pDacl, TRUE); ASSERT(bRet); // // Convert the descriptor to a self relative format. // dwSDSize = 0; hr = MQSec_MakeSelfRelative( (PSECURITY_DESCRIPTOR) &sd, &pSD, &dwSDSize ); if (FAILED(hr)) { return LogHR(hr, s_FN, 60); } ASSERT(dwSDSize != 0); pReleaseSD = (BYTE*) pSD; } else if (FAILED(hr)) { return LogHR(hr, s_FN, 70); } else { ASSERT(SUCCEEDED(hr)); ASSERT(varSD.vt == VT_BLOB); pReleaseSD = varSD.blob.pBlobData; pSD = varSD.blob.pBlobData; dwSDSize = varSD.blob.cbSize; } dwType = REG_BINARY; rc = SetFalconKeyValue( MSMQ_DS_SECURITY_CACHE_REGNAME, &dwType, (PVOID) pSD, &dwSDSize ); ASSERT(rc == ERROR_SUCCESS); if (rc != ERROR_SUCCESS) { return LogHR(HRESULT_FROM_WIN32(rc), s_FN, 80); } return MQ_OK ; } //+----------------------------------------------------------------------- // // HRESULT _RegisterMachine() // // Query machine properties from ADS and write them in registry. // //+----------------------------------------------------------------------- static HRESULT _RegisterMachine( IN WCHAR *pwszMachineName, IN GUID *pMachineGuid, IN BOOL fSupportDepClient, IN const GUID * pguidSiteIdOfCreatedObject ) { // // Lookup the GUID of the object // PROPID columnsetPropertyIDs[] = {PROPID_E_ID}; PROPVARIANT propVariant; propVariant.vt = VT_NULL; HRESULT hr = ADGetObjectProperties( eENTERPRISE, NULL, // pwcsDomainController false, // fServerName L"msmq", 1, columnsetPropertyIDs, &propVariant ); if (FAILED(hr)) { TrERROR(GENERAL, "Failed to get enterpriseID, in ADGetObjectProperties(), hr- %lxh", hr); return LogHR(hr, s_FN, 120); } DWORD dwType = REG_BINARY; DWORD dwSize = sizeof(GUID); LONG rc = ERROR_SUCCESS; if (propVariant.vt == VT_CLSID) { rc = SetFalconKeyValue( MSMQ_ENTERPRISEID_REGNAME, &dwType, propVariant.puuid, &dwSize ); ASSERT(rc == ERROR_SUCCESS); delete propVariant.puuid; } else { ASSERT(0); } // // Get back properties of object that was just created. // These properties are generated by the server side. // GUID guidSite = GUID_NULL; const UINT x_nMaxProps = 3; PROPID propIDs[x_nMaxProps]; PROPVARIANT propVariants[x_nMaxProps]; DWORD iProperty = 0; propIDs[iProperty] = PROPID_QM_MACHINE_ID; propVariants[iProperty].vt = VT_CLSID; propVariants[iProperty].puuid = pMachineGuid; iProperty++; propIDs[iProperty] = PROPID_QM_SITE_ID; propVariants[iProperty].vt = VT_CLSID; propVariants[iProperty].puuid = &guidSite; iProperty++; propIDs[iProperty] = PROPID_QM_SERVICE_DEPCLIENTS; propVariants[iProperty].vt = VT_UI1; DWORD dwDepClProp = iProperty; iProperty++; ASSERT(iProperty == x_nMaxProps); DWORD dwSupportDepClient = fSupportDepClient; if (memcmp(pMachineGuid, &GUID_NULL, sizeof(GUID)) == 0) { // // In normal case, we expect to get the machine guid from the // "CreateObject" call. But if object was already created, then // we'll query the DS for the guid and other data. In normal case, // it's OK to set the other data to null. The msmq service will // update it on initialization. // hr = ADGetObjectProperties( eMACHINE, NULL, // pwcsDomainController false, // fServerName pwszMachineName, iProperty, propIDs, propVariants ); if (FAILED(hr)) { // // We don't wait for replication delays. // In the normal case, the call to DSCreateObject() will return // the machine guid and we won't call DSGetObjectProperties(). // Reaching this point in code, and calling DSGet(), means that // the msmq service boot, created the configuration object and // then crashd. So user must run it manually. So we can safely // assume that user waited for replication to complete. Anyway, // the event below mention that user must wait for replication. // WCHAR wBuf[128]; swprintf(wBuf, L"%lxh", hr); EvReport(GetMsmqConfig_ERR, 1, wBuf); return LogHR(hr, s_FN, 150); } dwSupportDepClient = propVariants[dwDepClProp].bVal; } else // a newly created msmqConfiguration { // // Write the site-id that was found while creating the object // guidSite = *pguidSiteIdOfCreatedObject; } // // Write properties to registry. // dwType = REG_BINARY; dwSize = sizeof(GUID); rc = SetFalconKeyValue( MSMQ_SITEID_REGNAME, &dwType, &guidSite, &dwSize ); ASSERT(rc == ERROR_SUCCESS); dwType = REG_DWORD; dwSize = sizeof(DWORD); rc = SetFalconKeyValue( MSMQ_MQS_DEPCLINTS_REGNAME, &dwType, &dwSupportDepClient, &dwSize ); ASSERT(rc == ERROR_SUCCESS); // // Set same value, 0, in all MQS fields in registry. Automatic setup // is applicable only to msmq independent clients. // dwType = REG_DWORD; dwSize = sizeof(DWORD); DWORD dwVal = 0; rc = SetFalconKeyValue( MSMQ_MQS_REGNAME, &dwType, &dwVal, &dwSize ); ASSERT(rc == ERROR_SUCCESS); rc = SetFalconKeyValue( MSMQ_MQS_DSSERVER_REGNAME, &dwType, &dwVal, &dwSize ); ASSERT(rc == ERROR_SUCCESS); rc = SetFalconKeyValue( MSMQ_MQS_ROUTING_REGNAME, &dwType, &dwVal, &dwSize ); ASSERT(rc == ERROR_SUCCESS); return MQ_OK; } // _RegisterMachine //+---------------------------- // // HRESULT _GetSites() // //+---------------------------- static HRESULT _GetSites( IN WCHAR *pwszMachineName, OUT CACLSID *pcauuid ) { DWORD dwNumSites = 0; GUID *pguidSites; HRESULT hResult = ADGetComputerSites( pwszMachineName, &dwNumSites, &pguidSites ); if (FAILED(hResult)) { return LogHR(hResult, s_FN, 190); } ASSERT(dwNumSites); // Must be > 0 pcauuid->cElems = dwNumSites; pcauuid->pElems = pguidSites; return MQ_OK; } // _GetSites //+----------------------------------------------------- // // HRESULT _VerifyComputerObject() // //+----------------------------------------------------- HRESULT _VerifyComputerObject(IN LPCWSTR pComputerName) { PROPID propId = PROPID_COM_SID; PROPVARIANT propVar; propVar.vt = VT_NULL; HRESULT hr = ADGetObjectProperties( eCOMPUTER, NULL, // pwcsDomainController false, // fServerName pComputerName, 1, &propId, &propVar ); if (FAILED(hr)) { EvReport(ADS_COMPUTER_OBJECT_NOT_FOUND_ERR); return LogHR(hr, s_FN, 500); } delete propVar.blob.pBlobData; return MQ_OK; } // _VerifyComputerObject //+----------------------------------------------------- // // HRESULT _CreateTheConfigurationObject() // //+----------------------------------------------------- HRESULT _CreateTheConfigurationObject( IN WCHAR *pwszMachineName, OUT GUID *pMachineGuid, OUT PSID *ppUserSid, OUT BOOL *pfSupportDepClient, OUT GUID *pguidSiteId ) { // // Prepare the properties for object creation. // const UINT x_nMaxProps = 10; PROPID propIDs[x_nMaxProps]; PROPVARIANT propVariants[x_nMaxProps]; DWORD iProperty =0; propIDs[iProperty] = PROPID_QM_OLDSERVICE; propVariants[iProperty].vt = VT_UI4; propVariants[iProperty].ulVal = SERVICE_NONE; iProperty++; propIDs[iProperty] = PROPID_QM_SERVICE_DSSERVER; propVariants[iProperty].vt = VT_UI1; propVariants[iProperty].bVal = 0; iProperty++; propIDs[iProperty] = PROPID_QM_SERVICE_ROUTING; propVariants[iProperty].vt = VT_UI1; propVariants[iProperty].bVal = 0; iProperty++; DWORD dwOsType; DWORD dwType = REG_DWORD; DWORD dwSize = sizeof(dwOsType); DWORD dwDefaultOS = MSMQ_OS_NTW; LONG rc = GetFalconKeyValue( MSMQ_OS_TYPE_REGNAME, &dwType, static_cast<PVOID>(&dwOsType), &dwSize, (LPCWSTR) &dwDefaultOS ); if (rc != ERROR_SUCCESS) { return LogHR(HRESULT_FROM_WIN32(rc), s_FN, 210); } propIDs[iProperty] = PROPID_QM_OS; propVariants[iProperty].vt = VT_UI4; propVariants[iProperty].ulVal = dwOsType; iProperty++; propIDs[iProperty] = PROPID_QM_SERVICE_DEPCLIENTS; propVariants[iProperty].vt = VT_UI1; // // By Default, MSMQ on server doesn't supports Dep. Clients // propVariants[iProperty].bVal = 0; *pfSupportDepClient = propVariants[iProperty].bVal; iProperty++; BLOB blobEncrypt; blobEncrypt.cbSize = 0; blobEncrypt.pBlobData = NULL; BLOB blobSign; blobSign.cbSize = 0; blobSign.pBlobData = NULL; HRESULT hr; hr = MQSec_StorePubKeys( FALSE, eBaseProvider, eEnhancedProvider, &blobEncrypt, &blobSign ); if (FAILED(hr)) { return LogHR(hr, s_FN, 490); } P<BYTE> pCleaner1 = blobEncrypt.pBlobData; P<BYTE> pCleaner2 = blobSign.pBlobData; propIDs[iProperty] = PROPID_QM_ENCRYPT_PKS; propVariants[iProperty].vt = VT_BLOB; propVariants[iProperty].blob = blobEncrypt; iProperty++; propIDs[iProperty] = PROPID_QM_SIGN_PKS; propVariants[iProperty].vt = VT_BLOB; propVariants[iProperty].blob = blobSign; iProperty++; // // Get sites of this machine. // CACLSID cauuid; hr = _GetSites( pwszMachineName, &cauuid ); if (FAILED(hr)) { return LogHR(hr, s_FN, 220); } if (cauuid.cElems > 0) { // // Save one of the site-ids, to be written later to registry // *pguidSiteId = cauuid.pElems[0]; } propIDs[iProperty] = PROPID_QM_SITE_IDS; propVariants[iProperty].vt = (VT_CLSID | VT_VECTOR); propVariants[iProperty].cauuid.pElems = cauuid.pElems; propVariants[iProperty].cauuid.cElems = cauuid.cElems; DWORD iSitesIndex = iProperty; iProperty++; BYTE bSidBuf[256]; // should be enough for every possible SID. dwType = REG_BINARY; dwSize = sizeof(bSidBuf); DWORD ixQmOwnerSid = 0; // // Read user SID from registry. We'll send it to server, and server // add it with full-control to DACL of the msmqConfiguration object. // rc = GetFalconKeyValue( MSMQ_SETUP_USER_SID_REGNAME, &dwType, static_cast<PVOID>(bSidBuf), &dwSize ); if (rc != ERROR_SUCCESS) { // // See if setup from local user. // DWORD dwLocal = 0; dwSize = sizeof(dwLocal); rc = GetFalconKeyValue( MSMQ_SETUP_USER_LOCAL_REGNAME, &dwType, &dwLocal, &dwSize ); if ((rc == ERROR_SUCCESS) && (dwLocal == 1)) { // Ok, Local user. } else { // // Ok, This is the case we JoinDomain from Workgroup, // or move domains when initial installation was workgroup. // in that case both MSMQ_SETUP_USER_SID_REGNAME, MSMQ_SETUP_USER_LOCAL_REGNAME // are not set // in This case we will give no specific user right like in w2k // ilanh 27-Aug-2000 // TrWARNING(GENERAL, "setup\\UserSid and setup\\LocalUser not found, assuming JoinDomain from workgroup, or first installation was workgroup"); } } else { PSID pSid = (PSID) bSidBuf; ASSERT(IsValidSid(pSid)); // // Caution: This propid is known only to Win2000 // RTM msmq servers and above (not win2k beta3). // So if we fail to create the object, we try again w/o it. // This propid should be the last one in the list. // ULONG ulSidSize = GetLengthSid(pSid); ASSERT(ulSidSize <= dwSize); propIDs[iProperty] = PROPID_QM_OWNER_SID; propVariants[iProperty].vt = VT_BLOB; propVariants[iProperty].blob.pBlobData = (BYTE*) bSidBuf; propVariants[iProperty].blob.cbSize = ulSidSize; ixQmOwnerSid = iProperty; iProperty++; if (ppUserSid) { *ppUserSid = (PSID) new BYTE[ulSidSize]; memcpy(*ppUserSid, bSidBuf, ulSidSize); } } ASSERT(iProperty <= x_nMaxProps); // // Create the msmq Configuration object ! // hr = ADCreateObject( eMACHINE, NULL, // pwcsDomainController false, // fServerName pwszMachineName, NULL, iProperty, propIDs, propVariants, pMachineGuid ); if (FAILED(hr) && (ixQmOwnerSid > 0)) { ASSERT(("PROPID_QM_OWNDER_SID should be the last propid!", ixQmOwnerSid == (iProperty - 1))) ; // // If OWNER_SID was used, then try again without it, because this // propid is not known to win2k beta3 msmq server (and maybe our // server is beta3). // iProperty--; hr = ADCreateObject( eMACHINE, NULL, // pwcsDomainController false, // fServerName pwszMachineName, NULL, iProperty, propIDs, propVariants, pMachineGuid ); } delete propVariants[iSitesIndex].cauuid.pElems; if (FAILED(hr)) { if (hr == MQDS_OBJECT_NOT_FOUND) { // // We can verify computer object // HRESULT hr1 = _VerifyComputerObject(pwszMachineName); if (FAILED(hr1)) { return LogHR(hr1, s_FN, 380); } } return LogHR(hr, s_FN, 230); } return hr ; } //+------------------------------------------ // // HRESULT _PostCreateProcessing() // //+------------------------------------------ static HRESULT _PostCreateProcessing( IN HRESULT hrCreate, IN GUID *pMachineGuid, IN WCHAR *pwszMachineName, IN BOOL fSupportDepClient, IN const GUID * pguidSiteIdOfCreatedObject ) { if (hrCreate == MQ_ERROR_MACHINE_EXISTS) { // // that's OK. the msmqConfiguration object already exist. // Register it locally. // *pMachineGuid = GUID_NULL; } else if (FAILED(hrCreate)) { WCHAR wBuf[128]; swprintf(wBuf, L"%lxh", hrCreate); EvReport(CreateMsmqConfig_ERR, 1, wBuf); return LogHR(hrCreate, s_FN, 330); } else if (memcmp(pMachineGuid, &GUID_NULL, sizeof(GUID)) == 0) { // // That may happen if client on Win2000 RTM is setting up // agsinst a beta3 Win2000 server. Explicitely query the // server for machine guid. On win2000 rtm, the machine guid // is returned by call to CreateObject(). // } HRESULT hr = _RegisterMachine( pwszMachineName, pMachineGuid, fSupportDepClient, pguidSiteIdOfCreatedObject ); if (FAILED(hr)) { return LogHR(hr, s_FN, 340); } // // update QM guid in registry. We don't need previous values. // DWORD dwType = REG_BINARY; DWORD dwSize = sizeof(GUID); LONG rc = SetFalconKeyValue( MSMQ_QMID_REGNAME, &dwType, pMachineGuid, &dwSize ); DBG_USED(rc); ASSERT(rc == ERROR_SUCCESS); return MQ_OK; } //+------------------------------------------------------------------------- // // HRESULT APIENTRY MqCreateMsmqObj() // // Create the msmqConfiguration object in ADS. // // Parameters: // // Algorithm: // For Setup - the name of the msmq server is // already saved in registry. It was found by the setup process or was // given by user. For setup it's enough to use any msmq server (on domain // controller) in the client's site as there are no special restrictions // on the create process. // //+------------------------------------------------------------------------- extern HINSTANCE g_hMyModule; HRESULT APIENTRY MqCreateMsmqObj() { #ifdef _DEBUG TCHAR tszFileName[MAX_PATH * 2] = L""; DWORD dwGet = GetModuleFileName( g_hMyModule, tszFileName, STRLEN(tszFileName) ); if (dwGet) { DWORD dwLen = lstrlen(tszFileName); lstrcpy(&tszFileName[dwLen - 3], TEXT("ini")); UINT uiDbg = GetPrivateProfileInt( TEXT("Debug"), TEXT("StopBeforeRun"), 0, tszFileName ); if (uiDbg) { ASSERT(0); } } #endif // // Ignore WorkGroup registry // HRESULT hr = ADInit ( NULL, // pLookDS, NULL, // pGetServers true, // fSetupMode false, // fQMDll true, // fIgnoreWorkGroup true // fDisableDownlevelNotifications ); if (FAILED(hr)) { return LogHR(hr, s_FN, 320); } // // Get name of local machine. // BOOL fUsingDNS = TRUE; DWORD dwNumChars = 0; AP<WCHAR> pwszMachineName; BOOL fGet = GetComputerNameExW( ComputerNameDnsFullyQualified, pwszMachineName, &dwNumChars ); if (dwNumChars > 0) { pwszMachineName = new WCHAR[dwNumChars]; fGet = GetComputerNameExW( ComputerNameDnsFullyQualified, pwszMachineName, &dwNumChars ); } if (!fGet || (dwNumChars == 0)) { ASSERT(!fGet && (dwNumChars == 0)); // // DNS name not available. Retrieve NetBIOS name. // pwszMachineName.free(); dwNumChars = MAX_COMPUTERNAME_LENGTH + 2; pwszMachineName = new WCHAR[dwNumChars]; fGet = GetComputerNameW( pwszMachineName, &dwNumChars ); fUsingDNS = FALSE; } ASSERT(fGet && (dwNumChars > 0)); hr = MQ_OK; GUID MachineGuid = GUID_NULL; BOOL fSupportDepClient = 0; P<BYTE> pUserSid = NULL; GUID guidSiteId = GUID_NULL; hr = _CreateTheConfigurationObject( pwszMachineName, &MachineGuid, (PSID*) &pUserSid, &fSupportDepClient, &guidSiteId ); if ((hr == MQDS_OBJECT_NOT_FOUND) && fUsingDNS) { // // This problem may happen if attribute dnsHostName is not set // in the computer object. // dwNumChars = MAX_COMPUTERNAME_LENGTH + 2; pwszMachineName.free(); pwszMachineName = new WCHAR[dwNumChars]; fGet = GetComputerNameW( pwszMachineName, &dwNumChars ); ASSERT(fGet && (dwNumChars > 0)); fUsingDNS = FALSE; if (fGet && (dwNumChars > 0)) { if (pUserSid) { delete pUserSid.detach(); } MachineGuid = GUID_NULL ; hr = _CreateTheConfigurationObject( pwszMachineName, &MachineGuid, (PSID*) &pUserSid, &fSupportDepClient, &guidSiteId ); } } hr = _PostCreateProcessing( hr, &MachineGuid, pwszMachineName, fSupportDepClient, &guidSiteId ); if (SUCCEEDED(hr)) { hr = _UpdateMachineSecurityReg( pwszMachineName, pUserSid, &MachineGuid ); } return LogHR(hr, s_FN, 370); }
24.761639
145
0.547605
[ "object" ]
616e66ba05ab5efef5881d336346ffc74db37991
13,885
cpp
C++
src/Editor/CharacterEditor/CCharacterEditor.cpp
Antidote/PrimeWorldEditor
976796c161447cff63f514007971d128c7d094a2
[ "MIT" ]
1
2018-12-25T02:09:27.000Z
2018-12-25T02:09:27.000Z
src/Editor/CharacterEditor/CCharacterEditor.cpp
villadox/PrimeWorldEditor
9eb3d1d0110e2c28df0c9ebf29b905982a697f2d
[ "MIT" ]
null
null
null
src/Editor/CharacterEditor/CCharacterEditor.cpp
villadox/PrimeWorldEditor
9eb3d1d0110e2c28df0c9ebf29b905982a697f2d
[ "MIT" ]
1
2020-02-21T15:22:56.000Z
2020-02-21T15:22:56.000Z
#include "CCharacterEditor.h" #include "ui_CCharacterEditor.h" #include "Editor/UICommon.h" #include <Common/Macros.h> #include <Common/Math/MathUtil.h> #include <QFileDialog> #include <QMessageBox> #include <QTreeView> const CVector3f CCharacterEditor::skDefaultOrbitTarget = CVector3f(0,0,1); const float CCharacterEditor::skDefaultOrbitDistance = 4.f; CCharacterEditor::CCharacterEditor(CAnimSet *pSet, QWidget *parent) : IEditor(parent) , ui(new Ui::CCharacterEditor) , mpScene(new CScene()) , mpSelectedBone(nullptr) , mBindPose(false) , mPlayAnim(true) , mLoopAnim(true) , mAnimTime(0.f) , mPlaybackSpeed(1.f) { ui->setupUi(this); REPLACE_WINDOWTITLE_APPVARS; mpCharNode = new CCharacterNode(mpScene, -1); ui->Viewport->SetNode(mpCharNode); CCamera& rCamera = ui->Viewport->Camera(); rCamera.SetMoveSpeed(0.5f); rCamera.SetPitch(-0.3f); rCamera.SetMoveMode(ECameraMoveMode::Orbit); // Init UI ui->ToolBar->addSeparator(); mpCharComboBox = new QComboBox(this); mpCharComboBox->setMinimumWidth(175); ui->ToolBar->addWidget(mpCharComboBox); mpAnimComboBox = new QComboBox(this); mpAnimComboBox->setMinimumWidth(175); ui->ToolBar->addWidget(mpAnimComboBox); connect(ui->Viewport, SIGNAL(HoverBoneChanged(uint32)), this, SLOT(OnViewportHoverBoneChanged(uint32))); connect(ui->Viewport, SIGNAL(ViewportClick(QMouseEvent*)), this, SLOT(OnViewportClick())); connect(ui->ActionShowGrid, SIGNAL(toggled(bool)), this, SLOT(ToggleGrid(bool))); connect(ui->ActionShowMesh, SIGNAL(toggled(bool)), this, SLOT(ToggleMeshVisible(bool))); connect(ui->ActionShowSkeleton, SIGNAL(toggled(bool)), this, SLOT(ToggleSkeletonVisible(bool))); connect(ui->ActionBindPose, SIGNAL(toggled(bool)), this, SLOT(ToggleBindPose(bool))); connect(ui->ActionOrbit, SIGNAL(toggled(bool)), this, SLOT(ToggleOrbit(bool))); connect(ui->ActionPlay, SIGNAL(triggered()), this, SLOT(TogglePlay())); connect(ui->ActionLoop, SIGNAL(toggled(bool)), this, SLOT(ToggleLoop(bool))); connect(ui->ActionRewind, SIGNAL(triggered()), this, SLOT(Rewind())); connect(ui->ActionFastForward, SIGNAL(triggered()), this, SLOT(FastForward())); connect(ui->ActionPrevAnim, SIGNAL(triggered()), this, SLOT(PrevAnim())); connect(ui->ActionNextAnim, SIGNAL(triggered()), this, SLOT(NextAnim())); connect(mpCharComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(SetActiveCharacterIndex(int))); connect(mpAnimComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(SetActiveAnimation(int))); connect(ui->AnimSlider, SIGNAL(valueChanged(int)), this, SLOT(SetAnimTime(int))); connect(ui->PlayPauseButton, SIGNAL(pressed()), this, SLOT(TogglePlay())); connect(ui->LoopButton, SIGNAL(toggled(bool)), this, SLOT(ToggleLoop(bool))); connect(ui->RewindButton, SIGNAL(pressed()), this, SLOT(Rewind())); connect(ui->FastForwardButton, SIGNAL(pressed()), this, SLOT(FastForward())); connect(ui->AnimSpeedSpinBox, SIGNAL(valueChanged(double)), this, SLOT(AnimSpeedSpinBoxChanged(double))); // Init skeleton tree view ui->SkeletonHierarchyTreeView->setModel(&mSkeletonModel); QList<int> SplitterSizes; SplitterSizes << width() * 0.2 << width() * 0.8; ui->splitter->setSizes(SplitterSizes); connect(ui->SkeletonHierarchyTreeView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(OnSkeletonTreeSelectionChanged(QModelIndex))); SetActiveAnimSet(pSet); } CCharacterEditor::~CCharacterEditor() { delete ui; delete mpScene; delete mpCharNode; } void CCharacterEditor::EditorTick(float DeltaTime) { UpdateAnimTime(DeltaTime); UpdateCameraOrbit(); } void CCharacterEditor::UpdateAnimTime(float DeltaTime) { CAnimation *pAnim = CurrentAnimation(); if (pAnim && mPlayAnim && !mBindPose && !ui->AnimSlider->isSliderDown()) { mAnimTime += DeltaTime * mPlaybackSpeed; CAnimation *pAnim = CurrentAnimation(); float AnimLength = (pAnim ? pAnim->Duration() : 0.f); if (mAnimTime > AnimLength) { if (mLoopAnim) { mAnimTime = fmodf(mAnimTime, AnimLength); } else { mAnimTime = AnimLength; TogglePlay(); } } if (mAnimTime < 0.f) { if (mLoopAnim) { mAnimTime = AnimLength + fmodf(mAnimTime, AnimLength); } else { mAnimTime = 0.f; TogglePlay(); } } SetAnimTime(mAnimTime); } } void CCharacterEditor::UpdateCameraOrbit() { CSkeleton *pSkel = CurrentSkeleton(); if (!pSkel) { // Center around character if we have one, otherwise fall back to default orbit. if (mpSet) ui->Viewport->Camera().SetOrbitTarget(mpCharNode->CenterPoint()); else ui->Viewport->Camera().SetOrbit(skDefaultOrbitTarget, skDefaultOrbitDistance); } else { // If we have a selected bone, orbit around that. if (mpSelectedBone) ui->Viewport->Camera().SetOrbitTarget(mpCharNode->BonePosition(mpSelectedBone->ID())); // Otherwise, try to find Skeleton_Root. Barring that, we can orbit the root bone. else { CBone *pRoot = pSkel->RootBone(); CBone *pSkelRoot = (pRoot ? pRoot->ChildByIndex(0) : pRoot); CVector3f OrbitTarget = (pSkelRoot ? mpCharNode->BonePosition(pSkelRoot->ID()) : mpCharNode->CenterPoint()); ui->Viewport->Camera().SetOrbitTarget(OrbitTarget); } } } CSkeleton* CCharacterEditor::CurrentSkeleton() const { return mpSet ? mpSet->Character(mCurrentChar)->pSkeleton : nullptr; } CAnimation* CCharacterEditor::CurrentAnimation() const { return mpSet ? mpSet->FindAnimationAsset(mCurrentAnim) : nullptr; } void CCharacterEditor::SetActiveAnimSet(CAnimSet *pSet) { mpSet = pSet; mpCharNode->SetCharSet(mpSet); SET_WINDOWTITLE_APPVARS("%APP_FULL_NAME% - Character Editor: " + TO_QSTRING(mpSet->Source())); // Clear selected bone ui->SkeletonHierarchyTreeView->selectionModel()->clear(); SetSelectedBone(nullptr); // Set up character combo box mpCharComboBox->blockSignals(true); mpCharComboBox->clear(); for (uint32 iChar = 0; iChar < mpSet->NumCharacters(); iChar++) mpCharComboBox->addItem( TO_QSTRING(mpSet->Character(iChar)->Name) ); SetActiveCharacterIndex(0); mpCharComboBox->blockSignals(false); // Set up anim combo box mpAnimComboBox->blockSignals(true); mpAnimComboBox->clear(); for (uint32 iAnim = 0; iAnim < mpSet->NumAnimations(); iAnim++) mpAnimComboBox->addItem( TO_QSTRING(mpSet->Animation(iAnim)->Name) ); SetActiveAnimation(0); mpAnimComboBox->blockSignals(false); // Set up skeleton tree view CSkeleton *pSkel = mpSet->Character(mCurrentChar)->pSkeleton; mSkeletonModel.SetSkeleton(pSkel); ui->SkeletonHierarchyTreeView->expandAll(); ui->SkeletonHierarchyTreeView->resizeColumnToContents(0); // Select first child bone of root (which should be Skeleton_Root) to line up the camera for orbiting. QModelIndex RootIndex = mSkeletonModel.index(0, 0, QModelIndex()); ui->SkeletonHierarchyTreeView->selectionModel()->setCurrentIndex( mSkeletonModel.index(0, 0, RootIndex), QItemSelectionModel::ClearAndSelect ); // Run CCamera::SetOrbit to reset orbit distance. ui->Viewport->Camera().SetOrbit(mpCharNode->AABox()); } void CCharacterEditor::SetSelectedBone(CBone *pBone) { if (pBone != mpSelectedBone) { if (mpSelectedBone) mpSelectedBone->SetSelected(false); mpSelectedBone = pBone; if (mpSelectedBone) mpSelectedBone->SetSelected(true); } } CCharacterEditorViewport* CCharacterEditor::Viewport() const { return ui->Viewport; } // ************ PUBLIC SLOTS ************ void CCharacterEditor::ToggleGrid(bool Enable) { ui->Viewport->SetGridEnabled(Enable); } void CCharacterEditor::ToggleMeshVisible(bool Visible) { // eShowObjectGeometry isn't the best fit, but close enough...? ui->Viewport->SetShowFlag(EShowFlag::ObjectGeometry, Visible); } void CCharacterEditor::ToggleSkeletonVisible(bool Visible) { ui->Viewport->SetShowFlag(EShowFlag::Skeletons, Visible); } void CCharacterEditor::ToggleBindPose(bool Enable) { mpCharNode->SetAnimated(!Enable); if (sender() != ui->ActionBindPose) { ui->ActionBindPose->blockSignals(true); ui->ActionBindPose->setChecked(Enable); ui->ActionBindPose->blockSignals(false); } if (Enable && mPlayAnim) TogglePlay(); ui->AnimSlider->setEnabled(!Enable); mBindPose = Enable; } void CCharacterEditor::ToggleOrbit(bool Enable) { ui->Viewport->Camera().SetMoveMode(Enable ? ECameraMoveMode::Orbit : ECameraMoveMode::Free); } void CCharacterEditor::RefreshViewport() { ui->Viewport->ProcessInput(); ui->Viewport->Render(); } void CCharacterEditor::OnViewportHoverBoneChanged(uint32 BoneID) { if (BoneID == 0xFFFFFFFF) ui->StatusBar->clearMessage(); else ui->StatusBar->showMessage(QString("Bone %1: %2").arg(BoneID).arg( TO_QSTRING(mpSet->Character(mCurrentChar)->pSkeleton->BoneByID(BoneID)->Name()) )); } void CCharacterEditor::OnViewportClick() { uint32 HoverBoneID = ui->Viewport->HoverBoneID(); CSkeleton *pSkel = (mpSet ? mpSet->Character(mCurrentChar)->pSkeleton : nullptr); CBone *pBone = (pSkel ? pSkel->BoneByID(HoverBoneID) : nullptr); if (!pBone || !pBone->IsSelected()) { if (pBone) { QModelIndex NewBoneIndex = mSkeletonModel.IndexForBone(pBone); ui->SkeletonHierarchyTreeView->selectionModel()->setCurrentIndex(NewBoneIndex, QItemSelectionModel::ClearAndSelect); } else ui->SkeletonHierarchyTreeView->selectionModel()->clear(); SetSelectedBone(pBone); } } void CCharacterEditor::OnSkeletonTreeSelectionChanged(const QModelIndex& rkIndex) { CBone *pBone = mSkeletonModel.BoneForIndex(rkIndex); SetSelectedBone(pBone); } void CCharacterEditor::SetActiveCharacterIndex(int CharIndex) { mCurrentChar = CharIndex; mpCharNode->SetActiveChar((uint32) CharIndex); } void CCharacterEditor::SetActiveAnimation(int AnimIndex) { mCurrentAnim = AnimIndex; mpCharNode->SetActiveAnim((uint32) AnimIndex); ui->AnimSlider->blockSignals(true); ui->AnimSlider->setMaximum((int) (CurrentAnimation() ? CurrentAnimation()->Duration() * 1000 : 0)); ui->AnimSlider->blockSignals(false); mpAnimComboBox->blockSignals(true); mpAnimComboBox->setCurrentIndex(AnimIndex); mpAnimComboBox->blockSignals(false); SetAnimTime(0.f); } void CCharacterEditor::PrevAnim() { if (mCurrentAnim > 0) SetActiveAnimation(mCurrentAnim - 1); } void CCharacterEditor::NextAnim() { uint32 MaxAnim = (mpSet ? mpSet->NumAnimations() - 1 : 0); if (mCurrentAnim < MaxAnim) SetActiveAnimation(mCurrentAnim + 1); } void CCharacterEditor::SetAnimTime(int Time) { float FloatTime = Time / 1000.f; SetAnimTime(FloatTime); } void CCharacterEditor::SetAnimTime(float Time) { if (mBindPose) Time = 0.f; mAnimTime = Time; if (ui->AnimSlider != sender() || mBindPose) { int IntTime = (int) (Time * 1000); ui->AnimSlider->setValue(IntTime); } mpCharNode->SetAnimTime(Time); CAnimation *pAnim = CurrentAnimation(); uint32 NumKeys = 1, CurKey = 0; if (pAnim) { NumKeys = pAnim->NumKeys(); CurKey = Math::Min<uint32>((uint32) (Time / pAnim->TickInterval()) + 1, NumKeys - 1); } ui->FrameLabel->setText(QString("Frame %1 / %2 (%3s/%4s)").arg(CurKey).arg(NumKeys - 1).arg(mAnimTime, 0, 'f', 3).arg(pAnim ? pAnim->Duration() : 0.f, 0, 'f', 3)); } void CCharacterEditor::TogglePlay() { if (mBindPose) ToggleBindPose(false); mPlayAnim = !mPlayAnim; QString NewText = (mPlayAnim ? "Pause" : "Play"); ui->PlayPauseButton->setToolTip(NewText); ui->ActionPlay->setText(NewText); QIcon PlayPauseIcon = QIcon(mPlayAnim ? ":/icons/Pause_24px.png" : ":/icons/Play_24px.png"); ui->PlayPauseButton->setIcon(PlayPauseIcon); if (ui->ActionPlay != sender()) { ui->ActionPlay->blockSignals(true); ui->ActionPlay->setChecked(mPlayAnim); ui->ActionPlay->blockSignals(false); } CAnimation *pAnim = CurrentAnimation(); if (pAnim && mPlayAnim) { if (mPlaybackSpeed < 0.f && mAnimTime == 0.f) SetAnimTime(pAnim->Duration()); if (mPlaybackSpeed >= 0.f && mAnimTime == pAnim->Duration()) SetAnimTime(0.f); } } void CCharacterEditor::ToggleLoop(bool Loop) { mLoopAnim = Loop; QString NewText = (Loop ? "Disable Loop" : "Loop"); ui->LoopButton->setToolTip(NewText); ui->ActionLoop->setText(NewText); QIcon ActionIcon = QIcon(Loop ? ":/icons/DontLoop_24px" : ":/icons/Loop_24px.png"); ui->ActionLoop->setIcon(ActionIcon); if (sender() != ui->LoopButton) { ui->LoopButton->blockSignals(true); ui->LoopButton->setChecked(Loop); ui->LoopButton->blockSignals(false); } if (sender() != ui->ActionLoop) { ui->LoopButton->blockSignals(true); ui->ActionLoop->setChecked(Loop); ui->LoopButton->blockSignals(false); } } void CCharacterEditor::Rewind() { SetAnimTime(0.f); } void CCharacterEditor::FastForward() { CAnimation *pAnim = CurrentAnimation(); if (pAnim && !mBindPose) SetAnimTime(pAnim->Duration()); } void CCharacterEditor::AnimSpeedSpinBoxChanged(double NewVal) { mPlaybackSpeed = (float) NewVal; }
30.993304
167
0.670148
[ "render" ]
616fea17c614514e02245a4e007f7e74a7410873
4,258
cpp
C++
include/enki/enki/robots/s-bot/Sbot.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
include/enki/enki/robots/s-bot/Sbot.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
include/enki/enki/robots/s-bot/Sbot.cpp
ou-real/nevil-grandparent
38324705678afac77d002391da753c6f10ee95e2
[ "MIT" ]
null
null
null
/* Enki - a fast 2D robot simulator Copyright (C) 1999-2013 Stephane Magnenat <stephane at magnenat dot net> Copyright (C) 2004-2005 Markus Waibel <markus dot waibel at epfl dot ch> Copyright (c) 2004-2005 Antoine Beyeler <abeyeler at ab-ware dot com> Copyright (C) 2005-2006 Laboratory of Intelligent Systems, EPFL, Lausanne Copyright (C) 2006-2008 Laboratory of Robotics Systems, EPFL, Lausanne See AUTHORS for details This program is free software; the authors of any publication arising from research using this software are asked to add the following reference: Enki - a fast 2D robot simulator http://home.gna.org/enki Stephane Magnenat <stephane at magnenat dot net>, Markus Waibel <markus dot waibel at epfl dot ch> Laboratory of Intelligent Systems, EPFL, Lausanne. You can redistribute this program and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "enki/robots/s-bot/Sbot.h" /*! \file Sbot.cpp \brief Implementation of the Sbot robot */ namespace Enki { //! Response model for sound on s-bot double MicrophonePseudoRealResponseModel(double signal, double distance) { //apply filter to signal double Lp; double d = distance/10; double attenuation = 100; if (distance <= 5.2) Lp = log(signal); else Lp = log(signal/exp(d*d/attenuation)); if (Lp < 0) return 0.0; return Lp; } void SbotMicrophone::objectStep(double dt, PhysicalObject *po, World *w) { // Get current object sound double *currentSound = new double[noOfChannels]; assert(currentSound); SbotActiveSoundObject *so = dynamic_cast<SbotActiveSoundObject *>(po); if (so) { assert(noOfChannels==so->speaker.noOfChannels); for (size_t i=0; i<noOfChannels; i++) { currentSound[i] = so->speaker.pitch[i]; } } else { SoundSbot *ss = dynamic_cast<SoundSbot *>(po); if (ss) { assert(noOfChannels==ss->speaker.noOfChannels); for (size_t i=0; i<noOfChannels; i++) { currentSound[i] = ss->speaker.pitch[i]; } } } // Current distance between the interacting physical object and // the sensor (used later in sound filtering) double current_dist; double min_dist = 0xFFFFFFFF; unsigned min_dist_micNo = 0; for (size_t i=0; i<4; i++) { current_dist = (po->pos - allMicAbsPos[i]).norm(); // find mic closest to interacting physical object if ( current_dist < min_dist ) { min_dist = current_dist; min_dist_micNo = i; } } // Apply sensor model to acquisition // Acquired sound is always the sum of all contributes after model filtering for (size_t j=0; j<noOfChannels; j++) { acquiredSound[min_dist_micNo][j] += micModel(currentSound[j], min_dist); } delete[] currentSound; } Sbot::Sbot() : DifferentialWheeled(5, 40, 0.02), camera(this, 12, 64), globalSound(this) { addLocalInteraction(&camera); //addGlobalInteraction(&globalSound); setCylindric(6, 15, 500); } unsigned SbotGlobalSound::worldFrequenciesState = 0; unsigned SbotGlobalSound::getWorldFrequenciesState(void) { return worldFrequenciesState; } void FeedableSbot::controlStep(double dt) { DifferentialWheeled::controlStep(dt); // clear dEnergy for next step energy += dEnergy * dt; lastDEnergy = dEnergy; dEnergy = 0; } SoundSbot::SoundSbot() : // microphones can pick up sound reaching up to 1m away mic(this, 6.0, 150, MicrophonePseudoRealResponseModel, 25), // speaker can produce sounds heard by a microphone 1m + micrange away speaker(this, 0, 25) { addLocalInteraction(&mic); addLocalInteraction(&speaker); } }
28.198675
78
0.699389
[ "object", "model" ]
617334e51ba158194c43df4d6c0fef166ea15d2c
8,341
cpp
C++
Cesium3DTilesSelection/test/TestQuadtreeRasterOverlayTileProvider.cpp
SC-One/cesium-native
a8232ad039db1bb83ad2204c40c6dfb5d8207bb6
[ "Apache-2.0" ]
2
2021-10-02T17:45:12.000Z
2021-10-02T17:45:15.000Z
Cesium3DTilesSelection/test/TestQuadtreeRasterOverlayTileProvider.cpp
SC-One/cesium-native
a8232ad039db1bb83ad2204c40c6dfb5d8207bb6
[ "Apache-2.0" ]
null
null
null
Cesium3DTilesSelection/test/TestQuadtreeRasterOverlayTileProvider.cpp
SC-One/cesium-native
a8232ad039db1bb83ad2204c40c6dfb5d8207bb6
[ "Apache-2.0" ]
null
null
null
#include "Cesium3DTilesSelection/QuadtreeRasterOverlayTileProvider.h" #include "Cesium3DTilesSelection/RasterOverlay.h" #include "CesiumGeospatial/WebMercatorProjection.h" #include "SimpleAssetAccessor.h" #include <catch2/catch.hpp> using namespace Cesium3DTilesSelection; using namespace CesiumAsync; using namespace CesiumGeometry; using namespace CesiumGeospatial; using namespace CesiumGltf; using namespace CesiumUtility; namespace { class TestTileProvider : public QuadtreeRasterOverlayTileProvider { public: TestTileProvider( RasterOverlay& owner, const CesiumAsync::AsyncSystem& asyncSystem, const std::shared_ptr<CesiumAsync::IAssetAccessor>& pAssetAccessor, std::optional<Credit> credit, const std::shared_ptr<IPrepareRendererResources>& pPrepareRendererResources, const std::shared_ptr<spdlog::logger>& pLogger, const CesiumGeospatial::Projection& projection, const CesiumGeometry::QuadtreeTilingScheme& tilingScheme, const CesiumGeometry::Rectangle& coverageRectangle, uint32_t minimumLevel, uint32_t maximumLevel, uint32_t imageWidth, uint32_t imageHeight) noexcept : QuadtreeRasterOverlayTileProvider( owner, asyncSystem, pAssetAccessor, credit, pPrepareRendererResources, pLogger, projection, tilingScheme, coverageRectangle, minimumLevel, maximumLevel, imageWidth, imageHeight) {} // The tiles that will return an error from loadQuadtreeTileImage. std::vector<QuadtreeTileID> errorTiles; virtual CesiumAsync::Future<LoadedRasterOverlayImage> loadQuadtreeTileImage(const QuadtreeTileID& tileID) const { LoadedRasterOverlayImage result; result.rectangle = this->getTilingScheme().tileToRectangle(tileID); if (std::find(errorTiles.begin(), errorTiles.end(), tileID) != errorTiles.end()) { result.errors.emplace_back("Tile errored."); } else { // Return an image where every component of every pixel is equal to the // tile level. result.image.emplace(); result.image->width = int32_t(this->getWidth()); result.image->height = int32_t(this->getHeight()); result.image->bytesPerChannel = 1; result.image->channels = 4; result.image->pixelData.resize( this->getWidth() * this->getHeight() * 4, std::byte(tileID.level)); } return this->getAsyncSystem().createResolvedFuture(std::move(result)); } }; class TestRasterOverlay : public RasterOverlay { public: TestRasterOverlay( const std::string& name, const RasterOverlayOptions& options = RasterOverlayOptions()) : RasterOverlay(name, options) {} virtual CesiumAsync::Future<std::unique_ptr<RasterOverlayTileProvider>> createTileProvider( const CesiumAsync::AsyncSystem& asyncSystem, const std::shared_ptr<CesiumAsync::IAssetAccessor>& pAssetAccessor, const std::shared_ptr<CreditSystem>& /* pCreditSystem */, const std::shared_ptr<IPrepareRendererResources>& pPrepareRendererResources, const std::shared_ptr<spdlog::logger>& pLogger, RasterOverlay* pOwner) override { if (!pOwner) { pOwner = this; } return asyncSystem .createResolvedFuture<std::unique_ptr<RasterOverlayTileProvider>>( std::make_unique<TestTileProvider>( *pOwner, asyncSystem, pAssetAccessor, std::nullopt, pPrepareRendererResources, pLogger, WebMercatorProjection(), QuadtreeTilingScheme( WebMercatorProjection::computeMaximumProjectedRectangle(), 1, 1), WebMercatorProjection::computeMaximumProjectedRectangle(), 0, 10, 256, 256)); } }; class MockTaskProcessor : public ITaskProcessor { public: virtual void startTask(std::function<void()> f) { std::thread(f).detach(); } }; } // namespace TEST_CASE("QuadtreeRasterOverlayTileProvider getTile") { auto pTaskProcessor = std::make_shared<MockTaskProcessor>(); auto pAssetAccessor = std::make_shared<SimpleAssetAccessor>( std::map<std::string, std::shared_ptr<SimpleAssetRequest>>()); AsyncSystem asyncSystem(pTaskProcessor); TestRasterOverlay overlay("Test"); overlay.loadTileProvider( asyncSystem, pAssetAccessor, nullptr, nullptr, spdlog::default_logger()); asyncSystem.dispatchMainThreadTasks(); RasterOverlayTileProvider* pProvider = overlay.getTileProvider(); REQUIRE(pProvider); REQUIRE(!pProvider->isPlaceholder()); SECTION("uses root tile for a huge geometric error") { Rectangle rectangle(0.000001, 0.000001, 0.000002, 0.000002); double geometricError = 99999999999.0; IntrusivePointer<RasterOverlayTile> pTile = pProvider->getTile(rectangle, geometricError); pProvider->loadTile(*pTile); for (int i = 0; pTile->getState() != RasterOverlayTile::LoadState::Loaded; ++i) { asyncSystem.dispatchMainThreadTasks(); } CHECK(pTile->getState() == RasterOverlayTile::LoadState::Loaded); const ImageCesium& image = pTile->getImage(); CHECK(image.width > 0); CHECK(image.height > 0); CHECK(image.pixelData.size() > 0); CHECK(std::all_of( image.pixelData.begin(), image.pixelData.end(), [](std::byte b) { return b == std::byte(0); })); } SECTION("uses a mix of levels when a tile returns an error") { glm::dvec2 center(0.1, 0.2); double geometricError = 4000.0; // Verify that the parameters above geometric error successfully indicates // we should use tile level 8. We multiply by 8.0 because the // QuadtreeRasterOverlayTileProvider applies that adjustment to account for // the change from the 3D Tiles default SSE (16) to the terrain default SSE // (2). const int expectedLevel = 8; TestTileProvider* pTestProvider = static_cast<TestTileProvider*>(pProvider); REQUIRE( pTestProvider->computeLevelFromGeometricError( geometricError / 8.0, center) == expectedLevel); // Select a rectangle that spans four tiles at tile level 8. std::optional<QuadtreeTileID> centerTileID = pTestProvider->getTilingScheme().positionToTile(center, expectedLevel); REQUIRE(centerTileID); Rectangle centerRectangle = pTestProvider->getTilingScheme().tileToRectangle(*centerTileID); Rectangle tileRectangle( centerRectangle.minimumX - centerRectangle.computeWidth() * 0.5, centerRectangle.minimumY - centerRectangle.computeHeight() * 0.5, centerRectangle.maximumX + centerRectangle.computeWidth() * 0.5, centerRectangle.maximumY + centerRectangle.computeHeight() * 0.5); // The tile in the southeast corner will fail to load. std::optional<QuadtreeTileID> southeastID = pTestProvider->getTilingScheme().positionToTile( tileRectangle.getLowerRight(), expectedLevel); REQUIRE(southeastID); pTestProvider->errorTiles.emplace_back(*southeastID); IntrusivePointer<RasterOverlayTile> pTile = pProvider->getTile(tileRectangle, geometricError); pProvider->loadTile(*pTile); for (int i = 0; pTile->getState() != RasterOverlayTile::LoadState::Loaded; ++i) { asyncSystem.dispatchMainThreadTasks(); } CHECK(pTile->getState() == RasterOverlayTile::LoadState::Loaded); const ImageCesium& image = pTile->getImage(); CHECK(image.width > 0); CHECK(image.height > 0); CHECK(image.pixelData.size() > 0); // We should have pixels from both level 7 and level 8. CHECK(std::all_of( image.pixelData.begin(), image.pixelData.end(), [](std::byte b) { return b == std::byte(7) || b == std::byte(8); })); CHECK(std::any_of( image.pixelData.begin(), image.pixelData.end(), [](std::byte b) { return b == std::byte(7); })); CHECK(std::any_of( image.pixelData.begin(), image.pixelData.end(), [](std::byte b) { return b == std::byte(8); })); } }
34.754167
80
0.666587
[ "vector", "3d" ]
6174025a2eed1e197e5033a50409ddabca173b7a
7,452
hpp
C++
include/popnn/Loss.hpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
1
2021-02-23T05:58:24.000Z
2021-02-23T05:58:24.000Z
include/popnn/Loss.hpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
include/popnn/Loss.hpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
// Copyright (c) 2016 Graphcore Ltd. All rights reserved. #ifndef popnn_Loss_hpp #define popnn_Loss_hpp namespace popnn { enum LossType { SUM_SQUARED_LOSS, CROSS_ENTROPY_LOSS }; } // end namespace popnn #ifndef __POPC__ #include "popops/EncodingConstants.hpp" #include <poplar/Graph.hpp> #include <poplar/Program.hpp> #include <poplar/Tensor.hpp> namespace popnn { /** Calculate loss and gradient for a set of activations and * expected labels. * * \param graph Graph to add operations and tensors to. * \param modelOutputs 2D tensor of model outputs per-batch to calculate * loss for. * \param expected One-hot encoded tensor (Labels per-batch) with the * same number of rows as modelOutputs. Elements of * the expected labels may be masked by using * MASKED_LABEL_CODE. Such labels will not contribute * to loss calculation. * \param loss 1D Tensor to store the loss per-batch. Has * the same number of rows as modelOutputs. * \param deltas 2D Tensor to store deltas for each activation from * the expected per-batch. Has the same dimensions * as modelOutputs. * \param deltasScale Optional Tensor to scale output deltas with when * the lossType is CROSS_ENTROPY_LOSS. Scaling will * be deltasScale / modelOutputScaling. If no tensor * is specified a default will be created * initialised with 1.0. * \param modelOutputScaling Optional Tensor indicating the scaling of the * modelOutputs when lossType is CROSS_ENTROPY_LOSS, * normally from a softMax layer when the * nonLinearity used is SOFTMAX_SCALED. If no tensor * is specified a default will be created * initialised with 1.0. * \param lossType Method for calculating loss measurement. * \param debugContext Optional debug information. */ poplar::program::Program calcLoss(poplar::Graph &graph, const poplar::Tensor &modelOutputs, const poplar::Tensor &expected, const poplar::Tensor &loss, const poplar::Tensor &deltas, const poplar::Tensor &deltasScale, const poplar::Tensor &modelOutputScaling, LossType lossType, const poplar::DebugContext &debugContext = {}); poplar::program::Program calcLoss(poplar::Graph &graph, const poplar::Tensor &modelOutputs, const poplar::Tensor &expected, const poplar::Tensor &loss, const poplar::Tensor &deltas, LossType lossType, const poplar::DebugContext &debugContext = {}); /** Calculate loss, gradient, and number of correct classifications * per-batch for a set of activations and expected labels. * Elements of the expected labels may be masked by using * MASKED_LABEL_CODE. Such labels will not contribute to the accuracy * and loss calculation. * * \see `calcLoss`, and `calcAccuracy` which this function is simply * a combination of. */ poplar::program::Program calcLoss(poplar::Graph &graph, const poplar::Tensor &modelOutputs, const poplar::Tensor &expected, const poplar::Tensor &loss, const poplar::Tensor &deltas, const poplar::Tensor &deltasScale, const poplar::Tensor &modelOutputScaling, const poplar::Tensor &numCorrect, LossType lossType, const poplar::DebugContext &debugContext = {}); poplar::program::Program calcLoss(poplar::Graph &graph, const poplar::Tensor &modelOutputs, const poplar::Tensor &expected, const poplar::Tensor &loss, const poplar::Tensor &deltas, const poplar::Tensor &numCorrect, LossType lossType, const poplar::DebugContext &debugContext = {}); /** Calculate the number of correct classifications for a set of * activations and expected labels. * * \param graph Graph to add operations and tensors to. * \param modelOutputs 2D tensor of model outputs per-batch to calculate * loss for. * \param expected Labels per-batch. Elements of the expected labels * may be masked by using MASKED_LABEL_CODE. Such * labels will not contribute to the accuracy * calculation. * \param numCorrect Tensor to store the number of correct * classifications. Must be scalar, or single-element * Tensor. * \param activationType Device type used for activations. * \param expectedType Device type used for expected labels. * \param debugContext Optional debug information. */ poplar::program::Program calcAccuracy(poplar::Graph &graph, const poplar::Tensor &modelOutputs, const poplar::Tensor &expected, const poplar::Tensor &numCorrect, const poplar::DebugContext &debugContext = {}); /** Compute argmax for each of the outer dimensions of \p input tensor. * * If \p input is a tensor of dim [y][x] then argmax is computed over x * elements for each of the y outer dimension elements * * \param graph Graph to add operations and tensors to. * \param input 2D tensor of inputs * \param prog Program to which the graph for this operation is added * \param debugContext Optional debug information. */ poplar::Tensor argMax(poplar::Graph &graph, const poplar::Tensor &input, poplar::program::Sequence &prog, const poplar::DebugContext &debugContext = {}); /** Compute argmin for each of the outer dimensions of \p input tensor. * * If \p input is a tensor of dim [y][x] then argmin is computed over x * elements for each of the y outer dimension elements * * \param graph Graph to add operations and tensors to. * \param input 2D tensor of inputs * \param prog Program to which the graph for this operation is added * \param debugContext Optional debug information. */ poplar::Tensor argMin(poplar::Graph &graph, const poplar::Tensor &input, poplar::program::Sequence &prog, const poplar::DebugContext &debugContext = {}); /** Find the top K elements of |input|. Takes a 2D tensor in the form of * [batch][values] and will return a tensor in the shape of [batch][K] where K * is the max values of each batch of values. * * \param graph Graph to add operations and tensors to. * \param input 2D tensor of inputs * \param indices The tensor to store the indices in. * \param K The number of values to return. * \param sort If true values will be sorted in descending order. * \param prog Program to which the graph for this operation is added * \param debugContext Optional debug information. */ poplar::Tensor topK(poplar::Graph &graph, const poplar::Tensor &input, poplar::Tensor &indices, unsigned K, bool sort, poplar::program::Sequence &prog, const poplar::DebugContext &debugContext = {}); } // end namespace popnn #endif // !__POPC__ #endif // popnn_Loss_hpp
46.867925
80
0.638755
[ "shape", "model" ]
617892c9c5a01cd0c3668b8a956a1ea78d56254d
596
hpp
C++
mainapp/Classes/Games/ThirtyPuzzle/ThirtyPuzzleProblemBank.hpp
JaagaLabs/GLEXP-Team-KitkitSchool
f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0
[ "Apache-2.0" ]
45
2019-05-16T20:49:31.000Z
2021-11-05T21:40:54.000Z
mainapp/Classes/Games/ThirtyPuzzle/ThirtyPuzzleProblemBank.hpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
10
2019-05-17T13:38:22.000Z
2021-07-31T19:38:27.000Z
mainapp/Classes/Games/ThirtyPuzzle/ThirtyPuzzleProblemBank.hpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
29
2019-05-16T17:49:26.000Z
2021-12-30T16:36:24.000Z
// // ProblemBank.hpp // KitkitSchool-mobile // // Created by JungJaehun on 09/03/2018. // #pragma once #include "ThirtyPuzzleHeader.h" BEGIN_NS_THIRTYPUZZLE; struct ThirtyPuzzleLevelStruct { int level; int problem; string columns; string suggest; string isRandom; int problemNumber; }; class ProblemBank { static ProblemBank* _instance; public: static ProblemBank* getInstance(); void init(); vector<ThirtyPuzzleLevelStruct> loadData(int level); vector<int> getLevels(); private: int _maxLevel, _problemCount; }; END_NS_THIRTYPUZZLE;
17.028571
56
0.70302
[ "vector" ]
617b3eb4caa2005cc173c3b4b12dde3e3e356246
6,843
cpp
C++
Install/CodexDSSetupRunner.RTM/CodexSetupRunner/CodexSetupRunner.cpp
IrakliLomidze/CodexDS15
fb0dc7a6662068574d5cfe3ec5ce7b3d427ad723
[ "Unlicense" ]
null
null
null
Install/CodexDSSetupRunner.RTM/CodexSetupRunner/CodexSetupRunner.cpp
IrakliLomidze/CodexDS15
fb0dc7a6662068574d5cfe3ec5ce7b3d427ad723
[ "Unlicense" ]
null
null
null
Install/CodexDSSetupRunner.RTM/CodexSetupRunner/CodexSetupRunner.cpp
IrakliLomidze/CodexDS15
fb0dc7a6662068574d5cfe3ec5ce7b3d427ad723
[ "Unlicense" ]
null
null
null
// CodexSetupRunner.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "CodexSetupRunner.h" #include "CodexSetupRunnerDlg.h" #include "ILC\GeneralRun.h" #include <VersionHelpers.h> #include "ILC\detectFX.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CCodexSetupRunnerApp BEGIN_MESSAGE_MAP(CCodexSetupRunnerApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CCodexSetupRunnerApp construction CCodexSetupRunnerApp::CCodexSetupRunnerApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CCodexSetupRunnerApp object CCodexSetupRunnerApp theApp; // CCodexSetupRunnerApp initialization BOOL CCodexSetupRunnerApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); int dwRet = GetCurrentDirectory(MAX_PATH, this->CurrentPathStr); int dwRet2 = GetSystemDirectory(this->SystemPathStr, MAX_PATH); // Create the shell manager, in case the dialog contains // any shell tree view or shell list view controls. CShellManager *pShellManager = new CShellManager; // Activate "Windows Native" visual manager for enabling themes in MFC controls CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization //SetRegistryKey(_T("Local AppWizard-Generated Applications")); GeneralRun *r = new GeneralRun(); //BOOL isnr = r->NeedReboot(); // GeneralRun *r = new GeneralRun(); if (r->IsCurrentUserLocalAdministrator() == FALSE) { MessageBox(0,_T("To install Codex.net R4 Application you must be log as an Administrator"), _T("Codex.net R4 Installer"), MB_OK | MB_ICONINFORMATION); // Exit procudure copy from bottom // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; } if (!IsWindows7SP1OrGreater()) { MessageBox(NULL, _T("To Install Codex DS, You need at least Windows 7 with SP1"), _T("Windows Version Not Supported"), MB_ICONERROR | MB_OK); // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; } ILI_DOTNETFX *ili9 = new ILI_DOTNETFX(); if (ili9->IsNetfx461OrAboveInstalled() == false) { if (MessageBox(NULL, _T("To run Codex DS setup you should have at least .NET Framework 4.6.1 in your computer\n Do you want to install .net framework"), _T(" Warning "), MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2) == IDNO ) { #pragma region Deny_Install_NET_Framewokr // Exit from App // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; #pragma endregion Deny_Install_NET_Framewokr } else // Run .NET Framework 4 Instllation { //MessageBox(NULL, _T("111"), _T("2222"), 0); //NDP451-KB2858728-x86-x64-AllOS-ENU.exe #pragma region Install_NET_Framewokr CString runcommand = theApp.CurrentPathStr; runcommand.Append(_T("\\Packages\\netframework\\NDP461-KB3102436-x86-x64-AllOS-ENU.exe")); runcommand.Append(_T(" /qb ")); runcommand.Append(_T(" /promptrestart ")); DWORD d = ExecCmd2(runcommand); #pragma region responce //if (d == 0) netsetupstatus = 0; else netsetupstatus = 1; if (d != 0) { if (d == ERROR_SUCCESS_REBOOT_REQUIRED) { MessageBox(NULL, _T(" .Net Installation Completed \n Reboot Requred \n Please Reboot The System"), _T("Quesiton"), MB_ICONWARNING | MB_OK); } else MessageBox(NULL, _T(".NET Installation Failed Please See Log File"), _T("Quesiton"), MB_ICONWARNING | MB_OK); // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } return FALSE; } #pragma endregion responce #pragma endregion Install_NET_Framewokr } } // Run Codex Installer CString runcommand = theApp.CurrentPathStr; runcommand.Append(_T("\\Install\\CodexDSInstaller.exe")); //if (MessageBox(NULL, runcommand, _T(" Warning "), MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2)) CString WorkingDirectory = theApp.CurrentPathStr; WorkingDirectory.Append(_T("\\Install\\")); int nRet = (int)ShellExecute(NULL, _T("open"), runcommand, NULL, WorkingDirectory, SW_SHOWNORMAL); // DWORD d = ExecCmd2(runcommand); if (nRet <= 32) { DWORD dw = GetLastError(); /* char szMsg[250]; FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, 0, dw, 0, szMsg, sizeof(szMsg), NULL );*/ MessageBox(0, _T("Error launching Codex DS 1.5 Installer"), _T("Codex.net DS 1.5 Installer"), MB_OK | MB_ICONINFORMATION); } //CCodexSetupRunnerDlg dlg; //m_pMainWnd = &dlg; //INT_PTR nResponse = dlg.DoModal(); //if (nResponse == IDOK) //{ // // TODO: Place code here to handle when the dialog is // // dismissed with OK //} //else if (nResponse == IDCANCEL) //{ // // TODO: Place code here to handle when the dialog is // // dismissed with Cancel //} //else if (nResponse == -1) //{ // TRACE(traceAppMsg, 0, "Warning: dialog creation failed, so application is terminating unexpectedly.\n"); // TRACE(traceAppMsg, 0, "Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n"); //} // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
29.752174
224
0.723221
[ "object" ]
617c486013915d02d4e1dc0eb198d1491be1e59c
10,038
cc
C++
app/libs/hocr2pdf/hocr2pdf/src/codecs/png.cc
OCR-APPS-WEBSITES/textfairy
4af0b121137782b3c34d27fb5f5a1de30af9403d
[ "Apache-2.0" ]
3
2016-02-29T04:26:36.000Z
2018-07-12T03:11:24.000Z
app/libs/hocr2pdf/hocr2pdf/src/codecs/png.cc
OCR-APPS-WEBSITES/textfairy
4af0b121137782b3c34d27fb5f5a1de30af9403d
[ "Apache-2.0" ]
null
null
null
app/libs/hocr2pdf/hocr2pdf/src/codecs/png.cc
OCR-APPS-WEBSITES/textfairy
4af0b121137782b3c34d27fb5f5a1de30af9403d
[ "Apache-2.0" ]
3
2016-04-29T19:18:25.000Z
2018-10-13T07:05:05.000Z
/* * Copyright (C) 2006 - 2009 René Rebe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2. A copy of the GNU General * Public License can be found in the file LICENSE. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANT- * ABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * Alternatively, commercial licensing options are available from the * copyright holder ExactCODE GmbH Germany. */ #include <stdlib.h> #include <png.h> #include <iostream> #include "png.hh" #include "../utility/Endianess.hh" #define png_infopp_NULL (png_infopp)NULL #define int_p_NULL (int*)NULL #define png_bytepp_NULL (png_bytepp)NULL #define Z_BEST_COMPRESSION 100 void stdstream_read_data(png_structp png_ptr, png_bytep data, png_size_t length) { std::istream* stream = (std::istream*) png_get_io_ptr (png_ptr); stream->read ((char*)data, length); } void stdstream_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { std::ostream* stream = (std::ostream*) png_get_io_ptr (png_ptr); stream->write ((char*)data, length); } void stdstream_flush_data(png_structp png_ptr) { std::ostream* stream = (std::ostream*) png_get_io_ptr (png_ptr); stream = stream; } int PNGCodec::readImage (std::istream* stream, Image& image, const std::string& decompres) { { // quick magic check char buf [4]; stream->read (buf, sizeof (buf)); int cmp = png_sig_cmp ((png_byte*)buf, (png_size_t)0, sizeof (buf)); stream->seekg (0); if (cmp != 0) return false; } png_structp png_ptr; png_infop info_ptr; png_uint_32 width, height; int bit_depth, color_type, interlace_type; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL /*user_error_ptr*/, NULL /*user_error_fn*/, NULL /*user_warning_fn*/); if (png_ptr == NULL) return 0; /* Allocate/initialize the memory for image information. REQUIRED. */ info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL); return 0; } /* Set error handling if you are using the setjmp/longjmp method (this is * the normal method of doing things with libpng). REQUIRED unless you * set up your own error handlers in the png_create_read_struct() earlier. */ if (setjmp(png_jmpbuf(png_ptr))) { /* Free all of the memory associated with the png_ptr and info_ptr */ png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL); /* If we get here, we had a problem reading the file */ return 0; } /* Set up our STL stream input control */ png_set_read_fn (png_ptr, stream, &stdstream_read_data); ///* If we have already read some of the signature */ //png_set_sig_bytes(png_ptr, sig_read); /* The call to png_read_info() gives us all of the information from the * PNG file before the first IDAT (image data chunk). REQUIRED */ png_read_info (png_ptr, info_ptr); png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, int_p_NULL, int_p_NULL); image.w = width; image.h = height; image.bps = bit_depth; image.spp = png_get_channels(png_ptr, info_ptr); png_uint_32 res_x, res_y; res_x = png_get_x_pixels_per_meter(png_ptr, info_ptr); res_y = png_get_y_pixels_per_meter(png_ptr, info_ptr); image.setResolution((2.54 * res_x + .5) / 100, (2.54 * res_y + .5) / 100); /* Extract multiple pixels with bit depths of 1, 2, and 4 from a single * byte into separate bytes (useful for paletted and grayscale images) */ // png_set_packing(png_ptr); /* Change the order of packed pixels to least significant bit first * (not useful if you are using png_set_packing). */ // png_set_packswap(png_ptr); /* Expand paletted colors into true RGB triplets */ if (color_type == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); image.bps = 8; png_bytep trans_alpha; int num_trans; png_color_16p trans_color; png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color); if (num_trans) image.spp = 4; else image.spp = 3; } #if 0 // no longer needed /* Expand grayscale images to the full 8 bits from 2, or 4 bits/pixel */ if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth > 1 && bit_depth < 8) { png_set_gray_1_2_4_to_8(png_ptr); image.bps = 8; } #endif /* Expand paletted or RGB images with transparency to full alpha channels * so the data will be available as RGBA quartets. */ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr); /* Set the background color to draw transparent and alpha images over. * It is possible to set the red, green, and blue components directly * for paletted images instead of supplying a palette index. Note that * even if the PNG file supplies a background, you are not required to * use it - you should use the (solid) application background if it has one. */ #if 0 png_color_16* image_background; if (png_get_bKGD(png_ptr, info_ptr, &image_background)) { png_set_background(png_ptr, image_background, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0); image.spp = 3; } #endif /* If you want to shift the pixel values from the range [0,255] or * [0,65535] to the original [0,7] or [0,31], or whatever range the * colors were originally in: */ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT)) { png_color_8p sig_bit; png_get_sBIT(png_ptr, info_ptr, &sig_bit); png_set_shift(png_ptr, sig_bit); } /* swap bytes of 16 bit files to least significant byte first we store them in CPU byte order in memory */ if (Exact::NativeEndianTraits::IsBigendian) png_set_swap(png_ptr); /* Turn on interlace handling. REQURIED if you are not using * png_read_image(). To see how to handle interlacing passes, * see the png_read_row() method below: */ int number_passes = png_set_interlace_handling (png_ptr); /* Optional call to gamma correct and add the background to the palette * and update info structure. REQUIRED if you are expecting libpng to * update the palette for you (ie you selected such a transform above). */ png_read_update_info(png_ptr, info_ptr); /* Allocate the memory to hold the image using the fields of info_ptr. */ int stride = png_get_rowbytes (png_ptr, info_ptr); image.resize (image.w, image.h); png_bytep row_pointers[1]; /* The other way to read images - deal with interlacing: */ for (int pass = 0; pass < number_passes; ++pass) for (unsigned int y = 0; y < height; ++y) { row_pointers[0] = image.getRawData() + y * stride; png_read_rows(png_ptr, row_pointers, NULL, 1); } /* clean up after the read, and free any memory allocated - REQUIRED */ png_destroy_read_struct(&png_ptr, &info_ptr, NULL); /* that's it */ return true; } bool PNGCodec::writeImage (std::ostream* stream, Image& image, int quality, const std::string& compress) { png_structp png_ptr; png_infop info_ptr; png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL /*user_error_ptr*/, NULL /*user_error_fn*/, NULL /*user_warning_fn*/); if (png_ptr == NULL) { return false; } /* Allocate/initialize the memory for image information. REQUIRED. */ info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { png_destroy_write_struct(&png_ptr, png_infopp_NULL); return false; } /* Set error handling if you are using the setjmp/longjmp method (this is * the normal method of doing things with libpng). REQUIRED unless you * set up your own error handlers in the png_create_read_struct() earlier. */ if (setjmp(png_jmpbuf(png_ptr))) { /* Free all of the memory associated with the png_ptr and info_ptr */ png_destroy_write_struct(&png_ptr, &info_ptr); /* If we get here, we had a problem reading the file */ return false; } quality = Z_BEST_COMPRESSION * (quality + Z_BEST_COMPRESSION) / 100; if (quality < 1) quality = 1; else if (quality > Z_BEST_COMPRESSION) quality = Z_BEST_COMPRESSION; png_set_compression_level(png_ptr, quality); //png_info_init (info_ptr); /* Set up our STL stream output control */ png_set_write_fn (png_ptr, stream, &stdstream_write_data, &stdstream_flush_data); ///* If we have already read some of the signature */ //png_set_sig_bytes(png_ptr, sig_read); int color_type; switch (image.spp) { case 1: color_type = PNG_COLOR_TYPE_GRAY; break; case 4: color_type = PNG_COLOR_TYPE_RGB_ALPHA; break; default: color_type = PNG_COLOR_TYPE_RGB; } png_set_IHDR (png_ptr, info_ptr, image.w, image.h, image.bps, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_BASE); png_set_pHYs (png_ptr, info_ptr, (int)(image.resolutionX() * 100 / 2.54), (int)(image.resolutionY() * 100 / 2.54), PNG_RESOLUTION_METER); png_write_info (png_ptr, info_ptr); int stride = png_get_rowbytes (png_ptr, info_ptr); /* swap bytes of 16 bit data as PNG stores in network-byte-order */ if (!Exact::NativeEndianTraits::IsBigendian) png_set_swap(png_ptr); png_bytep row_pointers[1]; /* The other way to write images */ int number_passes = 1; for (int pass = 0; pass < number_passes; ++pass) for (int y = 0; y < image.h; ++y) { row_pointers[0] = image.getRawData() + y * stride; png_write_rows(png_ptr, (png_byte**)&row_pointers, 1); } png_write_end(png_ptr, NULL); /* clean up after the read, and free any memory allocated - REQUIRED */ png_destroy_write_struct(&png_ptr, &info_ptr); return true; } PNGCodec png_loader;
32.173077
90
0.70004
[ "transform", "solid" ]
617f7c1816c13546cc6c55d0db885a31c253089d
5,218
hh
C++
controller/src/map/gui/soccerview.hh
GuttinRibeiro/TCC
fa0fe1f65e651f940ac0b9c2d0cf228c986f32bd
[ "MIT" ]
null
null
null
controller/src/map/gui/soccerview.hh
GuttinRibeiro/TCC
fa0fe1f65e651f940ac0b9c2d0cf228c986f32bd
[ "MIT" ]
null
null
null
controller/src/map/gui/soccerview.hh
GuttinRibeiro/TCC
fa0fe1f65e651f940ac0b9c2d0cf228c986f32bd
[ "MIT" ]
null
null
null
//======================================================================== // This software is free: you can redistribute it and/or modify // it under the terms of the GNU General Public License Version 3, // as published by the Free Software Foundation. // // This software 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 // Version 3 in the file COPYING that came with this distribution. // If not, see <http://www.gnu.org/licenses/>. //======================================================================== /*! \file soccerview.h \brief C++ Interface: GLSoccerView \author Joydeep Biswas (C) 2011 */ //======================================================================== #ifndef SOCCERVIEW_H #define SOCCERVIEW_H #include <QtCore> #include <QMouseEvent> #include <QWidget> #include <QGLWidget> #include <QMutex> #include <QVector> #include <GL/glu.h> #include <math.h> #include <float.h> #include <stdio.h> #include <cstdio> #include "util/timer.hh" #include "util/geometry.hh" #include "util/field.hh" #include "util/util.h" #include "gltext.hh" #include "../../utils/field.hpp" #include "../../utils/element.hpp" using namespace std; #define FIELD_COLOR 0.0,0.5686,0.0980,1.0 #define FIELD_LINES_COLOR 1.0,1.0,1.0,1.0 #define PATHDRAWING_FRAMES 20 #define PATHDRAWING_FREQUENCY_HZ 20 class GLSoccerView : public QGLWidget { Q_OBJECT public: struct FieldDimensions { vector<FieldLine*> lines; vector<FieldCircularArc*> arcs; vector<FieldTriangle*> triangles; double field_length; double field_width; double boundary_width; FieldDimensions(); }; struct SoccerViewRobot { bool hasAngle; vector2d loc; double angle; int id; double conf; int team; int cameraID; }; typedef enum { teamUnknown = 0, teamBlue, teamYellow } TeamTypes; private: static constexpr double minZValue = -10; static constexpr double maxZValue = 10; static constexpr double FieldZ = 1.0; static constexpr double RobotZ = 2.0; static constexpr double BallZ = 3.0; static const int PreferedWidth = 1024; static const int PreferedHeight = 768; static constexpr double MinRedrawInterval = 0.01; ///Minimum time between graphics updates (limits the fps) static const int unknownRobotID = -1; QVector<SoccerViewRobot> robots; QVector<vector2d> robotsVelocities; QVector<std::pair<int, vector2d> > robotsNextPositions; QVector<QLinkedList<Vector> > robotsPaths; vector2d ball; vector2d ballVelocity; QMutex graphicsMutex; GLText glText; GLuint blueRobotShape; GLuint yellowRobotShape; GLuint greyRobotShape; GLuint blueCircleRobotShape; GLuint yellowCircleRobotShape; GLuint greyCircleRobotShape; double viewScale; /// Ratio of world space to screen space coordinates double viewXOffset; double viewYOffset; bool leftButton; bool midButton; bool rightButton; int mouseStartX; int mouseStartY; double tLastRedraw; FieldDimensions fieldDim; private: void drawFieldLines(FieldDimensions &dimensions); void drawRobots(); void drawRobotsVelocities(); void drawRobotTrajetory(const QLinkedList<Vector> &path); void drawRobotsNextPositions(); void drawBalls(); void drawBallsVelocities(); void drawX(vector2d nextPos); void drawStippleLine(vector2d pos, vector2d nextPos); void drawQuad(vector2d loc1, vector2d loc2, double z=0.0); void drawQuad(double x1, double y1, double x2, double y2, double z=0.0){drawQuad(vector2d(x1,y1),vector2d(x2,y2),z);} void drawQuad(vector2d v1, vector2d v2, vector2d v3, vector2d v4, double z); void drawArc(vector2d loc, double r1, double r2, double theta1, double theta2, double z=0.0, double dTheta = -1); void drawArc(double x, double y, double r1, double r2, double theta1, double theta2, double z=0.0, double dTheta = -1){drawArc(vector2d(x,y),r1,r2,theta1,theta2,z,dTheta);} void drawTriangle(vector2d v1, vector2d v2, vector2d v3, double z); void recomputeProjection(); void drawRobot(vector2d loc, double theta, double conf, int robotID, int team, bool hasAngle); void drawRobot(int team, bool hasAngle, bool useDisplayLists); void drawBall(vector2d loc); void drawVector(vector2d v1, vector2d v2, double z); void vectorTextTest(); void updateDefaultFieldDimensions(); protected: void paintEvent(QPaintEvent *event); void wheelEvent(QWheelEvent *event); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void keyPressEvent(QKeyEvent *event); void resizeEvent(QResizeEvent *event); void initializeGL(); void resizeGL(int width, int height); QSize sizeHint() const { return QSize(PreferedWidth,PreferedHeight); } public: GLSoccerView(QWidget *parent = nullptr); void updateDetection(Element ballInfo, QHash<qint8, Element> blueTeam, QHash<qint8, Element> yellowTeam); void updateFieldGeometry(Field *field); public slots: void resetView(); private slots: void redraw(); signals: void postRedraw(); }; #endif
29.817143
173
0.721349
[ "geometry", "vector" ]
61822b8e31430e5388c691f39fa86fee342c25ba
8,142
cc
C++
src/init/isolate-allocator.cc
KDr2/v8
6048f754931e0971cab58fb0de785482d175175b
[ "BSD-3-Clause" ]
null
null
null
src/init/isolate-allocator.cc
KDr2/v8
6048f754931e0971cab58fb0de785482d175175b
[ "BSD-3-Clause" ]
null
null
null
src/init/isolate-allocator.cc
KDr2/v8
6048f754931e0971cab58fb0de785482d175175b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/init/isolate-allocator.h" #include "src/base/bounded-page-allocator.h" #include "src/execution/isolate.h" #include "src/heap/code-range.h" #include "src/sandbox/sandbox.h" #include "src/utils/memcopy.h" #include "src/utils/utils.h" namespace v8 { namespace internal { #ifdef V8_COMPRESS_POINTERS namespace { // "IsolateRootBiasPage" is an optional region before the 4Gb aligned // reservation. This "IsolateRootBiasPage" page is supposed to be used for // storing part of the Isolate object when Isolate::isolate_root_bias() is // not zero. inline size_t GetIsolateRootBiasPageSize( v8::PageAllocator* platform_page_allocator) { return RoundUp(Isolate::isolate_root_bias(), platform_page_allocator->AllocatePageSize()); } } // namespace struct PtrComprCageReservationParams : public VirtualMemoryCage::ReservationParams { PtrComprCageReservationParams() { page_allocator = GetPlatformPageAllocator(); // This is only used when there is a per-Isolate cage, in which case the // Isolate is allocated within the cage, and the Isolate root is also the // cage base. const size_t kIsolateRootBiasPageSize = COMPRESS_POINTERS_IN_ISOLATE_CAGE_BOOL ? GetIsolateRootBiasPageSize(page_allocator) : 0; reservation_size = kPtrComprCageReservationSize + kIsolateRootBiasPageSize; base_alignment = kPtrComprCageBaseAlignment; base_bias_size = kIsolateRootBiasPageSize; // Simplify BoundedPageAllocator's life by configuring it to use same page // size as the Heap will use (MemoryChunk::kPageSize). page_size = RoundUp(size_t{1} << kPageSizeBits, page_allocator->AllocatePageSize()); requested_start_hint = reinterpret_cast<Address>(page_allocator->GetRandomMmapAddr()); jit = JitPermission::kNoJit; } }; #endif // V8_COMPRESS_POINTERS #ifdef V8_COMPRESS_POINTERS_IN_SHARED_CAGE namespace { DEFINE_LAZY_LEAKY_OBJECT_GETTER(VirtualMemoryCage, GetProcessWidePtrComprCage) } // anonymous namespace // static void IsolateAllocator::FreeProcessWidePtrComprCageForTesting() { if (std::shared_ptr<CodeRange> code_range = CodeRange::GetProcessWideCodeRange()) { code_range->Free(); } GetProcessWidePtrComprCage()->Free(); } #endif // V8_COMPRESS_POINTERS_IN_SHARED_CAGE // static void IsolateAllocator::InitializeOncePerProcess() { #ifdef V8_COMPRESS_POINTERS_IN_SHARED_CAGE PtrComprCageReservationParams params; base::AddressRegion existing_reservation; #ifdef V8_ENABLE_SANDBOX // For now, we allow the sandbox to be disabled even when compiling with // v8_enable_sandbox. This fallback will be disallowed in the future, at the // latest once sandboxed pointers are enabled. if (GetProcessWideSandbox()->is_disabled()) { CHECK(kAllowBackingStoresOutsideSandbox); } else { auto sandbox = GetProcessWideSandbox(); CHECK(sandbox->is_initialized()); // The pointer compression cage must be placed at the start of the sandbox. // TODO(chromium:12180) this currently assumes that no other pages were // allocated through the cage's page allocator in the meantime. In the // future, the cage initialization will happen just before this function // runs, and so this will be guaranteed. Currently however, it is possible // that the embedder accidentally uses the cage's page allocator prior to // initializing V8, in which case this CHECK will likely fail. Address base = sandbox->address_space()->AllocatePages( sandbox->base(), params.reservation_size, params.base_alignment, PagePermissions::kNoAccess); CHECK_EQ(sandbox->base(), base); existing_reservation = base::AddressRegion(base, params.reservation_size); params.page_allocator = sandbox->page_allocator(); } #endif if (!GetProcessWidePtrComprCage()->InitReservation(params, existing_reservation)) { V8::FatalProcessOutOfMemory( nullptr, "Failed to reserve virtual memory for process-wide V8 " "pointer compression cage"); } #endif } IsolateAllocator::IsolateAllocator() { #if defined(V8_COMPRESS_POINTERS_IN_ISOLATE_CAGE) PtrComprCageReservationParams params; if (!isolate_ptr_compr_cage_.InitReservation(params)) { V8::FatalProcessOutOfMemory( nullptr, "Failed to reserve memory for Isolate V8 pointer compression cage"); } page_allocator_ = isolate_ptr_compr_cage_.page_allocator(); CommitPagesForIsolate(); #elif defined(V8_COMPRESS_POINTERS_IN_SHARED_CAGE) // Allocate Isolate in C++ heap when sharing a cage. CHECK(GetProcessWidePtrComprCage()->IsReserved()); page_allocator_ = GetProcessWidePtrComprCage()->page_allocator(); isolate_memory_ = ::operator new(sizeof(Isolate)); #else // Allocate Isolate in C++ heap. page_allocator_ = GetPlatformPageAllocator(); isolate_memory_ = ::operator new(sizeof(Isolate)); #endif // V8_COMPRESS_POINTERS CHECK_NOT_NULL(page_allocator_); } IsolateAllocator::~IsolateAllocator() { #ifdef V8_COMPRESS_POINTERS_IN_ISOLATE_CAGE if (isolate_ptr_compr_cage_.reservation()->IsReserved()) { // The actual memory will be freed when the |isolate_ptr_compr_cage_| will // die. return; } #endif // The memory was allocated in C++ heap. ::operator delete(isolate_memory_); } VirtualMemoryCage* IsolateAllocator::GetPtrComprCage() { #if defined V8_COMPRESS_POINTERS_IN_ISOLATE_CAGE return &isolate_ptr_compr_cage_; #elif defined V8_COMPRESS_POINTERS_IN_SHARED_CAGE return GetProcessWidePtrComprCage(); #else return nullptr; #endif } const VirtualMemoryCage* IsolateAllocator::GetPtrComprCage() const { return const_cast<IsolateAllocator*>(this)->GetPtrComprCage(); } #ifdef V8_COMPRESS_POINTERS_IN_ISOLATE_CAGE void IsolateAllocator::CommitPagesForIsolate() { v8::PageAllocator* platform_page_allocator = GetPlatformPageAllocator(); CHECK(isolate_ptr_compr_cage_.IsReserved()); Address isolate_root = isolate_ptr_compr_cage_.base(); CHECK(IsAligned(isolate_root, kPtrComprCageBaseAlignment)); CHECK_GE(isolate_ptr_compr_cage_.reservation()->size(), kPtrComprCageReservationSize + GetIsolateRootBiasPageSize(platform_page_allocator)); CHECK(isolate_ptr_compr_cage_.reservation()->InVM( isolate_root, kPtrComprCageReservationSize)); size_t page_size = page_allocator_->AllocatePageSize(); Address isolate_address = isolate_root - Isolate::isolate_root_bias(); Address isolate_end = isolate_address + sizeof(Isolate); // Inform the bounded page allocator about reserved pages. { Address reserved_region_address = isolate_root; size_t reserved_region_size = RoundUp(isolate_end, page_size) - reserved_region_address; CHECK(isolate_ptr_compr_cage_.page_allocator()->AllocatePagesAt( reserved_region_address, reserved_region_size, PageAllocator::Permission::kNoAccess)); } // Commit pages where the Isolate will be stored. { size_t commit_page_size = platform_page_allocator->CommitPageSize(); Address committed_region_address = RoundDown(isolate_address, commit_page_size); size_t committed_region_size = RoundUp(isolate_end, commit_page_size) - committed_region_address; // We are using |isolate_ptr_compr_cage_.reservation()| directly here // because |page_allocator_| has bigger commit page size than we actually // need. CHECK(isolate_ptr_compr_cage_.reservation()->SetPermissions( committed_region_address, committed_region_size, PageAllocator::kReadWrite)); if (Heap::ShouldZapGarbage()) { MemsetPointer(reinterpret_cast<Address*>(committed_region_address), kZapValue, committed_region_size / kSystemPointerSize); } } isolate_memory_ = reinterpret_cast<void*>(isolate_address); } #endif // V8_COMPRESS_POINTERS_IN_ISOLATE_CAGE } // namespace internal } // namespace v8
37.178082
80
0.751781
[ "object" ]
6187617e05d24801b62a2ba93bf38b81e45654d9
254
cpp
C++
with_cpp14/matplotlib_basic.cpp
MengqiYe/Test_Cpp_Standards
3acf52bd4457be007534b2b481f01a3bdfda0813
[ "MIT" ]
null
null
null
with_cpp14/matplotlib_basic.cpp
MengqiYe/Test_Cpp_Standards
3acf52bd4457be007534b2b481f01a3bdfda0813
[ "MIT" ]
null
null
null
with_cpp14/matplotlib_basic.cpp
MengqiYe/Test_Cpp_Standards
3acf52bd4457be007534b2b481f01a3bdfda0813
[ "MIT" ]
null
null
null
// // Created by mqye on 2020/9/29. // #include "common.h" #include "matplotlibcpp.h" #include <vector> namespace plt = matplotlibcpp; int main() { std::vector<double> y = {1, 3, 2, 4}; plt::plot(y); plt::savefig("minimal.pdf"); plt::show(); }
15.875
39
0.61811
[ "vector" ]
618e3fc3897fce8a831f7b43ec668f52a47d4d82
42,842
cc
C++
extensions/browser/api/management/management_api.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
extensions/browser/api/management/management_api.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
extensions/browser/api/management/management_api.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/api/management/management_api.h" #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/json/json_writer.h" #include "base/lazy_instance.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "content/public/browser/browser_context.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/management/management_api_constants.h" #include "extensions/browser/disable_reason.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/management_policy.h" #include "extensions/browser/requirements_checker.h" #include "extensions/browser/uninstall_reason.h" #include "extensions/common/api/management.h" #include "extensions/common/error_utils.h" #include "extensions/common/extension.h" #include "extensions/common/extension_icon_set.h" #include "extensions/common/manifest.h" #include "extensions/common/manifest_handlers/icons_handler.h" #include "extensions/common/manifest_handlers/offline_enabled_info.h" #include "extensions/common/manifest_handlers/options_page_info.h" #include "extensions/common/manifest_handlers/replacement_apps.h" #include "extensions/common/manifest_url_handlers.h" #include "extensions/common/permissions/permission_message.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/url_pattern.h" #include "url/gurl.h" #include "url/url_constants.h" using content::BrowserThread; namespace keys = extension_management_api_constants; namespace extensions { namespace management = api::management; namespace { typedef std::vector<management::ExtensionInfo> ExtensionInfoList; typedef std::vector<management::IconInfo> IconInfoList; enum AutoConfirmForTest { DO_NOT_SKIP = 0, PROCEED, ABORT }; AutoConfirmForTest auto_confirm_for_test = DO_NOT_SKIP; std::vector<std::string> CreateWarningsList(const Extension* extension) { std::vector<std::string> warnings_list; for (const PermissionMessage& msg : extension->permissions_data()->GetPermissionMessages()) { warnings_list.push_back(base::UTF16ToUTF8(msg.message())); } return warnings_list; } std::vector<management::LaunchType> GetAvailableLaunchTypes( const Extension& extension, const ManagementAPIDelegate* delegate) { std::vector<management::LaunchType> launch_type_list; if (extension.is_platform_app()) { launch_type_list.push_back(management::LAUNCH_TYPE_OPEN_AS_WINDOW); return launch_type_list; } launch_type_list.push_back(management::LAUNCH_TYPE_OPEN_AS_REGULAR_TAB); launch_type_list.push_back(management::LAUNCH_TYPE_OPEN_AS_WINDOW); return launch_type_list; } management::ExtensionInfo CreateExtensionInfo( const Extension* source_extension, const Extension& extension, content::BrowserContext* context) { ExtensionSystem* system = ExtensionSystem::Get(context); ExtensionRegistry* registry = ExtensionRegistry::Get(context); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance()->Get(context)->GetDelegate(); management::ExtensionInfo info; info.id = extension.id(); info.name = extension.name(); info.short_name = extension.short_name(); info.enabled = registry->enabled_extensions().Contains(info.id); info.offline_enabled = OfflineEnabledInfo::IsOfflineEnabled(&extension); info.version = extension.VersionString(); if (!extension.version_name().empty()) info.version_name.reset(new std::string(extension.version_name())); info.description = extension.description(); info.options_url = OptionsPageInfo::GetOptionsPage(&extension).spec(); info.homepage_url.reset( new std::string(ManifestURL::GetHomepageURL(&extension).spec())); info.may_disable = !system->management_policy()->MustRemainEnabled(&extension, nullptr); info.is_app = extension.is_app(); if (info.is_app) { if (extension.is_legacy_packaged_app()) info.type = management::EXTENSION_TYPE_LEGACY_PACKAGED_APP; else if (extension.is_hosted_app()) info.type = management::EXTENSION_TYPE_HOSTED_APP; else info.type = management::EXTENSION_TYPE_PACKAGED_APP; } else if (extension.is_theme()) { info.type = management::EXTENSION_TYPE_THEME; } else if (extension.is_login_screen_extension()) { info.type = management::EXTENSION_TYPE_LOGIN_SCREEN_EXTENSION; } else { info.type = management::EXTENSION_TYPE_EXTENSION; } if (info.enabled) { info.disabled_reason = management::EXTENSION_DISABLED_REASON_NONE; } else { ExtensionPrefs* prefs = ExtensionPrefs::Get(context); if (prefs->DidExtensionEscalatePermissions(extension.id())) { info.disabled_reason = management::EXTENSION_DISABLED_REASON_PERMISSIONS_INCREASE; } else { info.disabled_reason = management::EXTENSION_DISABLED_REASON_UNKNOWN; } info.may_enable = std::make_unique<bool>( system->management_policy()->ExtensionMayModifySettings( source_extension, &extension, nullptr) && !system->management_policy()->MustRemainDisabled(&extension, nullptr, nullptr)); } const GURL update_url = delegate->GetEffectiveUpdateURL(extension, context); if (!update_url.is_empty()) info.update_url = std::make_unique<std::string>(update_url.spec()); if (extension.is_app()) { info.app_launch_url.reset( new std::string(delegate->GetFullLaunchURL(&extension).spec())); } const ExtensionIconSet::IconMap& icons = IconsInfo::GetIcons(&extension).map(); if (!icons.empty()) { info.icons.reset(new IconInfoList()); ExtensionIconSet::IconMap::const_iterator icon_iter; for (icon_iter = icons.begin(); icon_iter != icons.end(); ++icon_iter) { management::IconInfo icon_info; icon_info.size = icon_iter->first; GURL url = delegate->GetIconURL(&extension, icon_info.size, ExtensionIconSet::MATCH_EXACTLY, false); icon_info.url = url.spec(); info.icons->push_back(std::move(icon_info)); } } const std::set<std::string> perms = extension.permissions_data()->active_permissions().GetAPIsAsStrings(); if (!perms.empty()) { std::set<std::string>::const_iterator perms_iter; for (perms_iter = perms.begin(); perms_iter != perms.end(); ++perms_iter) info.permissions.push_back(*perms_iter); } if (!extension.is_hosted_app()) { // Skip host permissions for hosted apps. const URLPatternSet& host_perms = extension.permissions_data()->active_permissions().explicit_hosts(); if (!host_perms.is_empty()) { for (auto iter = host_perms.begin(); iter != host_perms.end(); ++iter) { info.host_permissions.push_back(iter->GetAsString()); } } } switch (extension.location()) { case Manifest::INTERNAL: info.install_type = management::EXTENSION_INSTALL_TYPE_NORMAL; break; case Manifest::UNPACKED: case Manifest::COMMAND_LINE: info.install_type = management::EXTENSION_INSTALL_TYPE_DEVELOPMENT; break; case Manifest::EXTERNAL_PREF: case Manifest::EXTERNAL_REGISTRY: case Manifest::EXTERNAL_PREF_DOWNLOAD: info.install_type = management::EXTENSION_INSTALL_TYPE_SIDELOAD; break; case Manifest::EXTERNAL_POLICY: case Manifest::EXTERNAL_POLICY_DOWNLOAD: info.install_type = management::EXTENSION_INSTALL_TYPE_ADMIN; break; case Manifest::NUM_LOCATIONS: NOTREACHED(); FALLTHROUGH; case Manifest::INVALID_LOCATION: case Manifest::COMPONENT: case Manifest::EXTERNAL_COMPONENT: info.install_type = management::EXTENSION_INSTALL_TYPE_OTHER; break; } info.launch_type = management::LAUNCH_TYPE_NONE; if (extension.is_app()) { LaunchType launch_type; if (extension.is_platform_app()) { launch_type = LAUNCH_TYPE_WINDOW; } else { launch_type = delegate->GetLaunchType(ExtensionPrefs::Get(context), &extension); } switch (launch_type) { case LAUNCH_TYPE_PINNED: info.launch_type = management::LAUNCH_TYPE_OPEN_AS_PINNED_TAB; break; case LAUNCH_TYPE_REGULAR: info.launch_type = management::LAUNCH_TYPE_OPEN_AS_REGULAR_TAB; break; case LAUNCH_TYPE_FULLSCREEN: info.launch_type = management::LAUNCH_TYPE_OPEN_FULL_SCREEN; break; case LAUNCH_TYPE_WINDOW: info.launch_type = management::LAUNCH_TYPE_OPEN_AS_WINDOW; break; case LAUNCH_TYPE_INVALID: case NUM_LAUNCH_TYPES: NOTREACHED(); } info.available_launch_types.reset(new std::vector<management::LaunchType>( GetAvailableLaunchTypes(extension, delegate))); } return info; } void AddExtensionInfo(const Extension* source_extension, const ExtensionSet& extensions, ExtensionInfoList* extension_list, content::BrowserContext* context) { for (ExtensionSet::const_iterator iter = extensions.begin(); iter != extensions.end(); ++iter) { const Extension& extension = **iter; if (!extension.ShouldExposeViaManagementAPI()) continue; extension_list->push_back( CreateExtensionInfo(source_extension, extension, context)); } } } // namespace ExtensionFunction::ResponseAction ManagementGetAllFunction::Run() { ExtensionInfoList extensions; ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); AddExtensionInfo(extension(), registry->enabled_extensions(), &extensions, browser_context()); AddExtensionInfo(extension(), registry->disabled_extensions(), &extensions, browser_context()); AddExtensionInfo(extension(), registry->terminated_extensions(), &extensions, browser_context()); return RespondNow( ArgumentList(management::GetAll::Results::Create(extensions))); } ExtensionFunction::ResponseAction ManagementGetFunction::Run() { std::unique_ptr<management::Get::Params> params( management::Get::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); const Extension* target_extension = registry->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); if (!target_extension) return RespondNow(Error(keys::kNoExtensionError, params->id)); return RespondNow(ArgumentList(management::Get::Results::Create( CreateExtensionInfo(extension(), *target_extension, browser_context())))); } ExtensionFunction::ResponseAction ManagementGetSelfFunction::Run() { return RespondNow(ArgumentList(management::Get::Results::Create( CreateExtensionInfo(extension(), *extension_, browser_context())))); } ExtensionFunction::ResponseAction ManagementGetPermissionWarningsByIdFunction::Run() { std::unique_ptr<management::GetPermissionWarningsById::Params> params( management::GetPermissionWarningsById::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); if (!extension) return RespondNow(Error(keys::kNoExtensionError, params->id)); std::vector<std::string> warnings = CreateWarningsList(extension); return RespondNow(ArgumentList( management::GetPermissionWarningsById::Results::Create(warnings))); } ExtensionFunction::ResponseAction ManagementGetPermissionWarningsByManifestFunction::Run() { std::unique_ptr<management::GetPermissionWarningsByManifest::Params> params( management::GetPermissionWarningsByManifest::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); if (delegate) { delegate->GetPermissionWarningsByManifestFunctionDelegate( this, params->manifest_str); // Matched with a Release() in OnParse(). AddRef(); // Response is sent async in OnParse(). return RespondLater(); } else { // TODO(lfg) add error string return RespondNow(Error(kUnknownErrorDoNotUse)); } } void ManagementGetPermissionWarningsByManifestFunction::OnParse( data_decoder::DataDecoder::ValueOrError result) { if (!result.value) { Respond(Error(*result.error)); // Matched with AddRef() in Run(). Release(); return; } const base::DictionaryValue* parsed_manifest; if (!result.value->GetAsDictionary(&parsed_manifest)) { Respond(Error(keys::kManifestParseError)); Release(); return; } std::string error; scoped_refptr<Extension> extension = Extension::Create(base::FilePath(), Manifest::INVALID_LOCATION, *parsed_manifest, Extension::NO_FLAGS, &error); // TODO(lazyboy): Do we need to use |error|? if (!extension) { Respond(Error(keys::kExtensionCreateError)); Release(); return; } std::vector<std::string> warnings = CreateWarningsList(extension.get()); Respond(ArgumentList( management::GetPermissionWarningsByManifest::Results::Create(warnings))); // Matched with AddRef() in Run(). Release(); } ExtensionFunction::ResponseAction ManagementLaunchAppFunction::Run() { std::unique_ptr<management::LaunchApp::Params> params( management::LaunchApp::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) return RespondNow(Error(keys::kNotAllowedInKioskError)); const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); if (!extension) return RespondNow(Error(keys::kNoExtensionError, params->id)); if (!extension->is_app()) return RespondNow(Error(keys::kNotAnAppError, params->id)); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); delegate->LaunchAppFunctionDelegate(extension, browser_context()); return RespondNow(NoArguments()); } ManagementSetEnabledFunction::ManagementSetEnabledFunction() = default; ManagementSetEnabledFunction::~ManagementSetEnabledFunction() = default; ExtensionFunction::ResponseAction ManagementSetEnabledFunction::Run() { std::unique_ptr<management::SetEnabled::Params> params( management::SetEnabled::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); extension_id_ = params->id; if (ExtensionsBrowserClient::Get()->IsAppModeForcedForApp(extension_id_)) return RespondNow(Error(keys::kCannotChangePrimaryKioskAppError)); ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); const Extension* target_extension = registry->GetExtensionById(extension_id_, ExtensionRegistry::EVERYTHING); if (!target_extension || !target_extension->ShouldExposeViaManagementAPI()) return RespondNow(Error(keys::kNoExtensionError, extension_id_)); bool should_enable = params->enabled; const ManagementPolicy* policy = ExtensionSystem::Get(browser_context())->management_policy(); if (!policy->ExtensionMayModifySettings(extension(), target_extension, nullptr)) { return RespondNow(Error(keys::kUserCantModifyError, extension_id_)); } SupervisedUserExtensionsDelegate* supervised_user_extensions_delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetSupervisedUserExtensionsDelegate(); if (supervised_user_extensions_delegate && supervised_user_extensions_delegate->IsChild(browser_context()) && // Don't prompt the user if the extension has unsupported requirements. // TODO(crbug/1071978): If OnRequirementsChecked() passes, the extension // will enable, bypassing parent approval. !HasUnsupportedRequirements(extension_id_) && // Only ask for parent approval if the extension still requires approval. !supervised_user_extensions_delegate->IsExtensionAllowedByParent( *target_extension, browser_context())) { // Either ask for parent permission or notify the child that their parent // has disabled this action. auto parent_permission_callback = base::BindOnce( &ManagementSetEnabledFunction::OnParentPermissionDialogDone, this); auto error_callback = base::BindOnce( &ManagementSetEnabledFunction::OnBlockedByParentDialogDone, this); AddRef(); // Matched in OnParentPermissionDialogDone() or // OnBlockedByParentDialogDone(). supervised_user_extensions_delegate->PromptForParentPermissionOrShowError( *target_extension, browser_context(), GetSenderWebContents(), std::move(parent_permission_callback), std::move(error_callback)); return RespondLater(); } if (should_enable && policy->MustRemainDisabled(target_extension, nullptr, nullptr)) { return RespondNow(Error(keys::kUserCantModifyError, extension_id_)); } bool currently_enabled = registry->enabled_extensions().Contains(extension_id_) || registry->terminated_extensions().Contains(extension_id_); if (!currently_enabled && should_enable) { ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context()); if (prefs->DidExtensionEscalatePermissions(extension_id_)) { if (!user_gesture()) return RespondNow(Error(keys::kGestureNeededForEscalationError)); AddRef(); // Matched in OnInstallPromptDone(). install_prompt_ = delegate->SetEnabledFunctionDelegate( GetSenderWebContents(), browser_context(), target_extension, base::BindOnce(&ManagementSetEnabledFunction::OnInstallPromptDone, this)); return RespondLater(); } if (HasUnsupportedRequirements(extension_id_)) { // Recheck the requirements. requirements_checker_ = std::make_unique<RequirementsChecker>(target_extension); requirements_checker_->Start( base::BindOnce(&ManagementSetEnabledFunction::OnRequirementsChecked, this)); // This bind creates a reference. return RespondLater(); } delegate->EnableExtension(browser_context(), extension_id_); } else if (currently_enabled && !params->enabled) { delegate->DisableExtension( browser_context(), extension(), extension_id_, Manifest::IsPolicyLocation(target_extension->location()) ? disable_reason::DISABLE_BLOCKED_BY_POLICY : disable_reason::DISABLE_USER_ACTION); } return RespondNow(NoArguments()); } void ManagementSetEnabledFunction::OnInstallPromptDone(bool did_accept) { if (did_accept) { ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate() ->EnableExtension(browser_context(), extension_id_); Respond(NoArguments()); } else { Respond(Error(keys::kUserDidNotReEnableError)); } Release(); // Balanced in Run(). } bool ManagementSetEnabledFunction::HasUnsupportedRequirements( const std::string& extension_id) { ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context()); return prefs->GetDisableReasons(extension_id) & disable_reason::DISABLE_UNSUPPORTED_REQUIREMENT; } void ManagementSetEnabledFunction::OnRequirementsChecked( const PreloadCheck::Errors& errors) { if (errors.empty()) { ManagementAPI::GetFactoryInstance()->Get(browser_context())->GetDelegate()-> EnableExtension(browser_context(), extension_id_); Respond(NoArguments()); } else { // TODO(devlin): Should we really be noisy here all the time? Respond(Error(keys::kMissingRequirementsError, base::UTF16ToUTF8(requirements_checker_->GetErrorMessage()))); } } void ManagementSetEnabledFunction::OnParentPermissionDialogDone( SupervisedUserExtensionsDelegate::ParentPermissionDialogResult result) { #if BUILDFLAG(IS_CHROMEOS_ASH) switch (result) { case SupervisedUserExtensionsDelegate::ParentPermissionDialogResult:: kParentPermissionReceived: { const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); delegate->EnableExtension(browser_context(), extension_id_); Respond(NoArguments()); break; } case SupervisedUserExtensionsDelegate::ParentPermissionDialogResult:: kParentPermissionCanceled: { Respond(Error(keys::kUserDidNotReEnableError)); break; } case SupervisedUserExtensionsDelegate::ParentPermissionDialogResult:: kParentPermissionFailed: { Respond(Error(keys::kParentPermissionFailedError)); break; } } // Matches the AddRef in Run(). Release(); #endif // BUILDFLAG(IS_CHROMEOS_ASH) } void ManagementSetEnabledFunction::OnBlockedByParentDialogDone() { #if BUILDFLAG(IS_CHROMEOS_ASH) Respond(Error(keys::kUserCantModifyError, extension_id_)); // Matches the AddRef in Run(). Release(); #endif // BUILDFLAG(IS_CHROMEOS_ASH) } ManagementUninstallFunctionBase::ManagementUninstallFunctionBase() = default; ManagementUninstallFunctionBase::~ManagementUninstallFunctionBase() = default; ExtensionFunction::ResponseAction ManagementUninstallFunctionBase::Uninstall( const std::string& target_extension_id, bool show_confirm_dialog) { if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) return RespondNow(Error(keys::kNotAllowedInKioskError)); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); target_extension_id_ = target_extension_id; const Extension* target_extension = extensions::ExtensionRegistry::Get(browser_context()) ->GetExtensionById(target_extension_id_, ExtensionRegistry::EVERYTHING); if (!target_extension || !target_extension->ShouldExposeViaManagementAPI()) { return RespondNow(Error(keys::kNoExtensionError, target_extension_id_)); } ManagementPolicy* policy = ExtensionSystem::Get(browser_context())->management_policy(); if (!policy->UserMayModifySettings(target_extension, nullptr) || policy->MustRemainInstalled(target_extension, nullptr)) { return RespondNow(Error(keys::kUserCantModifyError, target_extension_id_)); } // Note: null extension() means it's WebUI. bool self_uninstall = extension() && extension_id() == target_extension_id_; // We need to show a dialog for any extension uninstalling another extension. show_confirm_dialog |= !self_uninstall; if (show_confirm_dialog && !user_gesture()) return RespondNow(Error(keys::kGestureNeededForUninstallError)); if (show_confirm_dialog) { // We show the programmatic uninstall ui for extensions uninstalling // other extensions. bool show_programmatic_uninstall_ui = !self_uninstall && extension() && extension()->id() != extensions::kWebStoreAppId; AddRef(); // Balanced in OnExtensionUninstallDialogClosed. // TODO(devlin): A method called "UninstallFunctionDelegate" does not in // any way imply that this actually creates a dialog and runs it. uninstall_dialog_ = delegate->UninstallFunctionDelegate( this, target_extension, show_programmatic_uninstall_ui); } else { // No confirm dialog. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ManagementUninstallFunctionBase::UninstallExtension, this)); } return RespondLater(); } void ManagementUninstallFunctionBase::Finish(bool did_start_uninstall, const std::string& error) { Respond(did_start_uninstall ? NoArguments() : Error(error)); } void ManagementUninstallFunctionBase::OnExtensionUninstallDialogClosed( bool did_start_uninstall, const base::string16& error) { Finish(did_start_uninstall, ErrorUtils::FormatErrorMessage(keys::kUninstallCanceledError, target_extension_id_)); Release(); // Balanced in Uninstall(). } void ManagementUninstallFunctionBase::UninstallExtension() { // The extension can be uninstalled in another window while the UI was // showing. Do nothing in that case. const Extension* target_extension = extensions::ExtensionRegistry::Get(browser_context()) ->GetExtensionById(target_extension_id_, ExtensionRegistry::EVERYTHING); std::string error; bool success = false; if (target_extension) { const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); base::string16 utf16_error; success = delegate->UninstallExtension( browser_context(), target_extension_id_, extensions::UNINSTALL_REASON_MANAGEMENT_API, &utf16_error); error = base::UTF16ToUTF8(utf16_error); } else { error = ErrorUtils::FormatErrorMessage(keys::kNoExtensionError, target_extension_id_); } Finish(success, error); } ManagementUninstallFunction::ManagementUninstallFunction() { } ManagementUninstallFunction::~ManagementUninstallFunction() { } ExtensionFunction::ResponseAction ManagementUninstallFunction::Run() { std::unique_ptr<management::Uninstall::Params> params( management::Uninstall::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); bool show_confirm_dialog = params->options.get() && params->options->show_confirm_dialog.get() && *params->options->show_confirm_dialog; return Uninstall(params->id, show_confirm_dialog); } ManagementUninstallSelfFunction::ManagementUninstallSelfFunction() { } ManagementUninstallSelfFunction::~ManagementUninstallSelfFunction() { } ExtensionFunction::ResponseAction ManagementUninstallSelfFunction::Run() { std::unique_ptr<management::UninstallSelf::Params> params( management::UninstallSelf::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); EXTENSION_FUNCTION_VALIDATE(extension_.get()); bool show_confirm_dialog = params->options.get() && params->options->show_confirm_dialog.get() && *params->options->show_confirm_dialog; return Uninstall(extension_->id(), show_confirm_dialog); } ManagementCreateAppShortcutFunction::ManagementCreateAppShortcutFunction() { } ManagementCreateAppShortcutFunction::~ManagementCreateAppShortcutFunction() { } // static void ManagementCreateAppShortcutFunction::SetAutoConfirmForTest( bool should_proceed) { auto_confirm_for_test = should_proceed ? PROCEED : ABORT; } void ManagementCreateAppShortcutFunction::OnCloseShortcutPrompt(bool created) { Respond(created ? NoArguments() : Error(keys::kCreateShortcutCanceledError)); Release(); // Balanced in Run(). } ExtensionFunction::ResponseAction ManagementCreateAppShortcutFunction::Run() { if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) return RespondNow(Error(keys::kNotAllowedInKioskError)); if (!user_gesture()) return RespondNow(Error(keys::kGestureNeededForCreateAppShortcutError)); std::unique_ptr<management::CreateAppShortcut::Params> params( management::CreateAppShortcut::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); if (!extension) { return RespondNow(Error( ErrorUtils::FormatErrorMessage(keys::kNoExtensionError, params->id))); } if (!extension->is_app()) { return RespondNow(Error( ErrorUtils::FormatErrorMessage(keys::kNotAnAppError, params->id))); } #if defined(OS_MAC) if (!extension->is_platform_app()) return RespondNow(Error(keys::kCreateOnlyPackagedAppShortcutMac)); #endif if (auto_confirm_for_test != DO_NOT_SKIP) { // Matched with a Release() in OnCloseShortcutPrompt(). AddRef(); OnCloseShortcutPrompt(auto_confirm_for_test == PROCEED); // OnCloseShortcutPrompt() might have called Respond() already. return did_respond() ? AlreadyResponded() : RespondLater(); } std::string error; if (ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate() ->CreateAppShortcutFunctionDelegate(this, extension, &error)) { // Matched with a Release() in OnCloseShortcutPrompt(). AddRef(); // Response is sent async in OnCloseShortcutPrompt(). return RespondLater(); } else { return RespondNow(Error(std::move(error))); } } ExtensionFunction::ResponseAction ManagementSetLaunchTypeFunction::Run() { if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) return RespondNow(Error(keys::kNotAllowedInKioskError)); if (!user_gesture()) return RespondNow(Error(keys::kGestureNeededForSetLaunchTypeError)); std::unique_ptr<management::SetLaunchType::Params> params( management::SetLaunchType::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = ExtensionRegistry::Get(browser_context()) ->GetExtensionById(params->id, ExtensionRegistry::EVERYTHING); const ManagementAPIDelegate* delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); if (!extension) return RespondNow(Error(keys::kNoExtensionError, params->id)); if (!extension->is_app()) return RespondNow(Error(keys::kNotAnAppError, params->id)); std::vector<management::LaunchType> available_launch_types = GetAvailableLaunchTypes(*extension, delegate); management::LaunchType app_launch_type = params->launch_type; if (!base::Contains(available_launch_types, app_launch_type)) { return RespondNow(Error(keys::kLaunchTypeNotAvailableError)); } LaunchType launch_type = LAUNCH_TYPE_DEFAULT; switch (app_launch_type) { case management::LAUNCH_TYPE_OPEN_AS_PINNED_TAB: launch_type = LAUNCH_TYPE_PINNED; break; case management::LAUNCH_TYPE_OPEN_AS_REGULAR_TAB: launch_type = LAUNCH_TYPE_REGULAR; break; case management::LAUNCH_TYPE_OPEN_FULL_SCREEN: launch_type = LAUNCH_TYPE_FULLSCREEN; break; case management::LAUNCH_TYPE_OPEN_AS_WINDOW: launch_type = LAUNCH_TYPE_WINDOW; break; case management::LAUNCH_TYPE_NONE: NOTREACHED(); } delegate->SetLaunchType(browser_context(), params->id, launch_type); return RespondNow(NoArguments()); } ManagementGenerateAppForLinkFunction::ManagementGenerateAppForLinkFunction() {} ManagementGenerateAppForLinkFunction::~ManagementGenerateAppForLinkFunction() {} void ManagementGenerateAppForLinkFunction::FinishCreateWebApp( const std::string& web_app_id, bool install_success) { ResponseValue response; if (install_success) { response = ArgumentList(management::GenerateAppForLink::Results::Create( app_for_link_delegate_->CreateExtensionInfoFromWebApp( web_app_id, browser_context()))); } else { response = Error(keys::kGenerateAppForLinkInstallError); } Respond(std::move(response)); Release(); // Balanced in Run(). } ExtensionFunction::ResponseAction ManagementGenerateAppForLinkFunction::Run() { if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) return RespondNow(Error(keys::kNotAllowedInKioskError)); if (!user_gesture()) return RespondNow(Error(keys::kGestureNeededForGenerateAppForLinkError)); std::unique_ptr<management::GenerateAppForLink::Params> params( management::GenerateAppForLink::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); GURL launch_url(params->url); if (!launch_url.is_valid() || !launch_url.SchemeIsHTTPOrHTTPS()) { return RespondNow(Error( ErrorUtils::FormatErrorMessage(keys::kInvalidURLError, params->url))); } if (params->title.empty()) return RespondNow(Error(keys::kEmptyTitleError)); app_for_link_delegate_ = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate() ->GenerateAppForLinkFunctionDelegate(this, browser_context(), params->title, launch_url); // Matched with a Release() in FinishCreateWebApp(). AddRef(); // Response is sent async in FinishCreateWebApp(). return RespondLater(); } ManagementCanInstallReplacementAndroidAppFunction:: ManagementCanInstallReplacementAndroidAppFunction() {} ManagementCanInstallReplacementAndroidAppFunction:: ~ManagementCanInstallReplacementAndroidAppFunction() {} ExtensionFunction::ResponseAction ManagementCanInstallReplacementAndroidAppFunction::Run() { if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) return RespondNow(Error(keys::kNotAllowedInKioskError)); if (!extension()->from_webstore()) { return RespondNow( Error(keys::kInstallReplacementAndroidAppNotFromWebstoreError)); } auto* api_delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); DCHECK(api_delegate); if (!api_delegate->CanContextInstallAndroidApps(browser_context())) { return RespondNow(ArgumentList( management::CanInstallReplacementAndroidApp::Results::Create(false))); } DCHECK(ReplacementAppsInfo::HasReplacementAndroidApp(extension())); const std::string& package_name = ReplacementAppsInfo::GetReplacementAndroidApp(extension()); api_delegate->CheckAndroidAppInstallStatus( package_name, base::BindOnce(&ManagementCanInstallReplacementAndroidAppFunction:: OnFinishedAndroidAppCheck, this)); // Response is sent async in FinishCheckAndroidApp(). return RespondLater(); } void ManagementCanInstallReplacementAndroidAppFunction:: OnFinishedAndroidAppCheck(bool installable) { Respond( ArgumentList(management::CanInstallReplacementAndroidApp::Results::Create( installable))); } ManagementInstallReplacementAndroidAppFunction:: ManagementInstallReplacementAndroidAppFunction() {} ManagementInstallReplacementAndroidAppFunction:: ~ManagementInstallReplacementAndroidAppFunction() {} ExtensionFunction::ResponseAction ManagementInstallReplacementAndroidAppFunction::Run() { if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) return RespondNow(Error(keys::kNotAllowedInKioskError)); if (!extension()->from_webstore()) { return RespondNow( Error(keys::kInstallReplacementAndroidAppNotFromWebstoreError)); } if (!user_gesture()) { return RespondNow( Error(keys::kGestureNeededForInstallReplacementAndroidAppError)); } auto* api_delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); DCHECK(api_delegate); if (!api_delegate->CanContextInstallAndroidApps(browser_context())) { return RespondNow( Error(keys::kInstallReplacementAndroidAppInvalidContextError)); } DCHECK(ReplacementAppsInfo::HasReplacementAndroidApp(extension())); api_delegate->InstallReplacementAndroidApp( ReplacementAppsInfo::GetReplacementAndroidApp(extension()), base::BindOnce(&ManagementInstallReplacementAndroidAppFunction:: OnAppInstallInitiated, this)); // Response is sent async in OnAppInstallInitiated(). return RespondLater(); } void ManagementInstallReplacementAndroidAppFunction::OnAppInstallInitiated( bool initiated) { if (!initiated) return Respond(Error(keys::kInstallReplacementAndroidAppCannotInstallApp)); return Respond(NoArguments()); } ManagementInstallReplacementWebAppFunction:: ManagementInstallReplacementWebAppFunction() {} ManagementInstallReplacementWebAppFunction:: ~ManagementInstallReplacementWebAppFunction() {} ExtensionFunction::ResponseAction ManagementInstallReplacementWebAppFunction::Run() { if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) return RespondNow(Error(keys::kNotAllowedInKioskError)); if (!extension()->from_webstore()) { return RespondNow( Error(keys::kInstallReplacementWebAppNotFromWebstoreError)); } if (!user_gesture()) { return RespondNow( Error(keys::kGestureNeededForInstallReplacementWebAppError)); } DCHECK(ReplacementAppsInfo::HasReplacementWebApp(extension())); const GURL& web_app_url = ReplacementAppsInfo::GetReplacementWebApp(extension()); DCHECK(web_app_url.is_valid()); DCHECK(web_app_url.SchemeIs(url::kHttpsScheme)); auto* api_delegate = ManagementAPI::GetFactoryInstance() ->Get(browser_context()) ->GetDelegate(); if (!api_delegate->CanContextInstallWebApps(browser_context())) { return RespondNow( Error(keys::kInstallReplacementWebAppInvalidContextError)); } // Adds a ref-count. api_delegate->InstallOrLaunchReplacementWebApp( browser_context(), web_app_url, base::BindOnce( &ManagementInstallReplacementWebAppFunction::FinishResponse, this)); // Response is sent async in FinishResponse(). return RespondLater(); } void ManagementInstallReplacementWebAppFunction::FinishResponse( ManagementAPIDelegate::InstallOrLaunchWebAppResult result) { ResponseValue response; switch (result) { case ManagementAPIDelegate::InstallOrLaunchWebAppResult::kSuccess: response = NoArguments(); break; case ManagementAPIDelegate::InstallOrLaunchWebAppResult::kInvalidWebApp: response = Error(keys::kInstallReplacementWebAppInvalidWebAppError); break; case ManagementAPIDelegate::InstallOrLaunchWebAppResult::kUnknownError: response = Error(keys::kGenerateAppForLinkInstallError); } Respond(std::move(response)); } ManagementEventRouter::ManagementEventRouter(content::BrowserContext* context) : browser_context_(context) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); } ManagementEventRouter::~ManagementEventRouter() {} void ManagementEventRouter::OnExtensionLoaded( content::BrowserContext* browser_context, const Extension* extension) { BroadcastEvent(extension, events::MANAGEMENT_ON_ENABLED, management::OnEnabled::kEventName); } void ManagementEventRouter::OnExtensionUnloaded( content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionReason reason) { BroadcastEvent(extension, events::MANAGEMENT_ON_DISABLED, management::OnDisabled::kEventName); } void ManagementEventRouter::OnExtensionInstalled( content::BrowserContext* browser_context, const Extension* extension, bool is_update) { BroadcastEvent(extension, events::MANAGEMENT_ON_INSTALLED, management::OnInstalled::kEventName); } void ManagementEventRouter::OnExtensionUninstalled( content::BrowserContext* browser_context, const Extension* extension, extensions::UninstallReason reason) { BroadcastEvent(extension, events::MANAGEMENT_ON_UNINSTALLED, management::OnUninstalled::kEventName); } void ManagementEventRouter::BroadcastEvent( const Extension* extension, events::HistogramValue histogram_value, const char* event_name) { if (!extension->ShouldExposeViaManagementAPI()) return; std::unique_ptr<base::ListValue> args(new base::ListValue()); if (event_name == management::OnUninstalled::kEventName) { args->AppendString(extension->id()); } else { args->Append( CreateExtensionInfo(nullptr, *extension, browser_context_).ToValue()); } EventRouter::Get(browser_context_) ->BroadcastEvent(std::unique_ptr<Event>( new Event(histogram_value, event_name, std::move(args)))); } ManagementAPI::ManagementAPI(content::BrowserContext* context) : browser_context_(context), delegate_(ExtensionsAPIClient::Get()->CreateManagementAPIDelegate()), supervised_user_extensions_delegate_( ExtensionsAPIClient::Get() ->CreateSupervisedUserExtensionsDelegate()) { EventRouter* event_router = EventRouter::Get(browser_context_); event_router->RegisterObserver(this, management::OnInstalled::kEventName); event_router->RegisterObserver(this, management::OnUninstalled::kEventName); event_router->RegisterObserver(this, management::OnEnabled::kEventName); event_router->RegisterObserver(this, management::OnDisabled::kEventName); } ManagementAPI::~ManagementAPI() { } void ManagementAPI::Shutdown() { EventRouter::Get(browser_context_)->UnregisterObserver(this); } static base::LazyInstance< BrowserContextKeyedAPIFactory<ManagementAPI>>::DestructorAtExit g_factory = LAZY_INSTANCE_INITIALIZER; // static BrowserContextKeyedAPIFactory<ManagementAPI>* ManagementAPI::GetFactoryInstance() { return g_factory.Pointer(); } void ManagementAPI::OnListenerAdded(const EventListenerInfo& details) { management_event_router_.reset(new ManagementEventRouter(browser_context_)); EventRouter::Get(browser_context_)->UnregisterObserver(this); } } // namespace extensions
37.383944
80
0.724103
[ "vector" ]
6192c9599435ec07479d0ede009908f4732b5310
49,670
cpp
C++
drivers/gles3/rasterizer_canvas_base_gles3.cpp
MichaelBelousov/godot
ad64d5de1170109a53a5d0cfd8101824c2c4d77c
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
drivers/gles3/rasterizer_canvas_base_gles3.cpp
MichaelBelousov/godot
ad64d5de1170109a53a5d0cfd8101824c2c4d77c
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
drivers/gles3/rasterizer_canvas_base_gles3.cpp
MichaelBelousov/godot
ad64d5de1170109a53a5d0cfd8101824c2c4d77c
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* rasterizer_canvas_base_gles3.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "rasterizer_canvas_base_gles3.h" #include "core/os/os.h" #include "core/project_settings.h" #include "drivers/gles_common/rasterizer_asserts.h" #include "rasterizer_scene_gles3.h" #include "servers/visual/visual_server_raster.h" #ifndef GLES_OVER_GL #define glClearDepth glClearDepthf #endif static _FORCE_INLINE_ void store_transform2d(const Transform2D &p_mtx, float *p_array) { p_array[0] = p_mtx.elements[0][0]; p_array[1] = p_mtx.elements[0][1]; p_array[2] = 0; p_array[3] = 0; p_array[4] = p_mtx.elements[1][0]; p_array[5] = p_mtx.elements[1][1]; p_array[6] = 0; p_array[7] = 0; p_array[8] = 0; p_array[9] = 0; p_array[10] = 1; p_array[11] = 0; p_array[12] = p_mtx.elements[2][0]; p_array[13] = p_mtx.elements[2][1]; p_array[14] = 0; p_array[15] = 1; } static _FORCE_INLINE_ void store_transform(const Transform &p_mtx, float *p_array) { p_array[0] = p_mtx.basis.elements[0][0]; p_array[1] = p_mtx.basis.elements[1][0]; p_array[2] = p_mtx.basis.elements[2][0]; p_array[3] = 0; p_array[4] = p_mtx.basis.elements[0][1]; p_array[5] = p_mtx.basis.elements[1][1]; p_array[6] = p_mtx.basis.elements[2][1]; p_array[7] = 0; p_array[8] = p_mtx.basis.elements[0][2]; p_array[9] = p_mtx.basis.elements[1][2]; p_array[10] = p_mtx.basis.elements[2][2]; p_array[11] = 0; p_array[12] = p_mtx.origin.x; p_array[13] = p_mtx.origin.y; p_array[14] = p_mtx.origin.z; p_array[15] = 1; } static _FORCE_INLINE_ void store_camera(const CameraMatrix &p_mtx, float *p_array) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { p_array[i * 4 + j] = p_mtx.matrix[i][j]; } } } RID RasterizerCanvasBaseGLES3::light_internal_create() { LightInternal *li = memnew(LightInternal); glGenBuffers(1, &li->ubo); glBindBuffer(GL_UNIFORM_BUFFER, li->ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(LightInternal::UBOData), &state.canvas_item_ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); return light_internal_owner.make_rid(li); } void RasterizerCanvasBaseGLES3::light_internal_update(RID p_rid, Light *p_light) { LightInternal *li = light_internal_owner.getornull(p_rid); ERR_FAIL_COND(!li); store_transform2d(p_light->light_shader_xform, li->ubo_data.light_matrix); store_transform2d(p_light->xform_cache.affine_inverse(), li->ubo_data.local_matrix); store_camera(p_light->shadow_matrix_cache, li->ubo_data.shadow_matrix); for (int i = 0; i < 4; i++) { li->ubo_data.color[i] = p_light->color[i] * p_light->energy; li->ubo_data.shadow_color[i] = p_light->shadow_color[i]; } li->ubo_data.light_pos[0] = p_light->light_shader_pos.x; li->ubo_data.light_pos[1] = p_light->light_shader_pos.y; li->ubo_data.shadowpixel_size = (1.0 / p_light->shadow_buffer_size) * (1.0 + p_light->shadow_smooth); li->ubo_data.light_outside_alpha = p_light->mode == VS::CANVAS_LIGHT_MODE_MASK ? 1.0 : 0.0; li->ubo_data.light_height = p_light->height; if (p_light->radius_cache == 0) li->ubo_data.shadow_gradient = 0; else li->ubo_data.shadow_gradient = p_light->shadow_gradient_length / (p_light->radius_cache * 1.1); li->ubo_data.shadow_distance_mult = (p_light->radius_cache * 1.1); glBindBuffer(GL_UNIFORM_BUFFER, li->ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(LightInternal::UBOData), &li->ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } void RasterizerCanvasBaseGLES3::light_internal_free(RID p_rid) { LightInternal *li = light_internal_owner.getornull(p_rid); ERR_FAIL_COND(!li); glDeleteBuffers(1, &li->ubo); light_internal_owner.free(p_rid); memdelete(li); } void RasterizerCanvasBaseGLES3::canvas_begin() { if (storage->frame.current_rt && storage->frame.clear_request) { // a clear request may be pending, so do it bool transparent = storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]; glClearColor(storage->frame.clear_request_color.r, storage->frame.clear_request_color.g, storage->frame.clear_request_color.b, transparent ? storage->frame.clear_request_color.a : 1.0); glClear(GL_COLOR_BUFFER_BIT); storage->frame.clear_request = false; glColorMask(1, 1, 1, transparent ? 1 : 0); } reset_canvas(); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_TEXTURE_RECT, true); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF3, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF7, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF9, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_NINEPATCH, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_ATTRIB_LIGHT_ANGLE, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_ATTRIB_MODULATE, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_ATTRIB_LARGE_VERTEX, false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SKELETON, false); state.canvas_shader.set_custom_shader(0); state.canvas_shader.bind(); state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE, Color(1, 1, 1, 1)); state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, Transform2D()); state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX, Transform2D()); if (storage->frame.current_rt) { state.canvas_shader.set_uniform(CanvasShaderGLES3::SCREEN_PIXEL_SIZE, Vector2(1.0 / storage->frame.current_rt->width, 1.0 / storage->frame.current_rt->height)); } else { state.canvas_shader.set_uniform(CanvasShaderGLES3::SCREEN_PIXEL_SIZE, Vector2(1.0, 1.0)); } //state.canvas_shader.set_uniform(CanvasShaderGLES3::PROJECTION_MATRIX,state.vp); //state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,Transform()); //state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,Transform()); glBindBufferBase(GL_UNIFORM_BUFFER, 0, state.canvas_item_ubo); glBindVertexArray(data.canvas_quad_array); state.using_texture_rect = true; state.using_ninepatch = false; state.using_light_angle = false; state.using_modulate = false; state.using_large_vertex = false; state.using_skeleton = false; } void RasterizerCanvasBaseGLES3::canvas_end() { glBindVertexArray(0); glBindBufferBase(GL_UNIFORM_BUFFER, 0, 0); glColorMask(1, 1, 1, 1); glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1); state.using_texture_rect = false; state.using_ninepatch = false; state.using_light_angle = false; } RasterizerStorageGLES3::Texture *RasterizerCanvasBaseGLES3::_bind_canvas_texture(const RID &p_texture, const RID &p_normal_map, bool p_force) { RasterizerStorageGLES3::Texture *tex_return = NULL; if (p_texture == state.current_tex && !p_force) { tex_return = state.current_tex_ptr; } else if (p_texture.is_valid()) { RasterizerStorageGLES3::Texture *texture = storage->texture_owner.getornull(p_texture); if (!texture) { state.current_tex = RID(); state.current_tex_ptr = NULL; glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); } else { if (texture->redraw_if_visible) { //check before proxy, because this is usually used with proxies VisualServerRaster::redraw_request(); } texture = texture->get_ptr(); if (texture->render_target) texture->render_target->used_in_frame = true; glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture->tex_id); state.current_tex = p_texture; state.current_tex_ptr = texture; tex_return = texture; } } else { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); state.current_tex = RID(); state.current_tex_ptr = NULL; } if (p_normal_map == state.current_normal && !p_force) { //do none state.canvas_shader.set_uniform(CanvasShaderGLES3::USE_DEFAULT_NORMAL, state.current_normal.is_valid()); } else if (p_normal_map.is_valid()) { RasterizerStorageGLES3::Texture *normal_map = storage->texture_owner.getornull(p_normal_map); if (!normal_map) { state.current_normal = RID(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex); state.canvas_shader.set_uniform(CanvasShaderGLES3::USE_DEFAULT_NORMAL, false); } else { if (normal_map->redraw_if_visible) { //check before proxy, because this is usually used with proxies VisualServerRaster::redraw_request(); } normal_map = normal_map->get_ptr(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normal_map->tex_id); state.current_normal = p_normal_map; state.canvas_shader.set_uniform(CanvasShaderGLES3::USE_DEFAULT_NORMAL, true); } } else { state.current_normal = RID(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex); state.canvas_shader.set_uniform(CanvasShaderGLES3::USE_DEFAULT_NORMAL, false); } return tex_return; } void RasterizerCanvasBaseGLES3::_set_texture_rect_mode(bool p_enable, bool p_ninepatch, bool p_light_angle, bool p_modulate, bool p_large_vertex) { // this state check could be done individually if (state.using_texture_rect == p_enable && state.using_ninepatch == p_ninepatch && state.using_light_angle == p_light_angle && state.using_modulate == p_modulate && state.using_large_vertex == p_large_vertex) return; if (p_enable) { glBindVertexArray(data.canvas_quad_array); } else { glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_NINEPATCH, p_ninepatch && p_enable); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_TEXTURE_RECT, p_enable); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_ATTRIB_LIGHT_ANGLE, p_light_angle); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_ATTRIB_MODULATE, p_modulate); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_ATTRIB_LARGE_VERTEX, p_large_vertex); state.canvas_shader.bind(); state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE, state.canvas_item_modulate); state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform); state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX, state.extra_matrix); if (state.using_skeleton) { state.canvas_shader.set_uniform(CanvasShaderGLES3::SKELETON_TRANSFORM, state.skeleton_transform); state.canvas_shader.set_uniform(CanvasShaderGLES3::SKELETON_TRANSFORM_INVERSE, state.skeleton_transform_inverse); } if (storage->frame.current_rt) { state.canvas_shader.set_uniform(CanvasShaderGLES3::SCREEN_PIXEL_SIZE, Vector2(1.0 / storage->frame.current_rt->width, 1.0 / storage->frame.current_rt->height)); } else { state.canvas_shader.set_uniform(CanvasShaderGLES3::SCREEN_PIXEL_SIZE, Vector2(1.0, 1.0)); } state.using_texture_rect = p_enable; state.using_ninepatch = p_ninepatch; state.using_light_angle = p_light_angle; state.using_modulate = p_modulate; state.using_large_vertex = p_large_vertex; } void RasterizerCanvasBaseGLES3::_draw_polygon(const int *p_indices, int p_index_count, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor, const int *p_bones, const float *p_weights) { glBindVertexArray(data.polygon_buffer_pointer_array); glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); uint32_t buffer_ofs = 0; uint32_t buffer_ofs_after = buffer_ofs + (sizeof(Vector2) * p_vertex_count); #ifdef DEBUG_ENABLED ERR_FAIL_COND(buffer_ofs_after > data.polygon_buffer_size); #endif storage->buffer_orphan_and_upload(data.polygon_buffer_size, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_vertices, GL_ARRAY_BUFFER, _buffer_upload_usage_flag); glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; //color if (p_singlecolor) { glDisableVertexAttribArray(VS::ARRAY_COLOR); Color m = *p_colors; glVertexAttrib4f(VS::ARRAY_COLOR, m.r, m.g, m.b, m.a); } else if (!p_colors) { glDisableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1); } else { RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Color) * p_vertex_count, p_colors, buffer_ofs_after)); glEnableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; } if (p_uvs) { RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_uvs, buffer_ofs_after)); glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV); } if (p_bones && p_weights) { RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(int) * 4 * p_vertex_count, p_bones, buffer_ofs_after)); glEnableVertexAttribArray(VS::ARRAY_BONES); //glVertexAttribPointer(VS::ARRAY_BONES, 4, GL_UNSIGNED_INT, false, sizeof(int) * 4, ((uint8_t *)0) + buffer_ofs); glVertexAttribIPointer(VS::ARRAY_BONES, 4, GL_UNSIGNED_INT, sizeof(int) * 4, CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(float) * 4 * p_vertex_count, p_weights, buffer_ofs_after)); glEnableVertexAttribArray(VS::ARRAY_WEIGHTS); glVertexAttribPointer(VS::ARRAY_WEIGHTS, 4, GL_FLOAT, false, sizeof(float) * 4, CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; } else if (state.using_skeleton) { glVertexAttribI4ui(VS::ARRAY_BONES, 0, 0, 0, 0); glVertexAttrib4f(VS::ARRAY_WEIGHTS, 0, 0, 0, 0); } #ifdef DEBUG_ENABLED ERR_FAIL_COND((sizeof(int) * p_index_count) > data.polygon_index_buffer_size); #endif //bind the indices buffer. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); storage->buffer_orphan_and_upload(data.polygon_index_buffer_size, 0, sizeof(int) * p_index_count, p_indices, GL_ELEMENT_ARRAY_BUFFER, _buffer_upload_usage_flag); //draw the triangles. glDrawElements(GL_TRIANGLES, p_index_count, GL_UNSIGNED_INT, 0); storage->info.render._2d_draw_call_count++; if (p_bones && p_weights) { //not used so often, so disable when used glDisableVertexAttribArray(VS::ARRAY_BONES); glDisableVertexAttribArray(VS::ARRAY_WEIGHTS); } glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void RasterizerCanvasBaseGLES3::_draw_generic(GLuint p_primitive, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor) { glBindVertexArray(data.polygon_buffer_pointer_array); glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); //vertex uint32_t buffer_ofs = 0; uint32_t buffer_ofs_after = buffer_ofs + (sizeof(Vector2) * p_vertex_count); #ifdef DEBUG_ENABLED ERR_FAIL_COND(buffer_ofs_after > data.polygon_buffer_size); #endif storage->buffer_orphan_and_upload(data.polygon_buffer_size, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_vertices, GL_ARRAY_BUFFER, _buffer_upload_usage_flag); glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; //color if (p_singlecolor) { glDisableVertexAttribArray(VS::ARRAY_COLOR); Color m = *p_colors; glVertexAttrib4f(VS::ARRAY_COLOR, m.r, m.g, m.b, m.a); } else if (!p_colors) { glDisableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1); } else { RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Color) * p_vertex_count, p_colors, buffer_ofs_after)); glEnableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; } if (p_uvs) { RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_uvs, buffer_ofs_after)); glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV); } glDrawArrays(p_primitive, 0, p_vertex_count); storage->info.render._2d_draw_call_count++; glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void RasterizerCanvasBaseGLES3::_draw_generic_indices(GLuint p_primitive, const int *p_indices, int p_index_count, int p_vertex_count, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, bool p_singlecolor) { glBindVertexArray(data.polygon_buffer_pointer_array); glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); //vertex uint32_t buffer_ofs = 0; uint32_t buffer_ofs_after = buffer_ofs + (sizeof(Vector2) * p_vertex_count); #ifdef DEBUG_ENABLED ERR_FAIL_COND(buffer_ofs_after > data.polygon_buffer_size); #endif storage->buffer_orphan_and_upload(data.polygon_buffer_size, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_vertices, GL_ARRAY_BUFFER, _buffer_upload_usage_flag); glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; //color if (p_singlecolor) { glDisableVertexAttribArray(VS::ARRAY_COLOR); Color m = *p_colors; glVertexAttrib4f(VS::ARRAY_COLOR, m.r, m.g, m.b, m.a); } else if (!p_colors) { glDisableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1); } else { RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Color) * p_vertex_count, p_colors, buffer_ofs_after)); glEnableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; } if (p_uvs) { RAST_FAIL_COND(!storage->safe_buffer_sub_data(data.polygon_buffer_size, GL_ARRAY_BUFFER, buffer_ofs, sizeof(Vector2) * p_vertex_count, p_uvs, buffer_ofs_after)); glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), CAST_INT_TO_UCHAR_PTR(buffer_ofs)); buffer_ofs = buffer_ofs_after; } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV); } #ifdef RASTERIZER_EXTRA_CHECKS // very slow, do not enable in normal use for (int n = 0; n < p_index_count; n++) { RAST_DEV_DEBUG_ASSERT(p_indices[n] < p_vertex_count); } #endif #ifdef DEBUG_ENABLED ERR_FAIL_COND((sizeof(int) * p_index_count) > data.polygon_index_buffer_size); #endif //bind the indices buffer. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); storage->buffer_orphan_and_upload(data.polygon_index_buffer_size, 0, sizeof(int) * p_index_count, p_indices, GL_ELEMENT_ARRAY_BUFFER, _buffer_upload_usage_flag); //draw the triangles. glDrawElements(p_primitive, p_index_count, GL_UNSIGNED_INT, 0); storage->info.render._2d_draw_call_count++; glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void RasterizerCanvasBaseGLES3::_draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs, const float *p_light_angles) { static const GLenum prim[5] = { GL_POINTS, GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_FAN }; //#define GLES_USE_PRIMITIVE_BUFFER int version = 0; int color_ofs = 0; int uv_ofs = 0; int light_angle_ofs = 0; int stride = 2; if (p_colors) { //color version |= 1; color_ofs = stride; stride += 4; } if (p_uvs) { //uv version |= 2; uv_ofs = stride; stride += 2; } if (p_light_angles) { //light_angles version |= 4; light_angle_ofs = stride; stride += 1; } RAST_DEV_DEBUG_ASSERT(p_points <= 4); float b[(2 + 2 + 4 + 1) * 4]; for (int i = 0; i < p_points; i++) { b[stride * i + 0] = p_vertices[i].x; b[stride * i + 1] = p_vertices[i].y; } if (p_colors) { for (int i = 0; i < p_points; i++) { b[stride * i + color_ofs + 0] = p_colors[i].r; b[stride * i + color_ofs + 1] = p_colors[i].g; b[stride * i + color_ofs + 2] = p_colors[i].b; b[stride * i + color_ofs + 3] = p_colors[i].a; } } if (p_uvs) { for (int i = 0; i < p_points; i++) { b[stride * i + uv_ofs + 0] = p_uvs[i].x; b[stride * i + uv_ofs + 1] = p_uvs[i].y; } } if (p_light_angles) { for (int i = 0; i < p_points; i++) { b[stride * i + light_angle_ofs] = p_light_angles[i]; } } glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); //TODO the below call may need to be replaced with: p_points * stride * 4 * sizeof(float), &b[0]); storage->buffer_orphan_and_upload(data.polygon_buffer_size, 0, p_points * stride * 4, &b[0], GL_ARRAY_BUFFER, _buffer_upload_usage_flag); glBindVertexArray(data.polygon_buffer_quad_arrays[version]); glDrawArrays(prim[p_points], 0, p_points); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); storage->info.render._2d_draw_call_count++; } void RasterizerCanvasBaseGLES3::render_rect_nvidia_workaround(const Item::CommandRect *p_rect, const RasterizerStorageGLES3::Texture *p_texture) { if (p_texture) { bool send_light_angles = false; // only need to use light angles when normal mapping // otherwise we can use the default shader if (state.current_normal != RID()) { send_light_angles = true; } // we don't want to use texture rect, and we want to send light angles if we are using normal mapping _set_texture_rect_mode(false, false, send_light_angles); bool untile = false; if (p_rect->flags & CANVAS_RECT_TILE && !(p_texture->flags & VS::TEXTURE_FLAG_REPEAT)) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); untile = true; } Size2 texpixel_size(1.0 / p_texture->width, 1.0 / p_texture->height); state.canvas_shader.set_uniform(CanvasShaderGLES3::CLIP_RECT_UV, p_rect->flags & CANVAS_RECT_CLIP_UV); Vector2 points[4] = { p_rect->rect.position, p_rect->rect.position + Vector2(p_rect->rect.size.x, 0.0), p_rect->rect.position + p_rect->rect.size, p_rect->rect.position + Vector2(0.0, p_rect->rect.size.y), }; if (p_rect->rect.size.x < 0) { SWAP(points[0], points[1]); SWAP(points[2], points[3]); } if (p_rect->rect.size.y < 0) { SWAP(points[0], points[3]); SWAP(points[1], points[2]); } Rect2 src_rect = (p_rect->flags & CANVAS_RECT_REGION) ? Rect2(p_rect->source.position * texpixel_size, p_rect->source.size * texpixel_size) : Rect2(0, 0, 1, 1); Vector2 uvs[4] = { src_rect.position, src_rect.position + Vector2(src_rect.size.x, 0.0), src_rect.position + src_rect.size, src_rect.position + Vector2(0.0, src_rect.size.y), }; // for encoding in light angle bool flip_h = false; bool flip_v = false; if (p_rect->flags & CANVAS_RECT_TRANSPOSE) { SWAP(uvs[1], uvs[3]); } if (p_rect->flags & CANVAS_RECT_FLIP_H) { SWAP(uvs[0], uvs[1]); SWAP(uvs[2], uvs[3]); flip_h = true; flip_v = !flip_v; } if (p_rect->flags & CANVAS_RECT_FLIP_V) { SWAP(uvs[0], uvs[3]); SWAP(uvs[1], uvs[2]); flip_v = !flip_v; } if (send_light_angles) { // for single rects, there is no need to fully utilize the light angle, // we only need it to encode flips (horz and vert). But the shader can be reused with // batching in which case the angle encodes the transform as well as // the flips. // Note transpose is NYI. I don't think it worked either with the non-nvidia method. // if horizontal flip, angle is 180 float angle = 0.0f; if (flip_h) angle = Math_PI; // add 1 (to take care of zero floating point error with sign) angle += 1.0f; // flip if necessary if (flip_v) angle *= -1.0f; // light angle must be sent for each vert, instead as a single uniform in the uniform draw method // this has the benefit of enabling batching with light angles. float light_angles[4] = { angle, angle, angle, angle }; _draw_gui_primitive(4, points, NULL, uvs, light_angles); } else { _draw_gui_primitive(4, points, NULL, uvs); } if (untile) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } } else { _set_texture_rect_mode(false); state.canvas_shader.set_uniform(CanvasShaderGLES3::CLIP_RECT_UV, false); Vector2 points[4] = { p_rect->rect.position, p_rect->rect.position + Vector2(p_rect->rect.size.x, 0.0), p_rect->rect.position + p_rect->rect.size, p_rect->rect.position + Vector2(0.0, p_rect->rect.size.y), }; _draw_gui_primitive(4, points, NULL, nullptr); } } void RasterizerCanvasBaseGLES3::_copy_texscreen(const Rect2 &p_rect) { ERR_FAIL_COND_MSG(storage->frame.current_rt->effects.mip_maps[0].sizes.size() == 0, "Can't use screen texture copying in a render target configured without copy buffers."); glDisable(GL_BLEND); state.canvas_texscreen_used = true; //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); Vector2 wh(storage->frame.current_rt->width, storage->frame.current_rt->height); Color blur_section(p_rect.position.x / wh.x, p_rect.position.y / wh.y, p_rect.size.x / wh.x, p_rect.size.y / wh.y); if (p_rect != Rect2()) { scene_render->state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_BLUR_SECTION, true); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_COPY_SECTION, true); } glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); storage->shaders.copy.bind(); storage->shaders.copy.set_uniform(CopyShaderGLES3::COPY_SECTION, blur_section); scene_render->_copy_screen(); for (int i = 0; i < storage->frame.current_rt->effects.mip_maps[1].sizes.size(); i++) { int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width; int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height; glViewport(0, 0, vp_w, vp_h); //horizontal pass scene_render->state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL, true); scene_render->state.effect_blur_shader.bind(); scene_render->state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); scene_render->state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i)); scene_render->state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::BLUR_SECTION, blur_section); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo); scene_render->_copy_screen(); scene_render->state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL, false); //vertical pass scene_render->state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL, true); scene_render->state.effect_blur_shader.bind(); scene_render->state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h)); scene_render->state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i)); scene_render->state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::BLUR_SECTION, blur_section); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[i + 1].fbo); //next level, since mipmaps[0] starts one level bigger scene_render->_copy_screen(); scene_render->state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL, false); } scene_render->state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::USE_BLUR_SECTION, false); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_COPY_SECTION, false); glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //back to front glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height); // back to canvas, force rebind state.using_texture_rect = true; _set_texture_rect_mode(false); _bind_canvas_texture(state.current_tex, state.current_normal, true); glEnable(GL_BLEND); } void RasterizerCanvasBaseGLES3::canvas_debug_viewport_shadows(Light *p_lights_with_shadow) { Light *light = p_lights_with_shadow; canvas_begin(); //reset glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1); int h = 10; int w = storage->frame.current_rt->width; int ofs = h; glDisable(GL_BLEND); while (light) { if (light->shadow_buffer.is_valid()) { RasterizerStorageGLES3::CanvasLightShadow *sb = storage->canvas_light_shadow_owner.get(light->shadow_buffer); if (sb) { glBindTexture(GL_TEXTURE_2D, sb->distance); draw_generic_textured_rect(Rect2(h, ofs, w - h * 2, h), Rect2(0, 0, 1, 1)); ofs += h * 2; } } light = light->shadows_next_ptr; } canvas_end(); } void RasterizerCanvasBaseGLES3::canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache) { RasterizerStorageGLES3::CanvasLightShadow *cls = storage->canvas_light_shadow_owner.get(p_buffer); ERR_FAIL_COND(!cls); glDisable(GL_BLEND); glDisable(GL_SCISSOR_TEST); glDisable(GL_DITHER); glDisable(GL_CULL_FACE); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glDepthMask(true); glBindFramebuffer(GL_FRAMEBUFFER, cls->fbo); state.canvas_shadow_shader.bind(); glViewport(0, 0, cls->size, cls->height); glClearDepth(1.0f); glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); VS::CanvasOccluderPolygonCullMode cull = VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; for (int i = 0; i < 4; i++) { //make sure it remains orthogonal, makes easy to read angle later Transform light; light.origin[0] = p_light_xform[2][0]; light.origin[1] = p_light_xform[2][1]; light.basis[0][0] = p_light_xform[0][0]; light.basis[0][1] = p_light_xform[1][0]; light.basis[1][0] = p_light_xform[0][1]; light.basis[1][1] = p_light_xform[1][1]; //light.basis.scale(Vector3(to_light.elements[0].length(),to_light.elements[1].length(),1)); //p_near=1; CameraMatrix projection; { real_t fov = 90; real_t nearp = p_near; real_t farp = p_far; real_t aspect = 1.0; real_t ymax = nearp * Math::tan(Math::deg2rad(fov * 0.5)); real_t ymin = -ymax; real_t xmin = ymin * aspect; real_t xmax = ymax * aspect; projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp); } Vector3 cam_target = Basis(Vector3(0, 0, Math_PI * 2 * (i / 4.0))).xform(Vector3(0, 1, 0)); projection = projection * CameraMatrix(Transform().looking_at(cam_target, Vector3(0, 0, -1)).affine_inverse()); state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::PROJECTION_MATRIX, projection); state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::LIGHT_MATRIX, light); state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::DISTANCE_NORM, 1.0 / p_far); if (i == 0) *p_xform_cache = projection; glViewport(0, (cls->height / 4) * i, cls->size, cls->height / 4); LightOccluderInstance *instance = p_occluders; while (instance) { RasterizerStorageGLES3::CanvasOccluder *cc = storage->canvas_occluder_owner.getornull(instance->polygon_buffer); if (!cc || cc->len == 0 || !(p_light_mask & instance->light_mask)) { instance = instance->next; continue; } state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::WORLD_MATRIX, instance->xform_cache); VS::CanvasOccluderPolygonCullMode transformed_cull_cache = instance->cull_cache; if (transformed_cull_cache != VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED && (p_light_xform.basis_determinant() * instance->xform_cache.basis_determinant()) < 0) { transformed_cull_cache = transformed_cull_cache == VS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE ? VS::CANVAS_OCCLUDER_POLYGON_CULL_COUNTER_CLOCKWISE : VS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE; } if (cull != transformed_cull_cache) { cull = transformed_cull_cache; switch (cull) { case VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED: { glDisable(GL_CULL_FACE); } break; case VS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE: { glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); } break; case VS::CANVAS_OCCLUDER_POLYGON_CULL_COUNTER_CLOCKWISE: { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } break; } } glBindVertexArray(cc->array_id); glDrawElements(GL_TRIANGLES, cc->len * 3, GL_UNSIGNED_SHORT, 0); instance = instance->next; } } glBindVertexArray(0); } void RasterizerCanvasBaseGLES3::reset_canvas() { if (storage->frame.current_rt) { glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); glColorMask(1, 1, 1, 1); //don't touch alpha } glBindVertexArray(0); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glDisable(GL_DITHER); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } //glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); //glLineWidth(1.0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //use for reading from screen if (storage->frame.current_rt && !storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_NO_SAMPLING]) { glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3); glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex); glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1); Transform canvas_transform; if (storage->frame.current_rt) { float csy = 1.0; if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) { csy = -1.0; } canvas_transform.translate(-(storage->frame.current_rt->width / 2.0f), -(storage->frame.current_rt->height / 2.0f), 0.0f); canvas_transform.scale(Vector3(2.0f / storage->frame.current_rt->width, csy * -2.0f / storage->frame.current_rt->height, 1.0f)); } else { Vector2 ssize = OS::get_singleton()->get_window_size(); canvas_transform.translate(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f); canvas_transform.scale(Vector3(2.0f / ssize.width, -2.0f / ssize.height, 1.0f)); } state.vp = canvas_transform; store_transform(canvas_transform, state.canvas_item_ubo_data.projection_matrix); state.canvas_item_ubo_data.time = storage->frame.time[0]; glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_item_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(CanvasItemUBO), &state.canvas_item_ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.canvas_texscreen_used = false; } void RasterizerCanvasBaseGLES3::draw_generic_textured_rect(const Rect2 &p_rect, const Rect2 &p_src) { state.canvas_shader.set_uniform(CanvasShaderGLES3::DST_RECT, Color(p_rect.position.x, p_rect.position.y, p_rect.size.x, p_rect.size.y)); state.canvas_shader.set_uniform(CanvasShaderGLES3::SRC_RECT, Color(p_src.position.x, p_src.position.y, p_src.size.x, p_src.size.y)); state.canvas_shader.set_uniform(CanvasShaderGLES3::CLIP_RECT_UV, false); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } void RasterizerCanvasBaseGLES3::draw_lens_distortion_rect(const Rect2 &p_rect, float p_k1, float p_k2, const Vector2 &p_eye_center, float p_oversample) { Vector2 half_size; if (storage->frame.current_rt) { half_size = Vector2(storage->frame.current_rt->width, storage->frame.current_rt->height); } else { half_size = OS::get_singleton()->get_window_size(); } half_size *= 0.5; Vector2 offset((p_rect.position.x - half_size.x) / half_size.x, (p_rect.position.y - half_size.y) / half_size.y); Vector2 scale(p_rect.size.x / half_size.x, p_rect.size.y / half_size.y); float aspect_ratio = p_rect.size.x / p_rect.size.y; // setup our lens shader state.lens_shader.bind(); state.lens_shader.set_uniform(LensDistortedShaderGLES3::OFFSET, offset); state.lens_shader.set_uniform(LensDistortedShaderGLES3::SCALE, scale); state.lens_shader.set_uniform(LensDistortedShaderGLES3::K1, p_k1); state.lens_shader.set_uniform(LensDistortedShaderGLES3::K2, p_k2); state.lens_shader.set_uniform(LensDistortedShaderGLES3::EYE_CENTER, p_eye_center); state.lens_shader.set_uniform(LensDistortedShaderGLES3::UPSCALE, p_oversample); state.lens_shader.set_uniform(LensDistortedShaderGLES3::ASPECT_RATIO, aspect_ratio); glBindBufferBase(GL_UNIFORM_BUFFER, 0, state.canvas_item_ubo); glBindVertexArray(data.canvas_quad_array); // and draw glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindVertexArray(0); glBindBufferBase(GL_UNIFORM_BUFFER, 0, 0); } void RasterizerCanvasBaseGLES3::draw_window_margins(int *black_margin, RID *black_image) { Vector2 window_size = OS::get_singleton()->get_window_size(); int window_h = window_size.height; int window_w = window_size.width; glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo); glViewport(0, 0, window_size.width, window_size.height); canvas_begin(); if (black_image[MARGIN_LEFT].is_valid()) { _bind_canvas_texture(black_image[MARGIN_LEFT], RID(), true); Size2 sz(storage->texture_get_width(black_image[MARGIN_LEFT]), storage->texture_get_height(black_image[MARGIN_LEFT])); draw_generic_textured_rect(Rect2(0, 0, black_margin[MARGIN_LEFT], window_h), Rect2(0, 0, (float)black_margin[MARGIN_LEFT] / sz.x, (float)(window_h) / sz.y)); } else if (black_margin[MARGIN_LEFT]) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); draw_generic_textured_rect(Rect2(0, 0, black_margin[MARGIN_LEFT], window_h), Rect2(0, 0, 1, 1)); } if (black_image[MARGIN_RIGHT].is_valid()) { _bind_canvas_texture(black_image[MARGIN_RIGHT], RID(), true); Size2 sz(storage->texture_get_width(black_image[MARGIN_RIGHT]), storage->texture_get_height(black_image[MARGIN_RIGHT])); draw_generic_textured_rect(Rect2(window_w - black_margin[MARGIN_RIGHT], 0, black_margin[MARGIN_RIGHT], window_h), Rect2(0, 0, (float)black_margin[MARGIN_RIGHT] / sz.x, (float)window_h / sz.y)); } else if (black_margin[MARGIN_RIGHT]) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); draw_generic_textured_rect(Rect2(window_w - black_margin[MARGIN_RIGHT], 0, black_margin[MARGIN_RIGHT], window_h), Rect2(0, 0, 1, 1)); } if (black_image[MARGIN_TOP].is_valid()) { _bind_canvas_texture(black_image[MARGIN_TOP], RID(), true); Size2 sz(storage->texture_get_width(black_image[MARGIN_TOP]), storage->texture_get_height(black_image[MARGIN_TOP])); draw_generic_textured_rect(Rect2(0, 0, window_w, black_margin[MARGIN_TOP]), Rect2(0, 0, (float)window_w / sz.x, (float)black_margin[MARGIN_TOP] / sz.y)); } else if (black_margin[MARGIN_TOP]) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); draw_generic_textured_rect(Rect2(0, 0, window_w, black_margin[MARGIN_TOP]), Rect2(0, 0, 1, 1)); } if (black_image[MARGIN_BOTTOM].is_valid()) { _bind_canvas_texture(black_image[MARGIN_BOTTOM], RID(), true); Size2 sz(storage->texture_get_width(black_image[MARGIN_BOTTOM]), storage->texture_get_height(black_image[MARGIN_BOTTOM])); draw_generic_textured_rect(Rect2(0, window_h - black_margin[MARGIN_BOTTOM], window_w, black_margin[MARGIN_BOTTOM]), Rect2(0, 0, (float)window_w / sz.x, (float)black_margin[MARGIN_BOTTOM] / sz.y)); } else if (black_margin[MARGIN_BOTTOM]) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex); draw_generic_textured_rect(Rect2(0, window_h - black_margin[MARGIN_BOTTOM], window_w, black_margin[MARGIN_BOTTOM]), Rect2(0, 0, 1, 1)); } } void RasterizerCanvasBaseGLES3::initialize() { bool flag_stream = GLOBAL_GET("rendering/options/api_usage_legacy/flag_stream"); if (flag_stream) { _buffer_upload_usage_flag = GL_STREAM_DRAW; } else { _buffer_upload_usage_flag = GL_DYNAMIC_DRAW; } { //quad buffers glGenBuffers(1, &data.canvas_quad_vertices); glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices); { const float qv[8] = { 0, 0, 0, 1, 1, 1, 1, 0 }; glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 8, qv, GL_STATIC_DRAW); } glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind glGenVertexArrays(1, &data.canvas_quad_array); glBindVertexArray(data.canvas_quad_array); glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0); glEnableVertexAttribArray(0); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind } { //particle quad buffers glGenBuffers(1, &data.particle_quad_vertices); glBindBuffer(GL_ARRAY_BUFFER, data.particle_quad_vertices); { //quad of size 1, with pivot on the center for particles, then regular UVS. Color is general plus fetched from particle const float qv[16] = { -0.5, -0.5, 0.0, 0.0, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 1.0, 0.0 }; glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, qv, GL_STATIC_DRAW); } glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind glGenVertexArrays(1, &data.particle_quad_array); glBindVertexArray(data.particle_quad_array); glBindBuffer(GL_ARRAY_BUFFER, data.particle_quad_vertices); glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, 0); glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, CAST_INT_TO_UCHAR_PTR(8)); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind } { uint32_t poly_size = GLOBAL_DEF_RST("rendering/limits/buffers/canvas_polygon_buffer_size_kb", 128); ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/canvas_polygon_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/canvas_polygon_buffer_size_kb", PROPERTY_HINT_RANGE, "0,256,1,or_greater")); poly_size = MAX(poly_size, 2); // minimum 2k, may still see anomalies in editor poly_size *= 1024; //kb glGenBuffers(1, &data.polygon_buffer); glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); glBufferData(GL_ARRAY_BUFFER, poly_size, NULL, GL_DYNAMIC_DRAW); //allocate max size glBindBuffer(GL_ARRAY_BUFFER, 0); data.polygon_buffer_size = poly_size; //quad arrays for (int i = 0; i < Data::NUM_QUAD_ARRAY_VARIATIONS; i++) { glGenVertexArrays(1, &data.polygon_buffer_quad_arrays[i]); glBindVertexArray(data.polygon_buffer_quad_arrays[i]); glBindBuffer(GL_ARRAY_BUFFER, data.polygon_buffer); int uv_ofs = 0; int color_ofs = 0; int light_angle_ofs = 0; int stride = 2 * 4; if (i & 1) { //color color_ofs = stride; stride += 4 * 4; } if (i & 2) { //uv uv_ofs = stride; stride += 2 * 4; } if (i & 4) { //light_angle light_angle_ofs = stride; stride += 1 * 4; } glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, stride, NULL); if (i & 1) { glEnableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(color_ofs)); } if (i & 2) { glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(uv_ofs)); } if (i & 4) { // reusing tangent for light_angle glEnableVertexAttribArray(VS::ARRAY_TANGENT); glVertexAttribPointer(VS::ARRAY_TANGENT, 1, GL_FLOAT, GL_FALSE, stride, CAST_INT_TO_UCHAR_PTR(light_angle_ofs)); } glBindVertexArray(0); } glGenVertexArrays(1, &data.polygon_buffer_pointer_array); uint32_t index_size = GLOBAL_DEF_RST("rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", 128); ProjectSettings::get_singleton()->set_custom_property_info("rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", PropertyInfo(Variant::INT, "rendering/limits/buffers/canvas_polygon_index_buffer_size_kb", PROPERTY_HINT_RANGE, "0,256,1,or_greater")); index_size = MAX(index_size, 2); index_size *= 1024; //kb glGenBuffers(1, &data.polygon_index_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.polygon_index_buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_size, NULL, GL_DYNAMIC_DRAW); //allocate max size glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); data.polygon_index_buffer_size = index_size; } store_transform(Transform(), state.canvas_item_ubo_data.projection_matrix); glGenBuffers(1, &state.canvas_item_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_item_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(CanvasItemUBO), &state.canvas_item_ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.canvas_shader.init(); state.canvas_shader.set_base_material_tex_index(2); state.canvas_shadow_shader.init(); state.lens_shader.init(); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_RGBA_SHADOWS, storage->config.use_rgba_2d_shadows); state.canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES3::USE_RGBA_SHADOWS, storage->config.use_rgba_2d_shadows); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_PIXEL_SNAP, GLOBAL_DEF("rendering/quality/2d/use_pixel_snap", false)); } void RasterizerCanvasBaseGLES3::finalize() { glDeleteBuffers(1, &data.canvas_quad_vertices); glDeleteVertexArrays(1, &data.canvas_quad_array); glDeleteBuffers(1, &data.canvas_quad_vertices); glDeleteVertexArrays(1, &data.canvas_quad_array); glDeleteVertexArrays(1, &data.polygon_buffer_pointer_array); } RasterizerCanvasBaseGLES3::RasterizerCanvasBaseGLES3() { }
37.887109
260
0.745883
[ "render", "transform" ]
619446a22e66918729fb8af4df0842a94ad6b53e
26,339
cpp
C++
source/gui/widgets/combox.cpp
dudztroyer/nana
dbd8a4a6910aa3b81b77989a2d1866fdb26e4f6f
[ "BSL-1.0" ]
1
2018-10-28T20:01:43.000Z
2018-10-28T20:01:43.000Z
source/gui/widgets/combox.cpp
sahwar/nana
dbd8a4a6910aa3b81b77989a2d1866fdb26e4f6f
[ "BSL-1.0" ]
null
null
null
source/gui/widgets/combox.cpp
sahwar/nana
dbd8a4a6910aa3b81b77989a2d1866fdb26e4f6f
[ "BSL-1.0" ]
null
null
null
/* * A Combox Implementation * Nana C++ Library(http://www.nanapro.org) * Copyright(C) 2003-2018 Jinhao(cnjinhao@hotmail.com) * * 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) * * @file: nana/gui/widgets/combox.cpp */ #include <nana/gui.hpp> #include <nana/gui/widgets/combox.hpp> #include <nana/gui/element.hpp> #include <nana/system/dataexch.hpp> #include <nana/gui/widgets/float_listbox.hpp> #include <nana/gui/widgets/skeletons/text_editor.hpp> #include <nana/gui/widgets/skeletons/textbase_export_interface.hpp> #include <nana/gui/detail/widget_content_measurer_interface.hpp> #include <iterator> #include <algorithm> namespace nana { arg_combox::arg_combox(combox& wdg): widget(wdg) {} namespace drawerbase { namespace combox { class event_agent : public widgets::skeletons::textbase_event_agent_interface { public: event_agent(::nana::combox& wdg) : widget_(wdg) {} void first_change() override{} //empty, because combox does not have this event. void text_changed() override { widget_.events().text_changed.emit(::nana::arg_combox{ widget_ }, widget_); } private: ::nana::combox & widget_; }; struct item : public float_listbox::item_interface { public: std::shared_ptr<nana::detail::key_interface> key; nana::paint::image item_image; std::string item_text; mutable std::shared_ptr<nana::any> any_ptr; item(std::shared_ptr<nana::detail::key_interface> && kv) : key(std::move(kv)) { } item(std::string&& s) : item_text(std::move(s)) {} private: //implement item_interface methods const nana::paint::image & image() const override { return item_image; } const char* text() const override { return item_text.data(); } }; class drawer_impl { class content_measurer : public dev::widget_content_measurer_interface { public: content_measurer(drawer_impl* drwimpl) : drw_{ drwimpl } {} std::optional<size> measure(graph_reference graph, unsigned limit_pixels, bool /*limit_width*/) const override { //Combox doesn't provide a support of vfit and hfit if (limit_pixels) return{}; size content_size; for (std::size_t i = 0; i < drw_->the_number_of_options(); ++i) { auto & m = drw_->at(i); auto sz = graph.text_extent_size(m.item_text); content_size.width = (std::max)(content_size.width, sz.width); content_size.height = (std::max)(content_size.height, sz.height); } return content_size; } size extension() const override { return{ 19, 4 }; } private: drawer_impl* const drw_; }; public: using graph_reference = paint::graphics&; using widget_reference = widget&; enum class parts{none, text, push_button}; drawer_impl() { state_.focused = false; state_.button_state = element_state::normal; state_.pointer_where = parts::none; state_.lister = nullptr; measurer_.reset(new content_measurer{this}); } void renderer(drawerbase::float_listbox::item_renderer* ir) { item_renderer_ = ir; } void attached(widget_reference wd, graph_reference graph) { widget_ = static_cast< ::nana::combox*>(&wd); auto scheme = dynamic_cast< ::nana::widgets::skeletons::text_editor_scheme*>(API::dev::get_scheme(wd)); editor_ = new widgets::skeletons::text_editor(widget_->handle(), graph, scheme); _m_text_area(graph.size()); editor_->multi_lines(false); editable(false); graph_ = &graph; evt_agent_.reset(new event_agent{ static_cast<nana::combox&>(wd) }); editor_->textbase().set_event_agent(evt_agent_.get()); API::dev::set_measurer(wd, measurer_.get()); } void detached() { delete editor_; editor_ = nullptr; graph_ = nullptr; } void insert(std::string&& text) { items_.emplace_back(std::make_shared<item>(std::move(text))); API::refresh_window(widget_->handle()); } nana::any * anyobj(std::size_t pos, bool allocate_if_empty) const { if(pos >= items_.size()) return nullptr; auto & any_ptr = items_[pos]->any_ptr; if (allocate_if_empty && (nullptr == any_ptr)) any_ptr = std::make_shared<nana::any>(); return any_ptr.get(); } widgets::skeletons::text_editor * editor() const { return editor_; } widget* widget_ptr() const { return widget_; } void clear() { items_.clear(); module_.items.clear(); module_.index = nana::npos; } void editable(bool enb) { if(editor_) { editor_->editable(enb, false); editor_->show_caret(enb); if (!enb) { editor_->customized_renderers().background = [this](graph_reference graph, const ::nana::rectangle&, const ::nana::color&) { auto clr_from = colors::button_face_shadow_start; auto clr_to = colors::button_face_shadow_end; int pare_off_px = 1; if (element_state::pressed == state_.button_state) { pare_off_px = 2; std::swap(clr_from, clr_to); } graph.gradual_rectangle(::nana::rectangle(graph.size()).pare_off(pare_off_px), clr_from, clr_to, true); if (API::is_transparent_background(this->widget_ptr()->handle())) { paint::graphics trns_graph{ graph.size() }; if (API::dev::copy_transparent_background(this->widget_ptr()->handle(), trns_graph)) { graph.blend(rectangle{ trns_graph.size() }, trns_graph, {}, 0.5); } } }; } else editor_->customized_renderers().background = nullptr; editor_->enable_background(enb); editor_->enable_background_counterpart(!enb); API::refresh_window(widget_->handle()); } } bool editable() const { return (editor_ && editor_->attr().editable); } bool calc_where(graph_reference graph, int x, int y) { auto new_where = parts::none; if(1 < x && x < static_cast<int>(graph.width()) - 2 && 1 < y && y < static_cast<int>(graph.height()) - 2) { if((editor_->attr().editable == false) || (static_cast<int>(graph.width()) - 22 <= x)) new_where = parts::push_button; else new_where = parts::text; } if (new_where == state_.pointer_where) return false; state_.pointer_where = new_where; return true; } void set_button_state(element_state state, bool reset_where) { state_.button_state = state; if (reset_where) state_.pointer_where = parts::none; } void set_focused(bool f) { if(editor_) { state_.focused = f; if(editor_->attr().editable) editor_->select(f); } } bool has_lister() const { return (state_.lister != nullptr); } void open_lister_if_push_button_positioned() { if((nullptr == state_.lister) && !items_.empty() && (!editor_->attr().editable || (parts::push_button == state_.pointer_where))) { module_.items.clear(); std::copy(items_.cbegin(), items_.cend(), std::back_inserter(module_.items)); state_.lister = &form_loader<nana::float_listbox, false>()(widget_->handle(), nana::rectangle(0, widget_->size().height, widget_->size().width, 10), true); state_.lister->renderer(item_renderer_); state_.lister->set_module(module_, image_pixels_); state_.item_index_before_selection = module_.index; //The lister window closes by itself. I just take care about the destroy event. //The event should be destroy rather than unload. Because the unload event is invoked while //the lister is not closed, if popuping a message box, the lister will cover the message box. state_.lister->events().destroy.connect_unignorable([this](const arg_destroy&) { state_.lister = nullptr; //The lister closes by itself. if ((module_.index != nana::npos) && (module_.index != state_.item_index_before_selection)) { option(module_.index, true); API::update_window(*widget_); } else { //Redraw the widget even though the index has not been changed, //because the push button should be updated due to the state //changed from pressed to normal/hovered. API::refresh_window(*widget_); } }); } } void scroll_items(bool upwards) { if(state_.lister) state_.lister->scroll_items(upwards); } void move_items(bool upwards, bool circle) { if (state_.lister) { state_.lister->move_items(upwards, circle); return; } auto pos = module_.index; if (upwards) { if (pos && (pos < items_.size())) --pos; else if (circle) pos = items_.size() - 1; } else { if ((pos + 1) < items_.size()) ++pos; else if (circle) pos = 0; } if (pos != module_.index) option(pos, false); } void draw() { bool enb = widget_->enabled(); _m_text_area(widget_->size()); editor_->render(state_.focused); _m_draw_push_button(enb); _m_draw_image(); } std::size_t the_number_of_options() const { return items_.size(); } std::size_t option() const { return (module_.index < items_.size() ? module_.index : nana::npos); } void option(std::size_t index, bool ignore_condition) { if(items_.size() <= index) return; std::size_t old_index = module_.index; module_.index = index; if(nullptr == widget_) return; //Test if the current item or text is different from selected. if(ignore_condition || (old_index != index) || (items_[index]->item_text != widget_->caption())) { auto pos = API::cursor_position(); API::calc_window_point(widget_->handle(), pos); if (calc_where(*graph_, pos.x, pos.y)) state_.button_state = element_state::normal; editor_->text(to_wstring(items_[index]->item_text), false); editor_->try_refresh(); _m_draw_push_button(widget_->enabled()); _m_draw_image(); widget_->events().selected.emit(::nana::arg_combox(*widget_), widget_->handle()); } } std::size_t at_key(std::shared_ptr<nana::detail::key_interface>&& p) { std::size_t pos = 0; for (auto & m : items_) { if (m->key && detail::pred_equal(m->key.get(), p.get())) return pos; ++pos; } pos = items_.size(); items_.emplace_back(std::make_shared<item>(std::move(p))); //Redraw, because the state of push button is changed when a first new item is created. if (0 == pos) API::refresh_window(*widget_); return pos; } void erase(detail::key_interface * kv) { std::size_t pos = 0; for (auto & m : items_) { if (m->key && detail::pred_equal(m->key.get(), kv)) { erase(pos); return; } ++pos; } } item& at(std::size_t pos) { return *items_.at(pos); } const item& at(std::size_t pos) const { return *items_.at(pos); } void erase(std::size_t pos) { if (pos >= items_.size()) return; if (pos == module_.index) { module_.index = ::nana::npos; this->widget_->caption(""); } else if ((::nana::npos != module_.index) && (pos < module_.index)) --module_.index; items_.erase(items_.begin() + pos); //Redraw, because the state of push button is changed when the last item is removed. if (items_.empty()) API::refresh_window(*widget_); } void image(std::size_t pos, const nana::paint::image& img) { if (pos < items_.size()) { items_[pos]->item_image = img; if ((false == image_enabled_) && img) { image_enabled_ = true; draw(); } } } bool image_pixels(unsigned px) { if (image_pixels_ == px) return false; image_pixels_ = px; return true; } private: void _m_text_area(const nana::size& s) { auto extension = measurer_->extension(); nana::rectangle r(2, 2, s.width > extension.width ? s.width - extension.width : 0, s.height > extension.height ? s.height - extension.height : 0); if (image_enabled_) { unsigned place = image_pixels_ + 2; r.x += place; if (r.width > place) r.width -= place; } editor_->text_area(r); } void _m_draw_push_button(bool enabled) { ::nana::rectangle r{graph_->size()}; r.x = r.right() - 16; r.y = 1; r.width = 16; r.height -= 2; auto estate = state_.button_state; if (enabled && !items_.empty()) { if (has_lister() || (element_state::pressed == estate && state_.pointer_where == parts::push_button)) estate = element_state::pressed; } else estate = element_state::disabled; facade<element::button> button; button.draw(*graph_, ::nana::color{ 3, 65, 140 }, colors::white, r, estate); facade<element::arrow> arrow;// ("solid_triangle"); arrow.direction(::nana::direction::south); r.x += 4; r.y += (r.height / 2) - 7; r.width = r.height = 16; arrow.draw(*graph_, {}, colors::white, r, element_state::normal); } void _m_draw_image() { if(items_.size() <= module_.index) return; auto & img = items_[module_.index]->item_image; if(img.empty()) return; unsigned vpix = editor_->line_height(); nana::size imgsz = img.size(); if(imgsz.width > image_pixels_) { unsigned new_h = image_pixels_ * imgsz.height / imgsz.width; if(new_h > vpix) { imgsz.width = vpix * imgsz.width / imgsz.height; imgsz.height = vpix; } else { imgsz.width = image_pixels_; imgsz.height = new_h; } } else if(imgsz.height > vpix) { unsigned new_w = vpix * imgsz.width / imgsz.height; if(new_w > image_pixels_) { imgsz.height = image_pixels_ * imgsz.height / imgsz.width; imgsz.width = image_pixels_; } else { imgsz.height = vpix; imgsz.width = new_w; } } nana::point pos((image_pixels_ - imgsz.width) / 2 + 2, (vpix - imgsz.height) / 2 + 2); img.stretch(::nana::rectangle{ img.size() }, *graph_, nana::rectangle(pos, imgsz)); } private: std::vector<std::shared_ptr<item>> items_; nana::float_listbox::module_type module_; ::nana::combox * widget_{ nullptr }; nana::paint::graphics * graph_{ nullptr }; drawerbase::float_listbox::item_renderer* item_renderer_{ nullptr }; bool image_enabled_{ false }; unsigned image_pixels_{ 16 }; widgets::skeletons::text_editor * editor_{ nullptr }; std::unique_ptr<event_agent> evt_agent_; std::unique_ptr<content_measurer> measurer_; struct state_type { bool focused; element_state button_state; parts pointer_where; nana::float_listbox * lister; std::size_t item_index_before_selection; }state_; }; //end class drawer_impl //class trigger trigger::trigger() : drawer_(new drawer_impl) { } trigger::~trigger() { delete drawer_; } drawer_impl& trigger::get_drawer_impl() { return *drawer_; } const drawer_impl& trigger::get_drawer_impl() const { return *drawer_; } void trigger::attached(widget_reference wdg, graph_reference graph) { wdg.bgcolor(colors::white); drawer_->attached(wdg, graph); API::effects_edge_nimbus(wdg, effects::edge_nimbus::active); API::effects_edge_nimbus(wdg, effects::edge_nimbus::over); } void trigger::detached() { drawer_->detached(); } void trigger::refresh(graph_reference) { drawer_->draw(); } void trigger::focus(graph_reference, const arg_focus& arg) { drawer_->set_focused(arg.getting); if(drawer_->widget_ptr()->enabled()) { drawer_->draw(); drawer_->editor()->reset_caret(); API::dev::lazy_refresh(); } } void trigger::mouse_enter(graph_reference, const arg_mouse&) { drawer_->set_button_state(element_state::hovered, true); if(drawer_->widget_ptr()->enabled()) { drawer_->draw(); API::dev::lazy_refresh(); } } void trigger::mouse_leave(graph_reference, const arg_mouse&) { drawer_->set_button_state(element_state::normal, true); drawer_->editor()->mouse_enter(false); if(drawer_->widget_ptr()->enabled()) { drawer_->draw(); API::dev::lazy_refresh(); } } void trigger::mouse_down(graph_reference, const arg_mouse& arg) { drawer_->set_button_state(element_state::pressed, false); if(drawer_->widget_ptr()->enabled()) { auto * editor = drawer_->editor(); editor->mouse_pressed(arg); drawer_->open_lister_if_push_button_positioned(); drawer_->draw(); if(editor->attr().editable) editor->reset_caret(); API::dev::lazy_refresh(); } } void trigger::mouse_up(graph_reference, const arg_mouse& arg) { if (drawer_->widget_ptr()->enabled() && !drawer_->has_lister()) { drawer_->editor()->mouse_pressed(arg); drawer_->set_button_state(element_state::hovered, false); drawer_->draw(); API::dev::lazy_refresh(); } } void trigger::mouse_move(graph_reference graph, const arg_mouse& arg) { if(drawer_->widget_ptr()->enabled()) { bool redraw = drawer_->calc_where(graph, arg.pos.x, arg.pos.y); redraw |= drawer_->editor()->mouse_move(arg.left_button, arg.pos); if(redraw) { drawer_->draw(); drawer_->editor()->reset_caret(); API::dev::lazy_refresh(); } } } void trigger::mouse_wheel(graph_reference, const arg_wheel& arg) { if(drawer_->widget_ptr()->enabled()) { if(drawer_->has_lister()) drawer_->scroll_items(arg.upwards); else drawer_->move_items(arg.upwards, false); } } void trigger::key_press(graph_reference, const arg_keyboard& arg) { if(!drawer_->widget_ptr()->enabled()) return; bool call_other_keys = false; if(drawer_->editable()) { switch(arg.key) { case keyboard::os_arrow_left: case keyboard::os_arrow_right: drawer_->editor()->respond_key(arg); drawer_->editor()->reset_caret(); break; case keyboard::os_arrow_up: case keyboard::os_arrow_down: drawer_->move_items((keyboard::os_arrow_up == arg.key), true); break; default: call_other_keys = true; } } else { switch(arg.key) { case keyboard::os_arrow_left: case keyboard::os_arrow_up: drawer_->move_items(true, true); break; case keyboard::os_arrow_right: case keyboard::os_arrow_down: drawer_->move_items(false, true); break; default: call_other_keys = true; } } if (call_other_keys) drawer_->editor()->respond_key(arg); drawer_->editor()->try_refresh(); API::dev::lazy_refresh(); } void trigger::key_char(graph_reference, const arg_keyboard& arg) { drawer_->editor()->respond_char(arg); if (drawer_->editor()->try_refresh()) API::dev::lazy_refresh(); } //end class trigger //class item_proxy item_proxy::item_proxy(drawer_impl* impl, std::size_t pos) : impl_(impl), pos_(pos) {} item_proxy& item_proxy::text(const ::std::string& s) { throw_not_utf8(s); impl_->at(pos_).item_text = s; return *this; } ::std::string item_proxy::text() const { return impl_->at(pos_).item_text; } bool item_proxy::selected() const { return pos_ == impl_->option(); } item_proxy& item_proxy::select() { impl_->option(pos_, false); return *this; } item_proxy& item_proxy::icon(const nana::paint::image& img) { impl_->image(pos_, img); if (pos_ == impl_->option()) API::refresh_window(impl_->widget_ptr()->handle()); return *this; } nana::paint::image item_proxy::icon() const { return impl_->at(pos_).item_image; } /// Behavior of Iterator's value_type #ifdef _nana_std_has_string_view bool item_proxy::operator == (::std::string_view s) const { if (pos_ == nana::npos) return false; return (impl_->at(pos_).item_text == s); } #else bool item_proxy::operator == (const ::std::string& s) const { if (pos_ == nana::npos) return false; return (impl_->at(pos_).item_text ==s); } bool item_proxy::operator == (const char * s) const { if (pos_ == nana::npos) return false; return (impl_->at(pos_).item_text == s); } #endif /// Behavior of Iterator item_proxy & item_proxy::operator=(const item_proxy& r) { if (this != &r) { impl_ = r.impl_; pos_ = r.pos_; } return *this; } /// Behavior of Iterator item_proxy & item_proxy::operator++() { if (nana::npos != pos_) { if (++pos_ == impl_->the_number_of_options()) pos_ = nana::npos; } return *this; } /// Behavior of Iterator item_proxy item_proxy::operator++(int) { if (pos_ == nana::npos) return *this; item_proxy tmp = *this; if (++pos_ == impl_->the_number_of_options()) pos_ = nana::npos; return tmp; } /// Behavior of Iterator item_proxy& item_proxy::operator*() { return *this; } /// Behavior of Iterator const item_proxy& item_proxy::operator*() const { return *this; } /// Behavior of Iterator item_proxy* item_proxy::operator->() { return this; } /// Behavior of Iterator const item_proxy* item_proxy::operator->() const { return this; } /// Behavior of Iterator bool item_proxy::operator==(const item_proxy& r) const { return (impl_ == r.impl_ && pos_ == r.pos_); } /// Behavior of Iterator bool item_proxy::operator!=(const item_proxy& r) const { return ! this->operator==(r); } nana::any * item_proxy::_m_anyobj(bool alloc_if_empty) const { return impl_->anyobj(pos_, alloc_if_empty); } //end class item_proxy } }//end namespace drawerbase //class combox combox::combox(){} combox::combox(window wd, bool visible) { create(wd, rectangle(), visible); } combox::combox(window wd, std::string text, bool visible) { throw_not_utf8(text); create(wd, rectangle(), visible); caption(std::move(text)); } combox::combox(window wd, const char* text, bool visible) : combox(wd, std::string(text), visible) { } combox::combox(window wd, const nana::rectangle& r, bool visible) { create(wd, r, visible); } void combox::clear() { internal_scope_guard lock; _m_impl().clear(); API::refresh_window(handle()); } void combox::editable(bool eb) { internal_scope_guard lock; _m_impl().editable(eb); } bool combox::editable() const { internal_scope_guard lock; return _m_impl().editable(); } void combox::set_accept(std::function<bool(wchar_t)> pred) { internal_scope_guard lock; auto editor = _m_impl().editor(); if(editor) editor->set_accept(std::move(pred)); } combox& combox::push_back(std::string text) { internal_scope_guard lock; _m_impl().insert(std::move(text)); return *this; } std::size_t combox::the_number_of_options() const { internal_scope_guard lock; return _m_impl().the_number_of_options(); } std::size_t combox::option() const { internal_scope_guard lock; return _m_impl().option(); } void combox::option(std::size_t pos) { internal_scope_guard lock; _m_impl().option(pos, false); API::update_window(handle()); } ::std::string combox::text(std::size_t pos) const { internal_scope_guard lock; return _m_impl().at(pos).item_text; } void combox::erase(std::size_t pos) { internal_scope_guard lock; _m_impl().erase(pos); } void combox::renderer(item_renderer* ir) { internal_scope_guard lock; _m_impl().renderer(ir); } void combox::image(std::size_t i, const nana::paint::image& img) { internal_scope_guard lock; if(empty()) return; auto & impl = _m_impl(); impl.image(i, img); if(i == impl.option()) API::refresh_window(*this); } nana::paint::image combox::image(std::size_t pos) const { internal_scope_guard lock; return _m_impl().at(pos).item_image; } void combox::image_pixels(unsigned px) { internal_scope_guard lock; if (_m_impl().image_pixels(px)) API::refresh_window(*this); } auto combox::_m_caption() const noexcept -> native_string_type { internal_scope_guard lock; auto editor = _m_impl().editor(); if (editor) return to_nstring(editor->text()); return native_string_type(); } void combox::_m_caption(native_string_type&& str) { internal_scope_guard lock; auto editor = _m_impl().editor(); if (editor) editor->text(to_wstring(str), false); API::refresh_window(*this); } nana::any * combox::_m_anyobj(std::size_t pos, bool alloc_if_empty) const { internal_scope_guard lock; return _m_impl().anyobj(pos, alloc_if_empty); } auto combox::_m_at_key(std::shared_ptr<nana::detail::key_interface>&& p) -> item_proxy { internal_scope_guard lock; auto & impl = _m_impl(); return item_proxy(&impl, impl.at_key(std::move(p))); } void combox::_m_erase(nana::detail::key_interface* p) { internal_scope_guard lock; _m_impl().erase(p); } drawerbase::combox::drawer_impl & combox::_m_impl() { return get_drawer_trigger().get_drawer_impl(); } const drawerbase::combox::drawer_impl& combox::_m_impl() const { return get_drawer_trigger().get_drawer_impl(); } //end class combox }
24.010027
161
0.611489
[ "render", "vector" ]
6199b424dc9beb5ff9cbdb14954697a05a88e915
14,575
cpp
C++
src/FeatureUtils.cpp
alxvth/Spidr
307dfbec7e30d510275c6cffbf2e853cddf78e15
[ "MIT" ]
null
null
null
src/FeatureUtils.cpp
alxvth/Spidr
307dfbec7e30d510275c6cffbf2e853cddf78e15
[ "MIT" ]
null
null
null
src/FeatureUtils.cpp
alxvth/Spidr
307dfbec7e30d510275c6cffbf2e853cddf78e15
[ "MIT" ]
2
2022-02-17T10:18:51.000Z
2022-02-17T10:39:11.000Z
#include "FeatureUtils.h" #include <execution> // par_unseq #include <algorithm> // for_each_n #include <numeric> // iota #include <cmath> #include <stdexcept> #include <random> template<typename T> void NormVector(std::vector<T>& vec, T normVal) { std::for_each(std::execution::par_unseq, std::begin(vec), std::end(vec), [normVal](auto& val) { val /= normVal; }); } std::vector<unsigned int> PascalsTriangleRow(const unsigned int n) { std::vector<unsigned int> row(n + 1, 1); unsigned int entry = 1; for (unsigned int i = 1; i < n + 1; i++) { entry = (unsigned int)(entry * (n + 1 - i) / i); row[i] = entry; } return row; } // @param norm: 1 indicates max, 2 indicates sum, 0 indicates no normalization std::vector<float> BinomialKernel2D(const unsigned int width, norm_vec norm) { if (width % 2 == 0) throw std::invalid_argument("n must be odd"); std::vector<unsigned int> bino1D = PascalsTriangleRow(width - 1); std::vector<float> bino2D(width * width, -1); // helper for normalization int sum = 0; int max = 0; // outter product for (unsigned int row = 0; row < width; row++) { for (unsigned int col = 0; col < width; col++) { bino2D[row*width + col] = bino1D[row] * bino1D[col]; // helper for normalization sum += +bino2D[row*width + col]; if (bino2D[row*width + col] > (float)max) max = bino2D[row*width + col]; } } // normalization if (norm == norm_vec::NORM_MAX) NormVector(bino2D, (float)max); else if (norm == norm_vec::NORM_SUM) NormVector(bino2D, (float)sum); return bino2D; } std::vector<float> GaussianKernel1D(const unsigned int width, const float sd) { if (width % 2 == 0) throw std::invalid_argument("n must be odd"); if (sd < 0) throw std::invalid_argument("sd must be positive"); std::vector<float> kernel(width, 0); int coutner = 0; for (int i = (-1 * ((int)width - 1) / 2); i <= ((int)width - 1) / 2; i++) { kernel[coutner] = std::exp(-1 * (i*i) / (2 * sd * sd)); coutner++; } return kernel; } // @param norm: 1 indicates max, 2 indicates sum, 0 indicates no normalization std::vector<float> GaussianKernel2D(const unsigned int width, const float sd, norm_vec norm) { if (width % 2 == 0) throw std::invalid_argument("n must be odd"); if (sd < 0) throw std::invalid_argument("sd must be positive"); std::vector<float> gauss1D = GaussianKernel1D(width); std::vector<float> gauss2D(width * width, -1); // helper for normalization float sum = 0; float max = 0; // outter product for (unsigned int row = 0; row < width; row++) { for (unsigned int col = 0; col < width; col++) { gauss2D[row*width + col] = gauss1D[row] * gauss1D[col]; // helper for normalization sum += +gauss2D[row*width + col]; if (gauss2D[row*width + col] > (float)max) max = gauss2D[row*width + col]; } } // normalization if (norm == norm_vec::NORM_MAX) NormVector(gauss2D, max); else if (norm == norm_vec::NORM_SUM) NormVector(gauss2D, sum); return gauss2D; } unsigned int SqrtBinSize(unsigned int numItems) { return int(std::ceil(std::sqrt(numItems))); } unsigned int SturgesBinSize(unsigned int numItems) { return int(std::ceil(std::log2(numItems) + 1)); } unsigned int RiceBinSize(unsigned int numItems) { return int(std::ceil((2 * std::pow(numItems, 1.0/3)))); } std::vector<float> getNeighborhoodValues(const std::vector<int>& neighborIDs, const std::vector<float>& attribute_data, const size_t neighborhoodSize, const size_t numDims) { std::vector<float> neighborValues(neighborhoodSize * numDims); #ifdef NDEBUG // later an assert can check whether all values are different from FLT_MAX std::fill(neighborValues.begin(), neighborValues.end(), FLT_MAX); #endif // data layout with dimension d and neighbor n: [n0d0, n0d1, n0d2, ..., n1d0, n1d1, ..., n2d0, n2d1, ...] for (unsigned int neighbor = 0; neighbor < neighborhoodSize; neighbor++) { for (unsigned int dim = 0; dim < numDims; dim++) { neighborValues[neighbor * numDims + dim] = attribute_data[neighborIDs[neighbor] * numDims + dim]; } } return neighborValues; } std::vector<int> getNeighborhoodInds(const unsigned int coord_row, const unsigned int coord_col, const size_t kernelWidth, Eigen::MatrixXui* padded_ids) { Eigen::MatrixXui neighborhoodInds_mat = padded_ids->block(coord_row, coord_col, kernelWidth, kernelWidth); std::vector<int> neighborhoodInds_vec(neighborhoodInds_mat.data(), neighborhoodInds_mat.data() + neighborhoodInds_mat.size()); return neighborhoodInds_vec; } Eigen::MatrixXui padEdge(Eigen::MatrixXui mat, Eigen::Index pad_size) { //auto slice_sequence_rows = padAllDirections{ mat.rows(), pad_size }; //auto slice_sequence_cols = padAllDirections{ mat.cols(), pad_size }; //auto padded_mat = mat(slice_sequence_rows, slice_sequence_cols) return mat(padAllDirections{ mat.rows(), pad_size }, padAllDirections{ mat.cols(), pad_size }); } template< class scalar_type> Histogram_Base< scalar_type>::Histogram_Base(float min, float max, unsigned int numberOfBins) : _minVal(min), _maxVal(max), _numBins(numberOfBins), _countBinTotal(0), _countBinValid(0), _countBinUnderflow(0), _countBinOverflow(0) { _binWidth = (_maxVal - _minVal) / (float)_numBins; commonInit(); } // Resolve linker errors with explicit instantiation, https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl template Histogram_Base<unsigned int>::Histogram_Base(float min, float max, unsigned int numberOfBins); template Histogram_Base<float>::Histogram_Base(float min, float max, unsigned int numberOfBins); template< class scalar_type> Histogram_Base< scalar_type>::Histogram_Base(float min, float max, float binWidth) : _minVal(min), _maxVal(max), _binWidth(binWidth), _countBinTotal(0), _countBinValid(0), _countBinUnderflow(0), _countBinOverflow(0) { _numBins = std::ceil((_maxVal - _minVal) / (float)_binWidth); commonInit(); } template Histogram_Base<unsigned int>::Histogram_Base(float min, float max, float binWidth); template Histogram_Base<float>::Histogram_Base(float min, float max, float binWidth); template< class scalar_type> void Histogram_Base< scalar_type>::commonInit() { if (_minVal >= _maxVal) throw std::runtime_error("Histogram_Base: Bin max must be larger than bin min."); _counts = Eigen::Vector<scalar_type, -1>::Zero(_numBins); _binNormed = (float)_numBins / (_maxVal - _minVal); } template void Histogram_Base<unsigned int>::commonInit(); template void Histogram_Base<float>::commonInit(); template< class scalar_type> void Histogram_Base< scalar_type>::fill(const float value) { unsigned int binID; if (value >= _minVal && value < _maxVal) { binID = std::floor((value - _minVal) * _binNormed); _counts[binID] += 1; _countBinValid += 1; } else if (value == _maxVal) { _counts[_numBins - 1] += 1; _countBinValid += 1; } else if (value > _maxVal) { _countBinOverflow += 1; } else { _countBinUnderflow += 1; } _countBinTotal += 1; } template void Histogram_Base<unsigned int>::fill(const float value); template void Histogram_Base<float>::fill(const float value); template< class scalar_type> void Histogram_Base< scalar_type>::fill(const std::vector<float> values) { for (const float &value : values) fill(value); } template void Histogram_Base<unsigned int>::fill(const std::vector<float> values); template void Histogram_Base<float>::fill(const std::vector<float> values); template< class scalar_type> scalar_type Histogram_Base< scalar_type>::operator[](int index) const { assert(index >= 0 && index < _numBins); return _counts[index]; } template unsigned int Histogram_Base<unsigned int>::operator[](int index) const; template float Histogram_Base<float>::operator[](int index) const; void Histogram_Weighted::fill_weighted(const float value, const float weight) { unsigned int binID; if (value >= _minVal && value < _maxVal) { binID = std::floor((value - _minVal) * _binNormed); _counts[binID] += weight; _countBinValid += 1; } else if (value == _maxVal) { _counts[_numBins - 1] += weight; _countBinValid += 1; } else if (value > _maxVal) { _countBinOverflow += 1; } else { _countBinUnderflow += 1; } _countBinTotal += 1; } void Histogram_Weighted::fill_weighted(const std::vector<float> values, const std::vector<float> weights) { assert(values.size() == weights.size()); for (unsigned int i = 0; i < values.size(); i++) fill_weighted(values[i], weights[i]); } template< class scalar_type> Channel_Histogram_Base< scalar_type>::Channel_Histogram_Base(size_t numDims, float threshold) : _totalBinCounts(0), _numBins(numDims) { _tresholds = std::vector<float>(_numBins, threshold); _counts = Eigen::Vector<scalar_type, -1>::Zero(_numBins); } // Resolve linker errors with explicit instantiation, https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl template Channel_Histogram_Base<unsigned int>::Channel_Histogram_Base(size_t numDims, float threshold); template Channel_Histogram_Base<float>::Channel_Histogram_Base(size_t numDims, float threshold); template< class scalar_type> Channel_Histogram_Base< scalar_type>::Channel_Histogram_Base(std::vector<float> tresholds) : _tresholds(tresholds), _totalBinCounts(0) { _numBins = _tresholds.size(); _counts = Eigen::Vector<scalar_type, -1>::Zero(_numBins); } // Resolve linker errors with explicit instantiation, https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl template Channel_Histogram_Base<unsigned int>::Channel_Histogram_Base(std::vector<float> tresholds); template Channel_Histogram_Base<float>::Channel_Histogram_Base(std::vector<float> tresholds); template< class scalar_type> void Channel_Histogram_Base< scalar_type>::fill_ch(const size_t ch, const float value) { if (value >= _tresholds[ch]) { _counts[ch] += 1; _totalBinCounts += 1; } } template void Channel_Histogram_Base<unsigned int>::fill_ch(const size_t ch, const float values); template void Channel_Histogram_Base<float>::fill_ch(const size_t ch, const float values); template< class scalar_type> void Channel_Histogram_Base< scalar_type>::fill_ch(const size_t ch, const std::vector<float> values) { for (const float &value : values) fill_ch(ch, value); } template void Channel_Histogram_Base<unsigned int>::fill_ch(const size_t ch, const std::vector<float> values); template void Channel_Histogram_Base<float>::fill_ch(const size_t ch, const std::vector<float> values); template< class scalar_type> scalar_type Channel_Histogram_Base< scalar_type>::operator[](size_t index) const { assert(index >= 0 && index < _numBins); return _counts[index]; } template unsigned int Channel_Histogram_Base<unsigned int>::operator[](size_t index) const; template float Channel_Histogram_Base<float>::operator[](size_t size_t) const; void Channel_Histogram_Weighted::fill_ch_weighted(const size_t ch, const float value, const float weight) { if (value >= _tresholds[ch]) { _counts[ch] += weight; _totalBinCounts += 1; } } void Channel_Histogram_Weighted::fill_ch_weighted(const size_t ch, const std::vector<float> values, const std::vector<float> weights) { assert(values.size() == weights.size()); for (unsigned int i = 0; i < values.size(); i++) fill_ch_weighted(ch, values[i], weights[i]); } float variance(Eigen::VectorXf vec) { Eigen::VectorXf centered = vec.array() - vec.mean(); return (1.0f / (vec.size() - 1)) * centered.dot(centered); } float covariance(Eigen::VectorXf vec1, Eigen::VectorXf vec2) { assert(vec1.size() == vec2.size()); Eigen::VectorXf centered1 = vec1.array() - vec1.mean(); Eigen::VectorXf centered2 = vec2.array() - vec2.mean(); return (1.0f / (vec1.size() - 1)) * centered1.dot(centered2); } Eigen::MatrixXf covmat(Eigen::MatrixXf data) { // see https://stackoverflow.com/a/15142446 and https://en.wikipedia.org/wiki/Sample_mean_and_covariance#Definition_of_sample_covariance // also https://en.wikipedia.org/wiki/Sample_mean_and_covariance#Unbiasedness for discussion over (1 / (neighborhood.cols() - 1)) and (1 / neighborhood.cols()) // To align with the weighted case, we go for (1 / (neighborhood.cols() - 1)) Eigen::VectorXf mean_vec = data.rowwise().mean(); Eigen::MatrixXf centered = data.colwise() - mean_vec; float norm_weight = data.cols() - 1.0f; return (centered * centered.transpose()) / norm_weight; } Eigen::MatrixXf covmat(Eigen::MatrixXf data, Eigen::VectorXf probs) { assert(probs.size() == data.cols()); // one prob value for each observation assert(std::abs(probs.sum() - 1.0f) < 0.001); // cumulative prob must be 1 // see https://stackoverflow.com/a/42945996 for centered * probs.asDiagonal() // see https://en.wikipedia.org/wiki/Sample_mean_and_covariance#Weighted_samples for the 1 / (1 - probs.squaredNorm()) weight Eigen::VectorXf weighted_mean_vec = data * probs; Eigen::MatrixXf centered = data.colwise() - weighted_mean_vec; float norm_weight = 1 - probs.squaredNorm(); return ((centered * probs.asDiagonal()) * centered.transpose()) / norm_weight; } Multivar_normal compMultiVarFeatures(Eigen::MatrixXf data) { Eigen::VectorXf mean = data.rowwise().mean(); Eigen::MatrixXf cov_mat = covmat(data); return Multivar_normal{ mean , cov_mat }; } Multivar_normal compMultiVarFeatures(Eigen::MatrixXf data, Eigen::VectorXf probs) { Eigen::VectorXf weighted_mean = data * probs; Eigen::MatrixXf cov_mat = covmat(data, probs); return Multivar_normal{ weighted_mean , cov_mat }; } Eigen::VectorXf randomVector(unsigned int len, float lo, float hi) { std::random_device rd; std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd() std::uniform_real_distribution<float> dis(lo, hi); return Eigen::VectorXf::NullaryExpr(len, [&]() { return dis(gen); }); // definition with nullary expression: coefficients are defined by a functor }
37.661499
174
0.685969
[ "vector" ]
619c58c366bf046b69b79a07f0794513ff8934d2
23,210
cpp
C++
src/mbgl/style/layers/circle_layer.cpp
gomapi/gomapi-sdk-ios
e494bf0b31f612b5547e2830c1179ecd8bf350ed
[ "BSL-1.0", "Apache-2.0" ]
5
2019-12-02T07:13:06.000Z
2019-12-02T14:34:36.000Z
src/mbgl/style/layers/circle_layer.cpp
gomapi/gomapi-sdk-ios
e494bf0b31f612b5547e2830c1179ecd8bf350ed
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/style/layers/circle_layer.cpp
gomapi/gomapi-sdk-ios
e494bf0b31f612b5547e2830c1179ecd8bf350ed
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
// This file is generated. Edit scripts/generate-style-code.js, then run `make style-code`. #include <mbgl/style/layers/circle_layer.hpp> #include <mbgl/style/layers/circle_layer_impl.hpp> #include <mbgl/style/layer_observer.hpp> #include <mbgl/style/conversion/color_ramp_property_value.hpp> #include <mbgl/style/conversion/constant.hpp> #include <mbgl/style/conversion/property_value.hpp> #include <mbgl/style/conversion/transition_options.hpp> #include <mbgl/style/conversion/json.hpp> #include <mbgl/style/conversion_impl.hpp> #include <mbgl/util/traits.hpp> #include <mapbox/eternal.hpp> namespace mbgl { namespace style { // static const LayerTypeInfo* CircleLayer::Impl::staticTypeInfo() noexcept { const static LayerTypeInfo typeInfo{"circle", LayerTypeInfo::Source::Required, LayerTypeInfo::Pass3D::NotRequired, LayerTypeInfo::Layout::NotRequired, LayerTypeInfo::FadingTiles::NotRequired, LayerTypeInfo::CrossTileIndex::NotRequired, LayerTypeInfo::TileKind::Geometry}; return &typeInfo; } CircleLayer::CircleLayer(const std::string& layerID, const std::string& sourceID) : Layer(makeMutable<Impl>(layerID, sourceID)) { } CircleLayer::CircleLayer(Immutable<Impl> impl_) : Layer(std::move(impl_)) { } CircleLayer::~CircleLayer() = default; const CircleLayer::Impl& CircleLayer::impl() const { return static_cast<const Impl&>(*baseImpl); } Mutable<CircleLayer::Impl> CircleLayer::mutableImpl() const { return makeMutable<Impl>(impl()); } std::unique_ptr<Layer> CircleLayer::cloneRef(const std::string& id_) const { auto impl_ = mutableImpl(); impl_->id = id_; impl_->paint = CirclePaintProperties::Transitionable(); return std::make_unique<CircleLayer>(std::move(impl_)); } void CircleLayer::Impl::stringifyLayout(rapidjson::Writer<rapidjson::StringBuffer>&) const { } // Layout properties // Paint properties PropertyValue<float> CircleLayer::getDefaultCircleBlur() { return {0}; } const PropertyValue<float>& CircleLayer::getCircleBlur() const { return impl().paint.template get<CircleBlur>().value; } void CircleLayer::setCircleBlur(const PropertyValue<float>& value) { if (value == getCircleBlur()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleBlur>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleBlurTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleBlur>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleBlurTransition() const { return impl().paint.template get<CircleBlur>().options; } PropertyValue<Color> CircleLayer::getDefaultCircleColor() { return {Color::black()}; } const PropertyValue<Color>& CircleLayer::getCircleColor() const { return impl().paint.template get<CircleColor>().value; } void CircleLayer::setCircleColor(const PropertyValue<Color>& value) { if (value == getCircleColor()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleColor>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleColorTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleColor>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleColorTransition() const { return impl().paint.template get<CircleColor>().options; } PropertyValue<float> CircleLayer::getDefaultCircleOpacity() { return {1}; } const PropertyValue<float>& CircleLayer::getCircleOpacity() const { return impl().paint.template get<CircleOpacity>().value; } void CircleLayer::setCircleOpacity(const PropertyValue<float>& value) { if (value == getCircleOpacity()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleOpacity>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleOpacityTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleOpacity>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleOpacityTransition() const { return impl().paint.template get<CircleOpacity>().options; } PropertyValue<AlignmentType> CircleLayer::getDefaultCirclePitchAlignment() { return {AlignmentType::Viewport}; } const PropertyValue<AlignmentType>& CircleLayer::getCirclePitchAlignment() const { return impl().paint.template get<CirclePitchAlignment>().value; } void CircleLayer::setCirclePitchAlignment(const PropertyValue<AlignmentType>& value) { if (value == getCirclePitchAlignment()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CirclePitchAlignment>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCirclePitchAlignmentTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CirclePitchAlignment>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCirclePitchAlignmentTransition() const { return impl().paint.template get<CirclePitchAlignment>().options; } PropertyValue<CirclePitchScaleType> CircleLayer::getDefaultCirclePitchScale() { return {CirclePitchScaleType::Map}; } const PropertyValue<CirclePitchScaleType>& CircleLayer::getCirclePitchScale() const { return impl().paint.template get<CirclePitchScale>().value; } void CircleLayer::setCirclePitchScale(const PropertyValue<CirclePitchScaleType>& value) { if (value == getCirclePitchScale()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CirclePitchScale>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCirclePitchScaleTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CirclePitchScale>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCirclePitchScaleTransition() const { return impl().paint.template get<CirclePitchScale>().options; } PropertyValue<float> CircleLayer::getDefaultCircleRadius() { return {5}; } const PropertyValue<float>& CircleLayer::getCircleRadius() const { return impl().paint.template get<CircleRadius>().value; } void CircleLayer::setCircleRadius(const PropertyValue<float>& value) { if (value == getCircleRadius()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleRadius>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleRadiusTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleRadius>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleRadiusTransition() const { return impl().paint.template get<CircleRadius>().options; } PropertyValue<Color> CircleLayer::getDefaultCircleStrokeColor() { return {Color::black()}; } const PropertyValue<Color>& CircleLayer::getCircleStrokeColor() const { return impl().paint.template get<CircleStrokeColor>().value; } void CircleLayer::setCircleStrokeColor(const PropertyValue<Color>& value) { if (value == getCircleStrokeColor()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleStrokeColor>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleStrokeColorTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleStrokeColor>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleStrokeColorTransition() const { return impl().paint.template get<CircleStrokeColor>().options; } PropertyValue<float> CircleLayer::getDefaultCircleStrokeOpacity() { return {1}; } const PropertyValue<float>& CircleLayer::getCircleStrokeOpacity() const { return impl().paint.template get<CircleStrokeOpacity>().value; } void CircleLayer::setCircleStrokeOpacity(const PropertyValue<float>& value) { if (value == getCircleStrokeOpacity()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleStrokeOpacity>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleStrokeOpacityTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleStrokeOpacity>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleStrokeOpacityTransition() const { return impl().paint.template get<CircleStrokeOpacity>().options; } PropertyValue<float> CircleLayer::getDefaultCircleStrokeWidth() { return {0}; } const PropertyValue<float>& CircleLayer::getCircleStrokeWidth() const { return impl().paint.template get<CircleStrokeWidth>().value; } void CircleLayer::setCircleStrokeWidth(const PropertyValue<float>& value) { if (value == getCircleStrokeWidth()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleStrokeWidth>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleStrokeWidthTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleStrokeWidth>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleStrokeWidthTransition() const { return impl().paint.template get<CircleStrokeWidth>().options; } PropertyValue<std::array<float, 2>> CircleLayer::getDefaultCircleTranslate() { return {{{0, 0}}}; } const PropertyValue<std::array<float, 2>>& CircleLayer::getCircleTranslate() const { return impl().paint.template get<CircleTranslate>().value; } void CircleLayer::setCircleTranslate(const PropertyValue<std::array<float, 2>>& value) { if (value == getCircleTranslate()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleTranslate>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleTranslateTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleTranslate>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleTranslateTransition() const { return impl().paint.template get<CircleTranslate>().options; } PropertyValue<TranslateAnchorType> CircleLayer::getDefaultCircleTranslateAnchor() { return {TranslateAnchorType::Map}; } const PropertyValue<TranslateAnchorType>& CircleLayer::getCircleTranslateAnchor() const { return impl().paint.template get<CircleTranslateAnchor>().value; } void CircleLayer::setCircleTranslateAnchor(const PropertyValue<TranslateAnchorType>& value) { if (value == getCircleTranslateAnchor()) return; auto impl_ = mutableImpl(); impl_->paint.template get<CircleTranslateAnchor>().value = value; baseImpl = std::move(impl_); observer->onLayerChanged(*this); } void CircleLayer::setCircleTranslateAnchorTransition(const TransitionOptions& options) { auto impl_ = mutableImpl(); impl_->paint.template get<CircleTranslateAnchor>().options = options; baseImpl = std::move(impl_); } TransitionOptions CircleLayer::getCircleTranslateAnchorTransition() const { return impl().paint.template get<CircleTranslateAnchor>().options; } using namespace conversion; namespace { enum class Property : uint8_t { CircleBlur, CircleColor, CircleOpacity, CirclePitchAlignment, CirclePitchScale, CircleRadius, CircleStrokeColor, CircleStrokeOpacity, CircleStrokeWidth, CircleTranslate, CircleTranslateAnchor, CircleBlurTransition, CircleColorTransition, CircleOpacityTransition, CirclePitchAlignmentTransition, CirclePitchScaleTransition, CircleRadiusTransition, CircleStrokeColorTransition, CircleStrokeOpacityTransition, CircleStrokeWidthTransition, CircleTranslateTransition, CircleTranslateAnchorTransition, }; template <typename T> constexpr uint8_t toUint8(T t) noexcept { return uint8_t(mbgl::underlying_type(t)); } MAPBOX_ETERNAL_CONSTEXPR const auto layerProperties = mapbox::eternal::hash_map<mapbox::eternal::string, uint8_t>( {{"circle-blur", toUint8(Property::CircleBlur)}, {"circle-color", toUint8(Property::CircleColor)}, {"circle-opacity", toUint8(Property::CircleOpacity)}, {"circle-pitch-alignment", toUint8(Property::CirclePitchAlignment)}, {"circle-pitch-scale", toUint8(Property::CirclePitchScale)}, {"circle-radius", toUint8(Property::CircleRadius)}, {"circle-stroke-color", toUint8(Property::CircleStrokeColor)}, {"circle-stroke-opacity", toUint8(Property::CircleStrokeOpacity)}, {"circle-stroke-width", toUint8(Property::CircleStrokeWidth)}, {"circle-translate", toUint8(Property::CircleTranslate)}, {"circle-translate-anchor", toUint8(Property::CircleTranslateAnchor)}, {"circle-blur-transition", toUint8(Property::CircleBlurTransition)}, {"circle-color-transition", toUint8(Property::CircleColorTransition)}, {"circle-opacity-transition", toUint8(Property::CircleOpacityTransition)}, {"circle-pitch-alignment-transition", toUint8(Property::CirclePitchAlignmentTransition)}, {"circle-pitch-scale-transition", toUint8(Property::CirclePitchScaleTransition)}, {"circle-radius-transition", toUint8(Property::CircleRadiusTransition)}, {"circle-stroke-color-transition", toUint8(Property::CircleStrokeColorTransition)}, {"circle-stroke-opacity-transition", toUint8(Property::CircleStrokeOpacityTransition)}, {"circle-stroke-width-transition", toUint8(Property::CircleStrokeWidthTransition)}, {"circle-translate-transition", toUint8(Property::CircleTranslateTransition)}, {"circle-translate-anchor-transition", toUint8(Property::CircleTranslateAnchorTransition)}}); constexpr uint8_t lastPaintPropertyIndex = toUint8(Property::CircleTranslateAnchorTransition); } // namespace optional<Error> CircleLayer::setPaintProperty(const std::string& name, const Convertible& value) { const auto it = layerProperties.find(name.c_str()); if (it == layerProperties.end() || it->second > lastPaintPropertyIndex) { return Error{"layer doesn't support this property"}; } auto property = static_cast<Property>(it->second); if (property == Property::CircleBlur || property == Property::CircleOpacity || property == Property::CircleRadius || property == Property::CircleStrokeOpacity || property == Property::CircleStrokeWidth) { Error error; optional<PropertyValue<float>> typedValue = convert<PropertyValue<float>>(value, error, true, false); if (!typedValue) { return error; } if (property == Property::CircleBlur) { setCircleBlur(*typedValue); return nullopt; } if (property == Property::CircleOpacity) { setCircleOpacity(*typedValue); return nullopt; } if (property == Property::CircleRadius) { setCircleRadius(*typedValue); return nullopt; } if (property == Property::CircleStrokeOpacity) { setCircleStrokeOpacity(*typedValue); return nullopt; } if (property == Property::CircleStrokeWidth) { setCircleStrokeWidth(*typedValue); return nullopt; } } if (property == Property::CircleColor || property == Property::CircleStrokeColor) { Error error; optional<PropertyValue<Color>> typedValue = convert<PropertyValue<Color>>(value, error, true, false); if (!typedValue) { return error; } if (property == Property::CircleColor) { setCircleColor(*typedValue); return nullopt; } if (property == Property::CircleStrokeColor) { setCircleStrokeColor(*typedValue); return nullopt; } } if (property == Property::CirclePitchAlignment) { Error error; optional<PropertyValue<AlignmentType>> typedValue = convert<PropertyValue<AlignmentType>>(value, error, false, false); if (!typedValue) { return error; } setCirclePitchAlignment(*typedValue); return nullopt; } if (property == Property::CirclePitchScale) { Error error; optional<PropertyValue<CirclePitchScaleType>> typedValue = convert<PropertyValue<CirclePitchScaleType>>(value, error, false, false); if (!typedValue) { return error; } setCirclePitchScale(*typedValue); return nullopt; } if (property == Property::CircleTranslate) { Error error; optional<PropertyValue<std::array<float, 2>>> typedValue = convert<PropertyValue<std::array<float, 2>>>(value, error, false, false); if (!typedValue) { return error; } setCircleTranslate(*typedValue); return nullopt; } if (property == Property::CircleTranslateAnchor) { Error error; optional<PropertyValue<TranslateAnchorType>> typedValue = convert<PropertyValue<TranslateAnchorType>>(value, error, false, false); if (!typedValue) { return error; } setCircleTranslateAnchor(*typedValue); return nullopt; } Error error; optional<TransitionOptions> transition = convert<TransitionOptions>(value, error); if (!transition) { return error; } if (property == Property::CircleBlurTransition) { setCircleBlurTransition(*transition); return nullopt; } if (property == Property::CircleColorTransition) { setCircleColorTransition(*transition); return nullopt; } if (property == Property::CircleOpacityTransition) { setCircleOpacityTransition(*transition); return nullopt; } if (property == Property::CirclePitchAlignmentTransition) { setCirclePitchAlignmentTransition(*transition); return nullopt; } if (property == Property::CirclePitchScaleTransition) { setCirclePitchScaleTransition(*transition); return nullopt; } if (property == Property::CircleRadiusTransition) { setCircleRadiusTransition(*transition); return nullopt; } if (property == Property::CircleStrokeColorTransition) { setCircleStrokeColorTransition(*transition); return nullopt; } if (property == Property::CircleStrokeOpacityTransition) { setCircleStrokeOpacityTransition(*transition); return nullopt; } if (property == Property::CircleStrokeWidthTransition) { setCircleStrokeWidthTransition(*transition); return nullopt; } if (property == Property::CircleTranslateTransition) { setCircleTranslateTransition(*transition); return nullopt; } if (property == Property::CircleTranslateAnchorTransition) { setCircleTranslateAnchorTransition(*transition); return nullopt; } return Error{"layer doesn't support this property"}; } StyleProperty CircleLayer::getProperty(const std::string& name) const { const auto it = layerProperties.find(name.c_str()); if (it == layerProperties.end()) { return {}; } switch (static_cast<Property>(it->second)) { case Property::CircleBlur: return makeStyleProperty(getCircleBlur()); case Property::CircleColor: return makeStyleProperty(getCircleColor()); case Property::CircleOpacity: return makeStyleProperty(getCircleOpacity()); case Property::CirclePitchAlignment: return makeStyleProperty(getCirclePitchAlignment()); case Property::CirclePitchScale: return makeStyleProperty(getCirclePitchScale()); case Property::CircleRadius: return makeStyleProperty(getCircleRadius()); case Property::CircleStrokeColor: return makeStyleProperty(getCircleStrokeColor()); case Property::CircleStrokeOpacity: return makeStyleProperty(getCircleStrokeOpacity()); case Property::CircleStrokeWidth: return makeStyleProperty(getCircleStrokeWidth()); case Property::CircleTranslate: return makeStyleProperty(getCircleTranslate()); case Property::CircleTranslateAnchor: return makeStyleProperty(getCircleTranslateAnchor()); case Property::CircleBlurTransition: return makeStyleProperty(getCircleBlurTransition()); case Property::CircleColorTransition: return makeStyleProperty(getCircleColorTransition()); case Property::CircleOpacityTransition: return makeStyleProperty(getCircleOpacityTransition()); case Property::CirclePitchAlignmentTransition: return makeStyleProperty(getCirclePitchAlignmentTransition()); case Property::CirclePitchScaleTransition: return makeStyleProperty(getCirclePitchScaleTransition()); case Property::CircleRadiusTransition: return makeStyleProperty(getCircleRadiusTransition()); case Property::CircleStrokeColorTransition: return makeStyleProperty(getCircleStrokeColorTransition()); case Property::CircleStrokeOpacityTransition: return makeStyleProperty(getCircleStrokeOpacityTransition()); case Property::CircleStrokeWidthTransition: return makeStyleProperty(getCircleStrokeWidthTransition()); case Property::CircleTranslateTransition: return makeStyleProperty(getCircleTranslateTransition()); case Property::CircleTranslateAnchorTransition: return makeStyleProperty(getCircleTranslateAnchorTransition()); } return {}; } optional<Error> CircleLayer::setLayoutProperty(const std::string& name, const Convertible& value) { if (name == "visibility") { return Layer::setVisibility(value); } return Error { "layer doesn't support this property" }; } Mutable<Layer::Impl> CircleLayer::mutableBaseImpl() const { return staticMutableCast<Layer::Impl>(mutableImpl()); } } // namespace style } // namespace mbgl
34.590164
208
0.697372
[ "geometry" ]
61a1d15ed130e5bf79fefb0898370eeed3d4acae
3,149
cpp
C++
lib/mockturtle/experiments/node_resynthesis.cpp
gian21391/enumeration_tool
607ca83c5cf8a7da6ea7438afcd158607e005a11
[ "MIT" ]
1
2019-05-25T17:40:15.000Z
2019-05-25T17:40:15.000Z
lib/mockturtle/experiments/node_resynthesis.cpp
gian21391/enumeration_tool
607ca83c5cf8a7da6ea7438afcd158607e005a11
[ "MIT" ]
2
2021-03-05T21:12:07.000Z
2021-03-06T18:42:52.000Z
lib/mockturtle/experiments/node_resynthesis.cpp
gian21391/enumeration_tool
607ca83c5cf8a7da6ea7438afcd158607e005a11
[ "MIT" ]
2
2021-07-26T14:46:51.000Z
2021-11-09T11:32:09.000Z
/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * 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 <string> #include <vector> #include <fmt/format.h> #include <lorina/aiger.hpp> #include <mockturtle/algorithms/collapse_mapped.hpp> #include <mockturtle/algorithms/equivalence_checking.hpp> #include <mockturtle/algorithms/lut_mapping.hpp> #include <mockturtle/algorithms/miter.hpp> #include <mockturtle/algorithms/node_resynthesis/dsd.hpp> #include <mockturtle/algorithms/node_resynthesis/exact.hpp> #include <mockturtle/algorithms/node_resynthesis.hpp> #include <mockturtle/io/aiger_reader.hpp> #include <mockturtle/networks/aig.hpp> #include <mockturtle/networks/klut.hpp> #include <mockturtle/views/mapping_view.hpp> #include <experiments.hpp> int main() { using namespace experiments; using namespace mockturtle; experiment<std::string, uint32_t, double, bool> exp( "node_resynthesis", "benchmark", "gates", "runtime", "equivalent" ); exact_resynthesis_params ps; ps.cache = std::make_shared<exact_resynthesis_params::cache_map_t>(); exact_aig_resynthesis<aig_network> exact_resyn( false, ps ); for ( auto const& benchmark : epfl_benchmarks( ~hyp ) ) { fmt::print( "[i] processing {}\n", benchmark ); aig_network aig; lorina::read_aiger( benchmark_path( benchmark ), aiger_reader( aig ) ); lut_mapping_params ps; ps.cut_enumeration_ps.cut_size = 4u; lut_mapping_stats st; mapping_view<aig_network, true> mapped_aig{aig}; lut_mapping<decltype( mapped_aig ), true>( mapped_aig, ps, &st ); const auto klut = *collapse_mapped_network<klut_network>( mapped_aig ); node_resynthesis_stats nrst; dsd_resynthesis<aig_network, decltype( exact_resyn )> resyn( exact_resyn ); aig_network aig2 = node_resynthesis<aig_network>( klut, resyn, {}, &nrst ); auto cec = abc_cec( aig2, benchmark ); //*equivalence_checking( *miter<aig_network>( aig, aig2 ) ); exp( benchmark, aig2.num_gates(), to_seconds( st.time_total ) + to_seconds( nrst.time_total ), cec ); } exp.save(); exp.table(); return 0; }
37.939759
123
0.745316
[ "vector" ]
61a3f9bcb3753aa29eee32d97b75ccfc1e5a8725
32,176
cpp
C++
src/utils/yaml/YamlTraits.cpp
normal-coder/polarphp
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
[ "PHP-3.01" ]
1
2019-01-28T01:33:49.000Z
2019-01-28T01:33:49.000Z
src/utils/yaml/YamlTraits.cpp
normal-coder/polarphp
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
[ "PHP-3.01" ]
null
null
null
src/utils/yaml/YamlTraits.cpp
normal-coder/polarphp
a06e1f8781b4b75a2ca8cf2c22e0aa62631866fe
[ "PHP-3.01" ]
null
null
null
// This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2018 polarphp software foundation // Copyright (c) 2017 - 2018 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // #include "polarphp/utils/yaml/YamlTraits.h" #include "polarphp/basic/adt/StlExtras.h" #include "polarphp/basic/adt/SmallString.h" #include "polarphp/basic/adt/StringExtras.h" #include "polarphp/basic/adt/StringRef.h" #include "polarphp/basic/adt/Twine.h" #include "polarphp/utils/Casting.h" #include "polarphp/utils/ErrorCode.h" #include "polarphp/utils/ErrorHandling.h" #include "polarphp/utils/Format.h" #include "polarphp/utils/LineIterator.h" #include "polarphp/utils/MemoryBuffer.h" #include "polarphp/utils/Unicode.h" #include "polarphp/utils/yaml/YamlParser.h" #include "polarphp/utils/RawOutStream.h" #include <algorithm> #include <cassert> #include <cstdint> #include <cstdlib> #include <cstring> #include <string> #include <vector> namespace polar { namespace yaml { using polar::utils::SmallString; using polar::basic::StringLiteral; using polar::utils::MemoryBuffer; using polar::utils::LineIterator; using polar::utils::ErrorCode; using polar::utils::isa; using polar::utils::dyn_cast_or_null; using polar::utils::dyn_cast; using polar::utils::report_fatal_error; using polar::utils::format; using polar::basic::is_contained; using polar::utils::format_hex_no_prefix; using polar::basic::get_as_unsigned_integer; using polar::basic::get_as_signed_integer; using polar::basic::to_float; //===----------------------------------------------------------------------===// // IO //===----------------------------------------------------------------------===// IO::IO(void *context) : m_context(context) {} IO::~IO() {} void *IO::getContext() { return m_context; } void IO::setContext(void *context) { m_context = context; } //===----------------------------------------------------------------------===// // Input //===----------------------------------------------------------------------===// Input::Input(StringRef inputContent, void *context, SourceMgr::DiagHandlerTy diagHandler, void *diagHandlerCtxt) : IO(context), m_strm(new Stream(inputContent, m_srcMgr, false, &m_errorCode)) { if (diagHandler) { m_srcMgr.setDiagHandler(diagHandler, diagHandlerCtxt); } m_docIterator = m_strm->begin(); } Input::Input(MemoryBufferRef input, void *context, SourceMgr::DiagHandlerTy diagHandler, void *diagHandlerCtxt) : IO(context), m_strm(new Stream(input, m_srcMgr, false, &m_errorCode)) { if (diagHandler) { m_srcMgr.setDiagHandler(diagHandler, diagHandlerCtxt); } m_docIterator = m_strm->begin(); } Input::~Input() {} std::error_code Input::getError() { return m_errorCode; } // Pin the vtables to this file. void Input::HNode::anchor() {} void Input::EmptyHNode::anchor() {} void Input::ScalarHNode::anchor() {} void Input::MapHNode::anchor() {} void Input::SequenceHNode::anchor() {} bool Input::outputting() { return false; } bool Input::setCurrentDocument() { if (m_docIterator != m_strm->end()) { Node *node = m_docIterator->getRoot(); if (!node) { assert(m_strm->failed() && "Root is NULL iff parsing failed"); m_errorCode = make_error_code(ErrorCode::invalid_argument); return false; } if (isa<NullNode>(node)) { // Empty files are allowed and ignored ++m_docIterator; return setCurrentDocument(); } m_topNode = createHNodes(node); m_currentNode = m_topNode.get(); return true; } return false; } bool Input::nextDocument() { return ++m_docIterator != m_strm->end(); } const Node *Input::getCurrentNode() const { return m_currentNode ? m_currentNode->m_node : nullptr; } bool Input::mapTag(StringRef tag, bool defaultValue) { std::string foundTag = m_currentNode->m_node->getVerbatimTag(); if (foundTag.empty()) { // If no tag found and 'tag' is the default, say it was found. return defaultValue; } // Return true iff found tag matches supplied tag. return tag.equals(foundTag); } void Input::beginMapping() { if (m_errorCode) { return; } // m_currentNode can be null if the document is empty. MapHNode *mapNode = dyn_cast_or_null<MapHNode>(m_currentNode); if (mapNode) { mapNode->m_validKeys.clear(); } } std::vector<StringRef> Input::getKeys() { MapHNode *mapNode = dyn_cast<MapHNode>(m_currentNode); std::vector<StringRef> ret; if (!mapNode) { setError(m_currentNode, "not a mapping"); return ret; } for (auto &map : mapNode->m_mapping) { ret.push_back(map.getFirst()); } return ret; } bool Input::preflightKey(const char *key, bool required, bool, bool &useDefault, void *&saveInfo) { useDefault = false; if (m_errorCode) { return false; } // m_currentNode is null for empty documents, which is an error in case required // nodes are present. if (!m_currentNode) { if (required) { m_errorCode = make_error_code(ErrorCode::invalid_argument); } return false; } MapHNode *mapNode = dyn_cast<MapHNode>(m_currentNode); if (!mapNode) { if (required || !isa<EmptyHNode>(m_currentNode)) { setError(m_currentNode, "not a mapping"); } return false; } mapNode->m_validKeys.push_back(key); HNode *value = mapNode->m_mapping[key].get(); if (!value) { if (required) { setError(m_currentNode, Twine("missing required key '") + key + "'"); } else { useDefault = true; } return false; } saveInfo = m_currentNode; m_currentNode = value; return true; } void Input::postflightKey(void *saveInfo) { m_currentNode = reinterpret_cast<HNode *>(saveInfo); } void Input::endMapping() { if (m_errorCode) { return; } // m_currentNode can be null if the document is empty. MapHNode *mapNode = dyn_cast_or_null<MapHNode>(m_currentNode); if (!mapNode) { return; } for (const auto &mapItem : mapNode->m_mapping) { if (!is_contained(mapNode->m_validKeys, mapItem.getFirst())) { setError(mapItem.m_second.get(), Twine("unknown key '") + mapItem.getFirst() + "'"); break; } } } void Input::beginFlowMapping() { beginMapping(); } void Input::endFlowMapping() { endMapping(); } size_t Input::beginSequence() { if (SequenceHNode *sequence = dyn_cast<SequenceHNode>(m_currentNode)) { return sequence->m_entries.size(); } if (isa<EmptyHNode>(m_currentNode)) { return 0; } // Treat case where there's a scalar "null" value as an empty sequence. if (ScalarHNode *sn = dyn_cast<ScalarHNode>(m_currentNode)) { if (is_null(sn->value())) { return 0; } } // Any other type of HNode is an error. setError(m_currentNode, "not a sequence"); return 0; } void Input::endSequence() { } bool Input::preflightElement(unsigned index, void *&saveInfo) { if (m_errorCode) { return false; } if (SequenceHNode *sequence = dyn_cast<SequenceHNode>(m_currentNode)) { saveInfo = m_currentNode; m_currentNode = sequence->m_entries[index].get(); return true; } return false; } void Input::postflightElement(void *saveInfo) { m_currentNode = reinterpret_cast<HNode *>(saveInfo); } size_t Input::beginFlowSequence() { return beginSequence(); } bool Input::preflightFlowElement(unsigned index, void *&saveInfo) { if (m_errorCode) { return false; } if (SequenceHNode *sequence = dyn_cast<SequenceHNode>(m_currentNode)) { saveInfo = m_currentNode; m_currentNode = sequence->m_entries[index].get(); return true; } return false; } void Input::postflightFlowElement(void *saveInfo) { m_currentNode = reinterpret_cast<HNode *>(saveInfo); } void Input::endFlowSequence() { } void Input::beginEnumScalar() { m_scalarMatchFound = false; } bool Input::matchEnumScalar(const char *str, bool) { if (m_scalarMatchFound) { return false; } if (ScalarHNode *sn = dyn_cast<ScalarHNode>(m_currentNode)) { if (sn->value().equals(str)) { m_scalarMatchFound = true; return true; } } return false; } bool Input::matchEnumFallback() { if (m_scalarMatchFound) { return false; } m_scalarMatchFound = true; return true; } void Input::endEnumScalar() { if (!m_scalarMatchFound) { setError(m_currentNode, "unknown enumerated scalar"); } } bool Input::beginBitSetScalar(bool &doClear) { m_bitValuesUsed.clear(); if (SequenceHNode *sequence = dyn_cast<SequenceHNode>(m_currentNode)) { m_bitValuesUsed.insert(m_bitValuesUsed.begin(), sequence->m_entries.size(), false); } else { setError(m_currentNode, "expected sequence of bit values"); } doClear = true; return true; } bool Input::bitSetMatch(const char *str, bool) { if (m_errorCode) return false; if (SequenceHNode *sequence = dyn_cast<SequenceHNode>(m_currentNode)) { unsigned index = 0; for (auto &node : sequence->m_entries) { if (ScalarHNode *sn = dyn_cast<ScalarHNode>(node.get())) { if (sn->value().equals(str)) { m_bitValuesUsed[index] = true; return true; } } else { setError(m_currentNode, "unexpected scalar in sequence of bit values"); } ++index; } } else { setError(m_currentNode, "expected sequence of bit values"); } return false; } void Input::endBitSetScalar() { if (m_errorCode) { return; } if (SequenceHNode *sequence = dyn_cast<SequenceHNode>(m_currentNode)) { assert(m_bitValuesUsed.size() == sequence->m_entries.size()); for (unsigned i = 0; i < sequence->m_entries.size(); ++i) { if (!m_bitValuesUsed[i]) { setError(sequence->m_entries[i].get(), "unknown bit value"); return; } } } } void Input::scalarString(StringRef &str, QuotingType) { if (ScalarHNode *sn = dyn_cast<ScalarHNode>(m_currentNode)) { str = sn->value(); } else { setError(m_currentNode, "unexpected scalar"); } } void Input::blockScalarString(StringRef &str) { scalarString(str, QuotingType::None); } void Input::scalarTag(std::string &tag) { tag = m_currentNode->m_node->getVerbatimTag(); } void Input::setError(HNode *hnode, const Twine &message) { assert(hnode && "HNode must not be NULL"); setError(hnode->m_node, message); } void Input::setError(Node *node, const Twine &message) { m_strm->printError(node, message); m_errorCode = make_error_code(ErrorCode::invalid_argument); } NodeKind Input::getNodeKind() { if (isa<ScalarHNode>(m_currentNode)) { return NodeKind::Scalar; } else if (isa<MapHNode>(m_currentNode)) { return NodeKind::Map; } else if (isa<SequenceHNode>(m_currentNode)) { return NodeKind::Sequence; } polar_unreachable("Unsupported node kind"); } std::unique_ptr<Input::HNode> Input::createHNodes(Node *node) { SmallString<128> stringStorage; if (ScalarNode *sn = dyn_cast<ScalarNode>(node)) { StringRef keyStr = sn->getValue(stringStorage); if (!stringStorage.empty()) { // Copy string to permanent storage keyStr = stringStorage.getStr().copy(m_stringAllocator); } return std::make_unique<ScalarHNode>(node, keyStr); } else if (BlockScalarNode *bsn = dyn_cast<BlockScalarNode>(node)) { StringRef valueCopy = bsn->getValue().copy(m_stringAllocator); return std::make_unique<ScalarHNode>(node, valueCopy); } else if (SequenceNode *sequence = dyn_cast<SequenceNode>(node)) { auto sequenceHNode = std::make_unique<SequenceHNode>(node); for (Node &sn : *sequence) { auto Entry = createHNodes(&sn); if (m_errorCode) { break; } sequenceHNode->m_entries.push_back(std::move(Entry)); } return std::move(sequenceHNode); } else if (MappingNode *Map = dyn_cast<MappingNode>(node)) { auto mapHNode = std::make_unique<MapHNode>(node); for (KeyValueNode &kvn : *Map) { Node *KeyNode = kvn.getKey(); ScalarNode *key = dyn_cast<ScalarNode>(KeyNode); Node *value = kvn.getValue(); if (!key || !value) { if (!key) { setError(KeyNode, "Map key must be a scalar"); } if (!value) { setError(KeyNode, "Map value must not be empty"); } break; } stringStorage.clear(); StringRef keyStr = key->getValue(stringStorage); if (!stringStorage.empty()) { // Copy string to permanent storage keyStr = stringStorage.getStr().copy(m_stringAllocator); } auto ValueHNode = createHNodes(value); if (m_errorCode) { break; } mapHNode->m_mapping[keyStr] = std::move(ValueHNode); } return std::move(mapHNode); } else if (isa<NullNode>(node)) { return std::make_unique<EmptyHNode>(node); } else { setError(node, "unknown node kind"); return nullptr; } } void Input::setError(const Twine &Message) { setError(m_currentNode, Message); } bool Input::canElideEmptySequence() { return false; } //===----------------------------------------------------------------------===// // Output //===----------------------------------------------------------------------===// Output::Output(RawOutStream &out, void *context, int wrapColumn) : IO(context), m_out(out), m_wrapColumn(wrapColumn) {} Output::~Output() {} bool Output::outputting() { return true; } void Output::beginMapping() { m_stateStack.push_back(inMapFirstKey); m_needsNewLine = true; } bool Output::mapTag(StringRef tag, bool use) { if (use) { // If this tag is being written inside a sequence we should write the start // of the sequence before writing the tag, otherwise the tag won't be // attached to the element in the sequence, but rather the sequence itself. bool sequenceElement = false; if (m_stateStack.size() > 1) { auto &E = m_stateStack[m_stateStack.size() - 2]; sequenceElement = inSeqAnyElement(E) || inFlowSeqAnyElement(E); } if (sequenceElement && m_stateStack.back() == inMapFirstKey) { newLineCheck(); } else { output(" "); } output(tag); if (sequenceElement) { // If we're writing the tag during the first element of a map, the tag // takes the place of the first element in the sequence. if (m_stateStack.back() == inMapFirstKey) { m_stateStack.pop_back(); m_stateStack.push_back(inMapOtherKey); } // Tags inside maps in sequences should act as keys in the map from a // formatting perspective, so we always want a newline in a sequence. m_needsNewLine = true; } } return use; } void Output::endMapping() { // If we did not map anything, we should explicitly emit an empty map if (m_stateStack.back() == inMapFirstKey) { output("{}"); } m_stateStack.pop_back(); } std::vector<StringRef> Output::getKeys() { report_fatal_error("invalid call"); } bool Output::preflightKey(const char *key, bool required, bool sameAsDefault, bool &useDefault, void *&) { useDefault = false; if (required || !sameAsDefault || m_writeDefaultValues) { auto state = m_stateStack.getBack(); if (state == inFlowMapFirstKey || state == inFlowMapOtherKey) { flowKey(key); } else { newLineCheck(); paddedKey(key); } return true; } return false; } void Output::postflightKey(void *) { if (m_stateStack.getBack() == inMapFirstKey) { m_stateStack.pop_back(); m_stateStack.push_back(inMapOtherKey); } else if (m_stateStack.getBack() == inFlowMapFirstKey) { m_stateStack.pop_back(); m_stateStack.push_back(inFlowMapOtherKey); } } void Output::beginFlowMapping() { m_stateStack.push_back(inFlowMapFirstKey); newLineCheck(); m_columnAtMapFlowStart = m_column; output("{ "); } void Output::endFlowMapping() { m_stateStack.pop_back(); outputUpToEndOfLine(" }"); } void Output::beginDocuments() { outputUpToEndOfLine("---"); } bool Output::preflightDocument(size_t index) { if (index > 0) { outputUpToEndOfLine("\n---"); } return true; } void Output::postflightDocument() { } void Output::endDocuments() { output("\n...\n"); } size_t Output::beginSequence() { m_stateStack.push_back(inSeqFirstElement); m_needsNewLine = true; return 0; } void Output::endSequence() { // If we did not emit anything, we should explicitly emit an empty sequence if (m_stateStack.back() == inSeqFirstElement) { output("[]"); } m_stateStack.pop_back(); } bool Output::preflightElement(unsigned, void *&) { return true; } void Output::postflightElement(void *) { if (m_stateStack.back() == inSeqFirstElement) { m_stateStack.pop_back(); m_stateStack.push_back(inSeqOtherElement); } else if (m_stateStack.back() == inFlowSeqFirstElement) { m_stateStack.pop_back(); m_stateStack.push_back(inFlowSeqOtherElement); } } size_t Output::beginFlowSequence() { m_stateStack.push_back(inFlowSeqFirstElement); newLineCheck(); m_columnAtFlowStart = m_column; output("[ "); m_needFlowSequenceComma = false; return 0; } void Output::endFlowSequence() { m_stateStack.pop_back(); outputUpToEndOfLine(" ]"); } bool Output::preflightFlowElement(unsigned, void *&) { if (m_needFlowSequenceComma) { output(", "); } if (m_wrapColumn && m_column > m_wrapColumn) { output("\n"); for (int i = 0; i < m_columnAtFlowStart; ++i) { output(" "); } m_column = m_columnAtFlowStart; output(" "); } return true; } void Output::postflightFlowElement(void *) { m_needFlowSequenceComma = true; } void Output::beginEnumScalar() { m_enumerationMatchFound = false; } bool Output::matchEnumScalar(const char *str, bool match) { if (match && !m_enumerationMatchFound) { newLineCheck(); outputUpToEndOfLine(str); m_enumerationMatchFound = true; } return false; } bool Output::matchEnumFallback() { if (m_enumerationMatchFound) { return false; } m_enumerationMatchFound = true; return true; } void Output::endEnumScalar() { if (!m_enumerationMatchFound) { polar_unreachable("bad runtime enum value"); } } bool Output::beginBitSetScalar(bool &doClear) { newLineCheck(); output("[ "); m_needBitValueComma = false; doClear = false; return true; } bool Output::bitSetMatch(const char *str, bool matches) { if (matches) { if (m_needBitValueComma) { output(", "); } output(str); m_needBitValueComma = true; } return false; } void Output::endBitSetScalar() { outputUpToEndOfLine(" ]"); } void Output::scalarString(StringRef &str, QuotingType mustQuote) { newLineCheck(); if (str.empty()) { // Print '' for the empty string because leaving the field empty is not // allowed. outputUpToEndOfLine("''"); return; } if (mustQuote == QuotingType::None) { // Only quote if we must. outputUpToEndOfLine(str); return; } unsigned i = 0; unsigned j = 0; size_t endMark = str.getSize(); const char *base = str.getData(); const char *const quote = mustQuote == QuotingType::Single ? "'" : "\""; output(quote); // Starting quote. // When using double-quoted strings (and only in that case), non-printable characters may be // present, and will be escaped using a variety of unicode-scalar and special short-form // escapes. This is handled in yaml::escape. if (mustQuote == QuotingType::Double) { output(yaml::escape(base, /* EscapePrintable= */ false)); outputUpToEndOfLine(quote); return; } // When using single-quoted strings, any single quote ' must be doubled to be escaped. while (j < endMark) { if (str[j] == '\'') { // Escape quotes. output(StringRef(&base[i], j - i)); // "flush". output(StringLiteral("''")); // Print it as '' i = j + 1; } ++j; } output(StringRef(&base[i], j - i)); outputUpToEndOfLine(quote); // Ending quote. } void Output::blockScalarString(StringRef &str) { if (!m_stateStack.empty()) { newLineCheck(); } output(" |"); outputNewLine(); size_t indent = m_stateStack.empty() ? 1 : m_stateStack.getSize(); auto buffer = MemoryBuffer::getMemBuffer(str, "", false); for (LineIterator lines(*buffer, false); !lines.isAtEnd(); ++lines) { for (unsigned index = 0; index < indent; ++index) { output(" "); } output(*lines); outputNewLine(); } } void Output::scalarTag(std::string &tag) { if (tag.empty()) { return; } newLineCheck(); output(tag); output(" "); } void Output::setError(const Twine &) { } bool Output::canElideEmptySequence() { // Normally, with an optional key/value where the value is an empty sequence, // the whole key/value can be not written. But, that produces wrong yaml // if the key/value is the only thing in the map and the map is used in // a sequence. This detects if the this sequence is the first key/value // in map that itself is embedded in a sequnce. if (m_stateStack.getSize() < 2) { return true; } if (m_stateStack.getBack() != inMapFirstKey) { return true; } return !inSeqAnyElement(m_stateStack[m_stateStack.size() - 2]); } void Output::output(StringRef str) { m_column += str.getSize(); m_out << str; } void Output::outputUpToEndOfLine(StringRef str) { output(str); if (m_stateStack.empty() || (!inFlowSeqAnyElement(m_stateStack.back()) && !inFlowMapAnyKey(m_stateStack.back()))){ m_needsNewLine = true; } } void Output::outputNewLine() { m_out << "\n"; m_column = 0; } // if seq at top, indent as if map, then add "- " // if seq in middle, use "- " if firstKey, else use " " // void Output::newLineCheck() { if (!m_needsNewLine) { return; } m_needsNewLine = false; outputNewLine(); if (m_stateStack.size() == 0) { return; } size_t indent = m_stateStack.size() - 1; bool outputDash = false; if (m_stateStack.back() == inSeqFirstElement || m_stateStack.back() == inSeqOtherElement) { outputDash = true; } else if ((m_stateStack.size() > 1) && ((m_stateStack.back() == inMapFirstKey) || inFlowSeqAnyElement(m_stateStack.back()) || (m_stateStack.back() == inFlowMapFirstKey)) && inSeqAnyElement(m_stateStack[m_stateStack.size() - 2])) { --indent; outputDash = true; } for (unsigned i = 0; i < indent; ++i) { output(" "); } if (outputDash) { output("- "); } } void Output::paddedKey(StringRef key) { output(key); output(":"); const char *spaces = " "; if (key.getSize() < strlen(spaces)) { output(&spaces[key.getSize()]); } else { output(" "); } } void Output::flowKey(StringRef key) { if (m_stateStack.getBack() == inFlowMapOtherKey) { output(", "); } if (m_wrapColumn && m_column > m_wrapColumn) { output("\n"); for (int index = 0; index < m_columnAtMapFlowStart; ++index) { output(" "); } m_column = m_columnAtMapFlowStart; output(" "); } output(key); output(": "); } NodeKind Output::getNodeKind() { report_fatal_error("invalid call"); } bool Output::inSeqAnyElement(InState state) { return state == inSeqFirstElement || state == inSeqOtherElement; } bool Output::inFlowSeqAnyElement(InState state) { return state == inFlowSeqFirstElement || state == inFlowSeqOtherElement; } bool Output::inMapAnyKey(InState state) { return state == inMapFirstKey || state == inMapOtherKey; } bool Output::inFlowMapAnyKey(InState state) { return state == inFlowMapFirstKey || state == inFlowMapOtherKey; } //===----------------------------------------------------------------------===// // traits for built-in types //===----------------------------------------------------------------------===// void ScalarTraits<bool>::output(const bool &value, void *, RawOutStream &out) { out << (value ? "true" : "false"); } StringRef ScalarTraits<bool>::input(StringRef scalar, void *, bool &value) { if (scalar.equals("true")) { value = true; return StringRef(); } else if (scalar.equals("false")) { value = false; return StringRef(); } return "invalid boolean"; } void ScalarTraits<StringRef>::output(const StringRef &value, void *, RawOutStream &out) { out << value; } StringRef ScalarTraits<StringRef>::input(StringRef scalar, void *, StringRef &value) { value = scalar; return StringRef(); } void ScalarTraits<std::string>::output(const std::string &value, void *, RawOutStream &out) { out << value; } StringRef ScalarTraits<std::string>::input(StringRef scalar, void *, std::string &value) { value = scalar.getStr(); return StringRef(); } void ScalarTraits<uint8_t>::output(const uint8_t &value, void *, RawOutStream &out) { // use temp uin32_t because ostream thinks uint8_t is a character uint32_t num = value; out << num; } StringRef ScalarTraits<uint8_t>::input(StringRef scalar, void *, uint8_t &value) { unsigned long long n; if (get_as_unsigned_integer(scalar, 0, n)) { return "invalid number"; } if (n > 0xFF) { return "out of range number"; } value = static_cast<uint8_t>(n); return StringRef(); } void ScalarTraits<uint16_t>::output(const uint16_t &value, void *, RawOutStream &out) { out << value; } StringRef ScalarTraits<uint16_t>::input(StringRef scalar, void *, uint16_t &value) { unsigned long long n; if (get_as_unsigned_integer(scalar, 0, n)) { return "invalid number"; } if (n > 0xFFFF) { return "out of range number"; } value = static_cast<uint16_t>(n); return StringRef(); } void ScalarTraits<uint32_t>::output(const uint32_t &value, void *, RawOutStream &out) { out << value; } StringRef ScalarTraits<uint32_t>::input(StringRef scalar, void *, uint32_t &value) { unsigned long long n; if (get_as_unsigned_integer(scalar, 0, n)) { return "invalid number"; } if (n > 0xFFFFFFFFUL) { return "out of range number"; } value = static_cast<uint32_t>(n); return StringRef(); } void ScalarTraits<uint64_t>::output(const uint64_t &value, void *, RawOutStream &out) { out << value; } StringRef ScalarTraits<uint64_t>::input(StringRef scalar, void *, uint64_t &value) { unsigned long long node; if (get_as_unsigned_integer(scalar, 0, node)) { return "invalid number"; } value = node; return StringRef(); } void ScalarTraits<int8_t>::output(const int8_t &value, void *, RawOutStream &out) { // use temp in32_t because ostream thinks int8_t is a character int32_t num = value; out << num; } StringRef ScalarTraits<int8_t>::input(StringRef scalar, void *, int8_t &value) { long long node; if (get_as_signed_integer(scalar, 0, node)) { return "invalid number"; } if ((node > 127) || (node < -128)) { return "out of range number"; } value = static_cast<int8_t>(node); return StringRef(); } void ScalarTraits<int16_t>::output(const int16_t &value, void *, RawOutStream &out) { out << value; } StringRef ScalarTraits<int16_t>::input(StringRef scalar, void *, int16_t &value) { long long node; if (get_as_signed_integer(scalar, 0, node)) { return "invalid number"; } if ((node > INT16_MAX) || (node < INT16_MIN)) { return "out of range number"; } value = static_cast<int16_t>(node); return StringRef(); } void ScalarTraits<int32_t>::output(const int32_t &value, void *, RawOutStream &out) { out << value; } StringRef ScalarTraits<int32_t>::input(StringRef scalar, void *, int32_t &value) { long long node; if (get_as_signed_integer(scalar, 0, node)) { return "invalid number"; } if ((node > INT32_MAX) || (node < INT32_MIN)) { return "out of range number"; } value = static_cast<int32_t>(node); return StringRef(); } void ScalarTraits<int64_t>::output(const int64_t &value, void *, RawOutStream &out) { out << value; } StringRef ScalarTraits<int64_t>::input(StringRef scalar, void *, int64_t &value) { long long node; if (get_as_signed_integer(scalar, 0, node)) { return "invalid number"; } value = node; return StringRef(); } void ScalarTraits<double>::output(const double &value, void *, RawOutStream &out) { out << format("%g", value); } StringRef ScalarTraits<double>::input(StringRef scalar, void *, double &value) { if (to_float(scalar, value)) { return StringRef(); } return "invalid floating point number"; } void ScalarTraits<float>::output(const float &value, void *, RawOutStream &out) { out << format("%g", value); } StringRef ScalarTraits<float>::input(StringRef scalar, void *, float &value) { if (to_float(scalar, value)) { return StringRef(); } return "invalid floating point number"; } void ScalarTraits<Hex8>::output(const Hex8 &value, void *, RawOutStream &out) { uint8_t num = value; out << format("0x%02X", num); } StringRef ScalarTraits<Hex8>::input(StringRef scalar, void *, Hex8 &value) { unsigned long long n; if (get_as_unsigned_integer(scalar, 0, n)){ return "invalid hex8 number"; } if (n > 0xFF) { return "out of range hex8 number"; } value = static_cast<Hex8>(n); return StringRef(); } void ScalarTraits<Hex16>::output(const Hex16 &value, void *, RawOutStream &out) { uint16_t num = value; out << format("0x%04X", num); } StringRef ScalarTraits<Hex16>::input(StringRef scalar, void *, Hex16 &value) { unsigned long long n; if (get_as_unsigned_integer(scalar, 0, n)) { return "invalid hex16 number"; } if (n > 0xFFFF) { return "out of range hex16 number"; } value = static_cast<Hex16>(n); return StringRef(); } void ScalarTraits<Hex32>::output(const Hex32 &value, void *, RawOutStream &out) { uint32_t num = value; out << format("0x%08X", num); } StringRef ScalarTraits<Hex32>::input(StringRef scalar, void *, Hex32 &value) { unsigned long long n; if (get_as_unsigned_integer(scalar, 0, n)) { return "invalid hex32 number"; } if (n > 0xFFFFFFFFUL) { return "out of range hex32 number"; } value = static_cast<Hex32>(n); return StringRef(); } void ScalarTraits<Hex64>::output(const Hex64 &value, void *, RawOutStream &out) { uint64_t num = value; out << format("0x%016llX", num); } StringRef ScalarTraits<Hex64>::input(StringRef scalar, void *, Hex64 &value) { unsigned long long num; if (get_as_unsigned_integer(scalar, 0, num)) { return "invalid hex64 number"; } value = num; return StringRef(); } } // yaml } // polar
24.731745
95
0.620307
[ "vector" ]
61a6e31aaf236a1ad33e3f1a7d9df4848522aecc
24,934
cpp
C++
Src/Orbiter/Vesselstatus.cpp
jarmonik/orbiter
527db6209cb0acd4af839682f2d7f05132818fb8
[ "MIT" ]
1,040
2021-07-27T12:12:06.000Z
2021-08-02T14:24:49.000Z
Src/Orbiter/Vesselstatus.cpp
jarmonik/orbiter
527db6209cb0acd4af839682f2d7f05132818fb8
[ "MIT" ]
20
2021-07-27T12:25:22.000Z
2021-08-02T12:22:19.000Z
Src/Orbiter/Vesselstatus.cpp
jarmonik/orbiter
527db6209cb0acd4af839682f2d7f05132818fb8
[ "MIT" ]
71
2021-07-27T14:19:49.000Z
2021-08-02T05:51:52.000Z
// Copyright (c) Martin Schweiger // Licensed under the MIT License // ============================================================== // Contains the portion of the Vessel class definition // concerned with VESSELCLASS interfaces // ============================================================== #include "Orbiter.h" #include "Vessel.h" #include "Supervessel.h" #include "VVessel.h" #include "Config.h" #include "Pane.h" #include "Element.h" #include "Psys.h" #include "Base.h" #include "Util.h" #include "Log.h" #include <fstream> #include <iomanip> #include <stdio.h> #include <stdlib.h> extern Orbiter *g_pOrbiter; extern TimeData td; extern PlanetarySystem *g_psys; extern char DBG_MSG[256]; // ============================================================== // ParseScenarioLineX versions // ============================================================== // ============================================================== // Read a line from a scenario file into a VESSELSTATUS interface bool Vessel::ParseScenarioLine (char *line, VESSELSTATUS &vs) { char cbuf[256], *pd, c; DWORD n; double lvl; if (!_strnicmp (line, "STATUS", 6)) { line = trim_string (line+6); if (!_strnicmp (line, "LANDED", 6)) { vs.rbody = (OBJHANDLE)g_psys->GetGravObj (trim_string (line+6)); vs.status = 1; vs.vdata[0].z = 0.0f; // default when landed } else if (!_strnicmp (line, "ORBITING", 8)) { vs.rbody = (OBJHANDLE)g_psys->GetGravObj (trim_string (line+8)); vs.status = 0; } } else if (!_strnicmp (line, "BASE", 4)) { line = trim_string (line+4); if (pd = strtok (line, ":")) { strcpy (cbuf, pd); // at this point we assume that vs.rbody has already been assigned, // i.e. that the STATUS LANDED line has already been parsed Base *base = ((Planet*)vs.rbody)->GetBase (trim_string(cbuf)); vs.base = (OBJHANDLE)base; if (pd = strtok (NULL, ":")) { sscanf (pd, "%d", &vs.port); vs.port--; base->Pad_EquPos (vs.port, vs.vdata[0].x, vs.vdata[0].y); // place ship in centre of landing pad by default } } } else if (!_strnicmp (line, "POS", 3)) { sscanf (line+3, "%lf%lf", &vs.vdata[0].x, &vs.vdata[0].y); vs.vdata[0].x *= RAD; vs.vdata[0].y *= RAD; } else if (!_strnicmp (line, "HEADING", 7)) { sscanf (line+7, "%lf", &vs.vdata[0].z); vs.vdata[0].z *= RAD; } else if (!_strnicmp (line, "RPOS", 4)) { sscanf (line+4, "%lf%lf%lf", &vs.rpos.x, &vs.rpos.y, &vs.rpos.z); } else if (!_strnicmp (line, "RVEL", 4)) { sscanf (line+4, "%lf%lf%lf", &vs.rvel.x, &vs.rvel.y, &vs.rvel.z); } else if (!_strnicmp (line, "ELEMENTS", 8)) { double a, e, i, theta, omegab, L, elmjd; Vector rpos, rvel; sscanf (line+8, "%lf%lf%lf%lf%lf%lf%lf", &a, &e, &i, &theta, &omegab, &L, &elmjd); if (vs.rbody) { el->Set (a, e, i*RAD, theta*RAD, omegab*RAD, L*RAD, elmjd); el->Setup (mass, ((Body*)vs.rbody)->Mass(), td.MJD_ref); el->Update (rpos, rvel); vs.rpos.x = rpos.x, vs.rpos.y = rpos.y, vs.rpos.z = rpos.z; vs.rvel.x = rvel.x, vs.rvel.y = rvel.y, vs.rvel.z = rvel.z; el_valid = true; } } else if (!_strnicmp (line, "AROT", 4)) { sscanf (line+4, "%lf%lf%lf", &vs.arot.x, &vs.arot.y, &vs.arot.z); vs.arot.x *= RAD, vs.arot.y *= RAD, vs.arot.z *= RAD; } else if (!_strnicmp (line, "VROT", 4)) { sscanf (line+4, "%lf%lf%lf", &vs.vrot.x, &vs.vrot.y, &vs.vrot.z); vs.vrot.x *= RAD, vs.vrot.y *= RAD, vs.vrot.z *= RAD; } else if (!_strnicmp (line, "FUEL", 4)) { // old style propellant interface sscanf (line+4, "%lf", &vs.fuel); } else if (!_strnicmp (line, "PRPLEVEL", 8)) { // new style propellant interface for (pd = strtok (line+8, " "); pd; pd = strtok (NULL, " ")) if (sscanf (pd, "%d%c%lf", &n, &c, &lvl) == 3) if (n < ntank && tank[n] == def_tank) vs.fuel = lvl; } else if (!_strnicmp (line, "THLEVEL", 7)) { for (pd = strtok (line+7, " "); pd; pd = strtok (NULL, " ")) { if (sscanf (pd, "%d%c%lf", &n, &c, &lvl) == 3 && n < nthruster) { thruster[n]->level = thruster[n]->level_permanent = lvl; thruster[n]->level_override = 0.0; } } } else if (!_strnicmp (line, "IDS", 3)) { DWORD step, irange, m, i; for (pd = strtok (line+3, " "), n = 0; n < ndock && pd; pd = strtok (NULL, " ")) { if ((m = sscanf (pd, "%d%c%d%c%d", &i, &c, &step, &c, &irange)) >= 3 && i < ndock) { if (m < 5) irange = 20; SetDockIDS (dock[i], (float)(step*0.05 + NAV_RADIO_FREQ_MIN), (float)(irange*1e3)); } } } else if (!_strnicmp (line, "NAVFREQ", 7)) { DWORD step; for (pd = strtok (line+7, " "), n = 0; n < nnav && pd; pd = strtok (NULL, " ")) if (sscanf (pd, "%d", &step) == 1) { nav[n].freq = (float)((nav[n].step = step)*0.05 + NAV_RADIO_FREQ_MIN); n++; } } else return ParseScenarioLineDirect (line); return true; } // ============================================================== // Read a line from a scenario file into a VESSELSTATUS2 interface bool Vessel::ParseScenarioLine2 (char *line, void *status) { char cbuf[256], *pd, c; DWORD nn, n; double lvl; VESSELSTATUS2 *vs = (VESSELSTATUS2*)status; if (!_strnicmp (line, "STATUS", 6)) { line = trim_string (line+6); if (!_strnicmp (line, "LANDED", 6)) { vs->rbody = (OBJHANDLE)g_psys->GetGravObj (trim_string (line+6)); vs->surf_hdg = 0.0; // default when landed vs->status = 1; vs->arot.x = 10; // flag for 'not set' } else if (!_strnicmp (line, "ORBITING", 8)) { vs->rbody = (OBJHANDLE)g_psys->GetGravObj (trim_string (line+8)); vs->status = 0; #ifdef UNDEF } else if (!strnicmp (line, "DOCKED", 6)) { line = trim_string (line+6); if (pd = strtok (line, ":")) { strcpy (cbuf, pd); vs->rbody = (OBJHANDLE)g_psys->GetGravObj (trim_string (cbuf)); if (pd = strtok (NULL, ":")) { strcpy (cbuf, pd); vs->base = (OBJHANDLE)g_psys->GetStation (trim_string (cbuf)); if (pd = strtok (NULL, ":")) { sscanf (pd, "%d", &vs->port); vs->status = 3; } } } #endif } } else if (!_strnicmp (line, "BASE", 4)) { line = trim_string (line+4); if (pd = strtok (line, ":")) { strcpy (cbuf, pd); // at this point we assume that vs.rbody has already been assigned, // i.e. that the STATUS LANDED line has already been parsed Base *base = ((Planet*)vs->rbody)->GetBase (trim_string(cbuf)); if (!base) { char cerr[1024]; sprintf (cerr, "Scenario parse error for vessel %s: base '%s' not found on body '%s'.", name, trim_string(cbuf), ((Planet*)vs->rbody)->Name()); LOGOUT_ERR(cerr); g_pOrbiter->TerminateOnError(); } vs->base = (OBJHANDLE)base; if (pd = strtok (NULL, ":")) { sscanf (pd, "%d", &vs->port); vs->port--; base->Pad_EquPos (vs->port, vs->surf_lng, vs->surf_lat); // place ship in centre of landing pad by default } } } else if (!_strnicmp (line, "POS", 3)) { sscanf (line+3, "%lf%lf", &vs->surf_lng, &vs->surf_lat); vs->surf_lng *= RAD; vs->surf_lat *= RAD; } else if (!_strnicmp (line, "HEADING", 7)) { sscanf (line+7, "%lf", &vs->surf_hdg); vs->surf_hdg *= RAD; } else if (!_strnicmp (line, "PRPLEVEL", 8)) { // propellant status if (vs->nfuel) delete []vs->fuel; // pass 1: find out how many propellant definitions there are for (nn = 0, pd = line+8; *pd; pd++) { if (*pd == ':') nn++; } vs->nfuel = nn; vs->fuel = new VESSELSTATUS2::FUELSPEC[nn]; TRACENEW // pass 2: read propellant definitions for (nn = 0, pd = strtok (line+8, " "); pd; pd = strtok (NULL, " ")) if (sscanf (pd, "%d%c%lf", &n, &c, &lvl) == 3) { vs->fuel[nn].idx = n; vs->fuel[nn].level = lvl; nn++; } } else if (!_strnicmp (line, "FUEL", 4)) { // global propellant resource setting if (sscanf (line+4, "%lf", &lvl)) { // old style fuel definition if (vs->nfuel) delete []vs->fuel; vs->fuel = new VESSELSTATUS2::FUELSPEC[vs->nfuel = 1]; TRACENEW vs->fuel[0].idx = (DWORD)-1; // mark 'global' vs->fuel[0].level = lvl; } } else if (!_strnicmp (line, "THLEVEL", 7)) { // read thruster status if (vs->nthruster) delete []vs->thruster; // pass 1: find out how many thruster defintions there are for (nn = 0, pd = line+7; *pd; pd++) if (*pd == ':') nn++; vs->nthruster = nn; vs->thruster = new VESSELSTATUS2::THRUSTSPEC[nn]; TRACENEW // pass 2: read thruster definitions for (nn = 0, pd = strtok (line+7, " "); pd; pd = strtok (NULL, " ")) if (sscanf (pd, "%d%c%lf", &n, &c, &lvl) == 3) { vs->thruster[nn].idx = n; vs->thruster[nn].level = lvl; nn++; } } else if (!_strnicmp (line, "ENGINE_MAIN", 11)) { // old style main/retro thruster status if (sscanf (line+11, "%lf", &lvl)) { if (lvl > 0) { for (n = 0; n < thruster_grp_default[THGROUP_MAIN].nts; n++) { ThrustSpec *ts = thruster_grp_default[THGROUP_MAIN].ts[n]; for (nn = 0; nn < nthruster; nn++) { if (thruster[nn] == ts) { VESSELSTATUS2::THRUSTSPEC *tmp = new VESSELSTATUS2::THRUSTSPEC[vs->nthruster+1]; TRACENEW if (vs->nthruster) { memcpy (tmp, vs->thruster, vs->nthruster*sizeof (VESSELSTATUS2::THRUSTSPEC)); delete []vs->thruster; } tmp[vs->nthruster].idx = nn; tmp[vs->nthruster].level = lvl; vs->thruster = tmp; vs->nthruster++; } } } } else if (lvl < 0) { for (n = 0; n < thruster_grp_default[THGROUP_RETRO].nts; n++) { ThrustSpec *ts = thruster_grp_default[THGROUP_RETRO].ts[n]; for (nn = 0; nn < nthruster; nn++) { if (thruster[nn] == ts) { VESSELSTATUS2::THRUSTSPEC *tmp = new VESSELSTATUS2::THRUSTSPEC[vs->nthruster+1]; TRACENEW if (vs->nthruster) { memcpy (tmp, vs->thruster, vs->nthruster*sizeof (VESSELSTATUS2::THRUSTSPEC)); delete []vs->thruster; } tmp[vs->nthruster].idx = nn; tmp[vs->nthruster].level = -lvl; vs->thruster = tmp; vs->nthruster++; } } } } } } else if (!_strnicmp (line, "ENGINE_HOVR", 11)) { // old style hover thruster status if (sscanf (line+11, "%lf", &lvl) && lvl > 0) { for (n = 0; n < thruster_grp_default[THGROUP_HOVER].nts; n++) { ThrustSpec *ts = thruster_grp_default[THGROUP_HOVER].ts[n]; for (nn = 0; nn < nthruster; nn++) { if (thruster[nn] == ts) { VESSELSTATUS2::THRUSTSPEC *tmp = new VESSELSTATUS2::THRUSTSPEC[vs->nthruster+1]; TRACENEW if (vs->nthruster) { memcpy (tmp, vs->thruster, vs->nthruster*sizeof (VESSELSTATUS2::THRUSTSPEC)); delete []vs->thruster; } tmp[vs->nthruster].idx = nn; tmp[vs->nthruster].level = lvl; vs->thruster = tmp; vs->nthruster++; } } } } } else if (!_strnicmp (line, "DOCKINFO", 8)) { if (vs->ndockinfo) delete []vs->dockinfo; // pass 1: find number of dock info records for (nn = 0, pd = line+8; *pd; pd++) if (*pd == ':') nn++; vs->ndockinfo = nn; vs->dockinfo = new VESSELSTATUS2::DOCKINFOSPEC[nn]; TRACENEW // pass 2: read dock info records for (nn = 0, pd = strtok (line+8, " "); pd; pd = strtok (NULL, " ")) { sscanf (pd, "%d:%d,%s", &vs->dockinfo[nn].idx, &vs->dockinfo[nn].ridx, cbuf); // DODGY - cast name into 4 bytes of vessel pointer! vs->dockinfo[nn].rvessel = 0; BYTE *tmp = (BYTE*)&vs->dockinfo[nn].rvessel; for (int i = 0; cbuf[i]; i++) tmp[i%4] += cbuf[i]; nn++; } } else if (!_strnicmp (line, "RPOS", 4)) { sscanf (line+4, "%lf%lf%lf", &vs->rpos.x, &vs->rpos.y, &vs->rpos.z); } else if (!_strnicmp (line, "RVEL", 4)) { sscanf (line+4, "%lf%lf%lf", &vs->rvel.x, &vs->rvel.y, &vs->rvel.z); } else if (!_strnicmp (line, "AROT", 4)) { sscanf (line+4, "%lf%lf%lf", &vs->arot.x, &vs->arot.y, &vs->arot.z); vs->arot.x *= RAD, vs->arot.y *= RAD, vs->arot.z *= RAD; } else if (!_strnicmp (line, "VROT", 4)) { sscanf (line+4, "%lf%lf%lf", &vs->vrot.x, &vs->vrot.y, &vs->vrot.z); vs->vrot.x *= RAD, vs->vrot.y *= RAD, vs->vrot.z *= RAD; } else if (!_strnicmp (line, "ALT", 3)) { // NOTE: 'ALT' and 'VROT' cannot be used together. ALT is used for landed vessels sscanf (line+3, "%lf", &vs->vrot.x); } else if (!_strnicmp (line, "ELEMENTS", 8)) { double a, e, i, theta, omegab, L, elmjd; Vector rpos, rvel; sscanf (line+8, "%lf%lf%lf%lf%lf%lf%lf", &a, &e, &i, &theta, &omegab, &L, &elmjd); if (vs->rbody) { el->Set (a, e, i*RAD, theta*RAD, omegab*RAD, L*RAD, elmjd); el->Setup (mass, ((Body*)vs->rbody)->Mass(), td.MJD_ref); el->Update (rpos, rvel); vs->rpos.x = rpos.x, vs->rpos.y = rpos.y, vs->rpos.z = rpos.z; vs->rvel.x = rvel.x, vs->rvel.y = rvel.y, vs->rvel.z = rvel.z; el_valid = true; } } else if (!_strnicmp (line, "IDS", 3)) { DWORD step, irange, m, i, n = 0; char c; for (pd = strtok (line+3, " "); n < ndock && pd; pd = strtok (NULL, " ")) { if ((m = sscanf (pd, "%d%c%d%c%d", &i, &c, &step, &c, &irange)) >= 3 && i < ndock) { if (m < 5) irange = 20; SetDockIDS (dock[i], (float)(step*0.05 + NAV_RADIO_FREQ_MIN), (float)(irange*1e3)); } } } else if (!_strnicmp (line, "NAVFREQ", 7)) { DWORD step, n = 0; for (pd = strtok (line+7, " "); n < nnav && pd; pd = strtok (NULL, " ")) if (sscanf (pd, "%d", &step) == 1) { nav[n].freq = (float)((nav[n].step = step)*0.05 + NAV_RADIO_FREQ_MIN); n++; } } else if (!_strnicmp (line, "XPDR", 4)) { sscanf (line+4, "%d", &vs->xpdr); } else return ParseScenarioLineDirect (line); return true; } // ============================================================== // The following options are read directly from the scenario file, // bypassing the VESSELSTATUSx structure. They should be collected // into an extended VESSELSTATUSx (3?) structure. // ============================================================== bool Vessel::ParseScenarioLineDirect (char *line) { if (!_strnicmp (line, "RCSMODE", 7)) { sscanf (line+7, "%d", &attmode); return true; } else if (!_strnicmp (line, "AFCMODE", 7)) { sscanf (line+7, "%d", &ctrlsurfmode); return true; } else if (!_strnicmp (line, "ATTACHED", 8)) { char cbuf[256]; sscanf (line+8, "%d:%d,%s", &attach_status.ci, &attach_status.pi, cbuf); if (attach_status.pname) delete []attach_status.pname; attach_status.pname = new char[strlen(cbuf)+1]; TRACENEW strcpy (attach_status.pname, cbuf); return true; } else if (!_strnicmp (line, "FLIGHTDATA", 10)) { bRequestPlayback = true; } return false; } DWORD Vessel::PackDefaultState (char **data, DWORD flag) { DWORD size = sizeof(ScenarioData)-sizeof(char*); const char *cname = (fstatus == FLIGHTSTATUS_FREEFLIGHT ? cbody->Name() : proxyplanet->Name()); size += strlen(cname)+1; if (flag & SD_NAME) { size += strlen(name)+1; size += (classname ? strlen(classname)+1 : 1); } *data = new char[size]; ScenarioData *sd = (ScenarioData*)*data; TRACENEW sd->size = size; sd->flag = flag; sd->fstate = (BYTE)fstatus; switch (fstatus) { case FLIGHTSTATUS_FREEFLIGHT: sd->rpos = cpos; sd->rvel = cvel; EulerAngles (s0->R, sd->arot); sd->vrot = s0->omega; break; case FLIGHTSTATUS_LANDED: sd->lng = sp.lng; sd->lat = sp.lat; sd->hdg = sp.dir; break; } strcpy (sd->buf, cname); if (flag & SD_NAME) sprintf (sd->buf + strlen(sd->buf), "\n%s\n%s", name, classname ? classname:""); return size; } void Vessel::ApplyPackedState (const char *data) { char *pc; ScenarioData *sd = (ScenarioData*)data; pc = strtok (sd->buf, "\n"); cbody = g_psys->GetGravObj (pc); if (!cbody) cbody = g_psys->GetStar(0); // a rather desparate default to keep things going el->Setup (mass, cbody->Mass(), td.MJD_ref); switch (sd->fstate) { case 0: // freeflight InitOrbiting (sd->rpos, sd->rvel, sd->arot, &sd->vrot); break; case 1: // landed InitLanded ((Planet*)cbody, sd->lng, sd->lat, sd->hdg); if (proxybase) proxybase->ReportTouchdown (this, sd->lng, sd->lat); break; } } // ============================================================== // SetStateX versions // ============================================================== // ============================================================== // Set a vessel state from a VESSELSTATUS interface void Vessel::SetState (const VESSELSTATUS &status) { double lng, lat, dir; Vector rpos, rvel, orient, vrot; cbody = (CelestialBody*)status.rbody; if (!cbody) cbody = g_psys->GetStar(0); // use first sun if no reference is set if (!cbody) return; // big trouble! if (status.flag[0] & 2 && def_tank) { // status currently only supports default propellant resource SetPropellantMass (def_tank, status.fuel*def_tank->maxmass); } UpdateMass(); pfmass = fmass; el->Setup (mass, cbody->Mass(), td.MJD_ref); if (status.flag[0] & 1) { // old-style thruster definition if (status.eng_main >= 0.0) { SetThrusterGroupLevel (THGROUP_MAIN, status.eng_main); SetThrusterGroupLevel (THGROUP_RETRO, 0.0); } else { SetThrusterGroupLevel (THGROUP_MAIN, 0.0); SetThrusterGroupLevel (THGROUP_RETRO, -status.eng_main); } SetThrusterGroupLevel (THGROUP_HOVER, status.eng_hovr); } switch (status.status) { case 0: // freeflight rpos.Set (status.rpos.x, status.rpos.y, status.rpos.z); rvel.Set (status.rvel.x, status.rvel.y, status.rvel.z); orient.Set (status.arot.x, status.arot.y, status.arot.z); vrot.Set (status.vrot.x, status.vrot.y, status.vrot.z); if (rpos.length() < cbody->Size()) { // sanity check rpos.x = rpos.y = 0.0; rpos.z = 1.1*cbody->Size(); // desparate default } InitOrbiting (rpos, rvel, orient, &vrot); break; case 1: // landed lng = status.vdata[0].x, lat = status.vdata[0].y, dir = status.vdata[0].z; if (status.base) { landtgt = (Base*)status.base; nport = landtgt->OccupyPad (this, status.port, true); lstatus = 1; //landtgt->Pad_EquPos (nport, lng, lat); proxybase = landtgt; } InitLanded ((Planet*)cbody, lng, lat, dir); break; default: break; } } // ============================================================== // Set a vessel state from a VESSELSTATUS2 interface void Vessel::SetState2 (const void *status) { VESSELSTATUS2 *vs = (VESSELSTATUS2*)status; DWORD i, idx; double lvl; cbody = (CelestialBody*)vs->rbody; if (!cbody) cbody = g_psys->GetStar(0); // a rather desparate default to keep things going // should we call SetDefaultState() at this point? landtgt = 0; nport = (DWORD)-1; lstatus = 0; // set propellant status if (vs->flag & VS_FUELRESET) for (idx = 0; idx < ntank; idx++) SetPropellantMass (tank[idx], 0); if (vs->flag & VS_FUELLIST) { for (i = 0; i < vs->nfuel; i++) { idx = vs->fuel[i].idx; lvl = vs->fuel[i].level; if (idx < ntank) SetPropellantMass (tank[idx], lvl*tank[idx]->maxmass); else if (idx == (DWORD)-1) // global setting for (idx = 0; idx < ntank; idx++) SetPropellantMass (tank[idx], lvl*tank[idx]->maxmass); } } el->Setup (mass, cbody->Mass(), td.MJD_ref); // set thruster status if (vs->flag & VS_THRUSTRESET) for (idx = 0; idx < nthruster; idx++) thruster[idx]->level_permanent = 0; if (vs->flag & VS_THRUSTLIST) { for (i = 0; i < vs->nthruster; i++) { idx = vs->thruster[i].idx; lvl = vs->thruster[i].level; if (idx < nthruster) { thruster[idx]->level_permanent = lvl; thruster[idx]->level = min (1.0, lvl+thruster[idx]->level_override); } } } // set dock status if (vs->flag & VS_DOCKINFOLIST) { for (i = 0; i < vs->ndockinfo; i++) { idx = vs->dockinfo[i].idx; if ((idx = vs->dockinfo[i].idx) < ndock) { dock[idx]->matedock = vs->dockinfo[i].ridx; dock[idx]->mate = (Vessel*)vs->dockinfo[i].rvessel; } } } // state vectors switch (vs->status) { case 0: { // freeflight if (!attach_status.pname) { Vector rp (vs->rpos.x, vs->rpos.y, vs->rpos.z); Vector rv (vs->rvel.x, vs->rvel.y, vs->rvel.z); Vector orient (vs->arot.x, vs->arot.y, vs->arot.z); Vector vr (vs->vrot.x, vs->vrot.y, vs->vrot.z); InitOrbiting (rp, rv, orient, &vr); } } break; case 1: // landed if (vs->base) { landtgt = (Base*)vs->base; nport = landtgt->OccupyPad (this, vs->port, true); lstatus = 1; proxybase = landtgt; } if (vs->arot.x <= 4.0) { // extended information available Matrix lrot; lrot.Set (MakeVector(vs->arot)); double alt = vs->vrot.x; InitLanded ((Planet*)cbody, vs->surf_lng, vs->surf_lat, vs->surf_hdg, &lrot, alt); } else { InitLanded ((Planet*)cbody, vs->surf_lng, vs->surf_lat, vs->surf_hdg); } if (proxybase = landtgt) proxybase->ReportTouchdown (this, vs->surf_lng, vs->surf_lat); break; } if (xpdr && vs->xpdr) xpdr->SetStep (vs->xpdr); } // ============================================================== // GetStateX versions // ============================================================== // ============================================================== // Write a vessel state to a VESSELSTATUS interface void Vessel::GetState (VESSELSTATUS &status) { memset (&status, 0, sizeof(VESSELSTATUS)); status.rbody = (OBJHANDLE)cbody; Vector dp (GPos() - cbody->GPos()); status.rpos.x = dp.x; status.rpos.y = dp.y; status.rpos.z = dp.z; Vector dv (GVel() - cbody->GVel()); status.rvel.x = dv.x; status.rvel.y = dv.y; status.rvel.z = dv.z; if (fstatus == FLIGHTSTATUS_LANDED) { status.vrot.x = sp.alt; status.vrot.y = 0.0; status.vrot.z = 0.0; EulerAngles (land_rot, status.arot); } else { status.vrot.x = s0->omega.x; status.vrot.y = s0->omega.y; status.vrot.z = s0->omega.z; EulerAngles (s0->R, status.arot); } TankSpec *ts = PropellantHandle(0); status.fuel = (ts ? GetPropellantLevel(ts) : 0.0); status.eng_main = GetThrusterGroupLevel (THGROUP_MAIN); if (!status.eng_main) status.eng_main = -GetThrusterGroupLevel (THGROUP_RETRO); status.eng_hovr = GetThrusterGroupLevel (THGROUP_HOVER); status.port = nport; status.base = landtgt; // should also include docking target switch (fstatus) { case FLIGHTSTATUS_FREEFLIGHT: status.status = 0; break; case FLIGHTSTATUS_LANDED: status.status = 1; status.vdata[0].x = sp.lng; status.vdata[0].y = sp.lat; status.vdata[0].z = sp.dir; break; case FLIGHTSTATUS_TAXIING: status.status = 2; break; case FLIGHTSTATUS_DOCKED: status.status = 3; break; default: status.status = 99; break; } } // ============================================================== // Write a vessel state to a VESSELSTATUS2 interface void Vessel::GetState2 (void *status) { VESSELSTATUS2 *vs = (VESSELSTATUS2*)status; DWORD i; vs->rbody = (OBJHANDLE)cbody; vs->base = proxybase; vs->port = nport; Vector dp (GPos() - cbody->GPos()); Vector dv (GVel() - cbody->GVel()); vs->rpos = _V(dp.x, dp.y, dp.z); vs->rvel = _V(dv.x, dv.y, dv.z); vs->vrot = (fstatus == FLIGHTSTATUS_LANDED ? _V(sp.alt, 0, 0) : _V(s0->omega.x, s0->omega.y, s0->omega.z)); EulerAngles (fstatus == FLIGHTSTATUS_LANDED ? land_rot : s0->R, vs->arot); vs->surf_lng = sp.lng; vs->surf_lat = sp.lat; vs->surf_hdg = sp.dir; vs->status = (fstatus == FLIGHTSTATUS_LANDED ? 1 : fstatus == FLIGHTSTATUS_DOCKED ? 2 : 0); if (vs->flag & VS_FUELLIST) { vs->nfuel = ntank; if (!vs->fuel) { vs->fuel = new VESSELSTATUS2::FUELSPEC[ntank]; TRACENEW } for (i = 0; i < ntank; i++) { vs->fuel[i].idx = i; vs->fuel[i].level = tank[i]->mass / tank[i]->maxmass; } } if (vs->flag & VS_THRUSTLIST) { vs->nthruster = nthruster; if (!vs->thruster) { vs->thruster = new VESSELSTATUS2::THRUSTSPEC[nthruster]; TRACENEW } for (i = 0; i < nthruster; i++) { vs->thruster[i].idx = i; vs->thruster[i].level = thruster[i]->level; } } if (vs->flag & VS_DOCKINFOLIST) { vs->ndockinfo = ndock; if (!vs->dockinfo) { vs->dockinfo = new VESSELSTATUS2::DOCKINFOSPEC[ndock]; TRACENEW } for (i = 0; i < ndock; i++) { vs->dockinfo[i].idx = i; vs->dockinfo[i].ridx = dock[i]->matedock; vs->dockinfo[i].rvessel = (OBJHANDLE)dock[i]->mate; } } vs->xpdr = (xpdr ? xpdr->GetStep() : 0); } // ============================================================== int Vessel::TouchdownPointsFromFile (const char *fname) { // open the file char line[512], *c; strcpy (line, fname); strcat (line, ".dat"); std::ifstream ifs (g_pOrbiter->Cfg()->ConfigPathNoext (line)); if (!ifs.good()) return 1; // parse the touchdown point specs int i, res, ntdp; ifs.getline (line, 512); c = trim_string (line); res = sscanf (c, "%d", &ntdp); if (res != 1 || ntdp < 3) return 2; TOUCHDOWNVTX *tdp = new TOUCHDOWNVTX[ntdp]; for (i = 0; i < ntdp; i++) { ifs.getline (line, 512); c = trim_string (line); res = sscanf (c, "%lf%lf%lf%lf%lf%lf%lf", &tdp[i].pos.x, &tdp[i].pos.y, &tdp[i].pos.z, &tdp[i].stiffness, &tdp[i].damping, &tdp[i].mu, &tdp[i].mu_lng); if (res < 7) { tdp[i].mu_lng = mu_lng; if (res < 6) { tdp[i].mu = mu; if (res < 5) { tdp[i].damping = 1e5; if (res < 4) { tdp[i].stiffness = 1e6; if (res < 3) { delete []tdp; return 2; } } } } } } SetTouchdownPoints (tdp, ntdp); delete []tdp; return 0; }
33.112882
147
0.577364
[ "vector" ]
61abdf02dc00d13017d6f3f4aa8a19cae3d3d277
5,980
cpp
C++
src/blacklist.cpp
LJP-TW/Ponce
384eb38fcc698a9f0aa0f2242db36e5457358f56
[ "BSL-1.0" ]
1,270
2016-09-23T13:43:00.000Z
2022-03-27T10:00:02.000Z
src/blacklist.cpp
LJP-TW/Ponce
384eb38fcc698a9f0aa0f2242db36e5457358f56
[ "BSL-1.0" ]
87
2016-09-23T13:50:17.000Z
2021-05-16T06:02:36.000Z
src/blacklist.cpp
LJP-TW/Ponce
384eb38fcc698a9f0aa0f2242db36e5457358f56
[ "BSL-1.0" ]
232
2016-09-23T15:24:42.000Z
2022-03-30T13:22:34.000Z
//! \file /* ** Copyright (c) 2020 - Ponce ** Authors: ** Alberto Garcia Illera agarciaillera@gmail.com ** Francisco Oca francisco.oca.gonzalez@gmail.com ** ** This program is under the terms of the BSD License. */ #include <iostream> #include <fstream> // Ponce #include "blacklist.hpp" #include "globals.hpp" #include "callbacks.hpp" #include "utils.hpp" #include "triton_logic.hpp" // IDA #include <ida.hpp> #include <dbg.hpp> #include <loader.hpp> #include <intel.hpp> #include <bytes.hpp> std::list<breakpoint_pending_action> breakpoint_pending_actions; std::vector<std::string> builtin_black_functions = { "printf", "puts", "putc", "sleep", "recv", "recvfrom", "send", "closesocket", "exit", "abort", "malloc", "calloc", "realloc", "free", "calloc_crt", "realloc_crt", //cstdio "clearerr", "fclose", "feof", "ferror", "fflush", "fgetc", "fgetpos", "fgets", "fopen", "fprintf", "fputc", "fputs", "fread", "freopen", "fscanf", "fseek", "fsetpos", "ftell", "fwrite", "getc", "getchar", "gets", "perror", "printf", "putc", "putchar", "puts", "remove", "rename", "rewind", "scanf", "setbuf", "setvbuf", "snprintf", "sprintf", "sscanf", "tmpfile", "tmpnam", "ungetc", "vfprintf", "vfscanf", "vprintf", "vscanf", "vsnprintf", "vsprintf", "vsscanf", //Windows "Sleep", "HeapAlloc", "HeapFree", "HeapRealloc", "CreateThread", "NtTerminateProcess", "ExitThread", "TerminateThread", "ExitProcess", "EnterCriticalSection", "LeaveCriticalSection", "SendMessage", "WSAGetLastError", "WaitForSingleObject", "CloseHandle", }; //Helper to concretize and untaint volatile registers void concretizeAndUntaintVolatileRegisters() { //ToDo: check how different compilers behave regarding volatile registers #if defined(__i386) || defined(_M_IX86) char const* volatile_regs[] = { "eax", "ecx", "edx" }; #elif defined(__x86_64__) || defined(_M_X64) char const* volatile_regs[] = { "rax", "rcx", "rdx", "r8", "r8", "r10", "r11", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }; #endif for (const auto& [reg_id, reg] : api.getAllRegisters()) { for (auto i = 0; i < sizeof(volatile_regs) / sizeof(char*); i++) { if (strcmp(reg.getName().c_str(), volatile_regs[i]) == 0) { api.concretizeRegister(reg); api.untaintRegister(reg); } } } } //Helper to concretize and untaint all registers void concretizeAndUntaintAllRegisters() { api.concretizeAllRegister(); //We untaint all the registers auto regs = api.getAllRegisters(); for (auto it = regs.begin(); it != regs.end(); it++) { api.untaintRegister(it->second); } } /* We use this function to enable the trigger after a blacklisted function. We are also concretizing all the registers. The idea is after call a external function you couldn't assume any register has been unchanged, so we concretize all of them.*/ void enableTrigger_and_concretize_registers(ea_t main_address) { ponce_runtime_status.runtimeTrigger.enable(); concretizeAndUntaintVolatileRegisters(); } void readBlacklistfile(char* path) { std::ifstream file(path); std::string str; blacklkistedUserFunctions = new std::vector<std::string>(); while (std::getline(file, str)) { if (cmdOptions.showDebugInfo) msg("[+] Adding %s to the blacklist funtion list\n", str.c_str()); blacklkistedUserFunctions->push_back(str); } } bool should_blacklist(ea_t pc, thid_t tid) { insn_t cmd; decode_insn(&cmd, pc); // We do this to blacklist API that does not change the tainted input if (cmd.itype == NN_call || cmd.itype == NN_callfi || cmd.itype == NN_callni) { //qstring callee = get_callee_name(pc); qstring callee; auto callee_lenght = get_func_name(&callee, pc); std::vector<std::string>* to_use_blacklist; //Let's check if the user provided any blacklist file or we sholuld use the built in one if (blacklkistedUserFunctions != nullptr) { to_use_blacklist = blacklkistedUserFunctions; } else {//We need to use the built in one to_use_blacklist = &builtin_black_functions; } for (const auto& blacklisted_function : *to_use_blacklist) { if (strcmp(callee.c_str(), blacklisted_function.c_str()) == 0) { //We are in a call to a blacklisted function. /*We should set a BP in the next instruction right after the blacklisted callback to enable tracing again*/ ea_t next_ea = next_head(pc, BADADDR); add_bpt(next_ea, 1, BPT_EXEC); //We set a comment so the user know why there is a new bp there ponce_set_cmt(next_ea, "Temporal bp set by ponce for blacklisting\n", false); breakpoint_pending_action bpa; bpa.address = next_ea; bpa.ignore_breakpoint = false; bpa.callback = enableTrigger_and_concretize_registers; // We will enable back the trigger when this bp get's reached //We add the action to the list breakpoint_pending_actions.push_back(bpa); //Disabling step tracing... disable_step_trace(); //We want to tritonize the call, so the memory write for the ret address in the stack will be restore by the snapshot tritonize(pc, tid); ponce_runtime_status.runtimeTrigger.disable(); return true; } } } return false; }
27.181818
170
0.602341
[ "vector" ]
61afb3bd846def87abdfefef14bb3fe131953f68
2,269
cpp
C++
code/source/projects/App_AmbientInteractions/Scripts/AgentsTalking.cpp
DeRidderJonas/AmbientInteractionsUsingSmartLocations
2693cef6f84827a92019fb03801a0c112e165876
[ "MIT" ]
null
null
null
code/source/projects/App_AmbientInteractions/Scripts/AgentsTalking.cpp
DeRidderJonas/AmbientInteractionsUsingSmartLocations
2693cef6f84827a92019fb03801a0c112e165876
[ "MIT" ]
null
null
null
code/source/projects/App_AmbientInteractions/Scripts/AgentsTalking.cpp
DeRidderJonas/AmbientInteractionsUsingSmartLocations
2693cef6f84827a92019fb03801a0c112e165876
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "AgentsTalking.h" #include "projects/App_AmbientInteractions/NpcAgent.h" AgentsTalking::AgentsTalking(size_t min_agents, size_t max_agents, size_t min_agents_dynamic, size_t max_agents_dynamic) : Script() { m_Roles.push_back({ Role::Name::AnyHuman, Role::Flag::LeaveAfterEnd, min_agents, max_agents }); m_Roles.push_back({ Role::Name::AnyHuman, Role::Flag::LeaveAfterEnd | Role::Flag::DynamicJoin, min_agents_dynamic, max_agents_dynamic }); } AgentsTalking::AgentsTalking(size_t agents, size_t agents_dynamic) : AgentsTalking(agents, agents, agents_dynamic, agents_dynamic) { } void AgentsTalking::Start(Elite::Blackboard* pBlackboard) { Script::Start(pBlackboard); if (!m_IsRunning) return; std::vector<NpcAgent*> agents{ m_Roles[0].GetAgents() }; Elite::Vector2 inBetween{}; for (NpcAgent* pAgent : agents) inBetween += pAgent->GetPosition(); inBetween /= float(agents.size()); TargetData target{}; target.Position = inBetween; for (NpcAgent* pAgent : agents) { pAgent->SetToSeek(); pAgent->SetTarget(target); } m_pBlackboard->AddData("Target", target); } bool AgentsTalking::Update(float deltaTime) { if(!Script::Update(deltaTime)) return false; std::vector<NpcAgent*> agents{ m_Roles[0].GetAgents() }; agents.insert(agents.end(), m_Roles[1].GetAgents().begin(), m_Roles[1].GetAgents().end()); if (agents.size() <= 0) { OnError(); return false; } for (NpcAgent* pAgent : agents) { pAgent->SetBodyColor({ 0,0,1,1 }); } return true; } bool AgentsTalking::DynamicJoin() { //When another agent joins, reset the timer to 0 (otherwise he might join just before the conversation ends) m_TimeElapsed = 0.f; bool dynamicJoinSuccess = Script::DynamicJoin(); if (!dynamicJoinSuccess) return false; TargetData target{}; m_pBlackboard->GetData("Target", target); for (NpcAgent* pAgent : m_Roles[1].GetAgents()) { pAgent->SetToSeek(); pAgent->SetTarget(target); } return true; } bool AgentsTalking::IsEndConditionMet() { if (!Script::IsEndConditionMet()) return false; return m_TimeElapsed >= m_AmountOfSecondsTalking; }
26.694118
141
0.678272
[ "vector" ]
61afdf491ed615218fc788900d0b28431927e618
1,294
hpp
C++
sources/IR/operand.hpp
pavelkryukov/mipt-scheme-compiler
c14fd5fb79324a42cfc0450c196f3ebdfaba4edd
[ "Apache-2.0" ]
null
null
null
sources/IR/operand.hpp
pavelkryukov/mipt-scheme-compiler
c14fd5fb79324a42cfc0450c196f3ebdfaba4edd
[ "Apache-2.0" ]
null
null
null
sources/IR/operand.hpp
pavelkryukov/mipt-scheme-compiler
c14fd5fb79324a42cfc0450c196f3ebdfaba4edd
[ "Apache-2.0" ]
1
2016-01-03T02:49:25.000Z
2016-01-03T02:49:25.000Z
/** * @file:operand.hpp * Interface of operand * Core component of Operations and Objects */ /** * Copyright (C) 2012 MIPT Scheme Compiler team */ #pragma once namespace ir { /** * @class Operand * Representation of Operand */ class Operand { public: /** Constructor */ Operand(); /** Destructor */ ~Operand(); /** Return operand type */ inline const OperandType& type() const; /** Set operand type */ inline void setType( const OperandType& type); /** Return constant value */ inline Int64 constValue() const; /** Return object */ inline Object* object() const; /** Return target */ inline Operation* target() const; /** Set constant value */ inline void setConstValue( Int64 immediate); /** Set object */ inline void setObject( Object& obj); /** Set target */ inline void setTarget( Operation& target); /** Add the operation in the output stream s */ inline void toStream( ostream& s) const; private: /** Operand type */ OperandType type_; /** Operand data */ union OperandData { Int64 imm; Object *obj; Operation *target; } data; }; inline ostream& operator<<( ostream& s, const Operand& opnd); }//namespace ir
17.972222
61
0.602009
[ "object" ]
61b18cde0fcf284c807171d46c4e5256646f1632
13,549
cc
C++
shaka/src/mapping/jsc/js_wrappers.cc
Mousmi122767/shaka-player-embedded
10d9b5e0ec737c714c7d40c62593b9fae8514a36
[ "Apache-2.0", "BSD-3-Clause" ]
185
2018-11-06T06:04:44.000Z
2022-03-02T22:20:39.000Z
shaka/src/mapping/jsc/js_wrappers.cc
Mousmi122767/shaka-player-embedded
10d9b5e0ec737c714c7d40c62593b9fae8514a36
[ "Apache-2.0", "BSD-3-Clause" ]
211
2018-11-15T22:52:49.000Z
2022-03-02T18:46:20.000Z
shaka/src/mapping/jsc/js_wrappers.cc
Mousmi122767/shaka-player-embedded
10d9b5e0ec737c714c7d40c62593b9fae8514a36
[ "Apache-2.0", "BSD-3-Clause" ]
52
2018-12-12T11:00:46.000Z
2022-02-23T17:35:02.000Z
// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/mapping/js_wrappers.h" #include <fstream> #include "src/mapping/backing_object.h" #include "src/mapping/convert_js.h" #include "src/mapping/js_utils.h" #include "src/util/file_system.h" namespace shaka { namespace { JSClassDefinition wrapper_class_def = { .version = 1, .className = "<pointer wrapper>", }; JSClassRef GetWrapperClass() { static JSClassRef class_ = nullptr; if (!class_) { class_ = JSClassCreate(&wrapper_class_def); CHECK(class_); } return class_; } bool IsInstanceOfStandardType(Handle<JsValue> value, const std::string& type) { JSContextRef cx = GetContext(); JSValueRef ctor = GetMemberRaw(JSContextGetGlobalObject(cx), type); return JSValueIsInstanceOfConstructor(cx, value, UnsafeJsCast<JsObject>(ctor), nullptr); } } // namespace namespace util { template <> struct RefTypeTraits<JSPropertyNameArrayRef> { static constexpr const bool AcquireWithRaw = false; static JSPropertyNameArrayRef Duplicate(JSPropertyNameArrayRef arg) { if (arg) return JSPropertyNameArrayRetain(arg); else return nullptr; } static void Release(JSPropertyNameArrayRef arg) { if (arg) JSPropertyNameArrayRelease(arg); } }; } // namespace util // \cond Doxygen_Skip CallbackArguments::CallbackArguments(const JSValueRef* args, size_t count, JSObjectRef callee, JSObjectRef thisv, JSValueRef* except) : except_(except), callee_(callee), this_(thisv), args_(args), count_(count) {} CallbackArguments::~CallbackArguments() {} ReturnVal<JsValue> CallbackArguments::operator[](size_t i) const { if (i >= count_) return nullptr; return args_[i]; } void CallbackArguments::SetReturn(Handle<JsValue> ret) const { DCHECK(!ret_); ret_ = ret; } void CallbackArguments::SetException(Handle<JsValue> except) const { DCHECK(!ret_); *except_ = except; } std::vector<std::string> GetMemberNames(Handle<JsObject> object) { auto* cx = GetContext(); util::CFRef<JSPropertyNameArrayRef> props = JSObjectCopyPropertyNames(cx, object); const size_t max = JSPropertyNameArrayGetCount(props); std::vector<std::string> ret; ret.reserve(max); for (size_t i = 0; i < max; i++) { LocalVar<JsString> name(util::acquire_ref, JSPropertyNameArrayGetNameAtIndex(props, i)); ret.emplace_back(ConvertToString(RawToJsValue(name))); } return ret; } ReturnVal<JsValue> GetMemberRaw(Handle<JsObject> object, const std::string& name, LocalVar<JsValue>* exception) { JSValueRef raw_except = nullptr; auto* ret = JSObjectGetProperty(GetContext(), object, JsStringFromUtf8(name), &raw_except); if (exception) { *exception = raw_except; } return ret; } ReturnVal<JsValue> GetArrayIndexRaw(Handle<JsObject> object, size_t index, LocalVar<JsValue>* exception) { JSValueRef raw_except = nullptr; auto* ret = JSObjectGetPropertyAtIndex(GetContext(), object, index, &raw_except); if (exception) { *exception = raw_except; } return ret; } void SetMemberRaw(Handle<JsObject> object, const std::string& name, Handle<JsValue> value) { JSObjectSetProperty(GetContext(), object, JsStringFromUtf8(name), value, kJSPropertyAttributeNone, nullptr); } void SetArrayIndexRaw(Handle<JsObject> object, size_t i, Handle<JsValue> value) { JSObjectSetPropertyAtIndex(GetContext(), object, i, value, nullptr); } void SetGenericPropertyRaw(Handle<JsObject> object, const std::string& name, Handle<JsFunction> getter, Handle<JsFunction> setter) { // TODO: Find a better way to do this. // This works by effectively running the following JavaScript: // Object.defineProperty($object, $name, {get: $getter, set: $setter}); LocalVar<JsValue> js_Object = GetMemberRaw(JSContextGetGlobalObject(GetContext()), "Object"); CHECK(js_Object && IsObject(js_Object)); LocalVar<JsValue> define_prop = GetMemberRaw(UnsafeJsCast<JsObject>(js_Object), "defineProperty"); CHECK(define_prop && GetValueType(define_prop) == proto::ValueType::Function); LocalVar<JsObject> props(CreateObject()); SetMemberRaw(props, "get", getter); if (setter) SetMemberRaw(props, "set", setter); LocalVar<JsValue> args[] = {object, ToJsValue(name), props}; LocalVar<JsValue> except; CHECK(InvokeMethod(UnsafeJsCast<JsObject>(define_prop), UnsafeJsCast<JsObject>(js_Object), 3, args, &except)) << ConvertToString(except); } bool InvokeConstructor(Handle<JsFunction> ctor, int argc, LocalVar<JsValue>* argv, LocalVar<JsValue>* result_or_except) { JSValueRef except = nullptr; std::vector<JSValueRef> args(argv, argv + argc); LocalVar<JsValue> ret = JSObjectCallAsConstructor(GetContext(), ctor, argc, args.data(), &except); if (except) { *result_or_except = except; return false; } else { *result_or_except = ret; return true; } } bool InvokeMethod(Handle<JsFunction> func, Handle<JsObject> that, int argc, LocalVar<JsValue>* argv, LocalVar<JsValue>* result_or_except) { JSValueRef except = nullptr; std::vector<JSValueRef> args(argv, argv + argc); LocalVar<JsValue> ret = JSObjectCallAsFunction(GetContext(), func, that, argc, args.data(), &except); if (except) { *result_or_except = except; return false; } else { *result_or_except = ret; return true; } } std::string ConvertToString(Handle<JsValue> value) { LocalVar<JsString> str(JSValueToStringCopy(GetContext(), value, nullptr)); if (!str) return ""; const size_t max_size = JSStringGetMaximumUTF8CStringSize(str); std::string ret(max_size, '\0'); const size_t real_size = JSStringGetUTF8CString(str, &ret[0], ret.size()); ret.resize(real_size - 1); // Subtract 1 to remove the null-terminator. return ret; } ReturnVal<JsValue> WrapPointer(void* ptr) { return JSObjectMake(GetContext(), GetWrapperClass(), ptr); } void* MaybeUnwrapPointer(Handle<JsValue> value) { if (!JSValueIsObjectOfClass(GetContext(), value, GetWrapperClass())) return nullptr; return JSObjectGetPrivate(JSValueToObject(GetContext(), value, nullptr)); } BackingObject* GetInternalPointer(Handle<JsValue> value) { LocalVar<JsObject> obj(JSValueToObject(GetContext(), value, nullptr)); if (!obj) return nullptr; return reinterpret_cast<BackingObject*>(JSObjectGetPrivate(obj)); } bool IsDerivedFrom(BackingObject* ptr, const std::string& name) { return ptr ? ptr->DerivedFrom(name) : false; } bool RunScript(const std::string& path) { util::FileSystem fs; std::vector<uint8_t> code; CHECK(fs.ReadFile(path, &code)); return RunScript(path, code.data(), code.size()); } bool RunScript(const std::string& path, const uint8_t* data, size_t size) { LocalVar<JsString> code = JsStringFromUtf8(data, size); LocalVar<JsString> source = JsStringFromUtf8(path); JSValueRef except = nullptr; (void)JSEvaluateScript(GetContext(), code, nullptr, source, 0, &except); if (except) { OnUncaughtException(except, false); return false; } return true; } ReturnVal<JsValue> ParseJsonString(const std::string& json) { LocalVar<JsString> input = JsStringFromUtf8(json); return JSValueMakeFromJSONString(GetContext(), input); } ReturnVal<JsString> JsStringFromUtf8(const uint8_t* data, size_t size) { util::CFRef<CFStringRef> cf_str(CFStringCreateWithBytes( nullptr, data, size, kCFStringEncodingUTF8, false)); return JSStringCreateWithCFString(cf_str); } ReturnVal<JsString> JsStringFromUtf8(const std::string& str) { util::CFRef<CFStringRef> cf_str(CFStringCreateWithBytes( nullptr, reinterpret_cast<const uint8_t*>(str.data()), str.size(), kCFStringEncodingUTF8, false)); return JSStringCreateWithCFString(cf_str); } ReturnVal<JsValue> JsUndefined() { return JSValueMakeUndefined(GetContext()); } ReturnVal<JsValue> JsNull() { return JSValueMakeNull(GetContext()); } ReturnVal<JsObject> CreateArray(size_t length) { JSContextRef cx = GetContext(); LocalVar<JsObject> arr(JSObjectMakeArray(cx, 0, nullptr, nullptr)); SetMemberRaw(arr, "length", JSValueMakeNumber(cx, length)); return arr; } ReturnVal<JsObject> CreateObject() { return JSObjectMake(GetContext(), nullptr, nullptr); } ReturnVal<JsMap> CreateMap() { return UnsafeJsCast<JsObject>(CreateNativeObject("Map", nullptr, 0)); } void SetMapValue(Handle<JsMap> map, Handle<JsValue> key, Handle<JsValue> value) { LocalVar<JsValue> func_value = GetMemberRaw(map, "set"); DCHECK(GetValueType(func_value) == proto::ValueType::Function); LocalVar<JsFunction> func = UnsafeJsCast<JsFunction>(func_value); LocalVar<JsValue> args[] = {key, value}; LocalVar<JsValue> ignored; CHECK(InvokeMethod(func, map, 2, args, &ignored)); } bool IsNullOrUndefined(Handle<JsValue> value) { JSContextRef cx = GetContext(); return !value || JSValueIsNull(cx, value) || JSValueIsUndefined(cx, value); } bool IsObject(Handle<JsValue> value) { return JSValueIsObject(GetContext(), value); } bool IsBuiltInObject(Handle<JsObject> object) { LocalVar<JsValue> to_string_val = GetDescendant(JSContextGetGlobalObject(GetContext()), {"Object", "prototype", "toString"}); CHECK(IsObject(to_string_val)); LocalVar<JsObject> to_string = UnsafeJsCast<JsObject>(to_string_val); LocalVar<JsValue> value; CHECK(InvokeMethod(to_string, object, 0, nullptr, &value)); return ConvertToString(value) != "[object Object]"; } proto::ValueType GetValueType(Handle<JsValue> value) { JSContextRef cx = GetContext(); switch (JSValueGetType(cx, value)) { case kJSTypeUndefined: return proto::ValueType::Undefined; case kJSTypeNull: return proto::ValueType::Null; case kJSTypeBoolean: return proto::ValueType::Boolean; case kJSTypeNumber: return proto::ValueType::Number; case kJSTypeString: return proto::ValueType::String; case kJSTypeObject: break; default: LOG(FATAL) << "Unknown JavaScript value type"; } // Note JSC doesn't support symbols. if (JSValueIsArray(cx, value)) return proto::ValueType::Array; if (JSObjectIsFunction(cx, JSValueToObject(cx, value, nullptr))) return proto::ValueType::Function; switch (JSValueGetTypedArrayType(cx, value, nullptr)) { case kJSTypedArrayTypeArrayBuffer: return proto::ValueType::ArrayBuffer; case kJSTypedArrayTypeFloat32Array: return proto::ValueType::Float32Array; case kJSTypedArrayTypeFloat64Array: return proto::ValueType::Float64Array; case kJSTypedArrayTypeInt16Array: return proto::ValueType::Int16Array; case kJSTypedArrayTypeInt32Array: return proto::ValueType::Int32Array; case kJSTypedArrayTypeInt8Array: return proto::ValueType::Int8Array; case kJSTypedArrayTypeUint16Array: return proto::ValueType::Uint16Array; case kJSTypedArrayTypeUint32Array: return proto::ValueType::Uint32Array; case kJSTypedArrayTypeUint8Array: return proto::ValueType::Uint8Array; case kJSTypedArrayTypeUint8ClampedArray: return proto::ValueType::Uint8ClampedArray; case kJSTypedArrayTypeNone: break; default: LOG(FATAL) << "Unknown JavaScript TypedArray type"; } if (IsInstanceOfStandardType(value, "Boolean")) return proto::ValueType::BooleanObject; if (IsInstanceOfStandardType(value, "String")) return proto::ValueType::StringObject; if (IsInstanceOfStandardType(value, "Number")) return proto::ValueType::NumberObject; if (IsInstanceOfStandardType(value, "Promise")) return proto::ValueType::Promise; return proto::ValueType::OtherObject; } double NumberFromValue(Handle<JsValue> value) { JSContextRef cx = GetContext(); DCHECK(JSValueIsNumber(cx, value) || IsInstanceOfStandardType(value, "Number")); return JSValueToNumber(cx, value, nullptr); } bool BooleanFromValue(Handle<JsValue> value) { JSContextRef cx = GetContext(); if (IsInstanceOfStandardType(value, "Boolean")) { LocalVar<JsValue> func = GetMemberRaw(UnsafeJsCast<JsObject>(value), "valueOf"); CHECK(GetValueType(func) == proto::ValueType::Function); LocalVar<JsValue> except; CHECK(InvokeMethod(UnsafeJsCast<JsFunction>(func), UnsafeJsCast<JsObject>(value), 0, nullptr, &except)); value = except; } else { DCHECK(JSValueIsBoolean(cx, value)); } return JSValueToBoolean(cx, value); } // \endcond Doxygen_Skip } // namespace shaka
31.805164
80
0.695402
[ "object", "vector" ]
ba0ae0687230da447fd975641b2b940c17622162
3,831
hpp
C++
libraries/plugins/rc/include/voilk/plugins/rc/rc_objects.hpp
voilknetwork/voilk
839716ae446d39d7260505b5d6d16f4f122cf1fe
[ "MIT" ]
null
null
null
libraries/plugins/rc/include/voilk/plugins/rc/rc_objects.hpp
voilknetwork/voilk
839716ae446d39d7260505b5d6d16f4f122cf1fe
[ "MIT" ]
null
null
null
libraries/plugins/rc/include/voilk/plugins/rc/rc_objects.hpp
voilknetwork/voilk
839716ae446d39d7260505b5d6d16f4f122cf1fe
[ "MIT" ]
3
2020-09-03T11:23:13.000Z
2021-06-16T07:07:54.000Z
#pragma once #include <voilk/chain/util/manabar.hpp> #include <voilk/plugins/rc/rc_utility.hpp> #include <voilk/plugins/rc/resource_count.hpp> #include <voilk/chain/voilk_object_types.hpp> #include <fc/int_array.hpp> #include <boost/multi_index/composite_key.hpp> namespace voilk { namespace plugins { namespace rc { using namespace std; using namespace voilk::chain; #ifndef VOILK_RC_SPACE_ID #define VOILK_RC_SPACE_ID 16 #endif enum rc_object_types { rc_resource_param_object_type = ( VOILK_RC_SPACE_ID << 8 ), rc_pool_object_type = ( VOILK_RC_SPACE_ID << 8 ) + 1, rc_account_object_type = ( VOILK_RC_SPACE_ID << 8 ) + 2 }; class rc_resource_param_object : public object< rc_resource_param_object_type, rc_resource_param_object > { public: template< typename Constructor, typename Allocator > rc_resource_param_object( Constructor&& c, allocator< Allocator > a ) { c( *this ); } id_type id; fc::int_array< rc_resource_params, VOILK_NUM_RESOURCE_TYPES > resource_param_array; }; class rc_pool_object : public object< rc_pool_object_type, rc_pool_object > { public: template< typename Constructor, typename Allocator > rc_pool_object( Constructor&& c, allocator< Allocator > a ) { c( *this ); } id_type id; fc::int_array< int64_t, VOILK_NUM_RESOURCE_TYPES > pool_array; }; class rc_account_object : public object< rc_account_object_type, rc_account_object > { public: template< typename Constructor, typename Allocator > rc_account_object( Constructor&& c, allocator< Allocator > a ) { c( *this ); } id_type id; account_name_type account; voilk::chain::util::manabar rc_manabar; asset max_rc_creation_adjustment = asset( 0, COINS_SYMBOL ); // This is used for bug-catching, to match that the coining shares in a // pre-op are equal to what they were at the last post-op. int64_t last_max_rc = 0; }; int64_t get_maximum_rc( const voilk::chain::account_object& account, const rc_account_object& rc_account ); using namespace boost::multi_index; typedef multi_index_container< rc_resource_param_object, indexed_by< ordered_unique< tag< by_id >, member< rc_resource_param_object, rc_resource_param_object::id_type, &rc_resource_param_object::id > > >, allocator< rc_resource_param_object > > rc_resource_param_index; typedef multi_index_container< rc_pool_object, indexed_by< ordered_unique< tag< by_id >, member< rc_pool_object, rc_pool_object::id_type, &rc_pool_object::id > > >, allocator< rc_pool_object > > rc_pool_index; typedef multi_index_container< rc_account_object, indexed_by< ordered_unique< tag< by_id >, member< rc_account_object, rc_account_object::id_type, &rc_account_object::id > >, ordered_unique< tag< by_name >, member< rc_account_object, account_name_type, &rc_account_object::account > > >, allocator< rc_account_object > > rc_account_index; } } } // voilk::plugins::rc FC_REFLECT( voilk::plugins::rc::rc_resource_param_object, (id)(resource_param_array) ) CHAINBASE_SET_INDEX_TYPE( voilk::plugins::rc::rc_resource_param_object, voilk::plugins::rc::rc_resource_param_index ) FC_REFLECT( voilk::plugins::rc::rc_pool_object, (id)(pool_array) ) CHAINBASE_SET_INDEX_TYPE( voilk::plugins::rc::rc_pool_object, voilk::plugins::rc::rc_pool_index ) FC_REFLECT( voilk::plugins::rc::rc_account_object, (id) (account) (rc_manabar) (max_rc_creation_adjustment) (last_max_rc) ) CHAINBASE_SET_INDEX_TYPE( voilk::plugins::rc::rc_account_object, voilk::plugins::rc::rc_account_index )
31.401639
138
0.701122
[ "object" ]
ba0d4522e49406111442aba8f96433655ad73900
3,848
hpp
C++
src/external/armadillo/include/armadillo_bits/fn_sum.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
src/external/armadillo/include/armadillo_bits/fn_sum.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
src/external/armadillo/include/armadillo_bits/fn_sum.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2019-06-01T18:49:28.000Z
2019-06-01T18:49:28.000Z
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // 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. // ------------------------------------------------------------------------ //! \addtogroup fn_sum //! @{ template<typename T1> arma_warn_unused arma_inline const Op<T1, op_sum> sum ( const T1& X, const uword dim = 0, const typename enable_if< is_arma_type<T1>::value == true >::result* junk1 = 0, const typename enable_if< resolves_to_vector<T1>::value == false >::result* junk2 = 0 ) { arma_extra_debug_sigprint(); arma_ignore(junk1); arma_ignore(junk2); return Op<T1, op_sum>(X, dim, 0); } template<typename T1> arma_warn_unused arma_inline const Op<T1, op_sum> sum ( const T1& X, const uword dim, const typename enable_if< resolves_to_vector<T1>::value == true >::result* junk = 0 ) { arma_extra_debug_sigprint(); arma_ignore(junk); return Op<T1, op_sum>(X, dim, 0); } template<typename T1> arma_warn_unused inline typename T1::elem_type sum ( const T1& X, const arma_empty_class junk1 = arma_empty_class(), const typename enable_if< resolves_to_vector<T1>::value == true >::result* junk2 = 0 ) { arma_extra_debug_sigprint(); arma_ignore(junk1); arma_ignore(junk2); return accu(X); } template<typename T1> arma_warn_unused inline typename T1::elem_type sum(const Op<T1, op_sum>& in) { arma_extra_debug_sigprint(); arma_extra_debug_print("sum(): two consecutive sum() calls detected"); return accu(in.m); } template<typename T1> arma_warn_unused arma_inline const Op<Op<T1, op_sum>, op_sum> sum(const Op<T1, op_sum>& in, const uword dim) { arma_extra_debug_sigprint(); return Op<Op<T1, op_sum>, op_sum>(in, dim, 0); } template<typename T> arma_warn_unused arma_inline const typename arma_scalar_only<T>::result & sum(const T& x) { return x; } //! sum of cube template<typename T1> arma_warn_unused arma_inline const OpCube<T1, op_sum> sum ( const BaseCube<typename T1::elem_type,T1>& X, const uword dim = 0 ) { arma_extra_debug_sigprint(); return OpCube<T1, op_sum>(X.get_ref(), dim, 0); } //! sum of sparse object template<typename T1> arma_warn_unused inline typename enable_if2 < (is_arma_sparse_type<T1>::value == true) && (resolves_to_sparse_vector<T1>::value == true), typename T1::elem_type >::result sum(const T1& x) { arma_extra_debug_sigprint(); // sum elements return accu(x); } template<typename T1> arma_warn_unused inline typename enable_if2 < (is_arma_sparse_type<T1>::value == true) && (resolves_to_sparse_vector<T1>::value == false), const SpOp<T1,spop_sum> >::result sum(const T1& x, const uword dim = 0) { arma_extra_debug_sigprint(); return SpOp<T1,spop_sum>(x, dim, 0); } template<typename T1> arma_warn_unused inline typename T1::elem_type sum(const SpOp<T1, spop_sum>& in) { arma_extra_debug_sigprint(); arma_extra_debug_print("sum(): two consecutive sum() calls detected"); return accu(in.m); } template<typename T1> arma_warn_unused arma_inline const SpOp<SpOp<T1, spop_sum>, spop_sum> sum(const SpOp<T1, spop_sum>& in, const uword dim) { arma_extra_debug_sigprint(); return SpOp<SpOp<T1, spop_sum>, spop_sum>(in, dim, 0); } //! @}
18.955665
94
0.694127
[ "object" ]
ba0e8ccebc58556cebc10a9614697d392a1dbbf1
6,751
cpp
C++
Render/i0rDebugRender/DevMenu.cpp
i0r/i0rTech
c74b327345e6e9e1a08c6b5631e84383431f2661
[ "BSD-3-Clause" ]
null
null
null
Render/i0rDebugRender/DevMenu.cpp
i0r/i0rTech
c74b327345e6e9e1a08c6b5631e84383431f2661
[ "BSD-3-Clause" ]
null
null
null
Render/i0rDebugRender/DevMenu.cpp
i0r/i0rTech
c74b327345e6e9e1a08c6b5631e84383431f2661
[ "BSD-3-Clause" ]
null
null
null
#include "../Common.hpp" #ifdef FLAG_DEBUG #include "../i0rPrograms/Text.hpp" #include "DevMenu.hpp" DevMenu::DevMenu( const i32 x, const i32 y, std::string name ) { m_Name = name; m_PosX = x; m_PosY = y; m_ActiveItemIndex = -1; m_ActiveSubMenuIndex = -1; m_HasFocus = false; m_Parent = nullptr; } DevMenu::~DevMenu() { for( dev_menu_item_t* item : m_Items ) { SAFE_DELETE( item ) } m_Items.clear(); for( IDevMenu* subMenu : m_SubMenus ) { SAFE_DELETE( subMenu ) } m_SubMenus.clear(); m_PosX = 0; m_PosY = 0; m_ActiveItemIndex = 0; m_ActiveSubMenuIndex = 0; m_Name.clear(); } void DevMenu::SetAsActiveMenu( const i32 menuIndex ) { m_HasFocus = false; m_ActiveSubMenuIndex = menuIndex; if( m_ActiveSubMenuIndex != -1 ) m_SubMenus[m_ActiveSubMenuIndex]->SetHasFocus( true ); else m_Parent->SetHasFocus( true ); } DevMenu* DevMenu::CreateSubMenu( const char* name ) { if( m_ActiveItemIndex == -1 ) m_ActiveItemIndex = 0; DevMenu* submenu = new DevMenu( m_PosX, m_PosY, name ); submenu->AddItem( new dev_menu_item_t( "..", std::bind( &DevMenu::SetAsActiveMenu, submenu, -1 ), DEV_MENU_ITEM_TYPE_MENU ) ); submenu->SetParent( this ); dev_menu_item_t* item = new dev_menu_item_t(); item->Label = name; item->Action1 = std::bind( &DevMenu::SetAsActiveMenu, this, (i32)m_SubMenus.size() ); item->Type = DEV_MENU_ITEM_TYPE_MENU; m_SubMenus.push_back( submenu ); m_Items.push_back( item ); return submenu; } void DevMenu::Compute() const { if( m_HasFocus ) { PrintName(); i32 subMenuIt = -1; for( dev_menu_item_t* item : m_Items ) { ++subMenuIt; Instance.Renderer->GetTextProgram()->Compute( Instance.Renderer->GetTextProgram()->GetFontDebug(), m_PosX + 5, ( m_PosY + 15 ) + ( subMenuIt * 15 ), ( ( subMenuIt == m_ActiveItemIndex ) ) ? colorrgbaf( 1.0f, 0.0f, 0.0f, 1.0f ) : colorrgbaf( 1.0f, 1.0f, 0.0f, 1.0f ), colorrgbaf( 0.0f ), 1.0f, item->Label.c_str() ); } } else if( m_ActiveSubMenuIndex != -1 ) { m_SubMenus[m_ActiveSubMenuIndex]->Compute(); } } void DevMenu::PrintName( bool enableHighlight ) const { Instance.Renderer->GetTextProgram()->Compute( Instance.Renderer->GetTextProgram()->GetFontDebug(), m_PosX, m_PosY, ( enableHighlight ) ? colorrgbaf( 1.0f, 0.0f, 0.0f, 1.0f ) : colorrgbaf( 1.0f, 1.0f, 0.0f, 1.0f ), colorrgbaf( 0.0f ), 1.0f, m_Name.c_str() ); } void DevMenu::MoveIndex( const i32 whereTo ) { if( m_HasFocus ) { m_ActiveItemIndex += whereTo; if( m_ActiveItemIndex < 0 ) { m_ActiveItemIndex = (i32)m_Items.size() - 1; } else if( m_ActiveItemIndex >= m_Items.size() ) { m_ActiveItemIndex = 0; } } else if( m_ActiveSubMenuIndex != -1 ) { m_SubMenus[m_ActiveSubMenuIndex]->MoveIndex( whereTo ); } } void DevMenu::OnEntrySelection() { if( m_HasFocus ) { if( m_ActiveItemIndex != -1 ) { const dev_menu_item_t* curItem = m_Items[m_ActiveItemIndex]; if( curItem->Type != DEV_MENU_ITEM_TYPE_MENU ) return; curItem->Action1(); } } else if( m_ActiveSubMenuIndex != -1 ) { m_SubMenus[m_ActiveSubMenuIndex]->OnEntrySelection(); } } void DevMenu::OnEntryUpdate( const bool incUpdate ) { if( m_HasFocus ) { if( m_ActiveItemIndex != -1 ) { const dev_menu_item_t* curItem = m_Items[m_ActiveItemIndex]; if( curItem->Type != DEV_MENU_ITEM_TYPE_VARIABLE ) return; ( incUpdate ) ? curItem->Action1() : curItem->Action2(); } } else if( m_ActiveSubMenuIndex != -1 ) { m_SubMenus[m_ActiveSubMenuIndex]->OnEntryUpdate( incUpdate ); } } IDevMenu* DevMenu::FindMenuFromString( const std::string path ) { IDevMenu* curMenu = this; if( path != "" ) { std::vector<std::string> subPath = SplitString( path, '\\' ); for( std::string piece : subPath ) { for( IDevMenu* subMenu : curMenu->GetSubMenus() ) { if( subMenu->GetName() == piece ) { curMenu = subMenu; break; } } } } return curMenu; } void DevMenu::RegisterBoolean( bool* value, std::string name, std::string path, callback_t updateRoutine ) { IDevMenu* curMenu = FindMenuFromString( path ); dev_menu_item_t* i = new dev_menu_item_t(); i->Label = name + " : " + ( ( *value ) ? "true" : "false" ); i->Type = DEV_MENU_ITEM_TYPE_VARIABLE; callback_t actionFunc = std::bind( []( bool* v, dev_menu_item_t* i, std::string n, callback_t r ) { *v = !*v; i->Label = n + " : " + ( ( *v ) ? "true" : "false" ); if( r ) r(); }, value, i, name, updateRoutine ); i->Action1 = actionFunc; i->Action2 = actionFunc; curMenu->AddItem( i ); } void DevMenu::RegisterLabelOverlay( const char* label, const i32 x, const i32 y, std::string path ) { IDevMenu* curMenu = FindMenuFromString( path ); dev_menu_item_t* i = new dev_menu_item_t(); i->Label = label; i->Type = DEV_MENU_ITEM_TYPE_STRING; curMenu->AddItem( i ); } void DevMenu::RegisterLabel( const char* label, std::string path ) { IDevMenu* curMenu = FindMenuFromString( path ); dev_menu_item_t* i = new dev_menu_item_t(); i->Label = label; i->Type = DEV_MENU_ITEM_TYPE_STRING; curMenu->AddItem( i ); } void DevMenu::RegisterFloat( f32* value, f32 step, f32 min, f32 max, std::string name, std::string path, callback_t updateRoutine ) { IDevMenu* curMenu = FindMenuFromString( path ); dev_menu_item_t* i = new dev_menu_item_t(); i->Label = name + " : " + std::to_string( *value ); i->Type = DEV_MENU_ITEM_TYPE_VARIABLE; i->Action1 = std::bind( []( f32* v, f32 s, f32 m, dev_menu_item_t* i, std::string n, callback_t r ) { *v += s; if( *v > m ) *v = m; i->Label = n + " : " + std::to_string( *v ); if( r ) r(); }, value, step, max, i, name, updateRoutine ); i->Action2 = std::bind( []( f32* v, f32 s, f32 m, dev_menu_item_t* i, std::string n, callback_t r ) { *v -= s; if( *v < m ) *v = m; i->Label = n + " : " + std::to_string( *v ); if( r ) r(); }, value, step, min, i, name, updateRoutine ); curMenu->AddItem( i ); } void DevMenu::RegisterInteger( i32* value, i32 step, i32 min, i32 max, std::string name, std::string path, callback_t updateRoutine ) { IDevMenu* curMenu = FindMenuFromString( path ); dev_menu_item_t* i = new dev_menu_item_t(); i->Label = name + " : " + std::to_string( *value ); i->Type = DEV_MENU_ITEM_TYPE_VARIABLE; i->Action1 = std::bind( []( i32* v, i32 s, i32 m, dev_menu_item_t* i, std::string n, callback_t r ) { *v += s; if( *v > m ) *v = m; i->Label = n + " : " + std::to_string( *v ); if( r ) r(); }, value, step, max, i, name, updateRoutine ); i->Action2 = std::bind( []( i32* v, i32 s, i32 m, dev_menu_item_t* i, std::string n, callback_t r ) { *v -= s; if( *v < m ) *v = m; i->Label = n + " : " + std::to_string( *v ); if( r ) r(); }, value, step, min, i, name, updateRoutine ); curMenu->AddItem( i ); } #endif
27.11245
135
0.646719
[ "vector" ]
ba1099c21004e4075c3466eec81cefa614e65f66
12,528
hpp
C++
openstudiocore/src/analysis/Analysis_Impl.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/analysis/Analysis_Impl.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/analysis/Analysis_Impl.hpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2013, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef ANALYSIS_ANALYSISDATA_IMPL_HPP #define ANALYSIS_ANALYSISDATA_IMPL_HPP #include <analysis/AnalysisAPI.hpp> #include <analysis/AnalysisObject_Impl.hpp> #include <analysis/Problem.hpp> #include <analysis/Algorithm.hpp> #include <analysis/DataPoint.hpp> #include <utilities/core/FileReference.hpp> #include <vector> namespace openstudio { class Table; namespace runmanager { class Job; } namespace analysis { struct AnalysisSerializationOptions; namespace detail { /** Analysis_Impl is a AnalysisObject_Impl that is the implementation class for Analysis.*/ class ANALYSIS_API Analysis_Impl : public AnalysisObject_Impl { Q_OBJECT; public: /** @name Constructors and Destructors */ //@{ /** Constructor for an OSM or IDF analysis with seed model not yet specified. If the seed model * is never specified before the analysis is run, the AnalysisDriver will create a blank energy * model of seedType (must be OSM or IDF) to serve as a default starting point. */ Analysis_Impl(const std::string& name, const Problem& problem, const FileReferenceType& seedType); /** Constructor for OSM analysis (weather file sepecified in Model). As no algorithm is * specified, the user is expected to add incomplete \link DataPoint DataPoints \endlink * by hand. The AnalysisDriver will then run these custom points. */ Analysis_Impl(const std::string& name, const Problem& problem, const FileReference& seed); /** Constructor for IDF analysis (specify weather file directly). As no algorithm is * specified, the user is expected to add incomplete \link DataPoint DataPoints \endlink * by hand. The AnalysisDriver will then run these custom points. */ Analysis_Impl(const std::string& name, const Problem& problem, const FileReference& seed, const FileReference& weatherFile); /** Constructor for OSM analysis (weather file sepecified in Model). Algorithm is used to * populate the Analysis with incomplete \link DataPoint DataPoints \endlink. */ Analysis_Impl(const std::string& name, const Problem& problem, const Algorithm& algorithm, const FileReference& seed); /** Constructor for IDF analysis (specify weather file directly). Algorithm is used to * populate the Analysis with incomplete \link DataPoint DataPoints \endlink. */ Analysis_Impl(const std::string& name, const Problem& problem, const Algorithm& algorithm, const FileReference& seed, const FileReference& weatherFile); /** Constructor provided for deserialization; not for general use. */ Analysis_Impl(const UUID& uuid, const UUID& versionUUID, const std::string& name, const std::string& displayName, const std::string& description, const Problem& problem, const boost::optional<Algorithm>& algorithm, const FileReference& seed, const boost::optional<FileReference>& weatherFile, const std::vector<DataPoint>& dataPoints, bool resultsAreInvalid, bool dataPointsAreInvalid); Analysis_Impl(const Analysis_Impl& other); virtual ~Analysis_Impl() {} virtual AnalysisObject clone() const; //@} /** @name Getters and Queries */ //@{ Problem problem() const; boost::optional<Algorithm> algorithm() const; FileReference seed() const; boost::optional<FileReference> weatherFile() const; std::vector<DataPoint> dataPoints() const; std::vector<DataPoint> dataPointsToQueue() const; std::vector<DataPoint> completeDataPoints() const; std::vector<DataPoint> successfulDataPoints() const; std::vector<DataPoint> failedDataPoints() const; /** Return all complete \link DataPoint DataPoints\endlink with runType() == * DataPointRunType::CloudDetailed and an empty directory(). */ std::vector<DataPoint> dataPointsNeedingDetails() const; /** Get the DataPoints with matching variableValues. VariableValues may contain Null QVariants of * the correct type, which means that any value at that position should be returned. */ std::vector<DataPoint> getDataPoints(const std::vector<QVariant>& variableValues) const; /** Get the DataPoints defined by measures. Perturbations must be translatable into a valid set * of variableValues for the problem(). */ std::vector<DataPoint> getDataPoints( const std::vector< boost::optional<Measure> >& measures) const; std::vector<DataPoint> getDataPoints(const std::string& tag) const; /** Get the DataPoint defined by measures, if it exists. Perturbations must be a valid set * of variable values for the problem(). */ boost::optional<DataPoint> getDataPoint(const std::vector<Measure>& measures) const; boost::optional<DataPoint> getDataPointByUUID(const UUID& uuid) const; boost::optional<DataPoint> getDataPointByUUID(const DataPoint& dataPoint) const; /** Flag flips to true if underlying structure of analysis changes and there are any * completeDataPoints(). */ bool resultsAreInvalid() const; /** Flag flips to true if structure of problem's variables changes and there are dataPoints(). * New data points cannot be added when analysis is in this state (dataPointsAreInvalid() == * true). */ bool dataPointsAreInvalid() const; //@} /** @name Setters */ //@{ bool setProblem(Problem& problem); bool setAlgorithm(Algorithm& algorithm); void clearAlgorithm(); /** Set seed to newSeed. Used by AnalysisDriver to point to copy of seed placed within * ProjectDatabase file structure. */ bool setSeed(const FileReference& newSeed); /** Set seed to blank model of seedType. Fails if seedType is not OSM or IDF or is incompatible * with current data. */ bool clearSeed(const FileReferenceType& seedType); bool setWeatherFile(const FileReference& newWeatherFile); void clearWeatherFile(); /** Adds a DataPoint to this analysis and returns true if the data point is not already in the * analysis and if not dataPointsAreInvalid. Returns false otherwise. Throws an * openstudio::Exception if dataPoint.variableValues() are not valid for problem(). Should be * called before running a given workflow. Usually called by Algorithm, but may also be called * directly by a user to run custom analyses. */ bool addDataPoint(DataPoint& dataPoint); /** Adds a DataPoint to this analysis and returns true if measures are valid for problem(), * the resulting DataPoint is not yet in this Analysis, and if not dataPointsAreInvalid. */ bool addDataPoint(const std::vector<Measure>& measures); /** Sets run information on a DataPoint. Returns false if dataPoint is not in this analysis by * UUID. */ bool setDataPointRunInformation(DataPoint& dataPoint, const runmanager::Job& topLevelJob, const std::vector<openstudio::path>& dakotaParametersFiles); /** Removes dataPoint from this analysis. Returns false if dataPoint is not in this analysis by * UUID. */ bool removeDataPoint(const DataPoint& dataPoint); /** Removes all dataPoints from this analysis, resets dataPointsAreInvalid flag, and * reinitializes algorithm(), if it exists. */ void removeAllDataPoints(); /** Resets dataPoint to not point to any output data and to be incomplete and not failed. */ bool clearResults(DataPoint& dataPoint); /** Resets all data points to an incomplete, not failed state, resets resultsAreInvalid flag, * and reinitializes algorithm(), if it exists. */ void clearAllResults(); //@} /** @name Actions */ //@{ /** Call this method to reset the dirty flag of this object and all its children. In general, * this method should be called after this object has been saved to the ProjectDatabase * (record constructed, database saved, and transaction committed). Returns false if the flag * cannot be cleared for some reason. */ virtual bool clearDirtyFlag(); /** Updates an existing DataPoint in this analysis. Throws an openstudio::Exception if DataPoint * is not in this analysis, or if completedJob is not complete, or was not spawned by algorithm() * acting on problem(). Should be called after a given workflow has been run. */ void updateDataPoint(DataPoint& dataPoint, const runmanager::Job& completedJob); /** Register Dakota's restart file location so that the analysis can be restarted if necessary. * Throws if dakotaAlgorithm != algorithm().get(). */ void initializeDakotaAlgorithm(DakotaAlgorithm& dakotaAlgorithm, const runmanager::Job& dakotaJob); /** Updates the DakotaAlgorithm being used by this analysis. Thows an openstudio::Exception if * DakotaAlgorithm is not being used by this analysis, or if completedJob is not complete, or * does not correspond to the proper Dakota job. Should be called when the given Dakota job * completes. */ void updateDakotaAlgorithm(const runmanager::Job& completedDakotaJob); /** Returns a csv summary of all the data points in this analysis. */ Table summaryTable() const; /// Relocate path data from originalBase to newBase. virtual void updateInputPathData(const openstudio::path& originalBase, const openstudio::path& newBase); //@} /** @name Serialization * Methods to save to json format. See AnalysisObject.hpp, openstudio::analysis::loadJSON for * the de-serialization methods. */ //@{ bool saveJSON(const openstudio::path& p, const AnalysisSerializationOptions& options, bool overwrite=false) const; std::ostream& toJSON(std::ostream& os,const AnalysisSerializationOptions& options) const; std::string toJSON(const AnalysisSerializationOptions& options) const; //@} /** @name Protected in or Absent from Public Class */ //@{ virtual QVariant toVariant() const; /** Finalizes Analysis JSON based on options. */ QVariant toVariant(const AnalysisSerializationOptions& options) const; static Analysis fromVariant(const QVariant& variant,const VersionString& version); //@} signals: void seedChanged(); protected: Problem m_problem; boost::optional<Algorithm> m_algorithm; FileReference m_seed; boost::optional<FileReference> m_weatherFile; std::vector<DataPoint> m_dataPoints; bool m_resultsAreInvalid; bool m_dataPointsAreInvalid; /** Calls AnalysisObject_Impl version and invalidates data points if appropriate. */ virtual void onChange(ChangeType changeType); private: REGISTER_LOGGER("openstudio.analysis.Analysis"); }; } // detail } // model } // openstudio #endif // ANALYSIS_ANALYSISDATA_IMPL_HPP
41.346535
155
0.669141
[ "object", "vector", "model" ]
ba10aa1846504f6cd8d32698a84e248e4c11a810
4,095
cpp
C++
Problems/CtCi6thEd/Chapter-3/sortStack.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
1
2021-07-08T01:02:06.000Z
2021-07-08T01:02:06.000Z
Problems/CtCi6thEd/Chapter-3/sortStack.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
null
null
null
Problems/CtCi6thEd/Chapter-3/sortStack.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
null
null
null
/*********************************************************************************************/ /* Problem: Sort Stack (CtCi 3.5) ********/ /*********************************************************************************************/ /* --Problem statement: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty. --Reasoning: Basically, we insert the elements of the original stack (st) into a temporary stack (temp_st) in ascending order. To do that, we take the top element of st, st.top and compare it to the top element of temp_st. If st.top < temp_st.top, we push temp_st.top to st and repeat this step until we find the right position in temp_st to insert st.top, which will be when st.top >= temp_st.top or temp_st is empty. --Time complexity: O(N^2), for the worst case where the stack elements are arranged in reverse order. --Space complexity: O(N), due to the temporary stack */ #include <iostream> #include <vector> #include "stack/stack.h" void sortStack(Stack<int> *st) { Stack<int> temp_st; while (!st->isEmpty()) { int curr = st->peek(); st->pop(); while (!temp_st.isEmpty() && curr < temp_st.peek()) { st->push(temp_st.peek()); temp_st.pop(); } temp_st.push(curr); } while (!temp_st.isEmpty()) { st->push(temp_st.peek()); temp_st.pop(); } } void display_stack(Stack<int> st) { std::cout << "All: "; while (!st.isEmpty()) { std::cout << st.peek() << " "; st.pop(); } std::cout << "\n"; } int main() { Stack<int> st; // test vector - stack elements: std::vector<int> vec{12, 3, -1, 7, 55}; // fill stack: auto it = vec.begin(); while (it != vec.end()) { st.push(*it); ++it; } std::cout << "Top: " << st.peek() << "\n"; std::cout << "Orig. stack: "; display_stack(st); std::cout << "\n"; sortStack(&st); std::cout << "Top: " << st.peek() << "\n"; std::cout << "Sorted stack: "; display_stack(st); std::cout << "\n"; st.push(33); std::cout << "Top: " << st.peek() << "\n"; std::cout << "Orig. stack: "; display_stack(st); std::cout << "\n"; sortStack(&st); std::cout << "Top: " << st.peek() << "\n"; std::cout << "Sorted stack: "; display_stack(st); std::cout << "\n"; return 0; } /* step by step exec.: 1st iter.: curr: 55 st: 7 -1 3 12 while: FALSE (temp_st IS empty) temp_st: 55 2nd iter.: curr: 7 st: -1 3 12 while: TRUE (temp_st isn't empty AND curr < temp_st.top) st: 55 -1 3 12 temp_st: empty --> while DONE temp_st: 7 3rd iter.: curr: 55 st: -1 3 12 while: FALSE (curr > temp_st.top) temp_st: 55 7 4th iter.: curr: -1 st: 3 12 while: TRUE (temp_st isn't empty AND curr < temp_st.top) st: 55 3 12 temp_st: 7 st: 7 55 3 12 temp_st: empty --> while DONE temp_st: -1 5th iter.: curr: 7 st: 55 3 12 while: FALSE (curr > temp_st.top) temp_st: 7 -1 6th iter.: curr: 55 st: 3 12 while: FALSE (curr > temp_st.top) temp_st: 55 7 -1 7th iter.: curr: 3 st: 12 while: TRUE (temp_st isn't empty AND curr < temp_st.top) st: 55 12 temp_st: 7 -1 st: 7 55 12 temp_st: -1 --> while DONE (curr > temp_st.top) temp_st: 3 -1 8th iter.: curr: 7 st: 55 12 while: FALSE (curr > temp_st.top) temp_st: 7 3 -1 9th iter.: curr: 55 st: 12 while: FALSE (curr > temp_st.top) temp_st: 55 7 3 -1 10th iter.: curr: 12 st: empty while: TRUE (temp_st isn't empty AND curr < temp_st.top) st: 55 temp_st: 7 3 -1 --> while DONE (curr > temp_st.top) temp_st: 12 7 3 -1 11th iter.: curr: 55 st: empty while: FALSE (curr > temp_st.top) temp_st: 55 12 7 3 -1 while: FALSE (st IS empty) iterate through temp_st: push top element back to st pop an element from temp_st DONE: st now is ordered */
21.108247
105
0.565079
[ "vector" ]
ba1202e871a40368d1ff92d0394b879954c1bd97
9,033
cpp
C++
dashel/dashel-common.cpp
Mobsya/dashel
3b0c81a08ec5cba8979a9c7c879b35747e06d01f
[ "BSD-3-Clause" ]
8
2015-03-24T11:06:16.000Z
2021-06-19T14:05:02.000Z
dashel/dashel-common.cpp
Mobsya/dashel
3b0c81a08ec5cba8979a9c7c879b35747e06d01f
[ "BSD-3-Clause" ]
25
2015-04-02T10:39:30.000Z
2020-12-07T16:13:05.000Z
dashel/dashel-common.cpp
Mobsya/dashel
3b0c81a08ec5cba8979a9c7c879b35747e06d01f
[ "BSD-3-Clause" ]
13
2015-08-26T11:38:05.000Z
2020-12-07T14:59:11.000Z
/* Dashel A cross-platform DAta Stream Helper Encapsulation Library Copyright (C) 2007 -- 2018: Stephane Magnenat <stephane at magnenat dot net> (http://stephane.magnenat.net) Mobots group - Laboratory of Robotics Systems, EPFL, Lausanne (http://mobots.epfl.ch) Sebastian Gerlach Kenzan Technologies (http://www.kenzantech.com) and other contributors, see readme.md file for details. 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 names of "Mobots", "Laboratory of Robotics Systems", "EPFL", "Kenzan Technologies" nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS ``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 COPYRIGHT HOLDERS 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 "dashel.h" #include "dashel-private.h" #include <algorithm> #include <ostream> #include <sstream> // clang-format off #ifndef _WIN32 #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> #else #include <winsock2.h> #endif // clang-format on /*! \file dashel-commong.cpp \brief Implementation of Dashel, A cross-platform DAta Stream Helper Encapsulation Library */ namespace Dashel { using namespace std; // frome dashe-private.h ExpandableBuffer::ExpandableBuffer(size_t size) : _data((unsigned char*)malloc(size)), _size(size), _pos(0) { } ExpandableBuffer::~ExpandableBuffer() { free(_data); } void ExpandableBuffer::clear() { _pos = 0; } void ExpandableBuffer::add(const void* data, const size_t size) { if (_pos + size > _size) { _size = max(_size * 2, _size + size); _data = (unsigned char*)realloc(_data, _size); } memcpy(_data + _pos, (unsigned char*)data, size); _pos += size; } // to be removed when we switch to C++11 string _to_string(int se) { ostringstream ostr; ostr << se; return ostr.str(); } // frome dashel.h DashelException::DashelException(Source s, int se, const char* reason, Stream* stream) : std::runtime_error(sourceToString(s) + " (" + _to_string(se) + "): " + reason), source(s), sysError(se), stream(stream) { } string DashelException::sourceToString(Source s) { // clang-format off const char* const sourceNames[] = { "Unknown cause", "Synchronisation error", "Invalid target", "Invalid operation", "Connection lost", "I/O error", "Connection failed", "Enumeration error", "Previous incoming data not read" }; // clang-format on const size_t arrayLength(sizeof(sourceNames) / sizeof(const char*)); if (s >= arrayLength) return sourceNames[0]; else return sourceNames[s]; } IPV4Address::IPV4Address(unsigned addr, unsigned short prt) : address(addr), port(prt) {} IPV4Address::IPV4Address(const std::string& name, unsigned short port) : port(port) { hostent* he = gethostbyname(name.c_str()); if (he == NULL) { #ifndef WIN32 struct in_addr addr; if (inet_aton(name.c_str(), &addr)) { address = ntohl(addr.s_addr); } else { address = INADDR_ANY; } #else // WIN32 unsigned long addr = inet_addr(name.c_str()); if (addr != INADDR_NONE) address = addr; else address = INADDR_ANY; #endif // WIN32 } else { #ifndef WIN32 address = ntohl(*((unsigned*)he->h_addr)); #else address = ntohl(*((unsigned*)he->h_addr)); #endif } } bool IPV4Address::operator==(const IPV4Address& o) const { return address == o.address && port == o.port; } bool IPV4Address::operator<(const IPV4Address& o) const { return address < o.address || (address == o.address && port < o.port); } std::string IPV4Address::hostname() const { unsigned a2 = htonl(address); struct hostent* he = gethostbyaddr((const char*)&a2, 4, AF_INET); if (he == NULL) { struct in_addr addr; addr.s_addr = a2; return std::string(inet_ntoa(addr)); } else { return std::string(he->h_name); } } std::string IPV4Address::format(const bool resolveName) const { std::ostringstream buf; unsigned a2 = htonl(address); if (resolveName) { struct hostent* he = gethostbyaddr((const char*)&a2, 4, AF_INET); if (he != NULL) { buf << "tcp:host=" << he->h_name << ";port=" << port; return buf.str(); } } struct in_addr addr; addr.s_addr = a2; buf << "tcp:host=" << inet_ntoa(addr) << ";port=" << port; return buf.str(); } void ParameterSet::add(const char* line) { char* lc = strdup(line); int spc = 0; char* param; bool storeParams = (params.size() == 0); char* protocolName = strtok(lc, ":"); // Do nothing with this. assert(protocolName); while ((param = strtok(NULL, ";")) != NULL) { char* sep = strchr(param, '='); if (sep) { *sep++ = 0; values[param] = sep; if (storeParams) params.push_back(param); } else { if (storeParams) params.push_back(param); values[params[spc]] = param; } ++spc; } free(lc); } void ParameterSet::addParam(const char* param, const char* value, bool atStart) { if (atStart) params.insert(params.begin(), 1, param); else params.push_back(param); if (value) values[param] = value; } bool ParameterSet::isSet(const char* key) const { return (values.find(key) != values.end()); } const std::string& ParameterSet::get(const char* key) const { std::map<std::string, std::string>::const_iterator it = values.find(key); if (it == values.end()) { std::string r = std::string("Parameter missing: ").append(key); throw DashelException(DashelException::InvalidTarget, 0, r.c_str()); } return it->second; } // explicit template instanciation of get() for int, unsigned, float and double template bool ParameterSet::get<bool>(const char* key) const; template int ParameterSet::get<int>(const char* key) const; template unsigned ParameterSet::get<unsigned>(const char* key) const; template float ParameterSet::get<float>(const char* key) const; template double ParameterSet::get<double>(const char* key) const; std::string ParameterSet::getString() const { std::ostringstream oss; std::vector<std::string>::const_iterator i = params.begin(); while (i != params.end()) { oss << *i << "=" << values.find(*i)->second; if (++i == params.end()) break; oss << ";"; } return oss.str(); } void ParameterSet::erase(const char* key) { std::vector<std::string>::iterator i = std::find(params.begin(), params.end(), key); if (i != params.end()) params.erase(i); std::map<std::string, std::string>::iterator j = values.find(key); if (j != values.end()) values.erase(j); } void MemoryPacketStream::write(const void* data, const size_t size) { sendBuffer.add(data, size); } void MemoryPacketStream::read(void* data, size_t size) { if (size > receptionBuffer.size()) fail(DashelException::IOError, 0, "Attempt to read past available data"); unsigned char* ptr = (unsigned char*)data; std::copy(receptionBuffer.begin(), receptionBuffer.begin() + size, ptr); receptionBuffer.erase(receptionBuffer.begin(), receptionBuffer.begin() + size); } void Hub::closeStream(Stream* stream) { streams.erase(stream); dataStreams.erase(stream); delete stream; } void StreamTypeRegistry::reg(const std::string& proto, const CreatorFunc func) { creators[proto] = func; } Stream* StreamTypeRegistry::create(const std::string& proto, const std::string& target, const Hub& hub) const { typedef CreatorMap::const_iterator ConstIt; ConstIt it(creators.find(proto)); if (it == creators.end()) return 0; const CreatorFunc& creatorFunc(it->second); return creatorFunc(target, hub); } std::string StreamTypeRegistry::list() const { std::string s; for (CreatorMap::const_iterator it = creators.begin(); it != creators.end();) { s += it->first; ++it; if (it != creators.end()) s += ", "; } return s; } }
24.680328
110
0.676077
[ "vector" ]
ba143b924b1f9db855303d3dfc18bebc0d1d1880
9,006
cpp
C++
src/main/vendors/OceanOptics/features/pixel_binning/STSPixelBinningFeature.cpp
KOLANICH/SeaBreeze
615b6c689d432c2f901a4505ed0abff5ff799e13
[ "MIT" ]
null
null
null
src/main/vendors/OceanOptics/features/pixel_binning/STSPixelBinningFeature.cpp
KOLANICH/SeaBreeze
615b6c689d432c2f901a4505ed0abff5ff799e13
[ "MIT" ]
1
2022-01-10T19:33:53.000Z
2022-02-02T14:53:07.000Z
src/main/vendors/OceanOptics/features/pixel_binning/STSPixelBinningFeature.cpp
KOLANICH/SeaBreeze
615b6c689d432c2f901a4505ed0abff5ff799e13
[ "MIT" ]
null
null
null
/***************************************************/ /** * @file STSPixelBinningFeatureBase.cpp * @date October 2015 * @author Ocean Optics, Inc. * * LICENSE: * * SeaBreeze Copyright (C) 2015, Ocean Optics Inc * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************/ #include <SeaBreeze/api/seabreezeapi/FeatureFamilies.h> #include <SeaBreeze/common/exceptions/FeatureControlException.h> #include <SeaBreeze/common/globals.h> #include <SeaBreeze/vendors/OceanOptics/features/pixel_binning/STSPixelBinningFeature.h> #include <SeaBreeze/vendors/OceanOptics/features/spectrometer/STSSpectrometerFeature.h> #include <SeaBreeze/vendors/OceanOptics/protocols/interfaces/PixelBinningProtocolInterface.h> using namespace seabreeze; using namespace seabreeze::api; using namespace std; STSPixelBinningFeature::STSPixelBinningFeature(std::vector<ProtocolHelper *> helpers, STSSpectrometerFeature *spectroFeature) : spectrometerFeature(spectroFeature) { vector<ProtocolHelper *>::iterator iter; for(iter = helpers.begin(); iter != helpers.end(); iter++) { this->protocols.push_back(*iter); } } STSPixelBinningFeature::~STSPixelBinningFeature() { } void STSPixelBinningFeature::setPixelBinningFactor(const Protocol &protocol, const Bus &bus, const unsigned char binningFactor) throw(FeatureException) { PixelBinningProtocolInterface *pb = NULL; ProtocolHelper *proto = NULL; try { proto = lookupProtocolImpl(protocol); pb = static_cast<PixelBinningProtocolInterface *>(proto); } catch(FeatureProtocolNotFoundException fpnfe) { string error( "Could not find matching protocol implementation to set pixel binning factor."); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureProtocolNotFoundException(error); } try { const unsigned char maxBinning = pb->readMaxPixelBinningFactor(bus); // The binning factor must be in the range 0-maxBinning if(binningFactor > maxBinning) { string error("Specified binning factor is not supported."); throw FeatureException(error); } pb->writePixelBinningFactor(bus, binningFactor); if(spectrometerFeature != NULL) { spectrometerFeature->setPixelBinningFactor(binningFactor); } } catch(ProtocolException &pe) { string error("Caught protocol exception: "); error += pe.what(); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureControlException(error); } } unsigned char STSPixelBinningFeature::getPixelBinningFactor(const Protocol &protocol, const Bus &bus) throw(FeatureException) { PixelBinningProtocolInterface *pb = NULL; ProtocolHelper *proto = NULL; try { proto = lookupProtocolImpl(protocol); pb = static_cast<PixelBinningProtocolInterface *>(proto); } catch(FeatureProtocolNotFoundException fpnfe) { string error( "Could not find matching protocol implementation to read pixel binning factor."); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureProtocolNotFoundException(error); } unsigned char retval = 0; try { retval = pb->readPixelBinningFactor(bus); } catch(ProtocolException &pe) { string error("Caught protocol exception: "); error += pe.what(); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureControlException(error); } return retval; } void STSPixelBinningFeature::setDefaultPixelBinningFactor(const Protocol &protocol, const Bus &bus, const unsigned char binningFactor) throw(FeatureException) { PixelBinningProtocolInterface *pb = NULL; ProtocolHelper *proto = NULL; try { proto = lookupProtocolImpl(protocol); pb = static_cast<PixelBinningProtocolInterface *>(proto); } catch(FeatureProtocolNotFoundException fpnfe) { string error( "Could not find matching protocol implementation to set pixel binning factor."); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureProtocolNotFoundException(error); } try { const unsigned char maxBinning = pb->readMaxPixelBinningFactor(bus); // The binning factor must be in the range 0-maxBinning if(binningFactor > maxBinning) { string error("Specified binning factor is not supported."); throw FeatureException(error); } pb->writeDefaultPixelBinningFactor(bus, binningFactor); } catch(ProtocolException &pe) { string error("Caught protocol exception: "); error += pe.what(); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureControlException(error); } } void STSPixelBinningFeature::setDefaultPixelBinningFactor(const Protocol &protocol, const Bus &bus) throw(FeatureException) { PixelBinningProtocolInterface *pb = NULL; ProtocolHelper *proto = NULL; try { proto = lookupProtocolImpl(protocol); pb = static_cast<PixelBinningProtocolInterface *>(proto); } catch(FeatureProtocolNotFoundException fpnfe) { string error( "Could not find matching protocol implementation to set pixel binning factor."); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureProtocolNotFoundException(error); } try { pb->writeDefaultPixelBinningFactor(bus); } catch(ProtocolException &pe) { string error("Caught protocol exception: "); error += pe.what(); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureControlException(error); } } unsigned char STSPixelBinningFeature::getDefaultPixelBinningFactor(const Protocol &protocol, const Bus &bus) throw(FeatureException) { PixelBinningProtocolInterface *pb = NULL; ProtocolHelper *proto = NULL; try { proto = lookupProtocolImpl(protocol); pb = static_cast<PixelBinningProtocolInterface *>(proto); } catch(FeatureProtocolNotFoundException fpnfe) { string error( "Could not find matching protocol implementation to read pixel binning factor."); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureProtocolNotFoundException(error); } unsigned char retval = 0; try { retval = pb->readDefaultPixelBinningFactor(bus); } catch(ProtocolException &pe) { string error("Caught protocol exception: "); error += pe.what(); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureControlException(error); } return retval; } unsigned char STSPixelBinningFeature::getMaxPixelBinningFactor(const Protocol &protocol, const Bus &bus) throw(FeatureException) { PixelBinningProtocolInterface *pb = NULL; ProtocolHelper *proto = NULL; try { proto = lookupProtocolImpl(protocol); pb = static_cast<PixelBinningProtocolInterface *>(proto); } catch(FeatureProtocolNotFoundException fpnfe) { string error( "Could not find matching protocol implementation to read pixel binning factor."); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureProtocolNotFoundException(error); } unsigned char retval = 0; try { retval = pb->readMaxPixelBinningFactor(bus); } catch(ProtocolException &pe) { string error("Caught protocol exception: "); error += pe.what(); /* FIXME: previous exception should probably be bundled up into the new exception */ throw FeatureControlException(error); } return retval; } //void STSPixelBinningFeature::setSpectrometerFeature(STSSpectrometerFeature *s) { // spectrometerFeature = s; //} // FeatureFamily STSPixelBinningFeature::getFeatureFamily() { FeatureFamilies families; return families.PIXEL_BINNING; } bool STSPixelBinningFeature::initialize(const Protocol &protocol, const Bus &bus) throw(FeatureException) { /* This doesn't need to do anything special at this point. If desired, this * could be used to read out the current setting and cache it, but that is * not strictly required. */ return true; }
35.179688
125
0.755829
[ "vector" ]
ba15ceef4e0859e40218d1625fd149c9e7aadf77
518
hpp
C++
pom/maths/operation/hash.hpp
e-Sharp/pom_gen_proc
cef7a57620d52631c1e94f71c71e0455f9e1b653
[ "MIT" ]
null
null
null
pom/maths/operation/hash.hpp
e-Sharp/pom_gen_proc
cef7a57620d52631c1e94f71c71e0455f9e1b653
[ "MIT" ]
null
null
null
pom/maths/operation/hash.hpp
e-Sharp/pom_gen_proc
cef7a57620d52631c1e94f71c71e0455f9e1b653
[ "MIT" ]
null
null
null
#pragma once #include "pom/maths/fract.hpp" #include "pom/maths/vector/concepts.hpp" #include "pom/maths/exceptions.hpp" #include <iostream> namespace pom { namespace maths { template<vector V> constexpr V hash(V v) { if(size(v) != 2) throw precondition_violation{ "Vector size was expected to be 2."}; auto k = V{{0.3183099f, 0.3678794f}}; v = v * k + V{{at(k, 1), at(k, 0)}}; auto h = -1.f + 2.f * fract(16.f * k * fract(at(v, 0) * at(v, 1) * (at(v, 0) + at(v, 1)))); return h; } }}
22.521739
95
0.594595
[ "vector" ]
ba19c9d095f3ea004ce2bf6a7b9cf0262078a5c0
10,032
hh
C++
gazebo/transport/TopicManager.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
8
2015-07-02T08:23:30.000Z
2020-11-17T19:00:38.000Z
gazebo/transport/TopicManager.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/transport/TopicManager.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
10
2015-04-22T18:33:15.000Z
2021-11-16T10:17:45.000Z
/* * Copyright 2012 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _TOPICMANAGER_HH_ #define _TOPICMANAGER_HH_ #include <boost/bind.hpp> #include <map> #include <list> #include <string> #include <vector> #include "gazebo/common/Assert.hh" #include "gazebo/common/Exception.hh" #include "gazebo/msgs/msgs.hh" #include "gazebo/common/SingletonT.hh" #include "gazebo/transport/TransportTypes.hh" #include "gazebo/transport/SubscribeOptions.hh" #include "gazebo/transport/SubscriptionTransport.hh" #include "gazebo/transport/PublicationTransport.hh" #include "gazebo/transport/ConnectionManager.hh" #include "gazebo/transport/Publisher.hh" #include "gazebo/transport/Publication.hh" #include "gazebo/transport/Subscriber.hh" namespace gazebo { namespace transport { /// \addtogroup gazebo_transport /// \{ /// \class TopicManager TopicManager.hh transport/transport.hh /// \brief Manages topics and their subscriptions class TopicManager : public SingletonT<TopicManager> { private: TopicManager(); private: virtual ~TopicManager(); /// \brief Initialize the manager public: void Init(); /// \brief Finalize the manager public: void Fini(); /// \brief Find a publication object by topic /// \param[in] _topic The topic to search for /// \return Pointer to the publication object, if found (can be null) public: PublicationPtr FindPublication(const std::string &_topic); /// \brief Add a node to the manager /// \param[in,out] _node The node to be added public: void AddNode(NodePtr _node); /// \brief Remove a node by its id /// \param[in] _id The ID of the node to be removed public: void RemoveNode(unsigned int _id); /// \brief Process all nodes under management /// \param[in] _onlyOut True means only outbound messages on nodes will be /// sent. False means nodes process both outbound and inbound messages public: void ProcessNodes(bool _onlyOut = false); /// \brief Has the topic been advertised? /// \param[in] _topic The name of the topic to check /// \return true if the topic has been advertised, false otherwise public: bool IsAdvertised(const std::string &_topic); /// \brief Subscribe to a topic /// \param[in] _options The options to use for the subscription /// \return Pointer to the newly created subscriber public: SubscriberPtr Subscribe(const SubscribeOptions &_options); /// \brief Unsubscribe from a topic. Use a Subscriber rather than /// calling this function directly /// \param[in] _topic The topic to unsubscribe from /// \param[in] _sub The node to unsubscribe public: void Unsubscribe(const std::string &_topic, const NodePtr &_sub); /// \brief Advertise on a topic /// \param[in] _topic The name of the topic /// \param[in] _queueLimit The maximum number of outgoing messages /// to queue /// \param[in] _hz Update rate for the publisher. Units are /// 1.0/seconds. /// \return Pointer to the newly created Publisher public: template<typename M> PublisherPtr Advertise(const std::string &_topic, unsigned int _queueLimit, double _hzRate) { google::protobuf::Message *msg = NULL; M msgtype; msg = dynamic_cast<google::protobuf::Message *>(&msgtype); if (!msg) gzthrow("Advertise requires a google protobuf type"); this->UpdatePublications(_topic, msg->GetTypeName()); PublisherPtr pub = PublisherPtr(new Publisher(_topic, msg->GetTypeName(), _queueLimit, _hzRate)); std::string msgTypename; PublicationPtr publication; // Connect all local subscription to the publisher msgTypename = msg->GetTypeName(); publication = this->FindPublication(_topic); GZ_ASSERT(publication != NULL, "FindPublication returned NULL"); publication->AddPublisher(pub); if (!publication->GetLocallyAdvertised()) { ConnectionManager::Instance()->Advertise(_topic, msgTypename); } publication->SetLocallyAdvertised(true); pub->SetPublication(publication); SubNodeMap::iterator iter2; SubNodeMap::iterator stEnd2 = this->subscribedNodes.end(); for (iter2 = this->subscribedNodes.begin(); iter2 != stEnd2; ++iter2) { if (iter2->first == _topic) { std::list<NodePtr>::iterator liter; std::list<NodePtr>::iterator lEnd = iter2->second.end(); for (liter = iter2->second.begin(); liter != lEnd; ++liter) { publication->AddSubscription(*liter); } } } return pub; } /// \brief Unadvertise a topic /// \param[in] _topic The topic to be unadvertised public: void Unadvertise(const std::string &_topic); /// \brief Send a message. Use a Publisher instead of calling this /// function directly. /// \param _topic Name of the topic /// \param _message The message to send. /// \param _cb Callback, used when the publish is completed. public: void Publish(const std::string &_topic, MessagePtr _message, const boost::function<void()> &_cb = NULL); /// \brief Connection a local Publisher to a remote Subscriber /// \param[in] _topic The topic to use /// \param[in] _sublink The subscription transport object to use public: void ConnectPubToSub(const std::string &_topic, const SubscriptionTransportPtr _sublink); /// \brief Connect a local Subscriber to a remote Publisher /// \param[in] _pub The publish object to use public: void ConnectSubToPub(const msgs::Publish &_pub); /// \brief Disconnect a local publisher from a remote subscriber /// \param[in] _topic The topic to be disconnected /// \param[in] _host The host to be disconnected /// \param[in] _port The port to be disconnected public: void DisconnectPubFromSub(const std::string &_topic, const std::string &_host, unsigned int _port); /// \brief Disconnect all local subscribers from a remote publisher /// \param[in] _topic The topic to be disconnected /// \param[in] _host The host to be disconnected /// \param[in] _port The port to be disconnected public: void DisconnectSubFromPub(const std::string &_topic, const std::string &_host, unsigned int _port); /// \brief Connect all subscribers on a topic to known publishers /// \param[in] _topic The topic to be connected public: void ConnectSubscribers(const std::string &_topic); /// \brief Update our list of advertised topics /// \param[in] _topic The topic to be updated /// \param[in] _msgType The type of the topic to be updated /// \return True if the provided params define a new publisher, /// false otherwise public: PublicationPtr UpdatePublications(const std::string &_topic, const std::string &_msgType); /// \brief Register a new topic namespace /// \param[in] _name The name of the new namespace public: void RegisterTopicNamespace(const std::string &_name); /// \brief Get all the topic namespaces /// \param[out] _namespaces The list of namespaces will be written here public: void GetTopicNamespaces(std::list<std::string> &_namespaces); /// \brief Get a list of all the topics. /// \return A map where keys are message types, and values are a list /// of topic names. /// \sa transport::GetAdvertisedTopics public: std::map<std::string, std::list<std::string> > GetAdvertisedTopics() const GAZEBO_DEPRECATED(1.5); /// \brief Clear all buffers public: void ClearBuffers(); /// \brief Pause or unpause processing of incoming messages /// \param[in] _pause If true pause processing; otherwse unpause public: void PauseIncoming(bool _pause); /// \brief A map of string->list of Node pointers typedef std::map<std::string, std::list<NodePtr> > SubNodeMap; private: typedef std::map<std::string, PublicationPtr> PublicationPtr_M; private: PublicationPtr_M advertisedTopics; private: PublicationPtr_M::iterator advertisedTopicsEnd; private: SubNodeMap subscribedNodes; private: std::vector<NodePtr> nodes; private: boost::recursive_mutex nodeMutex; /// \brief Used to protect subscription connection creation. private: boost::mutex subscriberMutex; private: bool pauseIncoming; // Singleton implementation private: friend class SingletonT<TopicManager>; }; /// \} } } #endif
39.968127
80
0.622807
[ "object", "vector" ]
ba214610980d1fb68dcd5b9c1f4e846f71d3a7af
2,963
cpp
C++
core/fxcrt/fx_stream.cpp
KnIfER/pdfpdf
2b918c8d05c922287efbc8858f029026cee31442
[ "BSD-3-Clause" ]
3
2019-01-12T07:06:18.000Z
2019-10-13T08:07:26.000Z
core/fxcrt/fx_stream.cpp
KnIfER/pdf
2b918c8d05c922287efbc8858f029026cee31442
[ "BSD-3-Clause" ]
null
null
null
core/fxcrt/fx_stream.cpp
KnIfER/pdf
2b918c8d05c922287efbc8858f029026cee31442
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fxcrt/fx_stream.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include "core/fxcrt/fx_safe_types.h" #include "core/fxcrt/ifxcrt_fileaccess.h" namespace { class CFX_CRTFileStream final : public IFX_SeekableStream { public: template <typename T, typename... Args> friend CFX_RetainPtr<T> pdfium::MakeRetain(Args&&... args); // IFX_SeekableStream: FX_FILESIZE GetSize() override { return m_pFile->GetSize(); } bool IsEOF() override { return GetPosition() >= GetSize(); } FX_FILESIZE GetPosition() override { return m_pFile->GetPosition(); } bool ReadBlock(void* buffer, FX_FILESIZE offset, size_t size) override { return m_pFile->ReadPos(buffer, size, offset) > 0; } size_t ReadBlock(void* buffer, size_t size) override { return m_pFile->Read(buffer, size); } bool WriteBlock(const void* buffer, FX_FILESIZE offset, size_t size) override { return !!m_pFile->WritePos(buffer, size, offset); } bool Flush() override { return m_pFile->Flush(); } private: explicit CFX_CRTFileStream(std::unique_ptr<IFXCRT_FileAccess> pFA) : m_pFile(std::move(pFA)) {} ~CFX_CRTFileStream() override {} std::unique_ptr<IFXCRT_FileAccess> m_pFile; }; } // namespace // static CFX_RetainPtr<IFX_SeekableStream> IFX_SeekableStream::CreateFromFilename( const char* filename, uint32_t dwModes) { std::unique_ptr<IFXCRT_FileAccess> pFA = IFXCRT_FileAccess::Create(); if (!pFA->Open(filename, dwModes)) return nullptr; return pdfium::MakeRetain<CFX_CRTFileStream>(std::move(pFA)); } // static CFX_RetainPtr<IFX_SeekableStream> IFX_SeekableStream::CreateFromFilename( const wchar_t* filename, uint32_t dwModes) { std::unique_ptr<IFXCRT_FileAccess> pFA = IFXCRT_FileAccess::Create(); if (!pFA->Open(filename, dwModes)) return nullptr; return pdfium::MakeRetain<CFX_CRTFileStream>(std::move(pFA)); } // static CFX_RetainPtr<IFX_SeekableReadStream> IFX_SeekableReadStream::CreateFromFilename(const char* filename) { return IFX_SeekableStream::CreateFromFilename(filename, FX_FILEMODE_ReadOnly); } bool IFX_SeekableWriteStream::WriteBlock(const void* pData, size_t size) { return WriteBlock(pData, GetSize(), size); } bool IFX_SeekableReadStream::IsEOF() { return false; } FX_FILESIZE IFX_SeekableReadStream::GetPosition() { return 0; } size_t IFX_SeekableReadStream::ReadBlock(void* buffer, size_t size) { return 0; } bool IFX_SeekableStream::WriteBlock(const void* buffer, size_t size) { return WriteBlock(buffer, GetSize(), size); } bool IFX_SeekableStream::WriteString(const CFX_ByteStringC& str) { return WriteBlock(str.c_str(), str.GetLength()); }
29.63
80
0.735403
[ "vector" ]
ba23b63eea4d95979f101ed8d1592cd3f5c0cad4
33,097
cpp
C++
src/tests/unittests/validation/RenderPipelineValidationTests.cpp
softwarecapital/google.dawn
045a02adc0c6b2d6b406507bc58131644b41dc0c
[ "Apache-2.0" ]
null
null
null
src/tests/unittests/validation/RenderPipelineValidationTests.cpp
softwarecapital/google.dawn
045a02adc0c6b2d6b406507bc58131644b41dc0c
[ "Apache-2.0" ]
null
null
null
src/tests/unittests/validation/RenderPipelineValidationTests.cpp
softwarecapital/google.dawn
045a02adc0c6b2d6b406507bc58131644b41dc0c
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 The Dawn Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 "tests/unittests/validation/ValidationTest.h" #include "common/Constants.h" #include "utils/ComboRenderPipelineDescriptor.h" #include "utils/WGPUHelpers.h" #include <cmath> #include <sstream> class RenderPipelineValidationTest : public ValidationTest { protected: void SetUp() override { ValidationTest::SetUp(); vsModule = utils::CreateShaderModule(device, R"( [[stage(vertex)]] fn main() -> [[builtin(position)]] vec4<f32> { return vec4<f32>(0.0, 0.0, 0.0, 1.0); })"); fsModule = utils::CreateShaderModule(device, R"( [[stage(fragment)]] fn main() -> [[location(0)]] vec4<f32> { return vec4<f32>(0.0, 1.0, 0.0, 1.0); })"); } wgpu::ShaderModule vsModule; wgpu::ShaderModule fsModule; }; // Test cases where creation should succeed TEST_F(RenderPipelineValidationTest, CreationSuccess) { { // New format utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; device.CreateRenderPipeline2(&descriptor); } { // Deprecated format utils::ComboRenderPipelineDescriptor descriptor(device); descriptor.vertexStage.module = vsModule; descriptor.cFragmentStage.module = fsModule; EXPECT_DEPRECATION_WARNING(device.CreateRenderPipeline(&descriptor)); } { // Vertex input should be optional utils::ComboRenderPipelineDescriptor descriptor(device); descriptor.vertexStage.module = vsModule; descriptor.cFragmentStage.module = fsModule; descriptor.vertexState = nullptr; EXPECT_DEPRECATION_WARNING(device.CreateRenderPipeline(&descriptor)); } { // Rasterization state should be optional utils::ComboRenderPipelineDescriptor descriptor(device); descriptor.vertexStage.module = vsModule; descriptor.cFragmentStage.module = fsModule; descriptor.rasterizationState = nullptr; EXPECT_DEPRECATION_WARNING(device.CreateRenderPipeline(&descriptor)); } } // Tests that depth bias parameters must not be NaN. TEST_F(RenderPipelineValidationTest, DepthBiasParameterNotBeNaN) { // Control case, depth bias parameters in ComboRenderPipeline default to 0 which is finite { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.EnableDepthStencil(); device.CreateRenderPipeline2(&descriptor); } // Infinite depth bias clamp is valid { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; wgpu::DepthStencilState* depthStencil = descriptor.EnableDepthStencil(); depthStencil->depthBiasClamp = INFINITY; device.CreateRenderPipeline2(&descriptor); } // NAN depth bias clamp is invalid { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; wgpu::DepthStencilState* depthStencil = descriptor.EnableDepthStencil(); depthStencil->depthBiasClamp = NAN; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } // Infinite depth bias slope is valid { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; wgpu::DepthStencilState* depthStencil = descriptor.EnableDepthStencil(); depthStencil->depthBiasSlopeScale = INFINITY; device.CreateRenderPipeline2(&descriptor); } // NAN depth bias slope is invalid { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; wgpu::DepthStencilState* depthStencil = descriptor.EnableDepthStencil(); depthStencil->depthBiasSlopeScale = NAN; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } // Tests that at least one color target state is required. TEST_F(RenderPipelineValidationTest, ColorTargetStateRequired) { { // This one succeeds because attachment 0 is the color attachment utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.cFragment.targetCount = 1; device.CreateRenderPipeline2(&descriptor); } { // Fail because lack of color target states (and depth/stencil state) utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.cFragment.targetCount = 0; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } // Tests that the color formats must be renderable. TEST_F(RenderPipelineValidationTest, NonRenderableFormat) { { // Succeeds because RGBA8Unorm is renderable utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.cTargets[0].format = wgpu::TextureFormat::RGBA8Unorm; device.CreateRenderPipeline2(&descriptor); } { // Fails because RG11B10Ufloat is non-renderable utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.cTargets[0].format = wgpu::TextureFormat::RG11B10Ufloat; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } // Tests that the format of the color state descriptor must match the output of the fragment shader. TEST_F(RenderPipelineValidationTest, FragmentOutputFormatCompatibility) { constexpr uint32_t kNumTextureFormatBaseType = 3u; std::array<const char*, kNumTextureFormatBaseType> kScalarTypes = {{"f32", "i32", "u32"}}; std::array<wgpu::TextureFormat, kNumTextureFormatBaseType> kColorFormats = { {wgpu::TextureFormat::RGBA8Unorm, wgpu::TextureFormat::RGBA8Sint, wgpu::TextureFormat::RGBA8Uint}}; for (size_t i = 0; i < kNumTextureFormatBaseType; ++i) { for (size_t j = 0; j < kNumTextureFormatBaseType; ++j) { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cTargets[0].format = kColorFormats[j]; std::ostringstream stream; stream << R"( [[stage(fragment)]] fn main() -> [[location(0)]] vec4<)" << kScalarTypes[i] << R"(> { var result : vec4<)" << kScalarTypes[i] << R"(>; return result; })"; descriptor.cFragment.module = utils::CreateShaderModule(device, stream.str().c_str()); if (i == j) { device.CreateRenderPipeline2(&descriptor); } else { ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } } } /// Tests that the sample count of the render pipeline must be valid. TEST_F(RenderPipelineValidationTest, SampleCount) { { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.multisample.count = 4; device.CreateRenderPipeline2(&descriptor); } { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.multisample.count = 3; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } // Tests that the sample count of the render pipeline must be equal to the one of every attachments // in the render pass. TEST_F(RenderPipelineValidationTest, SampleCountCompatibilityWithRenderPass) { constexpr uint32_t kMultisampledCount = 4; constexpr wgpu::TextureFormat kColorFormat = wgpu::TextureFormat::RGBA8Unorm; constexpr wgpu::TextureFormat kDepthStencilFormat = wgpu::TextureFormat::Depth24PlusStencil8; wgpu::TextureDescriptor baseTextureDescriptor; baseTextureDescriptor.size.width = 4; baseTextureDescriptor.size.height = 4; baseTextureDescriptor.size.depthOrArrayLayers = 1; baseTextureDescriptor.mipLevelCount = 1; baseTextureDescriptor.dimension = wgpu::TextureDimension::e2D; baseTextureDescriptor.usage = wgpu::TextureUsage::RenderAttachment; utils::ComboRenderPipelineDescriptor2 nonMultisampledPipelineDescriptor; nonMultisampledPipelineDescriptor.multisample.count = 1; nonMultisampledPipelineDescriptor.vertex.module = vsModule; nonMultisampledPipelineDescriptor.cFragment.module = fsModule; wgpu::RenderPipeline nonMultisampledPipeline = device.CreateRenderPipeline2(&nonMultisampledPipelineDescriptor); nonMultisampledPipelineDescriptor.cFragment.targetCount = 0; nonMultisampledPipelineDescriptor.EnableDepthStencil(); wgpu::RenderPipeline nonMultisampledPipelineWithDepthStencilOnly = device.CreateRenderPipeline2(&nonMultisampledPipelineDescriptor); utils::ComboRenderPipelineDescriptor2 multisampledPipelineDescriptor; multisampledPipelineDescriptor.multisample.count = kMultisampledCount; multisampledPipelineDescriptor.vertex.module = vsModule; multisampledPipelineDescriptor.cFragment.module = fsModule; wgpu::RenderPipeline multisampledPipeline = device.CreateRenderPipeline2(&multisampledPipelineDescriptor); multisampledPipelineDescriptor.cFragment.targetCount = 0; multisampledPipelineDescriptor.EnableDepthStencil(); wgpu::RenderPipeline multisampledPipelineWithDepthStencilOnly = device.CreateRenderPipeline2(&multisampledPipelineDescriptor); // It is not allowed to use multisampled render pass and non-multisampled render pipeline. { wgpu::TextureDescriptor textureDescriptor = baseTextureDescriptor; textureDescriptor.format = kColorFormat; textureDescriptor.sampleCount = kMultisampledCount; wgpu::Texture multisampledColorTexture = device.CreateTexture(&textureDescriptor); utils::ComboRenderPassDescriptor renderPassDescriptor( {multisampledColorTexture.CreateView()}); wgpu::CommandEncoder encoder = device.CreateCommandEncoder(); wgpu::RenderPassEncoder renderPass = encoder.BeginRenderPass(&renderPassDescriptor); renderPass.SetPipeline(nonMultisampledPipeline); renderPass.EndPass(); ASSERT_DEVICE_ERROR(encoder.Finish()); } { wgpu::TextureDescriptor textureDescriptor = baseTextureDescriptor; textureDescriptor.sampleCount = kMultisampledCount; textureDescriptor.format = kDepthStencilFormat; wgpu::Texture multisampledDepthStencilTexture = device.CreateTexture(&textureDescriptor); utils::ComboRenderPassDescriptor renderPassDescriptor( {}, multisampledDepthStencilTexture.CreateView()); wgpu::CommandEncoder encoder = device.CreateCommandEncoder(); wgpu::RenderPassEncoder renderPass = encoder.BeginRenderPass(&renderPassDescriptor); renderPass.SetPipeline(nonMultisampledPipelineWithDepthStencilOnly); renderPass.EndPass(); ASSERT_DEVICE_ERROR(encoder.Finish()); } // It is allowed to use multisampled render pass and multisampled render pipeline. { wgpu::TextureDescriptor textureDescriptor = baseTextureDescriptor; textureDescriptor.format = kColorFormat; textureDescriptor.sampleCount = kMultisampledCount; wgpu::Texture multisampledColorTexture = device.CreateTexture(&textureDescriptor); utils::ComboRenderPassDescriptor renderPassDescriptor( {multisampledColorTexture.CreateView()}); wgpu::CommandEncoder encoder = device.CreateCommandEncoder(); wgpu::RenderPassEncoder renderPass = encoder.BeginRenderPass(&renderPassDescriptor); renderPass.SetPipeline(multisampledPipeline); renderPass.EndPass(); encoder.Finish(); } { wgpu::TextureDescriptor textureDescriptor = baseTextureDescriptor; textureDescriptor.sampleCount = kMultisampledCount; textureDescriptor.format = kDepthStencilFormat; wgpu::Texture multisampledDepthStencilTexture = device.CreateTexture(&textureDescriptor); utils::ComboRenderPassDescriptor renderPassDescriptor( {}, multisampledDepthStencilTexture.CreateView()); wgpu::CommandEncoder encoder = device.CreateCommandEncoder(); wgpu::RenderPassEncoder renderPass = encoder.BeginRenderPass(&renderPassDescriptor); renderPass.SetPipeline(multisampledPipelineWithDepthStencilOnly); renderPass.EndPass(); encoder.Finish(); } // It is not allowed to use non-multisampled render pass and multisampled render pipeline. { wgpu::TextureDescriptor textureDescriptor = baseTextureDescriptor; textureDescriptor.format = kColorFormat; textureDescriptor.sampleCount = 1; wgpu::Texture nonMultisampledColorTexture = device.CreateTexture(&textureDescriptor); utils::ComboRenderPassDescriptor nonMultisampledRenderPassDescriptor( {nonMultisampledColorTexture.CreateView()}); wgpu::CommandEncoder encoder = device.CreateCommandEncoder(); wgpu::RenderPassEncoder renderPass = encoder.BeginRenderPass(&nonMultisampledRenderPassDescriptor); renderPass.SetPipeline(multisampledPipeline); renderPass.EndPass(); ASSERT_DEVICE_ERROR(encoder.Finish()); } { wgpu::TextureDescriptor textureDescriptor = baseTextureDescriptor; textureDescriptor.sampleCount = 1; textureDescriptor.format = kDepthStencilFormat; wgpu::Texture multisampledDepthStencilTexture = device.CreateTexture(&textureDescriptor); utils::ComboRenderPassDescriptor renderPassDescriptor( {}, multisampledDepthStencilTexture.CreateView()); wgpu::CommandEncoder encoder = device.CreateCommandEncoder(); wgpu::RenderPassEncoder renderPass = encoder.BeginRenderPass(&renderPassDescriptor); renderPass.SetPipeline(multisampledPipelineWithDepthStencilOnly); renderPass.EndPass(); ASSERT_DEVICE_ERROR(encoder.Finish()); } } // Tests that the sample count of the render pipeline must be valid // when the alphaToCoverage mode is enabled. TEST_F(RenderPipelineValidationTest, AlphaToCoverageAndSampleCount) { { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.multisample.count = 4; descriptor.multisample.alphaToCoverageEnabled = true; device.CreateRenderPipeline2(&descriptor); } { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.multisample.count = 1; descriptor.multisample.alphaToCoverageEnabled = true; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } // Tests that the texture component type in shader must match the bind group layout. TEST_F(RenderPipelineValidationTest, TextureComponentTypeCompatibility) { constexpr uint32_t kNumTextureComponentType = 3u; std::array<const char*, kNumTextureComponentType> kScalarTypes = {{"f32", "i32", "u32"}}; std::array<wgpu::TextureSampleType, kNumTextureComponentType> kTextureComponentTypes = {{ wgpu::TextureSampleType::Float, wgpu::TextureSampleType::Sint, wgpu::TextureSampleType::Uint, }}; for (size_t i = 0; i < kNumTextureComponentType; ++i) { for (size_t j = 0; j < kNumTextureComponentType; ++j) { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; std::ostringstream stream; stream << R"( [[group(0), binding(0)]] var myTexture : texture_2d<)" << kScalarTypes[i] << R"(>; [[stage(fragment)]] fn main() { textureDimensions(myTexture); })"; descriptor.cFragment.module = utils::CreateShaderModule(device, stream.str().c_str()); wgpu::BindGroupLayout bgl = utils::MakeBindGroupLayout( device, {{0, wgpu::ShaderStage::Fragment, kTextureComponentTypes[j]}}); descriptor.layout = utils::MakeBasicPipelineLayout(device, &bgl); if (i == j) { device.CreateRenderPipeline2(&descriptor); } else { ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } } } // Tests that the texture view dimension in shader must match the bind group layout. TEST_F(RenderPipelineValidationTest, TextureViewDimensionCompatibility) { constexpr uint32_t kNumTextureViewDimensions = 6u; std::array<const char*, kNumTextureViewDimensions> kTextureKeywords = {{ "texture_1d", "texture_2d", "texture_2d_array", "texture_cube", "texture_cube_array", "texture_3d", }}; std::array<wgpu::TextureViewDimension, kNumTextureViewDimensions> kTextureViewDimensions = {{ wgpu::TextureViewDimension::e1D, wgpu::TextureViewDimension::e2D, wgpu::TextureViewDimension::e2DArray, wgpu::TextureViewDimension::Cube, wgpu::TextureViewDimension::CubeArray, wgpu::TextureViewDimension::e3D, }}; for (size_t i = 0; i < kNumTextureViewDimensions; ++i) { for (size_t j = 0; j < kNumTextureViewDimensions; ++j) { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; std::ostringstream stream; stream << R"( [[group(0), binding(0)]] var myTexture : )" << kTextureKeywords[i] << R"(<f32>; [[stage(fragment)]] fn main() { textureDimensions(myTexture); })"; descriptor.cFragment.module = utils::CreateShaderModule(device, stream.str().c_str()); wgpu::BindGroupLayout bgl = utils::MakeBindGroupLayout( device, {{0, wgpu::ShaderStage::Fragment, wgpu::TextureSampleType::Float, kTextureViewDimensions[j]}}); descriptor.layout = utils::MakeBasicPipelineLayout(device, &bgl); if (i == j) { device.CreateRenderPipeline2(&descriptor); } else { ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } } } // Test that declaring a storage buffer in the vertex shader without setting pipeline layout won't // cause crash. TEST_F(RenderPipelineValidationTest, StorageBufferInVertexShaderNoLayout) { wgpu::ShaderModule vsModuleWithStorageBuffer = utils::CreateShaderModule(device, R"( [[block]] struct Dst { data : array<u32, 100>; }; [[group(0), binding(0)]] var<storage> dst : [[access(read_write)]] Dst; [[stage(vertex)]] fn main([[builtin(vertex_index)]] VertexIndex : u32) -> [[builtin(position)]] vec4<f32> { dst.data[VertexIndex] = 0x1234u; return vec4<f32>(); })"); utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.layout = nullptr; descriptor.vertex.module = vsModuleWithStorageBuffer; descriptor.cFragment.module = fsModule; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } // Tests that strip primitive topologies require an index format TEST_F(RenderPipelineValidationTest, StripIndexFormatRequired) { constexpr uint32_t kNumStripType = 2u; constexpr uint32_t kNumListType = 3u; constexpr uint32_t kNumIndexFormat = 3u; std::array<wgpu::PrimitiveTopology, kNumStripType> kStripTopologyTypes = { {wgpu::PrimitiveTopology::LineStrip, wgpu::PrimitiveTopology::TriangleStrip}}; std::array<wgpu::PrimitiveTopology, kNumListType> kListTopologyTypes = { {wgpu::PrimitiveTopology::PointList, wgpu::PrimitiveTopology::LineList, wgpu::PrimitiveTopology::TriangleList}}; std::array<wgpu::IndexFormat, kNumIndexFormat> kIndexFormatTypes = { {wgpu::IndexFormat::Undefined, wgpu::IndexFormat::Uint16, wgpu::IndexFormat::Uint32}}; for (wgpu::PrimitiveTopology primitiveTopology : kStripTopologyTypes) { for (wgpu::IndexFormat indexFormat : kIndexFormatTypes) { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.primitive.topology = primitiveTopology; descriptor.primitive.stripIndexFormat = indexFormat; if (indexFormat == wgpu::IndexFormat::Undefined) { // Fail because the index format is undefined and the primitive // topology is a strip type. ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } else { // Succeeds because the index format is given. device.CreateRenderPipeline2(&descriptor); } } } for (wgpu::PrimitiveTopology primitiveTopology : kListTopologyTypes) { for (wgpu::IndexFormat indexFormat : kIndexFormatTypes) { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.primitive.topology = primitiveTopology; descriptor.primitive.stripIndexFormat = indexFormat; if (indexFormat == wgpu::IndexFormat::Undefined) { // Succeeds even when the index format is undefined because the // primitive topology isn't a strip type. device.CreateRenderPipeline2(&descriptor); } else { ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } } } // Test that specifying a clampDepth value results in an error if the feature is not enabled. TEST_F(RenderPipelineValidationTest, ClampDepthWithoutExtension) { { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; wgpu::PrimitiveDepthClampingState clampingState; clampingState.clampDepth = true; descriptor.primitive.nextInChain = &clampingState; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; wgpu::PrimitiveDepthClampingState clampingState; clampingState.clampDepth = false; descriptor.primitive.nextInChain = &clampingState; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } // Test that depthStencil.depthCompare must not be undefiend. TEST_F(RenderPipelineValidationTest, DepthCompareUndefinedIsError) { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; descriptor.EnableDepthStencil(wgpu::TextureFormat::Depth32Float); // Control case: Always is valid. descriptor.cDepthStencil.depthCompare = wgpu::CompareFunction::Always; device.CreateRenderPipeline2(&descriptor); // Error case: Undefined is invalid. descriptor.cDepthStencil.depthCompare = wgpu::CompareFunction::Undefined; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } // Test that the entryPoint names must be present for the correct stage in the shader module. TEST_F(RenderPipelineValidationTest, EntryPointNameValidation) { wgpu::ShaderModule module = utils::CreateShaderModule(device, R"( [[stage(vertex)]] fn vertex_main() -> [[builtin(position)]] vec4<f32> { return vec4<f32>(0.0, 0.0, 0.0, 1.0); } [[stage(fragment)]] fn fragment_main() -> [[location(0)]] vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); } )"); utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = module; descriptor.vertex.entryPoint = "vertex_main"; descriptor.cFragment.module = module; descriptor.cFragment.entryPoint = "fragment_main"; // Success case. device.CreateRenderPipeline2(&descriptor); // Test for the vertex stage entryPoint name. { // The entryPoint name doesn't exist in the module. descriptor.vertex.entryPoint = "main"; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); // The entryPoint name exists, but not for the correct stage. descriptor.vertex.entryPoint = "fragment_main"; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } descriptor.vertex.entryPoint = "vertex_main"; // Test for the fragment stage entryPoint name. { // The entryPoint name doesn't exist in the module. descriptor.cFragment.entryPoint = "main"; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); // The entryPoint name exists, but not for the correct stage. descriptor.cFragment.entryPoint = "vertex_main"; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } } // Test that vertex attrib validation is for the correct entryPoint TEST_F(RenderPipelineValidationTest, VertexAttribCorrectEntryPoint) { wgpu::ShaderModule module = utils::CreateShaderModule(device, R"( [[stage(vertex)]] fn vertex0([[location(0)]] attrib0 : vec4<f32>) -> [[builtin(position)]] vec4<f32> { return attrib0; } [[stage(vertex)]] fn vertex1([[location(1)]] attrib1 : vec4<f32>) -> [[builtin(position)]] vec4<f32> { return attrib1; } )"); utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = module; descriptor.cFragment.module = fsModule; descriptor.vertex.bufferCount = 1; descriptor.cBuffers[0].attributeCount = 1; descriptor.cBuffers[0].arrayStride = 16; descriptor.cAttributes[0].format = wgpu::VertexFormat::Float32x4; descriptor.cAttributes[0].offset = 0; // Success cases, the attribute used by the entryPoint is declared in the pipeline. descriptor.vertex.entryPoint = "vertex0"; descriptor.cAttributes[0].shaderLocation = 0; device.CreateRenderPipeline2(&descriptor); descriptor.vertex.entryPoint = "vertex1"; descriptor.cAttributes[0].shaderLocation = 1; device.CreateRenderPipeline2(&descriptor); // Error cases, the attribute used by the entryPoint isn't declared in the pipeline. descriptor.vertex.entryPoint = "vertex1"; descriptor.cAttributes[0].shaderLocation = 0; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); descriptor.vertex.entryPoint = "vertex0"; descriptor.cAttributes[0].shaderLocation = 1; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } // Test that fragment output validation is for the correct entryPoint TEST_F(RenderPipelineValidationTest, FragmentOutputCorrectEntryPoint) { wgpu::ShaderModule module = utils::CreateShaderModule(device, R"( [[stage(fragment)]] fn fragmentFloat() -> [[location(0)]] vec4<f32> { return vec4<f32>(0.0, 0.0, 0.0, 0.0); } [[stage(fragment)]] fn fragmentUint() -> [[location(0)]] vec4<u32> { return vec4<u32>(0u, 0u, 0u, 0u); } )"); utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = module; // Success case, the component type matches between the pipeline and the entryPoint descriptor.cFragment.entryPoint = "fragmentFloat"; descriptor.cTargets[0].format = wgpu::TextureFormat::RGBA32Float; device.CreateRenderPipeline2(&descriptor); descriptor.cFragment.entryPoint = "fragmentUint"; descriptor.cTargets[0].format = wgpu::TextureFormat::RGBA32Uint; device.CreateRenderPipeline2(&descriptor); // Error case, the component type doesn't match between the pipeline and the entryPoint descriptor.cFragment.entryPoint = "fragmentUint"; descriptor.cTargets[0].format = wgpu::TextureFormat::RGBA32Float; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); descriptor.cFragment.entryPoint = "fragmentFloat"; descriptor.cTargets[0].format = wgpu::TextureFormat::RGBA32Uint; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } // Test that fragment output validation is for the correct entryPoint // TODO(dawn:216): Re-enable when we correctly reflect which bindings are used for an entryPoint. TEST_F(RenderPipelineValidationTest, DISABLED_BindingsFromCorrectEntryPoint) { wgpu::ShaderModule module = utils::CreateShaderModule(device, R"( [[block]] struct Uniforms { data : vec4<f32>; }; [[group(0), binding(0)]] var<uniform> var0 : Uniforms; [[group(0), binding(1)]] var<uniform> var1 : Uniforms; [[stage(vertex)]] fn vertex0() -> [[builtin(position)]] vec4<f32> { return var0.data; } [[stage(vertex)]] fn vertex1() -> [[builtin(position)]] vec4<f32> { return var1.data; } )"); wgpu::BindGroupLayout bgl0 = utils::MakeBindGroupLayout( device, {{0, wgpu::ShaderStage::Vertex, wgpu::BufferBindingType::Uniform}}); wgpu::PipelineLayout layout0 = utils::MakeBasicPipelineLayout(device, &bgl0); wgpu::BindGroupLayout bgl1 = utils::MakeBindGroupLayout( device, {{1, wgpu::ShaderStage::Vertex, wgpu::BufferBindingType::Uniform}}); wgpu::PipelineLayout layout1 = utils::MakeBasicPipelineLayout(device, &bgl1); utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = module; descriptor.cFragment.module = fsModule; // Success case, the BGL matches the bindings used by the entryPoint descriptor.vertex.entryPoint = "vertex0"; descriptor.layout = layout0; device.CreateRenderPipeline2(&descriptor); descriptor.vertex.entryPoint = "vertex1"; descriptor.layout = layout1; device.CreateRenderPipeline2(&descriptor); // Error case, the BGL doesn't match the bindings used by the entryPoint descriptor.vertex.entryPoint = "vertex1"; descriptor.layout = layout0; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); descriptor.vertex.entryPoint = "vertex0"; descriptor.layout = layout1; ASSERT_DEVICE_ERROR(device.CreateRenderPipeline2(&descriptor)); } class DepthClampingValidationTest : public RenderPipelineValidationTest { protected: WGPUDevice CreateTestDevice() override { dawn_native::DeviceDescriptor descriptor; descriptor.requiredExtensions = {"depth_clamping"}; return adapter.CreateDevice(&descriptor); } }; // Tests that specifying a clampDepth value succeeds if the extension is enabled. TEST_F(DepthClampingValidationTest, Success) { { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; wgpu::PrimitiveDepthClampingState clampingState; clampingState.clampDepth = true; descriptor.primitive.nextInChain = &clampingState; device.CreateRenderPipeline2(&descriptor); } { utils::ComboRenderPipelineDescriptor2 descriptor; descriptor.vertex.module = vsModule; descriptor.cFragment.module = fsModule; wgpu::PrimitiveDepthClampingState clampingState; clampingState.clampDepth = false; descriptor.primitive.nextInChain = &clampingState; device.CreateRenderPipeline2(&descriptor); } }
41.683879
115
0.695229
[ "render" ]
ba3089dfb8c9e98f8a5d81c509727842dbe41a6b
4,656
cpp
C++
ISA/tools.cpp
thanhdolong/VUT-FIT-BIT-Projects
077164a2b1493f9223b25e7fc51bc0e3e90020b2
[ "MIT" ]
null
null
null
ISA/tools.cpp
thanhdolong/VUT-FIT-BIT-Projects
077164a2b1493f9223b25e7fc51bc0e3e90020b2
[ "MIT" ]
null
null
null
ISA/tools.cpp
thanhdolong/VUT-FIT-BIT-Projects
077164a2b1493f9223b25e7fc51bc0e3e90020b2
[ "MIT" ]
null
null
null
// ISA Project // Variant: LDAP server // // Author: Do Long Thanh // <xdolon00@stud.fit.vutbr.cz> #include <fstream> #include <sstream> #include <getopt.h> #include <regex> #include "tools.hpp" #include "ldap.hpp" /** * Parses arguments and stores them in the class attributes. * @param argc number of arguments * @param argv array of arguments * @param ptr save information from parsing in structure * @return parsing is succesful */ int processArg(int argc, char* argv[], tOptions* ptr) { int c; struct option longOpts[] = { {"help", no_argument, NULL, 'h'}, { NULL, 0, NULL, 0 } }; int longIndex = 0; while ((c = getopt_long(argc, argv, "p:f:h", longOpts, &longIndex)) != -1) switch (c) { case 'p': for (unsigned int i=0; i<strlen(optarg); i++) { if (!isdigit(optarg[i])) callError("Value is not an integer"); } ptr->port = (int)atol(optarg); break; case 'f': ptr->file = optarg; break; case 'h': help(); case 0: help(); default: help(); } if(ptr->file.empty()) { printf("File is required\n"); exit(EXIT_FAILURE); } return EXIT_SUCCESS; } /** * Load file and creating database of users * Some parts of code are adapted from URL below. * https://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf * @param ptr path to file and port */ void loadFile(tOptions* ptr) { std::ifstream input(ptr->file); if (!input.is_open()) callError("Unable to open file"); std::string line; while (std::getline(input, line)) { if (line.size() && line[line.size() - 1] == '\r') { line = line.substr(0, line.size() - 1); } std::istringstream linestream(line); std::string item; auto newPerson = std::make_shared<person>(); getline (linestream, item, ';'); newPerson->cn = item; getline (linestream, item, ';'); newPerson->uid = item; getline (linestream, item); newPerson->email = item; universe.insert(newPerson); } input.close(); } /** * Returns the character currently pointed * custom fgetc to store position for searchRequest * @param stream The pointer to a FILE object that identifies the stream * @return Current character in the object */ int customFgetc(FILE *stream) { ++position; return fgetc(stream); } /** * Method for get length * @param stream The pointer to a FILE object that identifies the stream * @return length */ size_t getLength(FILE *stream) { int l = customFgetc(stream); if (l > 0x80) { int numbers = l - 0x80; l = 0; while (numbers > 0) { size_t octet = customFgetc(stream); octet = octet << (--numbers * 8); l += octet; } } return l; } /** * Convert request to the regex * @param stream The pointer to a FILE object that identifies the stream * @param pattern Creating regex request * @param fd Socket for sending message */ void convertSubstringToRegex(FILE *stream, size_t *len, std::string &pattern, int fd) { auto begin = position; unsigned char op = (unsigned char) customFgetc(stream); if (op < 0x80 || op > 0x82) ldapResponse(fd, LDAP_PROTOCOL_ERROR); size_t local_len = (size_t) getLength(stream); if (op == 0x81 || op == 0x82) pattern += ".*"; // Found dot and make it non-regex for (size_t i = 0; i < local_len; i++) { auto c = customFgetc(stream); if (c == '.') pattern.push_back('\\'); pattern.push_back((char) c); } if (op == 0x80 || op == 0x81) pattern += ".*"; *len -= position - begin; } /** * Handle with errors */ void callError(std::string error){ std::cerr << "ERROR: " << error << std::endl; exit(EXIT_FAILURE); } /** * Prints help and exits the program. */ void help() { std::cout << R"(LDAP server)" << std::endl << R"(Usage: ./myldap {-p <port>} -f <file>)" << std::endl << R"(Example: ./myldap -p 3042 -f ldap.csv)" << std::endl << std::endl << R"([-p] - optional attribute - port number of the host to connect (default value is 389))" << std::endl << R"([-f] - required attribute - file path to database)" << std::endl << R"(Author: Do Long Thanh <xdolon00@stud.fit.vutbr.cz>)" << std::endl; exit(EXIT_SUCCESS); }
25.866667
120
0.5625
[ "object" ]
ba336a7c6caa181755370b77e1eb9de91e1ec17f
2,876
cpp
C++
aws-cpp-sdk-migrationhubstrategy/source/model/ServerCriteria.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-migrationhubstrategy/source/model/ServerCriteria.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-migrationhubstrategy/source/model/ServerCriteria.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/migrationhubstrategy/model/ServerCriteria.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace MigrationHubStrategyRecommendations { namespace Model { namespace ServerCriteriaMapper { static const int NOT_DEFINED_HASH = HashingUtils::HashString("NOT_DEFINED"); static const int OS_NAME_HASH = HashingUtils::HashString("OS_NAME"); static const int STRATEGY_HASH = HashingUtils::HashString("STRATEGY"); static const int DESTINATION_HASH = HashingUtils::HashString("DESTINATION"); static const int SERVER_ID_HASH = HashingUtils::HashString("SERVER_ID"); ServerCriteria GetServerCriteriaForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == NOT_DEFINED_HASH) { return ServerCriteria::NOT_DEFINED; } else if (hashCode == OS_NAME_HASH) { return ServerCriteria::OS_NAME; } else if (hashCode == STRATEGY_HASH) { return ServerCriteria::STRATEGY; } else if (hashCode == DESTINATION_HASH) { return ServerCriteria::DESTINATION; } else if (hashCode == SERVER_ID_HASH) { return ServerCriteria::SERVER_ID; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ServerCriteria>(hashCode); } return ServerCriteria::NOT_SET; } Aws::String GetNameForServerCriteria(ServerCriteria enumValue) { switch(enumValue) { case ServerCriteria::NOT_DEFINED: return "NOT_DEFINED"; case ServerCriteria::OS_NAME: return "OS_NAME"; case ServerCriteria::STRATEGY: return "STRATEGY"; case ServerCriteria::DESTINATION: return "DESTINATION"; case ServerCriteria::SERVER_ID: return "SERVER_ID"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ServerCriteriaMapper } // namespace Model } // namespace MigrationHubStrategyRecommendations } // namespace Aws
31.26087
92
0.616829
[ "model" ]
ba35fe465668f4a3189800bb179e081ac185e40e
179,219
cpp
C++
test/ref_ops_test.cpp
sjw36/AMDMIGraphX
c310bc5cf9b3f8ea44823a386a1b8bd72014bf09
[ "MIT" ]
null
null
null
test/ref_ops_test.cpp
sjw36/AMDMIGraphX
c310bc5cf9b3f8ea44823a386a1b8bd72014bf09
[ "MIT" ]
null
null
null
test/ref_ops_test.cpp
sjw36/AMDMIGraphX
c310bc5cf9b3f8ea44823a386a1b8bd72014bf09
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <migraphx/literal.hpp> #include <migraphx/op/pooling.hpp> #include <migraphx/op/batch_norm_inference.hpp> #include <migraphx/instruction.hpp> #include <migraphx/quantization.hpp> #include <migraphx/ref/target.hpp> #include <migraphx/quantization.hpp> #include <migraphx/verify.hpp> #include <migraphx/onnx.hpp> #include <migraphx/make_op.hpp> #include <migraphx/serialize.hpp> #include "test.hpp" #include <migraphx/half.hpp> #include <iomanip> float sigmoid(float x) { return 1 / (1 + expf(-x)); } float elu(float a, float x) { return x > 0 ? x : a * std::expm1(x); } TEST_CASE(abs_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2}}; auto l = mm->add_literal(migraphx::literal{s, {-1, 2, -3, 4}}); mm->add_instruction(migraphx::make_op("abs"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1, 2, 3, 4}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(acos_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::double_type, {3}}; std::vector<float> data{-0.8f, 0.0f, 1.0f}; auto l = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(migraphx::make_op("acos"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {2.4980915448f, 1.5707963268f, 0.0f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(acosh_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::double_type, {3}}; std::vector<float> data{1.1f, 1.2f, 2.0f}; auto l = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(migraphx::make_op("acosh"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.4435683, 0.6223626, 1.316958}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(add_broadcast_test) { { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape a_shape{migraphx::shape::float_type, {2, 2, 3}}; std::vector<float> a_data{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; migraphx::shape b_shape{migraphx::shape::float_type, {2, 2}}; std::vector<float> b_data{0, -1, -2, -3}; uint64_t axis = 0; auto l1 = mm->add_literal(migraphx::literal{a_shape, a_data}); auto l2 = mm->add_literal(migraphx::literal{b_shape, b_data}); auto l3 = mm->add_instruction( migraphx::make_op("broadcast", {{"axis", axis}, {"dims", l1->get_shape().lens()}}), l2); mm->add_instruction(migraphx::make_op("add"), l1, l3); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); EXPECT(result.get_shape().packed()); std::vector<float> results_vector(12); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8}; EXPECT(migraphx::verify_range(results_vector, gold)); } { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape a_shape{migraphx::shape::float_type, {2, 2, 3}}; std::vector<float> a_data{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; migraphx::shape b_shape{migraphx::shape::float_type, {2, 2, 1}}; std::vector<float> b_data{0, -1, -2, -3}; auto l1 = mm->add_literal(migraphx::literal{a_shape, a_data}); auto l2 = mm->add_literal(migraphx::literal{b_shape, b_data}); auto l3 = mm->add_instruction( migraphx::make_op("multibroadcast", {{"output_lens", {2, 2, 3}}}), l1); auto l4 = mm->add_instruction( migraphx::make_op("multibroadcast", {{"output_lens", {2, 2, 3}}}), l2); mm->add_instruction(migraphx::make_op("add"), l3, l4); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); EXPECT(result.get_shape().packed()); std::vector<float> results_vector(12); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8}; EXPECT(migraphx::verify_range(results_vector, gold)); } } TEST_CASE(add_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l1 = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); auto l2 = mm->add_literal(migraphx::literal{s, {1, 2, 3}}); mm->add_instruction(migraphx::make_op("add"), l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0, 2, 4}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(argmax_test_0) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data = {1.2255, 1.6834, -2.0305, -0.3221, 0.4701, 0.2583, 0.7545, 2.5758, -1.6849, 0.0928, 0.9022, -0.8765, -0.4090, 0.9301, 2.0724, -1.5706, 0.4867, -0.1493, 0.6957, -0.2179, 0.7142, 0.7177, 0.0183, 1.3497}; std::vector<int64_t> res_gold = {0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1}; migraphx::shape data_shape{migraphx::shape::float_type, {2, 3, 4}}; auto dl = mm->add_literal(migraphx::literal{data_shape, data}); mm->add_instruction(migraphx::make_op("argmax", {{"axis", 0}}), dl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int64_t> result_vec; result.visit([&](auto output) { result_vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vec, res_gold)); } TEST_CASE(argmax_test_1) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data = {1.2255, 1.6834, -2.0305, -0.3221, 0.4701, 0.2583, 0.7545, 2.5758, -1.6849, 0.0928, 0.9022, -0.8765, -0.4090, 0.9301, 2.0724, -1.5706, 0.4867, -0.1493, 0.6957, -0.2179, 0.7142, 0.7177, 0.0183, 1.3497}; std::vector<int64_t> res_gold = {0, 0, 2, 1, 2, 0, 0, 2}; migraphx::shape data_shape{migraphx::shape::float_type, {2, 3, 4}}; auto dl = mm->add_literal(migraphx::literal{data_shape, data}); mm->add_instruction(migraphx::make_op("argmax", {{"axis", 1}}), dl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int64_t> result_vec; result.visit([&](auto output) { result_vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vec, res_gold)); } TEST_CASE(argmax_test_2) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data = {1.2255, 1.6834, -2.0305, -0.3221, 0.4701, 0.2583, 0.7545, 2.5758, -1.6849, 0.0928, 0.9022, -0.8765, -0.4090, 0.9301, 2.0724, -1.5706, 0.4867, -0.1493, 0.6957, -0.2179, 0.7142, 0.7177, 0.0183, 1.3497}; std::vector<int64_t> res_gold = {1, 3, 2, 2, 2, 3}; migraphx::shape data_shape{migraphx::shape::float_type, {2, 3, 4}}; auto dl = mm->add_literal(migraphx::literal{data_shape, data}); mm->add_instruction(migraphx::make_op("argmax", {{"axis", 2}}), dl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int64_t> result_vec; result.visit([&](auto output) { result_vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vec, res_gold)); } TEST_CASE(argmax_test_neg_2) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data = {1.2255, 1.6834, -2.0305, -0.3221, 0.4701, 0.2583, 0.7545, 2.5758, -1.6849, 0.0928, 0.9022, -0.8765, -0.4090, 0.9301, 2.0724, -1.5706, 0.4867, -0.1493, 0.6957, -0.2179, 0.7142, 0.7177, 0.0183, 1.3497}; std::vector<int64_t> res_gold = {0, 0, 2, 1, 2, 0, 0, 2}; migraphx::shape data_shape{migraphx::shape::float_type, {2, 3, 4}}; auto dl = mm->add_literal(migraphx::literal{data_shape, data}); mm->add_instruction(migraphx::make_op("argmax", {{"axis", -2}}), dl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int64_t> result_vec; result.visit([&](auto output) { result_vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vec, res_gold)); } TEST_CASE(argmin_test_0) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data = {1.2255, 1.6834, -2.0305, -0.3221, 0.4701, 0.2583, 0.7545, 2.5758, -1.6849, 0.0928, 0.9022, -0.8765, -0.4090, 0.9301, 2.0724, -1.5706, 0.4867, -0.1493, 0.6957, -0.2179, 0.7142, 0.7177, 0.0183, 1.3497}; std::vector<int64_t> res_gold = {1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0}; migraphx::shape data_shape{migraphx::shape::float_type, {2, 3, 4}}; auto dl = mm->add_literal(migraphx::literal{data_shape, data}); mm->add_instruction(migraphx::make_op("argmin", {{"axis", 0}}), dl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int64_t> result_vec; result.visit([&](auto output) { result_vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vec, res_gold)); } TEST_CASE(argmin_test_1) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data = {1.2255, 1.6834, -2.0305, -0.3221, 0.4701, 0.2583, 0.7545, 2.5758, -1.6849, 0.0928, 0.9022, -0.8765, -0.4090, 0.9301, 2.0724, -1.5706, 0.4867, -0.1493, 0.6957, -0.2179, 0.7142, 0.7177, 0.0183, 1.3497}; std::vector<int64_t> res_gold = {2, 2, 0, 2, 0, 1, 2, 0}; migraphx::shape data_shape{migraphx::shape::float_type, {2, 3, 4}}; auto dl = mm->add_literal(migraphx::literal{data_shape, data}); mm->add_instruction(migraphx::make_op("argmin", {{"axis", 1}}), dl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int64_t> result_vec; result.visit([&](auto output) { result_vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vec, res_gold)); } TEST_CASE(argmin_test_2) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data = {1.2255, 1.6834, -2.0305, -0.3221, 0.4701, 0.2583, 0.7545, 2.5758, -1.6849, 0.0928, 0.9022, -0.8765, -0.4090, 0.9301, 2.0724, -1.5706, 0.4867, -0.1493, 0.6957, -0.2179, 0.7142, 0.7177, 0.0183, 1.3497}; std::vector<int64_t> res_gold = {2, 1, 0, 3, 3, 2}; migraphx::shape data_shape{migraphx::shape::float_type, {2, 3, 4}}; auto dl = mm->add_literal(migraphx::literal{data_shape, data}); mm->add_instruction(migraphx::make_op("argmin", {{"axis", 2}}), dl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int64_t> result_vec; result.visit([&](auto output) { result_vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vec, res_gold)); } TEST_CASE(argmin_test_neg_1) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data = {1.2255, 1.6834, -2.0305, -0.3221, 0.4701, 0.2583, 0.7545, 2.5758, -1.6849, 0.0928, 0.9022, -0.8765, -0.4090, 0.9301, 2.0724, -1.5706, 0.4867, -0.1493, 0.6957, -0.2179, 0.7142, 0.7177, 0.0183, 1.3497}; std::vector<int64_t> res_gold = {2, 1, 0, 3, 3, 2}; migraphx::shape data_shape{migraphx::shape::float_type, {2, 3, 4}}; auto dl = mm->add_literal(migraphx::literal{data_shape, data}); mm->add_instruction(migraphx::make_op("argmin", {{"axis", -1}}), dl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int64_t> result_vec; result.visit([&](auto output) { result_vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vec, res_gold)); } TEST_CASE(asin_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; std::vector<float> data{-0.5f, 0.0f, 0.9f}; auto l = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(migraphx::make_op("asin"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-0.5235987756f, 0.f, 1.119769515}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(asinh_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; std::vector<float> data{-0.5f, 0.0f, 0.9f}; auto l = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(migraphx::make_op("asinh"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-0.481211841, 0, 0.808866858}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(atan_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::double_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); mm->add_instruction(migraphx::make_op("atan"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-0.7853981634f, 0.0f, 0.7853981634f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(atanh_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::double_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {0.4435683, 0.6223626, 0.316958}}); mm->add_instruction(migraphx::make_op("atanh"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.476664424, 0.728852153, 0.328261733}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(avgpool_test) { // 1D case 1, input is 3D { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {1, 3, 4}}; auto op = migraphx::op::pooling{"average"}; op.lengths = {2}; op.padding = {0}; op.stride = {1}; std::vector<float> data{0.3, 0.2, 0.4, 0.1, 0.8, 0.5, 0.9, 0.1, 0.1, 0.7, 0.1, 0.6}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0.25, 0.3, 0.25, 0.65, 0.7, 0.5, 0.4, 0.4, 0.35}; EXPECT(migraphx::verify_range(results_vector, gold)); } // 1D case 2, stride 2 { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {2, 2, 4}}; auto op = migraphx::op::pooling{"average"}; op.lengths = {2}; op.padding = {1}; op.stride = {2}; std::vector<float> data{1.6321, -2.4186, 0.2239, -1.4232, 0.8158, 0.4103, -0.3149, -0.1361, -0.3442, 2.007, 0.4331, 1.5295, 0.9965, 0.4766, 1.0942, -0.2915}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.6321, -1.0974, -1.4232, 0.8158, 0.0477, -0.1361, -0.3442, 1.22005, 1.5295, 0.9965, 0.7854, -0.2915}; EXPECT(migraphx::verify_range(results_vector, gold)); } // 3D, input is 5D { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {2, 2, 3, 3, 3}}; auto op = migraphx::op::pooling{"average"}; op.lengths = {2, 2, 2}; op.padding = {0, 0, 0}; op.stride = {1, 1, 1}; std::vector<float> data{ -0.179, -1.756, 0.651, 1.955, 1.87, -0.604, 0.247, 0.449, -0.137, 1.187, 1.593, 0.424, 2.698, -0.104, -0.069, -1.293, 0.538, 1.291, 0.974, 1.096, 0.74, -0.669, -1.08, -1.041, -1.407, 1.43, -0.211, -0.017, 0.532, 1.276, 0.627, 0.236, -0.396, -0.204, 0.501, -0.599, -1.414, -0.615, -0.274, 0.168, -0.144, 0.5, 1.42, 1.082, -0.952, -0.846, -1.244, 1.475, 1.246, 1.344, -1.722, -1.24, -0.851, 0.06, 0.507, 0.762, -0.007, -1.484, 1.028, 0.317, 1.077, -1.289, 0.875, -0.417, -0.673, 1.715, -0.307, 0.264, -0.973, 1.412, 2.561, -0.515, -0.201, 0.827, -1.231, 1.958, -0.552, 0.036, -0.993, -0.859, -1.458, -0.575, 0.048, -0.779, -1.025, -1.135, 1.166, -0.131, 0.726, 0.52, 0.467, -0.494, 0.675, 0.203, -0.63, -0.918, -0.5, -1.395, 1.39, 1.705, 0.444, -0.835, -0.506, 0.101, 0.602, 0.543, 0.357, 1.042}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{ 0.908, 0.250625, 0.795, 0.40425, 0.711875, 0.194875, 0.014125, 0.09425, -0.078375, 0.139375, 0.46075, 0.0285, -0.188125, -0.085, 0.378125, -0.085375, -0.04, 0.304125, 0.40775, 0.2835, 0.112375, -0.073375, 0.4355, -0.187, -0.392625, -0.258375, -0.485875, -0.0345, 0.16125, -0.131875, -0.228375, 0.068625}; EXPECT(migraphx::verify_range(results_vector, gold)); } } TEST_CASE(batch_norm_1d_per_actv_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape x_shape{migraphx::shape::float_type, {2, 2, 4}}; migraphx::shape c_shape(migraphx::shape::float_type, {2, 4}); std::vector<float> x_data = {0.3547, 0.477, -1.8575, 0.663, -0.1881, -0.5113, -0.1803, -0.5915, -0.1552, 0.9821, 1.827, 0.0558, -0.0417, -1.0693, 1.9948, -0.7448}; std::vector<float> scale_data = { -0.3181, -0.3885, 1.655, 0.0704, -0.2565, -1.1761, -0.3751, 0.1057}; std::vector<float> bias_data = { -1.2118, -2.1156, 0.0046, -0.1341, -0.2724, -1.0718, 0.5535, -0.889}; std::vector<float> mean_data = { 0.0997, 0.7295, -0.0153, 0.3594, -0.1149, -0.7903, 0.9073, -0.6681}; std::vector<float> variance_data = { 0.13, 0.1276, 6.7878, 0.1843, 0.0107, 0.1556, 2.3655, 0.0117}; auto x = mm->add_literal(migraphx::literal{x_shape, x_data}); auto scale = mm->add_literal(migraphx::literal{c_shape, scale_data}); auto bias = mm->add_literal(migraphx::literal{c_shape, bias_data}); auto mean = mm->add_literal(migraphx::literal{c_shape, mean_data}); auto variance = mm->add_literal(migraphx::literal{c_shape, variance_data}); mm->add_instruction( migraphx::make_op( "batch_norm_inference", {{"epsilon", 1e-6}, {"momentum", 0.9}, {"bn_mode", migraphx::to_value(migraphx::op::batch_norm_inference::per_activation)}}), x, scale, bias, mean, variance); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> result_vector; result.visit([&](auto output) { result_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-1.43677, -1.84098, -1.16563, -0.0843136, -0.090896, -1.90364, 0.81875, -0.81415, -0.986915, -2.39032, 1.17489, -0.183886, -0.453904, -0.239955, 0.288275, -0.963948}; EXPECT(migraphx::verify_range(result_vector, gold)); } TEST_CASE(batch_norm_1d_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape x_shape{migraphx::shape::float_type, {2, 3, 4}}; migraphx::shape c_shape(migraphx::shape::float_type, {3}); std::vector<float> x_data = {0.7253, -0.6356, 0.4606, -0.8689, -1.1932, 0.4538, -1.0018, -0.365, -0.214, -0.9553, -0.7672, 0.2331, -0.8416, -0.6142, 0.0814, 0.2498, -0.6706, 1.4872, 0.5112, -1.5212, -0.9126, 0.0735, 1.085, -0.3417}; std::vector<float> scale_data = {1.1, 1.2, 1.3}; std::vector<float> bias_data = {0.1, 0.2, 0.3}; std::vector<float> mean_data = {-0.1804, -0.2875, -0.2249}; std::vector<float> variance_data = {2.7914, 7.3424, 3.3287}; auto x = mm->add_literal(migraphx::literal{x_shape, x_data}); auto scale = mm->add_literal(migraphx::literal{c_shape, scale_data}); auto bias = mm->add_literal(migraphx::literal{c_shape, bias_data}); auto mean = mm->add_literal(migraphx::literal{c_shape, mean_data}); auto variance = mm->add_literal(migraphx::literal{c_shape, variance_data}); mm->add_instruction(migraphx::make_op("batch_norm_inference", {{"epsilon", 1e-5}}), x, scale, bias, mean, variance); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> result_vector; result.visit([&](auto output) { result_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.696301, -0.199697, 0.522026, -0.353299, -0.201094, 0.528289, -0.116332, 0.165679, 0.307767, -0.220435, -0.086407, 0.62634, -0.335325, -0.185608, 0.272366, 0.383238, 0.0303421, 0.985936, 0.553709, -0.346351, -0.190009, 0.51262, 1.23335, 0.216776}; EXPECT(migraphx::verify_range(result_vector, gold)); } TEST_CASE(batch_norm_3d_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape x_shape{migraphx::shape::float_type, {2, 2, 2, 2, 2}}; migraphx::shape c_shape(migraphx::shape::float_type, {2}); std::vector<float> x_data = {-1.0833, 1.9681, 1.2075, -0.723, -0.4076, -0.8738, 0.5853, -0.5357, 1.734, 0.7904, 0.6953, -0.468, -0.425, 0.6895, 0.0096, 0.4205, -0.1749, 1.2821, 2.1453, -0.8538, 1.0687, 0.0906, 0.0714, -1.3079, -0.6376, 1.3023, 0.945, 0.0927, -0.7421, -1.4341, -1.0309, 1.5153}; std::vector<float> scale_data = {1.1, 1.3}; std::vector<float> bias_data = {0.1, 0.2}; std::vector<float> mean_data = {0.1537, 0.2161}; std::vector<float> variance_data = {18.0805, 13.3906}; auto x = mm->add_literal(migraphx::literal{x_shape, x_data}); auto scale = mm->add_literal(migraphx::literal{c_shape, scale_data}); auto bias = mm->add_literal(migraphx::literal{c_shape, bias_data}); auto mean = mm->add_literal(migraphx::literal{c_shape, mean_data}); auto variance = mm->add_literal(migraphx::literal{c_shape, variance_data}); mm->add_instruction(migraphx::make_op("batch_norm_inference"), x, scale, bias, mean, variance); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> result_vector; result.visit([&](auto output) { result_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = { -0.220005, 0.569376, 0.372612, -0.126798, -0.0452053, -0.165809, 0.211653, -0.0783441, 0.739245, 0.404024, 0.370239, -0.0430317, -0.0277556, 0.368179, 0.126639, 0.272615, 0.0149929, 0.391911, 0.615216, -0.160635, 0.336706, 0.0836764, 0.0787094, -0.278108, -0.103283, 0.585881, 0.458947, 0.156161, -0.140408, -0.386246, -0.243006, 0.661551}; EXPECT(migraphx::verify_range(result_vector, gold)); } TEST_CASE(batch_norm_inference_test) { migraphx::program p; auto* mm = p.get_main_module(); const size_t width = 2; const size_t height = 2; const size_t channels = 4; const size_t batches = 2; const float x_val = 8.0; const float mean_val = 2.0; const float variance_val = 4.0; const float scale_val = 2.0f; const float bias_val = 1.0f; const float output_val = scale_val * (x_val - mean_val) / (std::sqrt(variance_val)) + bias_val; migraphx::shape s{migraphx::shape::float_type, {batches, channels, height, width}}; migraphx::shape vars{migraphx::shape::float_type, {channels}}; std::vector<float> x_data(width * height * channels * batches); std::vector<float> scale_data(channels); std::vector<float> bias_data(channels); std::vector<float> mean_data(channels); std::vector<float> variance_data(channels); std::fill(x_data.begin(), x_data.end(), x_val); std::fill(mean_data.begin(), mean_data.end(), mean_val); std::fill(variance_data.begin(), variance_data.end(), variance_val); std::fill(scale_data.begin(), scale_data.end(), scale_val); std::fill(bias_data.begin(), bias_data.end(), bias_val); auto x = mm->add_literal(migraphx::literal{s, x_data}); auto scale = mm->add_literal(migraphx::literal{vars, scale_data}); auto bias = mm->add_literal(migraphx::literal{vars, bias_data}); auto mean = mm->add_literal(migraphx::literal{vars, mean_data}); auto variance = mm->add_literal(migraphx::literal{vars, variance_data}); mm->add_instruction(migraphx::make_op("batch_norm_inference"), x, scale, bias, mean, variance); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> result_vector(width * height * channels * batches); std::vector<float> gold(width * height * channels * batches); std::fill(gold.begin(), gold.end(), output_val); result.visit([&](auto output) { result_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(result_vector, gold)); } TEST_CASE(broadcast_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape a_shape{migraphx::shape::int32_type, {2, 2}}; std::vector<int32_t> a_data{0, 0, 0, 0}; migraphx::shape b_shape{migraphx::shape::int32_type, {2}}; std::vector<int32_t> b_data{-2, -3}; uint64_t axis = 0; auto l1 = mm->add_literal(migraphx::literal{a_shape, a_data}); auto l2 = mm->add_literal(migraphx::literal{b_shape, b_data}); mm->add_instruction( migraphx::make_op("broadcast", {{"axis", axis}, {"dims", l1->get_shape().lens()}}), l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); auto output = result.get<int32_t>(); EXPECT(output(0, 0) == -2); EXPECT(output(0, 1) == -2); EXPECT(output(1, 0) == -3); EXPECT(output(1, 1) == -3); } TEST_CASE(ceil_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {9}}; auto l = mm->add_literal(migraphx::literal{s, {1.1, 1.5, 1.6, -1.1, -1.5, -1.6, 0.0, 2.0, -2.0}}); mm->add_instruction(migraphx::make_op("ceil"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {2.0, 2.0, 2.0, -1.0, -1.0, -1.0, 0.0, 2.0, -2.0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(clip_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {-1.0, 0.0, 10.0}}); auto min_val = mm->add_literal(0.0f); auto max_val = mm->add_literal(6.0f); min_val = mm->add_instruction(migraphx::make_op("multibroadcast", {{"output_lens", {3}}}), min_val); max_val = mm->add_instruction(migraphx::make_op("multibroadcast", {{"output_lens", {3}}}), max_val); mm->add_instruction(migraphx::make_op("clip"), l, min_val, max_val); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.0, 0.0, 6.0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(concat_test) { { migraphx::program p; auto* mm = p.get_main_module(); int axis = 1; std::vector<int> data0 = {0, 1, 5, 6}; std::vector<int> data1 = {2, 3, 4, 7, 8, 9}; std::vector<int> data2 = {10, 20}; migraphx::shape s0{migraphx::shape::int32_type, {2, 2}}; migraphx::shape s1{migraphx::shape::int32_type, {2, 3}}; migraphx::shape s2{migraphx::shape::int32_type, {2, 1}}; auto l0 = mm->add_literal(migraphx::literal{s0, data0}); auto l1 = mm->add_literal(migraphx::literal{s1, data1}); auto l2 = mm->add_literal(migraphx::literal{s2, data2}); mm->add_instruction(migraphx::make_op("concat", {{"axis", axis}}), l0, l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> gold = {0, 1, 2, 3, 4, 10, 5, 6, 7, 8, 9, 20}; std::vector<int> results_vector(2 * 6); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); EXPECT(migraphx::verify_range(result.get_shape().lens(), std::vector<std::size_t>({2, 6}))); EXPECT( migraphx::verify_range(result.get_shape().strides(), std::vector<std::size_t>({6, 1}))); } { migraphx::program p; auto* mm = p.get_main_module(); int axis = -1; std::vector<int> data0 = {0, 1, 5, 6}; std::vector<int> data1 = {2, 3, 4, 7, 8, 9}; std::vector<int> data2 = {10, 20}; migraphx::shape s0{migraphx::shape::int32_type, {2, 2}}; migraphx::shape s1{migraphx::shape::int32_type, {2, 3}}; migraphx::shape s2{migraphx::shape::int32_type, {2, 1}}; auto l0 = mm->add_literal(migraphx::literal{s0, data0}); auto l1 = mm->add_literal(migraphx::literal{s1, data1}); auto l2 = mm->add_literal(migraphx::literal{s2, data2}); mm->add_instruction(migraphx::make_op("concat", {{"axis", axis}}), l0, l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> gold = {0, 1, 2, 3, 4, 10, 5, 6, 7, 8, 9, 20}; std::vector<int> results_vector(2 * 6); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); EXPECT(migraphx::verify_range(result.get_shape().lens(), std::vector<std::size_t>({2, 6}))); EXPECT( migraphx::verify_range(result.get_shape().strides(), std::vector<std::size_t>({6, 1}))); } { migraphx::program p; auto* mm = p.get_main_module(); int axis = 0; std::vector<int> data0 = {0, 1, 2, 3}; std::vector<int> data1 = {4, 5, 6, 7, 8, 9}; std::vector<int> data2 = {10, 11}; migraphx::shape s0{migraphx::shape::int32_type, {2, 2}}; migraphx::shape s1{migraphx::shape::int32_type, {3, 2}}; migraphx::shape s2{migraphx::shape::int32_type, {1, 2}}; auto l0 = mm->add_literal(migraphx::literal{s0, data0}); auto l1 = mm->add_literal(migraphx::literal{s1, data1}); auto l2 = mm->add_literal(migraphx::literal{s2, data2}); mm->add_instruction(migraphx::make_op("concat", {{"axis", axis}}), l0, l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> gold = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; std::vector<int> results_vector(6 * 2); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); EXPECT(migraphx::verify_range(result.get_shape().lens(), std::vector<std::size_t>({6, 2}))); EXPECT( migraphx::verify_range(result.get_shape().strides(), std::vector<std::size_t>({2, 1}))); } { migraphx::program p; auto* mm = p.get_main_module(); int axis = -2; std::vector<int> data0 = {0, 1, 2, 3}; std::vector<int> data1 = {4, 5, 6, 7, 8, 9}; std::vector<int> data2 = {10, 11}; migraphx::shape s0{migraphx::shape::int32_type, {2, 2}}; migraphx::shape s1{migraphx::shape::int32_type, {3, 2}}; migraphx::shape s2{migraphx::shape::int32_type, {1, 2}}; auto l0 = mm->add_literal(migraphx::literal{s0, data0}); auto l1 = mm->add_literal(migraphx::literal{s1, data1}); auto l2 = mm->add_literal(migraphx::literal{s2, data2}); mm->add_instruction(migraphx::make_op("concat", {{"axis", axis}}), l0, l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> gold = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; std::vector<int> results_vector(6 * 2); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); EXPECT(migraphx::verify_range(result.get_shape().lens(), std::vector<std::size_t>({6, 2}))); EXPECT( migraphx::verify_range(result.get_shape().strides(), std::vector<std::size_t>({2, 1}))); } } TEST_CASE(contiguous_test) { migraphx::shape a_shape{migraphx::shape::float_type, {1, 3, 2, 2}, {12, 1, 6, 3}}; std::vector<float> data(12); std::iota(data.begin(), data.end(), 0); migraphx::program p; auto* mm = p.get_main_module(); auto l = mm->add_literal(migraphx::literal{a_shape, data}); mm->add_instruction(migraphx::make_op("contiguous"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(12); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<size_t> new_lens = {1, 3, 2, 2}; std::vector<size_t> new_strides = {12, 1, 6, 3}; EXPECT(migraphx::verify_range(results_vector, data)); } TEST_CASE(conv2d_padding_stride_test) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { 2.71567607, -0.9960829, 0.91671127, 0.28140706, 0.63235772, 0.08077253, 0.80927712, -0.59108931, -1.05421555, -2.76622486, -0.85044265, -0.52049929, 0.67726439, -0.65290606, 0.02345525, -0.33579525, 0.38901961, 1.05473483, -1.31188095, 1.8963089, -0.07265259, 0.947339, 0.41949373, -0.70814759, 0.25892952, 1.07311416, 1.2571274, -0.62318051, -0.19951548, -0.94232577, -0.29393643, 0.42292568, -0.80230367, 1.40909171, 0.63617158, 0.13900366, 1.09253144, -0.15265895, 1.54781747, 0.72780299, 1.09189606, -0.38068101, 0.97057933, -0.58958799, 1.56188643, 0.21474874, 0.58725154, -1.27097559, -0.03024297, 1.09437096, -0.4897908, 0.34838957, -1.31042492, -1.69069934, 0.86956722, -0.40457946, 0.46691212, 1.29273605, 0.26464137, 0.22073045, -1.02178168, 0.22163901, -1.84387338, 0.75522131, -0.45775682, -0.42241111, -1.50944722, 1.07256448, -1.95876884, -0.28106022, 0.3341668, 2.13129425, -1.14728117, -1.06555498, -0.298444, -0.88322699, -0.65866792, -2.06007552, 0.01374334, 0.45612028, 0.52715492, 1.01914406, -1.72659791, 0.80650896, 0.16860051, 2.24112225, -0.78620857, 0.36566174, -0.07020134, -0.47976932, -0.68230027, -0.94711417, -0.54506505, 1.66504931, -0.71860826, 0.61132306}; std::vector<float> c = { -0.14601797, -0.13000923, 0.06521662, 0.06178288, -0.11083675, 0.10154136, 0.09990512, 0.06030385, -0.11374587, -0.17523311, -0.14344215, 0.17802463, 0.06300922, -0.15325832, 0.07066704, 0.05166031, 0.00615084, -0.02606523, 0.08083995, -0.17913306, 0.0624622, 0.0735731, -0.04198661, -0.0164391, -0.06374192, 0.16569914, 0.10681538, 0.07370754, 0.02802075, 0.00282027, 0.15104802, -0.11084409, -0.00197773, 0.07924436, 0.03528272, 0.04765259, -0.15896152, 0.07917164, 0.12125669, -0.1154705, -0.11999125, 0.12749968, -0.06269585, 0.18658121, -0.03944227, 0.0111798, -0.17731084, 0.11789055, -0.09982193, 0.08142821, 0.0729029, 0.11303909, 0.12735154, 0.03885292}; std::vector<float> s = {-0.20817225, 0.87965256, 0.14958936, -1.24887264, -0.06540672, 0.20778663, 0.40456355, -0.99900877, 0.4917807, 0.1994698, 0.64205718, 0.37798831, -0.25315839, 0.44276932, -0.16138598, 0.79344082}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 4, 4}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); migraphx::shape c_shape{migraphx::shape::float_type, {2, 3, 3, 3}}; auto cl = mm->add_literal(migraphx::literal{c_shape, c}); mm->add_instruction( migraphx::make_op("convolution", {{"padding", {1, 1}}, {"stride", {2, 2}}}), al, cl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(16); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(conv2d_padding_test) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { 2.71567607, -0.9960829, 0.91671127, 0.28140706, 0.63235772, 0.08077253, 0.80927712, -0.59108931, -1.05421555, -2.76622486, -0.85044265, -0.52049929, 0.67726439, -0.65290606, 0.02345525, -0.33579525, 0.38901961, 1.05473483, -1.31188095, 1.8963089, -0.07265259, 0.947339, 0.41949373, -0.70814759, 0.25892952, 1.07311416, 1.2571274, -0.62318051, -0.19951548, -0.94232577, -0.29393643, 0.42292568, -0.80230367, 1.40909171, 0.63617158, 0.13900366, 1.09253144, -0.15265895, 1.54781747, 0.72780299, 1.09189606, -0.38068101, 0.97057933, -0.58958799, 1.56188643, 0.21474874, 0.58725154, -1.27097559, -0.03024297, 1.09437096, -0.4897908, 0.34838957, -1.31042492, -1.69069934, 0.86956722, -0.40457946, 0.46691212, 1.29273605, 0.26464137, 0.22073045, -1.02178168, 0.22163901, -1.84387338, 0.75522131, -0.45775682, -0.42241111, -1.50944722, 1.07256448, -1.95876884, -0.28106022, 0.3341668, 2.13129425, -1.14728117, -1.06555498, -0.298444, -0.88322699, -0.65866792, -2.06007552, 0.01374334, 0.45612028, 0.52715492, 1.01914406, -1.72659791, 0.80650896, 0.16860051, 2.24112225, -0.78620857, 0.36566174, -0.07020134, -0.47976932, -0.68230027, -0.94711417, -0.54506505, 1.66504931, -0.71860826, 0.61132306}; std::vector<float> c = { -0.16115488, -0.09800646, -0.05412646, 0.10475694, 0.00555485, -0.12667653, 0.0458357, -0.02656217, -0.16338061, 0.15037455, 0.0102711, 0.01303349, 0.05242859, 0.02034754, 0.04751867, -0.17038961, -0.1434752, -0.10770349, 0.05676742, -0.15838449, 0.10128359, -0.18958683, 0.11954515, 0.10758857, -0.01058291, -0.12797487, 0.08971019, 0.18793164, -0.00881396, -0.06588994, -0.13321903, -0.03300409, 0.01439607, 0.07618178, -0.11556662, 0.00764295, 0.12956454, -0.08937147, -0.12763587, 0.04674943, 0.05765297, 0.11336918, 0.14747436, -0.06199479, -0.01166052, -0.12432006, -0.04494537, -0.17581205, 0.09475745, 0.1149437, -0.1014564, 0.0274073, -0.01323579, -0.11092556}; std::vector<float> s = { -0.0201216, 0.40407312, -0.39005592, -0.0631946, 0.37963012, -0.64611685, 0.1349397, -0.54113752, 0.28533003, 0.27667275, -0.16442731, -0.181494, 0.30564839, 0.58744538, 0.32015014, 0.24969585, -0.27367792, -0.53308117, 0.41236052, 0.26136363, -0.01489828, 0.57652152, -0.38506854, 0.119615, 0.0437076, 0.04779706, 0.57887721, 0.23126155, 0.05695833, -0.68200272, 0.02063358, -0.10267162, 0.8062973, -0.38149622, -0.40134856, -0.03353126, 0.38991132, -0.3478111, 0.03661491, 0.25783631, 0.62772679, -0.1961118, 0.76423508, -0.36241418, -0.20994355, -0.12368261, -0.9406727, 0.02340185, -0.08793129, -0.02471633, -0.58163726, -0.02211772, -0.42014724, 0.77525634, 0.504951, -0.20537445, -0.20369984, -0.83037728, -1.40423918, -0.46160448, -0.22944322, 0.36074194, 0.49579027, 0.46527559}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 4, 4}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); migraphx::shape c_shape{migraphx::shape::float_type, {2, 3, 3, 3}}; auto cl = mm->add_literal(migraphx::literal{c_shape, c}); mm->add_instruction( migraphx::make_op("convolution", {{"padding", {1, 1}}, {"stride", {1, 1}}}), al, cl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(64); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(conv2d_test) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { 2.71567607, -0.9960829, 0.91671127, 0.28140706, 0.63235772, 0.08077253, 0.80927712, -0.59108931, -1.05421555, -2.76622486, -0.85044265, -0.52049929, 0.67726439, -0.65290606, 0.02345525, -0.33579525, 0.38901961, 1.05473483, -1.31188095, 1.8963089, -0.07265259, 0.947339, 0.41949373, -0.70814759, 0.25892952, 1.07311416, 1.2571274, -0.62318051, -0.19951548, -0.94232577, -0.29393643, 0.42292568, -0.80230367, 1.40909171, 0.63617158, 0.13900366, 1.09253144, -0.15265895, 1.54781747, 0.72780299, 1.09189606, -0.38068101, 0.97057933, -0.58958799, 1.56188643, 0.21474874, 0.58725154, -1.27097559, -0.03024297, 1.09437096, -0.4897908, 0.34838957, -1.31042492, -1.69069934, 0.86956722, -0.40457946, 0.46691212, 1.29273605, 0.26464137, 0.22073045, -1.02178168, 0.22163901, -1.84387338, 0.75522131, -0.45775682, -0.42241111, -1.50944722, 1.07256448, -1.95876884, -0.28106022, 0.3341668, 2.13129425, -1.14728117, -1.06555498, -0.298444, -0.88322699, -0.65866792, -2.06007552, 0.01374334, 0.45612028, 0.52715492, 1.01914406, -1.72659791, 0.80650896, 0.16860051, 2.24112225, -0.78620857, 0.36566174, -0.07020134, -0.47976932, -0.68230027, -0.94711417, -0.54506505, 1.66504931, -0.71860826, 0.61132306}; std::vector<float> c = { 2.82721668e-02, 6.44195229e-02, 1.53499246e-02, 1.72468081e-01, -6.33238107e-02, 9.49496776e-02, 1.40258059e-01, -7.92879611e-02, -1.29301161e-01, 3.11307609e-03, -1.90624535e-01, 1.13238767e-01, -2.80647576e-02, 3.12882811e-02, -3.52091640e-02, 3.33581865e-02, 6.43158704e-02, 7.40238279e-02, -1.00106120e-01, -9.56912562e-02, 1.44342467e-01, 9.40258950e-02, 6.36333972e-02, 1.66158378e-03, -8.91554281e-02, 2.58734226e-02, 1.70919895e-02, 1.78214177e-01, 8.84564668e-02, 8.98126513e-02, -1.63809001e-01, 1.37802169e-01, 1.66439757e-01, -1.45631135e-02, 1.88469887e-04, 4.76950556e-02, -1.91969007e-01, -1.76233292e-01, -7.70473927e-02, 1.14828631e-01, 1.76608220e-01, -1.50728196e-01, 1.99946314e-02, -5.88052124e-02, 1.31612435e-01, 1.61106288e-02, -1.35080189e-01, 1.49512306e-01, 3.86456847e-02, 1.29330024e-01, -3.22975963e-02, -5.60784787e-02, -5.41997552e-02, 4.78562862e-02}; std::vector<float> s = {0.27039781, 0.19105849, -0.06339942, -0.65087199, 0.40867025, 0.05063812, -0.14907975, 0.49018705, -0.49197209, 0.33236548, -0.39374301, 0.16012701, 0.06574871, 0.71606487, -0.55201721, -0.46427044}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 4, 4}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); migraphx::shape c_shape{migraphx::shape::float_type, {2, 3, 3, 3}}; auto cl = mm->add_literal(migraphx::literal{c_shape, c}); mm->add_instruction(migraphx::make_op("convolution"), al, cl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(16); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(conv3d_test) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { 2.71567607, -0.9960829, 0.91671127, 0.28140706, 0.63235772, 0.08077253, 0.80927712, -0.59108931, -1.05421555, -2.76622486, -0.85044265, -0.52049929, 0.67726439, -0.65290606, 0.02345525, -0.33579525, 0.38901961, 1.05473483, -1.31188095, 1.8963089, -0.07265259, 0.947339, 0.41949373, -0.70814759, 0.25892952, 1.07311416, 1.2571274, -0.62318051, -0.19951548, -0.94232577, -0.29393643, 0.42292568, -0.80230367, 1.40909171, 0.63617158, 0.13900366, 1.09253144, -0.15265895, 1.54781747, 0.72780299, 1.09189606, -0.38068101, 0.97057933, -0.58958799, 1.56188643, 0.21474874, 0.58725154, -1.27097559, -0.03024297, 1.09437096, -0.4897908, 0.34838957, -1.31042492, -1.69069934, 0.86956722, -0.40457946, 0.46691212, 1.29273605, 0.26464137, 0.22073045, -1.02178168, 0.22163901, -1.84387338, 0.75522131, -0.45775682, -0.42241111, -1.50944722, 1.07256448, -1.95876884, -0.28106022, 0.3341668, 2.13129425, -1.14728117, -1.06555498, -0.298444, -0.88322699, -0.65866792, -2.06007552, 0.01374334, 0.45612028, 0.52715492, 1.01914406, -1.72659791, 0.80650896, 0.16860051, 2.24112225, -0.78620857, 0.36566174, -0.07020134, -0.47976932, -0.68230027, -0.94711417, -0.54506505, 1.66504931, -0.71860826, 0.61132306}; std::vector<float> c = { 2.82721668e-02, 6.44195229e-02, 1.53499246e-02, 1.72468081e-01, -6.33238107e-02, 9.49496776e-02, 1.40258059e-01, -7.92879611e-02, -1.29301161e-01, 3.11307609e-03, -1.90624535e-01, 1.13238767e-01, -2.80647576e-02, 3.12882811e-02, -3.52091640e-02, 3.33581865e-02, 6.43158704e-02, 7.40238279e-02, -1.00106120e-01, -9.56912562e-02, 1.44342467e-01, 9.40258950e-02, 6.36333972e-02, 1.66158378e-03, -8.91554281e-02, 2.58734226e-02, 1.70919895e-02, 1.78214177e-01, 8.84564668e-02, 8.98126513e-02, -1.63809001e-01, 1.37802169e-01, 1.66439757e-01, -1.45631135e-02, 1.88469887e-04, 4.76950556e-02, -1.91969007e-01, -1.76233292e-01, -7.70473927e-02, 1.14828631e-01, 1.76608220e-01, -1.50728196e-01, 1.99946314e-02, -5.88052124e-02, 1.31612435e-01, 1.61106288e-02, -1.35080189e-01, 1.49512306e-01, 3.86456847e-02, 1.29330024e-01, -3.22975963e-02, -5.60784787e-02, -5.41997552e-02, 4.78562862e-02}; std::vector<float> s = {0.27039781, 0.19105849, -0.06339942, -0.65087199, 0.40867025, 0.05063812, -0.14907975, 0.49018705, -0.49197209, 0.33236548, -0.39374301, 0.16012701, 0.06574871, 0.71606487, -0.55201721, -0.46427044}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 4, 4, 1}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); migraphx::shape c_shape{migraphx::shape::float_type, {2, 3, 3, 3, 1}}; auto cl = mm->add_literal(migraphx::literal{c_shape, c}); mm->add_instruction( migraphx::make_op("convolution", {{"padding", {0, 0, 0}}, {"stride", {1, 1, 1}}, {"dilation", {1, 1, 1}}}), al, cl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(16); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(cos_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); mm->add_instruction(migraphx::make_op("cos"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.54030231f, 1.f, 0.54030231f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(cosh_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2}}; auto l = mm->add_literal(migraphx::literal{s, {-1.0, 2.0, -3.0, 4.0}}); mm->add_instruction(migraphx::make_op("cosh"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{coshf(-1), coshf(2), coshf(-3), coshf(4)}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(deconv_1d_test) { migraphx::shape s{migraphx::shape::float_type, {1, 1, 3}}; std::vector<float> x_data{0, 0.5, 1}; std::vector<float> w_data{0.5, 0.5, 0.5}; std::vector<float> gold{0, 0.25, 0.75, 0.75, 0.5}; migraphx::program p; auto* mm = p.get_main_module(); auto x = mm->add_literal(migraphx::literal{s, x_data}); auto w = mm->add_literal(migraphx::literal{s, w_data}); mm->add_instruction( migraphx::make_op("deconvolution", {{"padding", {0}}, {"stride", {1}}, {"dilation", {1}}}), x, w); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(deconv_3d_test) { migraphx::shape s_1{migraphx::shape::float_type, {1, 1, 1, 2, 3}}; migraphx::shape s_2{migraphx::shape::float_type, {1, 1, 3, 2, 3}}; std::vector<float> x_data{0.8471, -0.4195, -2.2749, 1.2491, 0.1722, 0.3246}; std::vector<float> w_data{0.6478, -0.1985, 0.0633, -0.3479, 2.7056, -0.1440, -1.1229, -0.7507, -1.3151, 0.8884, -0.1859, -0.3407, -1.1544, -1.5893, 1.6265, -1.4624, 0.3812, -1.5378}; std::vector<float> gold{0.5488, -0.4399, -1.3369, 0.4251, -0.1439, 0.5145, 2.3015, -0.2104, -6.1482, 0.3482, -0.4346, 3.3197, 0.1731, 0.8533, -0.0467, -0.9512, -0.1649, 1.7553, 2.2594, 2.9917, -0.6500, -1.6612, -4.3680, 0.0957, 0.3482, 1.1097, -0.0792, -0.1692, -0.1190, -0.1106, -0.9779, -0.8621, 4.6707, 2.9332, -3.7001, -2.6808, -1.2476, 3.2475, -0.4578, 4.0263, -1.8267, 0.2243, -2.3299, -0.1411, -0.4991}; migraphx::program p; auto* mm = p.get_main_module(); auto x = mm->add_literal(migraphx::literal{s_1, x_data}); auto w = mm->add_literal(migraphx::literal{s_2, w_data}); mm->add_instruction( migraphx::make_op("deconvolution", {{"padding", {0, 0, 0}}, {"stride", {1, 1, 1}}, {"dilation", {1, 1, 1}}}), x, w); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(deconv_test) { migraphx::shape s{migraphx::shape::float_type, {1, 1, 3, 3}}; std::vector<float> x_data{0, 1, 2, 3, 4, 5, 6, 7, 8}; std::vector<float> w_data{1, 1, 1, 1, 1, 1, 1, 1, 1}; std::vector<float> gold{0, 1, 3, 3, 2, 3, 8, 15, 12, 7, 9, 21, 36, 27, 15, 9, 20, 33, 24, 13, 6, 13, 21, 15, 8}; migraphx::program p; auto* mm = p.get_main_module(); auto x = mm->add_literal(migraphx::literal{s, x_data}); auto w = mm->add_literal(migraphx::literal{s, w_data}); mm->add_instruction(migraphx::make_op("deconvolution"), x, w); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(div_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l1 = mm->add_literal(migraphx::literal{s, {-1.0f, 0.5f, 1.0f}}); auto l2 = mm->add_literal(migraphx::literal{s, {1.0f, 2.0f, 4.0f}}); mm->add_instruction(migraphx::make_op("div"), l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-1.f, 0.25f, 0.25f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(elu_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2}}; auto l = mm->add_literal(migraphx::literal{s, {-1.0, 2.0, -3.0, 4.0}}); float alpha = 0.5; mm->add_instruction(migraphx::make_op("elu", {{"alpha", alpha}}), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{elu(alpha, -1), elu(alpha, 2), elu(alpha, -3), elu(alpha, 4)}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(equal_brcst_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s0{migraphx::shape::float_type, {3, 3}}; auto l0 = mm->add_literal(migraphx::literal{s0, {1.1, 1.5, 0.1, -1.1, -1.5, -0.6, 0.0, 2.0, -2.0}}); migraphx::shape s1{migraphx::shape::float_type, {3, 1}}; auto l1 = mm->add_literal(migraphx::literal{s1, {1.1, -1.5, 0.0}}); auto bl1 = mm->add_instruction(migraphx::make_op("multibroadcast", {{"output_lens", {3, 3}}}), l1); auto eq = mm->add_instruction(migraphx::make_op("equal"), l0, bl1); auto r = mm->add_instruction( migraphx::make_op("convert", {{"target_type", migraphx::to_value(migraphx::shape::bool_type)}}), eq); mm->add_return({r}); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<bool> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<bool> gold = {true, false, false, false, true, false, true, false, false}; EXPECT(results_vector == gold); } TEST_CASE(equal_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {9}}; auto l0 = mm->add_literal(migraphx::literal{s, {1.1, 1.5, 0.1, -1.1, -1.5, -0.6, 0.0, 2.0, -2.0}}); auto l1 = mm->add_literal(migraphx::literal{s, {1.1, 1.6, -0.1, -1.2, -1.5, -0.7, 0.0, 2.3, -2.1}}); auto eq = mm->add_instruction(migraphx::make_op("equal"), l0, l1); auto r = mm->add_instruction( migraphx::make_op("convert", {{"target_type", migraphx::to_value(migraphx::shape::bool_type)}}), eq); mm->add_return({r}); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<bool> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<bool> gold = {true, false, false, false, true, false, true, false, false}; EXPECT(results_vector == gold); } TEST_CASE(erf_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {4}}; auto l = mm->add_literal(migraphx::literal{s, {0.73785057, 1.58165966, -0.43597795, -0.01677432}}); mm->add_instruction(migraphx::make_op("erf"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.70327317, 0.97470088, -0.46247893, -0.01892602}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(exp_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); mm->add_instruction(migraphx::make_op("exp"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.36787944f, 1.f, 2.71828183f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(floor_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {9}}; auto l = mm->add_literal(migraphx::literal{s, {1.1, 1.5, 0.6, -1.1, -1.5, -0.6, 0.0, 2.0, -2.0}}); mm->add_instruction(migraphx::make_op("floor"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {1.0, 1.0, 0.0, -2.0, -2.0, -1.0, -0.0, 2.0, -2.0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(fp16_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::half_type, {1}}; migraphx::half a{1.5}; migraphx::half b{2.5}; migraphx::half c{4.0}; auto l0 = mm->add_literal(migraphx::literal{s, {a}}); auto l1 = mm->add_literal(migraphx::literal{s, {b}}); mm->add_instruction(migraphx::make_op("add"), l0, l1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<migraphx::half> results_vector(1); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<migraphx::half> gold{c}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(fp32_fp16_test) { auto create_program = [] { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3}}; std::vector<float> data(2 * 3); std::iota(data.begin(), data.end(), 1.0f); auto l1 = mm->add_literal(migraphx::literal(s, data)); auto l2 = mm->add_literal(migraphx::literal(s, data)); mm->add_instruction(migraphx::make_op("add"), l1, l2); return p; }; auto test_case = [&](std::vector<std::string>&& op_names) { std::vector<float> gold_res = {2.0, 4.0, 6.0, 8.0, 10.0, 12.0}; auto p = create_program(); migraphx::quantize_fp16(p, op_names); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> res; result.visit([&](auto output) { res.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(res, gold_res)); }; test_case({"all"}); test_case({"add"}); } TEST_CASE(gather_test) { { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(3 * 3); std::iota(data.begin(), data.end(), 0.5); migraphx::shape s{migraphx::shape::float_type, {3, 3}}; auto a0 = mm->add_literal(migraphx::literal{s, data}); migraphx::shape s_indices{migraphx::shape::int32_type, {1, 2}}; std::vector<int> indices{0, 2}; auto a1 = mm->add_literal(migraphx::literal{s_indices, indices}); int axis = 0; mm->add_instruction(migraphx::make_op("gather", {{"axis", axis}}), a0, a1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> res_data(4 * 5); std::vector<float> golden = {0.5f, 1.5f, 2.5f, 6.5f, 7.5f, 8.5f}; result.visit([&](auto output) { res_data.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(res_data, golden)); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(3 * 3); std::iota(data.begin(), data.end(), 0.5); migraphx::shape s{migraphx::shape::float_type, {3, 3}}; auto a0 = mm->add_literal(migraphx::literal{s, data}); migraphx::shape s_indices{migraphx::shape::int32_type, {1, 2}}; std::vector<int> indices{-3, -1}; auto a1 = mm->add_literal(migraphx::literal{s_indices, indices}); int axis = 0; mm->add_instruction(migraphx::make_op("gather", {{"axis", axis}}), a0, a1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> res_data(4 * 5); std::vector<float> golden = {0.5f, 1.5f, 2.5f, 6.5f, 7.5f, 8.5f}; result.visit([&](auto output) { res_data.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(res_data, golden)); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(3 * 3); std::iota(data.begin(), data.end(), 0.5); migraphx::shape s{migraphx::shape::float_type, {3, 3}}; auto a0 = mm->add_literal(migraphx::literal{s, data}); migraphx::shape s_indices{migraphx::shape::int32_type, {1, 2}}; std::vector<int> indices{0, 2}; auto a1 = mm->add_literal(migraphx::literal{s_indices, indices}); int axis = 1; mm->add_instruction(migraphx::make_op("gather", {{"axis", axis}}), a0, a1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> res_data(4 * 5); std::vector<float> golden = {0.5f, 2.5f, 3.5f, 5.5f, 6.5f, 8.5f}; result.visit([&](auto output) { res_data.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(res_data, golden)); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(3 * 3); std::iota(data.begin(), data.end(), 0.5); migraphx::shape s{migraphx::shape::float_type, {3, 3}}; auto a0 = mm->add_literal(migraphx::literal{s, data}); migraphx::shape s_indices{migraphx::shape::int32_type, {1, 2}}; std::vector<int> indices{0, 2}; auto a1 = mm->add_literal(migraphx::literal{s_indices, indices}); int axis = -1; mm->add_instruction(migraphx::make_op("gather", {{"axis", axis}}), a0, a1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> res_data(4 * 5); std::vector<float> golden = {0.5f, 2.5f, 3.5f, 5.5f, 6.5f, 8.5f}; result.visit([&](auto output) { res_data.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(res_data, golden)); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(3 * 3); std::iota(data.begin(), data.end(), 0.5); migraphx::shape s{migraphx::shape::float_type, {3, 3}}; auto a0 = mm->add_literal(migraphx::literal{s, data}); // scalar index migraphx::shape s_indices{migraphx::shape::int32_type}; std::vector<int> indices{0}; auto a1 = mm->add_literal(migraphx::literal{s_indices, indices}); int axis = -1; mm->add_instruction(migraphx::make_op("gather", {{"axis", axis}}), a0, a1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> res_data{}; std::vector<float> golden = {0.5f, 3.5f, 6.5f}; result.visit([&](auto output) { res_data.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(res_data, golden)); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(3 * 3); std::iota(data.begin(), data.end(), 0.5); migraphx::shape s{migraphx::shape::float_type, {3, 3}}; auto a0 = mm->add_literal(migraphx::literal{s, data}); // scalar index migraphx::shape s_indices{migraphx::shape::int32_type}; std::vector<int> indices{-3}; auto a1 = mm->add_literal(migraphx::literal{s_indices, indices}); int axis = -1; mm->add_instruction(migraphx::make_op("gather", {{"axis", axis}}), a0, a1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> res_data{}; std::vector<float> golden = {0.5f, 3.5f, 6.5f}; result.visit([&](auto output) { res_data.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(res_data, golden)); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(3); std::iota(data.begin(), data.end(), 0.5); migraphx::shape s{migraphx::shape::float_type, {3}}; auto a0 = mm->add_literal(migraphx::literal{s, data}); // scalar index migraphx::shape s_indices{migraphx::shape::int32_type}; std::vector<int> indices{0}; auto a1 = mm->add_literal(migraphx::literal{s_indices, indices}); int axis = -1; mm->add_instruction(migraphx::make_op("gather", {{"axis", axis}}), a0, a1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> res_data{}; std::vector<float> golden = {0.5f}; result.visit([&](auto output) { res_data.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(res_data, golden)); } } TEST_CASE(globalavgpool_test) { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {1, 3, 2, 2}}; auto op = migraphx::op::pooling{"average"}; auto lens = s.lens(); op.lengths = {lens[2], lens[3]}; std::vector<float> data{0.3, 0.2, 0.4, 0.1, 0.8, 0.5, 0.9, 0.1, 0.1, 0.7, 0.1, 0.6}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0.25, 0.575, 0.375}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(globalmaxpool_test) { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {1, 3, 2, 2}}; auto op = migraphx::op::pooling{"max"}; auto lens = s.lens(); op.lengths = {lens[2], lens[3]}; std::vector<float> data{0.3, 0.2, 0.4, 0.1, 0.8, 0.5, 0.9, 0.1, 0.1, 0.7, 0.1, 0.6}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0.4, 0.9, 0.7}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(greater_brcst_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s0{migraphx::shape::float_type, {3, 3}}; auto l0 = mm->add_literal(migraphx::literal{s0, {1.1, 1.5, 0.1, -1.1, -1.5, -0.6, 0.0, 2.0, -2.0}}); migraphx::shape s1{migraphx::shape::float_type, {3, 1}}; auto l1 = mm->add_literal(migraphx::literal{s1, {1.1, -1.5, 0.0}}); auto bl1 = mm->add_instruction(migraphx::make_op("multibroadcast", {{"output_lens", {3, 3}}}), l1); auto gr = mm->add_instruction(migraphx::make_op("greater"), l0, bl1); auto r = mm->add_instruction( migraphx::make_op("convert", {{"target_type", migraphx::to_value(migraphx::shape::bool_type)}}), gr); mm->add_return({r}); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<bool> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<bool> gold = {false, true, false, true, false, true, false, true, false}; EXPECT(results_vector == gold); } TEST_CASE(greater_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {9}}; auto l0 = mm->add_literal(migraphx::literal{s, {1.1, 1.5, 0.1, -1.1, -1.5, -0.6, 0.0, 2.0, -2.0}}); auto l1 = mm->add_literal(migraphx::literal{s, {1.1, 1.6, -0.1, -1.2, -1.5, -0.7, 0.0, 2.3, -2.1}}); auto gr = mm->add_instruction(migraphx::make_op("greater"), l0, l1); auto r = mm->add_instruction( migraphx::make_op("convert", {{"target_type", migraphx::to_value(migraphx::shape::bool_type)}}), gr); mm->add_return({r}); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<bool> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<bool> gold = {false, false, true, true, false, true, false, false, true}; EXPECT(results_vector == gold); } TEST_CASE(identity_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2}}; std::vector<int> data{1, 2, 3, 4}; auto l = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(migraphx::make_op("identity"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(std::equal(data.begin(), data.end(), results_vector.begin())); } TEST_CASE(if_literal_test) { auto create_program = [] { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape cond_s{migraphx::shape::bool_type}; auto cond = mm->add_parameter("cond", cond_s); migraphx::shape s{migraphx::shape::float_type, {5}}; auto* then_mod = p.create_module("If_0_if"); std::vector<float> data1 = {1, 2, 3, 4, 5}; auto l1 = then_mod->add_literal(migraphx::literal(s, data1)); then_mod->add_return({l1}); auto* else_mod = p.create_module("If_0_else"); std::vector<float> data2 = {5, 4, 3, 2, 1}; auto l2 = else_mod->add_literal(migraphx::literal(s, data2)); else_mod->add_return({l2}); auto ret = mm->add_instruction(migraphx::make_op("if"), {cond}, {then_mod, else_mod}); mm->add_return({ret}); return p; }; auto run_prog = [&](bool cond) { auto p = create_program(); p.compile(migraphx::ref::target()); std::vector<char> c_data = {static_cast<char>(cond)}; migraphx::shape cs{migraphx::shape::bool_type}; migraphx::parameter_map m; m["cond"] = migraphx::argument(cs, c_data.data()); auto res = p.eval(m).back(); std::vector<float> ret; res.visit([&](auto v) { ret.assign(v.begin(), v.end()); }); return ret; }; // then branch { std::vector<float> gold_ret = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}; auto ret = run_prog(true); EXPECT(gold_ret == ret); } // else branch { std::vector<float> gold_ret = {5.0f, 4.0f, 3.0f, 2.0f, 1.0f}; auto ret = run_prog(false); EXPECT(gold_ret == ret); } } TEST_CASE(if_param_test) { auto create_program = [] { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape cond_s{migraphx::shape::bool_type}; auto cond = mm->add_parameter("cond", cond_s); migraphx::shape ds{migraphx::shape::float_type, {2, 3}}; auto x = mm->add_parameter("x", ds); auto y = mm->add_parameter("y", ds); std::vector<float> data2 = {-0.258047, 0.360394, 0.536804, -0.577762, 1.0217, 1.02442}; auto l2 = mm->add_literal(migraphx::literal(ds, data2)); auto sum = mm->add_instruction(migraphx::make_op("add"), x, l2); auto* then_mod = p.create_module("If_0_if"); std::vector<float> data1 = {0.384804, -1.77948, -0.453775, 0.477438, -1.06333, -1.12893}; auto l1 = then_mod->add_literal(migraphx::literal(ds, data1)); auto tx = then_mod->add_parameter("x", ds); auto a1 = then_mod->add_instruction(migraphx::make_op("add"), tx, l1); then_mod->add_return({a1}); auto* else_mod = p.create_module("If_0_else"); auto ey = else_mod->add_parameter("y", ds); auto a2 = else_mod->add_instruction(migraphx::make_op("mul"), ey, sum); else_mod->add_return({a2}); auto ret = mm->add_instruction(migraphx::make_op("if"), {cond, x, y}, {then_mod, else_mod}); mm->add_return({ret}); return p; }; auto run_prog = [&](bool cond) { auto p = create_program(); p.compile(migraphx::ref::target()); std::vector<char> c_data = {static_cast<char>(cond)}; migraphx::shape cs{migraphx::shape::bool_type}; migraphx::parameter_map m; m["cond"] = migraphx::argument(cs, c_data.data()); migraphx::shape ds{migraphx::shape::float_type, {2, 3}}; std::vector<float> data_x(ds.elements(), 1); m["x"] = migraphx::argument(ds, data_x.data()); std::vector<float> data_y(ds.elements(), 2); m["y"] = migraphx::argument(ds, data_y.data()); auto res = p.eval(m).back(); std::vector<float> ret; res.visit([&](auto v) { ret.assign(v.begin(), v.end()); }); std::cout << std::endl; return ret; }; // then branch { std::vector<float> gold_ret = { 1.384804, -0.77947998, 0.54622501, 1.477438, -0.063330054, -0.12892997}; auto ret = run_prog(true); EXPECT(gold_ret == ret); } // else branch { std::vector<float> gold_ret = { 1.483906, 2.720788, 3.0736079, 0.84447598, 4.0433998, 4.04884}; auto ret = run_prog(false); EXPECT(gold_ret == ret); } } TEST_CASE(if_pl_test) { auto create_program = [] { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape cond_s{migraphx::shape::bool_type}; migraphx::shape s{migraphx::shape::float_type, {5}}; auto cond = mm->add_parameter("cond", cond_s); auto x = mm->add_parameter("x", s); auto* then_mod = p.create_module("If_0_if"); std::vector<float> data1 = {1, 2, 3, 4, 5}; auto l1 = then_mod->add_literal(migraphx::literal(s, data1)); then_mod->add_return({l1, x}); auto* else_mod = p.create_module("If_0_else"); std::vector<float> data2 = {5, 4, 3, 2, 1}; auto l2 = else_mod->add_literal(migraphx::literal(s, data2)); auto s2 = else_mod->add_instruction(migraphx::make_op("add"), x, l2); else_mod->add_return({s2, l2}); auto ret = mm->add_instruction(migraphx::make_op("if"), {cond}, {then_mod, else_mod}); auto outline = mm->add_outline(s); mm->add_return({outline, ret}); return p; }; auto run_prog = [&](bool cond) { auto p = create_program(); p.compile(migraphx::ref::target()); std::vector<char> c_data = {static_cast<char>(cond)}; migraphx::shape cs{migraphx::shape::bool_type}; migraphx::parameter_map m; m["cond"] = migraphx::argument(cs, c_data.data()); migraphx::shape ds{migraphx::shape::float_type, {5}}; std::vector<float> data(ds.elements(), 1); m["x"] = migraphx::argument(ds, data.data()); auto res = p.eval(m).back(); std::vector<float> ret; res.visit([&](auto v) { ret.assign(v.begin(), v.end()); }); return ret; }; // then branch { std::vector<float> gold_ret = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}; auto ret = run_prog(true); EXPECT(gold_ret == ret); } // else branch { std::vector<float> gold_ret = {6.0f, 5.0f, 4.0f, 3.0f, 2.0f}; auto ret = run_prog(false); EXPECT(gold_ret == ret); } } TEST_CASE(im2col_3x3_no_pad_identity_test) { std::size_t f[2] = {3, 3}; std::size_t size[2] = {3, 3}; std::vector<std::size_t> padding{0, 0}; std::vector<std::size_t> stride{1, 1}; std::vector<std::size_t> dilation{1, 1}; std::size_t channels = 1; std::vector<int32_t> weights(channels * f[0] * f[1]); std::vector<int32_t> input(channels * size[0] * size[1]); std::iota(input.begin(), input.end(), 0); migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s_image{migraphx::shape::int32_type, {1, channels, size[0], size[1]}}; migraphx::shape s_weights{migraphx::shape::int32_type, {1, channels, f[0], f[1]}}; auto l_image = mm->add_literal(migraphx::literal{s_image, input}); auto l_weights = mm->add_literal(migraphx::literal{s_weights, weights}); mm->add_instruction( migraphx::make_op("im2col", {{"padding", padding}, {"stride", stride}, {"dilation", dilation}}), l_image, l_weights); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::size_t col_height = (size[0] - f[0] + 2 * padding[0]) / stride[0] + 1; std::size_t col_width = (size[1] - f[1] + 2 * padding[1]) / stride[1] + 1; std::vector<float> results_vector(channels * f[0] * f[1] * col_height * col_width); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, input)); } TEST_CASE(im2col_3x3_no_pad_test) { std::size_t f[2] = {3, 3}; std::size_t size[2] = {4, 4}; std::vector<std::size_t> padding{0, 0}; std::vector<std::size_t> stride{1, 1}; std::vector<std::size_t> dilation{1, 1}; std::size_t channels = 1; std::vector<int32_t> weights(channels * f[0] * f[1]); std::vector<int32_t> input(channels * size[0] * size[1]); std::iota(input.begin(), input.end(), 0); migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s_image{migraphx::shape::int32_type, {1, channels, size[0], size[1]}}; migraphx::shape s_weights{migraphx::shape::int32_type, {1, channels, f[0], f[1]}}; auto l_image = mm->add_literal(migraphx::literal{s_image, input}); auto l_weights = mm->add_literal(migraphx::literal{s_weights, weights}); mm->add_instruction( migraphx::make_op("im2col", {{"padding", padding}, {"stride", stride}, {"dilation", dilation}}), l_image, l_weights); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> correct = {0, 1, 2, 4, 5, 6, 8, 9, 10, 1, 2, 3, 5, 6, 7, 9, 10, 11, 4, 5, 6, 8, 9, 10, 12, 13, 14, 5, 6, 7, 9, 10, 11, 13, 14, 15}; std::size_t col_height = (size[0] - f[0] + 2 * padding[0]) / stride[0] + 1; std::size_t col_width = (size[1] - f[1] + 2 * padding[1]) / stride[1] + 1; std::vector<float> results_vector(channels * f[0] * f[1] * col_height * col_width); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, correct)); } TEST_CASE(im2col_3x3_stride_2_no_pad_test) { std::size_t f[2] = {3, 3}; std::size_t size[2] = {6, 6}; std::vector<std::size_t> padding{0, 0}; std::vector<std::size_t> stride{2, 2}; std::vector<std::size_t> dilation{1, 1}; std::size_t channels = 1; std::vector<int32_t> weights(channels * f[0] * f[1]); std::vector<int32_t> input(channels * size[0] * size[1]); std::iota(input.begin(), input.end(), 0); migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s_image{migraphx::shape::int32_type, {1, channels, size[0], size[1]}}; migraphx::shape s_weights{migraphx::shape::int32_type, {1, channels, f[0], f[1]}}; auto l_image = mm->add_literal(migraphx::literal{s_image, input}); auto l_weights = mm->add_literal(migraphx::literal{s_weights, weights}); mm->add_instruction( migraphx::make_op("im2col", {{"padding", padding}, {"stride", stride}, {"dilation", dilation}}), l_image, l_weights); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> correct = {0, 1, 2, 6, 7, 8, 12, 13, 14, 2, 3, 4, 8, 9, 10, 14, 15, 16, 12, 13, 14, 18, 19, 20, 24, 25, 26, 14, 15, 16, 20, 21, 22, 26, 27, 28}; std::size_t col_height = (size[0] - f[0] + 2 * padding[0]) / stride[0] + 1; std::size_t col_width = (size[1] - f[1] + 2 * padding[1]) / stride[1] + 1; std::vector<float> results_vector(channels * f[0] * f[1] * col_height * col_width); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, correct)); } TEST_CASE(im2col_3x3_with_channels_identity_test) { std::size_t f[2] = {3, 3}; std::size_t size[2] = {3, 3}; std::vector<std::size_t> padding{0, 0}; std::vector<std::size_t> stride{1, 1}; std::vector<std::size_t> dilation{1, 1}; std::size_t channels = 2; std::vector<int32_t> weights(channels * f[0] * f[1]); std::vector<int32_t> input(channels * size[0] * size[1]); std::iota(input.begin(), input.end(), 0); migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s_image{migraphx::shape::int32_type, {1, channels, size[0], size[1]}}; migraphx::shape s_weights{migraphx::shape::int32_type, {1, channels, f[0], f[1]}}; auto l_image = mm->add_literal(migraphx::literal{s_image, input}); auto l_weights = mm->add_literal(migraphx::literal{s_weights, weights}); mm->add_instruction( migraphx::make_op("im2col", {{"padding", padding}, {"stride", stride}, {"dilation", dilation}}), l_image, l_weights); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::size_t col_height = (size[0] - f[0] + 2 * padding[0]) / stride[0] + 1; std::size_t col_width = (size[1] - f[1] + 2 * padding[1]) / stride[1] + 1; std::vector<float> results_vector(channels * f[0] * f[1] * col_height * col_width); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, input)); } TEST_CASE(im2col_3x3_with_padding_test) { std::size_t f[2] = {3, 3}; std::size_t size[2] = {2, 2}; std::vector<std::size_t> padding{1, 1}; std::vector<std::size_t> stride{1, 1}; std::vector<std::size_t> dilation{1, 1}; std::size_t channels = 1; std::vector<int32_t> weights(channels * f[0] * f[1]); std::vector<int32_t> input(channels * size[0] * size[1]); std::iota(input.begin(), input.end(), 0); migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s_image{migraphx::shape::int32_type, {1, channels, size[0], size[1]}}; migraphx::shape s_weights{migraphx::shape::int32_type, {1, channels, f[0], f[1]}}; auto l_image = mm->add_literal(migraphx::literal{s_image, input}); auto l_weights = mm->add_literal(migraphx::literal{s_weights, weights}); mm->add_instruction( migraphx::make_op("im2col", {{"padding", padding}, {"stride", stride}, {"dilation", dilation}}), l_image, l_weights); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> correct = {0, 0, 0, 0, 0, 1, 0, 2, 3, 0, 0, 0, 0, 1, 0, 2, 3, 0, 0, 0, 1, 0, 2, 3, 0, 0, 0, 0, 1, 0, 2, 3, 0, 0, 0, 0}; std::size_t col_height = (size[0] - f[0] + 2 * padding[0]) / stride[0] + 1; std::size_t col_width = (size[1] - f[1] + 2 * padding[1]) / stride[1] + 1; std::vector<float> results_vector(channels * f[0] * f[1] * col_height * col_width); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, correct)); } TEST_CASE(imagescaler_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {1, 3, 2, 2}}; auto img = mm->add_literal(migraphx::literal{s, {0.2, 0.3, 0.5, 0.4, 0.7, 0.8, 0.1, 0.9, 0.15, 0.25, 0.35, 0.45}}); auto scale_val = mm->add_literal(2.f); auto scaled_tensor = mm->add_instruction( migraphx::make_op("scalar", {{"scalar_bcst_dims", s.lens()}}), scale_val); auto img_scaled = mm->add_instruction(migraphx::make_op("mul"), img, scaled_tensor); auto bias_vals = mm->add_literal( migraphx::literal{migraphx::shape{migraphx::shape::float_type, {3}}, {0.01, 0.02, 0.03}}); auto bias_bcast = mm->add_instruction( migraphx::make_op("broadcast", {{"axis", 1}, {"dims", s.lens()}}), bias_vals); mm->add_instruction(migraphx::make_op("add"), img_scaled, bias_bcast); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(12); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.41, 0.61, 1.01, 0.81, 1.42, 1.62, 0.22, 1.82, 0.33, 0.53, 0.73, 0.93}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(leaky_relu_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {-1.f, 0.f, 1.f}}); mm->add_instruction(migraphx::make_op("leaky_relu", {{"alpha", 0.01}}), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-0.01f, 0.f, 1.f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(less_brcst_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s0{migraphx::shape::float_type, {3, 3}}; auto l0 = mm->add_literal(migraphx::literal{s0, {1.1, 1.5, 0.1, -1.1, -1.5, -0.6, 0.0, 2.0, -2.0}}); migraphx::shape s1{migraphx::shape::float_type, {3, 1}}; auto l1 = mm->add_literal(migraphx::literal{s1, {1.1, -1.5, 0.0}}); auto bl1 = mm->add_instruction(migraphx::make_op("multibroadcast", {{"output_lens", {3, 3}}}), l1); auto le = mm->add_instruction(migraphx::make_op("less"), l0, bl1); auto r = mm->add_instruction( migraphx::make_op("convert", {{"target_type", migraphx::to_value(migraphx::shape::bool_type)}}), le); mm->add_return({r}); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<bool> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<bool> gold = {false, false, true, false, false, false, false, false, true}; EXPECT(results_vector == gold); } TEST_CASE(less_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {9}}; auto l0 = mm->add_literal(migraphx::literal{s, {1.1, 1.5, 0.1, -1.1, -1.5, -0.6, 0.0, 2.0, -2.0}}); auto l1 = mm->add_literal(migraphx::literal{s, {1.1, 1.6, -0.1, -1.2, -1.5, -0.7, 0.0, 2.3, -2.1}}); auto le = mm->add_instruction(migraphx::make_op("less"), l0, l1); auto r = mm->add_instruction( migraphx::make_op("convert", {{"target_type", migraphx::to_value(migraphx::shape::bool_type)}}), le); mm->add_return({r}); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<bool> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<bool> gold = {false, true, false, false, false, false, false, true, false}; EXPECT(results_vector == gold); } TEST_CASE(log_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {1, 2, 3}}); mm->add_instruction(migraphx::make_op("log"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.0f, 0.6931471806f, 1.0986122887f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(logical_and_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::bool_type, {4}}; auto l1 = mm->add_literal(migraphx::literal{s, {1, 0, 1, 0}}); auto l2 = mm->add_literal(migraphx::literal{s, {1, 1, 0, 0}}); mm->add_instruction(migraphx::make_op("logical_and"), l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<char> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<char> gold = {1, 0, 0, 0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(logical_or_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::bool_type, {4}}; auto l1 = mm->add_literal(migraphx::literal{s, {1, 0, 1, 0}}); auto l2 = mm->add_literal(migraphx::literal{s, {1, 1, 0, 0}}); mm->add_instruction(migraphx::make_op("logical_or"), l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<char> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<char> gold = {1, 1, 1, 0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(logical_xor_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::bool_type, {4}}; auto l1 = mm->add_literal(migraphx::literal{s, {1, 0, 1, 0}}); auto l2 = mm->add_literal(migraphx::literal{s, {1, 1, 0, 0}}); mm->add_instruction(migraphx::make_op("logical_xor"), l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<char> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<char> gold = {0, 1, 1, 0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(logsoftmax_test_axis_0) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { 1.93885877, -1.20006269, 0.90960855, 0.42108916, -1.50797544, -1.31047913, 1.07816336, -1.13288733, -0.86411064, 0.97800238, 0.76631385, 2.07962834, -0.8940665, -1.62855592, -0.53763057, -1.48165117, -0.64154112, 0.42486547, 0.89330917, -2.42022666, 0.192611, -0.01257413, -1.5326607, 0.53137897, -1.52383859, 0.46994381, 0.00453619, 0.0066996, 1.58394908, 0.84216752, -0.04137941, -0.88580789, 1.44055158, -0.17621241, -1.98917923, -0.08610038, 0.79020567, -0.67714548, 0.42774631, 0.1376574, 2.23569227, 1.16681234, -1.21191456, -0.28411502, -0.18688975, 1.67552548, 2.48357974, 0.95891282, -0.06616535, -0.99628491, 1.04314606, -1.22943315, 0.76930403, 0.31106618}; std::vector<float> s = { -0.135261, -2.843968, -0.659995, -0.488413, -1.051857, -2.812936, -0.250956, -0.353985, -1.155980, -0.603651, -0.211969, -0.175371, -1.336552, -3.885010, -1.871544, -0.837083, -0.887745, -0.433338, -1.158864, -4.911197, -1.147972, -0.666711, -0.996874, -0.981418, -0.851145, -0.853988, -0.858112, -2.067420, -0.059956, -0.727436, -0.950881, -0.429689, -0.061906, -1.505332, -1.210277, -0.377970, -0.791448, -1.655428, -1.827253, -0.304828, -0.020762, -0.167101, -0.567346, -0.530319, -1.045094, -0.376648, -0.007391, -0.381670, -0.720302, -0.460499, -0.469651, -0.556740, -0.554628, -0.551582}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 3, 3}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); int axis = 0; mm->add_instruction(migraphx::make_op("logsoftmax", {{"axis", axis}}), al); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(logsoftmax_test_axis_1) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { 1.93885877, -1.20006269, 0.90960855, 0.42108916, -1.50797544, -1.31047913, 1.07816336, -1.13288733, -0.86411064, 0.97800238, 0.76631385, 2.07962834, -0.8940665, -1.62855592, -0.53763057, -1.48165117, -0.64154112, 0.42486547, 0.89330917, -2.42022666, 0.192611, -0.01257413, -1.5326607, 0.53137897, -1.52383859, 0.46994381, 0.00453619, 0.0066996, 1.58394908, 0.84216752, -0.04137941, -0.88580789, 1.44055158, -0.17621241, -1.98917923, -0.08610038, 0.79020567, -0.67714548, 0.42774631, 0.1376574, 2.23569227, 1.16681234, -1.21191456, -0.28411502, -0.18688975, 1.67552548, 2.48357974, 0.95891282, -0.06616535, -0.99628491, 1.04314606, -1.22943315, 0.76930403, 0.31106618}; std::vector<float> s = { -0.550468, -2.132973, -1.549746, -0.650533, -1.051529, -2.248570, -0.141017, -2.028357, -1.947730, -1.511324, -0.166597, -0.379726, -1.965689, -1.172109, -1.475721, -2.700831, -1.537011, -0.658754, -1.596017, -3.353137, -2.266743, -1.084197, -1.076214, -0.406712, -2.743019, -0.425526, -1.079083, -2.139486, -1.270584, -1.024088, -1.154231, -3.201762, -0.888957, -0.532855, -3.103583, -1.221339, -1.355980, -3.531678, -1.438510, -0.975194, -0.080261, -1.162697, -1.568557, -1.398519, -1.322129, -0.470660, -0.370953, -0.907343, -1.179017, -3.312239, -1.286363, -1.586076, -0.345100, -0.824173}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 3, 3}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); int axis = 1; mm->add_instruction(migraphx::make_op("logsoftmax", {{"axis", axis}}), al); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(logsoftmax_test_axis_2) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { 1.93885877, -1.20006269, 0.90960855, 0.42108916, -1.50797544, -1.31047913, 1.07816336, -1.13288733, -0.86411064, 0.97800238, 0.76631385, 2.07962834, -0.8940665, -1.62855592, -0.53763057, -1.48165117, -0.64154112, 0.42486547, 0.89330917, -2.42022666, 0.192611, -0.01257413, -1.5326607, 0.53137897, -1.52383859, 0.46994381, 0.00453619, 0.0066996, 1.58394908, 0.84216752, -0.04137941, -0.88580789, 1.44055158, -0.17621241, -1.98917923, -0.08610038, 0.79020567, -0.67714548, 0.42774631, 0.1376574, 2.23569227, 1.16681234, -1.21191456, -0.28411502, -0.18688975, 1.67552548, 2.48357974, 0.95891282, -0.06616535, -0.99628491, 1.04314606, -1.22943315, 0.76930403, 0.31106618}; std::vector<float> s = { -0.495957, -1.031212, -0.245531, -2.013726, -1.339125, -2.465619, -1.356652, -0.964037, -2.019250, -0.214522, -0.289569, -0.234392, -2.086591, -2.684439, -2.851651, -2.674176, -1.697424, -1.889155, -0.401029, -3.064586, -1.173030, -1.306912, -2.177020, -0.834262, -2.818177, -0.174415, -1.361105, -1.024571, -0.106766, -1.167645, -1.072650, -2.576522, -0.569261, -1.207483, -3.679894, -2.095913, -0.504264, -3.039291, -1.290559, -1.156812, -0.126453, -0.551493, -2.506384, -2.646261, -1.905195, -0.206994, -0.191369, -0.959754, -1.948685, -3.671233, -0.875521, -3.111952, -1.905644, -1.6076011}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 3, 3}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); int axis = 2; mm->add_instruction(migraphx::make_op("logsoftmax", {{"axis", axis}}), al); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(logsoftmax_test_axis_3) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { 1.93885877, -1.20006269, 0.90960855, 0.42108916, -1.50797544, -1.31047913, 1.07816336, -1.13288733, -0.86411064, 0.97800238, 0.76631385, 2.07962834, -0.8940665, -1.62855592, -0.53763057, -1.48165117, -0.64154112, 0.42486547, 0.89330917, -2.42022666, 0.192611, -0.01257413, -1.5326607, 0.53137897, -1.52383859, 0.46994381, 0.00453619, 0.0066996, 1.58394908, 0.84216752, -0.04137941, -0.88580789, 1.44055158, -0.17621241, -1.98917923, -0.08610038, 0.79020567, -0.67714548, 0.42774631, 0.1376574, 2.23569227, 1.16681234, -1.21191456, -0.28411502, -0.18688975, 1.67552548, 2.48357974, 0.95891282, -0.06616535, -0.99628491, 1.04314606, -1.22943315, 0.76930403, 0.31106618}; std::vector<float> s = { -0.336904, -3.475825, -1.366154, -0.279366, -2.208430, -2.010934, -0.225511, -2.436562, -2.167785, -1.572415, -1.784104, -0.470789, -1.067459, -1.801948, -0.711023, -2.307197, -1.467087, -0.400681, -0.426983, -3.740518, -1.127681, -1.078919, -2.599005, -0.534965, -2.561400, -0.567617, -1.033025, -2.097713, -0.520463, -1.262245, -1.763230, -2.607658, -0.281299, -0.814243, -2.627210, -0.724131, -0.655704, -2.123055, -1.018163, -2.480634, -0.382599, -1.451479, -1.843102, -0.915303, -0.818078, -1.316929, -0.508875, -2.033541, -1.487672, -2.417791, -0.378360, -2.568531, -0.569794, -1.028032}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 3, 3}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); int axis = 3; mm->add_instruction(migraphx::make_op("logsoftmax", {{"axis", axis}}), al); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(lrn_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {1, 5, 1, 1}}; auto l = mm->add_literal(migraphx::literal{s, {-2.0f, 1.0f, 0.f, 1.0f, 2.0f}}); mm->add_instruction( migraphx::make_op("lrn", {{"alpha", 0.0001}, {"beta", 0.75}, {"bias", 1}, {"size", 5}}), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(5); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-2 / 1.000075, 1 / 1.00009, 0 / 1.000145, 1 / 1.00009, 2 / 1.000075}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(max_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l0 = mm->add_literal(migraphx::literal{s, {1, 4, 3}}); auto l1 = mm->add_literal(migraphx::literal{s, {2, 8, 6}}); auto l2 = mm->add_literal(migraphx::literal{s, {7, 5, 9}}); auto curr_max = mm->add_instruction(migraphx::make_op("max"), l0, l1); mm->add_instruction(migraphx::make_op("max"), curr_max, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{7, 8, 9}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(maxpool_test) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { -2.1314404, -1.63041711, 1.54562736, 1.04625261, -1.42931843, -0.48703974, 0.4065806, -0.1524526, 1.30775225, 0.45538983, -0.06631992, -1.75332725, 1.33493888, 0.47327688, 0.36873096, 1.18358743, -0.34640595, 1.22098756, 0.01946825, -0.20238149, 0.43348005, -0.67991608, -0.83041084, 0.93537551, 0.70241445, -0.5654031, -1.30899191, -0.26735824, -0.52444768, 1.99097753, 1.86504853, -0.26506025, 0.26236168, 0.43763575, 0.95300823, -1.02733946, -0.74655169, -0.5374338, -0.28901565, -0.59789604, 0.5310151, 0.99125904, 0.40609556, -1.57175648, 0.22031412, 1.45862222, 0.53217483, 1.39087725, 1.00170159, -0.87175864, -1.7204628, -1.72008383, -0.38656762, -0.01443311, 1.46645272, -1.39995027, 0.22505587, -0.43461126, -0.05511411, -0.79950953, -0.01439556, 0.08795211, 1.18943918, -0.84079367, -1.73383629, -0.55662078, -0.30626822, -0.67339015, 0.44179603, 0.54316711, 0.40899998, -0.27831686, -1.11900508, -0.0881724, 0.35483059, 2.36277103, -0.04765317, -0.36865309, 0.73814237, 1.47151589, 1.36546791, -0.32649881, -1.0517807, 2.24768877, 0.68883753, 0.58646208, -0.91017133, -0.50462508, -0.4013325, -0.72348958, -0.47368807, 0.35285577, -1.01817429, -0.5152272, 0.60321307, 0.43521205, -0.23733577, 0.66427642, 0.82949388, 0.82443929, 0.71550399, 0.34561086, 0.68570769, -0.40718508, -1.20350206, 0.15793853, -2.31013632, -0.07934658, -0.09348056, 0.36576006, 2.46601582, 0.11090943, 0.9144392, 0.56759721, -0.22112127, -0.21955389, 0.72474903, -1.28448462, 1.53285873, 0.37437943, 0.31409341, 1.95433736, 0.91620457, 0.86205518, 1.24365854, 0.19248386, 0.22526583, 0.13462132, -0.27561715, -2.06446075, -0.02306402, -1.38278747, 1.1411345, 1.31293464, -1.86041689, 1.06763375, -0.26541466, 1.4545635, 1.11430049, -0.66491818, 0.87101674, 0.67768967, -1.02062869, -1.05031872, -2.2764678, -2.0200038, 0.37592548, -0.26701379, -0.83388507, 0.19403623, 1.00968623, 0.11020003, 1.16736257, -1.1160326, 0.47346735, 0.6126079, -0.19135755, 1.33624589, -0.29802522, -0.57873946, -1.06555879, -0.20686582, 1.36892557, -0.19937795, 0.8649236, -1.40126073, 1.53441942, 0.34682792, -1.31724346, -1.32898355, 2.40126371, 0.07845283, 1.35732043, -0.63678312, 0.39429256, -1.36487007, -0.31026676, -0.44981545, -0.28994772, -0.14657612, -1.75206447, -0.70612341, 1.20071781, -1.64647579, -0.7133292, 0.88494766, 0.52119428, -2.77387547, 2.07681108, -0.90133125, 0.2847338, 0.6174528, -0.20616426, -0.64263535, -1.08496261, 0.54275119, -0.88503587, 0.6629802, 1.47319221, -1.05829155, -0.97027361, -0.93187737, -1.39954746, -0.52359426, -0.14743951, 1.51522756, 0.2078452, -1.28156149, -1.19363916, -0.78680223, -0.89094824, 1.30212069, -0.77974445, -0.58411664, 0.48764706, -0.67132682}; std::vector<float> c = {1.33493888, 1.54562736, 1.22098756, 1.33493888, 1.18358743, 1.99097753, 1.00170159, 1.45862222, 1.39087725, 1.46645272, 1.18943918, -0.01443311, 1.47151589, 2.36277103, 2.24768877, 0.68883753, 0.82949388, 0.71550399, 1.95433736, 2.46601582, 1.53285873, 1.95433736, 1.06763375, 1.4545635, 1.33624589, 1.16736257, 0.6126079, 1.36892557, 2.40126371, 1.53441942, 0.52119428, 2.07681108, 0.88494766, 1.51522756, 0.54275119, 0.6629802}; migraphx::shape a_shape{migraphx::shape::float_type, {2, 3, 6, 6}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); mm->add_instruction( migraphx::make_op( "pooling", {{"mode", "max"}, {"padding", {0, 0}}, {"stride", {2, 2}}, {"lengths", {3, 2}}}), al); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(36); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, c)); } TEST_CASE(maxpool_test_1D_3D) { // 1D case 1, input is 3D { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {1, 3, 4}}; auto op = migraphx::op::pooling{"max"}; op.lengths = {2}; op.padding = {0}; op.stride = {1}; std::vector<float> data{0.3, 0.2, 0.4, 0.1, 0.8, 0.5, 0.9, 0.1, 0.1, 0.7, 0.1, 0.6}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0.3, 0.4, 0.4, 0.8, 0.9, 0.9, 0.7, 0.7, 0.6}; EXPECT(migraphx::verify_range(results_vector, gold)); } // 1D case 2, input is 3D { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {2, 2, 5}}; auto op = migraphx::op::pooling{"max"}; op.lengths = {2}; op.padding = {0}; op.stride = {2}; std::vector<float> data{0.4975, -0.1226, -0.0405, -0.2861, -0.1227, -0.6186, -0.9618, 0.6022, -0.1912, 1.1925, 0.5493, 0.1692, -0.8039, -1.0281, 0.9907, 0.477, 1.5001, -1.1603, -1.361, 1.2556}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0.4975, -0.0405, -0.6186, 0.6022, 0.5493, -0.8039, 1.5001, -1.1603}; EXPECT(migraphx::verify_range(results_vector, gold)); } // 1D case 2, input is 3D, ceil mode { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {2, 2, 5}}; auto op = migraphx::op::pooling{"max"}; op.lengths = {2}; op.padding = {0}; op.stride = {2}; op.ceil_mode = true; std::vector<float> data{0.4975, -0.1226, -0.0405, -0.2861, -0.1227, -0.6186, -0.9618, 0.6022, -0.1912, 1.1925, 0.5493, 0.1692, -0.8039, -1.0281, 0.9907, 0.477, 1.5001, -1.1603, -1.361, 1.2556}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0.4975, -0.0405, -0.1227, -0.6186, 0.6022, 1.1925, 0.5493, -0.8039, 0.9907, 1.5001, -1.1603, 1.2556}; EXPECT(migraphx::verify_range(results_vector, gold)); } // 3D, input is 5D { migraphx::program p; auto* mm = p.get_main_module(); auto s = migraphx::shape{migraphx::shape::float_type, {2, 2, 3, 3, 3}}; auto op = migraphx::op::pooling{"max"}; op.lengths = {2, 2, 2}; op.padding = {0, 0, 0}; op.stride = {2, 2, 2}; std::vector<float> data{ -2.8029, 0.5861, 0.7015, 0.1297, -1.44, -1.9472, 0.7812, 2.408, -0.3145, 0.3405, -0.9146, 0.0624, 1.5064, -0.8345, 1.7977, 1.8949, 1.0073, -0.2102, -0.042, -0.7146, 0.6227, -0.5263, -2.2598, 0.1713, 0.449, 0.5303, -0.8622, -0.5691, 0.907, -0.0569, -1.5348, -0.4109, -0.1461, -0.5445, 0.4266, 0.2282, 1.3655, -2.1519, 0.6068, -0.2001, -0.4702, 0.3864, 1.7083, 0.9096, 0.4286, -1.8866, 0.7034, 0.0293, 1.4587, 0.7672, -2.8614, 0.8124, -0.053, 1.0449, 0.845, -0.0131, 0.1139, -0.859, -1.2681, -0.6337, -0.4644, 0.1938, 0.2889, 0.9035, 0.7118, -0.5767, 0.4577, -0.0549, 0.2237, 0.5756, 0.0677, -0.0223, -0.329, 0.2364, 2.7666, -0.7417, -1.3196, -0.2655, 0.1698, -0.1777, -0.9427, 2.6859, -0.7501, 0.5175, 1.0029, -2.6436, -0.4388, -1.2348, -0.1539, -0.6229, -0.4136, 0.5085, 0.4136, -0.6439, -1.1953, -0.406, -0.0195, 0.1869, -0.8664, 1.1364, 0.5041, 0.0647, 0.1941, -1.0819, -0.4629, -0.5107, 0.3612, -0.3583}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(op, l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.5064, 1.3655, 0.9035, 2.6859}; EXPECT(migraphx::verify_range(results_vector, gold)); } } TEST_CASE(min_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l0 = mm->add_literal(migraphx::literal{s, {1, 4, 3}}); auto l1 = mm->add_literal(migraphx::literal{s, {2, 8, 6}}); auto l2 = mm->add_literal(migraphx::literal{s, {7, 5, 9}}); auto curr_min = mm->add_instruction(migraphx::make_op("min"), l0, l1); mm->add_instruction(migraphx::make_op("min"), curr_min, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1, 4, 3}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(mul_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l1 = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); auto l2 = mm->add_literal(migraphx::literal{s, {1, 2, 3}}); mm->add_instruction(migraphx::make_op("mul"), l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-1, 0, 3}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(neg_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3}}; std::vector<float> data = {1.0f, 1.3f, -1.2f, 0.0f, -100.f, 200.f}; auto input = mm->add_literal(migraphx::literal(s, data)); auto ret = mm->add_instruction(migraphx::make_op("neg"), input); mm->add_return({ret}); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> result_vector; result.visit([&](auto output) { result_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-1.0f, -1.3f, 1.2f, 0.0f, 100.f, -200.f}; EXPECT(migraphx::verify_range(result_vector, gold)); } TEST_CASE(not_test) { // int32 { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::int32_type, {4}}; auto l1 = mm->add_literal(migraphx::literal{s, {0, 8, 1, -32}}); mm->add_instruction(migraphx::make_op("not"), l1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<char> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<char> gold = {1, 0, 0, 0}; EXPECT(migraphx::verify_range(results_vector, gold)); } // bool { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::bool_type, {4}}; auto l1 = mm->add_literal(migraphx::literal{s, {0, 0, 1, 1}}); mm->add_instruction(migraphx::make_op("not"), l1); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<char> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<char> gold = {1, 1, 0, 0}; EXPECT(migraphx::verify_range(results_vector, gold)); } } TEST_CASE(op_capture) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s1{migraphx::shape::float_type, {3, 3}}; migraphx::shape s2{migraphx::shape::float_type, {3, 6}}; std::vector<float> d1(s1.elements()); std::vector<float> d2(s2.elements()); std::iota(d1.begin(), d1.end(), 0.0f); std::iota(d2.begin(), d2.end(), 0.0f); auto p1 = mm->add_literal(s1, d1); auto p2 = mm->add_literal(s1, d1); auto pb = mm->add_literal(s2, d2); auto pc = mm->add_literal(s2, d2); auto pa = mm->add_instruction(migraphx::make_op("add"), p1, p2); auto ps = mm->add_instruction(migraphx::make_op("dot"), pa, pb, pc); mm->add_instruction(migraphx::make_op("dot"), pa, ps); migraphx::program capture_p = p; migraphx::target t = migraphx::ref::target{}; migraphx::capture_arguments(capture_p, t, {"dot"}); p.compile(migraphx::ref::target{}); capture_p.compile(migraphx::ref::target{}); auto cap_res = capture_p.eval({}).back(); auto res = p.eval({}).back(); std::vector<float> vec; std::vector<float> cap_vec; cap_res.visit([&](auto output) { cap_vec.assign(output.begin(), output.end()); }); res.visit([&](auto output) { vec.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(vec, cap_vec)); } TEST_CASE(pad_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2}}; auto l0 = mm->add_literal(migraphx::literal{s, {1, 2, 3, 4}}); mm->add_instruction(migraphx::make_op("pad", {{"pads", {1, 1, 1, 1}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(16); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0, 0, 0, 0, 0, 1, 2, 0, 0, 3, 4, 0, 0, 0, 0, 0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(pad_test_highest_half) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::half_type, {2, 2}}; auto l0 = mm->add_literal(migraphx::literal{s, {1, 2, 3, 4}}); mm->add_instruction( migraphx::make_op("pad", {{"pads", {1, 1, 1, 1}}, {"value", std::numeric_limits<float>::max()}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(16); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); const float x = std::numeric_limits<migraphx::half>::max(); std::vector<float> gold{x, x, x, x, x, 1, 2, x, x, 3, 4, x, x, x, x, x}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(pad_test_lowest_half) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::half_type, {2, 2}}; auto l0 = mm->add_literal(migraphx::literal{s, {1, 2, 3, 4}}); mm->add_instruction( migraphx::make_op( "pad", {{"pads", {1, 1, 1, 1}}, {"value", std::numeric_limits<float>::lowest()}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(16); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); const float x = std::numeric_limits<migraphx::half>::lowest(); std::vector<float> gold{x, x, x, x, x, 1, 2, x, x, 3, 4, x, x, x, x, x}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(pow_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto b = mm->add_literal(migraphx::literal{s, {1, 2, 3}}); auto e = mm->add_literal(migraphx::literal{s, {1, 2, 3}}); mm->add_instruction(migraphx::make_op("pow"), b, e); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {1.0f, 4.0f, 27.0f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(prefix_scan_sum_1d) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {6}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("prefix_scan_sum", {{"axis", 0}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 3.0, 6.0, 10.0, 15.0, 21.0}; EXPECT(results_vector == gold); } TEST_CASE(prefix_scan_sum_2d) { { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 0}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 3.0, 6.0, 9.0}; EXPECT(results_vector == gold); } { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 1}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0}; EXPECT(results_vector == gold); } } TEST_CASE(prefix_scan_sum_3d) { { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 0}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 2.0, 4.0, 6.0, 2.0, 4.0, 6.0}; EXPECT(results_vector == gold); } { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 1}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 3.0, 6.0, 9.0, 1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 3.0, 6.0, 9.0}; EXPECT(results_vector == gold); } { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 2}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0}; EXPECT(results_vector == gold); } } TEST_CASE(prefix_scan_sum_exclusive) { { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {8}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 1, 2, 3, 4}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 0}, {"exclusive", true}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0.0, 1.0, 3.0, 6.0, 10.0, 11.0, 13.0, 16.0}; EXPECT(results_vector == gold); } { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 1}, {"exclusive", true}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 2.0, 4.0, 6.0}; EXPECT(results_vector == gold); } } TEST_CASE(prefix_scan_sum_exclusive_reverse) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {6}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 0}, {"exclusive", true}, {"reverse", true}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{20.0, 18.0, 15.0, 11.0, 6.0, 0.0}; EXPECT(results_vector == gold); } TEST_CASE(prefix_scan_sum_negative_axis) { { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", -3}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 2.0, 4.0, 6.0, 2.0, 4.0, 6.0}; EXPECT(results_vector == gold); } { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", -2}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 3.0, 6.0, 9.0, 1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 3.0, 6.0, 9.0}; EXPECT(results_vector == gold); } { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 3, 3}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", -1}, {"exclusive", false}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0, 1.0, 3.0, 6.0}; EXPECT(results_vector == gold); } } TEST_CASE(prefix_scan_sum_reverse) { { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {8}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 1, 2, 3, 4}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 0}, {"exclusive", false}, {"reverse", true}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{20.0, 19.0, 17.0, 14.0, 10.0, 9.0, 7.0, 4.0}; EXPECT(results_vector == gold); } { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 1, 2, 3, 4}}; auto l0 = mm->add_literal(input); mm->add_instruction( migraphx::make_op("prefix_scan_sum", {{"axis", 0}, {"exclusive", false}, {"reverse", true}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{2.0, 4.0, 6.0, 8.0, 1.0, 2.0, 3.0, 4.0}; EXPECT(results_vector == gold); } } TEST_CASE(prelu_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto x = mm->add_literal(migraphx::literal{s, {-1, 0, 2}}); auto slope = mm->add_literal(migraphx::literal{s, {2, 1, 2}}); mm->add_instruction(migraphx::make_op("prelu"), x, slope); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-2.0f, 0.0f, 2.0f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(quant_conv2d_padding_stride_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape a_shape{migraphx::shape::int8_type, {2, 3, 4, 4}}; std::vector<int8_t> a(2 * 3 * 4 * 4); std::iota(a.begin(), a.end(), 0); auto al = mm->add_literal(migraphx::literal{a_shape, a}); migraphx::shape c_shape{migraphx::shape::int8_type, {2, 3, 3, 3}}; std::vector<int8_t> c(2 * 3 * 3 * 3); std::iota(c.begin(), c.end(), 0); auto cl = mm->add_literal(migraphx::literal{c_shape, c}); mm->add_instruction( migraphx::make_op("quant_convolution", {{"padding", {1, 1}}, {"stride", {2, 2}}}), al, cl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int32_t> s = {4521, 7014, 7830, 11952, 10515, 16734, 19737, 30906, 13161, 19542, 19494, 28800, 34707, 52590, 54729, 82746}; std::vector<int32_t> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(quant_conv2d_padding_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape a_shape{migraphx::shape::int8_type, {2, 3, 4, 4}}; std::vector<int8_t> a(2 * 3 * 4 * 4); std::iota(a.begin(), a.end(), 0); auto al = mm->add_literal(migraphx::literal{a_shape, a}); migraphx::shape c_shape{migraphx::shape::int8_type, {2, 3, 3, 3}}; std::vector<int8_t> c(2 * 3 * 3 * 3); std::iota(c.begin(), c.end(), 0); auto cl = mm->add_literal(migraphx::literal{c_shape, c}); mm->add_instruction( migraphx::make_op("quant_convolution", {{"padding", {1, 1}}, {"stride", {1, 1}}}), al, cl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int32_t> s = { 4521, 6753, 7014, 4635, 6858, 10197, 10548, 6939, 7830, 11601, 11952, 7839, 5007, 7383, 7590, 4953, 10515, 15987, 16734, 11277, 16821, 25506, 26586, 17874, 19737, 29826, 30906, 20718, 13593, 20505, 21198, 14187, 13161, 19281, 19542, 12699, 18522, 27045, 27396, 17739, 19494, 28449, 28800, 18639, 11919, 17319, 17526, 11289, 34707, 51843, 52590, 34893, 51813, 77346, 78426, 52002, 54729, 81666, 82746, 54846, 36057, 53769, 54462, 36075}; std::vector<int32_t> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(quant_conv2d_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape a_shape{migraphx::shape::int8_type, {2, 3, 4, 4}}; std::vector<int8_t> a(2 * 3 * 4 * 4); std::iota(a.begin(), a.end(), 0); auto al = mm->add_literal(migraphx::literal{a_shape, a}); migraphx::shape c_shape{migraphx::shape::int8_type, {2, 3, 3, 3}}; std::vector<int8_t> c(2 * 3 * 3 * 3); std::iota(c.begin(), c.end(), 0); auto cl = mm->add_literal(migraphx::literal{c_shape, c}); mm->add_instruction(migraphx::make_op("quant_convolution"), al, cl); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int32_t> s = {10197, 10548, 11601, 11952, 25506, 26586, 29826, 30906, 27045, 27396, 28449, 28800, 77346, 78426, 81666, 82746}; std::vector<int32_t> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(recip_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::double_type, {3}}; std::vector<float> data{-0.5f, 0.1f, 0.5f}; auto l = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction(migraphx::make_op("recip"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-2.0f, 10.0f, 2.0f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(reduce_max_axis0) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_max", {{"axes", {0}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{9, 10, 11, 12}; EXPECT(results_vector == gold); } TEST_CASE(reduce_max_axis01) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_max", {{"axes", {0, 1}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{11, 12}; EXPECT(results_vector == gold); } TEST_CASE(reduce_max_axis02) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_max", {{"axes", {0, 2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{10, 12}; EXPECT(results_vector == gold); } TEST_CASE(reduce_mean_axis02) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_mean", {{"axes", {0, 2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{5.5, 7.5}; EXPECT(results_vector == gold); } TEST_CASE(reduce_mean_axis1) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_mean", {{"axes", {1}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{2, 3, 6, 7, 10, 11}; EXPECT(results_vector == gold); } TEST_CASE(reduce_mean_axis12) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_mean", {{"axes", {1, 2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{2.5f, 6.5f, 10.5f}; EXPECT(results_vector == gold); } TEST_CASE(reduce_mean_axis2) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_mean", {{"axes", {2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1.5f, 3.5f, 5.5f, 7.5f, 9.5f, 11.5f}; EXPECT(results_vector == gold); } TEST_CASE(reduce_mean_int) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::int32_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_mean", {{"axes", {1, 2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<int> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<int> gold{2, 6, 10}; EXPECT(results_vector == gold); } TEST_CASE(reduce_min_axis02) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_min", {{"axes", {0, 2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1, 3}; EXPECT(results_vector == gold); } TEST_CASE(reduce_min_axis1) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_min", {{"axes", {1}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1, 2, 5, 6, 9, 10}; EXPECT(results_vector == gold); } TEST_CASE(reduce_min_axis12) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_min", {{"axes", {1, 2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{1, 5, 9}; EXPECT(results_vector == gold); } TEST_CASE(reduce_prod_axis0) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {4, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 3, 2, 3}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_prod", {{"axes", {0}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{6, 18, 12, 18}; EXPECT(results_vector == gold); } TEST_CASE(reduce_sum_axis0) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_sum", {{"axes", {0}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{15, 18, 21, 24}; EXPECT(results_vector == gold); } TEST_CASE(reduce_sum_axis02) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_sum", {{"axes", {0, 2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{33, 45}; EXPECT(results_vector == gold); } TEST_CASE(reduce_sum_axis1) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_sum", {{"axes", {1}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{4, 6, 12, 14, 20, 22}; EXPECT(results_vector == gold); } TEST_CASE(reduce_sum_axis12) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_sum", {{"axes", {1, 2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{10, 26, 42}; EXPECT(results_vector == gold); } TEST_CASE(reduce_sum_axis2) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3, 2, 2}}; auto input = migraphx::literal{s, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}; auto l0 = mm->add_literal(input); mm->add_instruction(migraphx::make_op("reduce_sum", {{"axes", {2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{3, 7, 11, 15, 19, 23}; EXPECT(results_vector == gold); } TEST_CASE(relu_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {-1.f, 0.f, 1.f}}); mm->add_instruction(migraphx::make_op("relu"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.f, 0.f, 1.f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(reshape_test) { migraphx::shape a_shape{migraphx::shape::float_type, {24, 1, 1, 1}}; std::vector<float> data(24); std::iota(data.begin(), data.end(), -3); { migraphx::program p; auto* mm = p.get_main_module(); auto l = mm->add_literal(migraphx::literal{a_shape, data}); std::vector<int64_t> new_shape = {8, 3, 1, 1}; mm->add_instruction(migraphx::make_op("reshape", {{"dims", new_shape}}), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, data)); } { migraphx::program p; auto* mm = p.get_main_module(); auto l = mm->add_literal(migraphx::literal{a_shape, data}); std::vector<int64_t> new_shape = {1, 3, 4, 2}; mm->add_instruction(migraphx::make_op("reshape", {{"dims", new_shape}}), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, data)); } { migraphx::program p; auto* mm = p.get_main_module(); auto l = mm->add_literal(migraphx::literal{a_shape, data}); std::vector<int64_t> new_shape = {1, 3, 4, 2}; mm->add_instruction(migraphx::make_op("reshape", {{"dims", new_shape}}), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, data)); } } TEST_CASE(round_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {9}}; auto l = mm->add_literal(migraphx::literal{s, {1.1, 1.5, 1.6, -1.1, -1.5, -1.6, 0.0, 2.0, -2.0}}); mm->add_instruction(migraphx::make_op("round"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {1.0, 2.0, 2.0, -1.0, -2.0, -2.0, 0.0, 2.0, -2.0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(rsqrt_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {4.0, 16.0, 64.0}}); mm->add_instruction(migraphx::make_op("rsqrt"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0.5, 0.25, 0.125}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(sigmoid_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2}}; auto l = mm->add_literal(migraphx::literal{s, {-1, 2, -3, 4}}); mm->add_instruction(migraphx::make_op("sigmoid"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{sigmoid(-1), sigmoid(2), sigmoid(-3), sigmoid(4)}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(sign_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {5}}; auto l = mm->add_literal( migraphx::literal{s, {1.02481645, 0.85643062, -0.03404123, -0.92791926, 0.0}}); mm->add_instruction(migraphx::make_op("sign"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {1.0, 1.0, -1.0, -1.0, 0.0}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(sin_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); mm->add_instruction(migraphx::make_op("sin"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-0.84147098f, 0.f, 0.84147098f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(sinh_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2}}; auto l = mm->add_literal(migraphx::literal{s, {-1.0, 2.0, -3.0, 4.0}}); mm->add_instruction(migraphx::make_op("sinh"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{sinhf(-1), sinhf(2), sinhf(-3), sinhf(4)}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(slice_test) { { migraphx::program p; auto* mm = p.get_main_module(); std::vector<int> data(2 * 2 * 3); std::iota(data.begin(), data.end(), 0); migraphx::shape s{migraphx::shape::int32_type, {2, 2, 3}}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction( migraphx::make_op("slice", {{"axes", {2}}, {"starts", {1}}, {"ends", {3}}}), l0); migraphx::shape s2{migraphx::shape::int32_type, {2, 2, 2}, {6, 3, 1}}; EXPECT(p.get_output_shapes().back() == s2); p.compile(migraphx::ref::target{}); migraphx::shape sresult{migraphx::shape::int32_type, {2, 2, 2}, {4, 2, 1}}; auto result = p.eval({}).back(); std::vector<int> gold = {1, 2, 4, 5, 7, 8, 10, 11}; std::vector<int> results_vector(2 * 2 * 2); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); EXPECT(result.get_shape() == sresult); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<int> data(2 * 2 * 3); std::iota(data.begin(), data.end(), 0); migraphx::shape s{migraphx::shape::int32_type, {2, 2, 3}}; auto l0 = mm->add_literal(migraphx::literal{s, data}); mm->add_instruction( migraphx::make_op("slice", {{"axes", {0, 1, 2}}, {"starts", {0, 0, 0}}, {"ends", {2, 2, 2}}}), l0); migraphx::shape s2{migraphx::shape::int32_type, {2, 2, 2}, {6, 3, 1}}; EXPECT(p.get_output_shapes().back() == s2); p.compile(migraphx::ref::target{}); migraphx::shape sresult{migraphx::shape::int32_type, {2, 2, 2}, {4, 2, 1}}; auto result = p.eval({}).back(); std::vector<int> gold = {0, 1, 3, 4, 6, 7, 9, 10}; std::vector<int> results_vector(2 * 2 * 2); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, gold)); EXPECT(result.get_shape() == sresult); } } TEST_CASE(softmax_simple_test) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = {0.25, 0.75}; std::vector<float> s = {0.377541, 0.622459}; migraphx::shape a_shape{migraphx::shape::float_type, {1, 2}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); mm->add_instruction(migraphx::make_op("softmax", {{"axis", 1}}), al); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(2); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(softmax_test) { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> a = { -5.61869681e-01, 9.07827199e-01, 1.29255986e+00, 3.18533443e-02, -1.22183852e-03, -2.83830553e-01, -1.03245842e+00, -9.28322077e-01, -8.82696748e-01, 1.11327164e-01, -9.20038462e-01, 8.47388089e-01, 2.51734018e-01, 1.50563884e+00, 2.23056650e+00, -6.17576987e-02, -1.00264274e-01, -6.10369384e-01, 1.17537189e+00, -2.51560897e-01, -8.50333512e-01, -8.03578615e-01, -6.51194930e-01, -2.58137047e-01, 4.65528190e-01, 3.23284641e-02, -1.54700470e+00, 1.38096774e+00, 5.39869189e-01, -7.56884992e-01, 1.81503093e+00, -2.11269641e+00, 1.92466557e+00, 1.77230799e+00, 2.21660900e+00, 1.56777036e+00, -2.08995026e-03, 3.50566894e-01, -1.15042710e+00, -1.18577778e+00, 8.90633047e-01, -6.63949102e-02, 1.44661188e+00, 1.59215283e+00, -2.56262213e-01, 9.39079225e-01, 4.07298543e-02, 3.86590779e-01, 6.09607756e-01, 8.22331488e-01, -2.82126725e-01, -9.49052632e-01, -4.24012303e-01, -5.32990396e-01, -3.18386006e+00, 3.27092171e-01, -1.33315325e+00, 3.62459183e-01, 3.74710828e-01, -1.30302286e+00, 1.79680198e-01, -4.51832324e-01, 4.34282750e-01, -7.09520102e-01, 6.20333970e-01, -1.28712380e+00, 2.04130828e-01, -7.70607769e-01, 1.61889160e+00, -1.50951004e+00, -4.10505563e-01, -3.56566496e-02, -1.29747534e+00, -1.49967879e-01, 7.77626812e-01, -8.28408226e-02, 2.73412596e-02, 5.79780899e-03, 9.87900198e-02, -7.95276761e-01, -1.38536084e+00, -6.63573861e-01, 3.89783204e-01, -1.30670881e+00, -7.62425125e-01, -4.04883057e-01, 6.24344349e-01, 3.68128955e-01, -1.01577950e+00, -3.06715906e-01, 5.67961395e-01, 2.98198581e-01, -1.63613629e+00, -3.75131965e-01, -6.75393403e-01, 2.59172034e+00, 6.75538957e-01, 9.07939598e-02, 1.92257717e-01, -1.21592450e+00, -2.73682117e-01, 1.25232983e+00, -1.39969170e+00, -1.91483587e-01, 2.57732719e-01, 3.10056299e-01, 1.41833842e+00, -1.81386679e-01, 3.92868072e-01, -8.14771175e-01, 2.02392387e+00, -9.42091495e-02, -3.77683818e-01, 2.05638766e+00, 2.93796062e-01, -6.02131486e-01, 2.70461679e-01, -8.92358482e-01, 1.04388881e+00, 2.66154885e-01}; std::vector<float> s = { 0.30191708, 0.59879845, 0.50029165, 0.24915339, 0.36823985, 0.13190967, 0.0349741, 0.18750034, 0.21905553, 0.27000085, 0.0547399, 0.56318235, 0.47422904, 0.78964758, 0.91381913, 0.44601166, 0.47902739, 0.13120073, 0.4449684, 0.18766427, 0.15753111, 0.07844277, 0.05120674, 0.36648798, 0.14637007, 0.13152322, 0.01560997, 0.29065287, 0.49196178, 0.10550152, 0.81890774, 0.06369215, 0.62972021, 0.74931765, 0.67285055, 0.35034987, 0.28612873, 0.31931475, 0.04220394, 0.16093165, 0.22390974, 0.11915915, 0.3115395, 0.35899726, 0.22190949, 0.57518375, 0.13888834, 0.7753762, 0.4642328, 0.57055861, 0.21954368, 0.34515455, 0.09486015, 0.40631217, 0.01842281, 0.48770609, 0.06652815, 0.36023033, 0.42343026, 0.24226256, 0.17348589, 0.44066274, 0.6865865, 0.17296699, 0.46923906, 0.06921105, 0.3570261, 0.4125829, 0.73165393, 0.15302512, 0.29499072, 0.33932695, 0.30852377, 0.40762195, 0.40170741, 0.36259529, 0.60848355, 0.42618036, 0.31721094, 0.02960522, 0.28256637, 0.24389413, 0.2725659, 0.10663581, 0.27622163, 0.28264219, 0.53652936, 0.09476089, 0.40890986, 0.34848392, 0.32572666, 0.53076893, 0.11529481, 0.29117745, 0.14625968, 0.8756339, 0.49818122, 0.10656087, 0.1813329, 0.17664003, 0.21410346, 0.80408043, 0.02315119, 0.27155462, 0.32804728, 0.13268511, 0.61795473, 0.49703068, 0.41696799, 0.10175809, 0.71028161, 0.29929739, 0.17377149, 0.76075399, 0.20071237, 0.32632929, 0.36892858, 0.09416146, 0.26656723, 0.42914796}; migraphx::shape a_shape{migraphx::shape::float_type, {5, 3, 4, 2}}; auto al = mm->add_literal(migraphx::literal{a_shape, a}); mm->add_instruction(migraphx::make_op("softmax", {{"axis", 1}}), al); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(120); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); EXPECT(migraphx::verify_range(results_vector, s)); } TEST_CASE(sqdiff_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l1 = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); auto l2 = mm->add_literal(migraphx::literal{s, {1, 2, 3}}); mm->add_instruction(migraphx::make_op("sqdiff"), l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {4, 4, 4}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(sqrt_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {5}}; auto l = mm->add_literal( migraphx::literal{s, {1.02481645, 0.85643062, 0.03404123, 0.92791926, 0.10569184}}); mm->add_instruction(migraphx::make_op("sqrt"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector; result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {1.01233218, 0.92543537, 0.18450265, 0.96328566, 0.32510282}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(squeeze_test) { { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(4 * 3 * 3); migraphx::shape s1{migraphx::shape::float_type, {4, 1, 3, 1, 3}}; migraphx::shape s2{migraphx::shape::float_type, {4, 3, 1, 3}}; auto l0 = mm->add_literal(migraphx::literal{s1, data}); mm->add_instruction(migraphx::make_op("squeeze", {{"axes", {1}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); EXPECT(result.get_shape() == s2); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(4 * 3 * 3); migraphx::shape s1{migraphx::shape::float_type, {4, 1, 3, 1, 3}}; migraphx::shape s2{migraphx::shape::float_type, {4, 1, 3, 3}}; auto l0 = mm->add_literal(migraphx::literal{s1, data}); mm->add_instruction(migraphx::make_op("squeeze", {{"axes", {3}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); EXPECT(result.get_shape() == s2); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(4 * 3 * 3); migraphx::shape s1{migraphx::shape::float_type, {4, 1, 3, 1, 3}}; migraphx::shape s2{migraphx::shape::float_type, {4, 3, 3}}; auto l0 = mm->add_literal(migraphx::literal{s1, data}); mm->add_instruction(migraphx::make_op("squeeze"), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); EXPECT(result.get_shape() == s2); } } TEST_CASE(sub_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l1 = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); auto l2 = mm->add_literal(migraphx::literal{s, {1, 2, 3}}); mm->add_instruction(migraphx::make_op("sub"), l1, l2); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-2, -2, -2}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(tan_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {3}}; auto l = mm->add_literal(migraphx::literal{s, {-1, 0, 1}}); mm->add_instruction(migraphx::make_op("tan"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(3); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {-1.55740772f, 0.0f, 1.55740772f}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(tanh_test) { migraphx::program p; auto* mm = p.get_main_module(); migraphx::shape s{migraphx::shape::float_type, {2, 2}}; auto l = mm->add_literal(migraphx::literal{s, {-1.0, 2.0, -3.0, 4.0}}); mm->add_instruction(migraphx::make_op("tanh"), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); std::vector<float> results_vector(4); result.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold{tanhf(-1), tanhf(2), tanhf(-3), tanhf(4)}; EXPECT(migraphx::verify_range(results_vector, gold)); } TEST_CASE(transpose_test) { migraphx::shape a_shape{migraphx::shape::float_type, {1, 2, 2, 3}}; std::vector<float> data(12); std::iota(data.begin(), data.end(), 0); { migraphx::program p; auto* mm = p.get_main_module(); auto l = mm->add_literal(migraphx::literal{a_shape, data}); std::vector<int64_t> perm = {0, 3, 1, 2}; mm->add_instruction(migraphx::make_op("transpose", {{"dims", perm}}), l); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); result.visit([&](auto output) { std::vector<size_t> new_lens = {1, 3, 2, 2}; EXPECT(bool{output.get_shape().lens() == new_lens}); }); } { migraphx::program p; auto* mm = p.get_main_module(); auto l = mm->add_literal(migraphx::literal{a_shape, data}); std::vector<int64_t> perm = {0, 3, 1, 2}; auto result = mm->add_instruction(migraphx::make_op("transpose", {{"dims", perm}}), l); mm->add_instruction(migraphx::make_op("contiguous"), result); p.compile(migraphx::ref::target{}); auto result2 = p.eval({}).back(); std::vector<float> results_vector(12); result2.visit([&](auto output) { results_vector.assign(output.begin(), output.end()); }); std::vector<float> gold = {0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11}; EXPECT(migraphx::verify_range(results_vector, gold)); } } TEST_CASE(unsqueeze_test) { { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(4 * 3 * 3); migraphx::shape s1{migraphx::shape::float_type, {4, 3, 3}}; migraphx::shape s2{migraphx::shape::float_type, {4, 1, 3, 3}}; auto l0 = mm->add_literal(migraphx::literal{s1, data}); mm->add_instruction(migraphx::make_op("unsqueeze", {{"axes", {1}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); EXPECT(result.get_shape() == s2); } { migraphx::program p; auto* mm = p.get_main_module(); std::vector<float> data(4 * 3 * 3); migraphx::shape s1{migraphx::shape::float_type, {4, 3, 3}}; migraphx::shape s2{migraphx::shape::float_type, {4, 3, 1, 3}}; auto l0 = mm->add_literal(migraphx::literal{s1, data}); mm->add_instruction(migraphx::make_op("unsqueeze", {{"axes", {2}}}), l0); p.compile(migraphx::ref::target{}); auto result = p.eval({}).back(); EXPECT(result.get_shape() == s2); } } int main(int argc, const char* argv[]) { test::run(argc, argv); }
45.234478
100
0.56311
[ "shape", "vector", "3d" ]
ba36d8c6745271004b7f9c18cbba88bd96a7c8fb
17,298
cpp
C++
lib/popops/Gather.cpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
95
2020-07-06T17:11:23.000Z
2022-03-12T14:42:28.000Z
lib/popops/Gather.cpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
null
null
null
lib/popops/Gather.cpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
14
2020-07-15T12:32:57.000Z
2022-01-26T14:58:45.000Z
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include "popops/Gather.hpp" #include "GatherInternal.hpp" #include "poplibs_support/Tracepoint.hpp" #include "poplibs_support/logging.hpp" #include "popops/DynamicSlice.hpp" #include "popops/ElementWise.hpp" #include "popops/Pad.hpp" #include "poputil/Broadcast.hpp" #include "poputil/TileMapping.hpp" #include "poputil/exceptions.hpp" #include <algorithm> #include <iterator> #include <string> #include <vector> #include <boost/range/algorithm.hpp> #include <boost/range/algorithm_ext.hpp> #include <boost/range/numeric.hpp> using namespace poplar; namespace logging = poplibs_support::logging; namespace poputil { template <> poplar::ProfileValue toProfileValue(const popops::GatherParams &p) { poplar::ProfileValue::Map v; v.insert({"lookupSplit", toProfileValue(p.maxElementsPerTile)}); return v; } } // namespace poputil namespace { // Transposes the given indices such that the indexVectorDim becomes the // most-minor dimension. Tensor transposeIndexVectorDimToLast(const Tensor &indices, unsigned indexVectorDim) { if (indices.rank() == indexVectorDim) { return indices; } if (indices.rank() == indexVectorDim + 1) { return indices; } std::vector<unsigned> permutation(indices.rank()); const auto front = std::begin(permutation); const auto mid = std::next(std::begin(permutation), indexVectorDim); const auto back = std::end(permutation) - 1; std::iota(front, mid, 0); std::iota(mid, back, indexVectorDim + 1); *back = indexVectorDim; return indices.dimShuffle(permutation); } // The canonicalized indices is a 2D tensor where each row represents a single // slice, and each column represents a coordinate into the input tensor. Tensor canonicalizeGatherIndices(const Tensor &startIndices, unsigned indexVectorDim, const std::vector<unsigned> &startIndexMap) { // Transpose the non-index-vector dimensions to the front. Tensor startIndicesT = transposeIndexVectorDimToLast(startIndices, indexVectorDim); const bool indicesAreScalar = startIndicesT.rank() == indexVectorDim; // The number of dimensions in startIndices that are index dimensions. const std::size_t indexDimsInScatterIndices = indicesAreScalar ? 0 : 1; // If there is only one index (i.e. indicesAreScalar has rank 1 and this // scatter is really just a dynamic update slice) add a leading degenerate // dimension for uniformity. Otherwise create a "collapsed" leading dimension // that subsumes all of the non-index-vector dimensions. std::vector<std::size_t> shape = startIndicesT.shape(); if (shape.empty()) { startIndicesT = startIndicesT.reshape({1, 1}); } else if (shape.size() == indexDimsInScatterIndices) { shape.insert(shape.begin(), 1); startIndicesT = startIndicesT.reshape(shape); } else if (indicesAreScalar) { startIndicesT = startIndicesT.reshape({startIndicesT.numElements(), 1}); } else { // Collapse all but the dimensions (0 or 1) in startIndices containing // the index vectors. std::vector<std::size_t> newShape = { startIndicesT.numElements() / shape.back(), shape.back()}; startIndicesT = startIndicesT.reshape(newShape); } // Reorganise the indices tensor to match the canonicalized input // This is kind of like a compile-time matmul with a permutation matrix std::vector<unsigned> permutation(startIndicesT.dim(1)); boost::iota(permutation, 0); boost::sort(permutation, [&](unsigned a, unsigned b) { return startIndexMap[a] < startIndexMap[b]; }); std::vector<Tensor> permutedStartIndices(startIndicesT.dim(1)); auto permuteIndices = [&](unsigned idx) { return startIndicesT.slice(idx, idx + 1, 1); }; boost::transform(permutation, permutedStartIndices.begin(), permuteIndices); return concat(permutedStartIndices, 1); } // The canonicalized input tensor has its axis permuted such that all of its // sliced axes are after the non-sliced axes. Tensor canonicalizeGatherInput(const Tensor &input, const std::vector<unsigned> &startIndexMap) { std::vector<unsigned> permutation(input.rank()); boost::iota(permutation, 0); auto dimPred = [&](std::size_t dim) { return std::find(startIndexMap.begin(), startIndexMap.end(), dim) != startIndexMap.end(); }; boost::stable_partition(permutation, dimPred); return input.dimShuffle(permutation); } // The gather result is in a canonical form where axes have been permuted such // that the zero-th dimension is a batch axis, followed by sliced axes, followed // by the non-sliced axes. This function applies an inverse of that permutation // which restores the original order of slice dimensions and keeps the batch // dimension at axis zero. Tensor adjustSliceDimensionsInAccumulator(const Tensor &accumulator, const std::vector<unsigned> &startIndexMap) { // Find the permutation of the non-batch axes which was applied to the gather // input prior to the gather. // Note that startIndexMap refers to the dimensions in the gather input which // (unlike the accumulator) doesn't have the batch dimension. std::vector<unsigned> permutation(accumulator.rank() - 1); boost::iota(permutation, 0); auto dimPred = [&](std::size_t dim) { return std::find(startIndexMap.begin(), startIndexMap.end(), dim) != startIndexMap.end(); }; // Recreate the permutation by putting the sliced axes first. boost::stable_partition(permutation, dimPred); // Reverse the permutation and add an extra 0 dimension at the beginning to // keep the batch dimension of the accumulator at the beginning and offset all // the other dimensions by one to account for this extra dimension. std::vector<unsigned> inversePermutation(permutation.size() + 1); inversePermutation[0] = 0; for (auto i = 0ul; i < permutation.size(); ++i) { inversePermutation[permutation[i] + 1] = i + 1; } return accumulator.dimShuffle(inversePermutation); } // The canonicalized input tensor has its axis permuted such that all of its // sliced axes after the non-sliced axes. This function transforms the // sliceSizes so that it still refers to the same dimensions in the // canonicalized input tensor. std::vector<std::size_t> canonicalizeSliceSizes(const std::vector<std::size_t> &sliceSizes, const std::vector<unsigned> &startIndexMap) { std::vector<unsigned> permutation(sliceSizes.size()); boost::iota(permutation, 0); auto dimPred = [&](std::size_t dim) { return std::find(startIndexMap.begin(), startIndexMap.end(), dim) != startIndexMap.end(); }; boost::stable_partition(permutation, dimPred); std::vector<std::size_t> newSliceSizes(sliceSizes.size()); for (uint i = 0; i < sliceSizes.size(); ++i) { newSliceSizes[i] = sliceSizes[permutation[i]]; } return newSliceSizes; } // This function "expands" the gather dimensions back to the indices shape. // For example, if we have an input of shape [2, 3, 4], scalar indices of shape // [1, 2, 3], and we are taking whole slices from dimension 0 of the input, the // accumulator would be of shape [6, 3, 4]. We want to reshape this back to // [1, 2, 3, 3, 4], Tensor adjustBatchDimsInAccumulator(const std::vector<std::size_t> &startIndicesShape, const Tensor &accumulator, std::size_t indexVectorDim) { std::vector<std::size_t> bounds; if (indexVectorDim < startIndicesShape.size()) { bounds.resize(startIndicesShape.size() - 1); } else { bounds.resize(startIndicesShape.size()); } const auto indicesShape = [&startIndicesShape](std::size_t dim) { return startIndicesShape[dim]; }; const auto begin = std::begin(bounds); const auto mid = begin + indexVectorDim; const auto end = std::end(bounds); std::iota(begin, mid, 0); std::iota(mid, end, indexVectorDim + 1); std::transform(begin, end, begin, indicesShape); if (bounds.empty()) { return accumulator.squeeze({0}); } else { const auto shape = accumulator.shape(); bounds.insert(std::end(bounds), std::begin(shape) + 1, std::end(shape)); return accumulator.reshape(bounds); } } // Undo the partitioning of the canonicalization on the accumulator. This // shuffles the dimensions back to how the users expects for the output. Tensor permuteBatchAndOffsetDims(const Tensor &accumulator, const std::vector<std::size_t> &offsetDims, std::size_t outputRank) { std::vector<unsigned> permutation; permutation.reserve(outputRank); std::size_t batch_idx_counter = 0; std::size_t offset_idx_counter = outputRank - offsetDims.size(); for (std::size_t dim = 0; dim < outputRank; ++dim) { bool is_offset_dim = std::find(offsetDims.begin(), offsetDims.end(), dim) != offsetDims.end(); if (is_offset_dim) { permutation.push_back(offset_idx_counter++); } else { permutation.push_back(batch_idx_counter++); } } return accumulator.dimShuffle(permutation); } } // namespace namespace popops { poplar::Tensor createGatherInput(poplar::Graph &graph, const poplar::Type &type, const std::vector<std::size_t> &inputShape, const std::vector<std::size_t> &sliceSizes, std::vector<unsigned> startIndexMap, const poplar::DebugContext &debugContext) { POPOPS_TRACEPOINT(); poputil::PoplibsOpDebugInfo di( debugContext, DI_ARGS(type, inputShape, sliceSizes, startIndexMap)); std::vector<unsigned> permutation(inputShape.size()); boost::iota(permutation, 0); auto dimPred = [&](std::size_t dim) { return std::find(startIndexMap.begin(), startIndexMap.end(), dim) != startIndexMap.end(); }; boost::stable_partition(permutation, dimPred); std::vector<std::size_t> canonShape; canonShape.reserve(inputShape.size()); for (auto i = 0ul; i < inputShape.size(); ++i) { canonShape.emplace_back(inputShape[permutation[i]]); } std::vector<std::size_t> canonSliceSizes; canonSliceSizes.reserve(startIndexMap.size()); std::sort(startIndexMap.begin(), startIndexMap.end()); for (unsigned i = 0; i < startIndexMap.size(); ++i) { canonSliceSizes.push_back(sliceSizes[startIndexMap[i]]); } auto input = internal::createGatherInputTensor(graph, type, canonShape, canonSliceSizes, {di}); std::vector<unsigned> inversePermutation(inputShape.size()); for (auto i = 0ul; i < inputShape.size(); ++i) { inversePermutation[permutation[i]] = i; } input = input.dimShuffle(inversePermutation); di.addOutput(input); return input; } Tensor gather(Graph &graph, const Tensor &input, const Tensor &indices, std::size_t indexVectorDim, const std::vector<std::size_t> &offsetDims, const std::vector<std::size_t> &sliceSizes, const std::vector<std::size_t> &collapsedSliceDims, const std::vector<unsigned> &startIndexMap, program::Sequence &prog, const poplar::DebugContext &debugContext) { POPOPS_TRACEPOINT(); poputil::PoplibsOpDebugInfo di( debugContext, DI_ARGS(input, indices, indexVectorDim, offsetDims, sliceSizes, collapsedSliceDims, startIndexMap)); logging::popops::info("gather input={}, indices={}, name={}", input.shape(), indices.shape(), debugContext.getPathName()); auto canonicalizedIndices = canonicalizeGatherIndices(indices, indexVectorDim, startIndexMap); auto canonicalizedInput = canonicalizeGatherInput(input, startIndexMap); auto canonSliceSizes = canonicalizeSliceSizes(sliceSizes, startIndexMap); for (uint i = canonicalizedIndices.dim(1); i < canonSliceSizes.size(); ++i) { canonicalizedInput = canonicalizedInput.slice(0, canonSliceSizes[i], i); } canonSliceSizes.resize(canonicalizedIndices.dim(1)); auto result = internal::gather(graph, canonicalizedInput, canonicalizedIndices, canonSliceSizes, prog, {di}); // Permute the dimensions in the result tensor to put the sliced and // non-sliced axes back into their original positions. result = adjustSliceDimensionsInAccumulator(result, startIndexMap); // Remove collapsed slice dimensions. auto offsetCollapsedSliceDims = collapsedSliceDims; boost::transform(offsetCollapsedSliceDims, offsetCollapsedSliceDims.begin(), [](std::size_t dim) { return dim + 1; }); result = result.squeeze(offsetCollapsedSliceDims); // Expand batch axes. result = adjustBatchDimsInAccumulator(indices.shape(), result, indexVectorDim); // Permute the dimensions into the expected output format. const auto outputRank = (indices.rank() == indexVectorDim ? 0 : -1) + offsetDims.size() + indices.rank(); auto output = permuteBatchAndOffsetDims(result, offsetDims, outputRank); di.addOutput(output); return output; } Tensor createGatherInput(Graph &graph, const Type &type, const std::vector<std::size_t> &operandShape, unsigned axis, GatherParams params, const poplar::DebugContext &debugContext) { POPOPS_TRACEPOINT(); poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(type, operandShape, axis, params)); if (operandShape[axis] > params.maxElementsPerTile) { std::vector<std::size_t> newOperandShape = operandShape; if (operandShape[axis] % 2 == 1) { newOperandShape[axis] += 1; auto output = createGatherInput(graph, type, newOperandShape, axis, params, {di}) .slice(0, operandShape[axis], axis); di.addOutput(output); return output; } else { newOperandShape[axis] /= 2; newOperandShape.insert(newOperandShape.begin() + axis + 1, 2); auto output = createGatherInput(graph, type, newOperandShape, axis, params, {di}) .reshape(operandShape); di.addOutput(output); return output; } } else { const std::vector<std::size_t> sliceSizes = {1}; std::vector<unsigned> permutation(operandShape.size()); boost::iota(permutation, 0); std::swap(permutation.front(), permutation[axis]); std::vector<std::size_t> canonShape = operandShape; for (unsigned i = 0; i < operandShape.size(); ++i) { canonShape[i] = operandShape[permutation[i]]; } auto input = internal::createGatherInputTensor(graph, type, canonShape, sliceSizes, {di}); auto output = input.dimShuffle(permutation); di.addOutput(output); return output; } } Tensor gather(Graph &graph, const Tensor &input, const Tensor &indices, unsigned axis, program::Sequence &prog, GatherParams params, const poplar::DebugContext &debugContext) { POPOPS_TRACEPOINT(); poputil::PoplibsOpDebugInfo di(debugContext, DI_ARGS(input, indices, axis, params)); if (input.dim(axis) > params.maxElementsPerTile) { if (input.dim(axis) % 2 == 1) { return gather(graph, pad(graph, input, 0, 1, axis), indices, axis, prog, params, {di}); } auto shape = input.shape(); shape[axis] /= 2; shape.insert(shape.begin() + axis + 1, 2); auto one = graph.addConstant(UNSIGNED_INT, {}, 1, {di, "const_1"}); graph.setTileMapping(one, 0); auto indicesDiv = shiftRight(graph, indices, one, prog, {di}); auto indicesRem = bitwiseAnd(graph, indices, one, prog, {di}); auto indicesPred = eq(graph, indicesRem, one, prog, {di}); auto result = gather(graph, input.reshape(shape), indicesDiv, axis, prog, params, {di, "halved"}); // The odd and even slice pairs from the split gather auto even = result.slice(0, 1, axis + 1); auto odd = result.slice(1, 2, axis + 1); auto s = odd.shape(); std::fill(s.begin(), s.end(), 1); s[axis] = indicesPred.numElements(); indicesPred = indicesPred.reshape(s); poputil::broadcastToMatch(indicesPred, odd.shape()); auto output = select(graph, odd, even, indicesPred, prog).squeeze({axis + 1}); di.addOutput(output); return output; } const std::vector<std::size_t> sliceSizes = {1}; std::vector<unsigned> inputPermutation(input.rank()); boost::iota(inputPermutation, 0); std::swap(inputPermutation.front(), inputPermutation[axis]); auto output = internal::gather(graph, input.dimShuffle(inputPermutation), indices.flatten().expand({1}), sliceSizes, prog, {di}); output = output.squeeze({1}); std::vector<unsigned> outputPermutation(output.rank()); boost::iota(outputPermutation, 0); std::swap(outputPermutation.front(), outputPermutation[axis]); auto output_ = output.dimShuffle(outputPermutation); di.addOutput(output_); return output_; } } // namespace popops
37.040685
80
0.672679
[ "shape", "vector", "transform" ]
ba3769814a3dc185adeef127f4310d8485dde1f0
17,019
cc
C++
content/renderer/media/webmediaplayer_ms_compositor.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
content/renderer/media/webmediaplayer_ms_compositor.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
content/renderer/media/webmediaplayer_ms_compositor.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.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 "content/renderer/media/webmediaplayer_ms_compositor.h" #include <stdint.h> #include <string> #include "base/command_line.h" #include "base/hash.h" #include "base/single_thread_task_runner.h" #include "base/values.h" #include "content/common/gpu/client/context_provider_command_buffer.h" #include "content/renderer/media/webmediaplayer_ms.h" #include "content/renderer/render_thread_impl.h" #include "media/base/media_switches.h" #include "media/base/video_frame.h" #include "media/base/video_util.h" #include "media/filters/video_renderer_algorithm.h" #include "media/renderers/skcanvas_video_renderer.h" #include "skia/ext/platform_canvas.h" #include "third_party/WebKit/public/platform/WebMediaStream.h" #include "third_party/WebKit/public/platform/WebMediaStreamSource.h" #include "third_party/WebKit/public/platform/WebMediaStreamTrack.h" #include "third_party/libyuv/include/libyuv/convert.h" #include "third_party/libyuv/include/libyuv/video_common.h" namespace content { namespace { // This function copies |frame| to a new I420 or YV12A media::VideoFrame. scoped_refptr<media::VideoFrame> CopyFrame( const scoped_refptr<media::VideoFrame>& frame, media::SkCanvasVideoRenderer* video_renderer) { scoped_refptr<media::VideoFrame> new_frame; if (frame->HasTextures()) { DCHECK(frame->format() == media::PIXEL_FORMAT_ARGB || frame->format() == media::PIXEL_FORMAT_XRGB || frame->format() == media::PIXEL_FORMAT_I420 || frame->format() == media::PIXEL_FORMAT_UYVY || frame->format() == media::PIXEL_FORMAT_NV12); new_frame = media::VideoFrame::CreateFrame( media::PIXEL_FORMAT_I420, frame->coded_size(), frame->visible_rect(), frame->natural_size(), frame->timestamp()); SkBitmap bitmap; bitmap.allocN32Pixels(frame->visible_rect().width(), frame->visible_rect().height()); SkCanvas canvas(bitmap); auto* provider = RenderThreadImpl::current()->SharedMainThreadContextProvider().get(); if (provider) { const media::Context3D context_3d = media::Context3D(provider->ContextGL(), provider->GrContext()); DCHECK(context_3d.gl); video_renderer->Copy(frame.get(), &canvas, context_3d); } else { // GPU Process crashed. bitmap.eraseColor(SK_ColorTRANSPARENT); } libyuv::ARGBToI420(reinterpret_cast<uint8_t*>(bitmap.getPixels()), bitmap.rowBytes(), new_frame->visible_data(media::VideoFrame::kYPlane), new_frame->stride(media::VideoFrame::kYPlane), new_frame->visible_data(media::VideoFrame::kUPlane), new_frame->stride(media::VideoFrame::kUPlane), new_frame->visible_data(media::VideoFrame::kVPlane), new_frame->stride(media::VideoFrame::kVPlane), bitmap.width(), bitmap.height()); } else { DCHECK(frame->IsMappable()); DCHECK(frame->format() == media::PIXEL_FORMAT_YV12 || frame->format() == media::PIXEL_FORMAT_YV12A || frame->format() == media::PIXEL_FORMAT_I420); const gfx::Size& coded_size = frame->coded_size(); new_frame = media::VideoFrame::CreateFrame( media::IsOpaque(frame->format()) ? media::PIXEL_FORMAT_I420 : media::PIXEL_FORMAT_YV12A, coded_size, frame->visible_rect(), frame->natural_size(), frame->timestamp()); libyuv::I420Copy(frame->data(media::VideoFrame::kYPlane), frame->stride(media::VideoFrame::kYPlane), frame->data(media::VideoFrame::kUPlane), frame->stride(media::VideoFrame::kUPlane), frame->data(media::VideoFrame::kVPlane), frame->stride(media::VideoFrame::kVPlane), new_frame->data(media::VideoFrame::kYPlane), new_frame->stride(media::VideoFrame::kYPlane), new_frame->data(media::VideoFrame::kUPlane), new_frame->stride(media::VideoFrame::kUPlane), new_frame->data(media::VideoFrame::kVPlane), new_frame->stride(media::VideoFrame::kVPlane), coded_size.width(), coded_size.height()); if (frame->format() == media::PIXEL_FORMAT_YV12A) { libyuv::CopyPlane(frame->data(media::VideoFrame::kAPlane), frame->stride(media::VideoFrame::kAPlane), new_frame->data(media::VideoFrame::kAPlane), new_frame->stride(media::VideoFrame::kAPlane), coded_size.width(), coded_size.height()); } } // Transfer metadata keys. base::DictionaryValue original_metadata; frame->metadata()->MergeInternalValuesInto(&original_metadata); new_frame->metadata()->MergeInternalValuesFrom(original_metadata); return new_frame; } } // anonymous namespace WebMediaPlayerMSCompositor::WebMediaPlayerMSCompositor( const scoped_refptr<base::SingleThreadTaskRunner>& compositor_task_runner, const blink::WebMediaStream& web_stream, const base::WeakPtr<WebMediaPlayerMS>& player) : compositor_task_runner_(compositor_task_runner), player_(player), video_frame_provider_client_(nullptr), current_frame_used_by_compositor_(false), last_render_length_(base::TimeDelta::FromSecondsD(1.0 / 60.0)), total_frame_count_(0), dropped_frame_count_(0), stopped_(true), weak_ptr_factory_(this) { main_message_loop_ = base::MessageLoop::current(); blink::WebVector<blink::WebMediaStreamTrack> video_tracks; if (!web_stream.isNull()) web_stream.videoTracks(video_tracks); const bool remote_video = video_tracks.size() && video_tracks[0].source().remote(); if (remote_video && !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableRTCSmoothnessAlgorithm)) { base::AutoLock auto_lock(current_frame_lock_); rendering_frame_buffer_.reset(new media::VideoRendererAlgorithm( base::Bind(&WebMediaPlayerMSCompositor::MapTimestampsToRenderTimeTicks, base::Unretained(this)))); } // Just for logging purpose. std::string stream_id = web_stream.isNull() ? std::string() : web_stream.id().utf8(); const uint32_t hash_value = base::Hash(stream_id); serial_ = (hash_value << 1) | (remote_video ? 1 : 0); } WebMediaPlayerMSCompositor::~WebMediaPlayerMSCompositor() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); if (video_frame_provider_client_) video_frame_provider_client_->StopUsingProvider(); } gfx::Size WebMediaPlayerMSCompositor::GetCurrentSize() { DCHECK(thread_checker_.CalledOnValidThread()); base::AutoLock auto_lock(current_frame_lock_); return current_frame_ ? current_frame_->natural_size() : gfx::Size(); } base::TimeDelta WebMediaPlayerMSCompositor::GetCurrentTime() { DCHECK(thread_checker_.CalledOnValidThread()); base::AutoLock auto_lock(current_frame_lock_); return current_frame_.get() ? current_frame_->timestamp() : base::TimeDelta(); } size_t WebMediaPlayerMSCompositor::total_frame_count() const { DVLOG(1) << __FUNCTION__ << ", " << total_frame_count_; DCHECK(thread_checker_.CalledOnValidThread()); return total_frame_count_; } size_t WebMediaPlayerMSCompositor::dropped_frame_count() const { DVLOG(1) << __FUNCTION__ << ", " << dropped_frame_count_; DCHECK(thread_checker_.CalledOnValidThread()); return dropped_frame_count_; } void WebMediaPlayerMSCompositor::SetVideoFrameProviderClient( cc::VideoFrameProvider::Client* client) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); if (video_frame_provider_client_) video_frame_provider_client_->StopUsingProvider(); video_frame_provider_client_ = client; if (video_frame_provider_client_ && !stopped_) video_frame_provider_client_->StartRendering(); } void WebMediaPlayerMSCompositor::EnqueueFrame( const scoped_refptr<media::VideoFrame>& frame) { DCHECK(thread_checker_.CalledOnValidThread()); base::AutoLock auto_lock(current_frame_lock_); ++total_frame_count_; // With algorithm off, just let |current_frame_| hold the incoming |frame|. if (!rendering_frame_buffer_) { SetCurrentFrame(frame); return; } // This is a signal frame saying that the stream is stopped. bool end_of_stream = false; if (frame->metadata()->GetBoolean(media::VideoFrameMetadata::END_OF_STREAM, &end_of_stream) && end_of_stream) { rendering_frame_buffer_.reset(); SetCurrentFrame(frame); return; } // If we detect a bad frame without |render_time|, we switch off algorithm, // because without |render_time|, algorithm cannot work. // In general, this should not happen. base::TimeTicks render_time; if (!frame->metadata()->GetTimeTicks( media::VideoFrameMetadata::REFERENCE_TIME, &render_time)) { DLOG(WARNING) << "Incoming VideoFrames have no REFERENCE_TIME, switching off super " "sophisticated rendering algorithm"; rendering_frame_buffer_.reset(); SetCurrentFrame(frame); return; } // The code below handles the case where UpdateCurrentFrame() callbacks stop. // These callbacks can stop when the tab is hidden or the page area containing // the video frame is scrolled out of view. // Since some hardware decoders only have a limited number of output frames, // we must aggressively release frames in this case. const base::TimeTicks now = base::TimeTicks::Now(); if (now > last_deadline_max_) { // Note: the frame in |rendering_frame_buffer_| with lowest index is the // same as |current_frame_|. Function SetCurrentFrame() handles whether // to increase |dropped_frame_count_| for that frame, so here we should // increase |dropped_frame_count_| by the count of all other frames. dropped_frame_count_ += rendering_frame_buffer_->frames_queued() - 1; rendering_frame_buffer_->Reset(); timestamps_to_clock_times_.clear(); SetCurrentFrame(frame); } timestamps_to_clock_times_[frame->timestamp()] = render_time; rendering_frame_buffer_->EnqueueFrame(frame); } bool WebMediaPlayerMSCompositor::UpdateCurrentFrame( base::TimeTicks deadline_min, base::TimeTicks deadline_max) { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); TRACE_EVENT_BEGIN2("webrtc", "WebMediaPlayerMS::UpdateCurrentFrame", "Actual Render Begin", deadline_min.ToInternalValue(), "Actual Render End", deadline_max.ToInternalValue()); if (stopped_) return false; base::TimeTicks render_time; base::AutoLock auto_lock(current_frame_lock_); if (rendering_frame_buffer_) Render(deadline_min, deadline_max); if (!current_frame_->metadata()->GetTimeTicks( media::VideoFrameMetadata::REFERENCE_TIME, &render_time)) { DCHECK(!rendering_frame_buffer_) << "VideoFrames need REFERENCE_TIME to use " "sophisticated video rendering algorithm."; } TRACE_EVENT_END2("webrtc", "WebMediaPlayerMS::UpdateCurrentFrame", "Ideal Render Instant", render_time.ToInternalValue(), "Serial", serial_); return !current_frame_used_by_compositor_; } bool WebMediaPlayerMSCompositor::HasCurrentFrame() { base::AutoLock auto_lock(current_frame_lock_); return current_frame_.get() != nullptr; } scoped_refptr<media::VideoFrame> WebMediaPlayerMSCompositor::GetCurrentFrame() { DVLOG(3) << __FUNCTION__; base::AutoLock auto_lock(current_frame_lock_); current_frame_used_by_compositor_ = true; return current_frame_; } void WebMediaPlayerMSCompositor::PutCurrentFrame() { DVLOG(3) << __FUNCTION__; } scoped_refptr<media::VideoFrame> WebMediaPlayerMSCompositor::GetCurrentFrameWithoutUpdatingStatistics() { DVLOG(3) << __FUNCTION__; base::AutoLock auto_lock(current_frame_lock_); return current_frame_; } void WebMediaPlayerMSCompositor::StartRendering() { DCHECK(thread_checker_.CalledOnValidThread()); compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerMSCompositor::StartRenderingInternal, weak_ptr_factory_.GetWeakPtr())); } void WebMediaPlayerMSCompositor::StartRenderingInternal() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); stopped_ = false; if (video_frame_provider_client_) video_frame_provider_client_->StartRendering(); } void WebMediaPlayerMSCompositor::StopRendering() { DCHECK(thread_checker_.CalledOnValidThread()); compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerMSCompositor::StopRenderingInternal, weak_ptr_factory_.GetWeakPtr())); } void WebMediaPlayerMSCompositor::StopRenderingInternal() { DCHECK(compositor_task_runner_->BelongsToCurrentThread()); stopped_ = true; // It is possible that the video gets paused and then resumed. We need to // reset VideoRendererAlgorithm, otherwise, VideoRendererAlgorithm will think // there is a very long frame in the queue and then make totally wrong // frame selection. { base::AutoLock auto_lock(current_frame_lock_); if (rendering_frame_buffer_) rendering_frame_buffer_->Reset(); } if (video_frame_provider_client_) video_frame_provider_client_->StopRendering(); } void WebMediaPlayerMSCompositor::ReplaceCurrentFrameWithACopy() { DCHECK(thread_checker_.CalledOnValidThread()); base::AutoLock auto_lock(current_frame_lock_); if (!current_frame_.get() || !player_) return; // Copy the frame so that rendering can show the last received frame. // The original frame must not be referenced when the player is paused since // there might be a finite number of available buffers. E.g, video that // originates from a video camera. current_frame_ = CopyFrame(current_frame_, player_->GetSkCanvasVideoRenderer()); } bool WebMediaPlayerMSCompositor::MapTimestampsToRenderTimeTicks( const std::vector<base::TimeDelta>& timestamps, std::vector<base::TimeTicks>* wall_clock_times) { DCHECK(compositor_task_runner_->BelongsToCurrentThread() || thread_checker_.CalledOnValidThread()); for (const base::TimeDelta& timestamp : timestamps) { DCHECK(timestamps_to_clock_times_.count(timestamp)); wall_clock_times->push_back(timestamps_to_clock_times_[timestamp]); } return true; } void WebMediaPlayerMSCompositor::Render(base::TimeTicks deadline_min, base::TimeTicks deadline_max) { DCHECK(compositor_task_runner_->BelongsToCurrentThread() || thread_checker_.CalledOnValidThread()); current_frame_lock_.AssertAcquired(); last_deadline_max_ = deadline_max; last_render_length_ = deadline_max - deadline_min; size_t frames_dropped = 0; scoped_refptr<media::VideoFrame> frame = rendering_frame_buffer_->Render( deadline_min, deadline_max, &frames_dropped); dropped_frame_count_ += frames_dropped; // There is a chance we get a null |frame| here: // When the player gets paused, we reset |rendering_frame_buffer_|; // When the player gets resumed, it is possible that render gets called before // we get a new frame. In that case continue to render the |current_frame_|. if (!frame || frame == current_frame_) return; SetCurrentFrame(frame); const auto& end = timestamps_to_clock_times_.end(); const auto& begin = timestamps_to_clock_times_.begin(); auto iterator = begin; while (iterator != end && iterator->first < frame->timestamp()) ++iterator; timestamps_to_clock_times_.erase(begin, iterator); } void WebMediaPlayerMSCompositor::SetCurrentFrame( const scoped_refptr<media::VideoFrame>& frame) { current_frame_lock_.AssertAcquired(); if (!current_frame_used_by_compositor_) ++dropped_frame_count_; current_frame_used_by_compositor_ = false; const bool size_changed = !current_frame_ || current_frame_->natural_size() != frame->natural_size(); current_frame_ = frame; if (size_changed) { main_message_loop_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerMS::TriggerResize, player_)); } main_message_loop_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerMS::ResetCanvasCache, player_)); } void WebMediaPlayerMSCompositor::SetAlgorithmEnabledForTesting( bool algorithm_enabled) { if (!algorithm_enabled) { rendering_frame_buffer_.reset(); return; } if (!rendering_frame_buffer_) { rendering_frame_buffer_.reset(new media::VideoRendererAlgorithm( base::Bind(&WebMediaPlayerMSCompositor::MapTimestampsToRenderTimeTicks, base::Unretained(this)))); } } } // namespace content
39.034404
80
0.712909
[ "render", "vector" ]
ba3a08ee0aecb4aa24da14f54b5f34ec8d721286
2,508
cc
C++
modules/audio_coding/neteq4/test/RTPtimeshift.cc
aleonliao/webrtc-3.31
a282cc166883aea82a8149d64e82ca29aa9f27f1
[ "DOC", "BSD-3-Clause" ]
7
2015-08-06T01:46:07.000Z
2020-10-20T09:14:58.000Z
modules/audio_coding/neteq4/test/RTPtimeshift.cc
aleonliao/webrtc-3.31
a282cc166883aea82a8149d64e82ca29aa9f27f1
[ "DOC", "BSD-3-Clause" ]
null
null
null
modules/audio_coding/neteq4/test/RTPtimeshift.cc
aleonliao/webrtc-3.31
a282cc166883aea82a8149d64e82ca29aa9f27f1
[ "DOC", "BSD-3-Clause" ]
16
2015-01-08T01:47:24.000Z
2022-02-25T06:06:06.000Z
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <algorithm> #include <stdio.h> #include <vector> #include "NETEQTEST_RTPpacket.h" #include "gtest/gtest.h" /*********************/ /* Misc. definitions */ /*********************/ #define FIRSTLINELEN 40 int main(int argc, char* argv[]) { if(argc < 4 || argc > 6) { printf("Usage: RTPtimeshift in.rtp out.rtp newStartTS [newStartSN [newStartArrTime]]\n"); exit(1); } FILE *inFile=fopen(argv[1],"rb"); if (!inFile) { printf("Cannot open input file %s\n", argv[1]); return(-1); } printf("Input RTP file: %s\n",argv[1]); FILE *outFile=fopen(argv[2],"wb"); if (!outFile) { printf("Cannot open output file %s\n", argv[2]); return(-1); } printf("Output RTP file: %s\n\n",argv[2]); // read file header and write directly to output file const unsigned int kRtpDumpHeaderSize = 4 + 4 + 4 + 2 + 2; char firstline[FIRSTLINELEN]; EXPECT_TRUE(fgets(firstline, FIRSTLINELEN, inFile) != NULL); EXPECT_GT(fputs(firstline, outFile), 0); EXPECT_EQ(kRtpDumpHeaderSize, fread(firstline, 1, kRtpDumpHeaderSize, inFile)); EXPECT_EQ(kRtpDumpHeaderSize, fwrite(firstline, 1, kRtpDumpHeaderSize, outFile)); NETEQTEST_RTPpacket packet; int packLen = packet.readFromFile(inFile); if (packLen < 0) { exit(1); } // get new start TS and start SeqNo from arguments uint32_t TSdiff = atoi(argv[3]) - packet.timeStamp(); uint16_t SNdiff = 0; uint32_t ATdiff = 0; if (argc > 4) { if (argv[4] >= 0) SNdiff = atoi(argv[4]) - packet.sequenceNumber(); if (argc > 5) { if (argv[5] >= 0) ATdiff = atoi(argv[5]) - packet.time(); } } while (packLen >= 0) { packet.setTimeStamp(packet.timeStamp() + TSdiff); packet.setSequenceNumber(packet.sequenceNumber() + SNdiff); packet.setTime(packet.time() + ATdiff); packet.writeToFile(outFile); packLen = packet.readFromFile(inFile); } fclose(inFile); fclose(outFile); return 0; }
25.591837
97
0.611244
[ "vector" ]
ba3ca51dc046efaa77c2a190a5aa607348a44530
27,452
cc
C++
content/browser/browser_child_process_host_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
content/browser/browser_child_process_host_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
content/browser/browser_child_process_host_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/browser_child_process_host_impl.h" #include <memory> #include "base/base_switches.h" #include "base/bind.h" #include "base/clang_profiling_buildflags.h" #include "base/command_line.h" #include "base/cxx17_backports.h" #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/persistent_histogram_allocator.h" #include "base/metrics/persistent_memory_allocator.h" #include "base/strings/string_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread_task_runner_handle.h" #include "base/token.h" #include "base/trace_event/memory_dump_manager.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "components/tracing/common/trace_startup_config.h" #include "components/tracing/common/tracing_switches.h" #include "content/browser/browser_main_loop.h" #include "content/browser/metrics/histogram_controller.h" #include "content/browser/tracing/background_tracing_manager_impl.h" #include "content/common/child_process_host_impl.h" #include "content/public/browser/browser_child_process_host_delegate.h" #include "content/public/browser/browser_child_process_observer.h" #include "content/public/browser/browser_message_filter.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/resource_coordinator_service.h" #include "content/public/common/content_client.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/result_codes.h" #include "content/public/common/sandboxed_process_launcher_delegate.h" #include "mojo/public/cpp/bindings/scoped_message_error_crash_key.h" #include "mojo/public/cpp/system/platform_handle.h" #include "services/tracing/public/cpp/trace_startup.h" #if defined(OS_MAC) #include "content/browser/child_process_task_port_provider_mac.h" #include "content/browser/sandbox_support_mac_impl.h" #include "content/common/sandbox_support_mac.mojom.h" #endif #if defined(OS_POSIX) && !defined(OS_ANDROID) #include "services/tracing/public/cpp/system_tracing_service.h" #endif #if defined(OS_WIN) #include "content/browser/renderer_host/dwrite_font_proxy_impl_win.h" #include "content/public/common/font_cache_dispatcher_win.h" #include "content/public/common/font_cache_win.mojom.h" #endif #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX) #include "content/public/common/profiling_utils.h" #endif namespace content { namespace { static base::LazyInstance< BrowserChildProcessHostImpl::BrowserChildProcessList>::DestructorAtExit g_child_process_list = LAZY_INSTANCE_INITIALIZER; base::LazyInstance<base::ObserverList<BrowserChildProcessObserver>::Unchecked>:: DestructorAtExit g_browser_child_process_observers = LAZY_INSTANCE_INITIALIZER; void NotifyProcessLaunchedAndConnected(const ChildProcessData& data) { for (auto& observer : g_browser_child_process_observers.Get()) observer.BrowserChildProcessLaunchedAndConnected(data); } void NotifyProcessKilled(const ChildProcessData& data, const ChildProcessTerminationInfo& info) { for (auto& observer : g_browser_child_process_observers.Get()) observer.BrowserChildProcessKilled(data, info); } memory_instrumentation::mojom::ProcessType GetCoordinatorClientProcessType( ProcessType process_type) { switch (process_type) { case PROCESS_TYPE_RENDERER: return memory_instrumentation::mojom::ProcessType::RENDERER; case PROCESS_TYPE_UTILITY: return memory_instrumentation::mojom::ProcessType::UTILITY; case PROCESS_TYPE_GPU: return memory_instrumentation::mojom::ProcessType::GPU; case PROCESS_TYPE_PPAPI_PLUGIN: case PROCESS_TYPE_PPAPI_BROKER: return memory_instrumentation::mojom::ProcessType::PLUGIN; default: NOTREACHED(); return memory_instrumentation::mojom::ProcessType::OTHER; } } void BindTracedProcessFromUIThread( base::WeakPtr<BrowserChildProcessHostImpl> weak_host, mojo::PendingReceiver<tracing::mojom::TracedProcess> receiver) { if (!weak_host) return; weak_host->GetHost()->BindReceiver(std::move(receiver)); } } // namespace // static std::unique_ptr<BrowserChildProcessHost> BrowserChildProcessHost::Create( content::ProcessType process_type, BrowserChildProcessHostDelegate* delegate, ChildProcessHost::IpcMode ipc_mode) { return std::make_unique<BrowserChildProcessHostImpl>(process_type, delegate, ipc_mode); } BrowserChildProcessHost* BrowserChildProcessHost::FromID(int child_process_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserChildProcessHostImpl::BrowserChildProcessList* process_list = g_child_process_list.Pointer(); for (BrowserChildProcessHostImpl* host : *process_list) { if (host->GetData().id == child_process_id) return host; } return nullptr; } #if defined(OS_MAC) base::PortProvider* BrowserChildProcessHost::GetPortProvider() { return ChildProcessTaskPortProvider::GetInstance(); } #endif // static BrowserChildProcessHostImpl::BrowserChildProcessList* BrowserChildProcessHostImpl::GetIterator() { return g_child_process_list.Pointer(); } // static void BrowserChildProcessHostImpl::AddObserver( BrowserChildProcessObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); g_browser_child_process_observers.Get().AddObserver(observer); } // static void BrowserChildProcessHostImpl::RemoveObserver( BrowserChildProcessObserver* observer) { // TODO(phajdan.jr): Check thread after fixing http://crbug.com/167126. g_browser_child_process_observers.Get().RemoveObserver(observer); } BrowserChildProcessHostImpl::BrowserChildProcessHostImpl( content::ProcessType process_type, BrowserChildProcessHostDelegate* delegate, ChildProcessHost::IpcMode ipc_mode) : data_(process_type), delegate_(delegate) { DCHECK_CURRENTLY_ON(BrowserThread::UI); data_.id = ChildProcessHostImpl::GenerateChildProcessUniqueId(); child_process_host_ = ChildProcessHost::Create(this, ipc_mode); g_child_process_list.Get().push_back(this); GetContentClient()->browser()->BrowserChildProcessHostCreated(this); // Create a persistent memory segment for subprocess histograms. CreateMetricsAllocator(); } BrowserChildProcessHostImpl::~BrowserChildProcessHostImpl() { DCHECK_CURRENTLY_ON(BrowserThread::UI); g_child_process_list.Get().remove(this); if (!notify_child_connection_status_) return; ChildProcessData data = data_.Duplicate(); for (auto& observer : g_browser_child_process_observers.Get()) observer.BrowserChildProcessHostDisconnected(data); } // static void BrowserChildProcessHostImpl::TerminateAll() { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Make a copy since the BrowserChildProcessHost dtor mutates the original // list. BrowserChildProcessList copy = g_child_process_list.Get(); for (auto it = copy.begin(); it != copy.end(); ++it) { delete (*it)->delegate(); // ~*HostDelegate deletes *HostImpl. } } // static void BrowserChildProcessHostImpl::CopyTraceStartupFlags( base::CommandLine* cmd_line) { tracing::PropagateTracingFlagsToChildProcessCmdLine(cmd_line); } void BrowserChildProcessHostImpl::Launch( std::unique_ptr<SandboxedProcessLauncherDelegate> delegate, std::unique_ptr<base::CommandLine> cmd_line, bool terminate_on_shutdown) { LaunchWithPreloadedFiles(std::move(delegate), std::move(cmd_line), /*files_to_preload=*/{}, terminate_on_shutdown); } void BrowserChildProcessHostImpl::LaunchWithPreloadedFiles( std::unique_ptr<SandboxedProcessLauncherDelegate> delegate, std::unique_ptr<base::CommandLine> cmd_line, std::map<std::string, base::FilePath> files_to_preload, bool terminate_on_shutdown) { GetContentClient()->browser()->AppendExtraCommandLineSwitches(cmd_line.get(), data_.id); LaunchWithoutExtraCommandLineSwitches( std::move(delegate), std::move(cmd_line), std::move(files_to_preload), terminate_on_shutdown); } const ChildProcessData& BrowserChildProcessHostImpl::GetData() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return data_; } ChildProcessHost* BrowserChildProcessHostImpl::GetHost() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return child_process_host_.get(); } const base::Process& BrowserChildProcessHostImpl::GetProcess() { DCHECK_CURRENTLY_ON(BrowserThread::UI); return data_.GetProcess(); } std::unique_ptr<base::PersistentMemoryAllocator> BrowserChildProcessHostImpl::TakeMetricsAllocator() { return std::move(metrics_allocator_); } void BrowserChildProcessHostImpl::SetName(const std::u16string& name) { DCHECK_CURRENTLY_ON(BrowserThread::UI); data_.name = name; } void BrowserChildProcessHostImpl::SetMetricsName( const std::string& metrics_name) { DCHECK_CURRENTLY_ON(BrowserThread::UI); data_.metrics_name = metrics_name; } void BrowserChildProcessHostImpl::SetProcess(base::Process process) { DCHECK_CURRENTLY_ON(BrowserThread::UI); data_.SetProcess(std::move(process)); } void BrowserChildProcessHostImpl::ForceShutdown() { DCHECK_CURRENTLY_ON(BrowserThread::UI); g_child_process_list.Get().remove(this); child_process_host_->ForceShutdown(); } void BrowserChildProcessHostImpl::AddFilter(BrowserMessageFilter* filter) { child_process_host_->AddFilter(filter->GetFilter()); } void BrowserChildProcessHostImpl::LaunchWithoutExtraCommandLineSwitches( std::unique_ptr<SandboxedProcessLauncherDelegate> delegate, std::unique_ptr<base::CommandLine> cmd_line, std::map<std::string, base::FilePath> files_to_preload, bool terminate_on_shutdown) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const base::CommandLine& browser_command_line = *base::CommandLine::ForCurrentProcess(); static const char* const kForwardSwitches[] = { switches::kDisableInProcessStackTraces, switches::kDisableBestEffortTasks, switches::kDisableLogging, switches::kEnableLogging, switches::kIPCConnectionTimeout, switches::kLogBestEffortTasks, switches::kLogFile, switches::kLoggingLevel, switches::kMojoCoreLibraryPath, switches::kPerfettoDisableInterning, switches::kTraceToConsole, switches::kV, switches::kVModule, }; cmd_line->CopySwitchesFrom(browser_command_line, kForwardSwitches, base::size(kForwardSwitches)); // All processes should have a non-empty metrics name. if (data_.metrics_name.empty()) data_.metrics_name = GetProcessTypeNameInEnglish(data_.process_type); data_.sandbox_type = delegate->GetSandboxType(); // Note that if this host has a legacy IPC Channel, we don't dispatch any // connection status notifications until we observe OnChannelConnected(). if (!has_legacy_ipc_channel_) notify_child_connection_status_ = true; #if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX) bool is_elevated = false; #if defined(OS_WIN) is_elevated = (delegate->GetSandboxType() == sandbox::mojom::Sandbox::kNoSandboxAndElevatedPrivileges); #endif if (!is_elevated) child_process_host_->SetProfilingFile(OpenProfilingFile()); #endif child_process_ = std::make_unique<ChildProcessLauncher>( std::move(delegate), std::move(cmd_line), data_.id, this, std::move(*child_process_host_->GetMojoInvitation()), base::BindRepeating(&BrowserChildProcessHostImpl::OnMojoError, weak_factory_.GetWeakPtr(), base::ThreadTaskRunnerHandle::Get()), std::move(files_to_preload), terminate_on_shutdown); ShareMetricsAllocatorToProcess(); if (!has_legacy_ipc_channel_) OnProcessConnected(); } void BrowserChildProcessHostImpl::HistogramBadMessageTerminated( ProcessType process_type) { UMA_HISTOGRAM_ENUMERATION("ChildProcess.BadMessgeTerminated", process_type, PROCESS_TYPE_MAX); } #if defined(OS_ANDROID) void BrowserChildProcessHostImpl::EnableWarmUpConnection() { can_use_warm_up_connection_ = true; } void BrowserChildProcessHostImpl::DumpProcessStack() { if (!child_process_) return; child_process_->DumpProcessStack(); } #endif ChildProcessTerminationInfo BrowserChildProcessHostImpl::GetTerminationInfo( bool known_dead) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!child_process_) { // If the delegate doesn't use Launch() helper. ChildProcessTerminationInfo info; info.status = base::GetTerminationStatus(data_.GetProcess().Handle(), &info.exit_code); return info; } return child_process_->GetChildTerminationInfo(known_dead); } bool BrowserChildProcessHostImpl::OnMessageReceived( const IPC::Message& message) { return delegate_->OnMessageReceived(message); } void BrowserChildProcessHostImpl::OnChannelConnected(int32_t peer_pid) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(has_legacy_ipc_channel_); notify_child_connection_status_ = true; delegate_->OnChannelConnected(peer_pid); OnProcessConnected(); } void BrowserChildProcessHostImpl::OnProcessConnected() { DCHECK_CURRENTLY_ON(BrowserThread::UI); #if defined(OS_WIN) // From this point onward, the exit of the child process is detected by an // error on the IPC channel or ChildProcessHost pipe. early_exit_watcher_.StopWatching(); #endif if (IsProcessLaunched()) NotifyProcessLaunchedAndConnected(data_.Duplicate()); } void BrowserChildProcessHostImpl::OnChannelError() { delegate_->OnChannelError(); } void BrowserChildProcessHostImpl::OnBadMessageReceived( const IPC::Message& message) { std::string log_message = "Bad message received of type: "; if (message.IsValid()) { log_message += std::to_string(message.type()); } else { log_message += "unknown"; } TerminateOnBadMessageReceived(log_message); } void BrowserChildProcessHostImpl::TerminateOnBadMessageReceived( const std::string& error) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Create a memory dump. This will contain enough stack frames to work out // what the bad message was. base::debug::DumpWithoutCrashing(); TerminateProcessForBadMessage(weak_factory_.GetWeakPtr(), error); } void BrowserChildProcessHostImpl::OnChannelInitialized(IPC::Channel* channel) { has_legacy_ipc_channel_ = true; // When using a legacy IPC Channel, we defer any notifications until the // Channel handshake is complete. See OnChannelConnected(). notify_child_connection_status_ = false; } void BrowserChildProcessHostImpl::OnChildDisconnected() { DCHECK_CURRENTLY_ON(BrowserThread::UI); tracing_registration_.reset(); #if defined(OS_WIN) // OnChildDisconnected may be called without OnChannelConnected, so stop the // early exit watcher so GetTerminationStatus can close the process handle. early_exit_watcher_.StopWatching(); #endif const base::Process& process = data_.GetProcess(); if (child_process_.get() || (process.IsValid() && !process.is_current())) { ChildProcessTerminationInfo info = GetTerminationInfo(true /* known_dead */); #if defined(OS_ANDROID) // Do not treat clean_exit, ie when child process exited due to quitting // its main loop, as a crash. if (!info.clean_exit) { delegate_->OnProcessCrashed(info.exit_code); } NotifyProcessKilled(data_.Duplicate(), info); #else // OS_ANDROID switch (info.status) { case base::TERMINATION_STATUS_PROCESS_CRASHED: case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: { delegate_->OnProcessCrashed(info.exit_code); ChildProcessData data = data_.Duplicate(); for (auto& observer : g_browser_child_process_observers.Get()) observer.BrowserChildProcessCrashed(data, info); UMA_HISTOGRAM_ENUMERATION("ChildProcess.Crashed2", static_cast<ProcessType>(data_.process_type), PROCESS_TYPE_MAX); break; } #if defined(OS_CHROMEOS) case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM: #endif case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: { delegate_->OnProcessCrashed(info.exit_code); NotifyProcessKilled(data_.Duplicate(), info); // Report that this child process was killed. UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2", static_cast<ProcessType>(data_.process_type), PROCESS_TYPE_MAX); break; } case base::TERMINATION_STATUS_STILL_RUNNING: { UMA_HISTOGRAM_ENUMERATION("ChildProcess.DisconnectedAlive2", static_cast<ProcessType>(data_.process_type), PROCESS_TYPE_MAX); break; } case base::TERMINATION_STATUS_LAUNCH_FAILED: { // This is handled in OnProcessLaunchFailed. NOTREACHED(); break; } case base::TERMINATION_STATUS_NORMAL_TERMINATION: { // TODO(wfh): This should not be hit but is sometimes. Investigate. break; } case base::TERMINATION_STATUS_OOM: { // TODO(wfh): Decide to what to do with OOMs here. break; } #if defined(OS_WIN) case base::TERMINATION_STATUS_INTEGRITY_FAILURE: { // TODO(wfh): Decide to what to do with CIG failures here. break; } #endif // OS_WIN case base::TERMINATION_STATUS_MAX_ENUM: { NOTREACHED(); break; } } #endif // OS_ANDROID UMA_HISTOGRAM_ENUMERATION("ChildProcess.Disconnected2", static_cast<ProcessType>(data_.process_type), PROCESS_TYPE_MAX); #if defined(OS_CHROMEOS) if (info.status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM) { UMA_HISTOGRAM_ENUMERATION("ChildProcess.Killed2.OOM", static_cast<ProcessType>(data_.process_type), PROCESS_TYPE_MAX); } #endif } delete delegate_; // Will delete us } bool BrowserChildProcessHostImpl::Send(IPC::Message* message) { DCHECK(has_legacy_ipc_channel_); return child_process_host_->Send(message); } void BrowserChildProcessHostImpl::CreateMetricsAllocator() { // Create a persistent memory segment for subprocess histograms only if // they're active in the browser. // TODO(bcwhite): Remove this once persistence is always enabled. if (!base::GlobalHistogramAllocator::Get()) return; // Determine the correct parameters based on the process type. size_t memory_size; base::StringPiece metrics_name; switch (data_.process_type) { case PROCESS_TYPE_UTILITY: // This needs to be larger for the network service. memory_size = 256 << 10; // 256 KiB metrics_name = "UtilityMetrics"; break; case PROCESS_TYPE_ZYGOTE: memory_size = 64 << 10; // 64 KiB metrics_name = "ZygoteMetrics"; break; case PROCESS_TYPE_SANDBOX_HELPER: memory_size = 64 << 10; // 64 KiB metrics_name = "SandboxHelperMetrics"; break; case PROCESS_TYPE_GPU: // This needs to be larger for the display-compositor in the gpu process. memory_size = 256 << 10; // 256 KiB metrics_name = "GpuMetrics"; break; case PROCESS_TYPE_PPAPI_PLUGIN: memory_size = 64 << 10; // 64 KiB metrics_name = "PpapiPluginMetrics"; break; case PROCESS_TYPE_PPAPI_BROKER: memory_size = 64 << 10; // 64 KiB metrics_name = "PpapiBrokerMetrics"; break; default: return; } // Create the shared memory segment and attach an allocator to it. // Mapping the memory shouldn't fail but be safe if it does; everything // will continue to work but just as if persistence weren't available. base::WritableSharedMemoryRegion shm_region = base::WritableSharedMemoryRegion::Create(memory_size); base::WritableSharedMemoryMapping shm_mapping = shm_region.Map(); if (!shm_region.IsValid() || !shm_mapping.IsValid()) return; metrics_allocator_ = std::make_unique<base::WritableSharedPersistentMemoryAllocator>( std::move(shm_mapping), static_cast<uint64_t>(data_.id), metrics_name); metrics_shared_region_ = std::move(shm_region); } void BrowserChildProcessHostImpl::ShareMetricsAllocatorToProcess() { if (metrics_allocator_) { HistogramController::GetInstance()->SetHistogramMemory<ChildProcessHost>( GetHost(), std::move(metrics_shared_region_)); } else { HistogramController::GetInstance()->SetHistogramMemory<ChildProcessHost>( GetHost(), base::WritableSharedMemoryRegion()); } } void BrowserChildProcessHostImpl::OnProcessLaunchFailed(int error_code) { DCHECK_CURRENTLY_ON(BrowserThread::UI); delegate_->OnProcessLaunchFailed(error_code); ChildProcessTerminationInfo info = child_process_->GetChildTerminationInfo(/*known_dead=*/true); DCHECK_EQ(info.status, base::TERMINATION_STATUS_LAUNCH_FAILED); ChildProcessData data = data_.Duplicate(); for (auto& observer : g_browser_child_process_observers.Get()) observer.BrowserChildProcessLaunchFailed(data, info); notify_child_connection_status_ = false; delete delegate_; // Will delete us } #if defined(OS_ANDROID) bool BrowserChildProcessHostImpl::CanUseWarmUpConnection() { return can_use_warm_up_connection_; } #endif void BrowserChildProcessHostImpl::OnProcessLaunched() { DCHECK_CURRENTLY_ON(BrowserThread::UI); const base::Process& process = child_process_->GetProcess(); DCHECK(process.IsValid()); #if defined(OS_MAC) ChildProcessTaskPortProvider::GetInstance()->OnChildProcessLaunched( process.Pid(), static_cast<ChildProcessHostImpl*>(child_process_host_.get()) ->child_process()); #endif #if defined(OS_WIN) // Start a WaitableEventWatcher that will invoke OnProcessExitedEarly if the // child process exits. This watcher is stopped once the IPC channel is // connected and the exit of the child process is detecter by an error on the // IPC channel thereafter. DCHECK(!early_exit_watcher_.GetWatchedObject()); early_exit_watcher_.StartWatchingOnce(process.Handle(), this); #endif data_.SetProcess(process.Duplicate()); delegate_->OnProcessLaunched(); if (notify_child_connection_status_) NotifyProcessLaunchedAndConnected(data_.Duplicate()); #if BUILDFLAG(IS_CHROMEOS_ASH) // In ChromeOS, there are still child processes of NaCl modules, and they // don't contribute to tracing actually. So do not register those clients // to the tracing service. See https://crbug.com/1101468. if (data_.process_type >= PROCESS_TYPE_CONTENT_END) return; #endif tracing_registration_ = TracingServiceController::Get().RegisterClient( process.Pid(), base::BindRepeating(&BindTracedProcessFromUIThread, weak_factory_.GetWeakPtr())); BackgroundTracingManagerImpl::ActivateForProcess( GetData().id, static_cast<ChildProcessHostImpl*>(GetHost())->child_process()); #if defined(OS_POSIX) && !defined(OS_ANDROID) system_tracing_service_ = std::make_unique<tracing::SystemTracingService>(); child_process()->EnableSystemTracingService( system_tracing_service_->BindAndPassPendingRemote()); #endif } void BrowserChildProcessHostImpl::RegisterCoordinatorClient( mojo::PendingReceiver<memory_instrumentation::mojom::Coordinator> receiver, mojo::PendingRemote<memory_instrumentation::mojom::ClientProcess> client_process) { // Intentionally disallow non-browser processes from getting a Coordinator. receiver.reset(); // The child process may have already terminated by the time this message is // dispatched. We do nothing in that case. if (!IsProcessLaunched()) return; base::trace_event::MemoryDumpManager::GetInstance() ->GetDumpThreadTaskRunner() ->PostTask( FROM_HERE, base::BindOnce( [](mojo::PendingReceiver< memory_instrumentation::mojom::Coordinator> receiver, mojo::PendingRemote< memory_instrumentation::mojom::ClientProcess> client_process, memory_instrumentation::mojom::ProcessType process_type, base::ProcessId process_id, absl::optional<std::string> service_name) { GetMemoryInstrumentationRegistry()->RegisterClientProcess( std::move(receiver), std::move(client_process), process_type, process_id, std::move(service_name)); }, std::move(receiver), std::move(client_process), GetCoordinatorClientProcessType( static_cast<ProcessType>(data_.process_type)), child_process_->GetProcess().Pid(), delegate_->GetServiceName())); } bool BrowserChildProcessHostImpl::IsProcessLaunched() const { DCHECK_CURRENTLY_ON(BrowserThread::UI); return child_process_.get() && child_process_->GetProcess().IsValid(); } // static void BrowserChildProcessHostImpl::OnMojoError( base::WeakPtr<BrowserChildProcessHostImpl> process, scoped_refptr<base::SingleThreadTaskRunner> task_runner, const std::string& error) { // Create a memory dump with the error message captured in a crash key value. // This will make it easy to determine details about what interface call // failed. // // It is important to call DumpWithoutCrashing synchronously - this will help // to preserve the callstack and the crash keys present when the bad mojo // message was received. mojo::debug::ScopedMessageErrorCrashKey scoped_error_key(error); base::debug::DumpWithoutCrashing(); if (task_runner->BelongsToCurrentThread()) { TerminateProcessForBadMessage(process, error); } else { task_runner->PostTask( FROM_HERE, base::BindOnce( &BrowserChildProcessHostImpl::TerminateProcessForBadMessage, process, error)); } } // static void BrowserChildProcessHostImpl::TerminateProcessForBadMessage( base::WeakPtr<BrowserChildProcessHostImpl> process, const std::string& error) { if (!process) return; HistogramBadMessageTerminated( static_cast<ProcessType>(process->data_.process_type)); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableKillAfterBadIPC)) { return; } LOG(ERROR) << "Terminating child process for bad message: " << error; process->child_process_->Terminate(RESULT_CODE_KILLED_BAD_MESSAGE); } #if defined(OS_WIN) void BrowserChildProcessHostImpl::OnObjectSignaled(HANDLE object) { OnChildDisconnected(); } #endif } // namespace content
35.884967
80
0.736413
[ "object" ]
ba3ea24d4a91e765856d582a505fed55c0fa6590
3,961
cc
C++
e2e/trt/video_runner.cc
stanford-futuredata/smol
82e2356755133cd1516dfbbbc782707eca70a34c
[ "Apache-2.0" ]
1
2021-11-29T01:24:03.000Z
2021-11-29T01:24:03.000Z
e2e/trt/video_runner.cc
stanford-futuredata/smol
82e2356755133cd1516dfbbbc782707eca70a34c
[ "Apache-2.0" ]
1
2021-11-29T09:29:14.000Z
2021-12-13T02:31:55.000Z
e2e/trt/video_runner.cc
stanford-futuredata/smol
82e2356755133cd1516dfbbbc782707eca70a34c
[ "Apache-2.0" ]
1
2021-12-13T06:55:18.000Z
2021-12-13T06:55:18.000Z
#include <fstream> #include <string> #include <vector> #include <experimental/filesystem> #include "yaml-cpp/yaml.h" #include "include/video_data_loader.h" #include "include/inference_server.h" #include "include/video_experiment_server.h" // Expects a validation directory as in pytorch std::vector<std::string> GetFileNames(const std::string& vid_dir) { namespace fs = std::experimental::filesystem; std::vector<std::string> str_paths; for (size_t i = 0; i < 1; i++) { std::vector<fs::path> paths; std::copy(fs::directory_iterator(vid_dir), fs::directory_iterator(), std::back_inserter(paths)); std::sort(paths.begin(), paths.end(), [](const fs::path& pa, const fs::path& pb) { std::stringstream sa(pa.filename()), sb(pb.filename()); int ia, ib; sa >> ia; sb >> ib; return ia < ib; }); for (auto f : paths) str_paths.push_back(f.string()); } // str_paths.erase(str_paths.begin() + 1000, str_paths.end()); return str_paths; } int main(int argc, char *argv[]) { // auto paths = GetFileNames("/lfs/1/ddkang/blazeit/data/svideo/jackson-town-square/2017-12-17"); // auto paths = GetFileNames("/lfs/1/ddkang/blazeit/data/svideo/jackson-town-square/short"); // auto paths = GetFileNames("/lfs/1/ddkang/vision-inf/data/svideo/decode-test/240p"); assert(argc == 2); YAML::Node cfg = YAML::LoadFile(argv[1]); // Record the config std::cout << cfg << std::endl << std::endl; const bool kWriteOut = cfg["experiment-config"]["write-out"].as<bool>(); const bool kRunInfer = cfg["experiment-config"]["run-infer"].as<bool>(); const bool kDoMemcpy = cfg["infer-config"]["do-memcpy"].as<bool>(); // Video only has one model auto model_cfg = cfg["model-config"]["model-single"]; const std::string kOnnxPath = model_cfg["onnx-path"].as<std::string>(); const std::string kEnginePath = model_cfg["engine-path"].as<std::string>(); const std::string kDataPath = model_cfg["data-path"].as<std::string>(); const size_t kBatchSize = model_cfg["batch-size"].as<size_t>(); const size_t kModelInputDim = model_cfg["input-dim"][0].as<size_t>(); auto paths = GetFileNames(kDataPath); std::cerr << "Processing " << paths.size() << " files" << std::endl; auto crop_cfg = cfg["crop"]; const size_t xmin = crop_cfg["xmin"].as<size_t>(); const size_t ymin = crop_cfg["ymin"].as<size_t>(); const size_t xmax = crop_cfg["xmax"].as<size_t>(); const size_t ymax = crop_cfg["ymax"].as<size_t>(); const CropRegion region(xmin, ymin, xmax, ymax); // FIXME: 256 VideoDataLoader *loader = NULL; const std::string kLoaderType = model_cfg["data-loader"].as<std::string>(); std::string cond_str = cfg["experiment-config"]["exp-type"].as<std::string>(); LoaderCondition cond = LoaderCondition::GetVal(cond_str); if (kLoaderType == "opt") { loader = new OptimizedVidDataLoader(256, kModelInputDim, region, cond); } else if (kLoaderType == "naive") { loader = new NaiveVidDataLoader(256, kModelInputDim, region, cond); } else { throw std::invalid_argument("Loader cfg wrong"); } OnnxInferenceServer *infer; namespace fs = std::experimental::filesystem; if (fs::exists(kEnginePath)) { infer = new OnnxInferenceServer(kEnginePath, kBatchSize, kDoMemcpy); } else { infer = new OnnxInferenceServer( kOnnxPath, "", kEnginePath, kBatchSize, kDoMemcpy, loader, paths, model_cfg["do-int8"].as<bool>()); } VideoExperimentServer server(*loader, infer, kBatchSize, kRunInfer); infer->warmup(kModelInputDim); float time; std::vector<float> output; std::tie(time, output) = server.TimeEndToEnd(paths); std::cerr << "Runtime: " << time << std::endl; if (kWriteOut) { std::ofstream fout("preds.out", std::ios::out | std::ios::binary); fout.write((char *) output.data(), output.size() * sizeof(float)); fout.close(); } return 0; }
36.675926
99
0.657915
[ "vector", "model" ]
ba41a480e1daf4fb0b9a07b0f3923d3d643aa0b1
5,107
hpp
C++
include/operon/operators/mutation.hpp
foolnotion/operon
5faa938b98e0ee40e224eca8793db5f6a9934673
[ "MIT" ]
3
2019-10-29T09:36:18.000Z
2020-08-17T08:31:37.000Z
include/operon/operators/mutation.hpp
foolnotion/operon
5faa938b98e0ee40e224eca8793db5f6a9934673
[ "MIT" ]
3
2020-04-24T20:02:56.000Z
2020-10-14T10:07:18.000Z
include/operon/operators/mutation.hpp
foolnotion/operon
5faa938b98e0ee40e224eca8793db5f6a9934673
[ "MIT" ]
3
2020-01-29T05:36:03.000Z
2020-05-31T06:48:52.000Z
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: Copyright 2019-2022 Heal Research #ifndef OPERON_MUTATION_HPP #define OPERON_MUTATION_HPP #include <utility> #include "operon/core/operator.hpp" #include "operon/core/pset.hpp" #include "operon/core/tree.hpp" namespace Operon { struct CoefficientInitializerBase; struct CreatorBase; struct Variable; // the mutator can work in place or return a copy (child) struct MutatorBase : public OperatorBase<Tree, Tree> { }; template<typename Dist> struct OPERON_EXPORT OnePointMutation : public MutatorBase { auto operator()(Operon::RandomGenerator& random, Tree tree) const -> Tree override { auto& nodes = tree.Nodes(); // sample a random leaf auto it = Operon::Random::Sample(random, nodes.begin(), nodes.end(), [](auto const& n) { return n.IsLeaf(); }); EXPECT(it < nodes.end()); it->Value += Dist(params_)(random); return tree; } template <typename... Args> auto ParameterizeDistribution(Args... args) const -> void { params_ = typename Dist::param_type { std::forward<Args&&>(args)... }; } private: mutable typename Dist::param_type params_; }; template<typename Dist> struct OPERON_EXPORT MultiPointMutation : public MutatorBase { auto operator()(Operon::RandomGenerator& random, Tree tree) const -> Tree override { for (auto& node : tree.Nodes()) { if (node.IsLeaf()) { node.Value += Dist(params_)(random); } } return tree; } template <typename... Args> auto ParameterizeDistribution(Args... args) const -> void { params_ = typename Dist::param_type { std::forward<Args&&>(args)... }; } private: mutable typename Dist::param_type params_; }; struct OPERON_EXPORT DiscretePointMutation : public MutatorBase { auto operator()(Operon::RandomGenerator& random, Tree tree) const -> Tree override; auto Add(Operon::Scalar value, Operon::Scalar weight = 1.0) -> void { values_.push_back(value); weights_.push_back(weight); } private: std::vector<Operon::Scalar> weights_; std::vector<Operon::Scalar> values_; }; struct OPERON_EXPORT MultiMutation : public MutatorBase { auto operator()(Operon::RandomGenerator& /*random*/, Tree /*args*/) const -> Tree override; void Add(const MutatorBase& op, double prob) { operators_.push_back(std::ref(op)); probabilities_.push_back(prob); } [[nodiscard]] auto Count() const -> size_t { return operators_.size(); } private: std::vector<std::reference_wrapper<const MutatorBase>> operators_; std::vector<double> probabilities_; }; struct OPERON_EXPORT ChangeVariableMutation : public MutatorBase { explicit ChangeVariableMutation(const Operon::Span<const Variable> vars) : variables(vars) { } auto operator()(Operon::RandomGenerator& /*random*/, Tree /*args*/) const -> Tree override; private: const Operon::Span<Variable const> variables; }; struct OPERON_EXPORT ChangeFunctionMutation : public MutatorBase { explicit ChangeFunctionMutation(PrimitiveSet ps) : pset_(std::move(ps)) { } auto operator()(Operon::RandomGenerator& /*random*/, Tree /*args*/) const -> Tree override; private: PrimitiveSet pset_; }; struct OPERON_EXPORT RemoveSubtreeMutation final : public MutatorBase { explicit RemoveSubtreeMutation(PrimitiveSet ps) : pset_(std::move(ps)) { } auto operator()(Operon::RandomGenerator& /*random*/, Tree /*args*/) const -> Tree override; private: PrimitiveSet pset_; }; struct OPERON_EXPORT InsertSubtreeMutation final : public MutatorBase { InsertSubtreeMutation(CreatorBase& creator, CoefficientInitializerBase& coeffInit, size_t maxDepth, size_t maxLength) : creator_(creator) , coefficientInitializer_(coeffInit) , maxDepth_(maxDepth) , maxLength_(maxLength) { } auto operator()(Operon::RandomGenerator& /*random*/, Tree /*args*/) const -> Tree override; private: std::reference_wrapper<CreatorBase> creator_; std::reference_wrapper<CoefficientInitializerBase> coefficientInitializer_; size_t maxDepth_; size_t maxLength_; }; struct OPERON_EXPORT ReplaceSubtreeMutation : public MutatorBase { ReplaceSubtreeMutation(CreatorBase& creator, CoefficientInitializerBase& coeffInit, size_t maxDepth, size_t maxLength) : creator_(creator) , coefficientInitializer_(coeffInit) , maxDepth_(maxDepth) , maxLength_(maxLength) { } auto operator()(Operon::RandomGenerator& /*random*/, Tree /*args*/) const -> Tree override; private: std::reference_wrapper<CreatorBase> creator_; std::reference_wrapper<CoefficientInitializerBase> coefficientInitializer_; size_t maxDepth_; size_t maxLength_; }; struct OPERON_EXPORT ShuffleSubtreesMutation : public MutatorBase { auto operator()(Operon::RandomGenerator& /*random*/, Tree /*args*/) const -> Tree override; }; } // namespace Operon #endif
29.69186
122
0.687684
[ "vector" ]
ba464a3050c269927729ce42eda216b4be2b5c6f
10,476
cpp
C++
tests/Unit/Parallel/Test_PhaseChangeMain.cpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
2
2021-04-11T04:07:42.000Z
2021-04-11T05:07:54.000Z
tests/Unit/Parallel/Test_PhaseChangeMain.cpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
null
null
null
tests/Unit/Parallel/Test_PhaseChangeMain.cpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #define CATCH_CONFIG_RUNNER #include "Framework/TestingFramework.hpp" #include <cstddef> #include <string> #include <tuple> #include "DataStructures/DataBox/DataBox.hpp" #include "DataStructures/DataBox/Tag.hpp" #include "Parallel/Actions/SetupDataBox.hpp" #include "Parallel/Algorithms/AlgorithmArray.hpp" #include "Parallel/Algorithms/AlgorithmGroup.hpp" #include "Parallel/GlobalCache.hpp" #include "Parallel/InboxInserters.hpp" #include "Parallel/InitializationFunctions.hpp" #include "Parallel/Main.hpp" #include "Parallel/ParallelComponentHelpers.hpp" #include "Parallel/PhaseControl/PhaseControlTags.hpp" #include "Parallel/PhaseDependentActionList.hpp" #include "ParallelAlgorithms/Initialization/MutateAssign.hpp" #include "Utilities/ErrorHandling/FloatingPointExceptions.hpp" #include "Utilities/Gsl.hpp" #include "Utilities/System/ParallelInfo.hpp" #include "Utilities/TMPL.hpp" #include "Utilities/TaggedTuple.hpp" namespace PhaseChangeTest { template <class Metavariables> struct ArrayComponent; template <class Metavariables> struct GroupComponent; struct StepNumber : db::SimpleTag { using type = size_t; }; using PhaseChangeStepNumber = PhaseControl::TagAndCombine<PhaseChangeTest::StepNumber, funcl::Max<>>; struct IsDone { using type = bool; using combine_method = funcl::And<>; using main_combine_method = funcl::Or<>; }; struct InitializeStepTag { using simple_tags = tmpl::list<StepNumber>; template <typename... DbTags, typename... InboxTags, typename Metavariables, typename ArrayIndex, typename ActionList, typename ParallelComponent> static std::tuple<db::DataBox<tmpl::list<DbTags...>>&&, bool> apply( db::DataBox<tmpl::list<DbTags...>>& box, tuples::TaggedTuple<InboxTags...>& /*inboxes*/, const Parallel::GlobalCache<Metavariables>& /*cache*/, const ArrayIndex& /*array_index*/, ActionList /*meta*/, const ParallelComponent* const /*meta*/) noexcept { Initialization::mutate_assign<simple_tags>(make_not_null(&box), 0_st); return {std::move(box), true}; } }; struct IncrementStep { template <typename... DbTags, typename... InboxTags, typename Metavariables, typename ArrayIndex, typename ActionList, typename ParallelComponent> static std::tuple<db::DataBox<tmpl::list<DbTags...>>&&> apply( db::DataBox<tmpl::list<DbTags...>>& box, tuples::TaggedTuple<InboxTags...>& /*inboxes*/, const Parallel::GlobalCache<Metavariables>& /*cache*/, const ArrayIndex& /*array_index*/, ActionList /*meta*/, const ParallelComponent* const /*meta*/) noexcept { db::mutate<StepNumber>( make_not_null(&box), [](const gsl::not_null<size_t*> step_number) noexcept { ++(*step_number); }); SPECTRE_PARALLEL_REQUIRE(db::get<StepNumber>(box) < 31); return {std::move(box)}; } }; struct ReportArrayPhaseControlDataAndTerminate{ template <typename... DbTags, typename... InboxTags, typename Metavariables, typename ActionList, typename ParallelComponent> static std::tuple<db::DataBox<tmpl::list<DbTags...>>&&, bool> apply( db::DataBox<tmpl::list<DbTags...>>& box, const tuples::TaggedTuple<InboxTags...>& /*inboxes*/, Parallel::GlobalCache<Metavariables>& cache, const int array_index, ActionList /*meta*/, const ParallelComponent* const /*meta*/) noexcept { Parallel::contribute_to_phase_change_reduction< ArrayComponent<Metavariables>>( tuples::TaggedTuple<IsDone>{array_index == 0 ? db::get<StepNumber>(box) % 2 == 0 : db::get<StepNumber>(box) % 3 == 0}, cache, array_index); return {std::move(box), true}; } }; struct ReportGroupPhaseControlDataAndTerminate { template <typename... DbTags, typename... InboxTags, typename Metavariables, typename ArrayIndex, typename ActionList, typename ParallelComponent> static std::tuple<db::DataBox<tmpl::list<DbTags...>>&&, bool> apply( db::DataBox<tmpl::list<DbTags...>>& box, tuples::TaggedTuple<InboxTags...>& /*inboxes*/, Parallel::GlobalCache<Metavariables>& cache, const ArrayIndex& /*array_index*/, ActionList /*meta*/, const ParallelComponent* const /*meta*/) noexcept { Parallel::contribute_to_phase_change_reduction< GroupComponent<Metavariables>>( tuples::TaggedTuple<IsDone, PhaseChangeStepNumber>{ false, db::get<StepNumber>(box)}, cache); return {std::move(box), true}; } }; template <class Metavariables> struct GroupComponent { using chare_type = Parallel::Algorithms::Group; using metavariables = Metavariables; using phase_dependent_action_list = tmpl::list< Parallel::PhaseActions< typename Metavariables::Phase, Metavariables::Phase::Initialization, tmpl::list<Actions::SetupDataBox, InitializeStepTag>>, Parallel::PhaseActions< typename Metavariables::Phase, Metavariables::Phase::Evolution, tmpl::list<IncrementStep, ReportGroupPhaseControlDataAndTerminate>>>; using initialization_tags = Parallel::get_initialization_tags< Parallel::get_initialization_actions_list<phase_dependent_action_list>>; static void execute_next_phase( const typename Metavariables::Phase next_phase, const Parallel::CProxy_GlobalCache<Metavariables>& global_cache) { auto& local_cache = *(global_cache.ckLocalBranch()); Parallel::get_parallel_component<GroupComponent>(local_cache) .start_phase(next_phase); } }; template <class Metavariables> struct ArrayComponent { using chare_type = Parallel::Algorithms::Array; using metavariables = Metavariables; using array_index = int; using phase_dependent_action_list = tmpl::list< Parallel::PhaseActions< typename Metavariables::Phase, Metavariables::Phase::Initialization, tmpl::list<Actions::SetupDataBox, InitializeStepTag>>, Parallel::PhaseActions< typename Metavariables::Phase, Metavariables::Phase::Evolution, tmpl::list<IncrementStep, ReportArrayPhaseControlDataAndTerminate>>>; using initialization_tags = Parallel::get_initialization_tags< Parallel::get_initialization_actions_list<phase_dependent_action_list>>; static void allocate_array( Parallel::CProxy_GlobalCache<Metavariables>& global_cache, const tuples::tagged_tuple_from_typelist<initialization_tags>& /*initialization_items*/) noexcept { auto& local_cache = *(global_cache.ckLocalBranch()); auto& array_proxy = Parallel::get_parallel_component<ArrayComponent>(local_cache); for (int i = 0, which_proc = 0, number_of_procs = sys::number_of_procs(); i < 2; ++i) { array_proxy[i].insert(global_cache, {}, which_proc); which_proc = which_proc + 1 == number_of_procs ? 0 : which_proc + 1; } array_proxy.doneInserting(); } static void execute_next_phase( const typename Metavariables::Phase next_phase, const Parallel::CProxy_GlobalCache<Metavariables>& global_cache) { auto& local_cache = *(global_cache.ckLocalBranch()); Parallel::get_parallel_component<ArrayComponent>(local_cache) .start_phase(next_phase); } }; } // namespace PhaseChangeTest struct TestMetavariables { // Two components, array component has two elements, group component has one // element (run only on one core). // Array component [0] asks to be done on steps divisible by 2 // Array component [1] asks to be done on steps divisible by 3 // The group component just submits its step number. // Phase moves to Exit phase when the step is greater than 25 and all // components with done states say they are done. // Test errors if any component reaches step 31. using component_list = tmpl::list<PhaseChangeTest::ArrayComponent<TestMetavariables>, PhaseChangeTest::GroupComponent<TestMetavariables>>; static constexpr Options::String help = ""; enum class Phase { Initialization, Evolution, Exit }; using phase_change_tags_and_combines_list = tmpl::list<PhaseChangeTest::IsDone, PhaseChangeTest::PhaseChangeStepNumber>; struct initialize_phase_change_decision_data { static void apply( const gsl::not_null<tuples::tagged_tuple_from_typelist< phase_change_tags_and_combines_list>*> phase_change_decision_data, const Parallel::GlobalCache<TestMetavariables>& /*cache*/) noexcept { tuples::get<PhaseChangeTest::IsDone>(*phase_change_decision_data) = false; tuples::get<PhaseChangeTest::PhaseChangeStepNumber>( *phase_change_decision_data) = 0; } }; template <typename... Tags> static Phase determine_next_phase( const gsl::not_null<tuples::TaggedTuple<Tags...>*> phase_change_decision_data, const Phase& current_phase, const Parallel::CProxy_GlobalCache< TestMetavariables>& /*cache_proxy*/) noexcept { switch (current_phase) { case Phase::Initialization: return Phase::Evolution; case Phase::Evolution: // confirm that the reduction is being performed consistently each step SPECTRE_PARALLEL_REQUIRE( tuples::get<PhaseChangeTest::IsDone>(*phase_change_decision_data) == (tuples::get<PhaseChangeTest::PhaseChangeStepNumber>( *phase_change_decision_data) % 6 == 0)); if (tuples::get<PhaseChangeTest::IsDone>( *phase_change_decision_data) and tuples::get<PhaseChangeTest::PhaseChangeStepNumber>( *phase_change_decision_data) > 25) { return Phase::Exit; } else { tuples::get<PhaseChangeTest::IsDone>(*phase_change_decision_data) = false; return Phase::Evolution; } case Phase::Exit: return Phase::Exit; default: ERROR("Unknown Phase..."); } return Phase::Exit; } }; static const std::vector<void (*)()> charm_init_node_funcs{ &setup_error_handling}; static const std::vector<void (*)()> charm_init_proc_funcs{ &enable_floating_point_exceptions}; using charmxx_main_component = Parallel::Main<TestMetavariables>; #include "Parallel/CharmMain.tpp" // IWYU pragma: keep
38.233577
80
0.697881
[ "vector" ]
ba49d0a918449ffb00b5b4f42c5eae8467854f7c
1,026
cpp
C++
platforms/leetcode/0240_longest_word_in_dictionary_through_deleting.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/leetcode/0240_longest_word_in_dictionary_through_deleting.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/leetcode/0240_longest_word_in_dictionary_through_deleting.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include "../../template.hpp" using i32 = std::int32_t; using i64 = std::int64_t; const i32 inf = 1'000'000'007; const i32 mod = 1'000'000'007; const i32 _io_ = ([](){ios_base::sync_with_stdio(0); cin.tie(0);return 0;})(); bool isLcs(string& s, string& t) { i32 i = 0, j = 0, m = s.size(), n = t.size(); if (m > n) return 0; while (i < m and j < n) { if (s[i] == t[j]) ++i, ++j; else ++j; } return i == m; } string sol(string s, vector<string> words) { string ans; for (string& word : words) { if (isLcs(word, s)) { if (ans.size() < word.size()) ans = word; else if (ans.size() == word.size() and ans > word) ans = word; } } return ans; } int main() { TimeMeasure _; cout << sol("abpcplea", {"ale","apple","monkey","plea"}) << endl; // apple cout << sol("abpcplea", {"a","b","c"}) << endl; // a cout << sol("aewfafwafjlwajflwajflwafj", {"apple","ewaf","awefawfwaf","awef","awefe","ewafeffewafewf"}) << endl; // ewaf }
29.314286
124
0.52729
[ "vector" ]
ba4a157b80926835348998da1018e05e93ca211b
2,850
cpp
C++
src/Stack.cpp
mocklerlab/supersplat
a1f254f2bc95a872dc69877252894cebba637585
[ "MIT" ]
1
2015-06-25T09:16:35.000Z
2015-06-25T09:16:35.000Z
src/Stack.cpp
mocklerlab/supersplat
a1f254f2bc95a872dc69877252894cebba637585
[ "MIT" ]
null
null
null
src/Stack.cpp
mocklerlab/supersplat
a1f254f2bc95a872dc69877252894cebba637585
[ "MIT" ]
null
null
null
/* * Stack.cpp * * Created on: Apr 22, 2011 * Author: Douglas W Bryant Jr */ #include "Stack.h" Stack::Stack(int argc, char** argv) { m_dParams = new StackParameters(); if(argc < 9) { Stack::outputUsage(); return; } else { char* parameter; for(int i = 1; i < argc; i++) { parameter = argv[i]; if(parameter[0] == '-') { switch(parameter[1]) { case 'r': m_dParams->setReferenceFileName(argv[++i]); break; case 's': m_dParams->setSplatOutputFileName(argv[++i]); break; case 'c': m_dParams->setMinReadCopyNumber(atoi(argv[++i])); break; case 'd': m_dParams->setMaxReadCopyNumber(atoi(argv[++i])); break; case 'n': m_dParams->setMinNumDiffSequences(atoi(argv[++i])); break; case 'o': m_dParams->setStackOutputFileName(argv[++i]); break; case 'R': m_dParams->setReferenceNameToAnalyze(argv[++i]); break; default: std::cout << "Error in " << argv[i] << " " << argv[i+1] << std::endl << std::endl; } } } } Stack::run(); } Stack::~Stack() { delete m_dParams; } bool Stack::run() { bool l_bSuccess = true; if(!m_dParams->verifyParameters()) { Stack::outputUsage(); l_bSuccess = false; } else { Stacker* stacker = new Stacker(m_dParams); bool success = stacker->initReferenceInfos(*(m_dParams->getReferenceFileName())); success = stacker->stackSplatOutput(*(m_dParams->getSplatOutputFileName())); printResults(stacker->getStackedResults()); delete stacker; } return l_bSuccess; } void Stack::printResults(std::vector<std::string>* p_vResultsVector) { if(!p_vResultsVector->empty()) { std::ofstream l_dOutputFile; std::string l_sFileName = *(m_dParams->getStackOutputFileName()); l_dOutputFile.open(l_sFileName.c_str(), std::ios::app | std::ios::out); for(int i = 0; i < p_vResultsVector->size(); i++) { l_dOutputFile << p_vResultsVector->at(i); } l_dOutputFile.close(); } } void Stack::outputUsage() { std::cout << std::endl; std::cout << "Usage: supersplat stack <options>" << std::endl; std::cout << "Options: -r <Fasta-formatted reference file.> (REQD)" << std::endl; std::cout << " -s <Splat output file> (REQD)" << std::endl; std::cout << " -n <Minimum number of unique hits.> (REQD)" << std::endl; std::cout << " -c <Minimum read copy number per unique hit.> (REQD)" << std::endl; std::cout << " -d <Maximum read copy number per unique hit.> (Optional, default = no such maximum)" << std::endl; std::cout << " -o <Output file name.> (Optional, default = name_of_splat_output.stack)" << std::endl; std::cout << "Additional options:" << std::endl; std::cout << " -R <Name of reference over which to restrict analysis> (Optional, default = no such restriction)" << std::endl; }
37.5
139
0.613333
[ "vector" ]
ba4a596c99c74c6422b993f1014aff8e8633a9f0
1,463
hpp
C++
include/multicontact-api/geometry/ellipsoid.hpp
proyan/multicontact-api
3ff225a2a114044dda07ee9d933dc060a96cc359
[ "BSD-2-Clause" ]
1
2020-11-23T11:55:53.000Z
2020-11-23T11:55:53.000Z
include/multicontact-api/geometry/ellipsoid.hpp
proyan/multicontact-api
3ff225a2a114044dda07ee9d933dc060a96cc359
[ "BSD-2-Clause" ]
14
2020-03-13T13:28:23.000Z
2022-03-25T12:23:27.000Z
include/multicontact-api/geometry/ellipsoid.hpp
proyan/multicontact-api
3ff225a2a114044dda07ee9d933dc060a96cc359
[ "BSD-2-Clause" ]
4
2019-08-02T13:52:06.000Z
2020-11-10T06:53:58.000Z
// Copyright (c) 2015-2018, CNRS // Authors: Justin Carpentier <jcarpent@laas.fr> #ifndef __multicontact_api_geometry_ellipsoid_hpp__ #define __multicontact_api_geometry_ellipsoid_hpp__ #include <Eigen/Dense> #include <iostream> #include "multicontact-api/geometry/fwd.hpp" namespace multicontact_api { namespace geometry { template <typename _Scalar, int _dim, int _Options> struct Ellipsoid { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; enum { dim = _dim }; enum { Options = _Options }; typedef Eigen::Matrix<Scalar, dim, dim, Options> Matrix; typedef Eigen::Matrix<Scalar, dim, 1, Options> Vector; Ellipsoid(const Matrix& A, const Vector& center) : m_A(A), m_center(center) {} Scalar lhsValue(const Vector& point) const { return (m_A * (point - m_center)).norm(); } const Matrix& A() const { return m_A; } Matrix& A() { return m_A; } const Vector& center() const { return m_center; } Vector& center() { return m_center; } void disp(std::ostream& os) const { os << "A:\n" << m_A << std::endl << "center: " << m_center.transpose() << std::endl; } friend std::ostream& operator<<(std::ostream& os, const Ellipsoid& E) { E.disp(os); return os; } protected: /// \brief Matrix m_A; /// \brief Center of the ellipsoid expressed in the global frame. Vector m_center; }; } // namespace geometry } // namespace multicontact_api #endif // ifndef __multicontact_api_geometry_ellipsoid_hpp__
27.603774
90
0.701982
[ "geometry", "vector" ]
ba540f73f51e5b4446512962200a742b21992235
9,884
cxx
C++
Rendering/OpenGL2/vtkOpenGLSkybox.cxx
jpouderoux/VTK
1af22bcce698e121b6c8064ea724636621d1bf7e
[ "BSD-3-Clause" ]
1
2019-05-31T14:00:53.000Z
2019-05-31T14:00:53.000Z
Rendering/OpenGL2/vtkOpenGLSkybox.cxx
Pandinosaurus/VTK
ff4d402a67189bb7f6b038fe51f9d4dc44e5c8c4
[ "BSD-3-Clause" ]
null
null
null
Rendering/OpenGL2/vtkOpenGLSkybox.cxx
Pandinosaurus/VTK
ff4d402a67189bb7f6b038fe51f9d4dc44e5c8c4
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLSkybox.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkOpenGLSkybox.h" #include "vtkCamera.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkOpenGLActor.h" #include "vtkOpenGLError.h" #include "vtkOpenGLPolyDataMapper.h" #include "vtkOpenGLRenderer.h" #include "vtkOpenGLShaderProperty.h" #include "vtkOpenGLState.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkShaderProgram.h" #include "vtkTexture.h" #include <cmath> vtkStandardNewMacro(vtkOpenGLSkybox); vtkOpenGLSkybox::vtkOpenGLSkybox() { vtkNew<vtkPolyData> poly; vtkNew<vtkPoints> pts; pts->SetNumberOfPoints(4); pts->SetPoint(0, -1, -1, 0); pts->SetPoint(1, 1, -1, 0); pts->SetPoint(2, 1, 1, 0); pts->SetPoint(3, -1, 1, 0); poly->SetPoints(pts); vtkNew<vtkCellArray> polys; poly->SetPolys(polys); polys->InsertNextCell(4); polys->InsertCellPoint(0); polys->InsertCellPoint(1); polys->InsertCellPoint(2); polys->InsertCellPoint(3); // this->CubeMapper->SetInputConnection(this->Cube->GetOutputPort(0)); this->CubeMapper->SetInputData(poly); this->SetMapper(this->CubeMapper); this->OpenGLActor->SetMapper(this->CubeMapper); vtkOpenGLShaderProperty* sp = vtkOpenGLShaderProperty::SafeDownCast(this->OpenGLActor->GetShaderProperty()); sp->AddShaderReplacement(vtkShader::Vertex, "//VTK::PositionVC::Dec", // replace true, // before the standard replacements "//VTK::PositionVC::Dec\n" // we still want the default "out vec3 TexCoords;\n", false // only do it once ); sp->AddShaderReplacement(vtkShader::Vertex, "//VTK::PositionVC::Impl", // replace true, // before the standard replacements " gl_Position = vec4(vertexMC.xy, 1.0, 1.0);\n" " vec4 tmpc = inverse(MCDCMatrix) * gl_Position;\n" " TexCoords = tmpc.xyz/tmpc.w;\n", false // only do it once ); this->CubeMapper->AddObserver( vtkCommand::UpdateShaderEvent, this, &vtkOpenGLSkybox::UpdateUniforms); this->LastProjection = -1; this->LastGammaCorrect = false; this->GetProperty()->SetDiffuse(0.0); this->GetProperty()->SetAmbient(1.0); this->GetProperty()->SetSpecular(0.0); this->OpenGLActor->SetProperty(this->GetProperty()); this->CurrentRenderer = nullptr; } vtkOpenGLSkybox::~vtkOpenGLSkybox() = default; void vtkOpenGLSkybox::UpdateUniforms(vtkObject*, unsigned long, void* calldata) { vtkShaderProgram* program = reinterpret_cast<vtkShaderProgram*>(calldata); program->SetUniform3f("cameraPos", this->LastCameraPosition); float plane[4]; double norm = vtkMath::Norm(this->FloorPlane, 3); plane[0] = this->FloorPlane[0] / norm; plane[1] = this->FloorPlane[1] / norm; plane[2] = this->FloorPlane[2] / norm; plane[3] = this->FloorPlane[3] / norm; program->SetUniform4f("floorPlane", plane); program->SetUniform3f("floorRight", this->FloorRight); float front[3]; vtkMath::Cross(plane, this->FloorRight, front); program->SetUniform3f("floorFront", front); program->SetUniformf( "leftEye", (this->CurrentRenderer->GetActiveCamera()->GetLeftEye() ? 1.0 : 0.0)); } // Actual Skybox render method. void vtkOpenGLSkybox::Render(vtkRenderer* ren, vtkMapper* mapper) { vtkOpenGLClearErrorMacro(); if (this->LastProjection != this->Projection || this->LastGammaCorrect != this->GammaCorrect) { vtkOpenGLShaderProperty* sp = vtkOpenGLShaderProperty::SafeDownCast(this->OpenGLActor->GetShaderProperty()); std::string str = "//VTK::System::Dec\n" // always start with this line "//VTK::Output::Dec\n" // always have this line in your FS "in vec3 TexCoords;\n" "uniform vec3 cameraPos;\n" // wc camera position; "//VTK::Projection::Dec\n" "void main () {\n" "//VTK::Projection::Impl\n" "}\n"; if (this->Projection == vtkSkybox::Cube) { vtkShaderProgram::Substitute(str, "//VTK::Projection::Dec", "uniform samplerCube actortexture;\n" "uniform vec4 floorPlane;\n" // floor plane eqn "uniform vec3 floorRight;\n" // floor plane right "uniform vec3 floorFront;\n" // floor plane front ); vtkShaderProgram::Substitute(str, "//VTK::Projection::Impl", " vec3 diri = normalize(TexCoords - cameraPos);\n" " vec3 dirv = vec3(dot(diri,floorRight),\n" " dot(diri,floorPlane.xyz),\n" " dot(diri,floorFront));\n" " vec4 color = texture(actortexture, dirv);\n" "//VTK::Gamma::Impl\n"); } if (this->Projection == vtkSkybox::Sphere) { vtkShaderProgram::Substitute(str, "//VTK::Projection::Dec", "uniform sampler2D actortexture;\n" "uniform vec4 floorPlane;\n" // floor plane eqn "uniform vec3 floorRight;\n" // floor plane right "uniform vec3 floorFront;\n" // floor plane front ); vtkShaderProgram::Substitute(str, "//VTK::Projection::Impl", " vec3 diri = normalize(TexCoords - cameraPos);\n" " vec3 dirv = vec3(dot(diri,floorRight),\n" " dot(diri,floorPlane.xyz),\n" " dot(diri,floorFront));\n" " float phix = length(vec2(dirv.x, dirv.z));\n" " vec4 color = textureLod(actortexture, vec2(0.5*atan(dirv.x, " "dirv.z)/3.1415927 + 0.5, atan(dirv.y,phix)/3.1415927 + 0.5), 1.0);\n" "//VTK::Gamma::Impl\n"); } if (this->Projection == vtkSkybox::StereoSphere) { vtkShaderProgram::Substitute(str, "//VTK::Projection::Dec", "uniform sampler2D actortexture;\n" "uniform vec4 floorPlane;\n" // floor plane eqn "uniform vec3 floorRight;\n" // floor plane right "uniform vec3 floorFront;\n" // floor plane front "uniform float leftEye;\n" // 1.0 for left, 0.0 for right ); vtkShaderProgram::Substitute(str, "//VTK::Projection::Impl", " vec3 diri = normalize(TexCoords - cameraPos);\n" " vec3 dirv = vec3(dot(diri,floorRight),\n" " dot(diri,floorPlane.xyz),\n" " dot(diri,floorFront));\n" " float phix = length(vec2(dirv.x, dirv.z));\n" " vec4 color = textureLod(actortexture, vec2(0.5*atan(dirv.x, dirv.z)/3.1415927 + " "0.5, 0.5*atan(dirv.y,phix)/3.1415927 + 0.25 + 0.5*leftEye), 1.0);\n" "//VTK::Gamma::Impl\n"); } if (this->Projection == vtkSkybox::Floor) { vtkShaderProgram::Substitute(str, "//VTK::Projection::Dec", "uniform vec4 floorPlane;\n" // floor plane eqn "uniform vec3 floorRight;\n" // floor plane right "uniform vec3 floorFront;\n" // floor plane front "uniform mat4 MCDCMatrix;\n" "uniform sampler2D actortexture;\n"); vtkShaderProgram::Substitute(str, "//VTK::Projection::Impl", " vec3 dirv = normalize(TexCoords - cameraPos);\n" " float den = dot(floorPlane.xyz, dirv);\n" " if (abs(den) < 0.0001 ) { discard; } else {\n" " vec3 p0 = -1.0*floorPlane.w*floorPlane.xyz;\n" " vec3 p0l0 = p0 - cameraPos;\n" " float t = dot(p0l0, floorPlane.xyz) / den;\n" " if (t >= 0.0) {\n" " vec3 pos = dirv*t - p0l0;\n" " vec4 color = texture(actortexture, " "vec2(dot(floorRight,pos), dot(floorFront, pos)));\n" " //VTK::Gamma::Impl\n" // The discards cause a discontinuity with mipmapping // on the horizon of the floor. So we fade out the floor // along the horizon. Specifically starting at when the // dot product equals .02 which is at 88.85 degrees and // going to zero at 90 degrees. " gl_FragData[0].a *= (50.0*min(0.02, abs(den)));\n" " vec4 tpos = MCDCMatrix*vec4(pos.xyz,1.0);\n" " gl_FragDepth = clamp(0.5 + 0.5*tpos.z/tpos.w,0.0,1.0);\n" " } else { discard; }\n" " }\n"); } if (this->GammaCorrect) { vtkShaderProgram::Substitute(str, "//VTK::Gamma::Impl", "gl_FragData[0] = vec4(pow(color.rgb, vec3(1.0 / 2.2)), color.a);\n"); } else { vtkShaderProgram::Substitute(str, "//VTK::Gamma::Impl", "gl_FragData[0] = color;\n"); } sp->SetFragmentShaderCode(str.c_str()); this->CubeMapper->Modified(); this->LastProjection = this->Projection; this->LastGammaCorrect = this->GammaCorrect; } double* pos = ren->GetActiveCamera()->GetPosition(); this->LastCameraPosition[0] = pos[0]; this->LastCameraPosition[1] = pos[1]; this->LastCameraPosition[2] = pos[2]; this->CurrentRenderer = ren; // get opacity static_cast<vtkOpenGLRenderer*>(ren)->GetState()->vtkglDepthMask(GL_TRUE); static_cast<vtkOpenGLRenderer*>(ren)->GetState()->vtkglDepthFunc(GL_LEQUAL); // send a render to the mapper; update pipeline this->Texture->Render(ren); this->OpenGLActor->SetTexture(this->GetTexture()); mapper->Render(ren, this->OpenGLActor); this->Texture->PostRender(ren); vtkOpenGLCheckErrorMacro("failed after Render"); } //------------------------------------------------------------------------------ void vtkOpenGLSkybox::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
37.581749
95
0.618575
[ "render" ]
ba59addc61cda6abe89c9e1d770335f419ba3dbe
526
cpp
C++
src/solutions/aoc_day.cpp
jtt9340/aoc2021
06e0636dd0fbc948d37fe4a6abf8f21557b22353
[ "MIT" ]
null
null
null
src/solutions/aoc_day.cpp
jtt9340/aoc2021
06e0636dd0fbc948d37fe4a6abf8f21557b22353
[ "MIT" ]
null
null
null
src/solutions/aoc_day.cpp
jtt9340/aoc2021
06e0636dd0fbc948d37fe4a6abf8f21557b22353
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <iostream> #include "aoc_day.h" using namespace std; AocDay::AocDay(int day):m_day(day) { } AocDay::~AocDay() { } string AocDay::part1(string &filename, vector<string> &extra_args) { cerr << "*****Part 1 implementation for day " << m_day << " is not defined*****" << endl; return ""; } string AocDay::part2(string &filename, vector<string> &extra_args) { cerr << "*****Part 2 implementation for day " << m_day << " is not defined*****" << endl; return ""; }
18.137931
93
0.625475
[ "vector" ]
ba5b8e5eaab121ac105be5c7c80445838b6e655e
11,227
cpp
C++
src/Watchdog/Server/Util.cpp
dolik-rce/thewatchdog
875aa1cb165fe483c28a0c1cb6ae202c0abe54df
[ "BSD-2-Clause" ]
null
null
null
src/Watchdog/Server/Util.cpp
dolik-rce/thewatchdog
875aa1cb165fe483c28a0c1cb6ae202c0abe54df
[ "BSD-2-Clause" ]
null
null
null
src/Watchdog/Server/Util.cpp
dolik-rce/thewatchdog
875aa1cb165fe483c28a0c1cb6ae202c0abe54df
[ "BSD-2-Clause" ]
1
2019-06-21T15:35:35.000Z
2019-06-21T15:35:35.000Z
#include "Server.h" #include <plugin/pcre/Pcre.h> void CleanResults(){ SQL * Delete(RESULT) .Where(STATUS==WD_INPROGRESS && START < GetUtcTime()-int(Ini::max_test_time)); } void CleanAuth(){ SQL * Delete(AUTH).Where(VALID < GetUtcTime()-600); } CommitFilter::CommitFilter(Http& http, bool skipPaging){ //filter if(IsNull(http["f_change"])){ branch = http[".f_branch"]; msg = http[".f_msg"]; author = http[".f_author"]; path = http[".f_path"]; } else { branch = http["f_branch"]; msg = http["f_msg"]; author = http["f_author"]; path = http["f_path"]; http.SessionSet("f_branch", branch); http.SessionSet("f_msg", msg); http.SessionSet("f_author", author); http.SessionSet("f_path", path); } //paging if (skipPaging) return; int count = 3; int pagesize = max(min(Nvl(http.Int("cnt"), Nvl(http.Int(".cnt"), 10)),100),1); http.SessionSet("cnt",pagesize); int total = commitcount(); int hi = total/pagesize; int current = Nvl(http.Int("page"), hi); limit = pagesize; offset = pagesize*(hi-current); ValueArray va; ValueMap vm; if(current != hi){ vm.Set("TEXT", "<< Newest"); va.Add(vm); } for(int i = min(current+count, hi); i > current; --i){ vm.Set("PAGE", i); vm.Set("TEXT", IntStr(i)); va.Add(vm); } if(current < hi){ vm.Set("PAGE", current + 1); vm.Set("TEXT", "< Newer"); va.Add(vm); } { vm.Set("PAGE", "current"); vm.Set("TEXT", IntStr(current)); va.Add(vm); } if(current > 0){ vm.Set("PAGE", current - 1); vm.Set("TEXT", "Older >"); va.Add(vm); } for(int i = current - 1; i > max(current-(count+1), 0); --i){ vm.Set("PAGE", i); vm.Set("TEXT", IntStr(i)); va.Add(vm); } if(current != 0){ vm.Set("PAGE", 0); vm.Set("TEXT", "Oldest >>"); va.Add(vm); } http("PAGING", va); } CommitFilter::operator SqlBool() const{ SqlBool res; if(!IsEmpty(branch)) { if(res.IsEmpty()) res = Regexp(BRANCH, ".*"+branch+".*"); else res &= Regexp(BRANCH, ".*"+branch+".*"); } if(!IsEmpty(msg)) { if(res.IsEmpty()) res = Regexp(MSG, ".*"+msg+".*"); else res &= Regexp(MSG, ".*"+msg+".*"); } if(!IsEmpty(author)) { if(res.IsEmpty()) res = Regexp(AUTHOR, ".*"+author+".*"); else res &= Regexp(AUTHOR, ".*"+author+".*"); } if(!IsEmpty(path)) { if(res.IsEmpty()) res = Regexp(PATH, ".*"+path+".*"); else res &= Regexp(PATH, ".*"+path+".*"); } if(res.IsEmpty()) res.SetTrue(); return res; } unsigned CommitFilter::GetHash() const { return CombineHash(branch, author, path, msg); } CommitFilter::CacheEntry::CacheEntry(const CommitFilter& f) { hash = f.GetHash(); used = stamp = GetUtcTime(); Sql sql; sql * Select(Count(SqlAll()).As("CNT")) .From(COMMITS) .Where(f); ValueMap vm; if(sql.Fetch(vm)) count = vm["CNT"]; else count = 0; LOG("CREATE "<<hash<<"@"<<stamp); } int CommitFilter::FindInCache(unsigned hash, const Time& maxage) const { // first, we search for item in cache for(int i = 0; i < cache.GetCount(); ++i){ if(cache[i].hash == hash){ // found the item... if(cache[i].stamp < maxage){ // ... but it is expired, so we replace it by refreshed version cache[i] = CacheEntry(*this); } else { // .. and it is not expired, we only update the usage timestamp cache[i].used = GetUtcTime(); } return i; } } // if we get here, we know the searched entry is not in the cache and we have to add it if(Ini::filter_cache_size == cache.GetCount()){ // cache is full, we first try to drop expired items Vector<int> rem; for(int i = 0; i < cache.GetCount(); ++i){ if(cache[i].stamp < maxage) rem.Add(i); } if(rem.GetCount() > 0){ // found some expired items, drop them and add fresh entry cache.Remove(rem); cache.Add(CacheEntry(*this)); return cache.GetCount()-1; } else { // no items are expired, we have to replace the least recently used item int oldest = 0; for(int i = 1; i < cache.GetCount(); i++){ if(cache[oldest].used > cache[i].used) oldest = i; } cache[oldest] = CacheEntry(*this); return oldest; } } else { // there is enough space in the cache, just add new item cache.Add(CacheEntry(*this)); return cache.GetCount()-1; } } Vector<CommitFilter::CacheEntry> CommitFilter::cache; int CommitFilter::commitcount(){ int p = FindInCache(GetHash(), GetUtcTime()-Ini::filter_cache_expiration); return cache[p].count; } bool CheckLocal(Http& http){ if(http.GetHeader("host").StartsWith("localhost") ||http.GetHeader("host").StartsWith("127.0.0.1")) return true; http.Response(403, "Forbiden"); return false; } bool CheckAuth(Http& http, Sql& sql, int client, const String& action){ #define AUTHLOG(X) RLOG("AUTH "<<X<<" (client:"<<cid<<", action:"<<http["wd_action"]<<", ip:"<<http.GetPeerAddr()<<")") int cid=http.Int("client_id"); if(cid!=client && cid!=0){ http << "Permission denied"; http.Response(403,"Permission denied"); AUTHLOG("FAIL [wrong client id]"); return false; } if(http["wd_action"] != action) { http << "Auth FAIL (action)"; http.Response(403,"Permission denied"); AUTHLOG("FAIL [wrong action]"); return false; } String nonce = http["wd_nonce"]; String auth = http["wd_auth"]; sql * Delete(AUTH).Where(NONCE==nonce); if(sql.GetRowsProcessed() == 0){ http << "Auth FAIL (nonce)"; http.Response(403,"Permission denied"); AUTHLOG("FAIL [wrong nonce]"); return false; } sql * Select(PASSWORD) .From(CLIENT).Where(ID == http.Int("client_id")); String pwd; sql.Fetch(pwd); if (auth!=MD5String(nonce+String(http["wd_action"])+pwd)) { http << "Auth FAIL (auth)"; http.Response(403,"Permission denied"); AUTHLOG("FAIL [wrong password]"); return false; } AUTHLOG("OK"); return true; #undef AUTHLOG } ValueArray ParseFilter(const String& filter){ Vector<String> v = Split(filter,"&"); ValueArray res; if(v.IsEmpty()) { res.Add("All the results"); return res; } for(int i = 0; i < v.GetCount(); i++){ if(v[i].StartsWith("author=")){ v[i].Replace("author=","Author is "); res.Add(v[i]); } else if(v[i].StartsWith("path=")){ v[i].Replace("path=","Commit affects path "); res.Add(v[i]); } else if(v[i].StartsWith("client=")){ v[i].Replace("client=",""); Sql sql; sql * Select(NAME).From(CLIENT).Where(ID==StrInt(v[i])); String name; sql.Fetch(name); res.Add("Client is " + name); } else if(v[i].StartsWith("status=")){ res.Add(v[i].EndsWith("=ok")?"Only successfull":"Only failed"); } } return res; } bool MatchFilter(const String& filter, const String& commit, const String& branch, int client, bool result, const String& author, const String& path){ Vector<String> v = Split(filter,"&"); if(v.IsEmpty()) return true; for(int i = 0; i < v.GetCount(); i++){ if(v[i].StartsWith("author=")){ v[i].Replace("author=",""); if(author != v[i]) return false; } else if(v[i].StartsWith("path=")){ v[i].Replace("path=",""); RegExp re(v[i]); if (re.Match(path)) return false; } else if(v[i].StartsWith("branch=")){ v[i].Replace("branch=",""); RegExp re(v[i]); if (re.Match(branch)) return false; } else if(v[i].StartsWith("client=")){ v[i].Replace("client=",""); if(StrInt(v[i]) != client) return false; } else if(v[i].StartsWith("status=")){ if (!((v[i].EndsWith("=ok") && result) || (v[i].EndsWith("=failed") && !result))) return false; } } return true; } String SuccessRate(int status, int ok, int fail, int err){ if (status != WD_DONE || ok+fail+err == 0) return ""; return DblStr(roundr(100.0*ok/(ok+fail+err), 2))+"%"; } String ComputeStatus(int status, int ok, int fail, int err){ if (status == WD_INPROGRESS) return "In progress"; if (ok+err+fail == 0) return "No results"; if (status != WD_DONE) return ""; String s; if (err>0) s = "E:" + IntStr(err); if (fail>0) s += (s.IsEmpty() ? "F:" : ", F:") + IntStr(fail); return s.IsEmpty() ? "OK" : ("(" + s + ")"); } Value ComputeColor(int status, int ok, int fail, int err, bool quoted){ if(status == WD_INPROGRESS) return Raw(quoted?"\"#88F\"":"s88F"); if (ok+fail+err == 0) return Raw(""); double norm = 1.0 / (ok+fail+err); int r = 0x7 * fail * norm + 0x8; int g = 0x7 * ok * norm + 0x8; int b = 0x8; return Raw(Format(quoted?"\"#%X%X%X\"":"s%X%X%X", r, g, b)); } void SetComputedAttributes(ValueMap& vm, int status, const String& suffix) { int st = status ? status : V2N(vm["STATUS"+suffix]); int ok = V2N(vm["OK"+suffix]); int fail = V2N(vm["FAIL"+suffix]); int err = V2N(vm["ERR"+suffix]); vm.Add("RATE"+suffix, SuccessRate(st, ok, fail, err)); vm.Add("COLOR"+suffix, ComputeColor(st, ok, fail, err)); vm.Add("STATUSSTR"+suffix, String(vm["RATE"+suffix]) + " " + ComputeStatus(st, ok, fail, err)); } void SetDuration(ValueMap& vm, int status) { vm.Set("DURATION", ((status == WD_INPROGRESS)?GetUtcTime():Time(vm["FINISHED"]))-Time(vm["START"])); } Value Duration(const Vector<Value>& arg, const Renderer *) { int t = arg[0]; if (t<=0) return ""; else if (t<60) return Format("%d`s", t); else if (t<3600) return Format("%d`m %d`s", t/60, t%60); else return Format("%d`h %d`m %d`s", t/3600, (t%3600)/60, (t%3600)%60); } Value Email(const Vector<Value>& arg, const Renderer *) { String name; switch(arg.GetCount()) { case 1: name = arg[0]; break; case 2: name = arg[1]; break; case 0: default: throw Exc("email: wrong number of arguments"); } String addr; addr.Cat() << "<a href=\"mailto:" << arg[0] << "\">" << name << "</a>"; RawHtmlText r; r.text.Cat("<script type=\"text/javascript\">document.write('"); for(int i = addr.GetCount()-1; i >= 0; --i) r.text.Cat(addr[i]); r.text.Cat("'.split('').reverse().join(''));</script>"); return RawPickToValue(r); } Value LocalTime(const Vector<Value>& arg, const Renderer *) { Time t = arg[0]; bool js = arg.GetCount() > 1 && (int)arg[1] == 1; if (IsNull(t)) return js ? "''" : ""; RawHtmlText r; if (!js) r.text.Cat("<script type=\"text/javascript\">document.write("); r.text.Cat("(new Date("); r.text.Cat(AsString(GetUTCSeconds(t)*1000)); r.text.Cat(")).toLocaleString()"); if (!js) r.text.Cat(");</script>"); return RawPickToValue(r); } Value Dbg(const Vector<Value>& arg, const Renderer *r) { int force = arg.GetCount() ? int(arg[0]) : -1; if (!(force == 1 || (force != 0 && Ini::debug))) return Value(); String html; if(r) { const VectorMap<String, Value>& set = r->Variables(); html << "<div class=\"dbg\"><table border='1'><tr><th>ID</th><th>VALUE</th></tr>"; for(int i = 0; i < set.GetCount(); i++) html << "<tr><td>" << EscapeHtml(set.GetKey(i)) << "</td><td><pre class=\"prewrap\">" << EscapeHtml(AsString(set[i])) << "</pre></td></tr>" ; html << "</table></div>"; } return Raw(html); } Value Params(const Vector<Value>& arg, const Renderer *) { RawHtmlText r; r.text = arg[0].To<RawHtmlText>().text; r.text.Insert(r.text.GetCount()-1, AsString(arg[1])); return RawPickToValue(r); } INITBLOCK { Compiler::Register("Duration", Duration); Compiler::Register("email", Email); Compiler::Register("time", LocalTime); Compiler::Register("dbg", Dbg); Compiler::Register("params", Params); };
26.730952
120
0.606752
[ "vector" ]
ba5d3acaf93dce75c3d875e29fbf4af331676250
20,775
cpp
C++
CP3/1.4/00139_Telephone_Tangles.cpp
phongvcao/Competitive_Programming_Books
90734b0ffb21a43932a179d6d698281a6aefd9cb
[ "MIT" ]
null
null
null
CP3/1.4/00139_Telephone_Tangles.cpp
phongvcao/Competitive_Programming_Books
90734b0ffb21a43932a179d6d698281a6aefd9cb
[ "MIT" ]
null
null
null
CP3/1.4/00139_Telephone_Tangles.cpp
phongvcao/Competitive_Programming_Books
90734b0ffb21a43932a179d6d698281a6aefd9cb
[ "MIT" ]
null
null
null
// // Created by Phong Cao. // // uncomment to disable assert() // #define NDEBUG #include <cassert> #include <iostream> #include <cstdio> #include <iomanip> #include <ios> #include <sstream> #include <fstream> #include <string> #include <cmath> #include <cstdlib> #include <ctime> #include <functional> #include <array> #include <vector> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <list> #include <forward_list> #include <deque> #include <queue> #include <stack> #include <tuple> #include <iterator> #include <utility> #include <algorithm> #include <memory> #include <cctype> #include <stdexcept> #include <limits> #include <numeric> //----< iostream >--------------// using std::cout; using std::cin; using std::endl; using std::ostream; using std::istream; //----< cstdio >----------------// using std::printf; using std::fprintf; using std::sprintf; using std::snprintf; //----< iomanip >---------------// using std::setprecision; using std::setw; //----< ios >-------------------// using std::hex; using std::dec; using std::oct; using std::fixed; //----< sstream >---------------// using std::stringstream; using std::ostringstream; using std::istringstream; //----< fstream >---------------// using std::ofstream; using std::ifstream; //----< string >----------------// using std::getline; using std::string; using std::to_string; using std::stoi; using std::stol; //----< cmath >-----------------// using std::sqrt; using std::pow; using std::log; // log( <arg> ) using std::exp; // e ^ <arg> using std::abs; using std::fabs; using std::floor; // Round down to nearest integer double using std::ceil; // Round up to nearest integer double using std::trunc; // Truncate the fractional part to get the integer part using std::round; // Round to nearest integer double //----< cstdlib >---------------// using std::rand; using std::srand; //----< ctime >-----------------// using std::time; //----< functional >------------// using std::hash; using std::greater; // lhs > rhs. Used for MinPQ using std::less; // lhs < rhs. Used for MaxPQ. Default for priority_queue<> using std::less_equal; using std::greater_equal; //----< array >-----------------// using std::array; // Fixed & Unordered Array //----< vector >----------------// using std::vector; // Resizable & Unordered Array //----< map >-------------------// using std::map; // Ordered Map (Red-Black Tree) using std::multimap; // Ordered Map (Red-Black Tree) & Allow duplicated keys //----< unordered_map >---------// using std::unordered_map; // HashMap (SeparateChainingHashST) using std::unordered_multimap; // Ordered Map (Red-Black Tree) & Allow duplicated keys //----< set >-------------------// using std::set; // Ordered Set (Red-Black Tree) using std::multiset; // Ordered Set (Red-Black Tree) & Allow duplicated keys //----< unordered_set >---------// using std::unordered_set; // HashSet (SeparateChainingHashST) using std::unordered_multiset; // HashSet (SeparateChainingHashST) & Allow duplicated keys //----< list >------------------// using std::list; // Doubly-Linked List with size() ( O( 1 ) ) //----< forward_list >----------// using std::forward_list; // Singly-Linked List without size() function ( so O( N ) if we need to get size() ) //----< deque >-----------------// using std::deque; // Vector of fixed-size Vectors: 1 fixed-size vector for each end of the deque //----< queue >-----------------// using std::queue; // Non-Iterable & Use std::deque as underlying data structure using std::priority_queue; // MaxPQ (MaxHeap) & Non-Iterable. // // => Pass std::greater<> as template params to create MinPQ (MinHeap) //----< stack >-----------------// using std::stack; // Non-Iterable & Use std::deque as underlying data structure //----< tuple >-----------------// using std::tuple; // Non-Iterable & Use std::pair as underlying data structure using std::get; // Access & Set element in tuple using get< index >( tuple_var ) //----< iterator >--------------// using std::next; // Return an advanced iter without changing original iter using std::prev; // Return an decremented iter without changing original iter using std::distance; // Calculate distance between 2 iterators using std::inserter; // Insert element into first arg starting from position in second arg //----< utility >---------------// using std::pair; using std::make_pair; using std::move; // Move resources between objects - typically used with std::unique_ptr<T> //----< algorithm >-------------// using std::fill; using std::max; using std::min; using std::find; using std::reverse; using std::sort; // Intro-Sort elements, but NOT preserve original order of equal elements using std::partial_sort; // Sort elements in range ( iterFirst, iterLast ) ( exclusively ) using std::stable_sort; // Merge-Sort elements & preserve original order of equal elements using std::remove; using std::swap; using std::binary_search; using std::next_permutation; using std::set_intersection; // Only works on std::set and not std::unordered_set // using std::nth_element; //----< memory >----------------// // using std::make_unique; using std::unique_ptr; using std::make_shared; using std::shared_ptr; using std::weak_ptr; //----< cctype >----------------// using std::isalnum; using std::isalpha; using std::islower; using std::isupper; using std::isdigit; using std::isspace; // Check whether char is whitespace character (space, newline, tab, etc. ) using std::isblank; // Check whether char is blank character ( space or tab ) using std::tolower; using std::toupper; //----< stdexcept >-------------// using std::runtime_error; using std::invalid_argument; using std::out_of_range; //----< limits >----------------// using std::numeric_limits; //----< numeric >---------------// using std::iota; // using std::gcd; // using std::lcm; //------------------------------// class Code { public: static const int CODE_LOCAL = 0; static const int CODE_NATIONAL = 1; static const int CODE_INTERNATIONAL = 2; static const int CODE_UNKNOWN = 3; int codeType = CODE_UNKNOWN; string areaCode = ""; string name = ""; int priceInCents = 0; double priceInDollars = 0; static int getCodeType( const string& numStr ) { if ( numStr[ 0 ] == '0' && numStr[ 1 ] == '0' ) { if ( numStr[ 2 ] != ' ' ) { return CODE_INTERNATIONAL; } else { return CODE_NATIONAL; } } else if ( numStr[ 0 ] == '0' ) { return CODE_NATIONAL; } else { return CODE_LOCAL; } } static int getCodeTypeWithSize( const string& numStr ) { if ( numStr[ 0 ] == '0' && numStr[ 1 ] == '0' ) { if ( numStr[ 2 ] != ' ' ) { return CODE_INTERNATIONAL; } else { return CODE_NATIONAL; } } else if ( numStr[ 0 ] == '0' ) { return CODE_NATIONAL; } else { return CODE_LOCAL; } } static int getMaxAreaCodeSize( int codeType ) { switch ( codeType ) { case CODE_NATIONAL: { return 5; } case CODE_INTERNATIONAL: { return 3; } case CODE_LOCAL: case CODE_UNKNOWN: { return 0; } default: { return 0; } } return 0; } Code() { // not implemented } Code( const string& codeStr ) : codeType( getCodeType( codeStr ) ) { stringstream ss( codeStr ); ss >> this->areaCode; string nameNPrice = codeStr.substr( this->areaCode.size() ); this->areaCode = this->areaCode.substr( codeType ); size_t dollarSignIdx = nameNPrice.find( "$" ); if ( dollarSignIdx != string::npos ) { this->priceInCents = atoi( nameNPrice.substr( dollarSignIdx + 1 ).c_str() ); this->priceInDollars = ( double )this->priceInCents / 100.0; } this->name = nameNPrice.substr( 0, dollarSignIdx ); int firstSpaceIdx = this->name.find_first_not_of( " " ); int lastSpaceIdx = this->name.find_last_not_of( " " ); if ( firstSpaceIdx != -1 && lastSpaceIdx != -1 ) { this->name = name.substr( firstSpaceIdx, lastSpaceIdx + 1 - firstSpaceIdx ); } } Code( int codeType, const string& areaCode, const string& name, int priceInCents, double priceInDollars ) : codeType( codeType ), areaCode( areaCode ), name( name ), priceInCents( priceInCents ), priceInDollars( priceInDollars ) { // not implemented } Code( const Code& other ) : codeType( other.codeType ), areaCode( other.areaCode ), name( other.name ), priceInCents( other.priceInCents ), priceInDollars( other.priceInDollars ) { // not implemented } virtual ~Code() { // not implemented } friend bool operator <( const Code& c1, const Code& c2 ) { return c1.areaCode < c2.areaCode; } friend bool operator >( const Code& c1, const Code& c2 ) { return c1.areaCode > c2.areaCode; } friend bool operator ==( const Code& c1, const Code& c2 ) { return c1.areaCode == c2.areaCode; } friend bool operator !=( const Code& c1, const Code& c2 ) { return ! ( c1 == c2 ); } friend ostream& operator <<( ostream& out, const Code& code ) { out << " | codeType : " << code.codeType << " ; areaCode : " << code.areaCode << " ; name : " << code.name << " ; priceInCents : " << code.priceInCents << " ; priceInDollars : " << code.priceInDollars << " | "; return out; } }; class Number { public: static int getNumberType( const string& numStr, bool ignoreIntl = false ) { int codeType = Code::getCodeType( numStr ); if ( ignoreIntl && codeType == Code::CODE_INTERNATIONAL ) { codeType = Code::CODE_NATIONAL; } switch ( codeType ) { case Code::CODE_NATIONAL: { if ( numStr.size() < 6 || numStr.size() > 13 ) return Code::CODE_UNKNOWN; break; } case Code::CODE_INTERNATIONAL: { if ( numStr.size() < 7 || numStr.size() > 15 ) { if ( numStr.size() >= 6 && numStr.size() <= 13 ) return Code::CODE_NATIONAL; return Code::CODE_UNKNOWN; } break; } default: { return Code::CODE_LOCAL; } } return codeType; } Number() { // not implemented } Number( const Number& other ) { // not implemented } virtual ~Number() { // not implemented } }; int main( int argc, char ** argv ) { // We will have a vector< set< Code > > of all codes // // For the numbers, we first identify the primitive numberType // Then we use this primitive type to extract: // - areaCode // The areaCode will be extract as longest, and we'll pop_back() each char // & find the areaCode in the respective set< Code >. If none is found, // then the area is unknown // If we can find the area code, we'll calculate & print out the result // string line = ""; vector< set< Code > > codeSetVec( 4, set< Code >() ); int stepCount = 0; while ( getline( cin, line ) ) { if ( line == "000000" ) { ++stepCount; continue; } else if ( line == "#" ) { break; } if ( stepCount == 0 ) { // We're reading in information for codeSetVec stringstream ss( line ); string areaCode = ""; ss >> areaCode; string nameNPrice = line.substr( areaCode.size() ); size_t dollarSignIdx = nameNPrice.find( "$" ); int priceInCents = 0; double priceInDollars = 0; if ( dollarSignIdx != string::npos ) { priceInCents = atoi( nameNPrice.substr( dollarSignIdx + 1 ).c_str() ); priceInDollars = ( double )priceInCents / 100.0; } string name = nameNPrice.substr( 0, dollarSignIdx ); int firstSpaceIdx = name.find_first_not_of( " " ); int lastSpaceIdx = name.find_last_not_of( " " ); if ( firstSpaceIdx != -1 && lastSpaceIdx != -1 ) { name = name.substr( firstSpaceIdx, lastSpaceIdx + 1 - firstSpaceIdx ); } int codeType = Code::getCodeType( line ); switch ( codeType ) { case Code::CODE_INTERNATIONAL: { // This can be both INTERNATIONAL & NATIONAL // CODE_INTERNATIONAL if ( areaCode.size() >= 3 && areaCode.size() <= 5 ) { codeType = Code::CODE_INTERNATIONAL; string tempAreaCode = areaCode.substr( codeType ); Code code( codeType, tempAreaCode, name, priceInCents, priceInDollars ); codeSetVec[ code.codeType ].insert( code ); } // CODE_NATIONAL if ( areaCode.size() >= 2 && areaCode.size() <= 6 ) { codeType = Code::CODE_NATIONAL; string tempAreaCode = areaCode.substr( codeType ); Code code( codeType, tempAreaCode, name, priceInCents, priceInDollars ); codeSetVec[ code.codeType ].insert( code ); } break; } case Code::CODE_NATIONAL: { // This can only be NATIONAL Code code( codeType, areaCode.substr( codeType ), name, priceInCents, priceInDollars ); codeSetVec[ code.codeType ].insert( code ); break; } default: { // Local break; } } } else if ( stepCount == 1 ) { // We're reading in numbers information stringstream ss( line ); int dur = 0; string numStr = ""; ss >> numStr; if ( line.size() == numStr.size() ) { getline( cin, line ); ss.clear(); ss.str( line ); ss >> dur; } else { ss >> dur; } int numberType = Number::getNumberType( numStr ); bool answerFound = false; switch ( numberType ) { case Code::CODE_LOCAL: { printf( "%-16s%-20s%15s%5d%6.2f%7.2f\n", numStr.c_str(), "Local", numStr.c_str(), dur, 0.0, 0.0 ); answerFound = true; break; } case Code::CODE_NATIONAL: case Code::CODE_INTERNATIONAL: { // If we cannot find this national/international code, // it's probably UNKNOWN string areaCode = numStr.substr( numberType, Code::getMaxAreaCodeSize( numberType ) ); string trueNum = numStr.substr( numberType + Code::getMaxAreaCodeSize( numberType ) ); string tempAreaCode = ""; string tempTrueNum = areaCode + trueNum; for ( int i = 0; i < areaCode.size(); i++ ) { Code query; tempAreaCode += areaCode[ i ]; tempTrueNum = tempTrueNum.substr( 1 ); query.areaCode = tempAreaCode; set< Code >::iterator codeSetIter = codeSetVec[ numberType ].find( query ); if ( codeSetIter != codeSetVec[ numberType ].end() ) { if ( ( tempTrueNum.size() < 4 || tempTrueNum.size() > 10 ) && ( numberType == Code::CODE_INTERNATIONAL ) ) { continue; } if ( ( tempTrueNum.size() < 4 || tempTrueNum.size() > 7 ) && ( numberType == Code::CODE_NATIONAL ) ) { continue; } printf( "%-16s%-20s%15s%5d%6.2f%7.2f\n", numStr.c_str(), codeSetIter->name.c_str(), tempTrueNum.c_str(), dur, ( double )codeSetIter->priceInCents / 100.0, ( double )dur * ( double )codeSetIter->priceInCents / 100.0 ); answerFound = true; break; } } break; } default: { break; } } if ( ! answerFound ) { if ( numberType == Code::CODE_INTERNATIONAL ) { numberType = Number::getNumberType( numStr, true ); if ( numberType == Code::CODE_NATIONAL ) { // If we cannot find this international code, // we should try national code string areaCode = numStr.substr( numberType, Code::getMaxAreaCodeSize( numberType ) ); string trueNum = numStr.substr( numberType + Code::getMaxAreaCodeSize( numberType ) ); string tempAreaCode = ""; string tempTrueNum = areaCode + trueNum; for ( int i = 0; i < areaCode.size(); i++ ) { Code query; tempAreaCode += areaCode[ i ]; tempTrueNum = tempTrueNum.substr( 1 ); query.areaCode = tempAreaCode; set< Code >::iterator codeSetIter = codeSetVec[ numberType ].find( query ); if ( codeSetIter != codeSetVec[ numberType ].end() ) { if ( ( tempTrueNum.size() < 4 || tempTrueNum.size() > 10 ) && ( numberType == Code::CODE_INTERNATIONAL ) ) { continue; } if ( ( tempTrueNum.size() < 4 || tempTrueNum.size() > 7 ) && ( numberType == Code::CODE_NATIONAL ) ) { continue; } printf( "%-16s%-20s%15s%5d%6.2f%7.2f\n", numStr.c_str(), codeSetIter->name.c_str(), tempTrueNum.c_str(), dur, ( double )codeSetIter->priceInCents / 100.0, ( double )dur * ( double )codeSetIter->priceInCents / 100.0 ); answerFound = true; break; } } } } } if ( ! answerFound ) { printf( "%-16s%-20s%15s%5d%6s%7.2f\n", numStr.c_str(), "Unknown", "", dur, "", -1.0 ); } } else { break; } } return 0; }
32.768139
140
0.480289
[ "vector" ]
ba5d554258408b6e60b6955d0a90363120abd0d0
3,506
hpp
C++
Nummerical Methods for CSE/PS12/rkintegrator_cus.hpp
valentinjacot/backupETHZ
36605c4f532eb65efb4a391ed0f17a07102f7d5b
[ "MIT" ]
1
2019-12-25T10:21:30.000Z
2019-12-25T10:21:30.000Z
Nummerical Methods for CSE/PS12/rkintegrator_cus.hpp
valentinjacot/backupETHZ
36605c4f532eb65efb4a391ed0f17a07102f7d5b
[ "MIT" ]
null
null
null
Nummerical Methods for CSE/PS12/rkintegrator_cus.hpp
valentinjacot/backupETHZ
36605c4f532eb65efb4a391ed0f17a07102f7d5b
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <cassert> #include <iostream> #include <iomanip> #include <Eigen/Dense> //! \file rkintegrator.hpp Solution for Problem 1a, implementing RkIntegrator class //! \brief Implements a Runge-Kutta explicit solver for a given Butcher tableau for autonomous ODEs //! \tparam State a type representing the space in which the solution lies, e.g. R^d, represented by e.g. Eigen::VectorXd. template <class State> class RKIntegrator { public: //! \brief Constructor for the RK method. //! Performs size checks and copies A and b into internal storage //! \param[in] A matrix containing coefficents of Butcher tableau, must be (strictly) lower triangular (no check) //! \param[in] b vector containing coefficients of lower part of Butcher tableau RKIntegrator(const Eigen::MatrixXd & A, const Eigen::VectorXd & b): A_(A),b_(b){ n=A_.rows(); assert(n==b_.size() && "size missmatch custom error"); assert(A_.rows()==A_.cols() && "matrix not square custom error"); // TODO: implement size checks and initialize internal data (DONE?) } //! \brief Perform the solution of the ODE //! Solve an autonomous ODE y' = f(y), y(0) = y0, using a RK scheme given in the Butcher tableau provided in the //! constructor. Performs N equidistant steps upto time T with initial data y0 //! \tparam Function type for function implementing the rhs function. Must have State operator()(State x) //! \param[in] f function handle for rhs in y' = f(y), e.g. implemented using lambda funciton //! \param[in] T final time T //! \param[in] y0 initial data y(0) = y0 for y' = f(y) //! \param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant. //! \return vector containing all steps y^n (for each n) including initial and final value template <class Function> std::vector<State> solve(const Function &f, double T, const State & y0, unsigned int N) const { double h = T/N; std::vector<State> y_f; y_f.reserve(N); y_f.push_back(y0); State ytemp1 = y0; State ytemp2 = y0; // Pointers to swap previous value State * yold = &ytemp1; State * ynew = &ytemp2; for (int i =1; i<N;++i){ step(f,h,*yold,*ynew); y_f.push_back(*ynew); std::swap(yold,ynew); } return y_f; // TODO: implement solver from 0 to T, calling function step appropriately } private: //! \brief Perform a single step of the RK method for the solution of the autonomous ODE //! Compute a single explicit RK step y^{n+1} = y_n + \sum ... starting from value y0 and storing next value in y1 //! \tparam Function type for function implementing the rhs. Must have State operator()(State x) //! \param[in] f function handle for ths f, s.t. y' = f(y) //! \param[in] h step size //! \param[in] y0 initial state //! \param[out] y1 next step y^{n+1} = y^n + ... template <class Function> void step(const Function &f, double h, const State & y0, State & y1) const { y1 = y0; std::vector<State> k; k.reserve(n); for (int i=0;i<n;++i){ State incr=y0; for (int j=0;j<i;++j){ incr+=h*A_(i,j)*k.at(j); } k.push_back(f(incr)); y1+=h*b_(i)*k.back(); } // TODO: implement a single step of the RK method using provided Butcher scheme } //! TODO: put here suitable internal data storage const Eigen::VectorXd b_; const Eigen::MatrixXd A_; unsigned n; };
38.527473
122
0.650314
[ "vector" ]
ba6068e3cfffc09165ef6844de7454d3a7b3bfa4
1,744
cpp
C++
Failed/1152B-failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
Failed/1152B-failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
Failed/1152B-failed.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
#include <bits/stdc++.h> using namespace std; #define PI 2*acos(0) #define ll unsigned int bool myAssert(bool b); void testDrivenDevelopment(); int start(int argc=0, char const *argv[] = NULL); // int n,m; vector<int> *g; bool *isvisited; int getNumberOfOnes(const ll& m){ ll n = m; int mycount = 0; while (n>0){ mycount = mycount+(n&1); n = (n>>1); } } int getLen(const ll& m,const ll& p ){ ll q=p; ll n=m; int mycount = 0; while( q != 0 ){ q = q - (n&1); n=n>>1; mycount++; } return mycount; } int findLeftMostZeroPosition(const ll& N, const ll& size){ ll n = size; ll retSize = size; n = 1<<n; while( (N&n) !=0 ){ n=n>>1; } retSize = n; return retSize; } int getNextOddNumber(const ll& input){ ll ret = input; ret = (ret<<1); ret = ret - 1; return ret; } int main(int argc, char const *argv[]) { /* code */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); /* cout << setprecision(8); cout << num1 << endl; */ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll x; int len=0; int count=0; vector<ll> nextOddNum; cin>>x; len = getLen(x, getNumberOfOnes(x)); ll temp = findLeftMostZeroPosition(x,len); while(temp!=0){ temp = getNextOddNumber(temp); nextOddNum.push_back(temp); x = x^temp; // step 1 x = x+1; // step 2 temp = findLeftMostZeroPosition(x,len); } ll mysize = nextOddNum.size(); mysize = mysize<<1; cout<<mysize<<"\n"; mysize = mysize>>1; for(int i=0; i<mysize; i++){ cout<<nextOddNum[i]<<" "; }cout<<"\n"; return 0; }
18.553191
58
0.534977
[ "vector" ]
ba611d6e5044938a1a6123f94de09b10cdd18647
31,796
cpp
C++
Stardust/src/graphics/renderer/Renderer.cpp
LucidSigma/stardust
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
[ "MIT" ]
7
2020-10-08T11:40:53.000Z
2022-03-30T10:40:06.000Z
Stardust/src/graphics/renderer/Renderer.cpp
LucidSigma/stardust
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
[ "MIT" ]
1
2020-10-08T11:44:27.000Z
2020-12-01T08:43:19.000Z
Stardust/src/graphics/renderer/Renderer.cpp
LucidSigma/stardust
7012b46b0e75fa272e0bd39f3a1cc483c29fc10c
[ "MIT" ]
null
null
null
#include "stardust/graphics/renderer/Renderer.h" #include <algorithm> #include <numeric> #include <utility> #include "stardust/graphics/renderer/objects/BufferUsage.h" #include "stardust/graphics/shaders/Shader.h" #include "stardust/graphics/colour/Colours.h" namespace stardust { Renderer::Renderer(const CreateInfo& createInfo) { Initialise(createInfo); } Renderer::~Renderer() noexcept { Destroy(); } void Renderer::Initialise(const CreateInfo& createInfo) { m_window = createInfo.window; SetVirtualSize(createInfo.virtualSize.has_value() ? createInfo.virtualSize.value() : m_window->GetDrawableSize()); UpdateScreenProjectionMatrix(); ProcessResize(); SetClearColour(colours::Black); SetPolygonMode(PolygonMode::Filled); m_worldQuadBuffer.resize(s_MaxVerticesPerBatch); m_worldQuadBufferPtr = m_worldQuadBuffer.data(); m_screenQuadBuffer.resize(s_MaxVerticesPerBatch); m_screenQuadBufferPtr = m_screenQuadBuffer.data(); InitialiseVertexObjects(); if (!m_worldVertexBuffer.IsValid() || !m_worldVertexLayout.IsValid() || !m_worldIndexBuffer.IsValid() || !m_screenVertexBuffer.IsValid() || !m_screenVertexLayout.IsValid() || !m_screenIndexBuffer.IsValid()) { return; } InitialiseShaders(); if (!m_batchShader.IsValid()) { return; } static const Vector<ubyte> blankTextureData{ 0xFF, 0xFF, 0xFF, 0xFF, }; m_blankTexture.Initialise(blankTextureData, UVec2{ 1u, 1u }, 4u); if (!m_blankTexture.IsValid()) { return; } InitialiseTextureIndices(); m_isValid = true; } void Renderer::Destroy() noexcept { if (m_isValid) { m_worldIndexBuffer.Destroy(); m_worldVertexBuffer.Destroy(); m_worldVertexLayout.Destroy(); m_screenIndexBuffer.Destroy(); m_screenVertexBuffer.Destroy(); m_screenVertexLayout.Destroy(); m_batchShader.Destroy(); m_blankTexture.Destroy(); m_isValid = false; } } void Renderer::ProcessResize() { const UVec2 windowSize = m_window->GetDrawableSize(); m_virtualScale = Vec2{ static_cast<f32>(windowSize.x) / static_cast<f32>(m_virtualSize.x), static_cast<f32>(windowSize.y) / static_cast<f32>(m_virtualSize.y), }; const auto [viewportTopLeft, viewportSize] = GetViewportRect(); glViewport( static_cast<i32>(viewportTopLeft.x), static_cast<i32>(viewportTopLeft.y), static_cast<i32>(viewportSize.x), static_cast<i32>(viewportSize.y) ); glScissor( static_cast<i32>(viewportTopLeft.x), static_cast<i32>(viewportTopLeft.y), static_cast<i32>(viewportSize.x), static_cast<i32>(viewportSize.y) ); } void Renderer::SetVirtualSize(const UVec2& virtualSize) { m_virtualSize = virtualSize; m_virtualAspectRatio = static_cast<f32>(m_virtualSize.x) / static_cast<f32>(m_virtualSize.y); UpdateScreenProjectionMatrix(); ProcessResize(); } void Renderer::SetPolygonMode(const PolygonMode polygonMode) const { glPolygonMode(GL_FRONT_AND_BACK, static_cast<GLenum>(polygonMode)); } void Renderer::SetClearColour(const Colour& colour) const { glClearColor( static_cast<f32>(colour.red / 255.0f), static_cast<f32>(colour.green / 255.0f), static_cast<f32>(colour.blue / 255.0f), static_cast<f32>(colour.alpha / 255.0f) ); } void Renderer::Clear() const { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Renderer::BeginFrame() { BeginWorldBatch(); BeginScreenBatch(); } void Renderer::EndFrame(const Camera2D& camera) { EndWorldBatch(); FlushWorldBatch(camera); EndScreenBatch(); FlushScreenBatch(); } void Renderer::NewWorldBatch(const Camera2D& camera) { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } void Renderer::NewScreenBatch() { EndScreenBatch(); FlushScreenBatch(); BeginScreenBatch(); } void Renderer::DrawWorldRect(const components::Transform& transform, const Colour& colour, const Camera2D& camera) { if (m_worldIndexCount >= s_MaxIndicesPerBatch) [[unlikely]] { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } const Mat4 modelMatrix = CreateWorldModelMatrix(transform.position, transform.scale, transform.rotation, transform.pivot); const f32 textureIndex = static_cast<f32>(s_BlankTextureSlot); GenerateRect(modelMatrix, colour, { Vec2Zero, Vec2One }, textureIndex, m_worldQuadBufferPtr, m_worldIndexCount); } void Renderer::DrawWorldRect(const components::Transform& transform, const components::ShearTransform& shear, const Colour& colour, const Camera2D& camera) { if (m_worldIndexCount >= s_MaxIndicesPerBatch) [[unlikely]] { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } const Mat4 modelMatrix = CreateWorldModelMatrix(transform.position, transform.scale, transform.rotation, transform.pivot, Vec2{ shear.xShear, shear.yShear }); const f32 textureIndex = static_cast<f32>(s_BlankTextureSlot); GenerateRect(modelMatrix, colour, { Vec2Zero, Vec2One }, textureIndex, m_worldQuadBufferPtr, m_worldIndexCount); } void Renderer::DrawWorldRect(const components::Transform& transform, const components::Sprite& sprite, const Camera2D& camera) { if (m_worldIndexCount >= s_MaxIndicesPerBatch || m_worldTextureSlotIndex > m_maxTextureUnits - 1u) [[unlikely]] { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } const Mat4 modelMatrix = CreateWorldModelMatrix(transform.position, transform.scale, transform.rotation, transform.pivot); f32 textureIndex = 0.0f; for (usize i = 0u; i < m_worldTextureSlotIndex; ++i) { if (m_worldTextureSlots[i] == sprite.texture) { textureIndex = static_cast<f32>(i); } } if (textureIndex == 0.0f) { textureIndex = static_cast<f32>(m_worldTextureSlotIndex); m_worldTextureSlots[m_worldTextureSlotIndex] = sprite.texture; ++m_worldTextureSlotIndex; } const TextureCoordinatePair textureCoordinates{ sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().first : Vec2Zero, sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().second : Vec2One, }; GenerateRect(modelMatrix, sprite.colourMod, textureCoordinates, textureIndex, m_worldQuadBufferPtr, m_worldIndexCount); } void Renderer::DrawWorldRect(const components::Transform& transform, const components::ShearTransform& shear, const components::Sprite& sprite, const Camera2D& camera) { if (m_worldIndexCount >= s_MaxIndicesPerBatch || m_worldTextureSlotIndex > m_maxTextureUnits - 1u) [[unlikely]] { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } const Mat4 modelMatrix = CreateWorldModelMatrix(transform.position, transform.scale, transform.rotation, transform.pivot, Vec2{ shear.xShear, shear.yShear }); f32 textureIndex = 0.0f; for (usize i = 0u; i < m_worldTextureSlotIndex; ++i) { if (m_worldTextureSlots[i] == sprite.texture) { textureIndex = static_cast<f32>(i); } } if (textureIndex == 0.0f) { textureIndex = static_cast<f32>(m_worldTextureSlotIndex); m_worldTextureSlots[m_worldTextureSlotIndex] = sprite.texture; ++m_worldTextureSlotIndex; } const TextureCoordinatePair textureCoordinates{ sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().first : Vec2Zero, sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().second : Vec2One, }; GenerateRect(modelMatrix, sprite.colourMod, textureCoordinates, textureIndex, m_worldQuadBufferPtr, m_worldIndexCount); } void Renderer::DrawWorldQuad(const Quad& quad, const components::Transform& transform, const Colour& colour, const Camera2D& camera) { if (m_worldIndexCount >= s_MaxIndicesPerBatch) [[unlikely]] { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } const Mat4 modelMatrix = CreateWorldModelMatrix(transform.position, transform.scale, transform.rotation, transform.pivot); const f32 textureIndex = static_cast<f32>(s_BlankTextureSlot); GenerateQuad(quad, modelMatrix, colour, { Vec2Zero, Vec2One }, textureIndex, m_worldQuadBufferPtr, m_worldIndexCount); } void Renderer::DrawWorldQuad(const Quad& quad, const components::Transform& transform, const components::ShearTransform& shear, const Colour& colour, const Camera2D& camera) { if (m_worldIndexCount >= s_MaxIndicesPerBatch) [[unlikely]] { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } const Mat4 modelMatrix = CreateWorldModelMatrix(transform.position, transform.scale, transform.rotation, transform.pivot, Vec2{ shear.xShear, shear.yShear }); const f32 textureIndex = static_cast<f32>(s_BlankTextureSlot); GenerateQuad(quad, modelMatrix, colour, { Vec2Zero, Vec2One }, textureIndex, m_worldQuadBufferPtr, m_worldIndexCount); } void Renderer::DrawWorldQuad(const Quad& quad, const components::Transform& transform, const components::Sprite& sprite, const Camera2D& camera) { if (m_worldIndexCount >= s_MaxIndicesPerBatch || m_worldTextureSlotIndex > m_maxTextureUnits - 1u) [[unlikely]] { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } const Mat4 modelMatrix = CreateWorldModelMatrix(transform.position, transform.scale, transform.rotation, transform.pivot); f32 textureIndex = 0.0f; for (usize i = 0u; i < m_worldTextureSlotIndex; ++i) { if (m_worldTextureSlots[i] == sprite.texture) { textureIndex = static_cast<f32>(i); } } if (textureIndex == 0.0f) { textureIndex = static_cast<f32>(m_worldTextureSlotIndex); m_worldTextureSlots[m_worldTextureSlotIndex] = sprite.texture; ++m_worldTextureSlotIndex; } const TextureCoordinatePair textureCoordinates{ sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().first : Vec2Zero, sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().second : Vec2One, }; GenerateQuad(quad, modelMatrix, sprite.colourMod, textureCoordinates, textureIndex, m_worldQuadBufferPtr, m_worldIndexCount); } void Renderer::DrawWorldQuad(const Quad& quad, const components::Transform& transform, const components::ShearTransform& shear, const components::Sprite& sprite, const Camera2D& camera) { if (m_worldIndexCount >= s_MaxIndicesPerBatch || m_worldTextureSlotIndex > m_maxTextureUnits - 1u) [[unlikely]] { EndWorldBatch(); FlushWorldBatch(camera); BeginWorldBatch(); } const Mat4 modelMatrix = CreateWorldModelMatrix(transform.position, transform.scale, transform.rotation, transform.pivot, Vec2{ shear.xShear, shear.yShear }); f32 textureIndex = 0.0f; for (usize i = 0u; i < m_worldTextureSlotIndex; ++i) { if (m_worldTextureSlots[i] == sprite.texture) { textureIndex = static_cast<f32>(i); } } if (textureIndex == 0.0f) { textureIndex = static_cast<f32>(m_worldTextureSlotIndex); m_worldTextureSlots[m_worldTextureSlotIndex] = sprite.texture; ++m_worldTextureSlotIndex; } const TextureCoordinatePair textureCoordinates{ sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().first : Vec2Zero, sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().second : Vec2One, }; GenerateQuad(quad, modelMatrix, sprite.colourMod, textureCoordinates, textureIndex, m_worldQuadBufferPtr, m_worldIndexCount); } void Renderer::DrawWorldLine(const Vec2& pointA, const Vec2& pointB, const components::Transform& transform, const Colour& colour, const Camera2D& camera) { DrawWorldQuad( Quad{ .lowerLeft = pointA, .upperLeft = pointA + (2.0f * Vec2Down / camera.GetPixelsPerUnit() / camera.GetZoom()), .upperRight = pointB, .lowerRight = pointB + (2.0f * Vec2Down / camera.GetPixelsPerUnit() / camera.GetZoom()), }, transform, colour, camera ); } void Renderer::DrawScreenRect(const components::ScreenTransform& transform, const Colour& colour) { if (m_screenIndexCount >= s_MaxIndicesPerBatch) [[unlikely]] { EndScreenBatch(); FlushScreenBatch(); BeginScreenBatch(); } const Mat4 modelMatrix = CreateScreenModelMatrix(Vec2(transform.position), Vec2(transform.size), transform.flip, transform.rotation, transform.pivot); const f32 textureIndex = static_cast<f32>(s_BlankTextureSlot); GenerateRect(modelMatrix, colour, { Vec2Zero, Vec2One }, textureIndex, m_screenQuadBufferPtr, m_screenIndexCount); } void Renderer::DrawScreenRect(const components::ScreenTransform& transform, const components::ShearTransform& shear, const Colour& colour) { if (m_screenIndexCount >= s_MaxIndicesPerBatch) [[unlikely]] { EndScreenBatch(); FlushScreenBatch(); BeginScreenBatch(); } const Mat4 modelMatrix = CreateScreenModelMatrix(Vec2(transform.position), Vec2(transform.size), transform.flip, transform.rotation, transform.pivot, Vec2{ shear.xShear, shear.yShear }); const f32 textureIndex = static_cast<f32>(s_BlankTextureSlot); GenerateRect(modelMatrix, colour, { Vec2Zero, Vec2One }, textureIndex, m_screenQuadBufferPtr, m_screenIndexCount); } void Renderer::DrawScreenRect(const components::ScreenTransform& transform, const components::Sprite& sprite) { if (m_screenIndexCount >= s_MaxIndicesPerBatch || m_screenTextureSlotIndex > m_maxTextureUnits - 1u) [[unlikely]] { EndScreenBatch(); FlushScreenBatch(); BeginScreenBatch(); } const Mat4 modelMatrix = CreateScreenModelMatrix(Vec2(transform.position), Vec2(transform.size), transform.flip, transform.rotation, transform.pivot); f32 textureIndex = 0.0f; for (usize i = 0u; i < m_screenTextureSlotIndex; ++i) { if (m_screenTextureSlots[i] == sprite.texture) { textureIndex = static_cast<f32>(i); } } if (textureIndex == 0.0f) { textureIndex = static_cast<f32>(m_screenTextureSlotIndex); m_screenTextureSlots[m_screenTextureSlotIndex] = sprite.texture; ++m_screenTextureSlotIndex; } const TextureCoordinatePair textureCoordinates{ sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().first : Vec2Zero, sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().second : Vec2One, }; GenerateRect(modelMatrix, sprite.colourMod, textureCoordinates, textureIndex, m_screenQuadBufferPtr, m_screenIndexCount); } void Renderer::DrawScreenRect(const components::ScreenTransform& transform, const components::ShearTransform& shear, const components::Sprite& sprite) { if (m_screenIndexCount >= s_MaxIndicesPerBatch || m_screenTextureSlotIndex > m_maxTextureUnits - 1u) [[unlikely]] { EndScreenBatch(); FlushScreenBatch(); BeginScreenBatch(); } const Mat4 modelMatrix = CreateScreenModelMatrix(Vec2(transform.position), Vec2(transform.size), transform.flip, transform.rotation, transform.pivot, Vec2{ shear.xShear, shear.yShear }); f32 textureIndex = 0.0f; for (usize i = 0u; i < m_screenTextureSlotIndex; ++i) { if (m_screenTextureSlots[i] == sprite.texture) { textureIndex = static_cast<f32>(i); } } if (textureIndex == 0.0f) { textureIndex = static_cast<f32>(m_screenTextureSlotIndex); m_screenTextureSlots[m_screenTextureSlotIndex] = sprite.texture; ++m_screenTextureSlotIndex; } const TextureCoordinatePair textureCoordinates{ sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().first : Vec2Zero, sprite.subTextureArea.has_value() ? sprite.subTextureArea.value().second : Vec2One, }; GenerateRect(modelMatrix, sprite.colourMod, textureCoordinates, textureIndex, m_screenQuadBufferPtr, m_screenIndexCount); } void Renderer::EnableScissorRect(const bool enable) const { if (enable) { glEnable(GL_SCISSOR_TEST); } else { glDisable(GL_SCISSOR_TEST); } } void Renderer::SetScissorRect(const IVec2& topLeft, const UVec2& size) const { glScissor( static_cast<i32>(topLeft.x), static_cast<i32>(size.y - topLeft.y), static_cast<i32>(size.x), static_cast<i32>(size.y) ); } void Renderer::ResetScissorRect() const { const auto [viewportTopLeft, viewportSize] = GetViewportRect(); glScissor( static_cast<i32>(viewportTopLeft.x), static_cast<i32>(viewportTopLeft.y), static_cast<i32>(viewportSize.x), static_cast<i32>(viewportSize.y) ); } void Renderer::SetAntiAliasing(const bool enableAntiAliasing) const { if (enableAntiAliasing) { glEnable(GL_MULTISAMPLE); } else { glDisable(GL_MULTISAMPLE); } } [[nodiscard]] Pair<UVec2, UVec2> Renderer::GetViewportRect() const { const UVec2 windowSize = m_window->GetDrawableSize(); u32 width = windowSize.x; u32 height = static_cast<u32>(width / m_virtualAspectRatio + 0.5f); if (height > static_cast<u32>(windowSize.y)) { height = windowSize.y; width = static_cast<u32>(height * m_virtualAspectRatio + 0.5f); } const i32 viewportX = (windowSize.x / 2) - (width / 2); const i32 viewportY = (windowSize.y / 2) - (height / 2); return { Vec2{ viewportX, viewportY }, Vec2{ width, height }, }; } void Renderer::InitialiseVertexObjects() { m_worldVertexBuffer.Initialise(s_MaxVerticesPerBatch * sizeof(BatchVertex), BufferUsage::Dynamic); m_screenVertexBuffer.Initialise(s_MaxVerticesPerBatch * sizeof(BatchVertex), BufferUsage::Dynamic); m_worldVertexLayout.AddAttribute({ // Position. .elementCount = 2u, .dataType = GL_FLOAT, .isNormalised = true, }) .AddAttribute({ // Colour. .elementCount = 4u, .dataType = GL_FLOAT, .isNormalised = true, }) .AddAttribute({ // Texture coordinates. .elementCount = 2u, .dataType = GL_FLOAT, .isNormalised = true, }) .AddAttribute({ // Texture unit index. .elementCount = 1u, .dataType = GL_FLOAT, .isNormalised = true, }) .AddVertexBuffer(m_worldVertexBuffer) .Initialise(); m_screenVertexLayout.AddAttribute({ // Position. .elementCount = 2u, .dataType = GL_FLOAT, .isNormalised = true, }) .AddAttribute({ // Colour. .elementCount = 4u, .dataType = GL_FLOAT, .isNormalised = true, }) .AddAttribute({ // Texture coordinates. .elementCount = 2u, .dataType = GL_FLOAT, .isNormalised = true, }) .AddAttribute({ // Texture unit index. .elementCount = 1u, .dataType = GL_FLOAT, .isNormalised = true, }) .AddVertexBuffer(m_screenVertexBuffer) .Initialise(); Vector<u32> indices(s_MaxIndicesPerBatch); u32 offset = 0u; for (usize i = 0u; i < s_MaxIndicesPerBatch; i += 6u) { indices[i + 0u] = 0u + offset; indices[i + 1u] = 1u + offset; indices[i + 2u] = 2u + offset; indices[i + 3u] = 2u + offset; indices[i + 4u] = 3u + offset; indices[i + 5u] = 0u + offset; offset += 4u; } m_worldIndexBuffer.Initialise(indices); m_screenIndexBuffer.Initialise(indices); } void Renderer::InitialiseShaders() { const Shader batchVertexShader(Shader::Type::Vertex, "assets/shaders/quad_batch.vert"); const Shader batchFragmentShader(Shader::Type::Fragment, "assets/shaders/quad_batch.frag"); m_batchShader.Initialise({ &batchVertexShader, &batchFragmentShader, }); } void Renderer::InitialiseTextureIndices() { constexpr usize MaxSupportedTextureUnits = 32u; i32 maxTextureUnits = 0; glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits); m_maxTextureUnits = std::min(static_cast<usize>(maxTextureUnits), MaxSupportedTextureUnits); m_worldTextureSlots.resize(m_maxTextureUnits); m_screenTextureSlots.resize(m_maxTextureUnits); m_worldTextureSlots[s_BlankTextureSlot] = &m_blankTexture; m_screenTextureSlots[s_BlankTextureSlot] = &m_blankTexture; for (usize i = 1u; i < m_maxTextureUnits; ++i) { m_worldTextureSlots[i] = 0u; m_screenTextureSlots[i] = 0u; } Vector<i32> textureIndices(m_maxTextureUnits); std::iota(std::begin(textureIndices), std::end(textureIndices), 0); m_batchShader.Use(); m_batchShader.SetUniformVector("u_Textures", textureIndices); m_batchShader.Disuse(); } void Renderer::BeginWorldBatch() { m_worldQuadBufferPtr = m_worldQuadBuffer.data(); } void Renderer::EndWorldBatch() { const isize batchSize = m_worldQuadBufferPtr - m_worldQuadBuffer.data(); m_worldVertexBuffer.SetSubData(m_worldQuadBuffer, static_cast<usize>(batchSize)); } void Renderer::FlushWorldBatch(const Camera2D& camera) { for (usize i = 0u; i < m_worldTextureSlotIndex; ++i) { if (m_worldTextureSlots[i] != nullptr) [[likely]] { m_worldTextureSlots[i]->Bind(static_cast<i32>(i)); } } m_batchShader.Use(); m_batchShader.SetUniform("u_ViewProjection", camera.GetProjectionMatrix() * camera.GetViewMatrix()); m_worldVertexLayout.Bind(); m_worldVertexLayout.DrawIndexed(m_worldIndexBuffer, m_worldIndexCount); m_worldVertexLayout.Unbind(); m_batchShader.Disuse(); for (usize i = 0u; i < m_worldTextureSlotIndex; ++i) { if (m_worldTextureSlots[i] != nullptr) [[likely]] { m_worldTextureSlots[i]->Unbind(); } } m_worldIndexCount = 0u; m_worldTextureSlotIndex = 1u; } void Renderer::BeginScreenBatch() { m_screenQuadBufferPtr = m_screenQuadBuffer.data(); } void Renderer::EndScreenBatch() { const isize batchSize = m_screenQuadBufferPtr - m_screenQuadBuffer.data(); m_screenVertexBuffer.SetSubData(m_screenQuadBuffer, static_cast<usize>(batchSize)); } void Renderer::FlushScreenBatch() { for (usize i = 0u; i < m_screenTextureSlotIndex; ++i) { if (m_screenTextureSlots[i] != nullptr) [[likely]] { m_screenTextureSlots[i]->Bind(static_cast<i32>(i)); } } m_batchShader.Use(); m_batchShader.SetUniform("u_ViewProjection", m_screenProjectionMatrix); m_screenVertexLayout.Bind(); m_screenVertexLayout.DrawIndexed(m_screenIndexBuffer, m_screenIndexCount); m_screenVertexLayout.Unbind(); m_batchShader.Disuse(); for (usize i = 0u; i < m_screenTextureSlotIndex; ++i) { if (m_screenTextureSlots[i] != nullptr) [[likely]] { m_screenTextureSlots[i]->Unbind(); } } m_screenIndexCount = 0u; m_screenTextureSlotIndex = 1u; } [[nodiscard]] Mat4 Renderer::CreateWorldModelMatrix(const Vec2& position, const Vec2& scale, const f32 rotation, const Optional<Vec2>& pivot, const Optional<Vec2>& shear) const { Mat4 modelMatrix{ 1.0f }; modelMatrix = glm::translate(modelMatrix, Vec3(position, 0.0f)); if (pivot.has_value()) { modelMatrix = glm::translate(modelMatrix, Vec3{ pivot.value(), 0.0f }); } modelMatrix = glm::rotate(modelMatrix, -glm::radians(rotation), Vec3Forward); if (pivot.has_value()) { modelMatrix = glm::translate(modelMatrix, Vec3{ -pivot.value(), 0.0f }); } if (shear.has_value()) { modelMatrix = glm::shearY3D(modelMatrix, glm::tan(glm::radians(shear.value().x)), 0.0f); modelMatrix = glm::shearX3D(modelMatrix, glm::tan(glm::radians(shear.value().y)), 0.0f); } modelMatrix = glm::scale(modelMatrix, Vec3{ scale, 1.0f }); return modelMatrix; } [[nodiscard]] Mat4 Renderer::CreateScreenModelMatrix(const Vec2& position, const Vec2& size, const FlipType flip, const f32 rotation, const Optional<IVec2>& pivot, const Optional<Vec2>& shear) const { Mat4 modelMatrix{ 1.0f }; modelMatrix = glm::translate(modelMatrix, Vec3{ position.x + static_cast<i32>(size.x) / 2, m_virtualSize.y - position.y - static_cast<i32>(size.y) / 2, 0.0f, }); if (pivot.has_value()) { const IVec2& pivotValue = pivot.value(); modelMatrix = glm::translate(modelMatrix, Vec3{ pivotValue.x, -pivotValue.y, 0.0f }); } modelMatrix = glm::rotate(modelMatrix, -glm::radians(rotation), Vec3Forward); if (pivot.has_value()) { const IVec2& pivotValue = pivot.value(); modelMatrix = glm::translate(modelMatrix, Vec3{ -pivotValue.x, pivotValue.y, 0.0f }); } if (shear.has_value()) { modelMatrix = glm::shearY3D(modelMatrix, glm::tan(glm::radians(shear.value().x)), 0.0f); modelMatrix = glm::shearX3D(modelMatrix, glm::tan(glm::radians(shear.value().y)), 0.0f); } const Vec2 flipScale = GetScaleFromFlipType(flip); modelMatrix = glm::scale(modelMatrix, Vec3{ static_cast<f32>(size.x) * flipScale.x, static_cast<f32>(size.y) * flipScale.y, 1.0f }); return modelMatrix; } void Renderer::GenerateRect(const Mat4& modelMatrix, const Colour& colour, const TextureCoordinatePair& textureCoordinates, const f32 textureIndex, BatchVertex*& bufferPtr, u32& indexCount) { const auto& [bottomLeftTextureCoordinate, topRightTextureCoordinate] = textureCoordinates; const Vec4 colourVector = Vec4(colour); bufferPtr->position = Vec2(modelMatrix * Vec4{ -0.5f, -0.5f, 0.0f, 1.0f }); bufferPtr->colour = colourVector; bufferPtr->textureCoordinates = Vec2{ bottomLeftTextureCoordinate.x, bottomLeftTextureCoordinate.y }; bufferPtr->textureIndex = textureIndex; ++bufferPtr; bufferPtr->position = Vec2(modelMatrix * Vec4{ -0.5f, 0.5f, 0.0f, 1.0f }); bufferPtr->colour = colourVector; bufferPtr->textureCoordinates = Vec2{ bottomLeftTextureCoordinate.x, topRightTextureCoordinate.y }; bufferPtr->textureIndex = textureIndex; ++bufferPtr; bufferPtr->position = Vec2(modelMatrix * Vec4{ 0.5f, 0.5f, 0.0f, 1.0f }); bufferPtr->colour = colourVector; bufferPtr->textureCoordinates = Vec2{ topRightTextureCoordinate.x, topRightTextureCoordinate.y }; bufferPtr->textureIndex = textureIndex; ++bufferPtr; bufferPtr->position = Vec2(modelMatrix * Vec4{ 0.5f, -0.5f, 0.0f, 1.0f }); bufferPtr->colour = colourVector; bufferPtr->textureCoordinates = Vec2{ topRightTextureCoordinate.x, bottomLeftTextureCoordinate.y }; bufferPtr->textureIndex = textureIndex; ++bufferPtr; indexCount += 6u; } void Renderer::GenerateQuad(const Quad& quad, const Mat4& modelMatrix, const Colour& colour, const TextureCoordinatePair& textureCoordinates, const f32 textureIndex, BatchVertex*& bufferPtr, u32& indexCount) { const auto& [bottomLeftTextureCoordinate, topRightTextureCoordinate] = textureCoordinates; const Vec4 colourVector = Vec4(colour); bufferPtr->position = Vec2(modelMatrix * Vec4{ quad.lowerLeft.x, quad.lowerLeft.y, 0.0f, 1.0f }); bufferPtr->colour = colourVector; bufferPtr->textureCoordinates = Vec2{ bottomLeftTextureCoordinate.x, bottomLeftTextureCoordinate.y }; bufferPtr->textureIndex = textureIndex; ++bufferPtr; bufferPtr->position = Vec2(modelMatrix * Vec4{ quad.upperLeft.x, quad.upperLeft.y, 0.0f, 1.0f }); bufferPtr->colour = colourVector; bufferPtr->textureCoordinates = Vec2{ bottomLeftTextureCoordinate.x, topRightTextureCoordinate.y }; bufferPtr->textureIndex = textureIndex; ++bufferPtr; bufferPtr->position = Vec2(modelMatrix * Vec4{ quad.upperRight.x, quad.upperRight.y, 0.0f, 1.0f }); bufferPtr->colour = colourVector; bufferPtr->textureCoordinates = Vec2{ topRightTextureCoordinate.x, topRightTextureCoordinate.y }; bufferPtr->textureIndex = textureIndex; ++bufferPtr; bufferPtr->position = Vec2(modelMatrix * Vec4{ quad.lowerRight.x, quad.lowerRight.y, 0.0f, 1.0f }); bufferPtr->colour = colourVector; bufferPtr->textureCoordinates = Vec2{ topRightTextureCoordinate.x, bottomLeftTextureCoordinate.y }; bufferPtr->textureIndex = textureIndex; ++bufferPtr; indexCount += 6u; } void Renderer::UpdateScreenProjectionMatrix() { m_screenProjectionMatrix = glm::ortho( 0.0f, static_cast<f32>(m_virtualSize.x), 0.0f, static_cast<f32>(m_virtualSize.y) ); } }
35.526257
211
0.626966
[ "vector", "transform" ]
ba627fedb495e71bb50cdf777081cb74d5bdd7db
6,028
cpp
C++
cppcryptfs/dokan/MountPointManager.cpp
thesmiley1/cppcryptfs
e655b18f59bfaa9cf046208cfd04811fb4f355d7
[ "MIT" ]
null
null
null
cppcryptfs/dokan/MountPointManager.cpp
thesmiley1/cppcryptfs
e655b18f59bfaa9cf046208cfd04811fb4f355d7
[ "MIT" ]
null
null
null
cppcryptfs/dokan/MountPointManager.cpp
thesmiley1/cppcryptfs
e655b18f59bfaa9cf046208cfd04811fb4f355d7
[ "MIT" ]
null
null
null
/* cppcryptfs : user-mode cryptographic virtual overlay filesystem. Copyright (C) 2016-2019 Bailey Brown (github.com/bailey27/cppcryptfs) cppcryptfs is based on the design of gocryptfs (github.com/rfjakob/gocryptfs) The MIT License (MIT) 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 <ntstatus.h> #define WIN32_NO_STATUS #include "dokan/dokan.h" #include "cryptdokan.h" #include "cryptdokanpriv.h" #include "context/cryptcontext.h" #include "CryptThreadData.h" #include "MountPointManager.h" #include <unordered_map> #include <string> #include <crtdbg.h> using namespace std; MountPointManager::~MountPointManager() { // should have already unmounted and destroyed everything // before exiting _ASSERT(m_tdatas.empty()); } // MountPointManager becomes owner of tdata bool MountPointManager::add(const wchar_t *mountpoint, CryptThreadData* tdata) { bool res = true; try { auto res = m_tdatas.emplace(mountpoint, tdata); _ASSERT(res.second); // that it wasn't already there } catch (...) { delete tdata; res = false; } return res; } CryptThreadData *MountPointManager::get(const wchar_t *mountpoint) { wstring mpstr; if (!find(mountpoint, mpstr)) { return NULL; } auto it = m_tdatas.find(mpstr); if (it != m_tdatas.end()) { return it->second; } else { return NULL; } } bool MountPointManager::destroy(const wchar_t *mountpoint) { wstring mpstr; if (!find(mountpoint, mpstr)) { return false; } bool result = true; auto it = m_tdatas.find(mpstr); if (it != m_tdatas.end()) { delete it->second; m_tdatas.erase(it); } else { result = false; } return result; } BOOL MountPointManager::wait_and_destroy(const WCHAR* mountpoint) { wstring mpstr; if (!find(mountpoint, mpstr)) { return FALSE; } auto it = m_tdatas.find(mpstr); if (it == m_tdatas.end()) { return FALSE; } BOOL result = TRUE; DWORD wait_timeout = UNMOUNT_TIMEOUT; DWORD status = WaitForSingleObject(it->second->hThread, wait_timeout); if (status == WAIT_OBJECT_0) { result = destroy(mountpoint); } else { result = FALSE; } return result; } bool MountPointManager::unmount_all(bool wait) { for (auto it = m_tdatas.begin(); it != m_tdatas.end(); it++) { wstring wmes; if (!unmount_crypt_fs(it->first.c_str(), false, wmes)) { return false; } } bool result = true; if (wait) { result = this->wait_all_and_destroy(); } return result; } BOOL MountPointManager::wait_multiple_and_destroy(int count, HANDLE handles[], wstring mountpoints[]) { const DWORD timeout = UNMOUNT_TIMEOUT; DWORD status = WaitForMultipleObjects(count, handles, TRUE, timeout); DWORD first = WAIT_OBJECT_0; DWORD last = WAIT_OBJECT_0 + (count - 1); if (status >= first && status <= last) { for (int i = 0; i < count; i++) { destroy(mountpoints[i].c_str()); } return TRUE; } else { return FALSE; } } BOOL MountPointManager::wait_all_and_destroy() { HANDLE handles[MAXIMUM_WAIT_OBJECTS]; wstring mountpoints[MAXIMUM_WAIT_OBJECTS]; int count = 0; for (auto &it : m_tdatas) { mountpoints[count] = it.first; handles[count++] = it.second->hThread; if (count == MAXIMUM_WAIT_OBJECTS) { if (!wait_multiple_and_destroy(count, handles, mountpoints)) return FALSE; count = 0; } } if (count) return wait_multiple_and_destroy(count, handles, mountpoints); else return TRUE; } bool MountPointManager::find(const WCHAR * mountpoint, wstring & mpstr) const { auto it = m_tdatas.find(mountpoint); if (it != m_tdatas.end()) { mpstr = it->first; return true; } for (auto it = m_tdatas.begin(); it != m_tdatas.end(); it++) { if (!lstrcmpi(it->first.c_str(), mountpoint)) { mpstr = it->first; return true; } } return false; } bool MountPointManager::get_path(const WCHAR *mountpoint, wstring& path) const { wstring mpstr; if (!find(mountpoint, mpstr)) { return false; } auto it = m_tdatas.find(mpstr); if (it == m_tdatas.end()) { return false; } path = it->second->con.GetConfig()->m_basedir; // get rid of leading \\?\ for display if (!wcsncmp(path.c_str(), L"\\\\?\\", wcslen(L"\\\\?\\"))) { path = path.c_str() + wcslen(L"\\\\?\\"); } return true; } void MountPointManager::get_mount_points(vector<wstring>& mps, function<bool(const wchar_t *)> filter) const { for (auto it = m_tdatas.begin(); it != m_tdatas.end(); it++) { if (filter) { if (filter(it->first.c_str())) { mps.push_back(it->first); } } else { mps.push_back(it->first); } } } void MountPointManager::apply(function<bool(const wchar_t*mountpoint, CryptThreadData*tdata)> f) { for (auto it = m_tdatas.begin(); it != m_tdatas.end(); it++) { if (!f(it->first.c_str(), it->second)) { return; } } }
24.704918
110
0.662575
[ "vector" ]
ba63c29a72784565a775d747f9ce6df198eb3f81
20,311
cpp
C++
src/webots/gui/WbVideoRecorder.cpp
jbnunn/webots
4f07a74a0631952a7b098e99f0ab92878051e256
[ "Apache-2.0" ]
null
null
null
src/webots/gui/WbVideoRecorder.cpp
jbnunn/webots
4f07a74a0631952a7b098e99f0ab92878051e256
[ "Apache-2.0" ]
null
null
null
src/webots/gui/WbVideoRecorder.cpp
jbnunn/webots
4f07a74a0631952a7b098e99f0ab92878051e256
[ "Apache-2.0" ]
1
2020-09-25T02:01:45.000Z
2020-09-25T02:01:45.000Z
// Copyright 1996-2019 Cyberbotics 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 "WbVideoRecorder.hpp" #include "WbApplication.hpp" #include "WbFileUtil.hpp" #include "WbLog.hpp" #include "WbMainWindow.hpp" #include "WbMessageBox.hpp" #include "WbPreferences.hpp" #include "WbProject.hpp" #include "WbSimulationState.hpp" #include "WbSimulationView.hpp" #include "WbStandardPaths.hpp" #include "WbVideoRecorderDialog.hpp" #include "WbView3D.hpp" #include "WbWorld.hpp" #include "WbWorldInfo.hpp" #include "WbWrenLabelOverlay.hpp" #include <QtCore/QBuffer> #include <QtCore/QCoreApplication> #include <QtCore/QFile> #include <QtCore/QProcess> #include <QtCore/QTextStream> #include <QtCore/QThread> #include <QtGui/QDesktopServices> #include <QtGui/QImage> #include <QtGui/QImageWriter> #include <QtGui/QScreen> #include <QtWidgets/QApplication> #include <QtWidgets/QCheckBox> #include <QtWidgets/QDesktopWidget> #include <QtWidgets/QFileDialog> #ifndef _WIN32 #include <sys/stat.h> #include <sys/types.h> #endif #define EXPECTED_FRAME_STEP 40 // ms (corresponding to 25 fps) class FrameWriterThread : public QThread { public: FrameWriterThread(unsigned char *frame, const QString &fileName, const QSize &resolution, int pixelRatio, int quality) : mFileName(fileName), mResolution(resolution), mPixelRatio(pixelRatio), mQuality(quality), mSuccess(false) { const int w = mResolution.width() / mPixelRatio; const int h = mResolution.height() / mPixelRatio; mFrame = new unsigned char[4 * w * h]; WbView3D::flipAndScaleDownImageBuffer(frame, mFrame, mResolution.width(), mResolution.height(), mPixelRatio); } virtual ~FrameWriterThread() { delete[] mFrame; } void run() override { const int w = mResolution.width() / mPixelRatio; const int h = mResolution.height() / mPixelRatio; QImage img = QImage(mFrame, w, h, QImage::Format_RGB32); QImageWriter writer(mFileName); writer.setQuality(mQuality); mSuccess = writer.write(img); if (!mSuccess) { WbLog::warning( QObject::tr("Problem while saving file: '%1'").arg(QDir::toNativeSeparators(mFileName)) + "\n" + writer.errorString(), false); QString supportedFormatsLog = QObject::tr("Supported image formats:") + " "; QList<QByteArray> supportedFormats = QImageWriter::supportedImageFormats(); for (int i = 0; i < supportedFormats.size(); ++i) supportedFormatsLog.append(QString::fromUtf8(supportedFormats[i]) + " "); WbLog::info(supportedFormatsLog, false); } } bool success() const { return mSuccess; } private: unsigned char *mFrame; const QString mFileName; const QSize mResolution; const int mPixelRatio; const int mQuality; bool mSuccess; }; static const QString TEMP_FRAME_FILENAME_PREFIX = "webotsFrame_"; WbVideoRecorder *WbVideoRecorder::cInstance = NULL; WbMainWindow *WbVideoRecorder::cMainWindow = NULL; int WbVideoRecorder::cDisplayRefresh = 1; WbVideoRecorder *WbVideoRecorder::instance() { if (cInstance == NULL) cInstance = new WbVideoRecorder(); return cInstance; } WbVideoRecorder::WbVideoRecorder() : mIsGraphicFeedbackEnabled(false), mIsInitialized(false), mIsFullScreen(false), mFrameFilePrefix(TEMP_FRAME_FILENAME_PREFIX + QString::number(QCoreApplication::applicationPid()) + "_"), mLastFileNumber(-1), mScreenPixelRatio(1), mVideoQuality(0), mVideoAcceleration(1), mShowCaption(false), mMovieFPS(25.0), mSimulationView(NULL), mScriptProcess(NULL) { } WbVideoRecorder::~WbVideoRecorder() { } bool WbVideoRecorder::initRecording(WbSimulationView *view, double basicTimeStep) { // show dialog to select parameters // compute maximum slow down with the current basicTimeStep WbVideoRecorderDialog dialog(NULL, view->view3D()->size(), 1.0 / floor(EXPECTED_FRAME_STEP / basicTimeStep)); bool accept = dialog.exec(); if (!accept) { // cancel button - reject if (mIsInitialized) { // reset state disconnect(view->view3D(), &WbView3D::mainRenderingEnded, this, &WbVideoRecorder::requestSnapshotIfNeeded); disconnect(view->view3D(), &WbView3D::videoImageReady, this, &WbVideoRecorder::writeSnapshot); // enable window resize view->disableView3DFixedSize(); WbLog::info(tr("Video creation canceled.")); } return false; } // initialize recording return initRecording(view, basicTimeStep, dialog.resolution(), dialog.quality(), 0, dialog.acceleration(), dialog.showCaption()); } bool WbVideoRecorder::setMainWindowFullScreen(bool fullScreen) { bool success = false; if (fullScreen) { success = cMainWindow->setFullScreen(true, true); if (success) cMainWindow->lockFullScreen(true); } else { // first unlock, otherwise not possible // to switch to normal mode cMainWindow->lockFullScreen(false); success = cMainWindow->setFullScreen(false, true); } return success; } void WbVideoRecorder::estimateMovieInfo(double basicTimeStep) { int roundedBasicTimeStep = round(basicTimeStep); double refresh = EXPECTED_FRAME_STEP / (double)roundedBasicTimeStep; int floorRefresh = floor(refresh); int ceilRefresh = ceil(refresh); int frameStep0 = floorRefresh * roundedBasicTimeStep; int frameStep1 = ceilRefresh * roundedBasicTimeStep; if (frameStep0 == 0 || abs(frameStep0 - EXPECTED_FRAME_STEP) > abs(frameStep1 - EXPECTED_FRAME_STEP)) { mMovieFPS = 1000.0 / frameStep1; cDisplayRefresh = ceilRefresh * mVideoAcceleration; } else { mMovieFPS = 1000.0 / frameStep0; cDisplayRefresh = floorRefresh * mVideoAcceleration; } } bool WbVideoRecorder::initRecording(WbSimulationView *view, double basicTimeStep, const QSize &videoResolution, int quality, int codec, double acceleration, bool caption, const QString &filename) { cDisplayRefresh = 1; mSimulationView = view; mVideoName = filename; mIsGraphicFeedbackEnabled = filename.isEmpty(); if (mIsInitialized) { // reset state disconnect(mSimulationView->view3D(), &WbView3D::mainRenderingEnded, this, &WbVideoRecorder::requestSnapshotIfNeeded); disconnect(mSimulationView->view3D(), &WbView3D::videoImageReady, this, &WbVideoRecorder::writeSnapshot); // enable window resize mSimulationView->disableView3DFixedSize(); } // set video parameters mVideoQuality = quality; mVideoAcceleration = acceleration; mVideoResolution = videoResolution; mShowCaption = caption; if (mShowCaption) { // add caption overlay WbWrenLabelOverlay *label = WbWrenLabelOverlay::createOrRetrieve(WbWrenLabelOverlay::movieCaptionOverlayId(), WbStandardPaths::fontsPath() + "Arial.ttf"); label->setText(QString::number(mVideoAcceleration) + "x"); // the resulting label text size depends on the 3D view height // 0.227 is an empirical value so that the label "0.01x" is fully displayed label->setPosition(1.0 - (0.227 * mVideoResolution.height() / mVideoResolution.width()), 0.025); label->setSize(0.2); label->setColor(0xffffff); label->applyChangesToWren(); } // set folder where temp files are stored mTempDirPath = WbStandardPaths::webotsTmpPath(); mLastFileNumber = -1; // remove old files removeOldTempFiles(); const QDesktopWidget *qDesktop = QApplication::desktop(); const int screenNumber = qDesktop->screenNumber(QCursor::pos()); QSize fullScreen(qDesktop->screenGeometry(screenNumber).width(), qDesktop->screenGeometry(screenNumber).height()); mIsFullScreen = (mVideoResolution == fullScreen); if (mIsFullScreen) { bool success = setMainWindowFullScreen(true); if (!success) { // do not start recording removeOldTempFiles(); // enable window resize mSimulationView->disableView3DFixedSize(); // remove caption if needed if (mShowCaption) WbWrenLabelOverlay::removeLabel(WbWrenLabelOverlay::movieCaptionOverlayId()); WbLog::info(tr("Video creation canceled.")); emit videoCreationStatusChanged(WB_SUPERVISOR_MOVIE_READY); return false; } } // disable window resize while making movie mSimulationView->enableView3DFixedSize(mVideoResolution); // disable some menus while the movie is beeing created // ... // estimate movie parameters estimateMovieInfo(basicTimeStep); connect(mSimulationView->view3D(), &WbView3D::mainRenderingEnded, this, &WbVideoRecorder::requestSnapshotIfNeeded); connect(mSimulationView->view3D(), &WbView3D::videoImageReady, this, &WbVideoRecorder::writeSnapshot); mSimulationView->view3D()->initVideoPBO(); if (mIsGraphicFeedbackEnabled) WbLog::info(tr("Video recording starts when you run a simulation...")); emit videoCreationStatusChanged(WB_SUPERVISOR_MOVIE_RECORDING); mIsInitialized = true; return true; } void WbVideoRecorder::stopRecording(bool canceled) { disconnect(mSimulationView->view3D(), &WbView3D::mainRenderingEnded, this, &WbVideoRecorder::requestSnapshotIfNeeded); disconnect(mSimulationView->view3D(), &WbView3D::videoImageReady, this, &WbVideoRecorder::writeSnapshot); mSimulationView->view3D()->completeVideoPBOProcessing(canceled); // enable window resize mSimulationView->disableView3DFixedSize(); // Fullscreen if (mIsFullScreen) setMainWindowFullScreen(false); // remove caption if needed if (mShowCaption) WbWrenLabelOverlay::removeLabel(WbWrenLabelOverlay::movieCaptionOverlayId()); if (mLastFileNumber == -1 || canceled) { cancelRecording(); emit videoCreationStatusChanged(WB_SUPERVISOR_MOVIE_SIMULATION_ERROR); if (!canceled) WbMessageBox::warning("Nothing was recorded because the simulation didn't run.", cMainWindow, "Warning"); return; } emit videoCreationStatusChanged(WB_SUPERVISOR_MOVIE_SAVING); WbLog::info(tr("Creating video...")); if (mVideoName.isEmpty()) { // pause simulation before recording video WbSimulationState::Mode currentMode = WbSimulationState::instance()->mode(); if (!WbSimulationState::instance()->isPaused()) WbSimulationState::instance()->setMode(WbSimulationState::PAUSE); // ask for video name static QString videoFilter = ".mp4"; QFileInfo fi(WbWorld::instance()->fileName()); QString worldBaseName = fi.baseName(); QString proposedFilename; for (int i = 0; i < 100; ++i) { QString suffix = i == 0 ? "" : QString("_%1").arg(i); proposedFilename = WbPreferences::instance()->value("Directories/movies").toString() + worldBaseName + suffix + videoFilter; if (!QFileInfo::exists(proposedFilename)) break; } mVideoName = QFileDialog::getSaveFileName(cMainWindow, tr("Save Video"), WbProject::computeBestPathForSaveAs(proposedFilename), tr("Videos (*%1)").arg(videoFilter)); if (mVideoName.isEmpty()) { // canceled by user cancelRecording(); // reset simulation mode WbSimulationState::instance()->setMode(currentMode); return; } WbPreferences::instance()->setValue("Directories/movies", QFileInfo(mVideoName).absolutePath() + "/"); mVideoName = QDir::toNativeSeparators(mVideoName); // reset simulation mode WbSimulationState::instance()->setMode(currentMode); } createMpeg(); mIsInitialized = false; } void WbVideoRecorder::writeSnapshot(unsigned char *frame) { QString fileName = nextFileName(); FrameWriterThread *thread = new FrameWriterThread(frame, fileName, mVideoResolution * mScreenPixelRatio, mScreenPixelRatio, mVideoQuality); connect(thread, &QThread::finished, this, &WbVideoRecorder::terminateSnapshotWrite); thread->start(); } void WbVideoRecorder::terminateSnapshotWrite() { FrameWriterThread *thread = dynamic_cast<FrameWriterThread *>(sender()); if (!thread->success()) emit videoCreationStatusChanged(WB_SUPERVISOR_MOVIE_WRITE_ERROR); delete thread; } void WbVideoRecorder::requestSnapshotIfNeeded(bool fromPhysics) { if (!fromPhysics) return; // request asynchronous OpenGL pixels read mSimulationView->view3D()->requestGrabWindowBuffer(); } void WbVideoRecorder::terminateVideoCreation(int exitCode, QProcess::ExitStatus exitStatus) { // cleanup delete mScriptProcess; mScriptProcess = NULL; removeOldTempFiles(); // remove script file QFile scriptFile(mScriptPath); if (scriptFile.exists()) { bool success = scriptFile.remove(); if (!success) WbLog::warning(tr("Impossible to delete temporary file: '%1'").arg(QDir::toNativeSeparators(mScriptPath)), false); } // report exit status to user or supervisor controller if (exitCode > 0 || exitStatus == QProcess::CrashExit) { WbLog::error(tr("Video generation failed.")); emit videoCreationStatusChanged(WB_SUPERVISOR_MOVIE_ENCODING_ERROR); if (mIsGraphicFeedbackEnabled) WbMessageBox::warning(tr("Video generation failed due to an encoding problem\n"), mSimulationView, tr("Make Movie")); return; } QFile::remove(mVideoName); QDir().rename(mTempDirPath + "video.mp4", mVideoName); WbLog::info(tr("Video creation finished.")); emit videoCreationStatusChanged(WB_SUPERVISOR_MOVIE_READY); if (mIsGraphicFeedbackEnabled) { QCheckBox *checkBox = new QCheckBox(tr("Open containg folder and YouTube upload page.")); QMessageBox box(cMainWindow); box.setWindowTitle(tr("Make Movie")); box.setText(tr("The movie has been created:\n%1\n\nDo you want to play it back?\n").arg(mVideoName)); box.setIcon(QMessageBox::Icon::Question); box.addButton(QMessageBox::Yes); box.addButton(QMessageBox::Cancel); box.setDefaultButton(QMessageBox::Cancel); box.setCheckBox(checkBox); if (box.exec() == QMessageBox::Yes) { if (checkBox->isChecked()) { QDesktopServices::openUrl(QUrl("https://www.youtube.com/upload")); WbFileUtil::revealInFileManager(mVideoName); } QDesktopServices::openUrl(QUrl::fromLocalFile(mVideoName)); } } } void WbVideoRecorder::cancelRecording() { removeOldTempFiles(); mIsInitialized = false; WbLog::info(tr("Video creation canceled.")); } void WbVideoRecorder::readStdout() { QByteArray bytes = mScriptProcess->readAllStandardOutput(); QString out = QString::fromUtf8(bytes.data(), bytes.size()); WbLog::appendStdout(out); } void WbVideoRecorder::readStderr() { QByteArray bytes = mScriptProcess->readAllStandardError(); QString err = QString::fromUtf8(bytes.data(), bytes.size()); WbLog::appendStdout(err); // ffmpeg/avconv prints all the messages on stderr } void WbVideoRecorder::removeOldTempFiles() { QDir tempDir(mTempDirPath); if (!tempDir.exists()) { WbLog::error(tr("Temporary directory '%1' does not exist.").arg(QDir::toNativeSeparators(mTempDirPath)), false); return; } // remove all files starting with selected prefix QStringList nameFilters; nameFilters.append(mFrameFilePrefix + "*"); QStringList tempFiles = tempDir.entryList(nameFilters); foreach (QString file, tempFiles) { bool success = tempDir.remove(file); if (!success) { WbLog::warning(tr("Impossible to delete temporary file: '%1'").arg(QDir::toNativeSeparators(file.toUtf8())), false); } } } QString WbVideoRecorder::nextFileName() { mLastFileNumber++; return mTempDirPath + mFrameFilePrefix + QString().sprintf("%06d", mLastFileNumber) + ".jpg"; } void WbVideoRecorder::createMpeg() { #ifdef __linux__ static const QString ffmpeg("ffmpeg"); static const QString percentageChar = "%"; mScriptPath = "ffmpeg_script.sh"; #elif defined(__APPLE__) static const QString ffmpeg(QString("\"%1util/ffmpeg\"").arg(WbStandardPaths::webotsHomePath())); static const QString percentageChar = "%"; mScriptPath = "ffmpeg_script.sh"; #else // _WIN32 static const QString ffmpeg = "ffmpeg.exe"; static const QString percentageChar = "%%"; mScriptPath = "ffmpeg_script.bat"; #endif const QString initialDir = QDir::currentPath(); QDir::setCurrent(mTempDirPath); // for MPEG-4: requires ffmpeg / avconv (installed on Linux, distributed on Win32 and Mac) QFile ffmpegScript(mScriptPath); if (ffmpegScript.open(QIODevice::WriteOnly)) { // bitrate range between 4 and 24000000 // cast into 'long long int' is mandatory on 32-bit machine long long int bitrate = (long long int)mVideoQuality * mMovieFPS * mVideoResolution.width() * mVideoResolution.height() / 256 / (mScreenPixelRatio * mScreenPixelRatio); QTextStream stream(&ffmpegScript); #ifndef _WIN32 stream << "#!/bin/sh\n"; static const QString openParenthesis = "\\("; static const QString closeParenthesis = "\\)"; #else stream << "@echo off\n"; static const QString openParenthesis = "("; static const QString closeParenthesis = ")"; #endif stream << "echo " + tr("Recording at %1 FPS, %2 bit/s.").arg(mMovieFPS).arg(bitrate) + "\n"; stream << "echo " + tr("Video encoding stage 1... ") + openParenthesis + tr("please wait") + closeParenthesis + "\n"; stream << ffmpeg << " -loglevel warning -y -f image2 -r " << (float)mMovieFPS << " -i \"" << mFrameFilePrefix << percentageChar << "06d.jpg\" -b:v " << bitrate; stream << " -vcodec libx264 -pass 1 -g 132 -an -pix_fmt yuvj420p video.mp4\n"; #ifdef _WIN32 stream << "IF ERRORLEVEL 1 Exit 1\n"; #else stream << "rc=$?\n"; stream << "if [ $rc != 0 ] ; then\n"; stream << " exit 1\n"; stream << "fi\n"; #endif stream << "echo " + tr("Video encoding stage 2... ") + openParenthesis + tr("please wait") + closeParenthesis + "\n"; stream << ffmpeg << " -loglevel warning -y -f image2 -r " << (float)mMovieFPS << " -i \"" << mFrameFilePrefix << percentageChar << "06d.jpg\" -b:v " << bitrate; stream << " -vcodec libx264 -pass 2 -g 132 -an -pix_fmt yuvj420p video.mp4\n"; #ifdef _WIN32 stream << "IF ERRORLEVEL 1 Exit 1\n"; #else stream << "rc=$?\n"; stream << "if [ $rc != 0 ] ; then\n"; stream << " exit 1\n"; stream << "fi\n"; #endif // at the end remove log files #ifdef _WIN32 stream << "del ffmpeg2pass-0.log\n"; stream << "del ffmpeg2pass-0.log.mbtree\n"; stream << "Exit 0\n"; #else // __APPLE__ and __linux__ stream << "rm -f *2pass-0.log*\n"; stream << "exit 0\n"; #endif stream << "echo Video Encoding complete.\n"; // close file ffmpegScript.close(); // change file properties QFile::setPermissions(mScriptPath, QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup | QFile::ReadOther | QFile::WriteOther | QFile::ExeOther); // run script QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("AV_LOG_FORCE_COLOR", "1"); // force output message to use ANSI Escape sequences mScriptProcess = new QProcess(); mScriptProcess->setProcessEnvironment(env); mScriptProcess->start("./" + mScriptPath); connect(mScriptProcess, (void (QProcess::*)(int, QProcess::ExitStatus)) & QProcess::finished, this, &WbVideoRecorder::terminateVideoCreation); connect(mScriptProcess, &QProcess::readyReadStandardOutput, this, &WbVideoRecorder::readStdout); connect(mScriptProcess, &QProcess::readyReadStandardError, this, &WbVideoRecorder::readStderr); } else { WbLog::error(tr("Impossible to write file: '%1'.").arg(mScriptPath) + "\n" + tr("Video generation failed."), mIsGraphicFeedbackEnabled); emit videoCreationStatusChanged(WB_SUPERVISOR_MOVIE_WRITE_ERROR); } QDir::setCurrent(initialDir); }
36.140569
126
0.70351
[ "3d" ]
ba64ef807847a8da93df175ee79e9132376fba9e
718
cpp
C++
1201-1300/1297-Maximum Number of Occurrences of a Substring/1297-Maximum Number of Occurrences of a Substring.cpp
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
1201-1300/1297-Maximum Number of Occurrences of a Substring/1297-Maximum Number of Occurrences of a Substring.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
1201-1300/1297-Maximum Number of Occurrences of a Substring/1297-Maximum Number of Occurrences of a Substring.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: int maxFreq(string s, int maxLetters, int minSize, int maxSize) { vector<int> table(26); unordered_map<string, int> count; int letter = 0, start = 0, maxCount = 0; for (int i = 0; i < s.size(); ++i) { if (++table[s[i] - 'a'] == 1) { ++letter; } if (i - start + 1 > minSize) { if (--table[s[start++] - 'a'] == 0) { --letter; } } if (i - start + 1 == minSize && letter <= maxLetters) { maxCount = max(maxCount, ++count[s.substr(start, minSize)]); } } return maxCount; } };
28.72
76
0.410864
[ "vector" ]
ba6f6f089a3fae1c2d69847e22f226b661015be5
18,765
cpp
C++
src/multiview_geometry/sfm_inc.cpp
bo-rc/3dv_tutorial
23189f66aba5c296f16e9902a88d62c3cc932f20
[ "Beerware" ]
791
2017-02-08T16:55:24.000Z
2022-02-11T06:03:05.000Z
src/multiview_geometry/sfm_inc.cpp
bo-rc/3dv_tutorial
23189f66aba5c296f16e9902a88d62c3cc932f20
[ "Beerware" ]
7
2017-04-16T17:45:41.000Z
2021-11-21T16:56:55.000Z
src/multiview_geometry/sfm_inc.cpp
bo-rc/3dv_tutorial
23189f66aba5c296f16e9902a88d62c3cc932f20
[ "Beerware" ]
204
2017-02-08T10:22:21.000Z
2022-01-27T05:06:20.000Z
#include "sfm.hpp" #include <unordered_set> cv::Mat getCameraMat(const SFM::Vec9d& camera) { const double &f = camera[6], &cx = camera[7], &cy = camera[8]; cv::Mat K = (cv::Mat_<double>(3, 3) << f, 0, cx, 0, f, cy, 0, 0, 1); return K; } cv::Mat getProjectionMat(const SFM::Vec9d& camera) { cv::Mat K = getCameraMat(camera); cv::Mat rvec = (cv::Mat_<double>(3, 1) << camera[0], camera[1], camera[2]), R, Rt; cv::Mat t = (cv::Mat_<double>(3, 1) << camera[3], camera[4], camera[5]); cv::Rodrigues(rvec, R); cv::hconcat(R, t, Rt); return K * Rt; } void updateCameraPose(SFM::Vec9d& camera, const cv::Mat& R, const cv::Mat& t) { cv::Mat rvec = R.clone(); if (rvec.cols == 3 && rvec.rows == 3) cv::Rodrigues(rvec, rvec); camera[0] = rvec.at<double>(0); camera[1] = rvec.at<double>(1); camera[2] = rvec.at<double>(2); camera[3] = t.at<double>(0); camera[4] = t.at<double>(1); camera[5] = t.at<double>(2); } bool isBadPoint(const cv::Point3d& X, const SFM::Vec9d& camera1, const SFM::Vec9d& camera2, double Z_limit, double max_cos_parallax) { if (X.z < -Z_limit || X.z > Z_limit) return true; // BAD! If the point is too far from the origin. cv::Vec3d rvec1(camera1[0], camera1[1], camera1[2]), rvec2(camera2[0], camera2[1], camera2[2]); cv::Matx33d R1, R2; cv::Rodrigues(rvec1, R1); cv::Rodrigues(rvec2, R2); cv::Point3d t1(camera1[3], camera1[4], camera1[5]), t2(camera2[3], camera2[4], camera2[5]); cv::Point3d p1 = R1 * X + t1; // A 3D point w.r.t. the 1st camera coordinate cv::Point3d p2 = R2 * X + t2; // A 3D point w.r.t. the 2nd camera coordinate if (p1.z <= 0 || p2.z <= 0) return true; // BAD! If the point is beyond of one of 1st and 2nd cameras. cv::Point3d v2 = R1 * R2.t() * p2; // A 3D vector 'p2' w.r.t. the 1st camera coordinate double cos_parallax = p1.dot(v2) / cv::norm(p1) / cv::norm(v2); if (cos_parallax > max_cos_parallax) return true; // BAD! If the point has small parallax angle. return false; } int main() { const char* input = "data/relief/%02d.jpg"; double img_resize = 0.25, f_init = 500, cx_init = -1, cy_init = -1, Z_limit = 100, max_cos_parallax = cos(10 * CV_PI / 180), ba_loss_width = 9; // Negative 'loss_width' makes BA not to use a loss function. int min_inlier_num = 200, ba_num_iter = 200; // Negative 'ba_num_iter' uses the default value for BA minimization bool show_match = false; // Load images and extract features cv::VideoCapture video; if (!video.open(input)) return -1; cv::Ptr<cv::FeatureDetector> fdetector = cv::BRISK::create(); std::vector<std::vector<cv::KeyPoint>> img_keypoint; std::vector<cv::Mat> img_set, img_descriptor; while (true) { cv::Mat image; video >> image; if (image.empty()) break; if (img_resize != 1) cv::resize(image, image, cv::Size(), img_resize, img_resize); std::vector<cv::KeyPoint> keypoint; cv::Mat descriptor; fdetector->detectAndCompute(image, cv::Mat(), keypoint, descriptor); img_set.push_back(image); img_keypoint.push_back(keypoint); img_descriptor.push_back(descriptor.clone()); } if (img_set.size() < 2) return -1; if (cx_init < 0) cx_init = img_set.front().cols / 2; if (cy_init < 0) cy_init = img_set.front().rows / 2; // Match features and find good matches cv::Ptr<cv::DescriptorMatcher> fmatcher = cv::DescriptorMatcher::create("BruteForce-Hamming"); std::vector<std::pair<uint, uint>> match_pair; // Good matches (image pairs) std::vector<std::vector<cv::DMatch>> match_inlier; // Good matches (inlier feature matches) for (size_t i = 0; i < img_set.size(); i++) { for (size_t j = i + 1; j < img_set.size(); j++) { // Match features of two image pair (i, j) and find their inliers std::vector<cv::DMatch> match, inlier; fmatcher->match(img_descriptor[i], img_descriptor[j], match); std::vector<cv::Point2d> src, dst; for (auto itr = match.begin(); itr != match.end(); itr++) { src.push_back(img_keypoint[i][itr->queryIdx].pt); dst.push_back(img_keypoint[j][itr->trainIdx].pt); } cv::Mat inlier_mask; cv::findFundamentalMat(src, dst, inlier_mask, cv::RANSAC); for (int k = 0; k < inlier_mask.rows; k++) if (inlier_mask.at<uchar>(k)) inlier.push_back(match[k]); printf("3DV Tutorial: Image %zd - %zd are matched (%zd / %zd).\n", i, j, inlier.size(), match.size()); // Determine whether the image pair is good or not if (inlier.size() < min_inlier_num) continue; printf("3DV Tutorial: Image %zd - %zd are selected.\n", i, j); match_pair.push_back(std::make_pair(uint(i), uint(j))); match_inlier.push_back(inlier); if (show_match) { cv::Mat match_image; cv::drawMatches(img_set[i], img_keypoint[i], img_set[j], img_keypoint[j], match, match_image, cv::Scalar::all(-1), cv::Scalar::all(-1), inlier_mask); cv::imshow("3DV Tutorial: Structure-from-Motion", match_image); cv::waitKey(); } } } if (match_pair.size() < 1) return -1; // Initialize cameras (rotation, translation, intrinsic parameters) std::vector<SFM::Vec9d> cameras(img_set.size(), SFM::Vec9d(0, 0, 0, 0, 0, 0, f_init, cx_init, cy_init)); uint best_pair = 0; std::vector<uint> best_score(match_inlier.size()); for (size_t i = 0; i < match_inlier.size(); i++) best_score[i] = uint(match_inlier[i].size()); cv::Mat best_Xs; while (true) { // 1) Select the best pair for (size_t i = 0; i < best_score.size(); i++) if (best_score[i] > best_score[best_pair]) best_pair = uint(i); if (best_score[best_pair] == 0) { printf("3DV Tutorial: There is no good match. Try again after reducing 'max_cos_parallax'.\n"); return -1; } const uint best_cam0 = match_pair[best_pair].first, best_cam1 = match_pair[best_pair].second;; // 2) Estimate relative pose from the best two views (epipolar geometry) std::vector<cv::Point2d> src, dst; for (auto itr = match_inlier[best_pair].begin(); itr != match_inlier[best_pair].end(); itr++) { src.push_back(img_keypoint[best_cam0][itr->queryIdx].pt); dst.push_back(img_keypoint[best_cam1][itr->trainIdx].pt); } cv::Mat K = getCameraMat(cameras[best_cam0]), R, t, inlier_mask; cv::Mat E = cv::findEssentialMat(src, dst, K, cv::RANSAC, 0.999, 1, inlier_mask); cv::recoverPose(E, src, dst, K, R, t, inlier_mask); for (int r = inlier_mask.rows - 1; r >= 0; r--) { if (!inlier_mask.at<uchar>(r)) { // Remove additionally detected outliers src.erase(src.begin() + r); dst.erase(dst.begin() + r); match_inlier[best_pair].erase(match_inlier[best_pair].begin() + r); } } updateCameraPose(cameras[best_cam1], R, t); // 3) Reconstruct 3D points of the best two views (triangulation) cv::Mat P0 = getProjectionMat(cameras[best_cam0]), P1 = getProjectionMat(cameras[best_cam1]); cv::triangulatePoints(P0, P1, src, dst, best_Xs); best_Xs.row(0) = best_Xs.row(0) / best_Xs.row(3); best_Xs.row(1) = best_Xs.row(1) / best_Xs.row(3); best_Xs.row(2) = best_Xs.row(2) / best_Xs.row(3); best_score[best_pair] = 0; for (int i = 0; i < best_Xs.cols; i++) { cv::Point3d p(best_Xs.col(i).rowRange(0, 3)); // A 3D point at 'idx' if (isBadPoint(p, cameras[best_cam0], cameras[best_cam1], Z_limit, max_cos_parallax)) continue; // Do not add if it is bad best_score[best_pair]++; } printf("3DV Tutorial: Image %u - %u were checked as the best match (# of inliers = %zd, # of good points = %d).\n", best_cam0, best_cam1, match_inlier[best_pair].size(), best_score[best_pair]); if (best_score[best_pair] > 100) break; best_score[best_pair] = 0; } // End of the 1st 'while (true)' const uint best_cam0 = match_pair[best_pair].first, best_cam1 = match_pair[best_pair].second;; // Prepare the initial 3D points std::vector<cv::Point3d> Xs; Xs.reserve(10000); // Allocate memory in advance not to break pointer access in Ceres Solver std::vector<cv::Vec3b> Xs_rgb; SFM::VisibilityGraph xs_visited; for (int i = 0; i < best_Xs.cols; i++) { cv::Point3d p(best_Xs.col(i).rowRange(0, 3)); // A 3D point at 'idx' if (isBadPoint(p, cameras[best_cam0], cameras[best_cam1], Z_limit, max_cos_parallax)) continue; // Do not add if it is bad uint X_idx = uint(Xs.size()), x0_idx = match_inlier[best_pair][i].queryIdx, x1_idx = match_inlier[best_pair][i].trainIdx; Xs.push_back(p); Xs_rgb.push_back(img_set[best_cam0].at<cv::Vec3b>(img_keypoint[best_cam0][x0_idx].pt)); xs_visited[SFM::genKey(best_cam0, x0_idx)] = X_idx; xs_visited[SFM::genKey(best_cam1, x1_idx)] = X_idx; } std::unordered_set<uint> img_added; img_added.insert(best_cam0); img_added.insert(best_cam1); printf("3DV Tutorial: Image %d - %d are complete (# of 3D points = %zd).\n", best_cam0, best_cam1, Xs.size()); // Prepare bundle adjustment ceres::Problem ba; for (auto visit = xs_visited.begin(); visit != xs_visited.end(); visit++) { int cam_idx = SFM::getCamIdx(visit->first), x_idx = SFM::getObsIdx(visit->first); const cv::Point2d& x = img_keypoint[cam_idx][x_idx].pt; SFM::addCostFunc6DOF(ba, Xs[visit->second], x, cameras[cam_idx], ba_loss_width); } ceres::Solver::Options options; options.linear_solver_type = ceres::ITERATIVE_SCHUR; if (ba_num_iter > 0) options.max_num_iterations = ba_num_iter; options.num_threads = 8; options.minimizer_progress_to_stdout = true; ceres::Solver::Summary summary; while (true) { // 4) Select the next image to add std::vector<uint> img_score(img_set.size(), 0); std::vector<std::vector<uint>> match_table(img_set.size()); for (size_t img = 0; img < img_score.size(); img++) { if (img_added.find(uint(img)) == img_added.end()) // When the image is not added to the viewing graph { for (size_t i = 0; i < match_pair.size(); i++) { if (match_pair[i].first == img && img_added.find(match_pair[i].second) != img_added.end()) // When 'first' is the current image and 'second' is already added { for (auto itr = match_inlier[i].begin(); itr != match_inlier[i].end(); itr++) if (xs_visited.find(SFM::genKey(match_pair[i].second, itr->trainIdx)) != xs_visited.end()) // When a matched inlier is in 'Xs', the current image gains more score img_score[img]++; match_table[img].push_back(uint(i)); } else if (match_pair[i].second == img && img_added.find(match_pair[i].first) != img_added.end()) // When 'second' is the current image and 'first' is already added { for (auto itr = match_inlier[i].begin(); itr != match_inlier[i].end(); itr++) if (xs_visited.find(SFM::genKey(match_pair[i].first, itr->queryIdx)) != xs_visited.end()) // When a matched inlier is in 'Xs', the current image gains more score img_score[img]++; match_table[img].push_back(uint(i)); } } } } const auto next_score = std::max_element(img_score.begin(), img_score.end()); const uint next_cam = static_cast<uint>(std::distance(img_score.begin(), next_score)); const std::vector<uint> next_match = match_table[next_cam]; if (next_match.empty()) break; // Separate points into known (pts_*) and unknown (new_*) for PnP (known) and triangulation (unknown) std::vector<cv::Point3d> pts_3d; std::vector<cv::Point2d> pts_2d; std::vector<uint> pts_key, pts_idx, new_pair_cam; std::vector<std::vector<cv::Point2d>> new_next_2d(next_match.size()), new_pair_2d(next_match.size()); std::vector<std::vector<uint>> new_next_key(next_match.size()), new_pair_key(next_match.size()); for (size_t i = 0; i < next_match.size(); i++) { bool next_is_first = true; int pair_cam = match_pair[next_match[i]].second; if (pair_cam == next_cam) { next_is_first = false; pair_cam = match_pair[next_match[i]].first; } new_pair_cam.push_back(pair_cam); for (auto itr = match_inlier[next_match[i]].begin(); itr != match_inlier[next_match[i]].end(); itr++) { int next_idx = itr->queryIdx, pair_idx = itr->trainIdx; if (!next_is_first) { next_idx = itr->trainIdx; pair_idx = itr->queryIdx; } auto found = xs_visited.find(SFM::genKey(pair_cam, pair_idx)); if (found != xs_visited.end()) // When the matched point is already known (--> PnP) { pts_3d.push_back(Xs[found->second]); pts_2d.push_back(img_keypoint[next_cam][next_idx].pt); pts_key.push_back(SFM::genKey(next_cam, next_idx)); pts_idx.push_back(found->second); } else // When the matched point is newly observed (--> triangulation) { new_next_2d[i].push_back(img_keypoint[next_cam][next_idx].pt); new_pair_2d[i].push_back(img_keypoint[pair_cam][pair_idx].pt); new_next_key[i].push_back(SFM::genKey(next_cam, next_idx)); new_pair_key[i].push_back(SFM::genKey(pair_cam, pair_idx)); } } } // 5) Estimate relative pose of the next view (PnP) if (pts_3d.size() < 10) { printf("3DV Tutorial: Image %d is ignored (due to the small number of points).\n", next_cam); img_added.insert(next_cam); continue; } cv::Mat K = getCameraMat(cameras[next_cam]), rvec, t; std::vector<int> inlier_idx; cv::solvePnPRansac(pts_3d, pts_2d, K, cv::Mat::zeros(5, 1, CV_64F), rvec, t, false, 100, 4.0, 0.999, inlier_idx); updateCameraPose(cameras[next_cam], rvec, t); for (size_t i = 0; i < pts_key.size(); i++) { SFM::addCostFunc6DOF(ba, Xs[pts_idx[i]], pts_2d[i], cameras[next_cam], ba_loss_width); xs_visited[pts_key[i]] = pts_idx[i]; } // 6) Reconstruct newly observed 3D points (triangulation) uint new_pts_total = 0; for (auto new_pts = new_next_2d.begin(); new_pts != new_next_2d.end(); new_pts++) new_pts_total += uint(new_pts->size()); if (new_pts_total < 10) { printf("3DV Tutorial: Image %d is complete (only localization; no 3D point addition).\n", next_cam); img_added.insert(next_cam); continue; } cv::Mat P0 = getProjectionMat(cameras[next_cam]); for (size_t i = 0; i < new_pair_cam.size(); i++) { const int pair_cam = new_pair_cam[i]; cv::Mat P1 = getProjectionMat(cameras[pair_cam]), new_Xs; cv::triangulatePoints(P0, P1, new_next_2d[i], new_pair_2d[i], new_Xs); new_Xs.row(0) = new_Xs.row(0) / new_Xs.row(3); new_Xs.row(1) = new_Xs.row(1) / new_Xs.row(3); new_Xs.row(2) = new_Xs.row(2) / new_Xs.row(3); for (int j = 0; j < new_Xs.cols; j++) { cv::Point3d p(new_Xs.col(j).rowRange(0, 3)); if (isBadPoint(p, cameras[next_cam], cameras[pair_cam], Z_limit, max_cos_parallax)) continue; // Do not add if it is bad uint X_idx = uint(Xs.size()); Xs.push_back(p); Xs_rgb.push_back(img_set[next_cam].at<cv::Vec3b>(new_next_2d[i][j])); xs_visited[new_next_key[i][j]] = X_idx; xs_visited[new_pair_key[i][j]] = X_idx; } } printf("3DV Tutorial: Image %d is complete (# of 3D points = %zd).\n", next_cam, Xs.size()); // 7) Optimize camera pose and 3D points together (bundle adjustment) ceres::Solve(options, &ba, &summary); img_added.insert(next_cam); } // End of the 2nd 'while (true)' for (size_t j = 0; j < cameras.size(); j++) printf("3DV Tutorial: Camera %zd's (f, cx, cy) = (%.3f, %.1f, %.1f)\n", j, cameras[j][6], cameras[j][7], cameras[j][8]); // Store the 3D points to an XYZ file FILE* fpts = fopen("sfm_inc(point).xyz", "wt"); if (fpts == NULL) return -1; for (size_t i = 0; i < Xs.size(); i++) { if (Xs[i].z > -Z_limit && Xs[i].z < Z_limit) fprintf(fpts, "%f %f %f %d %d %d\n", Xs[i].x, Xs[i].y, Xs[i].z, Xs_rgb[i][2], Xs_rgb[i][1], Xs_rgb[i][0]); // Format: x, y, z, R, G, B } fclose(fpts); // Store the camera poses to an XYZ file FILE* fcam = fopen("sfm_inc(camera).xyz", "wt"); if (fcam == NULL) return -1; for (size_t j = 0; j < cameras.size(); j++) { cv::Vec3d rvec(cameras[j][0], cameras[j][1], cameras[j][2]), t(cameras[j][3], cameras[j][4], cameras[j][5]); cv::Matx33d R; cv::Rodrigues(rvec, R); cv::Vec3d p = -R.t() * t; fprintf(fcam, "%f %f %f %f %f %f\n", p[0], p[1], p[2], R.t()(0, 2), R.t()(1, 2), R.t()(2, 2)); // Format: x, y, z, n_x, n_y, n_z } fclose(fcam); return 0; }
50.308311
210
0.558753
[ "geometry", "vector", "3d" ]
ba729ff925c4f49c2940f1f5b25ff1f0a336934b
6,999
cpp
C++
third_party/CppAD/example/atomic_three/dynamic.cpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
third_party/CppAD/example/atomic_three/dynamic.cpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
third_party/CppAD/example/atomic_three/dynamic.cpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-19 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 atomic_three_dynamic.cpp$$ $section Atomic Functions with Dynamic Parameters: Example and Test$$ $head Purpose$$ This example demonstrates using dynamic parameters with an $cref atomic_three$$ function. $head Function$$ For this example, the atomic function $latex g : \B{R}^3 \rightarrow \B{R}^3$$ is defined by $latex g_0 (x) = x_0 * x_ 0$$, $latex g_1 (x) = x_0 * x_ 1$$, $latex g_2 (x) = x_1 * x_ 2$$. $nospell $head Start Class Definition$$ $srccode%cpp% */ # include <cppad/cppad.hpp> // CppAD include file namespace { // start empty namespace using CppAD::vector; // abbreviate CppAD::vector using vector // start definition of atomic derived class using atomic_three interface class atomic_dynamic : public CppAD::atomic_three<double> { /* %$$ $head Constructor$$ $srccode%cpp% */ public: // can use const char* name when calling this constructor atomic_dynamic(const std::string& name) : // can have more arguments CppAD::atomic_three<double>(name) // inform base class of name { } private: /* %$$ $head for_type$$ $srccode%cpp% */ // calculate type_y virtual bool for_type( const vector<double>& parameter_x , const vector<CppAD::ad_type_enum>& type_x , vector<CppAD::ad_type_enum>& type_y ) { assert( parameter_x.size() == type_x.size() ); bool ok = type_x.size() == 3; // n ok &= type_y.size() == 3; // m if( ! ok ) return false; type_y[0] = type_x[0]; type_y[1] = std::max( type_x[0], type_x[1] ); type_y[2] = std::max( type_x[1], type_x[2] ); return true; } /* %$$ $head forward$$ $srccode%cpp% */ // forward mode routine called by CppAD virtual bool forward( const vector<double>& parameter_x , const vector<CppAD::ad_type_enum>& type_x , size_t need_y , size_t order_low , size_t order_up , const vector<double>& taylor_x , vector<double>& taylor_y ) { # ifndef NDEBUG size_t n = taylor_x.size() / (order_up + 1); size_t m = taylor_y.size() / (order_up + 1); # endif assert( n == 3 ); assert( m == 3 ); assert( order_low <= order_up ); // return flag bool ok = order_up == 0; if( ! ok ) return ok; // Order zero forward mode. // This case must always be implemented if( need_y > size_t(CppAD::variable_enum) ) { // g_0 = x_0 * x_0 taylor_y[0] = taylor_x[0] * taylor_x[0]; // g_1 = x_0 * x_1 taylor_y[1] = taylor_x[0] * taylor_x[1]; // g_2 = x_1 * x_2 taylor_y[2] = taylor_x[1] * taylor_x[2]; } else { // This uses need_y to reduce amount of computation. // It is probably faster, for this case, to ignore need_y. vector<CppAD::ad_type_enum> type_y( taylor_y.size() ); for_type(taylor_x, type_x, type_y); // g_0 = x_0 * x_0 if( size_t(type_y[0]) == need_y ) taylor_y[0] = taylor_x[0] * taylor_x[0]; // g_1 = x_0 * x_1 if( size_t(type_y[1]) == need_y ) taylor_y[1] = taylor_x[0] * taylor_x[1]; // g_2 = x_1 * x_2 if( size_t(type_y[2]) == need_y ) taylor_y[2] = taylor_x[1] * taylor_x[2]; } return ok; } /* %$$ $head End Class Definition$$ $srccode%cpp% */ }; // End of atomic_dynamic class } // End empty namespace /* %$$ $head Use Atomic Function$$ $srccode%cpp% */ bool dynamic(void) { bool ok = true; using CppAD::AD; using CppAD::NearEqual; double eps = 10. * CppAD::numeric_limits<double>::epsilon(); /* %$$ $subhead Constructor$$ $srccode%cpp% */ // Create the atomic dynamic object corresponding to g(x) atomic_dynamic afun("atomic_dynamic"); /* %$$ $subhead Recording$$ $srccode%cpp% */ // Create the function f(u) = g(c, p, u) for this example. // // constant parameter double c_0 = 2.0; // // indepndent dynamic parameter vector size_t np = 1; CPPAD_TESTVECTOR(double) p(np); CPPAD_TESTVECTOR( AD<double> ) ap(np); ap[0] = p[0] = 3.0; // // independent variable vector size_t nu = 1; double u_0 = 0.5; CPPAD_TESTVECTOR( AD<double> ) au(nu); au[0] = u_0; // declare independent variables and start tape recording CppAD::Independent(au, ap); // range space vector size_t ny = 3; CPPAD_TESTVECTOR( AD<double> ) ay(ny); // call atomic function and store result in ay // y = ( c * c, c * p, p * x ) CPPAD_TESTVECTOR( AD<double> ) ax(3); ax[0] = c_0; // x_0 ax[1] = ap[0]; // x_1 ax[2] = au[0]; // x_2 afun(ax, ay); // check type of result ok &= Constant( ay[0] ); ok &= Dynamic( ay[1] ); ok &= Variable( ay[2] ); // create f: x -> y and stop tape recording CppAD::ADFun<double> f; f.Dependent (au, ay); // f(u) = (c * c, c * p, p * u) /* %$$ $subhead forward$$ $srccode%cpp% */ // check function value double check = c_0 * c_0; ok &= NearEqual( Value(ay[0]) , check, eps, eps); check = c_0 * p[0]; ok &= NearEqual( Value(ay[1]) , check, eps, eps); check = p[0] * u_0; ok &= NearEqual( Value(ay[2]) , check, eps, eps); // check zero order forward mode size_t q; CPPAD_TESTVECTOR( double ) u_q(nu), y_q(ny); q = 0; u_q[0] = u_0; y_q = f.Forward(q, u_q); check = c_0 * c_0; ok &= NearEqual(y_q[0] , check, eps, eps); check = c_0 * p[0]; ok &= NearEqual(y_q[1] , check, eps, eps); check = p[0] * u_0; ok &= NearEqual(y_q[2] , check, eps, eps); // set new value for dynamic parameters p[0] = 2.0 * p[0]; f.new_dynamic(p); y_q = f.Forward(q, u_q); check = c_0 * c_0; ok &= NearEqual(y_q[0] , check, eps, eps); check = c_0 * p[0]; ok &= NearEqual(y_q[1] , check, eps, eps); check = p[0] * u_0; ok &= NearEqual(y_q[2] , check, eps, eps); /* %$$ $subhead Return Test Result$$ $srccode%cpp% */ return ok; } /* %$$ $$ $comment end nospell$$ $end */
30.969027
79
0.540934
[ "object", "vector" ]
ba7a5c97fdb06cca684d157c373ead583416dc63
5,417
cpp
C++
EZOJ/Contests/1394/B.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
EZOJ/Contests/1394/B.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
EZOJ/Contests/1394/B.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> #include <vector> using namespace std; typedef long long lint; #define cout cerr #define ni (next_num<int>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool flag=c=='-'; flag?c=getchar():0; while(i=i*10-'0'+c,isdigit(c=getchar())); return flag?-i:i; } template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;} template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;} const int SH=6,O=998244353; inline int fpow(int x,int n){ int a=1; for(;n;n>>=1,x=(lint)x*x%O){ if(n&1){ a=(lint)a*x%O; } } return a; } inline int inv(int x){ return fpow(x,O-2); } int statecnt; struct bignum{ const static int N=2600,D=N/9,M=1000000000; int a[D],as; inline void input(){ static char s[N]; scanf("%s",s); int i=strlen(s)-1; as=1; memset(a,0,sizeof(a)); for(int j=1;i>=0;i--){ a[as-1]+=j*(s[i]-'0'); j*=10; if(j==M){ as++,j=1; } } } inline bool zero(){ return as==0; } inline bool div2(){ bool r=false; for(int i=as-1;i>=0;i--){ if(r){ a[i]+=M; } r=a[i]&1; a[i]>>=1; } for(;as>=1&&a[as-1]==0;as--); return r; } }lend,rend; struct Mat{ const static int D=37; int a[D][D]; inline int det(){ lint d=1; const static int &n=statecnt; for(int i=0;i<=n;i++){ int j=i; for(;j<=n&&a[j][i]==0;j++); if(j>n)return 0; if(i!=j){ d=O-d; for(int k=i;k<=n;k++){ swap(a[i][k],a[j][k]); } } d=d*a[i][i]%O; lint r=inv(a[i][i]); for(int k=i;k<=n;k++){ a[i][k]=r*a[i][k]%O; } for(j=i+1;j<=n;j++){ if(a[j][i]==0)continue; r=O-a[j][i]; for(int k=i;k<=n;k++){ a[j][k]=(a[j][k]+(lint)r*a[i][k])%O; } } } return d; } }trans; struct Vec{ const static int D=37; int a[D]; inline void clr(){ memset(a,0,sizeof(a)); } inline void gmul(const Mat &x,const Vec &y){ const int &n=statecnt; for(int i=0;i<=n;i++){ lint cur=0; for(int j=0;j<=n;j++){ cur+=(lint)x.a[i][j]*y.a[j]; const static lint OO=(lint)O*O; if(cur>=OO){ cur-=OO; } } a[i]=cur%O; } } }; namespace poly{ const int N=43; int x[N],y[N],f[N],n; int tmpf[N]; inline void interpol(){ for(int i=1;i<=n;i++){ if(y[i]==0)continue; int ds=0; lint c=1; tmpf[0]=1; for(int j=1;j<=n&&c;j++){ if(i==j)continue; for(int k=++ds;k>=0;k--){ lint cur=0; if(k<ds){ cur=-(lint)tmpf[k]*x[j]; } if(k){ cur+=tmpf[k-1]; } tmpf[k]=(cur%O+O)%O; } c=c*(x[i]-x[j])%O; } if(c){ c=(lint)inv((c+O)%O)*y[i]%O; for(int j=0;j<=ds;j++){ f[j]=(f[j]+tmpf[j]*c)%O; } } } } Mat mat; inline void genmat(int lam){ for(int i=0;i<=statecnt;i++){ for(int j=0;j<=statecnt;j++){ mat.a[i][j]=(O-trans.a[i][j])%O; if(i==j){ mat.a[i][j]=(mat.a[i][j]+lam)%O; } } } } inline void main(){ n=statecnt+2; for(int i=1;i<=n;i++){ genmat(i); x[i]=i,y[i]=mat.det(); } interpol(); for(;n>=1&&f[n-1]==0;n--); assert(n>0); if(f[n-1]!=1){ lint r=inv(f[n-1]); for(int i=0;i<n;i++){ f[i]=f[i]*r%O; } } } int res[N],tmp[N<<1]; inline void modtmp(int i){ for(;i>=n-1;i--){ if(tmp[i]==0)continue; lint r=(O-tmp[i])%O; for(int j=0;j<n;j++){ tmp[i-j]=(tmp[i-j]+f[n-j-1]*r)%O; } } } inline void fpow(bignum &e){ if(e.zero()){ memset(res,0,n<<2); res[0]=1; return; } bool r=e.div2(); fpow(e); memset(tmp,0,n<<3); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ tmp[i+j]=(tmp[i+j]+(lint)res[i]*res[j])%O; } } modtmp(n*2-2),memcpy(res,tmp,n<<2); if(r){ for(int i=n;i>=1;i--){ tmp[i]=res[i-1]; } tmp[0]=0; modtmp(n),memcpy(res,tmp,n<<2); } } inline int gpow(bignum &e){ fpow(e); Vec a; a.clr(); a.a[0]=1; lint cur=0; for(int i=0;i<n;i++){ cur+=(lint)a.a[statecnt]*res[i]%O; Vec tmp; tmp.gmul(trans,a); a=tmp; } return cur%O; } } namespace prob{ const int N=1<<SH; lint trans[N][N]; int rep[N]; bool self[N]; int s1,s2; int rev[N]; void dfs(int x,int s,bool sd,int curs,int curf){ if(x<0){ if(sd)return; trans[s][curs]+=curf; return; } if(sd){ if((s>>x)&1)return; return dfs(x-1,s,0,curs,curf); } if((s>>x)&1)return dfs(x-1,s,0,curs,curf); dfs(x-1,s,1,curs,(lint)curf*s2%O);//go right dfs(x-1,s,0,curs|(1<<x),(lint)curf*s1%O);//go down } inline void main(){ int n=ni; s1=ni,s2=ni; memset(trans,0,sizeof(trans)); int ts=1<<n; for(int s=0;s<ts;s++){ dfs(n-1,s,0,0,1); } rev[0]=0; for(int i=1;i<ts;i++){ rev[i]=(rev[i>>1]>>1)|((i&1)<<(n-1)); } memset(rep,-1,sizeof(rep)); statecnt=0; for(int i=0;i<ts;i++){ if(rep[rev[i]]==-1){ self[i]=true,rep[i]=statecnt++; }else{ self[i]=false,rep[i]=rep[rev[i]]; } } memset(&::trans,0,sizeof(::trans)); for(int i=0;i<ts;i++){ if(!self[i])continue; for(int j=0;j<ts;j++){ int &f=::trans.a[rep[j]][rep[i]]; f=(f+trans[i][j])%O; } } ::trans.a[statecnt][0]=::trans.a[statecnt][statecnt]=1; } } int main(){ #ifndef ONLINE_JUDGE freopen("decoration.in","r",stdin); freopen("decoration.out","w",stdout); #endif lend.input(),rend.input(); prob::main(); poly::main(); rend.a[0]++; printf("%d\n",(poly::gpow(rend)-poly::gpow(lend)+O)%O); return 0; }
18.488055
76
0.512461
[ "vector" ]
ba7d1602d0f5859fb619e8caf8b6718ecc8b3113
461
hpp
C++
lockhandler.hpp
gwint/distributed-key-value-store
4450c1381f993fa4b094583db216e494cd58bc7f
[ "MIT" ]
5
2020-08-01T14:41:19.000Z
2022-01-16T03:26:33.000Z
lockhandler.hpp
gwint/distributed-key-value-store
4450c1381f993fa4b094583db216e494cd58bc7f
[ "MIT" ]
2
2021-06-18T00:56:51.000Z
2021-07-05T15:26:39.000Z
lockhandler.hpp
gwint/distributed-key-value-store
4450c1381f993fa4b094583db216e494cd58bc7f
[ "MIT" ]
null
null
null
#ifndef LOCK_HANDLER_H #define LOCK_HANDLER_H #include <pthread.h> #include <vector> #include <algorithm> #include <initializer_list> #include "locknames.hpp" class LockHandler { private: std::vector<pthread_mutex_t> mutexes; public: LockHandler(int); void acquireLocks(std::initializer_list<LockName>); void releaseLocks(std::initializer_list<LockName>); std::vector<pthread_mutex_t>& getLocks(); }; #endif
20.043478
59
0.700651
[ "vector" ]
ba7e87fd0b88af28685e5b87123c886777e3ea42
4,140
cpp
C++
contracts/eosio.distribute/src/eosio.distribute.cpp
EOS-Nation/eosio.contracts
7ee1ede8e5307f9cd03a22b40e0d985a9c431a2e
[ "MIT" ]
null
null
null
contracts/eosio.distribute/src/eosio.distribute.cpp
EOS-Nation/eosio.contracts
7ee1ede8e5307f9cd03a22b40e0d985a9c431a2e
[ "MIT" ]
null
null
null
contracts/eosio.distribute/src/eosio.distribute.cpp
EOS-Nation/eosio.contracts
7ee1ede8e5307f9cd03a22b40e0d985a9c431a2e
[ "MIT" ]
null
null
null
#include <eosio.distribute/eosio.distribute.hpp> #include <eosio.token/eosio.token.hpp> namespace eosiodistribute { using eosio::token; distribute_contract::distribute_contract( name s, name code, datastream<const char*> ds ) :contract(s,code,ds), _distrib_singleton(get_self(), get_self().value), _claimers(get_self(), get_self().value) { _distrib_state = _distrib_singleton.exists() ? _distrib_singleton.get() : distrib_state{}; } void distribute_contract::donate_to_rex(const asset& amount, const std::string& memo) { system_contract::donatetorex_action donate_action{ system_account, { get_self(), system_contract::active_permission } }; donate_action.send( get_self(), amount, memo ); } void distribute_contract::setdistrib(const std::vector<distribute_account>& accounts) { require_auth(get_self()); if( accounts.size() > 0 ){ int64_t remaining_pct = max_distribute_pct; for( distribute_account acct : accounts ) { check(acct.account != get_self(), "Cannot set account to " + get_self().to_string() ); check(is_account(acct.account), "Account does not exist: " + acct.account.to_string() ); check(0 < acct.percent, "Only positive percentages are allowed"); check(acct.percent <= remaining_pct, "Total percentage exceeds 100%"); remaining_pct -= acct.percent; if(acct.account == rex_account) donate_to_rex(asset(0, system_contract::get_core_symbol()), "rex enabled check" ); } check(remaining_pct == 0, "Total percentage does not equal 100%"); } // set accounts auto& accts = _distrib_state.accounts; accts = accounts; _distrib_singleton.set( _distrib_state, get_self() ); } void distribute_contract::claimdistrib(const name& claimer) { require_auth(claimer); auto citr = _claimers.find(claimer.value); check(citr != _claimers.end(), "Not a valid distribution account"); if(citr->balance.amount != 0) { token::transfer_action transfer_act{ system_contract::token_account, { get_self(), system_contract::active_permission } }; transfer_act.send( get_self(), claimer, citr->balance, "distribution claim" ); } _claimers.erase(citr); } void distribute_contract::distribute(name from, name to, asset quantity, eosio::ignore<std::string> memo) { if (to != get_self()) return; check(quantity.symbol == eosiosystem::system_contract::get_core_symbol(), "Invalid symbol"); check(_distrib_state.accounts.size() > 0, "distribution accounts were not setup"); if(quantity.amount > 0) { asset remaining = quantity; for( const auto& acct : _distrib_state.accounts) { if( remaining.amount == 0 ) { break; } asset dist_amount = quantity * acct.percent / max_distribute_pct; if( remaining < dist_amount ) dist_amount = remaining; if( acct.account == rex_account ) { donate_to_rex(dist_amount, std::string("donation from ") + from.to_string() + " to eosio.rex"); } else { // add to table index auto citr = _claimers.find(acct.account.value); if(citr == _claimers.end()) { // create record _claimers.emplace(get_self(), [&]( auto& row) { row.account = acct.account; row.balance = dist_amount; }); } else { // update balance _claimers.modify(citr, get_self(), [&]( auto& row ){ row.balance += dist_amount; }); } } remaining -= dist_amount; } } } } // ns eosiodistribute
43.578947
134
0.567874
[ "vector" ]
ba812fc9eadb3705a37400e99d4712060d69045d
500
cpp
C++
VGP332/HelloPathfinding/GameState.cpp
CyroPCJr/OmegaEngine
65fbd6cff54266a9c934e3a875a4493d26758661
[ "MIT" ]
1
2021-04-23T19:18:12.000Z
2021-04-23T19:18:12.000Z
VGP332/HelloPathfinding/GameState.cpp
CyroPCJr/OmegaEngine
65fbd6cff54266a9c934e3a875a4493d26758661
[ "MIT" ]
null
null
null
VGP332/HelloPathfinding/GameState.cpp
CyroPCJr/OmegaEngine
65fbd6cff54266a9c934e3a875a4493d26758661
[ "MIT" ]
1
2021-06-15T10:42:08.000Z
2021-06-15T10:42:08.000Z
#include "GameState.h" using namespace PathFinding; using namespace Omega::Graphics; void GameState::Initialize() { mTileMap.Load(); } void GameState::Terminate() { mTileMap.UnLoad(); } void GameState::Update(float deltaTime) { mTileMap.Update(deltaTime); } void GameState::Render() { mTileMap.Render(); } void GameState::DebugUI() { //TODO: Why the simple draw render works here instead Gamestate::reder ? SimpleDraw::Render(mCamera); mTileMap.DebugUI(); }
16.129032
74
0.686
[ "render" ]