hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a88a2a049bd49a278070def226ececefea847b96
4,962
cpp
C++
ApplicationUtilities/SystemSoundPlayer/src/SystemSoundPlayer.cpp
yodaos-project/voice-interface-avs
d01136637f92df952be894bb1869d420889689ac
[ "Apache-2.0" ]
1
2019-10-22T06:08:20.000Z
2019-10-22T06:08:20.000Z
ApplicationUtilities/SystemSoundPlayer/src/SystemSoundPlayer.cpp
yodaos-project/voice-interface-avs
d01136637f92df952be894bb1869d420889689ac
[ "Apache-2.0" ]
null
null
null
ApplicationUtilities/SystemSoundPlayer/src/SystemSoundPlayer.cpp
yodaos-project/voice-interface-avs
d01136637f92df952be894bb1869d420889689ac
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 "AVSCommon/Utils/Logger/Logger.h" #include "SystemSoundPlayer/SystemSoundPlayer.h" namespace alexaClientSDK { namespace applicationUtilities { namespace systemSoundPlayer { using namespace avsCommon::utils::logger; /// String to identify log entries originating from this file. static const std::string TAG("SystemSoundPlayer"); /** * Create a LogEntry using this file's TAG and the specified event string. * * @param The event string for this @c LogEntry. */ #define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event) /// Utility function to quickly return a ready future with value false. static std::shared_future<bool> getFalseFuture() { auto errPromise = std::promise<bool>(); errPromise.set_value(false); return errPromise.get_future(); } std::shared_ptr<SystemSoundPlayer> SystemSoundPlayer::create( std::shared_ptr<avsCommon::utils::mediaPlayer::MediaPlayerInterface> mediaPlayer, std::shared_ptr<avsCommon::sdkInterfaces::audio::SystemSoundAudioFactoryInterface> soundPlayerAudioFactory) { if (!mediaPlayer) { ACSDK_ERROR(LX("createFailed").d("reason", "nullMediaPlayer")); return nullptr; } if (!soundPlayerAudioFactory) { ACSDK_ERROR(LX("createFailed").d("reason", "nullSoundPlayerAudioFactory")); return nullptr; } auto systemSoundPlayer = std::shared_ptr<SystemSoundPlayer>(new SystemSoundPlayer(mediaPlayer, soundPlayerAudioFactory)); mediaPlayer->setObserver(systemSoundPlayer); return systemSoundPlayer; } std::shared_future<bool> SystemSoundPlayer::playTone(Tone tone) { std::lock_guard<std::mutex> lock(m_mutex); std::cout << "playTone" << std::endl; if (m_sharedFuture.valid()) { ACSDK_ERROR(LX("playToneFailed").d("reason", "Already Playing a Tone")); return getFalseFuture(); } m_sourceId = avsCommon::utils::mediaPlayer::MediaPlayerInterface::ERROR; switch (tone) { case Tone::WAKEWORD_NOTIFICATION: m_sourceId = m_mediaPlayer->setSource(m_soundPlayerAudioFactory->wakeWordNotificationTone()(), false); break; case Tone::END_SPEECH: m_sourceId = m_mediaPlayer->setSource(m_soundPlayerAudioFactory->endSpeechTone()(), false); break; } if (avsCommon::utils::mediaPlayer::MediaPlayerInterface::ERROR == m_sourceId) { ACSDK_ERROR(LX("playToneFailed").d("reason", "setSourceFailed").d("type", "attachment")); return getFalseFuture(); } if (!m_mediaPlayer->play(m_sourceId)) { ACSDK_ERROR(LX("playToneFailed").d("reason", "playSourceFailed")); return getFalseFuture(); } m_sharedFuture = m_playTonePromise.get_future(); return m_sharedFuture; } void SystemSoundPlayer::onPlaybackStarted(SourceId id) { ACSDK_DEBUG5(LX(__func__).d("SourceId", id)); } void SystemSoundPlayer::onPlaybackFinished(SourceId id) { std::lock_guard<std::mutex> lock(m_mutex); ACSDK_DEBUG5(LX(__func__).d("SourceId", id)); if (m_sourceId != id) { ACSDK_ERROR(LX(__func__).d("SourceId", id).d("reason", "sourceId doesn't match played file")); } finishPlayTone(true); } void SystemSoundPlayer::onPlaybackError( SourceId id, const avsCommon::utils::mediaPlayer::ErrorType& type, std::string error) { std::lock_guard<std::mutex> lock(m_mutex); ACSDK_ERROR(LX(__func__).d("SourceId", id).d("error", error)); if (m_sourceId != id) { ACSDK_ERROR(LX("UnexpectedSourceId") .d("expectedSourceId", m_sourceId) .d("reason", "sourceId doesn't match played file")); } finishPlayTone(false); } void SystemSoundPlayer::finishPlayTone(bool result) { m_playTonePromise.set_value(result); std::cout << "finishPlayTone" << std::endl; m_playTonePromise = std::promise<bool>(); m_sharedFuture = std::shared_future<bool>(); } SystemSoundPlayer::SystemSoundPlayer( std::shared_ptr<avsCommon::utils::mediaPlayer::MediaPlayerInterface> mediaPlayer, std::shared_ptr<avsCommon::sdkInterfaces::audio::SystemSoundAudioFactoryInterface> soundPlayerAudioFactory) : m_mediaPlayer{mediaPlayer}, m_soundPlayerAudioFactory{soundPlayerAudioFactory} { } } // namespace systemSoundPlayer } // namespace applicationUtilities } // namespace alexaClientSDK
35.442857
114
0.705159
yodaos-project
a88bb60b8cfba4c5329201301f9d32e310f9cfef
2,725
cc
C++
tests/semaphore_unit_test.cc
boboxxd/DelayQueueCpp
b6e7d0271122932e7d947973048bae4a4769aa3c
[ "Apache-2.0" ]
5
2020-11-10T00:07:35.000Z
2022-02-08T06:27:13.000Z
tests/semaphore_unit_test.cc
boboxxd/DelayQueueCpp
b6e7d0271122932e7d947973048bae4a4769aa3c
[ "Apache-2.0" ]
null
null
null
tests/semaphore_unit_test.cc
boboxxd/DelayQueueCpp
b6e7d0271122932e7d947973048bae4a4769aa3c
[ "Apache-2.0" ]
3
2021-02-07T07:16:29.000Z
2021-06-18T01:28:07.000Z
// Copyright (c) 2020 Xi Cheng. All rights reserved. // Use of this source code is governed by a Apache License 2.0 that can be // found in the LICENSE file. #include <atomic> #include <chrono> #include <thread> #include "gtest/gtest.h" #include "src/semaphore.h" class SemaphoreUnitTest : public ::testing::Test { }; // Initialize a semaphore with count 1, and verify that wait won't block TEST_F(SemaphoreUnitTest, InitCountAsOneAndSingleWait) { Semaphore semaphore(1); semaphore.Wait(); } // Initialize a sempahore with count 0, and wait until a timeout TEST_F(SemaphoreUnitTest, InitCountAsZeroAndSingleWaitUntil) { Semaphore sempahore; // Set the timeout duration to be 1 second auto now = std::chrono::high_resolution_clock::now(); auto wait_duration = std::chrono::milliseconds(1000); // Because there is only one thread and because the count is initialized as // zero, we expect WaitUntil to timeout and therefore return false EXPECT_FALSE(sempahore.WaitUntil(now + wait_duration)); // Just some sanity check on the time that elapses auto now2 = std::chrono::high_resolution_clock::now(); EXPECT_TRUE(now2 - now >= wait_duration); } // A rather simple multi-threaded case that one thread runs as producer which // notifies and the other runs as a consumer which wait on the semaphore // Repeat this exercise for 100 times TEST_F(SemaphoreUnitTest, InitCountAsOneAndOneWaitAndOneNotify) { Semaphore semaphore; for (int i = 0; i < 100; i++) { auto producer_thread(std::thread([&semaphore] () { semaphore.Notify(); })); auto consumer_thread(std::thread([&semaphore] () { semaphore.Wait(); })); // We expect both threads to complete so join should return successfully producer_thread.join(); consumer_thread.join(); } } // Initialize a semaphore with a count of 10, and have 20 consumer threads to // wait on this semaphore. 10 of them returns immediately and the remaining // 10 timeout TEST_F(SemaphoreUnitTest, InitCountAsTenWithTwentyConsumers) { Semaphore semaphore(10); std::atomic<int> timeouts{0}; auto const wait_duration = std::chrono::milliseconds(1000); std::vector<std::thread> threads; for (int i = 0; i < 20; i++) { threads.push_back(std::thread([&semaphore, &wait_duration, &timeouts] () { auto now = std::chrono::high_resolution_clock::now(); auto wait_result = semaphore.WaitUntil(now + wait_duration); // Increment the timeouts counter if a consumer thread times out on wait if (!wait_result) { timeouts++; } })); } // Join the threads and clear the placeholder for threads for (auto& t : threads) { t.join(); } threads.clear(); EXPECT_EQ(timeouts.load(), 10); }
34.493671
79
0.714862
boboxxd
a88f2e2937a230d55b889ba34b754bbfa13c1e1b
3,251
cc
C++
modules/tools/fuzz/guardian/guardian_fuzz.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
3
2019-01-30T11:58:40.000Z
2019-05-22T02:43:03.000Z
modules/tools/fuzz/guardian/guardian_fuzz.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
3
2020-02-24T14:19:55.000Z
2022-02-10T19:49:29.000Z
modules/tools/fuzz/guardian/guardian_fuzz.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
3
2019-02-20T00:24:05.000Z
2022-01-04T05:58:51.000Z
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #define private public #include "modules/guardian/guardian.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/guardian/common/guardian_gflags.h" #include "modules/tools/fuzz/guardian/proto/guardian_fuzz.pb.h" #include "libfuzzer/libfuzzer_macro.h" static google::protobuf::LogSilencer logSilencer; namespace apollo { namespace guardian { using apollo::common::adapter::AdapterConfig; using apollo::common::adapter::AdapterManager; using apollo::common::adapter::AdapterManagerConfig; using apollo::tools::fuzz::guardian::GuardianFuzzMessage; class GuardianFuzz { public: void Init(); void Fuzz(GuardianFuzzMessage guardian_fuzz_message); private: std::unique_ptr<Guardian> guardian_; } guardian_fuzzer; void GuardianFuzz::Init() { AdapterManagerConfig config; config.set_is_ros(false); { auto *sub_config_1 = config.add_config(); sub_config_1->set_type(AdapterConfig::CHASSIS); sub_config_1->set_mode(AdapterConfig::RECEIVE_ONLY); sub_config_1->set_message_history_limit(1); auto *sub_config_2 = config.add_config(); sub_config_2->set_type(AdapterConfig::SYSTEM_STATUS); sub_config_2->set_mode(AdapterConfig::RECEIVE_ONLY); sub_config_2->set_message_history_limit(1); auto *sub_config_3 = config.add_config(); sub_config_3->set_type(AdapterConfig::CONTROL_COMMAND); sub_config_3->set_mode(AdapterConfig::RECEIVE_ONLY); sub_config_3->set_message_history_limit(1); auto *sub_config_4 = config.add_config(); sub_config_4->set_type(AdapterConfig::GUARDIAN); sub_config_4->set_mode(AdapterConfig::PUBLISH_ONLY); } AdapterManager::Init(config); FLAGS_adapter_config_filename = "modules/tools/fuzz/guardian/conf/adapter.conf"; FLAGS_guardian_enabled = true; guardian_.reset(new Guardian()); guardian_->Init(); guardian_->Start(); } void GuardianFuzz::Fuzz(GuardianFuzzMessage guardian_fuzz_message) { guardian_->OnChassis(guardian_fuzz_message.chassis()); guardian_->OnSystemStatus(guardian_fuzz_message.system_status()); guardian_->OnControl( guardian_fuzz_message.control_command()); ros::TimerEvent event; guardian_->OnTimer(event); } DEFINE_PROTO_FUZZER(const GuardianFuzzMessage& guardian_fuzz_message) { guardian_fuzzer.Fuzz(guardian_fuzz_message); } extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) { guardian_fuzzer.Init(); return 0; } } // namespace guardian } // namespace apollo
34.585106
79
0.730852
BaiduXLab
a8920ba644c3c9ba7d729fa7f8da6344aabc0ee8
3,099
hpp
C++
classdef/ObjectRoot.hpp
dwringer/a3system
b14f8992542c2c3c38c9b87644f2c5d7249affda
[ "MIT" ]
3
2016-10-31T21:05:20.000Z
2017-08-15T14:00:05.000Z
classdef/ObjectRoot.hpp
dwringer/ANIMA
a8813dbac158d05bea5d9a9c882567446caf48c3
[ "MIT" ]
null
null
null
classdef/ObjectRoot.hpp
dwringer/ANIMA
a8813dbac158d05bea5d9a9c882567446caf48c3
[ "MIT" ]
null
null
null
/* ObjectRoot class :: ObjectRoot -> nil Methods: _setf var_name value :: set variable in obj namespace and record key _getf var_name :: simple getVariable interface _push_attr var_name value :: append to an array variable _locals :: list of all recorded keys that have been stored _class :: show object's class hierarchy array This class is meant to act as the root of an object hierarchy, providing a standard interface for keeping instance variables in a namespace unique to each instance. This is just a thin layer of abstraction over the built-in setVariable and getVariable functions (which are already object-oriented in nature and provide a simple way of bootstrapping on top of the engine). Example: Obj = ["ObjectRoot"] call fnc_new; [Obj, "_setf", "a key", "associated data"] call fnc_tell; hint str ([Obj, "_getf", "a key"] call fnc_tell) // ... outputs "associated data" hint str ([Obj, "_locals"] call fnc_tell) // ... outputs ["a key"] Subclass example: ["ANewClass", ["_self"], { [_self, "ObjectRoot"] call fnc_instance; ... rest of init ... } call fnc_lambda] call fnc_class; w/macros: DEFCLASS("HeaderDefinedClass") ["_self"] DO { SUPER("ObjectRoot", _self); ... rest of init ... } ENDCLASS; */ DEFCLASS("ObjectRoot") ["_self"] DO { /* Initialize base object class instance */ _self setVariable ["__locals__", []]; _self } ENDCLASS; DEFMETHOD("ObjectRoot", "_setf") ["_self", "_var_name", "_value"] DO { /* Set value of a local variable */ private ["_locals"]; _locals = _self getVariable "__locals__"; if (not isNil "_value") then { if (({_x == _var_name} count _locals) == 0) then { _locals pushBack _var_name; }; _self setVariable [_var_name, _value]; } else { if (({_x == _var_name} count _locals) > 0) then { _locals = _locals - [_var_name]; }; _self setVariable [_var_name, nil]; }; _self setVariable ["__locals__", _locals]; } ENDMETHOD; DEFMETHOD("ObjectRoot", "_getf") ["_self", "_var_name"] DO { /* Get value of a local variable */ _self getVariable [_var_name, nil] } ENDMETHOD; DEFMETHOD("ObjectRoot", "_locals") ["_self"] DO { /* Return list of locally stored variable names */ _self getVariable "__locals__" } ENDMETHOD; ///////////////////////////////// TEST //////////////////////////////////////// DEFMETHOD("ObjectRoot", "_push_attr") ["_self", "_attribute", "_value"] DO { /* Append a value to attribute variable that is an array */ _self setVariable [_attribute, (_self getVariable _attribute) + [_value]]; // [_self, "_setf", _attribute, // ([_self, "_getf", _attribute] call fnc_tell) + // [_value]] call fnc_tell } ENDMETHOD; ///////////////////////////////// TEST //////////////////////////////////////// DEFMETHOD("ObjectRoot", "_class") ["_self"] DO { /* Return the class hierarchy for an instance */ _self getVariable "class_names" } ENDMETHOD;
32.621053
79
0.611488
dwringer
a89281ddf5189a56b50f4ea8937666414b40aa0f
1,187
inl
C++
include/ecst/context/data/step/step.inl
SuperV1234/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
475
2016-05-03T13:34:30.000Z
2021-11-26T07:02:47.000Z
include/ecst/context/data/step/step.inl
vittorioromeo/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
28
2016-08-30T06:37:40.000Z
2017-11-24T11:14:07.000Z
include/ecst/context/data/step/step.inl
vittorioromeo/ecst
b3c42e2c28978f1cd8ea620ade62613c6c875432
[ "AFL-3.0" ]
60
2016-05-11T22:16:15.000Z
2021-08-02T20:42:35.000Z
// Copyright (c) 2015-2016 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 // http://vittorioromeo.info | vittorio.romeo@outlook.com #pragma once #include "./step.hpp" #include "../data/data.hpp" ECST_CONTEXT_NAMESPACE { namespace impl { namespace step { template <typename TSettings> proxy<TSettings>::proxy(context_type& context, refresh_state_type& refresh_state) noexcept : base_type{context, refresh_state} { } template <typename TSettings> template <typename... TStartSystemTags> auto proxy<TSettings>::execute_systems_from( TStartSystemTags... sts) noexcept { return this->context().execute_systems_from( this->context(), sts...); } template <typename TSettings> auto proxy<TSettings>::execute_systems() noexcept { return this->context().execute_systems(this->context()); } } } } ECST_CONTEXT_NAMESPACE_END
28.261905
72
0.572873
SuperV1234
a894569a0124c401fc23feec88043ef883769325
944
cpp
C++
std/src/cybergarage/upnp/media/server/directory/itunes/iTunesTrack.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
std/src/cybergarage/upnp/media/server/directory/itunes/iTunesTrack.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
std/src/cybergarage/upnp/media/server/directory/itunes/iTunesTrack.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************** * * MediaServer for CyberLink * * Copyright (C) Satoshi Konno 2006 * * File: iTunesTrack.cpp * * Revision: * * 03/13/06 * - first revision. * ******************************************************************/ #ifdef SUPPORT_ITUNES #include <cybergarage/upnp/media/server/directory/itunes/iTunesTrack.h> using namespace CyberLink; //////////////////////////////////////////////// // Constructor //////////////////////////////////////////////// iTunesTrack::iTunesTrack(CyberXML::Node *node) { setNode(node); } iTunesTrack::~iTunesTrack() { } //////////////////////////////////////////////// // equals //////////////////////////////////////////////// bool iTunesTrack::equals(iTunesTrack *otherTrack) { if (otherTrack == NULL) return false; if (getTrackID() != otherTrack->getTrackID()) return false; return true; } #endif
18.509804
72
0.435381
cybergarage
a89574102e7d1798c0f51304b552e553df5864df
1,700
cpp
C++
ema-tools/find-rigid-coil-vertex-correspondence/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
null
null
null
ema-tools/find-rigid-coil-vertex-correspondence/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
2
2017-05-29T09:43:01.000Z
2017-05-29T09:50:05.000Z
ema-tools/find-rigid-coil-vertex-correspondence/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
4
2017-05-17T11:56:02.000Z
2022-03-05T09:12:24.000Z
#include "mesh/MeshIO.h" #include "ema/Ema.h" #include "settings.h" #include "CorrespondenceSubsetFinder.h" #include "CorrespondenceSubsetFinderBuilder.h" #include "VertexSubsets.h" #include "OutputResult.h" int main(int argc, char* argv[]) { Settings settings(argc, argv); Mesh mesh = MeshIO::read(settings.mesh); Ema ema; ema.read().from(settings.emaFile); ema.reduce_coil_set().to(settings.channels); ema.transform_all_coils().scale(settings.scaleFactor); std::vector<arma::vec> emaData; for(const std::string& coilName: settings.channels) { ema.coil(coilName).boundary().change_size(1); ema.coil(coilName).mirror().positions(); emaData.push_back( ema.coil(coilName).interpolate().position_at_time(settings.timeStamp)); } // read subsets auto subset = VertexSubsets::read_from(settings.subsets); // find correspondences and record energy std::vector<unsigned int> vertexIndices; double energy; CorrespondenceSubsetFinderBuilder() \ .set_ema_data(emaData) \ .set_energy_settings(settings.energySettings) \ .set_minimizer_settings(settings.minimizerSettings) \ .set_mesh(mesh) \ .set_subsets(subset) \ .set_partition_index(settings.partitionIndex) \ .set_partition_amount(settings.partitionAmount) \ .build() \ .find_best_correspondence() \ .get_best_correspondence(vertexIndices) \ .get_best_energy(energy); // output result OutputResult() \ .set_vertex_indices(vertexIndices) \ .set_ema_channels(settings.channels) \ .set_energy(energy) \ .set_partition_amount(settings.partitionAmount) \ .set_partition_index(settings.partitionIndex) \ .write(settings.outputFile); }
27.419355
94
0.731765
ahewer
a89d419de02d737fbdb96d5cb9e63a37bb25c9a1
2,825
cpp
C++
src/test_hdf5.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
null
null
null
src/test_hdf5.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
2
2020-11-06T19:45:34.000Z
2020-11-07T03:22:25.000Z
src/test_hdf5.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
null
null
null
#include "recon_lib.h" using namespace NDarray; using namespace std; int main(void) { // Write Section { HDF5 file = HDF5("TEST.h5", "w"); Array<float, 3> TEMP(2, 3, 4, ColumnMajorArray<3>()); Array<complex<float>, 3> TEMPC(4, 3, 2, ColumnMajorArray<3>()); Array<short, 3> TEMPS(2, 3, 4, ColumnMajorArray<3>()); for (int k = 0; k < TEMPC.length(thirdDim); k++) { for (int j = 0; j < TEMPC.length(secondDim); j++) { for (int i = 0; i < TEMPC.length(firstDim); i++) { TEMPC(i, j, k) = complex<float>(10 * k + j, i); } } } for (int k = 0; k < TEMP.length(thirdDim); k++) { for (int j = 0; j < TEMP.length(secondDim); j++) { for (int i = 0; i < TEMP.length(firstDim); i++) { TEMP(i, j, k) = 100 * k + 10 * j + i; TEMPS(i, j, k) = 100 * k + 10 * j + i - 2; } } } cout << "Exporting Attributes" << endl; int A = 10; float B = 3.14156; string C = "Super"; file.AddH5Scaler("Kdata", "A", A); file.AddH5Scaler("Kdata", "B", B); file.AddH5Char("Kdata", "C", C.c_str()); file.AddH5Array("Kdata", "D", TEMP); file.AddH5Array("Kdata", "E", TEMPC); file.AddH5Array("Kdata", "F", TEMPS); } // Write Section { HDF5 file = HDF5("TEST.h5", "r"); cout << "Reading Attributes" << endl; int A; float B; std::string C; file.ReadH5Scaler("Kdata", "A", &A); cout << "A = " << A << endl << flush; file.ReadH5Scaler("Kdata", "B", &B); cout << "B = " << B << endl << flush; file.ReadH5Char("Kdata", "C", C); cout << "C = " << C << endl << flush; Array<float, 3> TEMP(3, 3, 3); file.ReadH5Array("Kdata", "D", TEMP); for (int k = 0; k < TEMP.length(thirdDim); k++) { for (int j = 0; j < TEMP.length(secondDim); j++) { for (int i = 0; i < TEMP.length(firstDim); i++) { cout << "k=" << k << ",j=" << j << ",i=" << i << " = " << TEMP(i, j, k) << endl; } } } Array<complex<float>, 3> TEMPC; file.ReadH5Array("Kdata", "E", TEMPC); for (int k = 0; k < TEMPC.length(thirdDim); k++) { for (int j = 0; j < TEMPC.length(secondDim); j++) { for (int i = 0; i < TEMPC.length(firstDim); i++) { cout << "k=" << k << ",j=" << j << ",i=" << i << " = " << TEMPC(i, j, k) << endl; } } } Array<short, 3> TEMPF; file.ReadH5Array("Kdata", "F", TEMPF); for (int k = 0; k < TEMPF.length(thirdDim); k++) { for (int j = 0; j < TEMPF.length(secondDim); j++) { for (int i = 0; i < TEMPF.length(firstDim); i++) { cout << "k=" << k << ",j=" << j << ",i=" << i << " = " << TEMPF(i, j, k) << endl; } } } } return 0; }
27.163462
67
0.458761
uwmri
a89dcff42adfeac4877255a9f16803f0a8e62a89
4,562
cc
C++
src/expr/Reservable.cc
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
1
2022-03-30T20:16:43.000Z
2022-03-30T20:16:43.000Z
src/expr/Reservable.cc
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
src/expr/Reservable.cc
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2021, Universities Space Research Association (USRA). // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Universities Space Research Association nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY USRA ``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 USRA 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 "Reservable.hh" #include "Debug.hh" #include "Error.hh" #include "NodeConnector.hh" #include <algorithm> namespace PLEXIL { //! Default constructor Reservable::Reservable() : m_waiters(), m_holder(nullptr) { } //! Report which node owns this mutex. //! @return Pointer to the node; may be null. NodeConnector const *Reservable::getHolder() const { return m_holder; } //! Attempt to acquire the object. On failure, add the node to the //! object's waiting list. //! @param node The node wishing to acquire this object. //! @return true if the object was successfully acquired; //! false if not. bool Reservable::acquire(NodeConnector *node) { if (m_holder) { debugMsg("Reservable:acquire", ' ' << this << " by node " << node->getNodeId() << ' ' << node << " failed"); addWaitingNode(node); return false; } m_holder = node; // If it's on the waiting list, remove it now. removeWaitingNode(node); debugMsg("Reservable:acquire", ' ' << this << " by node " << m_holder->getNodeId() << ' ' << m_holder << " succeeded"); return true; } //! If held by this node, release the object and notify other //! waiting nodes that the object is available. //! @param node The node which (we hope) previously acquired the object. void Reservable::release(NodeConnector *node) { if (!m_holder) { debugMsg("Reservable:release", ' ' << this << " releasing object which was not held"); } else if (m_holder != node) { debugMsg("Reservable:release", ' ' << this << " invalid attempt by node " << node->getNodeId() << ' ' << node << ", which was not the holder"); } else { debugMsg("Reservable:release", ' ' << this << " by node " << node->getNodeId() << ' ' << node); m_holder = nullptr; for (NodeConnector *n : m_waiters) n->notifyResourceAvailable(); } } //! Add a node to the list of nodes waiting on the variable. //! @param node Pointer to the node. void Reservable::addWaitingNode(NodeConnector *node) { if (std::find(m_waiters.begin(), m_waiters.end(), node) == m_waiters.end()) { debugMsg("Reservable:addWaitingNode", ' ' << this << " node " << node->getNodeId() << ' ' << node); m_waiters.push_back(node); } } //! Remove a node from the list of nodes waiting on the variable. //! @param node Pointer to the node. void Reservable::removeWaitingNode(NodeConnector *node) { WaitQueue::iterator it = std::find(m_waiters.begin(), m_waiters.end(), node); if (it != m_waiters.end()) { debugMsg("Reservable:removeWaitingNode", ' ' << this << " removing node " << node->getNodeId() << ' ' << node); m_waiters.erase(it); } } } // namespace PLEXIL
36.790323
81
0.642043
taless474
a89e36f1b9d207393ec85e491eee776119e464a1
406
cpp
C++
components/math/curves/tests/plot02.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/math/curves/tests/plot02.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/math/curves/tests/plot02.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include "shared.h" int main () { printf ("Results of plot02_test:\n"); try { tcb_splinef spline; spline.add_key (2.0f, 1.0f); spline.add_key (1.0f, 0.0f); spline.add_key (3.0f, -1.0f); plot_spline ("three points tcb spline", spline, 80, 80); } catch (std::exception& e) { printf ("exception: %s\n", e.what ()); } return 0; }
16.916667
63
0.524631
untgames
a8a1f8e567cd88425fd2864cba0cfaf5017f967a
3,395
cpp
C++
examples/07_BLE/BLE_write/lib/BLE/BLEServiceMap.cpp
MelihOzbk/deneyapkart-platformio-core
c0fbc8ffa181ee22e597569b24bde5a011ccaaa4
[ "Apache-2.0" ]
17
2021-07-28T21:57:26.000Z
2022-02-28T20:32:04.000Z
esp-at/libraries/BLE/src/BLEServiceMap.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
7
2021-08-07T23:20:14.000Z
2022-03-20T15:05:21.000Z
esp-at/libraries/BLE/src/BLEServiceMap.cpp
PowerfulCat/Works
94b729ee2afd14a5fde03ea94f826e0b98b80dcf
[ "MIT" ]
10
2021-08-11T13:47:36.000Z
2022-03-26T02:41:45.000Z
/* * BLEServiceMap.cpp * * Created on: Jun 22, 2017 * Author: kolban */ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include <stdio.h> #include <iomanip> #include "BLEService.h" /** * @brief Return the service by UUID. * @param [in] UUID The UUID to look up the service. * @return The characteristic. */ BLEService* BLEServiceMap::getByUUID(const char* uuid) { return getByUUID(BLEUUID(uuid)); } /** * @brief Return the service by UUID. * @param [in] UUID The UUID to look up the service. * @return The characteristic. */ BLEService* BLEServiceMap::getByUUID(BLEUUID uuid, uint8_t inst_id) { for (auto &myPair : m_uuidMap) { if (myPair.first->getUUID().equals(uuid)) { return myPair.first; } } //return m_uuidMap.at(uuid.toString()); return nullptr; } // getByUUID /** * @brief Return the service by handle. * @param [in] handle The handle to look up the service. * @return The service. */ BLEService* BLEServiceMap::getByHandle(uint16_t handle) { return m_handleMap.at(handle); } // getByHandle /** * @brief Set the service by UUID. * @param [in] uuid The uuid of the service. * @param [in] characteristic The service to cache. * @return N/A. */ void BLEServiceMap::setByUUID(BLEUUID uuid, BLEService* service) { m_uuidMap.insert(std::pair<BLEService*, std::string>(service, uuid.toString())); } // setByUUID /** * @brief Set the service by handle. * @param [in] handle The handle of the service. * @param [in] service The service to cache. * @return N/A. */ void BLEServiceMap::setByHandle(uint16_t handle, BLEService* service) { m_handleMap.insert(std::pair<uint16_t, BLEService*>(handle, service)); } // setByHandle /** * @brief Return a string representation of the service map. * @return A string representation of the service map. */ std::string BLEServiceMap::toString() { std::string res; char hex[5]; for (auto &myPair: m_handleMap) { res += "handle: 0x"; snprintf(hex, sizeof(hex), "%04x", myPair.first); res += hex; res += ", uuid: " + myPair.second->getUUID().toString() + "\n"; } return res; } // toString void BLEServiceMap::handleGATTServerEvent( esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { // Invoke the handler for every Service we have. for (auto &myPair : m_uuidMap) { myPair.first->handleGATTServerEvent(event, gatts_if, param); } } /** * @brief Get the first service in the map. * @return The first service in the map. */ BLEService* BLEServiceMap::getFirst() { m_iterator = m_uuidMap.begin(); if (m_iterator == m_uuidMap.end()) return nullptr; BLEService* pRet = m_iterator->first; m_iterator++; return pRet; } // getFirst /** * @brief Get the next service in the map. * @return The next service in the map. */ BLEService* BLEServiceMap::getNext() { if (m_iterator == m_uuidMap.end()) return nullptr; BLEService* pRet = m_iterator->first; m_iterator++; return pRet; } // getNext /** * @brief Removes service from maps. * @return N/A. */ void BLEServiceMap::removeService(BLEService* service) { m_handleMap.erase(service->getHandle()); m_uuidMap.erase(service); } // removeService /** * @brief Returns the amount of registered services * @return amount of registered services */ int BLEServiceMap::getRegisteredServiceCount(){ return m_handleMap.size(); } #endif /* CONFIG_BT_ENABLED */
24.601449
81
0.693078
MelihOzbk
a8a7066949366a04cb2241d22dc414ca03c1cb48
782
cpp
C++
ablateLibrary/domain/region.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
3
2021-01-19T21:29:10.000Z
2021-08-20T19:54:49.000Z
ablateLibrary/domain/region.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
124
2021-01-14T15:30:48.000Z
2022-03-28T14:44:31.000Z
ablateLibrary/domain/region.cpp
UBCHREST/ablate
02a5b390ba4e257b96bd19f4604c269598dccd9d
[ "BSD-3-Clause" ]
17
2021-02-10T22:34:57.000Z
2022-03-21T18:46:06.000Z
#include "region.hpp" #include <algorithm> #include <functional> ablate::domain::Region::Region(std::string name, std::vector<int> valuesIn) : name(name), values(valuesIn.empty() ? valuesIn : std::vector<int>{1}) { // sort the values std::sort(values.begin(), values.end()); // Create a unique string auto hashString = name; for (const auto& value : values) { hashString += "," + std::to_string(value); } id = std::hash<std::string>()(hashString); } #include "parser/registrar.hpp" REGISTERDEFAULT(ablate::domain::Region, ablate::domain::Region, "The region in which this solver applies (Label & Values)", ARG(std::string, "name", "the label name"), OPT(std::vector<int>, "values", "the values on the label (default is 1)"));
37.238095
167
0.648338
UBCHREST
a8a84ec6b2d6731049af178e48b57c0ed74bf879
57,757
cpp
C++
src/stm32_sd.cpp
andreili/STM32F4
9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc
[ "MIT" ]
6
2019-04-16T11:38:45.000Z
2020-12-12T16:55:03.000Z
src/stm32_sd.cpp
andreili/STM32F4
9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc
[ "MIT" ]
1
2020-12-15T10:45:53.000Z
2021-02-22T11:59:19.000Z
src/stm32_sd.cpp
andreili/STM32F4
9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc
[ "MIT" ]
2
2019-05-23T03:08:25.000Z
2020-10-10T12:43:06.000Z
#include "stm32_sd.hpp" #ifdef STM32_USE_SD #define DATA_BLOCK_SIZE EDataBlockSize::_512B #define SDIO_STATIC_FLAGS SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::DCRCFAIL, \ SDIO_STA::EMasks::CTIMEOUT, SDIO_STA::EMasks::DTIMEOUT, \ SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::RXOVERR, \ SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CMDSENT, \ SDIO_STA::EMasks::DATAEND, SDIO_STA::EMasks::DBCKEND #define CLKCR_CLEAR_MASK SetBits<(std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::CLKDIV, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::PWRSAV, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::BYPASS, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::WIDBUS, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::NEGEDGE, \ (std::uint32_t)STM32_REGS::SDIO::CLKCR::EMasks::HWFC_EN>() #define DCTRL_CLEAR_MASK SetBits<(std::uint32_t)STM32_REGS::SDIO::DCTRL::EMasks::DTEN, \ (std::uint32_t)STM32_REGS::SDIO::DCTRL::EMasks::DTDIR, \ (std::uint32_t)STM32_REGS::SDIO::DCTRL::EMasks::DTMODE, \ (std::uint32_t)STM32_REGS::SDIO::DCTRL::EMasks::DBLOCKSIZE>() #define CMD_CLEAR_MASK SetBits<(std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::CMDINDEX, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::WAITRESP, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::WAITINT, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::WAITPEND, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::CPSMEN, \ (std::uint32_t)STM32_REGS::SDIO::CMD::EMasks::SDIOSUSPEND>() #define SDIO_INIT_CLK_DIV 0x76U #define SDIO_TRANSFER_CLK_DIV ((uint8_t)0x00U) #define SDIO_CMD0TIMEOUT 0x00010000U #define SD_VOLTAGE_WINDOW_WALID 0x80000000U #define SD_VOLTAGE_WINDOW_SD 0x80100000U #define SD_HIGH_CAPACITY 0x40000000U #define SD_STD_CAPACITY 0x00000000U #define SD_CHECK_PATTERN 0x000001AAU #define SD_MAX_VOLT_TRIAL 0x0000FFFFU #define SD_ALLZERO 0x00000000U #define SD_WIDE_BUS_SUPPORT 0x00040000U #define SD_SINGLE_BUS_SUPPORT 0x00010000U #define SD_CARD_LOCKED 0x02000000U #define SD_DATATIMEOUT 0xFFFFFFFFU #define SD_0TO7BITS 0x000000FFU #define SD_8TO15BITS 0x0000FF00U #define SD_16TO23BITS 0x00FF0000U #define SD_24TO31BITS 0xFF000000U #define SD_MAX_DATA_LENGTH 0x01FFFFFFU #define SD_HALFFIFO ((uint32_t)0x00000008U) #define SD_HALFFIFOBYTES ((uint32_t)0x00000020U) /** * @brief Command Class Supported */ #define SD_CCCC_LOCK_UNLOCK 0x00000080U #define SD_CCCC_WRITE_PROT 0x00000040U #define SD_CCCC_ERASE 0x00000020U using SDIO_STA = STM32_REGS::SDIO::STA; namespace STM32 { SD::ECardType SD::m_card_type; uint16_t SD::m_RCA; uint32_t SD::m_CSD[4]; uint32_t SD::m_CID[4]; SD::CardInfo SD::m_card_info; SD::ESDError SD::init() { init_gpio(); ///TODO init_DMA(); STM32::NVIC::enable_and_set_prior_IRQ(STM32::IRQn::SDIO, 0, 0); init_low(EClockEdge::RISING, EClockBypass::DISABLE, EClockPowerSave::DISABLE, EBusWide::_1B, EHWFlowControl::DISABLE, SDIO_INIT_CLK_DIV); ESDError errorstate; disable_SDIO(); power_state_ON(); STM32::SYSTICK::delay(1); enable_SDIO(); STM32::SYSTICK::delay(2); if ((errorstate = power_ON()) != ESDError::OK) return errorstate; if ((errorstate = initialize_cards()) != ESDError::OK) return errorstate; if ((errorstate = get_card_info()) == ESDError::OK) select_deselect(static_cast<uint32_t>(m_card_info.RCA << 16)); init_low(EClockEdge::RISING, EClockBypass::DISABLE, EClockPowerSave::DISABLE, EBusWide::_1B, EHWFlowControl::DISABLE, STM32_SDIO_CLOCK_DIV); return errorstate; } void SD::deinit() { power_OFF(); STM32::RCC::disable_clk_SDIO(); deinit_gpio(); //TODO deinit DMA STM32::NVIC::disable_IRQ(STM32::IRQn::SDIO); } SD::ESDError SD::wide_bus_config(EBusWide mode) { ESDError errorstate = ESDError::OK; /* MMC Card does not support this feature */ if (m_card_type == ECardType::MULTIMEDIA) return ESDError::UNSUPPORTED_FEATURE; else if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) || (m_card_type == ECardType::HIGH_CAPACITY)) { if (mode == EBusWide::_8B) errorstate = ESDError::UNSUPPORTED_FEATURE; else if (mode == EBusWide::_4B) errorstate = wide_bus_enable(); else if (mode == EBusWide::_1B) errorstate = wide_bus_disable(); else /* mode is not a valid argument*/ errorstate = ESDError::INVALID_PARAMETER; if (errorstate == ESDError::OK) { /* Configure the SDIO peripheral */ init_low(EClockEdge::RISING, EClockBypass::DISABLE, EClockPowerSave::DISABLE, mode, EHWFlowControl::DISABLE, STM32_SDIO_CLOCK_DIV); } } return errorstate; } SD::ETransferState SD::get_status() { ECardState cardstate = ECardState::TRANSFER; cardstate = get_state(); /* Find SD status according to card state*/ if (cardstate == ECardState::TRANSFER) return ETransferState::OK; else if(cardstate == ECardState::ERROR) return ETransferState::ERROR; else return ETransferState::BUSY; } SD::ESDError SD::read_blocks(uint8_t *buf, uint32_t read_addr, uint32_t block_size, uint16_t blocks) { ESDError errorstate = ESDError::OK; uint32_t count = 0U, *tempbuff = reinterpret_cast<uint32_t*>(buf); /* Initialize data control register */ STM32_REGS::SDIO::DCTRL::set(0); if (m_card_type == ECardType::HIGH_CAPACITY) { block_size = 512U; read_addr /= 512U; } /* Set Block Size for Card */ send_command(block_size, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; /* Configure the SD DPSM (Data Path State Machine) */ data_config(SD_DATATIMEOUT, blocks * block_size, DATA_BLOCK_SIZE, ETransferDir::TO_SDIO, ETransferMode::BLOCK, EDPSM::ENABLE); if (blocks > 1U) { /* Send CMD18 READ_MULT_BLOCK with argument data address */ send_command(read_addr, ECMD::READ_MULT_BLOCK, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); } else { /* Send CMD17 READ_SINGLE_BLOCK */ send_command(read_addr, ECMD::READ_SINGLE_BLOCK, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); } /* Read block(s) in polling mode */ #ifdef STM32_USE_RTOS TCritSect cs; #endif if (blocks > 1U) { /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::READ_MULT_BLOCK); if (errorstate != ESDError::OK) return errorstate; /* Poll on SDIO flags */ #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DATAEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DATAEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::RXFIFOHF>()) { /* Read data from SDIO Rx FIFO */ for (count = 0U; count < 8U; count++) *(tempbuff + count) = read_FIFO(); tempbuff += 8U; } } } else { /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::READ_SINGLE_BLOCK); //xprintf("error 3=%d\n\r", errorstate); if (errorstate != ESDError::OK) return errorstate; /* In case of single block transfer, no need of stop transfer at all */ #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::RXFIFOHF>()) { /* Read data from SDIO Rx FIFO */ for (count = 0U; count < 8U; count++) *(tempbuff + count) = read_FIFO(); tempbuff += 8U; } } } /* Send stop transmission command in case of multiblock read */ if (get_flag<SDIO_STA::EMasks::DATAEND>() && (blocks > 1U)) { if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) || (m_card_type == ECardType::HIGH_CAPACITY)) /* Send stop transmission command */ errorstate = stop_transfer(); } /* Get error state */ if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_CRC_FAIL; } else if (get_flag<SDIO_STA::EMasks::RXOVERR>()) { clear_flag<SDIO_STA::EMasks::RXOVERR>(); return ESDError::RX_OVERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } count = SD_DATATIMEOUT; /* Empty FIFO if there is still any data */ while ((get_flag<SDIO_STA::EMasks::RXDAVL>()) && (count > 0U)) { *tempbuff = read_FIFO(); tempbuff++; count--; } /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); return errorstate; } SD::ESDError SD::write_blocks(uint8_t *buf, uint32_t write_addr, uint32_t block_size, uint16_t blocks) { ESDError errorstate = ESDError::OK; uint32_t totalnumberofbytes = 0U, bytestransferred = 0U, count = 0U, restwords = 0U; uint32_t *tempbuff = reinterpret_cast<uint32_t*>(buf); ECardState cardstate = ECardState::READY; /* Initialize data control register */ STM32_REGS::SDIO::DCTRL::set(0); if (m_card_type == ECardType::HIGH_CAPACITY) { block_size = 512U; write_addr /= 512U; } /* Set Block Size for Card */ send_command(block_size, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; if (blocks > 1U) /* Send CMD25 WRITE_MULT_BLOCK with argument data address */ send_command(write_addr, ECMD::WRITE_MULT_BLOCK, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); else /* Send CMD24 WRITE_SINGLE_BLOCK */ send_command(write_addr, ECMD::WRITE_SINGLE_BLOCK, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ if (blocks > 1U) errorstate = cmd_resp1_error(ECMD::WRITE_MULT_BLOCK); else errorstate = cmd_resp1_error(ECMD::WRITE_SINGLE_BLOCK); if (errorstate != ESDError::OK) return errorstate; /* Set total number of bytes to write */ totalnumberofbytes = blocks * block_size; /* Configure the SD DPSM (Data Path State Machine) */ data_config(SD_DATATIMEOUT, blocks * block_size, EDataBlockSize::_512B, ETransferDir::TO_CARD, ETransferMode::BLOCK, EDPSM::ENABLE); /* Write block(s) in polling mode */ if (blocks > 1U) { #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DATAEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DATAEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::TXFIFOHE>()) { if ((totalnumberofbytes - bytestransferred) < 32U) { restwords = ((totalnumberofbytes - bytestransferred) % 4U == 0U) ? ((totalnumberofbytes - bytestransferred) / 4U) : (( totalnumberofbytes - bytestransferred) / 4U + 1U); /* Write data to SDIO Tx FIFO */ for (count = 0U; count < restwords; count++) { write_FIFO(tempbuff); tempbuff++; bytestransferred += 4U; } } else { /* Write data to SDIO Tx FIFO */ for (count = 0U; count < 8U; count++) write_FIFO(tempbuff + count); tempbuff += 8U; bytestransferred += 32U; } } } } else { /* In case of single data block transfer no need of stop command at all */ #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::TXUNDERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::TXFIFOHE>()) { if ((totalnumberofbytes - bytestransferred) < 32U) { restwords = ((totalnumberofbytes - bytestransferred) % 4U == 0U) ? ((totalnumberofbytes - bytestransferred) / 4U) : (( totalnumberofbytes - bytestransferred) / 4U + 1U); /* Write data to SDIO Tx FIFO */ for (count = 0U; count < restwords; count++) { write_FIFO(tempbuff); tempbuff++; bytestransferred += 4U; } } else { /* Write data to SDIO Tx FIFO */ for (count = 0U; count < 8U; count++) write_FIFO(tempbuff + count); tempbuff += 8U; bytestransferred += 32U; } } } } /* Send stop transmission command in case of multiblock write */ if (get_flag<SDIO_STA::EMasks::DATAEND>() && (blocks > 1U)) { if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) ||\ (m_card_type == ECardType::HIGH_CAPACITY)) /* Send stop transmission command */ errorstate = stop_transfer(); } /* Get error state */ if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_CRC_FAIL; } else if (get_flag<SDIO_STA::EMasks::TXUNDERR>()) { clear_flag<SDIO_STA::EMasks::TXUNDERR>(); return ESDError::TX_UNDERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); /* Wait till the card is in programming state */ errorstate = is_card_programming(&cardstate); while ((errorstate == ESDError::OK) && ((cardstate == ECardState::PROGRAMMING) || (cardstate == ECardState::RECEIVING))) errorstate = is_card_programming(&cardstate); return errorstate; } SD::ESDError SD::erase(uint32_t start_addr, uint32_t end_addr) { ESDError errorstate = ESDError::OK; uint32_t delay = 0U; __IO uint32_t maxdelay = 0U; ECardState cardstate = ECardState::READY; /* Check if the card command class supports erase command */ if (((m_CSD[1U] >> 20U) & SD_CCCC_ERASE) == 0U) return ESDError::REQUEST_NOT_APPLICABLE; /* Get max delay value */ maxdelay = 120000U / (((STM32_REGS::SDIO::CLKCR::get()) & 0xFFU) + 2U); if ((get_response1() & SD_CARD_LOCKED) == SD_CARD_LOCKED) return ESDError::LOCK_UNLOCK_FAILED; /* Get start and end block for high capacity cards */ if (m_card_type == ECardType::HIGH_CAPACITY) { start_addr /= 512U; end_addr /= 512U; } /* According to sd-card spec 1.0 ERASE_GROUP_START (CMD32) and erase_group_end(CMD33) */ if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) || (m_card_type == ECardType::HIGH_CAPACITY)) { /* Send CMD32 SD_ERASE_GRP_START with argument as addr */ send_command(start_addr, ECMD::SD_ERASE_GRP_START, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SD_ERASE_GRP_START); if (errorstate != ESDError::OK) return errorstate; /* Send CMD33 SD_ERASE_GRP_END with argument as addr */ send_command(end_addr, ECMD::SD_ERASE_GRP_END, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SD_ERASE_GRP_END); if (errorstate != ESDError::OK) return errorstate; } /* Send CMD38 ERASE */ send_command(0, ECMD::ERASE, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::ERASE); if (errorstate != ESDError::OK) return errorstate; for (; delay < maxdelay; delay++) {} /* Wait until the card is in programming state */ errorstate = is_card_programming(&cardstate); delay = SD_DATATIMEOUT; while ((delay > 0U) && (errorstate == ESDError::OK) && ((cardstate == ECardState::PROGRAMMING) || (cardstate == ECardState::RECEIVING))) { errorstate = is_card_programming(&cardstate); delay--; } return errorstate; } SD::ESDError SD::high_speed() { ESDError errorstate = ESDError::OK; uint8_t SD_hs[64U] = {0U}; uint32_t SD_scr[2U] = {0U, 0U}; uint32_t SD_SPEC = 0U; uint32_t count = 0U, *tempbuff = reinterpret_cast<uint32_t*>(SD_hs); /* Initialize the Data control register */ STM32_REGS::SDIO::DCTRL::set(0); /* Get SCR Register */ errorstate = find_SCR(SD_scr); if (errorstate != ESDError::OK) return errorstate; /* Test the Version supported by the card*/ SD_SPEC = (SD_scr[1U] & 0x01000000U) | (SD_scr[1U] & 0x02000000U); if (SD_SPEC != SD_ALLZERO) { /* Set Block Size for Card */ send_command(64U, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; /* Configure the SD DPSM (Data Path State Machine) */ data_config(SD_DATATIMEOUT, 64U, EDataBlockSize::_64B, ETransferDir::TO_SDIO, ETransferMode::BLOCK, EDPSM::ENABLE); /* Send CMD6 switch mode */ send_command(0x80FFFF01U, ECMD::HS_SWITCH, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::HS_SWITCH); if (errorstate != ESDError::OK) return errorstate; #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR */ while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::RXFIFOHF>()) { for (count = 0U; count < 8U; count++) *(tempbuff + count) = read_FIFO(); tempbuff += 8U; } } if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_CRC_FAIL; } else if (get_flag<SDIO_STA::EMasks::RXOVERR>()) { clear_flag<SDIO_STA::EMasks::RXOVERR>(); return ESDError::RX_OVERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } count = SD_DATATIMEOUT; while ((get_flag<SDIO_STA::EMasks::RXDAVL>()) && (count > 0U)) { *tempbuff = read_FIFO(); tempbuff++; count--; } /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); /* Test if the switch mode HS is ok */ if ((SD_hs[13U]& 2U) != 2U) errorstate = ESDError::UNSUPPORTED_FEATURE; } return errorstate; } SD::ESDError SD::send_SD_status(uint32_t *status) { ESDError errorstate = ESDError::OK; uint32_t count = 0U; /* Check SD response */ if ((get_response1() & SD_CARD_LOCKED) == SD_CARD_LOCKED) return ESDError::LOCK_UNLOCK_FAILED; /* Set block size for card if it is not equal to current block size for card */ send_command(64U, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; /* Send CMD55 */ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_CMD); if (errorstate != ESDError::OK) return errorstate; /* Configure the SD DPSM (Data Path State Machine) */ data_config(SD_DATATIMEOUT, 64U, EDataBlockSize::_64B, ETransferDir::TO_SDIO, ETransferMode::BLOCK, EDPSM::ENABLE); /* Send ACMD13 (SD_APP_STATUS) with argument as card's RCA */ send_command(0, ECMD::SD_APP_STATUS, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SD_APP_STATUS); if (errorstate != ESDError::OK) return errorstate; /* Get status data */ #ifdef SDIO_STA_STBITERR while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while (!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if (get_flag<SDIO_STA::EMasks::RXFIFOHF>()) { for (count = 0U; count < 8U; count++) *(status + count) = read_FIFO(); status += 8U; } } if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_CRC_FAIL; } else if (get_flag<SDIO_STA::EMasks::RXOVERR>()) { clear_flag<SDIO_STA::EMasks::RXOVERR>(); return ESDError::RX_OVERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } count = SD_DATATIMEOUT; while ((get_flag<SDIO_STA::EMasks::RXDAVL>()) && (count > 0U)) { *status = read_FIFO(); status++; count--; } /* Clear all the static status flags*/ clear_flag<SDIO_STATIC_FLAGS>(); return errorstate; } void SD::init_gpio() { STM32::RCC::enable_clk_SDIO(); STM32::RCC::enable_clk_GPIOC(); STM32::RCC::enable_clk_GPIOD(); gpioc.set_config(STM32_GPIO::PIN_8 | STM32_GPIO::PIN_9 | STM32_GPIO::PIN_10 | STM32_GPIO::PIN_11 | STM32_GPIO::PIN_12, STM32_GPIO::EMode::AF_PP, STM32_GPIO::EAF::AF12_SDIO, STM32_GPIO::ESpeed::VERY_HIGH, STM32_GPIO::EPull::NOPULL); gpiod.set_config(STM32_GPIO::PIN_2, STM32_GPIO::EMode::AF_PP, STM32_GPIO::EAF::AF12_SDIO, STM32_GPIO::ESpeed::VERY_HIGH, STM32_GPIO::EPull::NOPULL); } void SD::deinit_gpio() { gpioc.unset_config(STM32_GPIO::PIN_8 | STM32_GPIO::PIN_9 | STM32_GPIO::PIN_10 | STM32_GPIO::PIN_11 | STM32_GPIO::PIN_12); gpiod.unset_config(STM32_GPIO::PIN_2); STM32::RCC::disable_clk_GPIOC(); STM32::RCC::disable_clk_GPIOD(); } void SD::init_low(EClockEdge clock_edge, EClockBypass clock_bypass, EClockPowerSave clock_power_save, EBusWide bus_wide, EHWFlowControl hw_control, uint32_t clock_div) { uint32_t val = STM32_REGS::SDIO::CLKCR::get(); val &= ~(CLKCR_CLEAR_MASK); val |= static_cast<uint32_t>(clock_edge) | static_cast<uint32_t>(clock_bypass) | static_cast<uint32_t>(clock_power_save) | static_cast<uint32_t>(bus_wide) | static_cast<uint32_t>(hw_control) | clock_div; STM32_REGS::SDIO::CLKCR::set(val); } SD::ESDError SD::power_ON() { /* CMD0: GO_IDLE_STATE */ send_command(0, ECMD::GO_IDLE_STATE, EResponse::NO, EWait::NO, ECPSM::ENABLE); ESDError errorstate = cmd_error(); if (errorstate != ESDError::OK) { clear_flag<SDIO_STATIC_FLAGS>(); return errorstate; } /* CMD8: SEND_IF_COND ------------------------------------------------------*/ /* Send CMD8 to verify SD card interface operating condition */ /* Argument: - [31:12]: Reserved (shall be set to '0') - [11:8]: Supply Voltage (VHS) 0x1 (Range: 2.7-3.6 V) - [7:0]: Check Pattern (recommended 0xAA) */ uint32_t sdtype = SD_STD_CAPACITY; send_command(SD_CHECK_PATTERN, ECMD::HS_SEND_EXT_CSD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); errorstate = cmd_resp7_error(); if (errorstate != ESDError::OK) { m_card_type = ECardType::STD_CAPACITY_V1_1; sdtype = SD_STD_CAPACITY; } else { /* SD Card 2.0 */ m_card_type = ECardType::STD_CAPACITY_V2_0; sdtype = SD_HIGH_CAPACITY; } /* Send CMD55 */ send_command(0, ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* If errorstate is Command Timeout, it is a MMC card */ /* If errorstate is ESDError::OK it is a SD card: SD card 2.0 (voltage range mismatch) or SD card 1.x */ uint32_t response = 0; errorstate = cmd_resp1_error(ECMD::APP_CMD); if (errorstate == ESDError::OK) { /* SD CARD */ /* Send ACMD41 SD_APP_OP_COND with Argument 0x80100000 */ uint32_t validvoltage = 0; uint32_t count = 0; while ((!validvoltage) && (count <SD_MAX_VOLT_TRIAL)) { /* SEND CMD55 APP_CMD with RCA as 0 */ send_command(0, ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); errorstate = cmd_resp1_error(ECMD::APP_CMD); if (errorstate != ESDError::OK) return errorstate; /* Send CMD41 */ send_command(SD_VOLTAGE_WINDOW_SD | sdtype, ECMD::SD_APP_OP_COND, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); errorstate = cmd_resp3_error(); if (errorstate != ESDError::OK) return errorstate; /* Get command response */ response = get_response1(); validvoltage = ((response & SD_VOLTAGE_WINDOW_WALID) == SD_VOLTAGE_WINDOW_WALID); ++count; } if (count >= SD_MAX_VOLT_TRIAL) return ESDError::INVALID_VOLTRANGE; if ((response & SD_HIGH_CAPACITY) == SD_HIGH_CAPACITY) m_card_type = ECardType::HIGH_CAPACITY; else m_card_type = ECardType::STD_CAPACITY_V2_0; } /* else MMC Card */ else { } return errorstate; } SD::ESDError SD::power_OFF() { power_state_OFF(); return ESDError::OK; } SD::ESDError SD::send_status(uint32_t *card_status) { ESDError errorstate = ESDError::OK; if(card_status == nullptr) return ESDError::INVALID_PARAMETER; /* Send Status command */ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::SEND_STATUS, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SEND_STATUS); if(errorstate != ESDError::OK) return errorstate; /* Get SD card status */ *card_status = get_response1(); return errorstate; } SD::ESDError SD::initialize_cards() { ESDError errorstate = ESDError::OK; uint16_t sd_rca = 1; if (get_power_state() == 0) /* Power off */ return ESDError::REQUEST_NOT_APPLICABLE; if (m_card_type != ECardType::SECURE_DIGITAL_IO) { /* Send CMD2 ALL_SEND_CID */ send_command(0, ECMD::ALL_SEND_CID, EResponse::LONG, EWait::NO, ECPSM::ENABLE); if ((errorstate = cmd_resp2_error()) != ESDError::OK) return errorstate; m_CID[0] = get_response1(); m_CID[1] = get_response2(); m_CID[2] = get_response3(); m_CID[3] = get_response4(); } if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0) || (m_card_type == ECardType::SECURE_DIGITAL_IO_COMBO) || (m_card_type == ECardType::HIGH_CAPACITY)) { /* Send CMD3 SET_REL_ADDR with argument 0 */ /* SD Card publishes its RCA. */ send_command(0, ECMD::SET_REL_ADDR, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); if ((errorstate = cmd_resp6_error(ECMD::SET_REL_ADDR, &sd_rca)) != ESDError::OK) return errorstate; } if (m_card_type != ECardType::SECURE_DIGITAL_IO) { /* Get the SD card RCA */ m_RCA = sd_rca; /* Send CMD9 SEND_CSD with argument as card's RCA */ send_command(static_cast<uint32_t>(m_RCA << 16), ECMD::SEND_CSD, EResponse::LONG, EWait::NO, ECPSM::ENABLE); if ((errorstate = cmd_resp2_error()) != ESDError::OK) return errorstate; m_CSD[0] = get_response1(); m_CSD[1] = get_response2(); m_CSD[2] = get_response3(); m_CSD[3] = get_response4(); } return errorstate; } void SD::send_command(uint32_t arg, ECMD cmd, EResponse resp, EWait wait_IT, ECPSM cpsm) { STM32_REGS::SDIO::ARG::set(arg); uint32_t val = STM32_REGS::SDIO::CMD::get(); val &= ~(CMD_CLEAR_MASK); val |= static_cast<uint32_t>(cmd) | static_cast<uint32_t>(resp) | static_cast<uint32_t>(wait_IT) | static_cast<uint32_t>(cpsm); STM32_REGS::SDIO::CMD::set(val); } SD::ESDError SD::cmd_error() { WAIT_TIMEOUT_EX((!get_flag<SDIO_STA::EMasks::CMDSENT>()), SDIO_CMD0TIMEOUT, ESDError::CMD_RSP_TIMEOUT); clear_flag<SDIO_STATIC_FLAGS>(); return ESDError::OK; } SD::ESDError SD::cmd_resp7_error() { WAIT_TIMEOUT_EX((!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()), SDIO_CMD0TIMEOUT, ESDError::CMD_RSP_TIMEOUT); if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { /* Card is not V2.0 compliant or card does not support the set voltage range */ clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } if (get_flag<SDIO_STA::EMasks::CMDREND>()) { /* Card is SD V2.0 compliant */ clear_flag<SDIO_STA::EMasks::CMDREND>(); return ESDError::OK; } return ESDError::ERROR; } SD::ESDError SD::cmd_resp1_error(ECMD cmd) { while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::CCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::CCRCFAIL>(); return ESDError::CMD_CRC_FAIL; } /* Check response received is of desired command */ if (get_cmd_response() != cmd) return ESDError::CMD_CRC_FAIL; /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); uint32_t response_r1 = get_response1(); if ((response_r1 & EOCRMasks::ERRORBITS) == SD_ALLZERO) return ESDError::OK; if ((response_r1 & EOCRMasks::ADDR_OUT_OF_RANGE)) return ESDError::ADDR_OUT_OF_RANGE; if ((response_r1 & EOCRMasks::ADDR_MISALIGNED)) return ESDError::ADDR_MISALIGNED; if ((response_r1 & EOCRMasks::BLOCK_LEN_ERR)) return ESDError::BLOCK_LEN_ERR; if ((response_r1 & EOCRMasks::ERASE_SEQ_ERR)) return ESDError::ERASE_SEQ_ERR; if ((response_r1 & EOCRMasks::BAD_ERASE_PARAM)) return ESDError::BAD_ERASE_PARAM; if ((response_r1 & EOCRMasks::WRITE_PROT_VIOLATION)) return ESDError::WRITE_PROT_VIOLATION; if ((response_r1 & EOCRMasks::LOCK_UNLOCK_FAILED)) return ESDError::LOCK_UNLOCK_FAILED; if ((response_r1 & EOCRMasks::COM_CRC_FAILED)) return ESDError::COM_CRC_FAILED; /*if ((response_r1 & EOCRMasks::ILLEGAL_CMD)) return ESDError::ILLEGAL_CMD;*/ if ((response_r1 & EOCRMasks::CARD_ECC_FAILED)) return ESDError::CARD_ECC_FAILED; if ((response_r1 & EOCRMasks::CC_ERROR)) return ESDError::CC_ERROR; if ((response_r1 & EOCRMasks::GENERAL_UNKNOWN_ERROR)) return ESDError::GENERAL_UNKNOWN_ERROR; if ((response_r1 & EOCRMasks::STREAM_READ_UNDERRUN)) return ESDError::STREAM_READ_UNDERRUN; if ((response_r1 & EOCRMasks::STREAM_WRITE_OVERRUN)) return ESDError::STREAM_WRITE_OVERRUN; if ((response_r1 & EOCRMasks::CID_CSD_OVERWRITE)) return ESDError::CID_CSD_OVERWRITE; if ((response_r1 & EOCRMasks::WP_ERASE_SKIP)) return ESDError::WP_ERASE_SKIP; if ((response_r1 & EOCRMasks::CARD_ECC_DISABLED)) return ESDError::CARD_ECC_DISABLED; if ((response_r1 & EOCRMasks::ERASE_RESET)) return ESDError::ERASE_RESET; if ((response_r1 & EOCRMasks::AKE_SEQ_ERROR)) return ESDError::AKE_SEQ_ERROR; return ESDError::OK; } SD::ESDError SD::cmd_resp3_error() { while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } clear_flag<SDIO_STATIC_FLAGS>(); return ESDError::OK; } SD::ESDError SD::cmd_resp2_error() { while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::CCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::CCRCFAIL>(); return ESDError::CMD_CRC_FAIL; } clear_flag<SDIO_STATIC_FLAGS>(); return ESDError::OK; } SD::ESDError SD::cmd_resp6_error(ECMD cmd, uint16_t *pRCA) { while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::CCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::CCRCFAIL>(); return ESDError::CMD_CRC_FAIL; } if (get_cmd_response() != cmd) return ESDError::ILLEGAL_CMD; clear_flag<SDIO_STATIC_FLAGS>(); ER6Msk response_r1 = static_cast<ER6Msk>(get_response1()); if (response_r1 & ER6Msk::GENERAL_UNKNOWN_ERROR_6) return ESDError::GENERAL_UNKNOWN_ERROR; if (response_r1 & ER6Msk::ILLEGAL_CMD_6) return ESDError::ILLEGAL_CMD; if (response_r1 & ER6Msk::COM_CRC_FAILED_6) return ESDError::COM_CRC_FAILED; *pRCA = response_r1 >> 16; return ESDError::OK; } SD::ESDError SD::data_config(uint32_t time_out, uint32_t dat_len, EDataBlockSize block_size, ETransferDir transf_dir, ETransferMode transf_mode, EDPSM DPSM) { STM32_REGS::SDIO::DTIMER::set(time_out); STM32_REGS::SDIO::DLEN::set(dat_len); uint32_t val = STM32_REGS::SDIO::DCTRL::get(); val &= ~(DCTRL_CLEAR_MASK); val |= static_cast<uint32_t>(block_size) | static_cast<uint32_t>(transf_dir) | static_cast<uint32_t>(transf_mode) | static_cast<uint32_t>(DPSM); STM32_REGS::SDIO::DCTRL::set(val); return ESDError::OK; } SD::ESDError SD::stop_transfer() { send_command(0, ECMD::STOP_TRANSMISSION, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); return cmd_resp1_error(ECMD::STOP_TRANSMISSION); } SD::ESDError SD::get_card_info() { ESDError errorstate = ESDError::OK; m_card_info.CardType = static_cast<uint8_t>(m_card_type); m_card_info.RCA = m_RCA; /* Byte 1 */ uint32_t tmp = (m_CSD[0U] & 0x00FF0000U) >> 16U; m_card_info.SD_csd.TAAC = static_cast<uint8_t>(tmp); /* Byte 2 */ tmp = (m_CSD[0U] & 0x0000FF00U) >> 8U; m_card_info.SD_csd.NSAC = static_cast<uint8_t>(tmp); /* Byte 3 */ tmp = m_CSD[0U] & 0x000000FFU; m_card_info.SD_csd.MaxBusClkFrec = static_cast<uint8_t>(tmp); /* Byte 4 */ tmp = (m_CSD[1U] & 0xFF000000U) >> 24U; m_card_info.SD_csd.CardComdClasses = static_cast<uint16_t>(tmp << 4U); /* Byte 5 */ tmp = (m_CSD[1U] & 0x00FF0000U) >> 16U; m_card_info.SD_csd.CardComdClasses |= static_cast<uint16_t>((tmp & 0xF0) >> 4U); m_card_info.SD_csd.RdBlockLen = static_cast<uint8_t>(tmp & 0x0FU); /* Byte 6 */ tmp = (m_CSD[1U] & 0x0000FF00U) >> 8U; m_card_info.SD_csd.PartBlockRead = static_cast<uint8_t>((tmp & 0x80U) >> 7U); m_card_info.SD_csd.WrBlockMisalign = static_cast<uint8_t>((tmp & 0x40U) >> 6U); m_card_info.SD_csd.RdBlockMisalign = static_cast<uint8_t>((tmp & 0x20U) >> 5U); m_card_info.SD_csd.DSRImpl = static_cast<uint8_t>((tmp & 0x10U) >> 4U); m_card_info.SD_csd.Reserved2 = 0U; /*!< Reserved */ if ((m_card_type == ECardType::STD_CAPACITY_V1_1) || (m_card_type == ECardType::STD_CAPACITY_V2_0)) { m_card_info.SD_csd.DeviceSize = (tmp & 0x03U) << 10U; /* Byte 7 */ tmp = static_cast<uint8_t>(m_CSD[1U] & 0x000000FFU); m_card_info.SD_csd.DeviceSize |= (tmp) << 2U; /* Byte 8 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0xFF000000U) >> 24U); m_card_info.SD_csd.DeviceSize |= (tmp & 0xC0U) >> 6U; m_card_info.SD_csd.MaxRdCurrentVDDMin = (tmp & 0x38U) >> 3U; m_card_info.SD_csd.MaxRdCurrentVDDMax = (tmp & 0x07U); /* Byte 9 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0x00FF0000U) >> 16U); m_card_info.SD_csd.MaxWrCurrentVDDMin = (tmp & 0xE0U) >> 5U; m_card_info.SD_csd.MaxWrCurrentVDDMax = (tmp & 0x1CU) >> 2U; m_card_info.SD_csd.DeviceSizeMul = static_cast<uint8_t>((tmp & 0x03U) << 1U); /* Byte 10 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0x0000FF00U) >> 8U); m_card_info.SD_csd.DeviceSizeMul |= (tmp & 0x80U) >> 7U; m_card_info.CardCapacity = (m_card_info.SD_csd.DeviceSize + 1U) ; m_card_info.CardCapacity *= (1U << (m_card_info.SD_csd.DeviceSizeMul + 2U)); m_card_info.CardBlockSize = 1U << (m_card_info.SD_csd.RdBlockLen); m_card_info.CardCapacity *= m_card_info.CardBlockSize; } else if (m_card_type == ECardType::HIGH_CAPACITY) { /* Byte 7 */ tmp = static_cast<uint8_t>(m_CSD[1U] & 0x000000FFU); m_card_info.SD_csd.DeviceSize = (tmp & 0x3FU) << 16U; /* Byte 8 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0xFF000000U) >> 24U); m_card_info.SD_csd.DeviceSize |= (tmp << 8U); /* Byte 9 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0x00FF0000U) >> 16U); m_card_info.SD_csd.DeviceSize |= (tmp); /* Byte 10 */ tmp = static_cast<uint8_t>((m_CSD[2U] & 0x0000FF00U) >> 8U); m_card_info.CardCapacity = static_cast<uint64_t>((m_card_info.SD_csd.DeviceSize + 1U) * 512U * 1024U); m_card_info.CardBlockSize = 512U; } else { /* Not supported card type */ errorstate = ESDError::ERROR; } m_card_info.SD_csd.EraseGrSize = (tmp & 0x40U) >> 6U; m_card_info.SD_csd.EraseGrMul = static_cast<uint8_t>((tmp & 0x3FU) << 1U); /* Byte 11 */ tmp = static_cast<uint8_t>(m_CSD[2U] & 0x000000FFU); m_card_info.SD_csd.EraseGrMul |= (tmp & 0x80U) >> 7U; m_card_info.SD_csd.WrProtectGrSize = (tmp & 0x7FU); /* Byte 12 */ tmp = static_cast<uint8_t>((m_CSD[3U] & 0xFF000000U) >> 24U); m_card_info.SD_csd.WrProtectGrEnable = (tmp & 0x80U) >> 7U; m_card_info.SD_csd.ManDeflECC = (tmp & 0x60U) >> 5U; m_card_info.SD_csd.WrSpeedFact = (tmp & 0x1CU) >> 2U; m_card_info.SD_csd.MaxWrBlockLen = static_cast<uint8_t>((tmp & 0x03U) << 2U); /* Byte 13 */ tmp = static_cast<uint8_t>((m_CSD[3U] & 0x00FF0000U) >> 16U); m_card_info.SD_csd.MaxWrBlockLen |= (tmp & 0xC0U) >> 6U; m_card_info.SD_csd.WriteBlockPaPartial = (tmp & 0x20U) >> 5U; m_card_info.SD_csd.Reserved3 = 0U; m_card_info.SD_csd.ContentProtectAppli = (tmp & 0x01U); /* Byte 14 */ tmp = static_cast<uint8_t>((m_CSD[3U] & 0x0000FF00U) >> 8U); m_card_info.SD_csd.FileFormatGrouop = (tmp & 0x80U) >> 7U; m_card_info.SD_csd.CopyFlag = (tmp & 0x40U) >> 6U; m_card_info.SD_csd.PermWrProtect = (tmp & 0x20U) >> 5U; m_card_info.SD_csd.TempWrProtect = (tmp & 0x10U) >> 4U; m_card_info.SD_csd.FileFormat = (tmp & 0x0CU) >> 2U; m_card_info.SD_csd.ECC = (tmp & 0x03U); /* Byte 15 */ tmp = static_cast<uint8_t>(m_CSD[3U] & 0x000000FFU); m_card_info.SD_csd.CSD_CRC = (tmp & 0xFEU) >> 1U; m_card_info.SD_csd.Reserved4 = 1U; /* Byte 0 */ tmp = static_cast<uint8_t>((m_CID[0U] & 0xFF000000U) >> 24U); m_card_info.SD_cid.ManufacturerID = static_cast<uint8_t>(tmp); /* Byte 1 */ tmp = static_cast<uint8_t>((m_CID[0U] & 0x00FF0000U) >> 16U); m_card_info.SD_cid.OEM_AppliID = static_cast<uint8_t>(tmp << 8U); /* Byte 2 */ tmp = static_cast<uint8_t>((m_CID[0U] & 0x0000FF00U) >> 8U); m_card_info.SD_cid.OEM_AppliID |= tmp; /* Byte 3 */ tmp = static_cast<uint8_t>(m_CID[0U] & 0x000000FFU); m_card_info.SD_cid.ProdName1 = tmp << 24U; /* Byte 4 */ tmp = static_cast<uint8_t>((m_CID[1U] & 0xFF000000U) >> 24U); m_card_info.SD_cid.ProdName1 |= tmp << 16U; /* Byte 5 */ tmp = static_cast<uint8_t>((m_CID[1U] & 0x00FF0000U) >> 16U); m_card_info.SD_cid.ProdName1 |= tmp << 8U; /* Byte 6 */ tmp = static_cast<uint8_t>((m_CID[1U] & 0x0000FF00U) >> 8U); m_card_info.SD_cid.ProdName1 |= tmp; /* Byte 7 */ tmp = static_cast<uint8_t>(m_CID[1U] & 0x000000FFU); m_card_info.SD_cid.ProdName2 = static_cast<uint8_t>(tmp); /* Byte 8 */ tmp = static_cast<uint8_t>((m_CID[2U] & 0xFF000000U) >> 24U); m_card_info.SD_cid.ProdRev = static_cast<uint8_t>(tmp); /* Byte 9 */ tmp = static_cast<uint8_t>((m_CID[2U] & 0x00FF0000U) >> 16U); m_card_info.SD_cid.ProdSN = tmp << 24U; /* Byte 10 */ tmp = static_cast<uint8_t>((m_CID[2U] & 0x0000FF00U) >> 8U); m_card_info.SD_cid.ProdSN |= tmp << 16U; /* Byte 11 */ tmp = static_cast<uint8_t>(m_CID[2U] & 0x000000FFU); m_card_info.SD_cid.ProdSN |= tmp << 8U; /* Byte 12 */ tmp = static_cast<uint8_t>((m_CID[3U] & 0xFF000000U) >> 24U); m_card_info.SD_cid.ProdSN |= tmp; /* Byte 13 */ tmp = static_cast<uint8_t>((m_CID[3U] & 0x00FF0000U) >> 16U); m_card_info.SD_cid.Reserved1 |= (tmp & 0xF0U) >> 4U; m_card_info.SD_cid.ManufactDate = static_cast<uint16_t>((tmp & 0x0FU) << 8U); /* Byte 14 */ tmp = static_cast<uint8_t>((m_CID[3U] & 0x0000FF00U) >> 8U); m_card_info.SD_cid.ManufactDate |= tmp; /* Byte 15 */ tmp = static_cast<uint8_t>(m_CID[3U] & 0x000000FFU); m_card_info.SD_cid.CID_CRC = (tmp & 0xFEU) >> 1U; m_card_info.SD_cid.Reserved2 = 1U; return errorstate; } SD::ESDError SD::select_deselect(uint32_t addr) { send_command(addr, ECMD::SEL_DESEL_CARD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); return cmd_resp1_error(ECMD::SEL_DESEL_CARD); } SD::ESDError SD::is_card_programming(ECardState *status) { ESDError errorstate = ESDError::OK; __IO uint32_t responseR1 = 0U; send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::SEND_STATUS, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); while (!get_flag<SDIO_STA::EMasks::CCRCFAIL, SDIO_STA::EMasks::CMDREND, SDIO_STA::EMasks::CTIMEOUT>()) {} if (get_flag<SDIO_STA::EMasks::CTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::CTIMEOUT>(); return ESDError::CMD_RSP_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::CCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::CCRCFAIL>(); return ESDError::CMD_CRC_FAIL; } else { /* No error flag set */ } /* Check response received is of desired command */ if (get_cmd_response() != ECMD::SEND_STATUS) return ESDError::ILLEGAL_CMD; /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); /* We have received response, retrieve it for analysis */ responseR1 = get_response1(); /* Find out card status */ *status = static_cast<ECardState>((responseR1 >> 9U) & 0x0000000FU); if ((responseR1 & EOCRMasks::ERRORBITS) == SD_ALLZERO) return errorstate; if ((responseR1 & EOCRMasks::ADDR_OUT_OF_RANGE) == EOCRMasks::ADDR_OUT_OF_RANGE) return(ESDError::ADDR_OUT_OF_RANGE); if ((responseR1 & EOCRMasks::ADDR_MISALIGNED) == EOCRMasks::ADDR_MISALIGNED) return(ESDError::ADDR_MISALIGNED); if ((responseR1 & EOCRMasks::BLOCK_LEN_ERR) == EOCRMasks::BLOCK_LEN_ERR) return(ESDError::BLOCK_LEN_ERR); if ((responseR1 & EOCRMasks::ERASE_SEQ_ERR) == EOCRMasks::ERASE_SEQ_ERR) return(ESDError::ERASE_SEQ_ERR); if ((responseR1 & EOCRMasks::BAD_ERASE_PARAM) == EOCRMasks::BAD_ERASE_PARAM) return(ESDError::BAD_ERASE_PARAM); if ((responseR1 & EOCRMasks::WRITE_PROT_VIOLATION) == EOCRMasks::WRITE_PROT_VIOLATION) return(ESDError::WRITE_PROT_VIOLATION); if ((responseR1 & EOCRMasks::LOCK_UNLOCK_FAILED) == EOCRMasks::LOCK_UNLOCK_FAILED) return(ESDError::LOCK_UNLOCK_FAILED); if ((responseR1 & EOCRMasks::COM_CRC_FAILED) == EOCRMasks::COM_CRC_FAILED) return(ESDError::COM_CRC_FAILED); if ((responseR1 & EOCRMasks::ILLEGAL_CMD) == EOCRMasks::ILLEGAL_CMD) return(ESDError::ILLEGAL_CMD); if ((responseR1 & EOCRMasks::CARD_ECC_FAILED) == EOCRMasks::CARD_ECC_FAILED) return(ESDError::CARD_ECC_FAILED); if ((responseR1 & EOCRMasks::CC_ERROR) == EOCRMasks::CC_ERROR) return(ESDError::CC_ERROR); if ((responseR1 & EOCRMasks::GENERAL_UNKNOWN_ERROR) == EOCRMasks::GENERAL_UNKNOWN_ERROR) return(ESDError::GENERAL_UNKNOWN_ERROR); if ((responseR1 & EOCRMasks::STREAM_READ_UNDERRUN) == EOCRMasks::STREAM_READ_UNDERRUN) return(ESDError::STREAM_READ_UNDERRUN); if ((responseR1 & EOCRMasks::STREAM_WRITE_OVERRUN) == EOCRMasks::STREAM_WRITE_OVERRUN) return(ESDError::STREAM_WRITE_OVERRUN); if ((responseR1 & EOCRMasks::CID_CSD_OVERWRITE) == EOCRMasks::CID_CSD_OVERWRITE) return(ESDError::CID_CSD_OVERWRITE); if ((responseR1 & EOCRMasks::WP_ERASE_SKIP) == EOCRMasks::WP_ERASE_SKIP) return(ESDError::WP_ERASE_SKIP); if ((responseR1 & EOCRMasks::CARD_ECC_DISABLED) == EOCRMasks::CARD_ECC_DISABLED) return(ESDError::CARD_ECC_DISABLED); if ((responseR1 & EOCRMasks::ERASE_RESET) == EOCRMasks::ERASE_RESET) return(ESDError::ERASE_RESET); if ((responseR1 & EOCRMasks::AKE_SEQ_ERROR) == EOCRMasks::AKE_SEQ_ERROR) return(ESDError::AKE_SEQ_ERROR); return errorstate; } SD::ESDError SD::wide_bus_enable() { ESDError errorstate = ESDError::OK; uint32_t scr[2U] = {0U, 0U}; if ((get_response1() & SD_CARD_LOCKED) == SD_CARD_LOCKED) return ESDError::LOCK_UNLOCK_FAILED; /* Get SCR Register */ errorstate = find_SCR(scr); if (errorstate != ESDError::OK) return errorstate; /* If requested card supports wide bus operation */ if ((scr[1U] & SD_WIDE_BUS_SUPPORT) != SD_ALLZERO) { /* Send CMD55 APP_CMD with argument as card's RCA.*/ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_CMD); if(errorstate != ESDError::OK) return errorstate; /* Send ACMD6 APP_CMD with argument as 2 for wide bus mode */ send_command(2, ECMD::APP_SD_SET_BUSWIDTH, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_SD_SET_BUSWIDTH); } else return ESDError::REQUEST_NOT_APPLICABLE; return errorstate; } SD::ESDError SD::wide_bus_disable() { ESDError errorstate = ESDError::OK; uint32_t scr[2U] = {0U, 0U}; if ((get_response1() & SD_CARD_LOCKED) == SD_CARD_LOCKED) return ESDError::LOCK_UNLOCK_FAILED; /* Get SCR Register */ errorstate = find_SCR(scr); if (errorstate != ESDError::OK) return errorstate; /* If requested card supports 1 bit mode operation */ if ((scr[1U] & SD_SINGLE_BUS_SUPPORT) != SD_ALLZERO) { /* Send CMD55 APP_CMD with argument as card's RCA */ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_CMD); if(errorstate != ESDError::OK) return errorstate; /* Send ACMD6 APP_CMD with argument as 0 for single bus mode */ send_command(0, ECMD::APP_SD_SET_BUSWIDTH, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_SD_SET_BUSWIDTH); } else return ESDError::REQUEST_NOT_APPLICABLE; return errorstate; } SD::ESDError SD::find_SCR(uint32_t *scr) { ESDError errorstate = ESDError::OK; uint32_t index = 0U; uint32_t tempscr[2U] = {0U, 0U}; /* Set Block Size To 8 Bytes */ /* Send CMD55 APP_CMD with argument as card's RCA */ send_command(8, ECMD::SET_BLOCKLEN, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SET_BLOCKLEN); if (errorstate != ESDError::OK) return errorstate; /* Send CMD55 APP_CMD with argument as card's RCA */ send_command(static_cast<uint32_t>(m_RCA << 16U), ECMD::APP_CMD, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::APP_CMD); if (errorstate != ESDError::OK) return errorstate; data_config(SD_DATATIMEOUT, 8U, EDataBlockSize::_8B, ETransferDir::TO_SDIO, ETransferMode::BLOCK, EDPSM::ENABLE); /* Send ACMD51 SD_APP_SEND_SCR with argument as 0 */ send_command(0, ECMD::SD_APP_SEND_SCR, EResponse::SHORT, EWait::NO, ECPSM::ENABLE); /* Check for error conditions */ errorstate = cmd_resp1_error(ECMD::SD_APP_SEND_SCR); if (errorstate != ESDError::OK) return errorstate; #ifdef SDIO_STA_STBITERR while(!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND, SDIO_STA::EMasks::STBITERR>()) #else /* SDIO_STA_STBITERR not defined */ while(!get_flag<SDIO_STA::EMasks::RXOVERR, SDIO_STA::EMasks::DCRCFAIL, SDIO_STA::EMasks::DTIMEOUT, SDIO_STA::EMasks::DBCKEND>()) #endif /* SDIO_STA_STBITERR */ { if(get_flag<SDIO_STA::EMasks::RXDAVL>()) { *(tempscr + index) = read_FIFO(); index++; } } if (get_flag<SDIO_STA::EMasks::DTIMEOUT>()) { clear_flag<SDIO_STA::EMasks::DTIMEOUT>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::DCRCFAIL>()) { clear_flag<SDIO_STA::EMasks::DCRCFAIL>(); return ESDError::DATA_TIMEOUT; } else if (get_flag<SDIO_STA::EMasks::RXOVERR>()) { clear_flag<SDIO_STA::EMasks::RXOVERR>(); return ESDError::RX_OVERRUN; } #ifdef SDIO_STA_STBITERR else if (get_flag<SDIO_STA::EMasks::STBITERR>()) { clear_flag<SDIO_STA::EMasks::STBITERR>(); return ESDError::START_BIT_ERR; } #endif /* SDIO_STA_STBITERR */ else { /* No error flag set */ } /* Clear all the static flags */ clear_flag<SDIO_STATIC_FLAGS>(); *(scr + 1U) = ((tempscr[0U] & SD_0TO7BITS) << 24U) | ((tempscr[0U] & SD_8TO15BITS) << 8U) | ((tempscr[0U] & SD_16TO23BITS) >> 8U) | ((tempscr[0U] & SD_24TO31BITS) >> 24U); *(scr) = ((tempscr[1U] & SD_0TO7BITS) << 24U) | ((tempscr[1U] & SD_8TO15BITS) << 8U) | ((tempscr[1U] & SD_16TO23BITS) >> 8U) | ((tempscr[1U] & SD_24TO31BITS) >> 24U); return errorstate; } SD::ECardState SD::get_state() { uint32_t resp1 = 0U; if (send_status(&resp1) != ESDError::OK) return ECardState::ERROR; else return static_cast<ECardState>((resp1 >> 9U) & 0x0FU); } } void ISR::SDIO_IRQ() { ///TODO } #endif //STM32_USE_SD
33.231876
125
0.603546
andreili
a8a9e9cada22d02e04ef8d38652d2316a62eb347
1,786
cpp
C++
01-assignment/vigenere/main.cpp
Feqzz/DCS3101-1-20H
dcdccf63d9eaec23e37cda6827ce208f3cb35728
[ "MIT" ]
null
null
null
01-assignment/vigenere/main.cpp
Feqzz/DCS3101-1-20H
dcdccf63d9eaec23e37cda6827ce208f3cb35728
[ "MIT" ]
null
null
null
01-assignment/vigenere/main.cpp
Feqzz/DCS3101-1-20H
dcdccf63d9eaec23e37cda6827ce208f3cb35728
[ "MIT" ]
null
null
null
#include <iostream> #include <string> std::string vigenereEncrypt(std::string plaintext, std::string key) { char tmp[plaintext.size()]; int outOfBoundsCharacters = 0; for (int i = 0; i < plaintext.size(); i++) { bool isLowerCaseInput; bool isLowerCaseKey; if (static_cast<int>(plaintext[i]) > 64 && static_cast<int>(plaintext[i]) < 91) { isLowerCaseInput = false; } else if (static_cast<int>(plaintext[i]) > 96 && static_cast<int>(plaintext[i]) < 123) { isLowerCaseInput = true; } else { tmp[i] = plaintext[i]; outOfBoundsCharacters++; continue; } const int keyIndex = (i - outOfBoundsCharacters) % key.length(); if (static_cast<int>(key[keyIndex]) > 64 && static_cast<int>(key[keyIndex]) < 91) { isLowerCaseKey = false; } else if (static_cast<int>(key[keyIndex]) > 96 && static_cast<int>(key[keyIndex]) < 123) { isLowerCaseKey = true; } else { std::cout << "The key is illegal! Only alphabet characters are allowed." << std::endl; exit(1); } const int asciiGapInput = isLowerCaseInput ? 97 : 65; const int asciiGapKey = isLowerCaseKey ? 97 : 65; const int indexInAlphabetInput = static_cast<int>(plaintext[i]) - asciiGapInput; const int indexInAlphabetKey = static_cast<int>(key[keyIndex]) - asciiGapKey; tmp[i] = static_cast<char>(((indexInAlphabetInput + indexInAlphabetKey) % 26) + asciiGapInput); } return tmp; } void printUsage() { std::cout << "Usage: ./vigenere <text> <key1> ... <key N>" << std::endl; } int main(int argc, char** argv) { if (argc < 3) { printUsage(); exit(1); } std::string text = argv[1]; for (int i = 0; i < (argc - 2); i++) { const std::string key = argv[i + 2]; text = vigenereEncrypt(text, key); } std::cout << text << std::endl; return 0; }
23.194805
97
0.643897
Feqzz
a8ac83184d41a9ccaf4d1b6d51779cf607045d30
3,812
cc
C++
caffe2/mobile/contrib/opengl/operators/GLSigmoid.cc
shigengtian/caffe2
e19489d6acd17fea8ca98cd8e4b5b680e23a93c5
[ "Apache-2.0" ]
1
2018-03-26T13:25:03.000Z
2018-03-26T13:25:03.000Z
caffe2/mobile/contrib/opengl/operators/GLSigmoid.cc
shigengtian/caffe2
e19489d6acd17fea8ca98cd8e4b5b680e23a93c5
[ "Apache-2.0" ]
null
null
null
caffe2/mobile/contrib/opengl/operators/GLSigmoid.cc
shigengtian/caffe2
e19489d6acd17fea8ca98cd8e4b5b680e23a93c5
[ "Apache-2.0" ]
1
2018-12-20T09:14:48.000Z
2018-12-20T09:14:48.000Z
#include "../core/GLFilter.h" #include "../core/GLImage.h" #include "../core/ImageAllocator.h" #include "caffe2/core/operator.h" #include "caffe2/core/timer.h" #include <iostream> #include <vector> typedef enum { Sigmoid, Tanh } OpType; class GLSigmoid : public GLFilter { public: binding* inputData; binding* outputSize; GLSigmoid(OpType opType) : GLFilter("GLSigmoid", vertex_shader, fragment_shader, {BINDING(outputSize), BINDING(inputData)}, {/* no uniform blocks */}, {/* no attributes */}, {{"SIGMOID", caffe2::to_string(opType == Sigmoid)}, {"TANH", caffe2::to_string(opType == Tanh)}}) {} template <typename T> void sigmoid(const GLImageVector<T>& input_images, const GLImageVector<T>& output_images); static const char* fragment_shader; }; // MARK: GLSL const char* GLSigmoid::fragment_shader = R"GLSL(#version 300 es #define SIGMOID $(SIGMOID) #define TANH $(TANH) precision mediump float; precision mediump int; in highp vec2 v_texCoord; uniform ivec2 outputSize; TEXTURE_INPUT(inputData); TEXTURE_OUTPUT(0, outputData); void main() { ivec2 texelCoord = ivec2(v_texCoord * vec2(outputSize)); vec4 value = TEXTURE_LOAD(inputData, ivec2(texelCoord)); #if SIGMOID value = vec4(1.0) / (vec4(1.0) + exp(-value)); outputData = TEXTURE_STORE(value); #elif TANH value = tanh(value); outputData = TEXTURE_STORE(value); #endif } )GLSL"; template <typename T> void GLSigmoid::sigmoid(const GLImageVector<T>& input_images, const GLImageVector<T>& output_images) { for (int i = 0; i < input_images.size(); i++) { auto input_image = input_images[i]; auto output_image = output_images[i]; int input_slices = input_image->slices; int output_slices = output_image->slices; for (int is = 0; is < input_slices; is++) { run(std::vector<texture_attachment>({{input_image->textures[is], inputData}}), {output_image->textures.begin() + is, output_image->textures.begin() + is + 1}, [&]() { glUniform2i(outputSize->location, output_image->width, output_image->height); }, output_image->width, output_image->height); } } } namespace caffe2 { template <typename T, OpType opType> class OpenGLSigmoidOp final : public Operator<CPUContext>, ImageAllocator<T> { public: OpenGLSigmoidOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CPUContext>(operator_def, ws) {} bool RunOnDevice() override { const GLImageVector<T>& input = Inputs()[0]->template Get<GLImageVector<T>>(); const int num_images = input.size(); const int input_channels = input.channels(); const int input_width = input.width(); const int input_height = input.height(); const int output_channels = input_channels; const int output_width = input_width; const int output_height = input_height; int is_last = OperatorBase::GetSingleArgument<int>("is_last", 0); GLImageVector<T>* output = ImageAllocator<T>::newImage( num_images, output_width, output_height, output_channels, is_last); if (!_sigmoid) { _sigmoid.reset(new GLSigmoid(opType)); } _sigmoid->sigmoid(input, *output); Outputs()[0]->Reset(output); return true; } private: std::unique_ptr<GLSigmoid> _sigmoid; }; REGISTER_CPU_OPERATOR(OpenGLSigmoid, OpenGLSigmoidOp<float16_t, Sigmoid>); OPERATOR_SCHEMA(OpenGLSigmoid) .NumInputs(1) .NumOutputs(1) .AllowInplace({{0, 0}}) .IdenticalTypeAndShape(); REGISTER_CPU_OPERATOR(OpenGLTanh, OpenGLSigmoidOp<float16_t, Tanh>); OPERATOR_SCHEMA(OpenGLTanh) .NumInputs(1) .NumOutputs(1) .AllowInplace({{0, 0}}) .IdenticalTypeAndShape(); } // namespace caffe2
28.237037
98
0.673137
shigengtian
a8aef35415225fc1967e15a145501c3b551bd520
1,235
cpp
C++
test/gtx/gtx_scalar_multiplication.cpp
hrehfeld/glm_working
8dd5acc8ccc1fb8b6557670281c9786ee643e629
[ "MIT" ]
null
null
null
test/gtx/gtx_scalar_multiplication.cpp
hrehfeld/glm_working
8dd5acc8ccc1fb8b6557670281c9786ee643e629
[ "MIT" ]
null
null
null
test/gtx/gtx_scalar_multiplication.cpp
hrehfeld/glm_working
8dd5acc8ccc1fb8b6557670281c9786ee643e629
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2014-09-22 // Updated : 2014-09-22 // Licence : This source is under MIT licence // File : test/gtx/gtx_scalar_multiplication.cpp /////////////////////////////////////////////////////////////////////////////////////////////////// #include <glm/glm.hpp> #if GLM_HAS_TEMPLATE_ALIASES #include <glm/gtx/scalar_multiplication.hpp> int main() { int Error(0); glm::vec3 v(0.5, 3.1, -9.1); Error += glm::all(glm::equal(v, 1.0 * v)) ? 0 : 1; Error += glm::all(glm::equal(v, 1 * v)) ? 0 : 1; Error += glm::all(glm::equal(v, 1u * v)) ? 0 : 1; glm::mat3 m(1, 2, 3, 4, 5, 6, 7, 8, 9); glm::vec3 w = 0.5f * m * v; Error += glm::all(glm::equal((m*v)/2, w)) ? 0 : 1; Error += glm::all(glm::equal(m*(v/2), w)) ? 0 : 1; Error += glm::all(glm::equal((m/2)*v, w)) ? 0 : 1; Error += glm::all(glm::equal((0.5*m)*v, w)) ? 0 : 1; Error += glm::all(glm::equal(0.5*(m*v), w)) ? 0 : 1; return Error; } #else int main() { return 0; } #endif
28.068182
99
0.434008
hrehfeld
a8b03d386ec956bdb23cc703ac21b37af63514ff
23,329
cxx
C++
src/test/test_CalCalibSvc.cxx
fermi-lat/CalXtalResponse
3bd209402fa2d1ba3bb13e6a6228ea16881a3dc8
[ "BSD-3-Clause" ]
null
null
null
src/test/test_CalCalibSvc.cxx
fermi-lat/CalXtalResponse
3bd209402fa2d1ba3bb13e6a6228ea16881a3dc8
[ "BSD-3-Clause" ]
null
null
null
src/test/test_CalCalibSvc.cxx
fermi-lat/CalXtalResponse
3bd209402fa2d1ba3bb13e6a6228ea16881a3dc8
[ "BSD-3-Clause" ]
null
null
null
// $Header: /nfs/slac/g/glast/ground/cvs/CalXtalResponse/src/test/test_CalCalibSvc.cxx,v 1.2 2008/05/19 21:49:00 chehtman Exp $ /** @file @author Z.Fewtrell */ // LOCAL INCLUDES #include "test_CalCalibSvc.h" #include "CalXtalResponse/ICalCalibSvc.h" #include "test_util.h" #include "TestCfg.h" // GLAST INCLUDES #include "CalUtil/stl_util.h" // EXTLIB INCLUDES #include "CLHEP/Random/RandFlat.h" // STD INCLUDES #include <string> #include <cmath> using namespace CalUtil; using namespace std; using namespace CalXtalResponse; namespace { /// relative tolerance for calibration values (should only see /// rounding issues ) static const float MAX_CALIB_DIFF = .001; }; test_CalCalibSvc::TestCalibSet::TestCalibSet(const string &pedTXTPath, const string &cidac2adcTXTPath, const string &asymTXTPath, const string &mpdTXTPath, const string &tholdCITXTPath) { m_calPed.readTXT(pedTXTPath); m_cidac2adc.readTXT(cidac2adcTXTPath); m_calAsym.readTXT(asymTXTPath); m_calMPD.readTXT(mpdTXTPath); m_calTholdCI.readTXT(tholdCITXTPath); } /** Algorithm: - if appropriate tower module is missing, test for correct answer in this case - else test each major calibration type (ped, intNonlin, asymmetry, mevPerDAC, tholdCI) */ StatusCode test_CalCalibSvc::testXtal(const XtalIdx xtalIdx, ICalCalibSvc &calCalibSvc, const TestCalibSet &calibSet, const TwrSet &twrSet) { StatusCode sc; if (twrSet.find(xtalIdx.getTwr()) == twrSet.end()) return testMissingXtal(xtalIdx, calCalibSvc); sc = testPed(xtalIdx, calCalibSvc, calibSet); if (sc.isFailure()) return sc; sc = testINL(xtalIdx, calCalibSvc, calibSet); if (sc.isFailure()) return sc; sc = testAsym(xtalIdx, calCalibSvc, calibSet); if (sc.isFailure()) return sc; sc = testMPD(xtalIdx, calCalibSvc, calibSet); if (sc.isFailure()) return sc; sc = testTholdCI(xtalIdx, calCalibSvc, calibSet); if (sc.isFailure()) return sc; if (testFaceSignal(xtalIdx, calCalibSvc).isFailure()) return StatusCode::FAILURE; return StatusCode::SUCCESS; } /// check calCalibSvc values against TestCalibSet StatusCode test_CalCalibSvc::testPed(const XtalIdx xtalIdx, ICalCalibSvc &calCalibSvc, const TestCalibSet &calibSet) { for (XtalRng xRng; xRng.isValid(); xRng++) { const RngIdx rngIdx(xtalIdx, xRng); float val,sig; StatusCode sc = calCalibSvc.getPed(rngIdx,val); StatusCode scs = calCalibSvc.getPedSig(rngIdx,sig); if (sc.isFailure() || scs.isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "missing pedestal: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } // check calibs against test values (should be close to w/in // rounding diff if (!smart_compare(val, calibSet.m_calPed.getPed(rngIdx), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid pedestal: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } // check calibs against test values (should be close to w/in // rounding diff if (!smart_compare(sig, calibSet.m_calPed.getPedSig(rngIdx), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid pedestal sigma: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } } return StatusCode::SUCCESS; } /** Algorithm: - check calCalibSvc values against TestCalibSet - check all points in spline (ADC & CIDAC) - for each point in spline, evaluate spline function both ways & check answer. */ StatusCode test_CalCalibSvc::testINL(const XtalIdx xtalIdx, ICalCalibSvc &calCalibSvc, const TestCalibSet &calibSet) { for (XtalRng xRng; xRng.isValid(); xRng++) { const RngIdx rngIdx(xtalIdx, xRng); vector<float> const*const inlCIDAC = calCalibSvc.getInlCIDAC(rngIdx); if (!inlCIDAC) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "missing INL CIDAC data: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } const vector<float> &cidacTest = calibSet.m_cidac2adc.getPtsDAC(rngIdx); if (!compare_collection(cidacTest.begin(), cidacTest.end(), inlCIDAC->begin(), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "invalid INL CIDAC data: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } vector<float> const*const inlADC = calCalibSvc.getInlAdc(rngIdx); if (!inlADC) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "missing INL ADC data: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } const vector<float> &adcTest = calibSet.m_cidac2adc.getPtsADC(rngIdx); if (!compare_collection(adcTest.begin(), adcTest.end(), inlADC->begin(), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "invalid INL ADC data: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } /// eval splines @ each point StatusCode sc; float tmp = 0; for (unsigned short i = 0; i < inlADC->size(); i++) { sc = calCalibSvc.evalCIDAC(rngIdx, inlADC->at(i), tmp); if (sc.isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "INL spline failure: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(tmp, inlCIDAC->at(i), MAX_SPLINE_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "bad INL spline value: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } sc = calCalibSvc.evalADC(rngIdx, inlCIDAC->at(i), tmp); if (sc.isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "INL spline failure: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(tmp, inlADC->at(i), MAX_SPLINE_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "bad INL spline value: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } } } return StatusCode::SUCCESS; } /** check calCalibSvc values against TestCalibSet Algorithm: - check asymmetry value & xpos value for each point in each asym spline. - @ each point evalute spline function both ways & compare results against known answers. - test asymCtr method against evalAsym(pos=0) */ StatusCode test_CalCalibSvc::testAsym(const XtalIdx xtalIdx, ICalCalibSvc &calCalibSvc, const TestCalibSet &calibSet) { StatusCode sc; CalibData::CalAsym const*const asymCalib = calCalibSvc.getAsym(xtalIdx); if (!asymCalib) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "missing Asym data: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } CalVec<AsymType, const vector<CalibData::ValSig> *> db_asym; db_asym[ASYM_LL] = asymCalib->getBig(); db_asym[ASYM_SS] = asymCalib->getSmall(); db_asym[ASYM_LS] = asymCalib->getNSmallPBig(); db_asym[ASYM_SL] = asymCalib->getPSmallNBig(); CalibData::Xpos const *const xpos = calCalibSvc.getAsymXpos(); if (!xpos) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "missing Asym xpos data: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } const vector<float> *xvals = xpos->getVals(); if (!xvals) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "missing Asym xpos data: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } for (AsymType asymType; asymType.isValid(); asymType++) { const vector<float> &asymTest = calibSet.m_calAsym.getPtsAsym(xtalIdx, asymType); const vector<float> &errTest = calibSet.m_calAsym.getPtsErr(xtalIdx, asymType); if (db_asym[asymType]->size() == 0) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "missing Asym data: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } if (db_asym[asymType]->size() != asymTest.size()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "invalid Asym data: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } for (unsigned short i = 0; i < asymTest.size(); i++) { if (!smart_compare(db_asym[asymType]->at(i).getVal(), asymTest[i], MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "invalid Asym data: " << xtalIdx.toStr() << " " << asymType.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(db_asym[asymType]->at(i).getSig(), errTest[i], MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "invalid Asym data: " << xtalIdx.toStr() << " " << asymType.toStr() << endreq; return StatusCode::FAILURE; } //-- test spline methods float tmp = 0; sc = calCalibSvc.evalPos(xtalIdx, asymType, db_asym[asymType]->at(i).getVal(), tmp); if (sc.isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Asym spline failure: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(tmp, xvals->at(i), MAX_SPLINE_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "bad Asym spline value: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } sc = calCalibSvc.evalAsym(xtalIdx, asymType, xvals->at(i), tmp); if (sc.isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Asym spline failure: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(tmp, db_asym[asymType]->at(i).getVal(), MAX_SPLINE_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "bad Asym spline value: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } } // asym point loop //-- test AsymCtr method --// float tmp, tmp2 = 0; sc = calCalibSvc.getAsymCtr(xtalIdx,asymType, tmp); if (sc.isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "getAsymCtr() failure: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } sc = calCalibSvc.evalAsym(xtalIdx, asymType, 0, tmp2); if (sc.isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Asym spline failure: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(tmp, tmp2, MAX_SPLINE_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "getAsymCtr() failure: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } } return StatusCode::SUCCESS; } /// test calCalibSvc values against TestCalibSet StatusCode test_CalCalibSvc::testMPD(const XtalIdx xtalIdx, ICalCalibSvc &calCalibSvc, const TestCalibSet &calibSet) { CalibData::CalMevPerDac const*const mpdCalib = calCalibSvc.getMPD(xtalIdx); if (!mpdCalib) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "MISSING mevPerDAC: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } CalVec<DiodeNum, float> mpd, sig; mpd[CalUtil::LRG_DIODE] = mpdCalib->getBig()->getVal(); mpd[CalUtil::SM_DIODE] = mpdCalib->getSmall()->getVal(); sig[CalUtil::LRG_DIODE] = mpdCalib->getBig()->getSig(); sig[CalUtil::SM_DIODE] = mpdCalib->getSmall()->getSig(); for (DiodeNum diode; diode.isValid(); diode++) { if (!smart_compare(mpd[diode], calibSet.m_calMPD.getMPD(xtalIdx, diode), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid mevPerDAC: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(sig[diode], calibSet.m_calMPD.getMPDErr(xtalIdx, diode), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid mevPerDAC sigma: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } } return StatusCode::SUCCESS; } /// test calCalibSvc values against TestCalibSet StatusCode test_CalCalibSvc::testTholdCI(const XtalIdx xtalIdx, ICalCalibSvc &calCalibSvc, const TestCalibSet &calibSet) { for (FaceNum face; face.isValid(); face++) { const FaceIdx faceIdx(xtalIdx, face); CalibData::CalTholdCI const*const tholdCICalib = calCalibSvc.getTholdCI(faceIdx); if (!tholdCICalib) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "MISSING tholdCI: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(tholdCICalib->getLAC()->getVal(), calibSet.m_calTholdCI.getLACThresh(faceIdx), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid LAC threshold: " << faceIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(tholdCICalib->getFLE()->getVal(), calibSet.m_calTholdCI.getFLEThresh(faceIdx), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid FLE threshold: " << faceIdx.toStr() << endreq; return StatusCode::FAILURE; } if (!smart_compare(tholdCICalib->getFHE()->getVal(), calibSet.m_calTholdCI.getFHEThresh(faceIdx), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid FHE threshold: " << faceIdx.toStr() << endreq; return StatusCode::FAILURE; } for (RngNum rng; rng.isValid(); rng++) { const RngIdx rngIdx(faceIdx, rng); if (!smart_compare(tholdCICalib->getULD(rng.val())->getVal(), calibSet.m_calTholdCI.getULDThresh(rngIdx), MAX_CALIB_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid ULD threshold: " << faceIdx.toStr() << endreq; return StatusCode::FAILURE; } } } return StatusCode::SUCCESS; } /// ensure that correct answer is always returned in case of empty /// tower bay for all methods in CalCalibSvc. StatusCode test_CalCalibSvc::testMissingXtal(const XtalIdx xtalIdx, ICalCalibSvc &calCalibSvc) { StatusCode sc; //-- PER XTAL CALIBRATIONS --// if (calCalibSvc.getMPD(xtalIdx) != 0) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "MPD calibrations for empty tower returned: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } if (calCalibSvc.getAsym(xtalIdx) != 0) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "ASYM calibrations for empty tower returned: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } float tmp; //-- PER ASYM TYPE --// for (AsymType asymType; asymType.isValid(); asymType++) { sc = calCalibSvc.evalAsym(xtalIdx, asymType, 0, tmp); if (sc.isSuccess()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "ASYM calibrations for empty tower returned: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } sc = calCalibSvc.evalPos(xtalIdx, asymType, 0, tmp); if (sc.isSuccess()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "ASYM calibrations for empty tower returned: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } sc = calCalibSvc.getAsymCtr(xtalIdx, asymType, tmp); if (sc.isSuccess()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "ASYM calibrations for empty tower returned: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } } // asym type //-- PER FACE CALIBRATIONS --// for (FaceNum face; face.isValid(); face++) { const FaceIdx faceIdx(xtalIdx,face); if (calCalibSvc.getTholdCI(faceIdx) != 0) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "tholdCI calibrations for empty tower returned: " << faceIdx.toStr() << endreq; return StatusCode::FAILURE; } } //-- PER RANGE CALIBRATIONS --// for (XtalRng xRng; xRng.isValid(); xRng++) { const RngIdx rngIdx(xtalIdx, xRng); float ped; if (!calCalibSvc.getPed(rngIdx,ped).isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Ped calibrations for empty tower returned: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } if (calCalibSvc.getInlAdc(rngIdx) != 0) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "INL calibrations for empty tower returned: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } if (calCalibSvc.getInlCIDAC(rngIdx) != 0) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "INL calibrations for empty tower returned: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } sc = calCalibSvc.evalCIDAC(rngIdx, 0, tmp); if (sc.isSuccess()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "INL calibrations for empty tower returned: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } sc = calCalibSvc.evalADC(rngIdx, 0, tmp); if (sc.isSuccess()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "INL calibrations for empty tower returned: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } sc = calCalibSvc.evalFaceSignal(rngIdx, 0, tmp); if (sc.isSuccess()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "FaceSignal calibrations for empty tower returned: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } } // rngIdx loop return StatusCode::SUCCESS; } /// loop through each selected xtal in TestCfg & verify individutally. StatusCode test_CalCalibSvc::verify(ICalCalibSvc &calCalibSvc, const test_CalCalibSvc::TestCalibSet &calibSet, const CalXtalResponse::TestCfg &testCfg, const TwrSet &twrSet) { StatusCode sc; MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); // xtal loop for (TestCfg::XtalList::const_iterator xtalIt(testCfg.testXtals.begin()); xtalIt != testCfg.testXtals.end(); xtalIt++) { sc = testXtal(*xtalIt, calCalibSvc, calibSet, twrSet); if (sc.isFailure()) return sc; } // xtal loop return StatusCode::SUCCESS; } /// test calCalibSvc->evalFaceSignal() against my own hand-calculated version. StatusCode test_CalCalibSvc::testFaceSignal(const CalUtil::XtalIdx xtalIdx, ICalCalibSvc &calCalibSvc) { /// will need mevPerDAC for calculation CalibData::CalMevPerDac const*const mpdCalib = calCalibSvc.getMPD(xtalIdx); if (!mpdCalib) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "MISSING mevPerDAC: " << xtalIdx.toStr() << endreq; return StatusCode::FAILURE; } CalVec<DiodeNum, float> mpd, sig; mpd[CalUtil::LRG_DIODE] = mpdCalib->getBig()->getVal(); mpd[CalUtil::SM_DIODE] = mpdCalib->getSmall()->getVal(); /// test all adc channels in xtal for (XtalRng xRng; xRng.isValid(); xRng++) { const RngIdx rngIdx(xtalIdx, xRng); /// get pedestal float ped; StatusCode sc = calCalibSvc.getPed(rngIdx,ped); if (sc.isFailure()) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "missing pedestal: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } /// select adc value within adc range. const float testADC = CLHEP::RandFlat::shoot(4095-ped); float testCIDAC(0); if (calCalibSvc.evalCIDAC(rngIdx, testADC, testCIDAC).isFailure()) return StatusCode::FAILURE; /// get value to test float faceSignal(0); if (calCalibSvc.evalFaceSignal(rngIdx, testADC, faceSignal).isFailure()) return StatusCode::FAILURE; // log(posDAC/negDAC) float asymCtr(0); const DiodeNum diode(xRng.getRng().getDiode()); if (calCalibSvc.getAsymCtr(xtalIdx, AsymType(diode,diode), asymCtr).isFailure()) return StatusCode::FAILURE; // posDAC/negDAC const float asymRatio(exp(asymCtr)); const FaceNum face(xRng.getFace()); float meanCIDAC = 0; // asymRatio = POSDAC/NEGDAC // meanDAC = sqrt(POSDAC*NEGDAC) switch ((idents::CalXtalId::XtalFace)face) { case idents::CalXtalId::POS: // NEGDAC = POSDAC/asym // mean = sqrt(POSDAC*POSDAC/asym) meanCIDAC = sqrt(testCIDAC*testCIDAC/asymRatio); break; case idents::CalXtalId::NEG: // POSDAC = NEGDAC*asym // mean = sqrt(NEGDAC*NEGDAC*asym) meanCIDAC = sqrt(testCIDAC*testCIDAC*asymRatio); break; default: MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid FaceNum" << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } const float testMeV = mpd[diode]*meanCIDAC; if (!smart_compare(testMeV, faceSignal, MAX_RECON_DIFF)) { MsgStream msglog(m_msgSvc, "test_CalCalibSvc"); msglog << MSG::ERROR << "Invalid faceSignal: " << rngIdx.toStr() << endreq; return StatusCode::FAILURE; } } return StatusCode::SUCCESS; }
35.890769
131
0.617858
fermi-lat
a8b15c63f821b46ef33930a7c9e76bce717e51a2
33,264
cpp
C++
frmts/pcidsk/sdk/blockdir/asciitiledir.cpp
sthagen/OSGeo-gdal
07631e3f3352f4f7453344b1cb73c6b681609d38
[ "Apache-2.0" ]
null
null
null
frmts/pcidsk/sdk/blockdir/asciitiledir.cpp
sthagen/OSGeo-gdal
07631e3f3352f4f7453344b1cb73c6b681609d38
[ "Apache-2.0" ]
null
null
null
frmts/pcidsk/sdk/blockdir/asciitiledir.cpp
sthagen/OSGeo-gdal
07631e3f3352f4f7453344b1cb73c6b681609d38
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * Purpose: Block directory API. * ****************************************************************************** * Copyright (c) 2011 * PCI Geomatics, 90 Allstate Parkway, Markham, Ontario, Canada. * * 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 "blockdir/asciitiledir.h" #include "blockdir/asciitilelayer.h" #include "blockdir/blockfile.h" #include "core/pcidsk_utils.h" #include "core/pcidsk_scanint.h" #include "pcidsk_exception.h" #include "pcidsk_buffer.h" #include <cstdlib> #include <cstring> #include <cstdio> #include <algorithm> #include <limits> #include <set> using namespace PCIDSK; #define ASCII_TILEDIR_VERSION 1 #define SYS_BLOCK_SIZE 8192 #define SYS_BLOCK_INFO_SIZE 28 #define SYS_BLOCK_LAYER_INFO_SIZE 24 struct SysBlockInfo { uint16 nSegment; uint32 nStartBlock; uint32 nNextBlock; }; typedef std::vector<SysBlockInfo> SysBlockInfoList; /************************************************************************/ /* GetBlockList() */ /************************************************************************/ static BlockInfoList GetBlockList(const SysBlockInfoList & oBlockInfoList, uint32 iStartBlock) { uint32 iBlock = iStartBlock; BlockInfoList oBlockList; oBlockList.reserve(oBlockInfoList.size()); while (iBlock < oBlockInfoList.size() && oBlockList.size() <= oBlockInfoList.size()) { const SysBlockInfo * psBlockInfo = &oBlockInfoList[iBlock]; BlockInfo sBlock; sBlock.nSegment = psBlockInfo->nSegment; sBlock.nStartBlock = psBlockInfo->nStartBlock; oBlockList.push_back(sBlock); iBlock = psBlockInfo->nNextBlock; } // If the block list is larger than the block info list, it means that the // file is corrupted so look for a loop in the block list. if (oBlockList.size() > oBlockInfoList.size()) { iBlock = iStartBlock; std::set<uint32> oBlockSet; oBlockList.clear(); while (iBlock < oBlockInfoList.size()) { const SysBlockInfo * psBlockInfo = &oBlockInfoList[iBlock]; BlockInfo sBlock; sBlock.nSegment = psBlockInfo->nSegment; sBlock.nStartBlock = psBlockInfo->nStartBlock; oBlockList.push_back(sBlock); oBlockSet.insert(iBlock); iBlock = psBlockInfo->nNextBlock; if (oBlockSet.find(iBlock) != oBlockSet.end()) break; } } return oBlockList; } /************************************************************************/ /* GetOptimizedDirSize() */ /************************************************************************/ size_t AsciiTileDir::GetOptimizedDirSize(BlockFile * poFile) { std::string oFileOptions = poFile->GetFileOptions(); for (char & chIter : oFileOptions) chIter = (char) toupper((uchar) chIter); // Compute the ratio. double dfRatio = 0.0; // The 35% is for the overviews. if (oFileOptions.find("TILED") != std::string::npos) dfRatio = 1.35; else dfRatio = 0.35; // The 5% is for the new blocks. dfRatio += 0.05; double dfFileSize = poFile->GetImageFileSize() * dfRatio; uint32 nBlockSize = SYS_BLOCK_SIZE; uint64 nBlockCount = (uint64) (dfFileSize / nBlockSize); uint64 nLayerCount = poFile->GetChannels(); // The 12 is for the overviews. nLayerCount *= 12; uint64 nDirSize = 512 + (nBlockCount * SYS_BLOCK_INFO_SIZE + nLayerCount * SYS_BLOCK_LAYER_INFO_SIZE + nLayerCount * sizeof(TileLayerInfo)); #if SIZEOF_VOIDP < 8 if (nDirSize > std::numeric_limits<size_t>::max()) return ThrowPCIDSKException(0, "Unable to create extremely large file on 32-bit system."); #endif return static_cast<size_t>(nDirSize); } /************************************************************************/ /* AsciiTileDir() */ /************************************************************************/ /** * Constructor. * * @param poFile The associated file object. * @param nSegment The segment of the block directory. */ AsciiTileDir::AsciiTileDir(BlockFile * poFile, uint16 nSegment) : BlockTileDir(poFile, nSegment) { // Read the block directory header from disk. uint8 abyHeader[512]; mpoFile->ReadFromSegment(mnSegment, abyHeader, 0, 512); // Get the version of the block directory. mnVersion = ScanInt3(abyHeader + 7); // Read the block directory info from the header. msBlockDir.nLayerCount = ScanInt8(abyHeader + 10); msBlockDir.nBlockCount = ScanInt8(abyHeader + 18); msBlockDir.nFirstFreeBlock = ScanInt8(abyHeader + 26); // The third last byte is for the endianness. mchEndianness = abyHeader[512 - 3]; mbNeedsSwap = (mchEndianness == 'B' ? !BigEndianSystem() : BigEndianSystem()); // The last 2 bytes of the header are for the validity info. memcpy(&mnValidInfo, abyHeader + 512 - 2, 2); SwapValue(&mnValidInfo); // Check that we support the tile directory version. if (mnVersion > ASCII_TILEDIR_VERSION) { ThrowPCIDSKException("The tile directory version %d is not supported.", mnVersion); return; } // The size of the block layers. uint64 nReadSize = (static_cast<uint64>(msBlockDir.nBlockCount) * SYS_BLOCK_INFO_SIZE + static_cast<uint64>(msBlockDir.nLayerCount) * SYS_BLOCK_LAYER_INFO_SIZE); if (mpoFile->IsCorruptedSegment(mnSegment, 512, nReadSize)) { ThrowPCIDSKException("The tile directory is corrupted."); return; } #if SIZEOF_VOIDP < 8 if (nReadSize > std::numeric_limits<size_t>::max()) { ThrowPCIDSKException("Unable to open extremely large file on 32-bit system."); return; } #endif // Initialize the block layers. try { moLayerInfoList.resize(msBlockDir.nLayerCount); moTileLayerInfoList.resize(msBlockDir.nLayerCount); moLayerList.resize(msBlockDir.nLayerCount); } catch (const std::exception & ex) { ThrowPCIDSKException("Out of memory in AsciiTileDir(): %s", ex.what()); return; } for (uint32 iLayer = 0; iLayer < msBlockDir.nLayerCount; iLayer++) { moLayerInfoList[iLayer] = new BlockLayerInfo; moTileLayerInfoList[iLayer] = new TileLayerInfo; moLayerList[iLayer] = new AsciiTileLayer(this, iLayer, moLayerInfoList[iLayer], moTileLayerInfoList[iLayer]); } // Read the block directory from disk. if (memcmp(abyHeader + 128, "SUBVERSION 1", 12) != 0) { ReadFullDir(); for (uint32 iLayer = 0; iLayer < msBlockDir.nLayerCount; iLayer++) GetTileLayer(iLayer)->ReadHeader(); } else { ReadPartialDir(); } // Check if any of the tile layers are corrupted. for (BlockLayer * poLayer : moLayerList) { BlockTileLayer * poTileLayer = dynamic_cast<BlockTileLayer *>(poLayer); if (poTileLayer == nullptr || poTileLayer->IsCorrupted()) { ThrowPCIDSKException("The tile directory is corrupted."); return; } } } /************************************************************************/ /* AsciiTileDir() */ /************************************************************************/ /** * Constructor. * * @param poFile The associated file object. * @param nSegment The segment of the block directory. * @param nBlockSize The size of the blocks. */ AsciiTileDir::AsciiTileDir(BlockFile * poFile, uint16 nSegment, CPL_UNUSED uint32 nBlockSize) : BlockTileDir(poFile, nSegment, ASCII_TILEDIR_VERSION) { // Initialize the directory info. msBlockDir.nLayerCount = 0; msBlockDir.nBlockCount = 0; msBlockDir.nFirstFreeBlock = 0; // Create an empty free block layer. msFreeBlockLayer.nLayerType = BLTFree; msFreeBlockLayer.nStartBlock = INVALID_BLOCK; msFreeBlockLayer.nBlockCount = 0; msFreeBlockLayer.nLayerSize = 0; mpoFreeBlockLayer = new AsciiTileLayer(this, INVALID_LAYER, &msFreeBlockLayer, nullptr); } /************************************************************************/ /* GetTileLayer() */ /************************************************************************/ /** * Gets the block layer at the specified index. * * @param iLayer The index of the block layer. * * @return The block layer at the specified index. */ AsciiTileLayer * AsciiTileDir::GetTileLayer(uint32 iLayer) { return (AsciiTileLayer *) BlockDir::GetLayer(iLayer); } /************************************************************************/ /* GetBlockSize() */ /************************************************************************/ /** * Gets the block size of the block directory. * * @return The block size of the block directory. */ uint32 AsciiTileDir::GetBlockSize(void) const { return SYS_BLOCK_SIZE; } /************************************************************************/ /* ReadFullDir() */ /************************************************************************/ void AsciiTileDir::ReadFullDir(void) { // The size of the block layers. uint64 nReadSize = (static_cast<uint64>(msBlockDir.nBlockCount) * SYS_BLOCK_INFO_SIZE + static_cast<uint64>(msBlockDir.nLayerCount) * SYS_BLOCK_LAYER_INFO_SIZE); if (mpoFile->IsCorruptedSegment(mnSegment, 512, nReadSize)) return ThrowPCIDSKException("The tile directory is corrupted."); #if SIZEOF_VOIDP < 8 if (nReadSize > std::numeric_limits<size_t>::max()) return ThrowPCIDSKException("Unable to open extremely large file on 32-bit system."); #endif // Read the block layers from disk. uint8 * pabyBlockDir = (uint8 *) malloc(static_cast<size_t>(nReadSize)); if (pabyBlockDir == nullptr) return ThrowPCIDSKException("Out of memory in AsciiTileDir::ReadFullDir()."); PCIDSKBuffer oBlockDirAutoPtr; oBlockDirAutoPtr.buffer = (char *) pabyBlockDir; uint8 * pabyBlockDirIter = pabyBlockDir; mpoFile->ReadFromSegment(mnSegment, pabyBlockDir, 512, nReadSize); // Read the block list. SysBlockInfoList oBlockInfoList(msBlockDir.nBlockCount); for (uint32 iBlock = 0; iBlock < msBlockDir.nBlockCount; iBlock++) { SysBlockInfo * psBlock = &oBlockInfoList[iBlock]; psBlock->nSegment = ScanInt4(pabyBlockDirIter); pabyBlockDirIter += 4; psBlock->nStartBlock = ScanInt8(pabyBlockDirIter); pabyBlockDirIter += 8; //psBlock->nLayer = ScanInt8(pabyBlockDirIter); pabyBlockDirIter += 8; psBlock->nNextBlock = ScanInt8(pabyBlockDirIter); pabyBlockDirIter += 8; } // Read the block layers. for (uint32 iLayer = 0; iLayer < msBlockDir.nLayerCount; iLayer++) { BlockLayerInfo * psLayer = moLayerInfoList[iLayer]; psLayer->nLayerType = ScanInt4(pabyBlockDirIter); pabyBlockDirIter += 4; psLayer->nStartBlock = ScanInt8(pabyBlockDirIter); pabyBlockDirIter += 8; psLayer->nLayerSize = ScanInt12(pabyBlockDirIter); pabyBlockDirIter += 12; } // Create all the block layers. for (uint32 iLayer = 0; iLayer < msBlockDir.nLayerCount; iLayer++) { BlockLayerInfo * psLayer = moLayerInfoList[iLayer]; AsciiTileLayer * poLayer = GetTileLayer((uint32) iLayer); poLayer->moBlockList = GetBlockList(oBlockInfoList, psLayer->nStartBlock); // We need to validate the block count field. psLayer->nBlockCount = (uint32) poLayer->moBlockList.size(); } // Create the free block layer. msFreeBlockLayer.nLayerType = BLTFree; msFreeBlockLayer.nStartBlock = msBlockDir.nFirstFreeBlock; msFreeBlockLayer.nBlockCount = 0; msFreeBlockLayer.nLayerSize = 0; mpoFreeBlockLayer = new AsciiTileLayer(this, INVALID_LAYER, &msFreeBlockLayer, nullptr); ((AsciiTileLayer *) mpoFreeBlockLayer)->moBlockList = GetBlockList(oBlockInfoList, msFreeBlockLayer.nStartBlock); // We need to validate the block count field. msFreeBlockLayer.nBlockCount = (uint32) ((AsciiTileLayer *) mpoFreeBlockLayer)->moBlockList.size(); } /************************************************************************/ /* ReadPartialDir() */ /************************************************************************/ void AsciiTileDir::ReadPartialDir(void) { // The offset of the block layers. uint64 nOffset = static_cast<uint64>(msBlockDir.nBlockCount) * SYS_BLOCK_INFO_SIZE; // The size of the block layers. uint64 nReadSize = (static_cast<uint64>(msBlockDir.nLayerCount) * SYS_BLOCK_LAYER_INFO_SIZE + static_cast<uint64>(msBlockDir.nLayerCount) * sizeof(TileLayerInfo)); if (mpoFile->IsCorruptedSegment(mnSegment, 512 + nOffset, nReadSize)) return ThrowPCIDSKException("The tile directory is corrupted."); #if SIZEOF_VOIDP < 8 if (nReadSize > std::numeric_limits<size_t>::max()) return ThrowPCIDSKException("Unable to open extremely large file on 32-bit system."); #endif // Read the block layers from disk. uint8 * pabyBlockDir = (uint8 *) malloc(static_cast<size_t>(nReadSize)); if (pabyBlockDir == nullptr) return ThrowPCIDSKException("Out of memory in AsciiTileDir::ReadPartialDir()."); PCIDSKBuffer oBlockDirAutoPtr; oBlockDirAutoPtr.buffer = (char *) pabyBlockDir; uint8 * pabyBlockDirIter = pabyBlockDir; mpoFile->ReadFromSegment(mnSegment, pabyBlockDir, 512 + nOffset, nReadSize); // Read the block layers. BlockLayerInfo * psPreviousLayer = nullptr; for (uint32 iLayer = 0; iLayer < msBlockDir.nLayerCount; iLayer++) { BlockLayerInfo * psLayer = moLayerInfoList[iLayer]; psLayer->nLayerType = ScanInt4(pabyBlockDirIter); pabyBlockDirIter += 4; psLayer->nStartBlock = ScanInt8(pabyBlockDirIter); pabyBlockDirIter += 8; psLayer->nLayerSize = ScanInt12(pabyBlockDirIter); pabyBlockDirIter += 12; if (psLayer->nStartBlock != INVALID_BLOCK) { if (psPreviousLayer) { if (psLayer->nStartBlock < psPreviousLayer->nStartBlock) return ThrowPCIDSKException("The tile directory is corrupted."); psPreviousLayer->nBlockCount = psLayer->nStartBlock - psPreviousLayer->nStartBlock; } psPreviousLayer = psLayer; } else { psLayer->nBlockCount = 0; } } // Read the tile layers. for (uint32 iLayer = 0; iLayer < msBlockDir.nLayerCount; iLayer++) { size_t nSize = sizeof(TileLayerInfo); SwapTileLayer((TileLayerInfo *) pabyBlockDirIter); memcpy(moTileLayerInfoList[iLayer], pabyBlockDirIter, nSize); pabyBlockDirIter += nSize; } // Read the free block layer. msFreeBlockLayer.nLayerType = BLTFree; msFreeBlockLayer.nStartBlock = msBlockDir.nFirstFreeBlock; msFreeBlockLayer.nBlockCount = 0; msFreeBlockLayer.nLayerSize = 0; if (msFreeBlockLayer.nStartBlock != INVALID_BLOCK) { if (psPreviousLayer) { if (msFreeBlockLayer.nStartBlock < psPreviousLayer->nStartBlock) return ThrowPCIDSKException("The tile directory is corrupted."); psPreviousLayer->nBlockCount = msFreeBlockLayer.nStartBlock - psPreviousLayer->nStartBlock; } if (msBlockDir.nBlockCount < msFreeBlockLayer.nStartBlock) return ThrowPCIDSKException("The tile directory is corrupted."); msFreeBlockLayer.nBlockCount = msBlockDir.nBlockCount - msFreeBlockLayer.nStartBlock; } else { if (psPreviousLayer) { if (msBlockDir.nBlockCount < psPreviousLayer->nStartBlock) return ThrowPCIDSKException("The tile directory is corrupted."); psPreviousLayer->nBlockCount = msBlockDir.nBlockCount - psPreviousLayer->nStartBlock; } msFreeBlockLayer.nBlockCount = 0; } } /************************************************************************/ /* GetDirSize() */ /************************************************************************/ /** * Gets the size in bytes of the block tile directory. * * @return The size in bytes of the block tile directory. */ size_t AsciiTileDir::GetDirSize(void) const { uint64 nDirSize = 0; // Add the size of the header. nDirSize += 512; // Add the size of the blocks. for (size_t iLayer = 0; iLayer < moLayerInfoList.size(); iLayer++) { const BlockLayerInfo * psLayer = moLayerInfoList[iLayer]; nDirSize += static_cast<uint64>(psLayer->nBlockCount) * SYS_BLOCK_INFO_SIZE; } // Add the size of the free blocks. nDirSize += static_cast<uint64>(msFreeBlockLayer.nBlockCount) * SYS_BLOCK_INFO_SIZE; // Add the size of the block layers. nDirSize += static_cast<uint64>(moLayerInfoList.size()) * SYS_BLOCK_LAYER_INFO_SIZE; // Add the size of the tile layers. nDirSize += static_cast<uint64>(moTileLayerInfoList.size()) * sizeof(TileLayerInfo); #if SIZEOF_VOIDP < 8 if (nDirSize > std::numeric_limits<size_t>::max()) return ThrowPCIDSKException(0, "Unable to open extremely large file on 32-bit system or the tile directory is corrupted."); #endif return static_cast<size_t>(nDirSize); } /************************************************************************/ /* GetLayerBlockCount() */ /************************************************************************/ uint32 AsciiTileDir::GetLayerBlockCount(void) const { uint32 nLayerBlockCount = 0; for (size_t iLayer = 0; iLayer < moLayerInfoList.size(); iLayer++) { const BlockLayerInfo * psLayer = moLayerInfoList[iLayer]; nLayerBlockCount += psLayer->nBlockCount; } return nLayerBlockCount; } /************************************************************************/ /* GetFreeBlockCount() */ /************************************************************************/ uint32 AsciiTileDir::GetFreeBlockCount(void) const { return msFreeBlockLayer.nBlockCount; } /************************************************************************/ /* UpdateBlockDirInfo() */ /************************************************************************/ void AsciiTileDir::UpdateBlockDirInfo(void) { uint32 nLayerBlockCount = GetLayerBlockCount(); uint32 nFreeBlockCount = GetFreeBlockCount(); // Update the block directory info. msBlockDir.nLayerCount = (uint32) moLayerInfoList.size(); msBlockDir.nBlockCount = nLayerBlockCount + nFreeBlockCount; msBlockDir.nFirstFreeBlock = nLayerBlockCount; } /************************************************************************/ /* InitBlockList() */ /************************************************************************/ void AsciiTileDir::InitBlockList(AsciiTileLayer * poLayer) { if (!poLayer) return; if( poLayer->mpsBlockLayer->nBlockCount == 0) { poLayer->moBlockList = BlockInfoList(); return; } BlockLayerInfo * psLayer = poLayer->mpsBlockLayer; // The offset of the blocks. uint64 nOffset = static_cast<uint64>(psLayer->nStartBlock) * SYS_BLOCK_INFO_SIZE; // The size of the blocks. uint64 nReadSize = static_cast<uint64>(psLayer->nBlockCount) * SYS_BLOCK_INFO_SIZE; if (mpoFile->IsCorruptedSegment(mnSegment, 512 + nOffset, nReadSize)) return ThrowPCIDSKException("The tile directory is corrupted."); #if SIZEOF_VOIDP < 8 if (nReadSize > std::numeric_limits<size_t>::max()) return ThrowPCIDSKException("Unable to open extremely large file on 32-bit system."); #endif // Read the blocks from disk. uint8 * pabyBlockDir = (uint8 *) malloc(static_cast<size_t>(nReadSize)); if (pabyBlockDir == nullptr) return ThrowPCIDSKException("Out of memory in AsciiTileDir::InitBlockList()."); PCIDSKBuffer oBlockDirAutoPtr; oBlockDirAutoPtr.buffer = (char *) pabyBlockDir; uint8 * pabyBlockDirIter = pabyBlockDir; mpoFile->ReadFromSegment(mnSegment, pabyBlockDir, 512 + nOffset, nReadSize); // Setup the block list. try { poLayer->moBlockList.resize(psLayer->nBlockCount); } catch (const std::exception & ex) { return ThrowPCIDSKException("Out of memory in AsciiTileDir::InitBlockList(): %s", ex.what()); } for (uint32 iBlock = 0; iBlock < psLayer->nBlockCount; iBlock++) { BlockInfo * psBlock = &poLayer->moBlockList[iBlock]; psBlock->nSegment = ScanInt4(pabyBlockDirIter); pabyBlockDirIter += 4; psBlock->nStartBlock = ScanInt8(pabyBlockDirIter); pabyBlockDirIter += 8; //psBlock->nLayer = ScanInt8(pabyBlockDirIter); pabyBlockDirIter += 8; //psBlock->nNextBlock = ScanInt8(pabyBlockDirIter); pabyBlockDirIter += 8; } } /************************************************************************/ /* ReadLayerBlocks() */ /************************************************************************/ void AsciiTileDir::ReadLayerBlocks(uint32 iLayer) { InitBlockList((AsciiTileLayer *) moLayerList[iLayer]); } /************************************************************************/ /* ReadFreeBlockLayer() */ /************************************************************************/ void AsciiTileDir::ReadFreeBlockLayer(void) { mpoFreeBlockLayer = new AsciiTileLayer(this, INVALID_LAYER, &msFreeBlockLayer, nullptr); InitBlockList((AsciiTileLayer *) mpoFreeBlockLayer); } /************************************************************************/ /* WriteDir() */ /************************************************************************/ void AsciiTileDir::WriteDir(void) { UpdateBlockDirInfo(); // Make sure all the layer's block list are valid. if (mbOnDisk) { for (size_t iLayer = 0; iLayer < moLayerList.size(); iLayer++) { AsciiTileLayer * poLayer = GetTileLayer((uint32) iLayer); if (poLayer->moBlockList.size() != poLayer->GetBlockCount()) InitBlockList(poLayer); } } // What is the size of the block directory. size_t nDirSize = GetDirSize(); // If we are resizing the segment, resize it to the optimized size. if (nDirSize > mpoFile->GetSegmentSize(mnSegment)) nDirSize = std::max(nDirSize, GetOptimizedDirSize(mpoFile)); // Write the block directory to disk. char * pabyBlockDir = (char *) malloc(nDirSize + 1); // +1 for '\0'. if (pabyBlockDir == nullptr) return ThrowPCIDSKException("Out of memory in AsciiTileDir::WriteDir()."); PCIDSKBuffer oBlockDirAutoPtr; oBlockDirAutoPtr.buffer = pabyBlockDir; char * pabyBlockDirIter = pabyBlockDir; // Initialize the header. memset(pabyBlockDir, ' ', 512); // The first 10 bytes are for the version. memcpy(pabyBlockDirIter, "VERSION", 7); snprintf(pabyBlockDirIter + 7, 9, "%3d", mnVersion); pabyBlockDirIter += 10; // Write the block directory info. snprintf(pabyBlockDirIter, 9, "%8d", msBlockDir.nLayerCount); pabyBlockDirIter += 8; snprintf(pabyBlockDirIter, 9, "%8d", msBlockDir.nBlockCount); pabyBlockDirIter += 8; snprintf(pabyBlockDirIter, 9, "%8d", msBlockDir.nFirstFreeBlock); // The bytes from 128 to 140 are for the subversion. memcpy(pabyBlockDir + 128, "SUBVERSION 1", 12); // The third last byte is for the endianness. pabyBlockDir[512 - 3] = mchEndianness; // The last 2 bytes of the header are for the validity info. uint16 nValidInfo = ++mnValidInfo; SwapValue(&nValidInfo); memcpy(pabyBlockDir + 512 - 2, &nValidInfo, 2); // The header is 512 bytes. pabyBlockDirIter = pabyBlockDir + 512; // Write the block info list. uint32 nNextBlock = 1; for (size_t iLayer = 0; iLayer < moLayerInfoList.size(); iLayer++) { BlockLayerInfo * psLayer = moLayerInfoList[iLayer]; AsciiTileLayer * poLayer = GetTileLayer((uint32) iLayer); for (size_t iBlock = 0; iBlock < psLayer->nBlockCount; iBlock++) { BlockInfo * psBlock = &poLayer->moBlockList[iBlock]; snprintf(pabyBlockDirIter, 9, "%4d", psBlock->nSegment); pabyBlockDirIter += 4; snprintf(pabyBlockDirIter, 9, "%8d", psBlock->nStartBlock); pabyBlockDirIter += 8; snprintf(pabyBlockDirIter, 9, "%8d", (uint32) iLayer); pabyBlockDirIter += 8; if (iBlock != psLayer->nBlockCount - 1) snprintf(pabyBlockDirIter, 9, "%8d", nNextBlock); else snprintf(pabyBlockDirIter, 9, "%8d", -1); pabyBlockDirIter += 8; nNextBlock++; } } // Write the free block info list. AsciiTileLayer * poLayer = (AsciiTileLayer *) mpoFreeBlockLayer; for (size_t iBlock = 0; iBlock < msFreeBlockLayer.nBlockCount; iBlock++) { BlockInfo * psBlock = &poLayer->moBlockList[iBlock]; snprintf(pabyBlockDirIter, 9, "%4d", psBlock->nSegment); pabyBlockDirIter += 4; snprintf(pabyBlockDirIter, 9, "%8d", psBlock->nStartBlock); pabyBlockDirIter += 8; snprintf(pabyBlockDirIter, 9, "%8d", -1); pabyBlockDirIter += 8; if (iBlock != msFreeBlockLayer.nBlockCount - 1) snprintf(pabyBlockDirIter, 9, "%8d", nNextBlock); else snprintf(pabyBlockDirIter, 9, "%8d", -1); pabyBlockDirIter += 8; nNextBlock++; } // Write the block layers. uint32 nStartBlock = 0; for (BlockLayerInfo * psLayer : moLayerInfoList) { snprintf(pabyBlockDirIter, 9, "%4d", psLayer->nLayerType); pabyBlockDirIter += 4; if (psLayer->nBlockCount != 0) snprintf(pabyBlockDirIter, 9, "%8d", nStartBlock); else snprintf(pabyBlockDirIter, 9, "%8d", -1); pabyBlockDirIter += 8; snprintf(pabyBlockDirIter, 13, "%12" PCIDSK_FRMT_64_WITHOUT_PREFIX "d", psLayer->nLayerSize); pabyBlockDirIter += 12; nStartBlock += psLayer->nBlockCount; } // Write the tile layers. for (uint32 iLayer = 0; iLayer < msBlockDir.nLayerCount; iLayer++) { size_t nSize = sizeof(TileLayerInfo); memcpy(pabyBlockDirIter, moTileLayerInfoList[iLayer], nSize); SwapTileLayer((TileLayerInfo *) pabyBlockDirIter); pabyBlockDirIter += nSize; } // Initialize the remaining bytes so that Valgrind doesn't complain. size_t nRemainingBytes = pabyBlockDir + nDirSize - pabyBlockDirIter; if (nRemainingBytes) memset(pabyBlockDirIter, 0, nRemainingBytes); // Write the block directory to disk. mpoFile->WriteToSegment(mnSegment, pabyBlockDir, 0, nDirSize); } /************************************************************************/ /* _CreateLayer() */ /************************************************************************/ /** * Creates a block layer of the specified type at the specified index. * * @param nLayerType The type of the block layer to create. * @param iLayer The index of the block layer to create. * * @return The new block layer. */ BlockLayer * AsciiTileDir::_CreateLayer(uint16 nLayerType, uint32 iLayer) { if (iLayer == moLayerInfoList.size()) { try { moLayerInfoList.resize(moLayerInfoList.size() + 1); moTileLayerInfoList.resize(moLayerInfoList.size()); } catch (const std::exception & ex) { return (BlockLayer *) ThrowPCIDSKExceptionPtr("Out of memory in AsciiTileDir::_CreateLayer(): %s", ex.what()); } moLayerInfoList[iLayer] = new BlockLayerInfo; moTileLayerInfoList[iLayer] = new TileLayerInfo; } // Setup the block layer info. BlockLayerInfo * psBlockLayer = moLayerInfoList[iLayer]; psBlockLayer->nLayerType = nLayerType; psBlockLayer->nBlockCount = 0; psBlockLayer->nLayerSize = 0; // Setup the tile layer info. TileLayerInfo * psTileLayer = moTileLayerInfoList[iLayer]; memset(psTileLayer, 0, sizeof(TileLayerInfo)); return new AsciiTileLayer(this, iLayer, psBlockLayer, psTileLayer); } /************************************************************************/ /* _DeleteLayer() */ /************************************************************************/ /** * Deletes the block layer with the specified index. * * @param iLayer The index of the block layer to delete. */ void AsciiTileDir::_DeleteLayer(uint32 iLayer) { // Invalidate the block layer info. BlockLayerInfo * psBlockLayer = moLayerInfoList[iLayer]; psBlockLayer->nLayerType = BLTDead; psBlockLayer->nBlockCount = 0; psBlockLayer->nLayerSize = 0; // Invalidate the tile layer info. TileLayerInfo * psTileLayer = moTileLayerInfoList[iLayer]; memset(psTileLayer, 0, sizeof(TileLayerInfo)); } /************************************************************************/ /* GetDataSegmentName() */ /************************************************************************/ std::string AsciiTileDir::GetDataSegmentName(void) const { return "SysBData"; } /************************************************************************/ /* GetDataSegmentDesc() */ /************************************************************************/ std::string AsciiTileDir::GetDataSegmentDesc(void) const { return "Block Tile Data - Do not modify."; } /************************************************************************/ /* ValidateNewBlocks() */ /************************************************************************/ void AsciiTileDir::ValidateNewBlocks(uint32 & nNewBlockCount, bool bFreeBlocks) { uint32 nLimitBlockCount = 99999999; uint32 nTotalBlockCount = GetLayerBlockCount() + GetFreeBlockCount(); if (nTotalBlockCount >= nLimitBlockCount) { Sync(); // Make sure the directory is synchronized to disk. ThrowPCIDSKException("The file size limit has been reached."); } if (nTotalBlockCount + nNewBlockCount > nLimitBlockCount) { if (!bFreeBlocks) { Sync(); // Make sure the directory is synchronized to disk. ThrowPCIDSKException("The file size limit has been reached."); } nNewBlockCount = nLimitBlockCount - nTotalBlockCount; } }
33.633974
131
0.570707
sthagen
a8b22945fcd3c79673df188e2016fed380cf4809
326
cpp
C++
Module-2/Problem_7c.cpp
farhanmasud/ruet-discrete-mathematics
4c510c48a6e5f3ed8f202a57c4761c6a1f1286ea
[ "MIT" ]
null
null
null
Module-2/Problem_7c.cpp
farhanmasud/ruet-discrete-mathematics
4c510c48a6e5f3ed8f202a57c4761c6a1f1286ea
[ "MIT" ]
null
null
null
Module-2/Problem_7c.cpp
farhanmasud/ruet-discrete-mathematics
4c510c48a6e5f3ed8f202a57c4761c6a1f1286ea
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int sum = 0; int l1 = 0; int u1 = 5; int l2 = 0; int u2 = 10; for(int i = l1; i <= u1; i++) { for(int j = l2; j <= u2; j++) { sum = sum + i + j; } } cout << "The sum is: " << sum; return 0; }
13.583333
37
0.389571
farhanmasud
a8b767bd14d13c540bf9f64b0aa3d5f71e5f1b14
14,065
cpp
C++
Examples/DEPRECATED_Test_Video/src/VideoPlayer.cpp
headupinclouds/GLIP-Lib
e0315e9c5b7ceda6280be8c33734e1dcdc04de8e
[ "MIT" ]
null
null
null
Examples/DEPRECATED_Test_Video/src/VideoPlayer.cpp
headupinclouds/GLIP-Lib
e0315e9c5b7ceda6280be8c33734e1dcdc04de8e
[ "MIT" ]
null
null
null
Examples/DEPRECATED_Test_Video/src/VideoPlayer.cpp
headupinclouds/GLIP-Lib
e0315e9c5b7ceda6280be8c33734e1dcdc04de8e
[ "MIT" ]
null
null
null
#include "VideoPlayer.hpp" // Namespace using namespace Glip::CoreGL; using namespace Glip::CorePipeline; using namespace Glip::Modules; // Objects VideoModIHM::VideoModIHM(void) : QWidget(), player(NULL), src(NULL), output(NULL), pbo(NULL), textureA(NULL), textureB(NULL), textureLatest(NULL), textureOldest(NULL), pipeline(NULL), videosLayout(NULL), streamControlsLayout(NULL), generalLayout(NULL), loadVideo(NULL), play(NULL), pause(NULL), loadPipeline(NULL), saveFrame(NULL), pipelineControl(NULL), box(NULL), timer(NULL), pixmap(NULL), image(NULL), fmt(NULL), buffer(NULL), timeLayout(NULL), timeSlider(NULL), timeLabel(NULL), timeBox(NULL) { log.open("./log.txt", std::fstream::out | std::fstream::trunc); if(!log.is_open()) { QMessageBox::warning(NULL, tr("TestVideo"), tr("Unable to write to the log file log.txt.\n")); throw Exception("VideoModIHM::VideoModIHM - Cannot open log file.", __FILE__, __LINE__); } try { videosLayout = new QHBoxLayout(); timeLayout = new QHBoxLayout(); streamControlsLayout = new QHBoxLayout(); pipelineControl = new QHBoxLayout(); generalLayout = new QVBoxLayout(this); player = new Phonon::VideoPlayer(Phonon::VideoCategory); output = new WindowRendererContainer(this, 640, 480); output->renderer().setMouseActions(true); output->renderer().setPixelAspectRatio(1.0f); // Info : log << "> TestVideo" << std::endl; log << "Vendor name : " << HandleOpenGL::getVendorName() << std::endl; log << "Renderer name : " << HandleOpenGL::getRendererName() << std::endl; log << "GL version : " << HandleOpenGL::getVersion() << std::endl; log << "GLSL version : " << HandleOpenGL::getGLSLVersion() << std::endl; timeSlider = new QSlider(this); timeSlider->setOrientation(Qt::Horizontal); timeSlider->setRange(0,1000); timeLabel = new QLabel("00:00", this); timeLabel->setFixedWidth(100); timeLabel->setAlignment(Qt::AlignHCenter); timeBox = new QComboBox(this); timeBox->addItem("1 FPS"); timeBox->addItem("5 FPS"); timeBox->addItem("10 FPS"); timeBox->addItem("20 FPS"); timeBox->addItem("30 FPS"); timeBox->addItem("60 FPS"); timeBox->setCurrentIndex(3); loadVideo = new QPushButton("Open a Video", this); play = new QPushButton("Play", this); pause = new QPushButton("Pause", this); loadPipeline = new QPushButton("Open a Pipeline", this); saveFrame = new QPushButton("Save Frame", this); box = new QComboBox(this); box->addItem("<Input Stream>"); pixmap = new QPixmap(); image = new QImage(); fmt = new HdlTextureFormat(1,1,GL_RGB,GL_UNSIGNED_BYTE,GL_LINEAR,GL_LINEAR); videosLayout->addWidget(player); videosLayout->addWidget(output); timeLayout->addWidget(timeLabel); timeLayout->addWidget(timeSlider); streamControlsLayout->addWidget(loadVideo); streamControlsLayout->addWidget(play); streamControlsLayout->addWidget(pause); streamControlsLayout->addWidget(timeBox); pipelineControl->addWidget(loadPipeline); pipelineControl->addWidget(box); pipelineControl->addWidget(saveFrame); generalLayout->addLayout(videosLayout); generalLayout->addLayout(timeLayout); generalLayout->addLayout(streamControlsLayout); generalLayout->addLayout(pipelineControl); setGeometry(100, 100, 1280, 720); show(); // Timer : timer = new QTimer; timer->setInterval(50); // Connections : QObject::connect(loadVideo, SIGNAL(released(void)), this, SLOT(openVideo(void))); QObject::connect(play, SIGNAL(released(void)), player, SLOT(play(void))); QObject::connect(pause, SIGNAL(released(void)), player, SLOT(pause(void))); QObject::connect(loadPipeline, SIGNAL(released(void)), this, SLOT(openPipeline(void))); QObject::connect(saveFrame, SIGNAL(released(void)), this, SLOT(save(void))); QObject::connect(timer, SIGNAL(timeout(void)), this, SLOT(grabFrame(void))); QObject::connect(timer, SIGNAL(timeout(void)), this, SLOT(updateTime(void))); QObject::connect(timeSlider, SIGNAL(sliderReleased()), this, SLOT(seekPosition(void))); QObject::connect(timeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeFPS(void))); timer->start(); } catch(Exception& e) { log << "Exception caught : " << std::endl; log << e.what() << std::endl; log << "> Abort" << std::endl; log.close(); QMessageBox::warning(NULL, tr("TestVideo"), e.what()); std::cout << "Exception caught : " << std::endl; std::cout << e.what() << std::endl; std::cout << "(Will be rethrown)" << std::endl; throw e; } } VideoModIHM::~VideoModIHM(void) { timer->stop(); log << "> End" << std::endl; log.close(); delete player; delete src; delete output; delete pbo; delete timeSlider; delete timeLabel; delete textureA; delete textureB; delete pipeline; delete videosLayout; delete timeLayout; delete streamControlsLayout; delete pipelineControl; delete generalLayout; delete loadVideo; delete play; delete pause; delete loadPipeline; delete saveFrame; delete timeBox; delete box; delete pixmap; delete image; delete fmt; delete[] buffer; } void VideoModIHM::openVideo(void) { static bool showMIMETypesOnce = false; if(!showMIMETypesOnce) { QString mimeTypesMessage = "MIME Types of the formats than can be decoded on your system : \n"; QStringList types = Phonon::BackendCapabilities::availableMimeTypes(); for(int i = 0; i<(types.size()-1); i++) if(types[i].contains("video/")) mimeTypesMessage += types[i] + ", "; if(types.back().contains("video/")) mimeTypesMessage += types.back(); QMessageBox::information(NULL, "MIME Types", mimeTypesMessage); std::cout << mimeTypesMessage.toStdString() << std::endl; showMIMETypesOnce = true; } // Get a filename : QString filename = QFileDialog::getOpenFileName(this, tr("Open a Video"), ".", "*"); if (!filename.isEmpty()) { if(player->isPlaying()) { player->stop(); delete src; } // Try to open stream : src = new Phonon::MediaSource(filename); player->play(*src); } } void VideoModIHM::openPipeline(void) { QString filename = QFileDialog::getOpenFileName(this, tr("Load a Pipeline"), ".", "*.ppl"); if (!filename.isEmpty()) { std::cout << "Building : " << filename.toStdString() << std::endl; bool success = true; PipelineLayout* model = NULL; LayoutLoader loader; try { model = loader(filename.toUtf8().constData()); } catch(std::exception& e) { success = false; log << "Exception caught : " << std::endl; log << e.what() << std::endl; log << "> Abort" << std::endl; QMessageBox::information(NULL, tr("Error while loading the pipeline : "), e.what()); std::cout << "Error while building the pipeline : " << e.what() << std::endl; } if(success) { if(pipeline!=NULL) { delete pipeline; pipeline = NULL; // clean the box too... while(box->count()>1) box->removeItem(1); } try { pipeline = new Pipeline(*model, "LoadedPipeline"); } catch(std::exception& e) { success = false; log << "Exception caught : " << std::endl; log << e.what() << std::endl; log << "> Abort" << std::endl; QMessageBox::information(this, tr("Error while creating the pipeline : \n"), e.what()); std::cout << "Error while creating the pipeline : " << e.what() << std::endl; delete pipeline; pipeline = NULL; } if(success) { //Test writing : loader.write(*pipeline, "./Filters/writingTest.ppl"); std::cout << "Pipeline size on the GPU : " << static_cast<int>(static_cast<float>(pipeline->getSize())/(1024.0*1024.0)) << " MB" << std::endl; // Update the box : for(int i=0; i<pipeline->getNumOutputPort(); i++) box->addItem(pipeline->getOutputPortName(i).c_str()); } delete model; } } } void VideoModIHM::grabFrame(void) { if(player->isPlaying() && src!=NULL) { try { #if defined(__linux__) const QPixmap& snapshot = QPixmap::grabWindow(player->videoWidget()->winId()); (*image) = snapshot.toImage(); QImage& img = (*image); #elif (defined(_WIN32) && defined(__GNUC__)) || defined(_MSC_VER) const QPixmap& snapshot = QPixmap::grabWidget(player->videoWidget()); (*image) = snapshot.toImage(); QImage& img = (*image); #else #error "Undefined platform" #endif if(img.isNull()) throw Exception("VideoModIHM::grabFrame - NULL Image.", __FILE__, __LINE__); // Check size : const int w = img.width(), h = img.height(); // Check ressources : if(fmt->getWidth()!=w || fmt->getHeight()!=h) { std::cout << "Updating format to : " << w << "X" << h << " pixels." << std::endl; fmt->setWidth(w); fmt->setHeight(h); if(pbo!=NULL) delete pbo; pbo = new HdlPBO(*fmt,GL_PIXEL_UNPACK_BUFFER_ARB,GL_STREAM_DRAW_ARB); if(textureA!=NULL) delete textureA; textureA = new HdlTexture(*fmt); if(textureB!=NULL) delete textureB; textureB = new HdlTexture(*fmt); if(buffer!=NULL) delete[] buffer; buffer = new unsigned char[textureA->getSize()]; textureOldest = textureA; textureLatest = textureB; std::cout << "Done" << std::endl; } // Transcode image : int t=0; for(int i=h-1; i>=0; i--) { for(int j=0; j<w; j++) { QRgb col = img.pixel(j,i); buffer[t+0] = static_cast<unsigned char>( qRed( col ) ); buffer[t+1] = static_cast<unsigned char>( qGreen( col ) ); buffer[t+2] = static_cast<unsigned char>( qBlue( col ) ); t += 3; } } textureOldest->write(buffer); // swap order : HdlTexture* tmp = textureLatest; textureLatest = textureOldest; textureOldest = tmp; // Update pipeline if needed : if(pipeline!=NULL) { if(pipeline->getNumInputPort()==1) (*pipeline) << (*textureLatest) << Pipeline::Process; else if(pipeline->getNumInputPort()==2) (*pipeline) << (*textureLatest) << (*textureOldest) << Pipeline::Process; } } catch(Exception& e) { player->pause(); log << "Exception caught : " << std::endl; log << e.what() << std::endl; log << "> Abort" << std::endl; QMessageBox::information(NULL, tr("Error while build texture from PBO : \n"), e.what()); std::cout << "Error while build texture from PBO : \n" << e.what() << std::endl; delete pbo; delete textureA; delete textureB; textureLatest = NULL; textureOldest = NULL; pbo = NULL; textureA = NULL; textureB = NULL; } } drawOutput(); } void VideoModIHM::drawOutput(void) { int port = box->currentIndex(); if(textureLatest!=NULL && src!=NULL) { if(port==0) output->renderer() << (*textureLatest); else if( pipeline!=NULL ) output->renderer() << pipeline->out(port-1); } } void VideoModIHM::save(void) { int port = box->currentIndex(); QString filename = QFileDialog::getSaveFileName(this); if (!filename.isEmpty()) { if(textureLatest!=NULL && (port==0 || pipeline!=NULL) ) { // The image selected try { std::cout << "Exporting image... (" << port << ')' << std::endl; HdlTextureFormat *tmpfmt = NULL; // Read the target format : if(port==0) tmpfmt = new HdlTextureFormat(*textureLatest); else tmpfmt = new HdlTextureFormat(pipeline->out(port-1)); TextureReader reader("reader",*tmpfmt); reader.yFlip = true; if(port==0) reader << *textureLatest; else if(pipeline!=NULL) reader << pipeline->out(port-1); else throw Exception("VideoModIHM::save - Cannot save NULL content.", __FILE__, __LINE__); // Create an image with Qt QImage image(reader.getWidth(), reader.getHeight(), QImage::Format_RGB888); QRgb value; double r, g, b; for(int y=0; y<reader.getHeight(); y++) { for(int x=0; x<reader.getWidth(); x++) { r = static_cast<unsigned char>(reader(x,y,0)*255.0); g = static_cast<unsigned char>(reader(x,y,1)*255.0); b = static_cast<unsigned char>(reader(x,y,2)*255.0); value = qRgb(r, g, b); image.setPixel(x, y, value); } } delete tmpfmt; if(!image.save(filename)) { QMessageBox::information(this, tr("Error while writing : "), filename); std::cout << "Error while writing : " << filename.toUtf8().constData() << std::endl; } } catch(std::exception& e) { log << "Exception caught : " << std::endl; log << e.what() << std::endl; log << "> Abort" << std::endl; QMessageBox::information(this, tr("Error while saving : "), e.what()); std::cout << "Error while saving : " << e.what() << std::endl; } } } } void VideoModIHM::updateTime(void) { if(player->isPlaying() && !timeSlider->isSliderDown()) { double c = player->currentTime(), t = player->totalTime(); timeSlider->setSliderPosition(static_cast<int>(c/t*1000.0)); int m = static_cast<int>(c/60000.0); c -= m*60000.0; int s = static_cast<int>(c/1000.0); timeLabel->setText(tr("%1:%2").arg(m).arg(s)); } } void VideoModIHM::seekPosition(void) { if(player->mediaObject()->isSeekable()) { double val = timeSlider->value(); val /= 1000.0; qint64 p = static_cast<qint64>(val*player->totalTime()); player->seek(p); } } void VideoModIHM::changeFPS(void) { QString str = timeBox->currentText(); str.remove(QString("FPS")); double fps = str.toDouble(); timer->stop(); timer->setInterval(static_cast<int>(1000.0/fps)); timer->start(); } VideoModApplication::VideoModApplication(int& argc, char** argv) : QApplication(argc,argv) { setApplicationName("GlipLib-VideoPipeline"); ihm = new VideoModIHM(); } VideoModApplication::~VideoModApplication() { delete ihm; }
27.906746
468
0.624529
headupinclouds
a8bc210c67bfebf4f0bc8d51a5cbe72c2bbc0e3a
17,616
cpp
C++
source/glbinding/source/gl/functions_d.cpp
j-o/glbinding
c1e3a571ea4ee7058879e46777ba728a58ca2fa8
[ "MIT" ]
null
null
null
source/glbinding/source/gl/functions_d.cpp
j-o/glbinding
c1e3a571ea4ee7058879e46777ba728a58ca2fa8
[ "MIT" ]
null
null
null
source/glbinding/source/gl/functions_d.cpp
j-o/glbinding
c1e3a571ea4ee7058879e46777ba728a58ca2fa8
[ "MIT" ]
null
null
null
#include "../Binding_pch.h" #include <glbinding/gl/functions.h> using namespace glbinding; namespace gl { void glDebugMessageCallback(GLDEBUGPROC callback, const void * userParam) { return Binding::DebugMessageCallback(callback, userParam); } void glDebugMessageCallbackAMD(GLDEBUGPROCAMD callback, void * userParam) { return Binding::DebugMessageCallbackAMD(callback, userParam); } void glDebugMessageCallbackARB(GLDEBUGPROCARB callback, const void * userParam) { return Binding::DebugMessageCallbackARB(callback, userParam); } void glDebugMessageControl(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled) { return Binding::DebugMessageControl(source, type, severity, count, ids, enabled); } void glDebugMessageControlARB(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled) { return Binding::DebugMessageControlARB(source, type, severity, count, ids, enabled); } void glDebugMessageEnableAMD(GLenum category, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled) { return Binding::DebugMessageEnableAMD(category, severity, count, ids, enabled); } void glDebugMessageInsert(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * buf) { return Binding::DebugMessageInsert(source, type, id, severity, length, buf); } void glDebugMessageInsertAMD(GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar * buf) { return Binding::DebugMessageInsertAMD(category, severity, id, length, buf); } void glDebugMessageInsertARB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * buf) { return Binding::DebugMessageInsertARB(source, type, id, severity, length, buf); } void glDeformSGIX(FfdMaskSGIX mask) { return Binding::DeformSGIX(mask); } void glDeformationMap3dSGIX(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble * points) { return Binding::DeformationMap3dSGIX(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, w1, w2, wstride, worder, points); } void glDeformationMap3fSGIX(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat * points) { return Binding::DeformationMap3fSGIX(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, w1, w2, wstride, worder, points); } void glDeleteAsyncMarkersSGIX(GLuint marker, GLsizei range) { return Binding::DeleteAsyncMarkersSGIX(marker, range); } void glDeleteBuffers(GLsizei n, const GLuint * buffers) { return Binding::DeleteBuffers(n, buffers); } void glDeleteBuffersARB(GLsizei n, const GLuint * buffers) { return Binding::DeleteBuffersARB(n, buffers); } void glDeleteCommandListsNV(GLsizei n, const GLuint * lists) { return Binding::DeleteCommandListsNV(n, lists); } void glDeleteFencesAPPLE(GLsizei n, const GLuint * fences) { return Binding::DeleteFencesAPPLE(n, fences); } void glDeleteFencesNV(GLsizei n, const GLuint * fences) { return Binding::DeleteFencesNV(n, fences); } void glDeleteFragmentShaderATI(GLuint id) { return Binding::DeleteFragmentShaderATI(id); } void glDeleteFramebuffers(GLsizei n, const GLuint * framebuffers) { return Binding::DeleteFramebuffers(n, framebuffers); } void glDeleteFramebuffersEXT(GLsizei n, const GLuint * framebuffers) { return Binding::DeleteFramebuffersEXT(n, framebuffers); } void glDeleteLists(GLuint list, GLsizei range) { return Binding::DeleteLists(list, range); } void glDeleteMemoryObjectsEXT(GLsizei n, const GLuint * memoryObjects) { return Binding::DeleteMemoryObjectsEXT(n, memoryObjects); } void glDeleteNamedStringARB(GLint namelen, const GLchar * name) { return Binding::DeleteNamedStringARB(namelen, name); } void glDeleteNamesAMD(GLenum identifier, GLuint num, const GLuint * names) { return Binding::DeleteNamesAMD(identifier, num, names); } void glDeleteObjectARB(GLhandleARB obj) { return Binding::DeleteObjectARB(obj); } void glDeleteOcclusionQueriesNV(GLsizei n, const GLuint * ids) { return Binding::DeleteOcclusionQueriesNV(n, ids); } void glDeletePathsNV(GLuint path, GLsizei range) { return Binding::DeletePathsNV(path, range); } void glDeletePerfMonitorsAMD(GLsizei n, GLuint * monitors) { return Binding::DeletePerfMonitorsAMD(n, monitors); } void glDeletePerfQueryINTEL(GLuint queryHandle) { return Binding::DeletePerfQueryINTEL(queryHandle); } void glDeleteProgram(GLuint program) { return Binding::DeleteProgram(program); } void glDeleteProgramPipelines(GLsizei n, const GLuint * pipelines) { return Binding::DeleteProgramPipelines(n, pipelines); } void glDeleteProgramsARB(GLsizei n, const GLuint * programs) { return Binding::DeleteProgramsARB(n, programs); } void glDeleteProgramsNV(GLsizei n, const GLuint * programs) { return Binding::DeleteProgramsNV(n, programs); } void glDeleteQueries(GLsizei n, const GLuint * ids) { return Binding::DeleteQueries(n, ids); } void glDeleteQueriesARB(GLsizei n, const GLuint * ids) { return Binding::DeleteQueriesARB(n, ids); } void glDeleteRenderbuffers(GLsizei n, const GLuint * renderbuffers) { return Binding::DeleteRenderbuffers(n, renderbuffers); } void glDeleteRenderbuffersEXT(GLsizei n, const GLuint * renderbuffers) { return Binding::DeleteRenderbuffersEXT(n, renderbuffers); } void glDeleteSamplers(GLsizei count, const GLuint * samplers) { return Binding::DeleteSamplers(count, samplers); } void glDeleteSemaphoresEXT(GLsizei n, const GLuint * semaphores) { return Binding::DeleteSemaphoresEXT(n, semaphores); } void glDeleteShader(GLuint shader) { return Binding::DeleteShader(shader); } void glDeleteStatesNV(GLsizei n, const GLuint * states) { return Binding::DeleteStatesNV(n, states); } void glDeleteSync(GLsync sync) { return Binding::DeleteSync(sync); } void glDeleteTextures(GLsizei n, const GLuint * textures) { return Binding::DeleteTextures(n, textures); } void glDeleteTexturesEXT(GLsizei n, const GLuint * textures) { return Binding::DeleteTexturesEXT(n, textures); } void glDeleteTransformFeedbacks(GLsizei n, const GLuint * ids) { return Binding::DeleteTransformFeedbacks(n, ids); } void glDeleteTransformFeedbacksNV(GLsizei n, const GLuint * ids) { return Binding::DeleteTransformFeedbacksNV(n, ids); } void glDeleteVertexArrays(GLsizei n, const GLuint * arrays) { return Binding::DeleteVertexArrays(n, arrays); } void glDeleteVertexArraysAPPLE(GLsizei n, const GLuint * arrays) { return Binding::DeleteVertexArraysAPPLE(n, arrays); } void glDeleteVertexShaderEXT(GLuint id) { return Binding::DeleteVertexShaderEXT(id); } void glDepthBoundsEXT(GLclampd zmin, GLclampd zmax) { return Binding::DepthBoundsEXT(zmin, zmax); } void glDepthBoundsdNV(GLdouble zmin, GLdouble zmax) { return Binding::DepthBoundsdNV(zmin, zmax); } void glDepthFunc(GLenum func) { return Binding::DepthFunc(func); } void glDepthMask(GLboolean flag) { return Binding::DepthMask(flag); } void glDepthRange(GLdouble near_, GLdouble far_) { return Binding::DepthRange(near_, far_); } void glDepthRangeArrayv(GLuint first, GLsizei count, const GLdouble * v) { return Binding::DepthRangeArrayv(first, count, v); } void glDepthRangeIndexed(GLuint index, GLdouble n, GLdouble f) { return Binding::DepthRangeIndexed(index, n, f); } void glDepthRangedNV(GLdouble zNear, GLdouble zFar) { return Binding::DepthRangedNV(zNear, zFar); } void glDepthRangef(GLfloat n, GLfloat f) { return Binding::DepthRangef(n, f); } void glDepthRangefOES(GLclampf n, GLclampf f) { return Binding::DepthRangefOES(n, f); } void glDepthRangexOES(GLfixed n, GLfixed f) { return Binding::DepthRangexOES(n, f); } void glDetachObjectARB(GLhandleARB containerObj, GLhandleARB attachedObj) { return Binding::DetachObjectARB(containerObj, attachedObj); } void glDetachShader(GLuint program, GLuint shader) { return Binding::DetachShader(program, shader); } void glDetailTexFuncSGIS(GLenum target, GLsizei n, const GLfloat * points) { return Binding::DetailTexFuncSGIS(target, n, points); } void glDisable(GLenum cap) { return Binding::Disable(cap); } void glDisableClientState(GLenum array) { return Binding::DisableClientState(array); } void glDisableClientStateIndexedEXT(GLenum array, GLuint index) { return Binding::DisableClientStateIndexedEXT(array, index); } void glDisableClientStateiEXT(GLenum array, GLuint index) { return Binding::DisableClientStateiEXT(array, index); } void glDisableIndexedEXT(GLenum target, GLuint index) { return Binding::DisableIndexedEXT(target, index); } void glDisableVariantClientStateEXT(GLuint id) { return Binding::DisableVariantClientStateEXT(id); } void glDisableVertexArrayAttrib(GLuint vaobj, GLuint index) { return Binding::DisableVertexArrayAttrib(vaobj, index); } void glDisableVertexArrayAttribEXT(GLuint vaobj, GLuint index) { return Binding::DisableVertexArrayAttribEXT(vaobj, index); } void glDisableVertexArrayEXT(GLuint vaobj, GLenum array) { return Binding::DisableVertexArrayEXT(vaobj, array); } void glDisableVertexAttribAPPLE(GLuint index, GLenum pname) { return Binding::DisableVertexAttribAPPLE(index, pname); } void glDisableVertexAttribArray(GLuint index) { return Binding::DisableVertexAttribArray(index); } void glDisableVertexAttribArrayARB(GLuint index) { return Binding::DisableVertexAttribArrayARB(index); } void glDisablei(GLenum target, GLuint index) { return Binding::Disablei(target, index); } void glDispatchCompute(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z) { return Binding::DispatchCompute(num_groups_x, num_groups_y, num_groups_z); } void glDispatchComputeGroupSizeARB(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z) { return Binding::DispatchComputeGroupSizeARB(num_groups_x, num_groups_y, num_groups_z, group_size_x, group_size_y, group_size_z); } void glDispatchComputeIndirect(GLintptr indirect) { return Binding::DispatchComputeIndirect(indirect); } void glDrawArrays(GLenum mode, GLint first, GLsizei count) { return Binding::DrawArrays(mode, first, count); } void glDrawArraysEXT(GLenum mode, GLint first, GLsizei count) { return Binding::DrawArraysEXT(mode, first, count); } void glDrawArraysIndirect(GLenum mode, const void * indirect) { return Binding::DrawArraysIndirect(mode, indirect); } void glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instancecount) { return Binding::DrawArraysInstanced(mode, first, count, instancecount); } void glDrawArraysInstancedARB(GLenum mode, GLint first, GLsizei count, GLsizei primcount) { return Binding::DrawArraysInstancedARB(mode, first, count, primcount); } void glDrawArraysInstancedBaseInstance(GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance) { return Binding::DrawArraysInstancedBaseInstance(mode, first, count, instancecount, baseinstance); } void glDrawArraysInstancedEXT(GLenum mode, GLint start, GLsizei count, GLsizei primcount) { return Binding::DrawArraysInstancedEXT(mode, start, count, primcount); } void glDrawBuffer(GLenum buf) { return Binding::DrawBuffer(buf); } void glDrawBuffers(GLsizei n, const GLenum * bufs) { return Binding::DrawBuffers(n, bufs); } void glDrawBuffersARB(GLsizei n, const GLenum * bufs) { return Binding::DrawBuffersARB(n, bufs); } void glDrawBuffersATI(GLsizei n, const GLenum * bufs) { return Binding::DrawBuffersATI(n, bufs); } void glDrawCommandsAddressNV(GLenum primitiveMode, const GLuint64 * indirects, const GLsizei * sizes, GLuint count) { return Binding::DrawCommandsAddressNV(primitiveMode, indirects, sizes, count); } void glDrawCommandsNV(GLenum primitiveMode, GLuint buffer, const GLintptr * indirects, const GLsizei * sizes, GLuint count) { return Binding::DrawCommandsNV(primitiveMode, buffer, indirects, sizes, count); } void glDrawCommandsStatesAddressNV(const GLuint64 * indirects, const GLsizei * sizes, const GLuint * states, const GLuint * fbos, GLuint count) { return Binding::DrawCommandsStatesAddressNV(indirects, sizes, states, fbos, count); } void glDrawCommandsStatesNV(GLuint buffer, const GLintptr * indirects, const GLsizei * sizes, const GLuint * states, const GLuint * fbos, GLuint count) { return Binding::DrawCommandsStatesNV(buffer, indirects, sizes, states, fbos, count); } void glDrawElementArrayAPPLE(GLenum mode, GLint first, GLsizei count) { return Binding::DrawElementArrayAPPLE(mode, first, count); } void glDrawElementArrayATI(GLenum mode, GLsizei count) { return Binding::DrawElementArrayATI(mode, count); } void glDrawElements(GLenum mode, GLsizei count, GLenum type, const void * indices) { return Binding::DrawElements(mode, count, type, indices); } void glDrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type, const void * indices, GLint basevertex) { return Binding::DrawElementsBaseVertex(mode, count, type, indices, basevertex); } void glDrawElementsIndirect(GLenum mode, GLenum type, const void * indirect) { return Binding::DrawElementsIndirect(mode, type, indirect); } void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount) { return Binding::DrawElementsInstanced(mode, count, type, indices, instancecount); } void glDrawElementsInstancedARB(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei primcount) { return Binding::DrawElementsInstancedARB(mode, count, type, indices, primcount); } void glDrawElementsInstancedBaseInstance(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLuint baseinstance) { return Binding::DrawElementsInstancedBaseInstance(mode, count, type, indices, instancecount, baseinstance); } void glDrawElementsInstancedBaseVertex(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex) { return Binding::DrawElementsInstancedBaseVertex(mode, count, type, indices, instancecount, basevertex); } void glDrawElementsInstancedBaseVertexBaseInstance(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance) { return Binding::DrawElementsInstancedBaseVertexBaseInstance(mode, count, type, indices, instancecount, basevertex, baseinstance); } void glDrawElementsInstancedEXT(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei primcount) { return Binding::DrawElementsInstancedEXT(mode, count, type, indices, primcount); } void glDrawMeshArraysSUN(GLenum mode, GLint first, GLsizei count, GLsizei width) { return Binding::DrawMeshArraysSUN(mode, first, count, width); } void glDrawPixels(GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels) { return Binding::DrawPixels(width, height, format, type, pixels); } void glDrawRangeElementArrayAPPLE(GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count) { return Binding::DrawRangeElementArrayAPPLE(mode, start, end, first, count); } void glDrawRangeElementArrayATI(GLenum mode, GLuint start, GLuint end, GLsizei count) { return Binding::DrawRangeElementArrayATI(mode, start, end, count); } void glDrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices) { return Binding::DrawRangeElements(mode, start, end, count, type, indices); } void glDrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices, GLint basevertex) { return Binding::DrawRangeElementsBaseVertex(mode, start, end, count, type, indices, basevertex); } void glDrawRangeElementsEXT(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices) { return Binding::DrawRangeElementsEXT(mode, start, end, count, type, indices); } void glDrawTextureNV(GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1) { return Binding::DrawTextureNV(texture, sampler, x0, y0, x1, y1, z, s0, t0, s1, t1); } void glDrawTransformFeedback(GLenum mode, GLuint id) { return Binding::DrawTransformFeedback(mode, id); } void glDrawTransformFeedbackInstanced(GLenum mode, GLuint id, GLsizei instancecount) { return Binding::DrawTransformFeedbackInstanced(mode, id, instancecount); } void glDrawTransformFeedbackNV(GLenum mode, GLuint id) { return Binding::DrawTransformFeedbackNV(mode, id); } void glDrawTransformFeedbackStream(GLenum mode, GLuint id, GLuint stream) { return Binding::DrawTransformFeedbackStream(mode, id, stream); } void glDrawTransformFeedbackStreamInstanced(GLenum mode, GLuint id, GLuint stream, GLsizei instancecount) { return Binding::DrawTransformFeedbackStreamInstanced(mode, id, stream, instancecount); } void glDrawVkImageNV(GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1) { return Binding::DrawVkImageNV(vkImage, sampler, x0, y0, x1, y1, z, s0, t0, s1, t1); } } // namespace gl
28.504854
232
0.770322
j-o
a8bd6b6dec9bb821a5b3ef6b09a21c3213aa6ec0
4,465
hpp
C++
include/seqan3/core/algorithm/all.hpp
h-2/seqan3
2cbc19c6f2cdb76c65ed6ff6ae70fc67334146d7
[ "CC-BY-4.0", "CC0-1.0" ]
4
2018-03-09T09:37:51.000Z
2020-07-28T04:52:01.000Z
include/seqan3/core/algorithm/all.hpp
h-2/seqan3
2cbc19c6f2cdb76c65ed6ff6ae70fc67334146d7
[ "CC-BY-4.0", "CC0-1.0" ]
null
null
null
include/seqan3/core/algorithm/all.hpp
h-2/seqan3
2cbc19c6f2cdb76c65ed6ff6ae70fc67334146d7
[ "CC-BY-4.0", "CC0-1.0" ]
1
2018-03-09T09:37:54.000Z
2018-03-09T09:37:54.000Z
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- /*!\file * \brief Meta-Header for components of the algorithm submodule. * \author Rene Rahn <rene.rahn AT fu-berlin.de> */ #pragma once /*!\defgroup algorithm Algorithm * \ingroup core * \brief Provides core functionality used to configure algorithms. * * \details * * In SeqAn there are many algorithms, e.g. alignment or search algorithms, that can be configured through * many different settings and policies that alter the execution of the respective algorithm. * These configurations can be orthogonal or might be mutually exclusive and can make interfaces very difficult to use. * This module provides a basic system to manage the configurations of algorithms using a unified interface. * * ### Usage * * The basis of any algorithm configuration are configuration elements. These are objects that handle a specific * setting and must satisfy the seqan3::detail::ConfigElement. The following snippet demonstrates a * basic setup for such configuration elements. * * \snippet test/snippet/core/algorithm/configuration.cpp configuration_setup * * Here, two classes with the name `bar` and `foo` are created. They can be normal or template classes and must * inherit from seqan3::pipeable_config_element and contain a member with the name `value` to satisfy the respective * concept. The separate `value` member is used for a proper encapsulation from the actual setting parameter. * For example the alignment algorithms require a scoring scheme, but the scoring scheme itself should not be pipeable * with other settings. * * In addition an enum type was defined that will be used later to allow for compatibility checks when combining * settings in a configuration object. This enum assigns every configuration element a unique id. * To provide compatibility checks the `seqan3::detail::compatibility_table` must be overloaded for the specific * algorithm configuration. * * \snippet test/snippet/core/algorithm/configuration.cpp compatibility * * The type for the configuration element ids is used to overload the bool table. In the example above, both * elements can be combined with each other but not with themselves, to avoid inconsistent settings. * * ### Combining Configurations * * To enable easy creation of algorithm settings the seqan3::configuration supports a pipeable interface for the * different configuration elements which are added through the seqan3::pipeable_config_element base class. * The following snippet demonstrates how `bar` and `foo` can be combined. * * \snippet test/snippet/core/algorithm/configuration.cpp combine * ### Access the data * * The configuration inherits from a std::tuple and exposes a tuple like interface using the standard * position-based and type-based `get` interfaces. The `get` interface was extended to also support * template template types as input template parameters to query the correct element: * * \snippet test/snippet/core/algorithm/configuration.cpp get * * The get interface returns a reference to the stored configuration element. In some cases, e.g. the implementor * of the actual algorithm, one wants to have an easy access to the actual value of the setting. Since, the * configuration must not contain all possible configuration elements the seqan3::configuration provides a * seqan3::configuration::value_or interface, which provides direct access to the value of the respective * configuration element or uses a default value if the queried type is not contained in the configuration. * * \snippet test/snippet/core/algorithm/configuration.cpp value_or */ #include <seqan3/core/algorithm/bound.hpp> #include <seqan3/core/algorithm/concept.hpp> #include <seqan3/core/algorithm/configuration_utility.hpp> #include <seqan3/core/algorithm/configuration.hpp> #include <seqan3/core/algorithm/parameter_pack.hpp> #include <seqan3/core/algorithm/pipeable_config_element.hpp>
55.8125
119
0.747144
h-2
a8c03f48697e81f1d38f294227fc5696fc575a31
23,961
cpp
C++
_studio/enctools/src/mfx_enctools_common.cpp
alexelizarov/oneVPL-intel-gpu
1aecebeea5e73670f194481b4c1402628837506f
[ "MIT" ]
null
null
null
_studio/enctools/src/mfx_enctools_common.cpp
alexelizarov/oneVPL-intel-gpu
1aecebeea5e73670f194481b4c1402628837506f
[ "MIT" ]
null
null
null
_studio/enctools/src/mfx_enctools_common.cpp
alexelizarov/oneVPL-intel-gpu
1aecebeea5e73670f194481b4c1402628837506f
[ "MIT" ]
1
2021-07-13T08:25:02.000Z
2021-07-13T08:25:02.000Z
// Copyright (c) 2019-2021 Intel Corporation // // 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 "mfx_enctools.h" #include <algorithm> #include <math.h> mfxExtBuffer* Et_GetExtBuffer(mfxExtBuffer** extBuf, mfxU32 numExtBuf, mfxU32 id) { if (extBuf != 0) { for (mfxU16 i = 0; i < numExtBuf; i++) { if (extBuf[i] != 0 && extBuf[i]->BufferId == id) // assuming aligned buffers return (extBuf[i]); } } return 0; } mfxStatus InitCtrl(mfxVideoParam const & par, mfxEncToolsCtrl *ctrl) { MFX_CHECK_NULL_PTR1(ctrl); mfxExtCodingOption *CO = (mfxExtCodingOption *)Et_GetExtBuffer(par.ExtParam, par.NumExtParam, MFX_EXTBUFF_CODING_OPTION); mfxExtCodingOption2 *CO2 = (mfxExtCodingOption2 *)Et_GetExtBuffer(par.ExtParam, par.NumExtParam, MFX_EXTBUFF_CODING_OPTION2); mfxExtCodingOption3 *CO3 = (mfxExtCodingOption3 *)Et_GetExtBuffer(par.ExtParam, par.NumExtParam, MFX_EXTBUFF_CODING_OPTION3); MFX_CHECK_NULL_PTR3(CO, CO2, CO3); ctrl = {}; ctrl->CodecId = par.mfx.CodecId; ctrl->CodecProfile = par.mfx.CodecProfile; ctrl->CodecLevel = par.mfx.CodecLevel; ctrl->FrameInfo = par.mfx.FrameInfo; ctrl->IOPattern = par.IOPattern; ctrl->MaxDelayInFrames = CO2->LookAheadDepth; ctrl->MaxGopSize = par.mfx.GopPicSize; ctrl->MaxGopRefDist = par.mfx.GopRefDist; ctrl->MaxIDRDist = par.mfx.GopPicSize * (par.mfx.IdrInterval + 1); ctrl->BRefType = CO2->BRefType; ctrl->ScenarioInfo = CO3->ScenarioInfo; // Rate control info mfxU32 mult = par.mfx.BRCParamMultiplier ? par.mfx.BRCParamMultiplier : 1; bool BRC = (par.mfx.RateControlMethod == MFX_RATECONTROL_CBR || par.mfx.RateControlMethod == MFX_RATECONTROL_VBR); ctrl->RateControlMethod = par.mfx.RateControlMethod; //CBR, VBR, CRF,CQP if (!BRC) { ctrl->QPLevel[0] = par.mfx.QPI; ctrl->QPLevel[1] = par.mfx.QPP; ctrl->QPLevel[2] = par.mfx.QPB; } else { ctrl->TargetKbps = par.mfx.TargetKbps*mult; ctrl->MaxKbps = par.mfx.MaxKbps*mult; ctrl->HRDConformance = MFX_BRC_NO_HRD; if (!IsOff(CO->NalHrdConformance) && !IsOff(CO->VuiNalHrdParameters)) ctrl->HRDConformance = MFX_BRC_HRD_STRONG; else if (IsOn(CO->NalHrdConformance) && IsOff(CO->VuiNalHrdParameters)) ctrl->HRDConformance = MFX_BRC_HRD_WEAK; if (ctrl->HRDConformance) { ctrl->BufferSizeInKB = par.mfx.BufferSizeInKB*mult; //if HRDConformance is ON ctrl->InitialDelayInKB = par.mfx.InitialDelayInKB*mult; //if HRDConformance is ON } else { ctrl->ConvergencePeriod = 0; //if HRDConformance is OFF, 0 - the period is whole stream, ctrl->Accuracy = 10; //if HRDConformance is OFF } ctrl->WinBRCMaxAvgKbps = CO3->WinBRCMaxAvgKbps*mult; ctrl->WinBRCSize = CO3->WinBRCSize; ctrl->MaxFrameSizeInBytes[0] = CO3->MaxFrameSizeI ? CO3->MaxFrameSizeI : CO2->MaxFrameSize; // MaxFrameSize limitation ctrl->MaxFrameSizeInBytes[1] = CO3->MaxFrameSizeP ? CO3->MaxFrameSizeP : CO2->MaxFrameSize; ctrl->MaxFrameSizeInBytes[2] = CO2->MaxFrameSize; ctrl->MinQPLevel[0] = CO2->MinQPI; //QP range limitations ctrl->MinQPLevel[1] = CO2->MinQPP; ctrl->MinQPLevel[2] = CO2->MinQPB; ctrl->MaxQPLevel[0] = CO2->MaxQPI; //QP range limitations ctrl->MaxQPLevel[1] = CO2->MaxQPP; ctrl->MaxQPLevel[2] = CO2->MaxQPB; ctrl->PanicMode = CO3->BRCPanicMode; } return MFX_ERR_NONE; } inline void SetToolsStatus(mfxExtEncToolsConfig* conf, bool bOn) { conf->SceneChange = conf->AdaptiveI = conf->AdaptiveB = conf->AdaptiveRefP = conf->AdaptiveRefB = conf->AdaptiveLTR = conf->AdaptivePyramidQuantP = conf->AdaptivePyramidQuantB = conf->AdaptiveQuantMatrices = conf->BRCBufferHints = conf->BRC = mfxU16(bOn ? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF); } inline void CopyPreEncSCTools(mfxExtEncToolsConfig const & confIn, mfxExtEncToolsConfig* confOut) { confOut->AdaptiveI = confIn.AdaptiveI; confOut->AdaptiveB = confIn.AdaptiveB; confOut->AdaptiveRefP = confIn.AdaptiveRefP; confOut->AdaptiveRefB = confIn.AdaptiveRefB; confOut->AdaptiveLTR = confIn.AdaptiveLTR; confOut->AdaptivePyramidQuantP = confIn.AdaptivePyramidQuantP; confOut->AdaptivePyramidQuantB = confIn.AdaptivePyramidQuantB; } inline void OffPreEncSCDTools(mfxExtEncToolsConfig* conf) { mfxExtEncToolsConfig confIn = {}; SetToolsStatus(&confIn, false); CopyPreEncSCTools(confIn, conf); } inline void CopyPreEncLATools(mfxExtEncToolsConfig const & confIn, mfxExtEncToolsConfig* confOut) { confOut->AdaptiveQuantMatrices = confIn.AdaptiveQuantMatrices; confOut->BRCBufferHints = confIn.BRCBufferHints; confOut->AdaptivePyramidQuantP = confIn.AdaptivePyramidQuantP; confOut->AdaptiveI = confIn.AdaptiveI; } inline void OffPreEncLATools(mfxExtEncToolsConfig* conf) { mfxExtEncToolsConfig confIn = {}; SetToolsStatus(&confIn, false); CopyPreEncLATools(confIn, conf); } inline bool isPreEncSCD(mfxExtEncToolsConfig const & conf, mfxEncToolsCtrl const & ctrl) { return ((IsOn(conf.AdaptiveI) || IsOn(conf.AdaptiveB) || IsOn(conf.AdaptiveRefP) || IsOn(conf.AdaptiveRefB) || IsOn(conf.AdaptiveLTR) || IsOn(conf.AdaptivePyramidQuantP) || IsOn(conf.AdaptivePyramidQuantB)) && ctrl.ScenarioInfo != MFX_SCENARIO_GAME_STREAMING); } inline bool isPreEncLA(mfxExtEncToolsConfig const & conf, mfxEncToolsCtrl const & ctrl) { return ( ctrl.ScenarioInfo == MFX_SCENARIO_GAME_STREAMING && (IsOn(conf.AdaptiveI) || IsOn(conf.AdaptiveQuantMatrices) || IsOn(conf.BRCBufferHints) || IsOn(conf.AdaptivePyramidQuantP))); } mfxStatus EncTools::GetSupportedConfig(mfxExtEncToolsConfig* config, mfxEncToolsCtrl const * ctrl) { MFX_CHECK_NULL_PTR2(config, ctrl); SetToolsStatus(config, false); config->BRC = (mfxU16)((ctrl->RateControlMethod == MFX_RATECONTROL_CBR || ctrl->RateControlMethod == MFX_RATECONTROL_VBR)? MFX_CODINGOPTION_ON : MFX_CODINGOPTION_OFF); if (ctrl->ScenarioInfo != MFX_SCENARIO_GAME_STREAMING) { if (ctrl->MaxGopRefDist == 8 || ctrl->MaxGopRefDist == 4 || ctrl->MaxGopRefDist == 2 || ctrl->MaxGopRefDist == 1) { config->SceneChange = MFX_CODINGOPTION_ON; config->AdaptiveI = MFX_CODINGOPTION_ON; config->AdaptiveB = MFX_CODINGOPTION_ON; config->AdaptiveRefP = MFX_CODINGOPTION_ON; config->AdaptiveRefB = MFX_CODINGOPTION_ON; config->AdaptiveLTR = MFX_CODINGOPTION_ON; config->AdaptivePyramidQuantP = MFX_CODINGOPTION_ON; config->AdaptivePyramidQuantB = MFX_CODINGOPTION_ON; } } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else { config->AdaptiveQuantMatrices = MFX_CODINGOPTION_ON; config->BRCBufferHints = MFX_CODINGOPTION_ON; config->SceneChange = MFX_CODINGOPTION_ON; config->AdaptivePyramidQuantP = MFX_CODINGOPTION_ON; config->AdaptiveI = MFX_CODINGOPTION_ON; config->AdaptiveB = MFX_CODINGOPTION_ON; config->AdaptivePyramidQuantB = MFX_CODINGOPTION_ON; } #endif return MFX_ERR_NONE; } mfxStatus EncTools::GetActiveConfig(mfxExtEncToolsConfig* pConfig) { MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); MFX_CHECK_NULL_PTR1(pConfig); *pConfig = m_config; return MFX_ERR_NONE; } mfxStatus EncTools::GetDelayInFrames(mfxExtEncToolsConfig const * config, mfxEncToolsCtrl const * ctrl, mfxU32 *numFrames) { MFX_CHECK_NULL_PTR3(config, ctrl, numFrames); //to fix: delay should be asked from m_scd *numFrames = (isPreEncSCD(*config, *ctrl)) ? 8 : 0; // #if defined (MFX_ENABLE_ENCTOOLS_LPLA) if (isPreEncLA(*config, *ctrl)) { *numFrames = std::max(*numFrames, (mfxU32)ctrl->MaxDelayInFrames); } #endif return MFX_ERR_NONE; } mfxStatus EncTools::InitVPP(mfxEncToolsCtrl const & ctrl) { MFX_CHECK(!m_bVPPInit, MFX_ERR_UNDEFINED_BEHAVIOR); MFX_CHECK(m_device && m_pAllocator, MFX_ERR_UNDEFINED_BEHAVIOR); mfxStatus sts; if (mfxSession(m_mfxSession) == 0) { mfxInitParam initPar = {}; initPar.Version.Major = 1; initPar.Version.Minor = 0; initPar.Implementation = MFX_IMPL_HARDWARE; initPar.Implementation |= (m_deviceType == MFX_HANDLE_D3D11_DEVICE ? MFX_IMPL_VIA_D3D11 : (m_deviceType == MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9 ? MFX_IMPL_VIA_D3D9 : MFX_IMPL_VIA_VAAPI)); initPar.GPUCopy = MFX_GPUCOPY_DEFAULT; sts = m_mfxSession.InitEx(initPar); MFX_CHECK_STS(sts); } //mfxVersion version; // real API version with which library is initialized //sts = MFXQueryVersion(m_mfxSession, &version); // get real API version of the loaded library //MFX_CHECK_STS(sts); sts = m_mfxSession.SetFrameAllocator(m_pAllocator); MFX_CHECK_STS(sts); sts = m_mfxSession.SetHandle((mfxHandleType)m_deviceType, m_device); MFX_CHECK_STS(sts); m_pmfxVPP.reset(new MFXVideoVPP(m_mfxSession)); MFX_CHECK(m_pmfxVPP, MFX_ERR_MEMORY_ALLOC); sts = InitMfxVppParams(ctrl); MFX_CHECK_STS(sts); mfxExtVPPScaling vppScalingMode = {}; vppScalingMode.Header.BufferId = MFX_EXTBUFF_VPP_SCALING; vppScalingMode.Header.BufferSz = sizeof(vppScalingMode); vppScalingMode.ScalingMode = MFX_SCALING_MODE_LOWPOWER; vppScalingMode.InterpolationMethod = MFX_INTERPOLATION_NEAREST_NEIGHBOR; std::vector<mfxExtBuffer*> extParams; extParams.push_back((mfxExtBuffer *)&vppScalingMode); m_mfxVppParams.ExtParam = extParams.data(); m_mfxVppParams.NumExtParam = (mfxU16)extParams.size(); sts = m_pmfxVPP->Init(&m_mfxVppParams); MFX_CHECK_STS(sts); mfxFrameAllocRequest VppRequest[2]; sts = m_pmfxVPP->QueryIOSurf(&m_mfxVppParams, VppRequest); MFX_CHECK_STS(sts); VppRequest[1].Type |= MFX_MEMTYPE_FROM_DECODE; // ffmpeg's qsv allocator requires MFX_MEMTYPE_FROM_DECODE or MFX_MEMTYPE_FROM_ENCODE sts = m_pAllocator->Alloc(m_pAllocator->pthis, &(VppRequest[1]), &m_VppResponse); MFX_CHECK_STS(sts); m_pIntSurfaces.resize(m_VppResponse.NumFrameActual); for (mfxU32 i = 0; i < (mfxU32)m_pIntSurfaces.size(); i++) { m_pIntSurfaces[i] = {}; m_pIntSurfaces[i].Info = m_mfxVppParams.vpp.Out; m_pIntSurfaces[i].Data.MemId = m_VppResponse.mids[i]; } m_bVPPInit = true; return MFX_ERR_NONE; } mfxStatus EncTools::InitMfxVppParams(mfxEncToolsCtrl const & ctrl) { m_mfxVppParams.IOPattern = ctrl.IOPattern | MFX_IOPATTERN_OUT_VIDEO_MEMORY; m_mfxVppParams.vpp.In = ctrl.FrameInfo; m_mfxVppParams.vpp.Out = m_mfxVppParams.vpp.In; if (isPreEncSCD(m_config, ctrl)) { mfxFrameInfo frameInfo; mfxStatus sts = m_scd.GetInputFrameInfo(frameInfo); MFX_CHECK_STS(sts); m_mfxVppParams.vpp.Out.Width = frameInfo.Width; m_mfxVppParams.vpp.Out.Height = frameInfo.Height; m_mfxVppParams.vpp.Out.CropW = m_mfxVppParams.vpp.Out.Width; m_mfxVppParams.vpp.Out.CropH = m_mfxVppParams.vpp.Out.Height; } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else // LPLA { if (!m_mfxVppParams.vpp.In.CropW) m_mfxVppParams.vpp.In.CropW = m_mfxVppParams.vpp.In.Width; if (!m_mfxVppParams.vpp.In.CropH) m_mfxVppParams.vpp.In.CropH = m_mfxVppParams.vpp.In.Height; mfxU32 downscale = 0; m_lpLookAhead.GetDownScaleParams(m_mfxVppParams.vpp.Out, downscale); mfxPlatform platform; m_mfxSession.QueryPlatform(&platform); if (platform.CodeName < MFX_PLATFORM_TIGERLAKE) { m_mfxVppParams.vpp.In.CropW = m_mfxVppParams.vpp.In.Width = m_mfxVppParams.vpp.In.CropW & ~0x3F; m_mfxVppParams.vpp.In.CropH = m_mfxVppParams.vpp.In.Height = m_mfxVppParams.vpp.In.CropH & ~0x3F; } } #endif return MFX_ERR_NONE; } mfxStatus EncTools::CloseVPP() { MFX_CHECK(m_bVPPInit, MFX_ERR_NOT_INITIALIZED); mfxStatus sts; if (m_pAllocator) { m_pAllocator->Free(m_pAllocator->pthis, &m_VppResponse); m_pAllocator = nullptr; } if (m_pIntSurfaces.size()) m_pIntSurfaces.clear(); if (m_pmfxVPP) { m_pmfxVPP->Close(); m_pmfxVPP.reset(); } sts = m_mfxSession.Close(); MFX_CHECK_STS(sts); m_bVPPInit = false; return sts; } mfxStatus EncTools::Init(mfxExtEncToolsConfig const * pConfig, mfxEncToolsCtrl const * ctrl) { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK_NULL_PTR2(pConfig, ctrl); MFX_CHECK(!m_bInit, MFX_ERR_UNDEFINED_BEHAVIOR); m_ctrl = *ctrl; mfxU16 crW = ctrl->FrameInfo.CropW ? ctrl->FrameInfo.CropW : ctrl->FrameInfo.Width; bool needVPP = (ctrl->IOPattern & MFX_IOPATTERN_IN_VIDEO_MEMORY) && (isPreEncSCD(*pConfig, *ctrl) || (isPreEncLA(*pConfig, *ctrl) && crW >= 720)); needVPP = needVPP || ((ctrl->IOPattern & MFX_IOPATTERN_IN_SYSTEM_MEMORY) && isPreEncLA(*pConfig, *ctrl)); if (needVPP) { mfxEncToolsCtrlExtDevice *extDevice = (mfxEncToolsCtrlExtDevice *)Et_GetExtBuffer(ctrl->ExtParam, ctrl->NumExtParam, MFX_EXTBUFF_ENCTOOLS_DEVICE); if (extDevice) { m_device = extDevice->DeviceHdl; m_deviceType = extDevice->HdlType; } if (!m_device) return MFX_ERR_UNDEFINED_BEHAVIOR; mfxEncToolsCtrlExtAllocator *extAlloc = (mfxEncToolsCtrlExtAllocator *)Et_GetExtBuffer(ctrl->ExtParam, ctrl->NumExtParam, MFX_EXTBUFF_ENCTOOLS_ALLOCATOR); if (extAlloc) m_pAllocator = extAlloc->pAllocator; if (!m_pAllocator) { MFX_CHECK_NULL_PTR1(m_pETAllocator); sts = m_pETAllocator->Init(m_pmfxAllocatorParams); MFX_CHECK_STS(sts); m_pAllocator = m_pETAllocator; } } SetToolsStatus(&m_config, false); if (IsOn(pConfig->BRC)) { sts = m_brc.Init(*ctrl); MFX_CHECK_STS(sts); m_config.BRC = MFX_CODINGOPTION_ON; } if (isPreEncSCD(*pConfig, *ctrl)) { sts = m_scd.Init(*ctrl, *pConfig); MFX_CHECK_STS(sts); // to add request to m_scd about supported tools CopyPreEncSCTools(*pConfig, &m_config); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) if (isPreEncLA(*pConfig, *ctrl)) { m_lpLookAhead.SetAllocator(m_pAllocator); sts = m_lpLookAhead.Init(*ctrl, *pConfig); MFX_CHECK_STS(sts); CopyPreEncLATools(*pConfig, &m_config); } #endif if (needVPP) { sts = InitVPP(*ctrl); MFX_CHECK_STS(sts); } m_bInit = true; return sts; } mfxStatus EncTools::Close() { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); if (IsOn(m_config.BRC)) { m_brc.Close(); m_config.BRC = false; } if (isPreEncSCD(m_config, m_ctrl)) { m_scd.Close(); OffPreEncSCDTools(&m_config); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) if (isPreEncLA(m_config, m_ctrl)) { m_lpLookAhead.Close(); OffPreEncLATools(&m_config); } #endif if (m_bVPPInit) sts = CloseVPP(); m_bInit = false; return sts; } mfxStatus EncTools::Reset(mfxExtEncToolsConfig const * config, mfxEncToolsCtrl const * ctrl) { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK_NULL_PTR2(config,ctrl); MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); if (IsOn(config->BRC)) { MFX_CHECK(m_config.BRC, MFX_ERR_UNSUPPORTED); sts = m_brc.Reset(*ctrl); } if (isPreEncSCD(*config, *ctrl)) { // to add check if Close/Init is real needed if (isPreEncSCD(m_config, m_ctrl)) m_scd.Close(); sts = m_scd.Init(*ctrl, *config); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) if (isPreEncLA(*config, *ctrl)) { // to add check if Close/Init is real needed if (isPreEncLA(m_config, m_ctrl)) m_lpLookAhead.Close(); sts = m_lpLookAhead.Init(*ctrl, *config); } #endif return sts; } #define MSDK_VPP_WAIT_INTERVAL 300000 mfxStatus EncTools::VPPDownScaleSurface(mfxFrameSurface1 *pInSurface, mfxFrameSurface1 *pOutSurface) { mfxStatus sts; MFX_CHECK_NULL_PTR2(pInSurface, pOutSurface); mfxSyncPoint vppSyncp; sts = m_pmfxVPP->RunFrameVPPAsync(pInSurface, pOutSurface, NULL, &vppSyncp); MFX_CHECK_STS(sts); sts = m_mfxSession.SyncOperation(vppSyncp, MSDK_VPP_WAIT_INTERVAL); MFX_CHECK_STS(sts); return MFX_ERR_NONE; } mfxStatus EncTools::Submit(mfxEncToolsTaskParam const * par) { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK_NULL_PTR1(par); MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); mfxEncToolsFrameToAnalyze *pFrameData = (mfxEncToolsFrameToAnalyze *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_FRAME_TO_ANALYZE); if (pFrameData) { pFrameData->Surface->Data.FrameOrder = par->DisplayOrder; if (m_bVPPInit && (isPreEncSCD(m_config, m_ctrl) || isPreEncLA(m_config, m_ctrl))) { sts = VPPDownScaleSurface(pFrameData->Surface, m_pIntSurfaces.data()); MFX_CHECK_STS(sts); m_pIntSurfaces[0].Data.FrameOrder = pFrameData->Surface->Data.FrameOrder; if (isPreEncSCD(m_config, m_ctrl)) { m_pAllocator->Lock(m_pAllocator->pthis, m_pIntSurfaces[0].Data.MemId, &m_pIntSurfaces[0].Data); sts = m_scd.SubmitFrame(m_pIntSurfaces.data()); m_pAllocator->Unlock(m_pAllocator->pthis, m_pIntSurfaces[0].Data.MemId, &m_pIntSurfaces[0].Data); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else if (isPreEncLA(m_config, m_ctrl)) sts = m_lpLookAhead.Submit(m_pIntSurfaces.data()); #endif } else if (isPreEncSCD(m_config, m_ctrl)) sts = m_scd.SubmitFrame(pFrameData->Surface); #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else if (isPreEncLA(m_config, m_ctrl)) sts = m_lpLookAhead.Submit(pFrameData->Surface); #endif return sts; } mfxEncToolsBRCEncodeResult *pEncRes = (mfxEncToolsBRCEncodeResult *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_ENCODE_RESULT); if (pEncRes) { m_scd.ReportEncResult(par->DisplayOrder, *pEncRes); } if (pEncRes && IsOn(m_config.BRC)) { return m_brc.ReportEncResult(par->DisplayOrder, *pEncRes); } mfxEncToolsBRCFrameParams *pFrameStruct = (mfxEncToolsBRCFrameParams *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_FRAME_PARAM ); if (pFrameStruct && IsOn(m_config.BRC)) { sts = m_brc.SetFrameStruct(par->DisplayOrder, *pFrameStruct); MFX_CHECK_STS(sts); } mfxEncToolsBRCBufferHint *pBRCHints = (mfxEncToolsBRCBufferHint *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_BUFFER_HINT); if (pBRCHints && IsOn(m_config.BRC)) { return m_brc.ReportBufferHints(par->DisplayOrder, *pBRCHints); } mfxEncToolsHintPreEncodeGOP *pPreEncGOP = (mfxEncToolsHintPreEncodeGOP *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_GOP); if (pPreEncGOP && IsOn(m_config.BRC)) { return m_brc.ReportGopHints(par->DisplayOrder, *pPreEncGOP); } return sts; } mfxStatus EncTools::Query(mfxEncToolsTaskParam* par, mfxU32 /*timeOut*/) { mfxStatus sts = MFX_ERR_NONE; MFX_CHECK_NULL_PTR1(par); MFX_CHECK(m_bInit, MFX_ERR_NOT_INITIALIZED); mfxEncToolsHintPreEncodeSceneChange *pPreEncSC = (mfxEncToolsHintPreEncodeSceneChange *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_SCENE_CHANGE); if (pPreEncSC) { sts = m_scd.GetSCDecision(par->DisplayOrder, pPreEncSC); MFX_CHECK_STS(sts); } mfxEncToolsHintPreEncodeGOP *pPreEncGOP = (mfxEncToolsHintPreEncodeGOP *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_GOP); if (pPreEncGOP) { if (isPreEncSCD(m_config, m_ctrl)) sts = m_scd.GetGOPDecision(par->DisplayOrder, pPreEncGOP); #if defined (MFX_ENABLE_ENCTOOLS_LPLA) else { sts = m_lpLookAhead.Query(par->DisplayOrder, pPreEncGOP); if (sts == MFX_ERR_NOT_FOUND) sts = MFX_ERR_NONE; } #endif MFX_CHECK_STS(sts); } mfxEncToolsHintPreEncodeARefFrames *pPreEncARef = (mfxEncToolsHintPreEncodeARefFrames *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_AREF); if (pPreEncARef) { sts = m_scd.GetARefDecision(par->DisplayOrder, pPreEncARef); MFX_CHECK_STS(sts); } #if defined (MFX_ENABLE_ENCTOOLS_LPLA) mfxEncToolsHintQuantMatrix *pCqmHint = (mfxEncToolsHintQuantMatrix *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_HINT_MATRIX); if (pCqmHint) { sts = m_lpLookAhead.Query(par->DisplayOrder, pCqmHint); if (sts == MFX_ERR_NOT_FOUND) sts = MFX_ERR_NONE; MFX_CHECK_STS(sts); } mfxEncToolsBRCBufferHint *bufferHint = (mfxEncToolsBRCBufferHint *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_BUFFER_HINT); if (bufferHint) { sts = m_lpLookAhead.Query(par->DisplayOrder, bufferHint); if (sts == MFX_ERR_NOT_FOUND) sts = MFX_ERR_NONE; MFX_CHECK_STS(sts); } #endif mfxEncToolsBRCStatus *pFrameSts = (mfxEncToolsBRCStatus *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_STATUS); if (pFrameSts && IsOn(m_config.BRC)) { return m_brc.UpdateFrame(par->DisplayOrder, pFrameSts); } mfxEncToolsBRCQuantControl *pFrameQp = (mfxEncToolsBRCQuantControl *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_QUANT_CONTROL); if (pFrameQp && IsOn(m_config.BRC)) { sts = m_brc.ProcessFrame(par->DisplayOrder, pFrameQp); MFX_CHECK_STS(sts); } mfxEncToolsBRCHRDPos *pHRDPos = (mfxEncToolsBRCHRDPos *)Et_GetExtBuffer(par->ExtParam, par->NumExtParam, MFX_EXTBUFF_ENCTOOLS_BRC_HRD_POS); if (pHRDPos && IsOn(m_config.BRC)) { sts = m_brc.GetHRDPos(par->DisplayOrder, pHRDPos); MFX_CHECK_STS(sts); } return sts; } mfxStatus EncTools::Discard(mfxU32 displayOrder) { mfxStatus sts = MFX_ERR_NONE; sts = m_scd.CompleteFrame(displayOrder); return sts; }
34.377331
194
0.683527
alexelizarov
a8c0d02ac2dfe6f87a733efaa1d1891fe141ba39
1,359
cpp
C++
leetcode/Cpp/13.RomantoInteger.cpp
henrytien/AlgorithmSolutions
62339269f4fa698ddd2e73458caef875af05af8f
[ "MIT" ]
15
2020-06-27T03:28:39.000Z
2021-08-13T10:42:24.000Z
leetcode/Cpp/13.RomantoInteger.cpp
henrytien/AlgorithmSolutions
62339269f4fa698ddd2e73458caef875af05af8f
[ "MIT" ]
40
2020-06-27T03:29:53.000Z
2020-11-05T12:29:49.000Z
leetcode/Cpp/13.RomantoInteger.cpp
henrytien/AlgorithmSolutions
62339269f4fa698ddd2e73458caef875af05af8f
[ "MIT" ]
22
2020-07-16T03:23:43.000Z
2022-02-19T16:00:55.000Z
#include"AllInclude.h" class Solution { public: int romanToInt(string s) { int res = 0; char I = 'I', V = 'V', X = 'X', L = 'L', C = 'C', D = 'D', M = 'M'; for (size_t i = 0; i < s.length();) { int end = i + 1; if (s[i] == I && s[i + 1] == V && end < s.length()) // IV = 4 { res += 4; i+=2; } else if (s[i] == I && s[i + 1] == X && end < s.length()) // IX = 9 { res += 9; i+=2; } else if (s[i] == I) { res += 1; ++i; } if (s[i] == V) { res += 5; i++; } if (s[i] == X && s[i + 1] == L && end < s.length()) // XL = 40 { res += 40; i+=2; } else if (s[i] == X && s[i + 1] == C && end < s.length()) // XC = 90 { res += 90; i += 2; } else if (s[i] == X) { res += 10; i++; } if (s[i] == L) { res += 50; ++i; } if (s[i] == C && s[i + 1] == D && end < s.length()) // CD = 400 { res += 400; i += 2; } else if (s[i] == C && s[i + 1] == M && end < s.length()) // CM = 900 { res += 900; i+=2; } else if (s[i] == C) { res += 100; ++i; } if (s[i] == D) { res += 500; ++i; } if (s[i] == M) { res += 1000; i++; } } return res; } }; int main() { string s = "MCDLXXVI"; cout << Solution().romanToInt(s); getchar(); return 0; }
15.1
71
0.338484
henrytien
a8c719ad0486a0f96c8cfe09eda6bb4c74608387
1,533
cc
C++
src/ui/lib/yuv/yuv.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
3
2020-08-02T04:46:18.000Z
2020-08-07T10:10:53.000Z
src/ui/lib/yuv/yuv.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
src/ui/lib/yuv/yuv.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
1
2020-08-07T10:11:49.000Z
2020-08-07T10:11:49.000Z
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ui/lib/yuv/yuv.h" #include <algorithm> #include <cmath> namespace { uint8_t NormalizedFloatToUnsignedByte(float in) { int32_t out = std::roundf(in * 255.0f); return static_cast<uint8_t>(std::clamp(out, 0, 255)); } } // namespace namespace yuv { // Letting compiler decide whether to inline, for now. void YuvToBgra(uint8_t y_raw, uint8_t u_raw, uint8_t v_raw, uint8_t* bgra) { // Convert from encoded space to normalized space assuming eItuNarrow. int32_t y = static_cast<int32_t>(y_raw) - 16; int32_t u = static_cast<int32_t>(u_raw) - 128; int32_t v = static_cast<int32_t>(v_raw) - 128; // Note: Normally, we would clamp here. But some drivers do not clamp in the // middle of their implementation, and this function is used for pixel tests. float fy = static_cast<float>(y) / 219.0f; float fu = static_cast<float>(u) / 224.0f; float fv = static_cast<float>(v) / 224.0f; // Convert from YUV to RGB using the coefficients for eYcbcr709. float r = fy + 1.5748f * fv; float g = fy - (0.13397432f / 0.7152f) * fu - (0.33480248f / 0.7152) * fv; float b = fy + 1.8556f * fu; bgra[0] = NormalizedFloatToUnsignedByte(b); // blue bgra[1] = NormalizedFloatToUnsignedByte(g); // green bgra[2] = NormalizedFloatToUnsignedByte(r); // red bgra[3] = 0xff; // alpha } } // namespace yuv
33.326087
79
0.682975
zhangpf
a8c77a8d6511d8e05f53b5006e55b6a009c4a853
1,285
hpp
C++
src/func.hpp
Dlanis/SDLPong
8229aae0d8b80c530a49e98cb6fb91c1f7768929
[ "MIT" ]
null
null
null
src/func.hpp
Dlanis/SDLPong
8229aae0d8b80c530a49e98cb6fb91c1f7768929
[ "MIT" ]
null
null
null
src/func.hpp
Dlanis/SDLPong
8229aae0d8b80c530a49e98cb6fb91c1f7768929
[ "MIT" ]
null
null
null
#pragma once #include <thread> #include <cmath> #include <SDL.h> #include "ball.hpp" #include "paddle.hpp" constexpr float pi = 3.14159; inline void sleep(double seconds) { std::this_thread::sleep_for(std::chrono::duration<double>(seconds)); } inline constexpr bool intersects(float cx, float cy, float radius, float left, float top, float right, float bottom) { float closestX = (cx < left ? left : (cx > right ? right : cx)); float closestY = (cy < top ? top : (cy > bottom ? bottom : cy)); float dx = closestX - cx; float dy = closestY - cy; return ( dx * dx + dy * dy ) <= radius * radius; } inline constexpr bool intersects(const Ball &ball, const Paddle &paddle) { SDL_FRect paddlerect = paddle.getRect(); return intersects(ball.position.x, ball.position.y, ball.radius, paddlerect.x, paddlerect.y, paddlerect.x + paddlerect.w, paddlerect.y + paddlerect.h); } inline constexpr SDL_FPoint rotate_vector(const SDL_FPoint &vector, const double &degree) { SDL_FPoint m_vector = vector; float l = (m_vector.x > 0 ? m_vector.x : 1) * (m_vector.y > 0 ? m_vector.y : 1); double angle = degree / (180 / pi); m_vector.x = l * std::cos(angle); m_vector.y = l * std::sin(angle); return m_vector; }
29.204545
116
0.65214
Dlanis
a8c8e780539ebbd41bdaf47e88918419b8c5380e
3,671
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/net/UidRange.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/net/UidRange.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/net/UidRange.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "_Elastos.Droid.Os.h" #include "elastos/droid/net/UidRange.h" #include "elastos/droid/net/CUidRange.h" #include <elastos/utility/logging/Logger.h> using Elastos::Droid::Os::IUserHandle; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace Net { CAR_INTERFACE_IMPL_2(UidRange, Object, IParcelable, IUidRange) ECode UidRange::constructor() { return NOERROR; } ECode UidRange::constructor( /* [in] */ Int32 startUid, /* [in] */ Int32 stopUid) { if (startUid < 0) { Logger::E("UidRange", "Invalid start UID."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (stopUid < 0) { Logger::E("UidRange", "Invalid stop UID."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (startUid > stopUid) { Logger::E("UidRange", "Invalid UID range."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } mStart = startUid; mStop = stopUid; return NOERROR; } ECode UidRange::CreateForUser( /* [in] */ Int32 userId, /* [out] */ IUidRange** result) { VALIDATE_NOT_NULL(result) return CUidRange::New(userId * IUserHandle::PER_USER_RANGE, (userId + 1) * IUserHandle::PER_USER_RANGE - 1, result); } ECode UidRange::GetStartUser( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mStart / IUserHandle::PER_USER_RANGE; return NOERROR; } ECode UidRange::GetHashCode( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = 17; *result = 31 * *result + mStart; *result = 31 * *result + mStop; return NOERROR; } ECode UidRange::Equals( /* [in] */ IInterface* o, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) if (TO_IINTERFACE(this) == IInterface::Probe(o)) { *result = TRUE; return NOERROR; } if (IUidRange::Probe(o) != NULL) { AutoPtr<UidRange> other = (UidRange*) IUidRange::Probe(o); *result = mStart == other->mStart && mStop == other->mStop; return NOERROR; } *result = FALSE; return NOERROR; } ECode UidRange::ToString( /* [out] */ String* result) { VALIDATE_NOT_NULL(result) String rev; rev.AppendFormat("%d-%d", mStart, mStop); *result = rev; return NOERROR; } ECode UidRange::ReadFromParcel( /* [in] */ IParcel* parcel) { parcel->ReadInt32(&mStart); parcel->ReadInt32(&mStop); return NOERROR; } ECode UidRange::WriteToParcel( /* [in] */ IParcel* dest) { dest->WriteInt32(mStart); dest->WriteInt32(mStop); return NOERROR; } ECode UidRange::GetStart( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mStart; return NOERROR; } ECode UidRange::GetStop( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mStop; return NOERROR; } } // namespace Net } // namespace Droid } // namespace Elastos
23.993464
120
0.61945
jingcao80
a8c94980f544f30152f6937a3bfdaa292b7e6feb
19,268
cpp
C++
src/trident/ml/batch.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
20
2018-10-17T21:39:40.000Z
2021-11-10T11:07:23.000Z
src/trident/ml/batch.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
5
2020-07-06T22:50:04.000Z
2022-03-17T10:34:15.000Z
src/trident/ml/batch.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
9
2018-09-18T11:37:35.000Z
2022-03-29T07:46:41.000Z
#include <trident/ml/batch.h> #include <trident/kb/kb.h> #include <trident/kb/querier.h> #include <fstream> #include <algorithm> #include <random> #include <unordered_map> BatchCreator::BatchCreator(string kbdir, uint64_t batchsize, uint16_t nthreads, const float valid, const float test, const bool filter, const bool createBatchFile, std::shared_ptr<Feedback> feedback) : kbdir(kbdir), batchsize(batchsize), /*nthreads(nthreads),*/ valid(valid), test(test), createBatchFile(createBatchFile), filter(filter), feedback(feedback) { KBConfig config; this->kb = new KB(kbdir.c_str(), true, false, false, config); rawtriples = NULL; ntriples = 0; currentidx = 0; usedIndex = IDX_POS; } std::shared_ptr<Feedback> BatchCreator::getFeedback() { return feedback; } string BatchCreator::getValidPath() { return kbdir + "/_batch_valid" + std::to_string(this->usedIndex); } string BatchCreator::getTestPath() { return kbdir + "/_batch_test" + std::to_string(this->usedIndex); } string BatchCreator::getValidPath(string kbdir, int usedIndex) { return kbdir + "/_batch_valid" + std::to_string(usedIndex); } string BatchCreator::getTestPath(string kbdir, int usedIndex) { return kbdir + "/_batch_test" + std::to_string(usedIndex); } void BatchCreator::createInputForBatch(bool createTraining, const float valid, const float test) { Querier *q = kb->query(); auto itr = q->getIterator(this->usedIndex, -1, -1, -1); int64_t s, p, o; ofstream ofs_valid; if (valid > 0) { ofs_valid.open(this->kbdir + "/_batch_valid" + std::to_string(this->usedIndex), ios::out | ios::app | ios::binary); } ofstream ofs_test; if (test > 0) { ofs_test.open(this->kbdir + "/_batch_test" + std::to_string(this->usedIndex), ios::out | ios::app | ios::binary); } std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<float> dis(0.0, 1.0); //Create a file called '_batch' in the maindir with a fixed-length record size ofstream ofs; if (createTraining) { LOG(INFOL) << "Store the input for the batch process in " << kbdir + "/_batch" + std::to_string(this->usedIndex) << " ..."; ofs.open(this->kbdir + "/_batch" + std::to_string(this->usedIndex), ios::out | ios::app | ios::binary); } std::unordered_map<uint64_t, uint64_t> mapPredicates; if (!kb->areRelIDsSeparated()) { size_t i = 0; auto querier = kb->query(); auto itr = querier->getTermList(IDX_POS); while (itr->hasNext()) { itr->next(); auto pname = itr->getKey(); mapPredicates.insert(std::make_pair(pname, i)); i++; } querier->releaseItr(itr); delete querier; } while (itr->hasNext()) { itr->next(); if (this->usedIndex == IDX_SPO) { s = itr->getKey(); p = itr->getValue1(); o = itr->getValue2(); } else if (this->usedIndex == IDX_SOP) { s = itr->getKey(); o = itr->getValue1(); p = itr->getValue2(); } else if (this->usedIndex == IDX_POS) { p = itr->getKey(); o = itr->getValue1(); s = itr->getValue2(); } else if (this->usedIndex == IDX_PSO) { p = itr->getKey(); s = itr->getValue1(); o = itr->getValue2(); } else if (this->usedIndex == IDX_OSP) { o = itr->getKey(); s = itr->getValue1(); p = itr->getValue2(); } else if (this->usedIndex == IDX_OPS) { o = itr->getKey(); p = itr->getValue1(); s = itr->getValue2(); } if (!kb->areRelIDsSeparated()) { p = mapPredicates[p]; } const char *cs = (const char*)&s; const char *cp = (const char*)&p; const char *co = (const char*)&o; if (valid > 0 && dis(gen) < valid) { ofs_valid.write(cs, 5); //Max numbers have 5 bytes ofs_valid.write(cp, 5); ofs_valid.write(co, 5); } else if (test > 0 && dis(gen) < test) { ofs_test.write(cs, 5); //Max numbers have 5 bytes ofs_test.write(cp, 5); ofs_test.write(co, 5); } else if (createTraining) { ofs.write(cs, 5); //Max numbers have 5 bytes ofs.write(cp, 5); ofs.write(co, 5); } } q->releaseItr(itr); if (createTraining) { ofs.close(); } if (valid > 0) { ofs_valid.close(); } if (test > 0) { ofs_test.close(); } delete q; LOG(INFOL) << "Done"; } struct _pso { const char *rawtriples; _pso(const char *rawtriples) : rawtriples(rawtriples) {} bool operator() (const uint64_t idx1, const uint64_t idx2) const { int64_t s1 = *(int64_t*)(rawtriples + idx1 * 15); s1 = s1 & 0xFFFFFFFFFFl; int64_t p1 = *(int64_t*)(rawtriples + idx1 * 15 + 5); p1 = p1 & 0xFFFFFFFFFFl; int64_t o1 = *(int64_t*)(rawtriples + idx1 * 15 + 10); o1 = o1 & 0xFFFFFFFFFFl; int64_t s2 = *(int64_t*)(rawtriples + idx2 * 15); s2 = s2 & 0xFFFFFFFFFFl; int64_t p2 = *(int64_t*)(rawtriples + idx2 * 15 + 5); p2 = p2 & 0xFFFFFFFFFFl; int64_t o2 = *(int64_t*)(rawtriples + idx2 * 15 + 10); o2 = o2 & 0xFFFFFFFFFFl; if (p1 != p2) { return p1 < p2; } else if (s1 != s2) { return s1 < s2; } else { return o1 < o2; } } }; int64_t BatchCreator::findFirstOccurrence(int64_t start, int64_t end, uint64_t x, int offset) { int64_t idxTerm = -1; while (start <= end) { int64_t middle = start + (end - start) / 2; int64_t term = *(int64_t*)(rawtriples + middle * 15 + offset); term = term & 0xFFFFFFFFFFl; if (term < x) { start = middle + 1; } else if (term > x) { end = middle - 1; } else { idxTerm = middle; end = middle - 1; } } return idxTerm; } int64_t BatchCreator::findLastOccurrence(int64_t start, int64_t end, uint64_t x, int offset) { int64_t idxTerm = -1; while (start <= end) { int64_t middle = start + (end - start) / 2; int64_t term = *(int64_t*)(rawtriples + middle * 15 + offset); term = term & 0xFFFFFFFFFFl; if (term < x) { start = middle + 1; } else if (term > x) { end = middle - 1; } else { idxTerm = middle; start = middle + 1; } } return idxTerm; } void BatchCreator::populateIndicesFromQuery(int64_t s, int64_t p, int64_t o) { int64_t start = 0; int64_t end = ntriples; int64_t firstTerm = ~0lu; int offset = 0; if (this->usedIndex == IDX_POS || this->usedIndex == IDX_PSO) { firstTerm = p; offset = 5; } else if (this->usedIndex == IDX_SOP || this->usedIndex == IDX_SPO) { firstTerm = s; offset = 0; } else { firstTerm = o; offset = 10; } int64_t idxStartFirstTerm = -1; if (firstTerm != -1) { idxStartFirstTerm = findFirstOccurrence(start, end, firstTerm, offset); if (idxStartFirstTerm != -1) { int64_t idxEndFirstTerm = findLastOccurrence(idxStartFirstTerm, end, firstTerm, offset); start = idxStartFirstTerm; if (idxEndFirstTerm < end) end = idxEndFirstTerm + 1; } else { start = end = 0; } } int64_t idxStartSecondTerm = -1; if (idxStartFirstTerm != -1) { int64_t secondTerm = ~0lu; if (this->usedIndex == IDX_OPS || this->usedIndex == IDX_SPO) { secondTerm = p; offset = 5; } else if (this->usedIndex == IDX_OSP || this->usedIndex == IDX_PSO) { secondTerm = s; offset = 0; } else { secondTerm = o; offset = 10; } if (secondTerm != -1) { idxStartSecondTerm = findFirstOccurrence(start, end, secondTerm, offset); if (idxStartSecondTerm != -1) { int64_t idxEndSecondTerm = findLastOccurrence(idxStartSecondTerm, end, secondTerm, offset); start = idxStartSecondTerm; if (idxEndSecondTerm < end) end = idxEndSecondTerm + 1; } else { start = end = 0; } } } if (idxStartSecondTerm != -1) { int64_t thirdTerm; if (this->usedIndex == IDX_OPS || this->usedIndex == IDX_POS) { thirdTerm = s; offset = 0; } else if (this->usedIndex == IDX_OSP || this->usedIndex == IDX_SOP) { thirdTerm = p; offset = 5; } else { thirdTerm = o; offset = 10; } if (thirdTerm != -1) { int64_t idxStartThirdTerm = findFirstOccurrence(start, end, thirdTerm, offset); if (idxStartThirdTerm != -1) { start = idxStartThirdTerm; end = start + 1; } else { start = end = 0; } } } //std::cout << "Creating an index with " << (end - start) << std::endl; //Populate indices this->indices.resize(end - start); uint64_t i = 0; while (start < end) { indices[i++] = start++; } } uint64_t BatchCreator::getNBatches() { int64_t n = indices.size() / this->batchsize; if ((indices.size() % this->batchsize) != 0) { return n + 1; } else { return n; } } void BatchCreator::start(int64_t s, int64_t p, int64_t o) { //Get index for s,p,o this->usedIndex = IDX_POS; if (s != -1 || p != -1 || o != -1) { if (valid != 0 || test != 0) { LOG(ERRORL) << "Query-based batching works only if the entire KB is used for training"; throw 10; } Querier *q = kb->query(); this->usedIndex = q->getIndex(s, p, o); delete q; } //First check if the file exists string fin = this->kbdir + "/_batch" + std::to_string(this->usedIndex); if (Utils::exists(fin)) { } else { if (createBatchFile) { LOG(INFOL) << "Could not find the input file for the batch." " I will create it and store it in a file called '_batch'"; createInputForBatch(createBatchFile, valid, test); } } if (createBatchFile) { //Load the file into a memory-mapped file this->mappedFile = std::unique_ptr<MemoryMappedFile>(new MemoryMappedFile( fin)); this->rawtriples = this->mappedFile->getData(); this->ntriples = this->mappedFile->getLength() / 15; } else { this->kbbatch = std::unique_ptr<KBBatch>(new KBBatch(kb)); this->kbbatch->populateCoordinates(); this->ntriples = this->kbbatch->ntriples(); } LOG(DEBUGL) << "Creating index array ..."; if (s != -1 || p != -1 || o != -1) { assert(createBatchFile); //Put in indices only the triples that satisfy the query populateIndicesFromQuery(s, p, o); } else { this->indices.resize(this->ntriples); for(int64_t i = 0; i < this->ntriples; ++i) { this->indices[i] = i; } } LOG(DEBUGL) << "Shuffling array ..."; shuffle(); LOG(DEBUGL) << "Done"; } void BatchCreator::shuffle() { std::shuffle(this->indices.begin(), this->indices.end(), engine); this->currentidx = 0; } bool BatchCreator::getBatch(std::vector<uint64_t> &output) { int64_t i = 0; output.resize(this->batchsize * 3); //The output vector is already supposed to contain batchsize elements. Otherwise, resize it while (i < batchsize && currentidx < indices.size()) { int64_t idx = indices[currentidx]; uint64_t s,p,o; if (createBatchFile) { s = *(uint64_t*)(rawtriples + idx * 15); s = s & 0xFFFFFFFFFFl; p = *(uint64_t*)(rawtriples + idx * 15 + 5); p = p & 0xFFFFFFFFFFl; o = *(uint64_t*)(rawtriples + idx * 15 + 10); o = o & 0xFFFFFFFFFFl; } else { kbbatch->getAt(idx, s, p, o); } if (filter && shouldBeUsed(s,p,o)) { output[i*3] = s; output[i*3+1] = p; output[i*3+2] = o; i+=1; } currentidx++; } if (i < batchsize) { output.resize(i*3); } return i > 0; } bool BatchCreator::shouldBeUsed(int64_t s, int64_t p, int64_t o) { return feedback->shouldBeIncluded(s, p, o); } bool BatchCreator::getBatchNr(uint64_t nr, std::vector<uint64_t> &output1, std::vector<uint64_t> &output2, std::vector<uint64_t> &output3) { output1.resize(this->batchsize); output2.resize(this->batchsize); output3.resize(this->batchsize); //Try to get up to batchsize triples int64_t i = 0; int64_t cidx = nr * this->batchsize; while (i < batchsize && cidx < indices.size()) { int64_t idx = indices[cidx]; uint64_t s, p, o; if (createBatchFile) { s = *(uint64_t *)(rawtriples + idx * 15); s = s & 0xFFFFFFFFFFl; p = *(uint64_t *)(rawtriples + idx * 15 + 5); p = p & 0xFFFFFFFFFFl; o = *(uint64_t *)(rawtriples + idx * 15 + 10); o = o & 0xFFFFFFFFFFl; } else { kbbatch->getAt(idx, s, p, o); } if (!filter || shouldBeUsed(s,p,o)) { output1[i] = s; output2[i] = p; output3[i] = o; i+=1; } cidx++; } if (i < this->batchsize) { output1.resize(i); output2.resize(i); output3.resize(i); } return i > 0; } bool BatchCreator::getBatch(std::vector<uint64_t> &output1, std::vector<uint64_t> &output2, std::vector<uint64_t> &output3) { int64_t i = 0; output1.resize(this->batchsize); output2.resize(this->batchsize); output3.resize(this->batchsize); //The output vector is already supposed to contain batchsize elements. //Otherwise, resize it while (i < batchsize && currentidx < indices.size()) { int64_t idx = indices[currentidx]; uint64_t s,p,o; if (createBatchFile) { s = *(uint64_t *)(rawtriples + idx * 15); s = s & 0xFFFFFFFFFFl; p = *(uint64_t *)(rawtriples + idx * 15 + 5); p = p & 0xFFFFFFFFFFl; o = *(uint64_t *)(rawtriples + idx * 15 + 10); o = o & 0xFFFFFFFFFFl; } else { kbbatch->getAt(idx, s, p, o); } if (!filter || shouldBeUsed(s,p,o)) { output1[i] = s; output2[i] = p; output3[i] = o; i+=1; } currentidx++; } if (i < batchsize) { output1.resize(i); output2.resize(i); output3.resize(i); } return i > 0; } void BatchCreator::loadTriples(string path, std::vector<uint64_t> &output) { MemoryMappedFile mf(path); char *start = mf.getData(); char *end = start + mf.getLength(); while (start < end) { int64_t s = *(int64_t*)(start); s = s & 0xFFFFFFFFFFl; int64_t p = *(int64_t*)(start + 5); p = p & 0xFFFFFFFFFFl; int64_t o = *(int64_t*)(start + 10); o = o & 0xFFFFFFFFFFl; output.push_back(s); output.push_back(p); output.push_back(o); start += 15; } } BatchCreator::KBBatch::KBBatch(KB *kb) : kb(kb) { this->querier = std::unique_ptr<Querier>(kb->query()); } void BatchCreator::KBBatch::populateCoordinates() { //Load all files allposfiles = kb->openAllFiles(IDX_POS); auto itr = (TermItr*)querier->getTermList(IDX_POS); string kbdir = kb->getPath(); string posdir = kbdir + "/p" + to_string(IDX_POS); //Get all the predicates uint64_t current = 0; while (itr->hasNext()) { itr->next(); uint64_t pred = itr->getKey(); uint64_t card = itr->getCount(); PredCoordinates info; info.pred = pred; info.boundary = current + card; //Get beginning of the table short currentFile = itr->getCurrentFile(); int64_t currentMark = itr->getCurrentMark(); string fdidx = posdir + "/" + to_string(currentFile) + ".idx"; if (Utils::exists(fdidx)) { ifstream idxfile(fdidx); idxfile.seekg(8 + 11 * currentMark); char buffer[5]; idxfile.read(buffer, 5); int64_t pos = Utils::decode_longFixedBytes(buffer, 5); info.buffer = allposfiles[currentFile] + pos; } else { LOG(ERRORL) << "Cannot happen!"; throw 10; } char currentStrat = itr->getCurrentStrat(); int storageType = StorageStrat::getStorageType(currentStrat); if (storageType == NEWCOLUMN_ITR) { //Get reader and offset char header1 = info.buffer[0]; char header2 = info.buffer[1]; const uint8_t bytesPerStartingPoint = header2 & 7; const uint8_t bytesPerCount = (header2 >> 3) & 7; const uint8_t remBytes = bytesPerCount + bytesPerStartingPoint; const uint8_t bytesPerFirstEntry = (header1 >> 3) & 7; const uint8_t bytesPerSecondEntry = (header1) & 7; info.offset = remBytes; //update the buffer int offset = 2; info.nfirstterms = Utils::decode_vlong2(info.buffer, &offset); Utils::decode_vlong2(info.buffer, &offset); info.buffer = info.buffer + offset; FactoryNewColumnTable::get12Reader(bytesPerFirstEntry, bytesPerSecondEntry, &info.reader); } else if (storageType == NEWROW_ITR) { const char nbytes1 = (currentStrat >> 3) & 3; const char nbytes2 = (currentStrat >> 1) & 3; FactoryNewRowTable::get12Reader(nbytes1, nbytes2, &info.reader); } else { LOG(ERRORL) << "Not supported"; throw 10; } predicates.push_back(info); current += card; } querier->releaseItr(itr); } void BatchCreator::KBBatch::getAt(uint64_t pos, uint64_t &s, uint64_t &p, uint64_t &o) { auto itr = predicates.begin(); uint64_t offset = 0; while(itr != predicates.end() && pos >= itr->boundary) { offset = itr->boundary; itr++; } pos -= offset; if (itr != predicates.end()) { //Take the reader and read the values itr->reader(itr->nfirstterms, itr->offset, itr->buffer, pos, o, s); p = itr->pred; } } BatchCreator::KBBatch::~KBBatch() { querier = NULL; } uint64_t BatchCreator::KBBatch::ntriples() { return kb->getSize(); }
31.847934
123
0.535344
dkw-aau
a8c978333b4cc8f14c54e1d6a096d8ba09193dc3
6,495
inl
C++
qbase/include/util/Iterators.inl
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
qbase/include/util/Iterators.inl
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
qbase/include/util/Iterators.inl
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
////////////////////////////////////////////////////////////////////////// template<class T> Const_Ptr_Iterator<T>::Const_Ptr_Iterator(uint8_t const* data, size_type stride, size_type count) : m_begin(data) , m_end(data ? data + stride*count : nullptr) , m_ptr(data) , m_stride(stride) { QASSERT(stride > 0); } template<class T> Const_Ptr_Iterator<T>::Const_Ptr_Iterator(uint8_t const* data, size_type count) : m_begin(data) , m_end(data ? data + sizeof(T)*count : nullptr) , m_ptr(data) , m_stride(sizeof(T)) { } template<class T> typename Const_Ptr_Iterator<T>::value_type const& Const_Ptr_Iterator<T>::operator*() const { QASSERT(m_ptr <= m_end); return *reinterpret_cast<T const*>(m_ptr); } template<class T> Const_Ptr_Iterator<T>::Const_Ptr_Iterator(Const_Ptr_Iterator<T> const& other) : m_begin(other.m_begin) , m_end(other.m_end) , m_ptr(other.m_ptr) , m_stride(other.m_stride) { } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator=(Const_Ptr_Iterator<T> const& other) { m_begin = other.m_begin; m_end = other.m_end; m_ptr = other.m_ptr; m_stride = other.m_stride; return *this; } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator++() { QASSERT(m_ptr + m_stride <= m_end); m_ptr += m_stride; return *this; } template<class T> Const_Ptr_Iterator<T> Const_Ptr_Iterator<T>::operator++(int) { QASSERT(m_ptr + m_stride <= m_end); Const_Ptr_Iterator<T> p(*this); m_ptr += m_stride; return p; } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator+=(size_type i) { QASSERT(m_ptr + m_stride*i <= m_end); m_ptr += m_stride*i; return *this; } template<class T> Const_Ptr_Iterator<T> Const_Ptr_Iterator<T>::operator+(size_type i) const { Const_Ptr_Iterator<T> x(*this); x += i; return x; } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator--() { QASSERT(m_ptr - m_stride >= m_begin); m_ptr -= m_stride; return *this; } template<class T> Const_Ptr_Iterator<T> Const_Ptr_Iterator<T>::operator--(int) { QASSERT(m_ptr - m_stride >= m_begin); Const_Ptr_Iterator<T> p(*this); m_ptr -= m_stride; return p; } template<class T> Const_Ptr_Iterator<T>& Const_Ptr_Iterator<T>::operator-=(size_type i) { QASSERT(m_ptr - m_stride*i >= m_begin); m_ptr -= m_stride*i; return *this; } template<class T> Const_Ptr_Iterator<T> Const_Ptr_Iterator<T>::operator-(size_type i) const { Const_Ptr_Iterator<T> x(*this); x -= i; return x; } template<class T> typename Const_Ptr_Iterator<T>::difference_type Const_Ptr_Iterator<T>::operator-(Const_Ptr_Iterator const& other) const { return static_cast<difference_type>(m_ptr - other.m_ptr); } template<class T> bool Const_Ptr_Iterator<T>::operator==(Const_Ptr_Iterator<T> const& other) const { return m_ptr == other.m_ptr; } template<class T> bool Const_Ptr_Iterator<T>::operator!=(Const_Ptr_Iterator<T> const& other) const { return !operator==(other); } template<class T> bool Const_Ptr_Iterator<T>::operator<(Const_Ptr_Iterator<T> const& other) const { return m_ptr < other.m_ptr; } template<class T> bool Const_Ptr_Iterator<T>::is_valid() const { return m_ptr != nullptr; } template<class T> T const* Const_Ptr_Iterator<T>::get() const { QASSERT(m_ptr <= m_end); return reinterpret_cast<T const*>(m_ptr); } ////////////////////////////////////////////////////////////////////////// template<class T> Ptr_Iterator<T>::Ptr_Iterator(uint8_t* data, size_type stride, size_type count) : m_begin(data) , m_end(data ? data + stride*count : nullptr) , m_ptr(data) , m_stride(stride) { QASSERT(stride > 0); } template<class T> Ptr_Iterator<T>::Ptr_Iterator(uint8_t* data, size_type count) : m_begin(data) , m_end(data ? data + sizeof(T)*count : nullptr) , m_ptr(data) , m_stride(sizeof(T)) { } template<class T> typename Ptr_Iterator<T>::value_type& Ptr_Iterator<T>::operator*() { QASSERT(m_ptr <= m_end); return *reinterpret_cast<T*>(m_ptr); } template<class T> Ptr_Iterator<T>::Ptr_Iterator(Ptr_Iterator const& other) : m_begin(other.m_begin) , m_end(other.m_end) , m_ptr(other.m_ptr) , m_stride(other.m_stride) { } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator=(Ptr_Iterator<T> const& other) { m_begin = other.m_begin; m_end = other.m_end; m_ptr = other.m_ptr; m_stride = other.m_stride; return *this; } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator++() { QASSERT(m_ptr + m_stride <= m_end); m_ptr += m_stride; return *this; } template<class T> Ptr_Iterator<T> Ptr_Iterator<T>::operator++(int) { QASSERT(m_ptr + m_stride <= m_end); Ptr_Iterator<T> p(*this); m_ptr += m_stride; return p; } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator+=(size_type i) { QASSERT(m_ptr + m_stride*i <= m_end); m_ptr += m_stride*i; return *this; } template<class T> Ptr_Iterator<T> Ptr_Iterator<T>::operator+(size_type i) const { Ptr_Iterator<T> x(*this); x += i; return x; } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator--() { QASSERT(m_ptr - m_stride >= m_begin); m_ptr -= m_stride; return *this; } template<class T> Ptr_Iterator<T> Ptr_Iterator<T>::operator--(int) { QASSERT(m_ptr - m_stride >= m_begin); Ptr_Iterator<T> p(*this); m_ptr -= m_stride; return p; } template<class T> Ptr_Iterator<T>& Ptr_Iterator<T>::operator-=(size_type i) { QASSERT(m_ptr - m_stride*i >= m_begin); m_ptr -= m_stride*i; return *this; } template<class T> Ptr_Iterator<T> Ptr_Iterator<T>::operator-(size_type i) const { Ptr_Iterator<T> x(*this); x -= i; return x; } template<class T> typename Ptr_Iterator<T>::difference_type Ptr_Iterator<T>::operator-(Ptr_Iterator const& other) const { return static_cast<difference_type>(m_ptr - other.m_ptr); } template<class T> bool Ptr_Iterator<T>::operator==(Ptr_Iterator<T> const& other) const { return m_ptr == other.m_ptr; } template<class T> bool Ptr_Iterator<T>::operator!=(Ptr_Iterator<T> const& other) const { return !operator==(other); } template<class T> bool Ptr_Iterator<T>::operator<(Ptr_Iterator<T> const& other) const { return m_ptr < other.m_ptr; } template<class T> bool Ptr_Iterator<T>::is_valid() const { return m_ptr != nullptr; } template<class T> T* Ptr_Iterator<T>::get() { QASSERT(m_ptr <= m_end); return reinterpret_cast<T*>(m_ptr); }
24.602273
120
0.676982
jeanleflambeur
a8c9b6217d453f3fcfc699a816d4107dac77435c
9,935
cpp
C++
chapter21/chapter21_drill.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
170
2015-05-02T18:08:38.000Z
2018-07-31T11:35:17.000Z
chapter21/chapter21_drill.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
7
2018-08-29T15:43:14.000Z
2021-09-23T21:56:49.000Z
chapter21/chapter21_drill.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
105
2015-05-28T11:52:19.000Z
2018-07-17T14:11:25.000Z
// Chapter 21, drill #include "../lib_files/std_lib_facilities.h" #include<map> #include<numeric> //------------------------------------------------------------------------------ struct Item { string name; int iid; double value; Item() :name(), iid(0), value(0) { } Item(string n, int i, double v) :name(n), iid(i), value(v) { } }; //------------------------------------------------------------------------------ istream& operator>>(istream& is, Item& it) { string name; int iid; double value; is >> name >> iid >> value; if (!is) return is; it = Item(name,iid,value); return is; } //------------------------------------------------------------------------------ ostream& operator<<(ostream& os, const Item& it) { return os << it.name << '\t' << it.iid << '\t' << it.value; } //------------------------------------------------------------------------------ struct Comp_by_name { bool operator()(const Item& a, const Item& b) const { return a.name < b.name; } }; //------------------------------------------------------------------------------ struct Comp_by_iid { bool operator()(const Item& a, const Item& b) const { return a.iid < b.iid; } }; //------------------------------------------------------------------------------ bool comp_by_value(const Item& a, const Item& b) { return a.value < b.value; } //------------------------------------------------------------------------------ class Find_by_name { string name; public: Find_by_name(const string& s) :name(s) { } bool operator()(const Item& it) const { return it.name == name; } }; //------------------------------------------------------------------------------ class Find_by_iid { int iid; public: Find_by_iid(int i) :iid(i) { } bool operator()(const Item& it) const { return it.iid == iid; } }; //------------------------------------------------------------------------------ template<class iter> void print(iter first, iter last) { while (first!=last) { cout << *first << '\n'; ++first; } } //------------------------------------------------------------------------------ void f1() { cout << "First round: vector\n"; vector<Item> vi; const string ifname = "pics_and_txt/chapter21_drill_in.txt"; // 1.1 cout << "1.1: fill with ten items from file\n"; { ifstream ifs(ifname.c_str()); if (!ifs) error("can't open ",ifname); Item i; while (ifs>>i) vi.insert(vi.end(),i); } print(vi.begin(),vi.end()); // 1.2 cout << "\n1.2: sort by name\n"; sort(vi.begin(),vi.end(),Comp_by_name()); print(vi.begin(),vi.end()); // 1.3 cout << "\n1.3: sort by iid\n"; sort(vi.begin(),vi.end(),Comp_by_iid()); print(vi.begin(),vi.end()); // 1.4 - use function instead of function object cout << "\n1.4: sort by value, print in decreasing order\n"; sort(vi.begin(),vi.end(),comp_by_value); reverse(vi.begin(),vi.end()); print(vi.begin(),vi.end()); // 1.5 - use function instead of function object cout << "\n1.5: insert two items\n"; vi.insert(vi.end(),Item("Horsesh",99,12.34)); vi.insert(vi.end(),Item("C S400",9988,499.95)); sort(vi.begin(),vi.end(),comp_by_value); reverse(vi.begin(),vi.end()); print(vi.begin(),vi.end()); // 1.6 cout << "\n1.6: remove two items identified by name\n"; vector<Item>::iterator vi_it = find_if(vi.begin(),vi.end(),Find_by_name("GoPro")); vi.erase(vi_it); vi_it = find_if(vi.begin(),vi.end(),Find_by_name("Xbox")); vi.erase(vi_it); print(vi.begin(),vi.end()); // 1.7 cout << "\n1.7: remove two tems identified by iid\n"; vi_it = find_if(vi.begin(),vi.end(),Find_by_iid(14910)); vi.erase(vi_it); vi_it = find_if(vi.begin(),vi.end(),Find_by_iid(754)); vi.erase(vi_it); print(vi.begin(),vi.end()); } //------------------------------------------------------------------------------ void f2() { cout << "\nSecond round: list\n"; list<Item> li; const string ifname = "pics_and_txt/chapter21_drill_in.txt"; // 1.1 cout << "1.1: fill with ten items from file\n"; { ifstream ifs(ifname.c_str()); if (!ifs) error("can't open ",ifname); Item i; while (ifs>>i) li.insert(li.end(),i); } print(li.begin(),li.end()); // 1.2 cout << "\n1.2: sort by name\n"; li.sort(Comp_by_name()); print(li.begin(),li.end()); // 1.3 cout << "\n1.3: sort by iid\n"; li.sort(Comp_by_iid()); print(li.begin(),li.end()); // 1.4 - use function instead of function object cout << "\n1.4: sort by value, print in decreasing order\n"; li.sort(comp_by_value); reverse(li.begin(),li.end()); print(li.begin(),li.end()); // 1.5 - use function instead of function object cout << "\n1.5: insert two items\n"; li.insert(li.end(),Item("Horsesh",99,12.34)); li.insert(li.end(),Item("C S400",9988,499.95)); li.sort(comp_by_value); reverse(li.begin(),li.end()); print(li.begin(),li.end()); // 1.6 cout << "\n1.6: remove two items identified by name\n"; list<Item>::iterator li_it = find_if(li.begin(),li.end(),Find_by_name("GoPro")); li.erase(li_it); li_it = find_if(li.begin(),li.end(),Find_by_name("Xbox")); li.erase(li_it); print(li.begin(),li.end()); // 1.7 cout << "\n1.7: remove two tems identified by iid\n"; li_it = find_if(li.begin(),li.end(),Find_by_iid(14910)); li.erase(li_it); li_it = find_if(li.begin(),li.end(),Find_by_iid(754)); li.erase(li_it); print(li.begin(),li.end()); } //------------------------------------------------------------------------------ // 2.5 void read_pair(map<string,int>& msi) { string s; int i; cin >> s >> i; if (!cin) error("Problem reading from cin"); msi[s] = i; } //------------------------------------------------------------------------------ template<class T, class U> ostream& operator<<(ostream& os, const pair<T,U>& p) { os << setw(12) << left << p.first << '\t' << p.second; return os; } //------------------------------------------------------------------------------ template<class T> struct Map_add { T operator()(T v, const pair<string,T>& p) { return v + p.second; } }; //------------------------------------------------------------------------------ void f3() { // 2.1 map<string,int> msi; // 2.2 msi["lecture"] = 21; msi["university"] = 35; msi["education"] = 15; msi["school"] = 99; msi["kindergarten"] = 105; msi["river"] = 5; msi["city"] = 10; msi["capital"] = 70; msi["software"] = 88; msi["hardware"] = 43; // 2.3 print(msi.begin(),msi.end()); // 2.4 typedef map<string,int>::const_iterator MI; MI p = msi.begin(); while (p!=msi.end()) p = msi.erase(p); cout << "Size of map after deleting: " << msi.size() << '\n'; // 2.6 cout << "Enter 10 (string,int) pairs, separated by space:\n"; for (int i = 0; i<10; ++i) read_pair(msi); // 2.7 cout << '\n'; print(msi.begin(),msi.end()); // 2.8 int msi_sum = 0; msi_sum = accumulate(msi.begin(),msi.end(),msi_sum,Map_add<int>()); cout << "\nSum of all ints in msi: " << msi_sum << '\n'; // 2.9 map<int,string> mis; // 2.10 for (p = msi.begin(); p!=msi.end(); ++p) mis[p->second] = p->first; // 2.11 cout << "\nContents of mis:\n"; print(mis.begin(),mis.end()); } //------------------------------------------------------------------------------ template<class T> class Less_than { T v; public: Less_than(T val) :v(val) { } bool operator()(T x) const { return x < v; } }; //class Less_than { // double v; //public: // Less_than(double val) :v(val) { } // bool operator()(double x) const { return x < v; } //}; //------------------------------------------------------------------------------ void f4() { // 3.1 const string fname = "pics_and_txt/chapter21_drill_in2.txt"; ifstream ifs(fname.c_str()); if (!ifs) error("can't open ",fname); vector<double> vd; double d; while (ifs>>d) vd.push_back(d); // 3.2 cout << "vd:\n"; print(vd.begin(),vd.end()); // 3.3 vector<int> vi(vd.size()); copy(vd.begin(),vd.end(),vi.begin()); // 3.4 cout << "\n(vd,vi) pairs:\n"; for (int i = 0; i<vd.size(); ++i) { cout << '(' << vd[i] << ',' << vi[i] << ")\n"; } // 3.5 double sum_vd = 0; sum_vd = accumulate(vd.begin(),vd.end(),sum_vd); cout << "\nSum of the elements of vd: " << sum_vd << '\n'; // 3.6 int sum_vi = 0; sum_vi = accumulate(vi.begin(),vi.end(),sum_vi); cout << "Difference of sum_vd and sum_vi: " << sum_vd - sum_vi << '\n'; // 3.7 reverse(vd.begin(),vd.end()); cout << "\nvd after reverse:\n"; print(vd.begin(),vd.end()); // 3.8 double vd_mean = sum_vd / vd.size(); cout << "\nMean value of elements in vd: " << vd_mean << '\n'; // 3.9 vector<double> vd2(count_if(vd.begin(),vd.end(),Less_than<double>(vd_mean))); copy_if(vd.begin(),vd.end(),vd2.begin(),Less_than<double>(vd_mean)); cout << "\nvd2:\n"; print(vd2.begin(),vd2.end()); // 3.10 sort(vd.begin(),vd.end()); cout << "\nvd:\n"; print(vd.begin(),vd.end()); } //------------------------------------------------------------------------------ int main() try { f1(); // 1.8 f2(); f3(); f4(); } catch (Range_error& re) { cerr << "bad index: " << re.index << "\n"; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; } //------------------------------------------------------------------------------
24.899749
81
0.459386
TingeOGinge
a8cdcd5026c1d66b26e281d5d96e3f8f2763849f
1,628
cpp
C++
tests/UnitTests/DelegateTest.cpp
evugar/Mcucpp
202d98587e8b9584370a32c1bafa2c7315120c9e
[ "BSD-3-Clause" ]
87
2015-03-16T19:09:09.000Z
2022-03-19T19:48:49.000Z
tests/UnitTests/DelegateTest.cpp
evugar/Mcucpp
202d98587e8b9584370a32c1bafa2c7315120c9e
[ "BSD-3-Clause" ]
5
2015-04-19T11:02:35.000Z
2021-04-21T05:29:22.000Z
tests/UnitTests/DelegateTest.cpp
evugar/Mcucpp
202d98587e8b9584370a32c1bafa2c7315120c9e
[ "BSD-3-Clause" ]
42
2015-02-11T16:29:35.000Z
2022-03-12T11:48:08.000Z
#include <gtest/gtest.h> #include <delegate.h> class Foo { public: Foo() { barCalled = 0; arg1 = 0; arg2 = 0; arg3 = 0; } void Bar() { barCalled++; } void Bar1(int a1) { barCalled++; arg1 = a1; } void Bar2(int a1, int a2) { barCalled++; arg1 = a1; arg2 = a2; } void Bar3(int a1, int a2, int a3) { barCalled++; arg1 = a1; arg2 = a2; arg3 = a3; } int barCalled; int arg1, arg2, arg3; }; Foo foo; int delegateTestFuncCalled = 0; void DelegateTestFunc() { delegateTestFuncCalled++; } TEST(Delegate, NoArgsClassMember) { foo.barCalled = 0; Mcucpp::Delegate<void> delegate(foo, &Foo::Bar); delegate(); EXPECT_EQ(1, foo.barCalled); } TEST(Delegate, OneArgClassMember) { foo.barCalled = 0; Mcucpp::Delegate1<void, int> delegate(foo, &Foo::Bar1); delegate(10); EXPECT_EQ(1, foo.barCalled); EXPECT_EQ(10, foo.arg1); } TEST(Delegate, TwoArgClassMember) { foo.barCalled = 0; Mcucpp::Delegate2<void, int, int> delegate(foo, &Foo::Bar2); delegate(10, 20); EXPECT_EQ(1, foo.barCalled); EXPECT_EQ(10, foo.arg1); EXPECT_EQ(20, foo.arg2); } TEST(Delegate, ThreeArgClassMember) { foo.barCalled = 0; Mcucpp::Delegate3<void, int, int, int> delegate(foo, &Foo::Bar3); delegate(10, 20, 30); EXPECT_EQ(1, foo.barCalled); EXPECT_EQ(10, foo.arg1); EXPECT_EQ(20, foo.arg2); EXPECT_EQ(30, foo.arg3); } TEST(Delegate, NoArgsStaticFunc) { delegateTestFuncCalled = 0; Mcucpp::Delegate<void> delegate(DelegateTestFunc); delegate(); EXPECT_EQ(1, delegateTestFuncCalled); }
16.612245
67
0.624693
evugar
a8d2a313ad5617fefbde1f293e387688f997fe2d
7,966
cpp
C++
source/rx/Font.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
1
2021-02-07T08:40:11.000Z
2021-02-07T08:40:11.000Z
source/rx/Font.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
null
null
null
source/rx/Font.cpp
zhiayang/sim-thing
8d9d5163146e2bdde15f4eadefa85453f12fac18
[ "Apache-2.0" ]
null
null
null
// Font.cpp // Copyright (c) 2014 - 2017, zhiayang@gmail.com // Licensed under the Apache License Version 2.0. #include <map> #include <algorithm> #include <stdio.h> #include <sys/stat.h> #include "rx.h" #include <glbinding/gl/gl.h> #define STB_RECT_PACK_IMPLEMENTATION #include "stb/stb_pack_rect.h" #define STB_TRUETYPE_IMPLEMENTATION #include "stb/stb_truetype.h" namespace rx { typedef std::pair<std::string, size_t> FontTuple; static std::map<FontTuple, Font*> fontMap; Font* getFont(std::string name, size_t pixelSize, uint32_t firstChar, size_t numChars, size_t oversampleH, size_t oversampleV) { FontTuple tup(name, pixelSize); if(fontMap.find(tup) != fontMap.end()) { return fontMap[tup]; } std::string path = AssetLoader::getResourcePath() + "fonts/" + name + ".ttf"; uint8_t* ttfbuffer = 0; size_t ttfSize = 0; { struct stat st; int err = stat(path.c_str(), &st); if(err != 0) ERROR("fstat failed with: errno = %d\n", errno); size_t expected = st.st_size; FILE* f = fopen(path.c_str(), "r"); ttfbuffer = new uint8_t[expected]; size_t done = fread(ttfbuffer, 1, expected, f); if(done != expected) ERROR("failure in reading file: expected %zu, got %zu bytes (errno = %d)\n", expected, done, errno); ttfSize = done; fclose(f); } Font* font = new Font(name); font->pixelSize = pixelSize; font->ttfBuffer = ttfbuffer; font->ttfBufferSize = ttfSize; font->firstChar = firstChar; font->numChars = numChars; font->horzOversample = oversampleH; font->vertOversample = oversampleV; // determine how large, approximately, the atlas needs to be. size_t maxpixsize = std::max(oversampleH * pixelSize, oversampleV * pixelSize); size_t numperside = (size_t) (sqrt(numChars) + 1); { size_t atlasWidth = numperside * maxpixsize; size_t atlasHeight = numperside * maxpixsize; uint8_t* atlasBuffer = new uint8_t[atlasWidth * atlasHeight]; assert(atlasBuffer && "failed to allocate memory for atlas"); memset(atlasBuffer, 0, atlasWidth * atlasHeight); // autotex = false -- we want to generate the texture ourselves. font->fontAtlas = new Texture(atlasBuffer, atlasWidth, atlasHeight, ImageFormat::GREYSCALE, false); } LOG("Allocated a %s font atlas (%zux%zu) for font '%s' at size %zupx", Units::formatWithUnits(font->fontAtlas->width * font->fontAtlas->height, 1, "B").c_str(), font->fontAtlas->width, font->fontAtlas->height, name.c_str(), pixelSize); stbtt_InitFont(&font->fontInfo, font->ttfBuffer, 0); // begin stb_truetype stuff { stbtt_pack_context context; if(!stbtt_PackBegin(&context, font->fontAtlas->surf->data, font->fontAtlas->width, font->fontAtlas->height, 0, 1, nullptr)) ERROR("Failed to initialise font '%s'", name.c_str()); font->charInfo = new stbtt_packedchar[font->numChars]; memset(font->charInfo, 0, sizeof(stbtt_packedchar) * font->numChars); stbtt_PackSetOversampling(&context, font->horzOversample, font->vertOversample); if(!stbtt_PackFontRange(&context, font->ttfBuffer, 0, pixelSize, font->firstChar, font->numChars, (stbtt_packedchar*) font->charInfo)) { ERROR("Failed to pack font '%s' into atlas", name.c_str()); } stbtt_PackEnd(&context); // make the opengl texture { using namespace gl; glGenTextures(1, &font->fontAtlas->glTextureID); glBindTexture(GL_TEXTURE_2D, font->fontAtlas->glTextureID); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // minification is more important, since we usually oversample and down-scale for better-looking text glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); float maxAnisotropicFiltering = 0; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnisotropicFiltering); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropicFiltering); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, font->fontAtlas->width, font->fontAtlas->height, 0, GL_RED, GL_UNSIGNED_BYTE, font->fontAtlas->surf->data); glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST); glGenerateMipmap(GL_TEXTURE_2D); } } int ascent = 0; int descent = 0; int linegap = 0; stbtt_GetFontVMetrics(&font->fontInfo, &ascent, &descent, &linegap); font->ascent = ascent * stbtt_ScaleForPixelHeight(&font->fontInfo, font->pixelSize); font->descent = descent * stbtt_ScaleForPixelHeight(&font->fontInfo, font->pixelSize); // make some VBOs that contain all the vertex and UV coordinates { using namespace gl; font->renderObject = new RenderObject(); glBindVertexArray(font->renderObject->vertexArrayObject); GLuint uvBuffer = 0; glGenBuffers(1, &uvBuffer); GLuint vertBuffer = 0; glGenBuffers(1, &vertBuffer); font->renderObject->buffers = { uvBuffer, vertBuffer }; std::vector<lx::fvec2> verts; std::vector<lx::fvec2> uvs; // make the VBO. for(uint32_t ch = firstChar; ch < firstChar + numChars; ch++) { auto fgp = font->getGlyphMetrics(ch); verts.push_back(lx::round(lx::fvec2(fgp.x1, fgp.y0))); // 3 verts.push_back(lx::round(lx::fvec2(fgp.x0, fgp.y1))); // 2 verts.push_back(lx::round(lx::fvec2(fgp.x0, fgp.y0))); // 1 verts.push_back(lx::round(lx::fvec2(fgp.x0, fgp.y1))); verts.push_back(lx::round(lx::fvec2(fgp.x1, fgp.y0))); verts.push_back(lx::round(lx::fvec2(fgp.x1, fgp.y1))); uvs.push_back(lx::fvec2(fgp.u1, fgp.v0)); // 3 uvs.push_back(lx::fvec2(fgp.u0, fgp.v1)); // 2 uvs.push_back(lx::fvec2(fgp.u0, fgp.v0)); // 1 uvs.push_back(lx::fvec2(fgp.u0, fgp.v1)); uvs.push_back(lx::fvec2(fgp.u1, fgp.v0)); uvs.push_back(lx::fvec2(fgp.u1, fgp.v1)); } glEnableVertexAttribArray(0); { glBindBuffer(GL_ARRAY_BUFFER, vertBuffer); glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(lx::fvec2), &verts[0], GL_STATIC_DRAW); glVertexAttribPointer( 0, // location 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); } glEnableVertexAttribArray(1); { glBindBuffer(GL_ARRAY_BUFFER, uvBuffer); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(lx::fvec2), &uvs[0], GL_STATIC_DRAW); glVertexAttribPointer( 1, // location 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); } font->renderObject->arrayLength = verts.size(); font->renderObject->renderType = RenderType::Text; font->renderObject->material = Material(util::colour::white(), font->fontAtlas, font->fontAtlas, 1); glBindVertexArray(0); } fontMap[tup] = font; return font; } FontGlyphPos Font::getGlyphMetrics(uint32_t character) { auto it = this->coordCache.find(character); if(it != this->coordCache.end()) return (*it).second; float xpos = 0; float ypos = 0; // stbtt_aligned_quad quad; stbtt_GetPackedQuad(this->charInfo, this->fontAtlas->width, this->fontAtlas->height, character - this->firstChar, &xpos, &ypos, &quad, 0); auto x0 = quad.x0; auto x1 = quad.x1; auto y0 = quad.y1; auto y1 = quad.y0; FontGlyphPos ret; ret.x0 = x0; ret.y0 = y0; ret.x1 = x1; ret.y1 = y1; // note that we flip the vertical tex coords, since opengl works with (0, 0) at bottom-left // but stb_truetype gives us (0, 0) at top-left. ret.u0 = quad.s0; ret.v0 = quad.t1; ret.u1 = quad.s1; ret.v1 = quad.t0; // fprintf(stderr, "glyph ('%c'):\nxy0: (%f, %f)\nxy1: (%f, %f)\n\n", character, x0, y0, x1, y1); ret.xAdvance = this->charInfo->xadvance; ret.descent = -y0; this->coordCache[character] = ret; return ret; } void closeAllFonts() { for(auto pair : fontMap) { delete[] pair.second->ttfBuffer; delete[] pair.second->fontAtlas; delete[] ((stbtt_packedchar*) pair.second->charInfo); } } }
27.37457
127
0.6765
zhiayang
a8d3237a56ea3587567abea6faf254e185968081
1,671
hpp
C++
program/object-detection-armnn-tflite/includes/detect.hpp
steffenlarsen/armnn-mlperf
c7da4c51f62af7c4e5c43e83345fa23df2fb0bc6
[ "MIT" ]
23
2019-04-24T15:12:40.000Z
2022-01-06T16:10:34.000Z
program/object-detection-armnn-tflite/includes/detect.hpp
steffenlarsen/armnn-mlperf
c7da4c51f62af7c4e5c43e83345fa23df2fb0bc6
[ "MIT" ]
5
2019-06-04T11:07:52.000Z
2022-01-06T16:45:40.000Z
program/object-detection-armnn-tflite/includes/detect.hpp
steffenlarsen/armnn-mlperf
c7da4c51f62af7c4e5c43e83345fa23df2fb0bc6
[ "MIT" ]
8
2019-10-31T11:55:36.000Z
2021-11-21T04:33:34.000Z
/* * Copyright (c) 2019 dividiti Ltd. * Copyright (c) 2019 Arm Ltd. * * SPDX-License-Identifier: MIT. */ #ifndef DETECT_H #define DETECT_H #include <iomanip> #include <vector> #include <iterator> #include "armnn/ArmNN.hpp" #include "armnn/Exceptions.hpp" #include "armnn/Tensor.hpp" #include "armnn/INetwork.hpp" #include "armnnTfLiteParser/ITfLiteParser.hpp" #define OBJECT_DETECTION_ARMNN_TFLITE #include "settings.h" #include "non_max_suppression.h" #include "benchmark.h" using namespace std; using namespace CK; template <typename TData, typename TInConverter, typename TOutConverter> class ArmNNBenchmark : public Benchmark<TData, TInConverter, TOutConverter> { public: ArmNNBenchmark(Settings* settings, TData *in_ptr, TData *boxes_ptr, TData *scores_ptr ) : Benchmark<TData, TInConverter, TOutConverter>(settings, in_ptr, boxes_ptr, scores_ptr) { } }; armnn::InputTensors MakeInputTensors(const std::pair<armnn::LayerBindingId, armnn::TensorInfo>& input, const void* inputTensorData) { return { {input.first, armnn::ConstTensor(input.second, inputTensorData) } }; } armnn::OutputTensors MakeOutputTensors(const std::pair<armnn::LayerBindingId, armnn::TensorInfo>& output, void* outputTensorData) { return { {output.first, armnn::Tensor(output.second, outputTensorData) } }; } void AddTensorToOutput(armnn::OutputTensors &v, const std::pair<armnn::LayerBindingId, armnn::TensorInfo>& output, void* outputTensorData ) { v.push_back({output.first, armnn::Tensor(output.second, outputTensorData) }); } #endif //DETECT_H
28.322034
102
0.708558
steffenlarsen
a8d33ad75224dd08756dc3270497cc6a0db5532e
328
cpp
C++
lessons/06-objects/src/main_item_v2_sol.cpp
chemphys/LearnCPP
025a6e043c6eadb61324c261168bbd0478d9690b
[ "BSD-3-Clause" ]
null
null
null
lessons/06-objects/src/main_item_v2_sol.cpp
chemphys/LearnCPP
025a6e043c6eadb61324c261168bbd0478d9690b
[ "BSD-3-Clause" ]
null
null
null
lessons/06-objects/src/main_item_v2_sol.cpp
chemphys/LearnCPP
025a6e043c6eadb61324c261168bbd0478d9690b
[ "BSD-3-Clause" ]
null
null
null
#include "item_v2_sol.h" int main() { Item myItem; std::cout << "Setting name to `chocolate`\n" << " price to `$1.15`\n" << " num_items to `10`\n"; myItem.SetName("chocolate"); myItem.SetPrice(1.15); myItem.SetNumItems(10); myItem.PrintItem(); return 0; }
16.4
51
0.521341
chemphys
a8d482b137992070a001f7aba4e957db268c238b
6,659
cpp
C++
Libtorch eval/VGG16/vgg16eighty.cpp
atcp1520/soter4
2c2273e1b4788bf30dc93c5590daf77c6b10fb65
[ "MIT" ]
null
null
null
Libtorch eval/VGG16/vgg16eighty.cpp
atcp1520/soter4
2c2273e1b4788bf30dc93c5590daf77c6b10fb65
[ "MIT" ]
null
null
null
Libtorch eval/VGG16/vgg16eighty.cpp
atcp1520/soter4
2c2273e1b4788bf30dc93c5590daf77c6b10fb65
[ "MIT" ]
1
2022-01-14T07:59:21.000Z
2022-01-14T07:59:21.000Z
// VGG16 - 80% in CUDA #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <torch/library.h> #include <torch/script.h> #include <torch/torch.h> #include <ATen/ATen.h> #include <iostream> #include <random> #include <string> #include <io.h> #include <memory> #include <vector> #include <time.h> #include <sys/time.h> namespace F = torch::nn::functional; struct part1 : public torch::nn::Module { torch::nn::Conv2d C1; part1(): C1(torch::nn::Conv2d(torch::nn::Conv2dOptions(3, 64, 3).padding(1))) { register_module("C1", C1); } torch::Tensor fwd_p1(torch::Tensor input) { auto x = F::relu(C1(input)); return x; } }; struct part2 : public torch::nn::Module { torch::nn::Conv2d C3; part2(): C3(torch::nn::Conv2d(torch::nn::Conv2dOptions(64, 64, 3).padding(1))) { register_module("C3", C3); } torch::Tensor fwd_p2(torch::Tensor input) { auto x = F::max_pool2d(F::relu(C3(input)), F::MaxPool2dFuncOptions(2)); return x; } }; struct part3 : public torch::nn::Module { torch::nn::Conv2d C6; part3(): C6(torch::nn::Conv2d(torch::nn::Conv2dOptions(64, 128, 3).padding(1))) { register_module("C6", C6); } torch::Tensor fwd_p3(torch::Tensor input) { auto x = F::relu(C6(input)); return x; } }; struct part4 : public torch::nn::Module { torch::nn::Conv2d C8; part4(): C8(torch::nn::Conv2d(torch::nn::Conv2dOptions(128, 128, 3).padding(1))) { register_module("C8", C8); } torch::Tensor fwd_p4(torch::Tensor input) { auto x = F::max_pool2d(F::relu(C8(input)), F::MaxPool2dFuncOptions(2)); return x; } }; struct part5 : public torch::nn::Module { torch::nn::Conv2d C11; part5(): C11(torch::nn::Conv2d(torch::nn::Conv2dOptions(128, 256, 3).padding(1))) { register_module("C11", C11); } torch::Tensor fwd_p5(torch::Tensor input) { auto x = F::relu(C11(input)); return x; } }; struct part6 : public torch::nn::Module { torch::nn::Conv2d C13; torch::nn::Conv2d C15; torch::nn::Conv2d C18; torch::nn::Conv2d C20; torch::nn::Conv2d C22; torch::nn::Conv2d C25; torch::nn::Conv2d C27; torch::nn::Conv2d C29; torch::nn::Linear FC32; torch::nn::Linear FC35; torch::nn::Linear FC38; part6(): C13(torch::nn::Conv2d(torch::nn::Conv2dOptions(256, 256, 3).padding(1))), C15(torch::nn::Conv2d(torch::nn::Conv2dOptions(256, 256, 3).padding(1))), C18(torch::nn::Conv2d(torch::nn::Conv2dOptions(256, 512, 3).padding(1))), C20(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), C22(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), C25(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), C27(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), C29(torch::nn::Conv2d(torch::nn::Conv2dOptions(512, 512, 3).padding(1))), FC32(torch::nn::Linear(512 * 7 * 7, 4096)), FC35(torch::nn::Linear(4096, 4096)), FC38(torch::nn::Linear(4096, 1000)) { register_module("C13", C13); register_module("C15", C15); register_module("C18", C18); register_module("C20", C20); register_module("C22", C22); register_module("C25", C25); register_module("C27", C27); register_module("C29", C29); register_module("FC32", FC32); register_module("FC35", FC35); register_module("FC38", FC38); } torch::Tensor fwd_p6(torch::Tensor input) { auto x = F::max_pool2d(F::relu(C15(F::relu(C13(input)))), F::MaxPool2dFuncOptions(2)); x = F::max_pool2d(F::relu(C22(F::relu(C20(F::relu(C18(x)))))), F::MaxPool2dFuncOptions(2)); x = F::max_pool2d(F::relu(C29(F::relu(C27(F::relu(C25(x)))))), F::MaxPool2dFuncOptions(2)); x = x.view({ -1, num_flat_features(x) }); x = F::relu(FC32(x)); x = F::relu(FC35(x)); x = FC38(x); return x; } long num_flat_features(torch::Tensor x) { // To except the batch dimension for vgg16_bn: // auto size = x.size()[1:] // For vgg16: auto size = x.sizes(); auto num_features = 1; for (auto s : size) { num_features *= s; } return num_features; } }; struct vgg16_eighty_split { part1 p1; part2 p2; part3 p3; part4 p4; part5 p5; part6 p6; torch::Tensor forward(torch::Tensor input) { input = input.to(at::kCPU); p1.to(at::kCPU); auto x = p1.fwd_p1(input); x = x.to(at::kCUDA); p2.to(at::kCUDA); x = p2.fwd_p2(x); x = x.to(at::kCPU); p3.to(at::kCPU); x = p3.fwd_p3(x); x = x.to(at::kCUDA); p4.to(at::kCUDA); x = p4.fwd_p4(x); x = x.to(at::kCPU); p5.to(at::kCPU); x = p5.fwd_p5(x); x = x.to(at::kCUDA); p6.to(at::kCUDA); x = p6.fwd_p6(x); return x; } }; int main() { std::cout << "vgg16 - 80% outsourced to CUDA version." << std::endl; vgg16_eighty_split model; int count1 = 1000; int count_warmup = 3000; torch::Tensor input = torch::rand({1, 3, 224, 224}); torch::Tensor output; for (size_t i = 0; i < count_warmup; i++) { output = model.forward(input); } cudaEvent_t start, stop; float esp_time_gpu; cudaEventCreate(&start); cudaEventCreate(&stop); float total = 0; for (size_t i = 0; i < count1; i++) { cudaEventRecord(start, 0); output = model.forward(input); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&esp_time_gpu, start, stop); total += esp_time_gpu; } float latency; latency = total / ((float)count1); std::cout << "For " << count1 << " inferences..." << std::endl; std::cout << "Time elapsed: " << total << " ms." << std::endl; std::cout << "Time consuming: " << latency << " ms per instance." << std::endl; return 0; }
26.636
100
0.526055
atcp1520
a8d49ff1ec11ad853d6f03fb76dd531ab76c3856
899
cc
C++
src/comm/communicator.cc
akkaze/rdc
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
[ "BSD-3-Clause" ]
52
2018-10-08T01:56:15.000Z
2021-03-14T12:19:51.000Z
src/comm/communicator.cc
akkaze/rdc
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
[ "BSD-3-Clause" ]
null
null
null
src/comm/communicator.cc
akkaze/rdc
76e85e3fe441e3ba968a190d9496f467b9d4d2e6
[ "BSD-3-Clause" ]
3
2019-01-02T05:17:28.000Z
2020-01-06T03:53:12.000Z
/*! * Copyright (c) 2018 by Contributors * \file comm.cc * \brief this file governs which implementation of comm we are actually using * provides an singleton of comm interface * * \author Ankun Zheng */ #include "comm/communicator.h" #include <memory> #include "comm/communicator_base.h" #include "comm/communicator_manager.h" #include "common/thread_local.h" namespace rdc { namespace comm { // singleton sync manager #ifndef RDC_USE_BASE typedef CommunicatorRobust Comm; #else typedef Communicator Comm; #endif // perform in-place allreduce, on sendrecvbuf void Allreduce_(Buffer sendrecvbuf, ReduceFunction red, mpi::DataType dtype, mpi::OpType op, const std::string& name) { CommunicatorManager::Get()->GetCommunicator(name)->Allreduce(sendrecvbuf, red); } } // namespace comm } // namespace rdc
28.09375
78
0.686318
akkaze
a8d4fe181bcec3f99675a7a771839ca38b3db16f
458
hpp
C++
telnetpp/include/telnetpp/options/msdp/detail/decoder.hpp
CalielOfSeptem/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
1
2017-03-30T14:31:33.000Z
2017-03-30T14:31:33.000Z
telnetpp/include/telnetpp/options/msdp/detail/decoder.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
telnetpp/include/telnetpp/options/msdp/detail/decoder.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
#pragma once #include "telnetpp/options/msdp/variable.hpp" namespace telnetpp { namespace options { namespace msdp { namespace detail { //* ========================================================================= /// \brief Decode a byte stream into a list of MSDP variables. //* ========================================================================= std::vector<telnetpp::options::msdp::variable> decode( telnetpp::u8stream const &stream); }}}}
32.714286
77
0.4869
CalielOfSeptem
a8d56ed7fbb946a2683c587b702609c12bc06614
1,570
cc
C++
src/developer/forensics/testing/stubs/device_id_provider.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/developer/forensics/testing/stubs/device_id_provider.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/developer/forensics/testing/stubs/device_id_provider.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/forensics/testing/stubs/device_id_provider.h" #include <lib/syslog/cpp/macros.h> #include <zircon/errors.h> namespace forensics { namespace stubs { void DeviceIdProviderBase::GetId(GetIdCallback callback) { GetIdInternal(std::move(callback)); } void DeviceIdProviderBase::GetIdInternal(GetIdCallback callback) { callback_ = std::move(callback); if (!dirty_) { dirty_ = true; } else { FX_CHECK(device_id_.has_value()); callback_(device_id_.value()); dirty_ = false; } } void DeviceIdProviderBase::SetDeviceId(std::string device_id) { device_id_ = std::move(device_id); if (dirty_ && callback_) { callback_(device_id_.value()); } dirty_ = false; } void DeviceIdProvider::GetId(GetIdCallback callback) { GetIdInternal(std::move(callback)); } DeviceIdProviderExpectsOneCall::~DeviceIdProviderExpectsOneCall() { FX_CHECK(!is_first_) << "Too few calls made to GetId, expecting 1 call"; } void DeviceIdProviderExpectsOneCall::GetId(GetIdCallback callback) { FX_CHECK(is_first_) << "Too many calls made to GetId, expecting 1 call"; is_first_ = false; GetIdInternal(std::move(callback)); } void DeviceIdProviderClosesFirstConnection::GetId(GetIdCallback callback) { if (is_first_) { is_first_ = false; CloseConnection(); return; } GetIdInternal(std::move(callback)); } } // namespace stubs } // namespace forensics
27.068966
96
0.733758
allansrc
a8d583db195c82521f55ed7dc779441d8da2e4ae
1,922
cpp
C++
UdpReciever/test_udp_receiver/SequencerTest.cpp
tomoyuki-nakabayashi/MyQtSamples
2bb2d74b989bd3895338a9d3740c26d813e76b74
[ "MIT" ]
null
null
null
UdpReciever/test_udp_receiver/SequencerTest.cpp
tomoyuki-nakabayashi/MyQtSamples
2bb2d74b989bd3895338a9d3740c26d813e76b74
[ "MIT" ]
5
2018-03-31T11:54:59.000Z
2018-10-14T10:32:15.000Z
UdpReciever/test_udp_receiver/SequencerTest.cpp
tomoyuki-nakabayashi/MyQtSamples
2bb2d74b989bd3895338a9d3740c26d813e76b74
[ "MIT" ]
null
null
null
/** * Copyright <2017> <Tomoyuki Nakabayashi> * This software is released under the MIT License, see LICENSE. */ #include <gtest/gtest.h> #include <QObject> #include <QVector> #include "Sequencer.h" #include "FrameBuilder.h" #include "SubFrameBuilder.h" namespace sequencer_test { using udp_receiver::Sequencer; using udp_receiver::BaseFrameBuilder; using udp_receiver::FrameBuilder; using udp_receiver::SubFrameBuilder; using udp_receiver::Frame; class SequencerTest : public ::testing::Test { protected: SequencerTest() : ds_(&buffer_, QIODevice::WriteOnly), kFrame(Frame::kHeaderMagic, 4, QByteArray::fromHex("01020304")), kSubFrame(Frame::kHeaderMagic, 4, QByteArray::fromHex("01020304")) {} virtual void SetUp() { } virtual void TearDown() { } protected: Sequencer seq_; QDataStream ds_; QByteArray buffer_; const Frame kFrame, kSubFrame; }; TEST_F(SequencerTest, AppendDatagram) { QByteArray x("free"); QByteArray y("dom"); seq_.AppendPendingData(x); auto res = seq_.AppendPendingData(y); EXPECT_EQ(QByteArray("freedom"), res); EXPECT_EQ(7, res.size()); } TEST_F(SequencerTest, FrameConstructed) { QSharedPointer<Frame> p = nullptr; QObject::connect(&seq_, &Sequencer::FrameConstructed, [&](QSharedPointer<Frame> frame){p = frame;}); ds_ << kFrame; seq_.AppendPendingData(buffer_); seq_.ConstructFrame(); ASSERT_TRUE(p != nullptr); EXPECT_EQ(kFrame, *p); auto res = seq_.AppendPendingData(QByteArray()); EXPECT_EQ(0, res.size()); } TEST_F(SequencerTest, RecieveFrameAfterSubFrames) { QVector<QSharedPointer<Frame>> pframe; QObject::connect(&seq_, &Sequencer::FrameConstructed, [&](QSharedPointer<Frame> frame){pframe.append(frame);}); ds_ << kFrame << kSubFrame << kFrame; seq_.AppendPendingData(buffer_); while (seq_.ConstructFrame()) {} EXPECT_EQ(3, pframe.size()); } } // namespace sequencer_test
24.961039
75
0.712799
tomoyuki-nakabayashi
a8d7152a7c5c73f4b69e0391ae6068e95ad5d417
699
cpp
C++
libcxx/test/libcxx/utilities/tuple/tuple.tuple/tuple.cnstr/empty_tuple_trivial.pass.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
778
2015-01-01T03:30:02.000Z
2022-03-20T15:58:39.000Z
libcxx/test/libcxx/utilities/tuple/tuple.tuple/tuple.cnstr/empty_tuple_trivial.pass.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
47
2019-12-11T02:34:13.000Z
2020-06-08T19:26:59.000Z
libcxx/test/libcxx/utilities/tuple/tuple.tuple/tuple.cnstr/empty_tuple_trivial.pass.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
412
2015-01-01T06:25:38.000Z
2022-03-26T16:58:34.000Z
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // This test ensures that std::tuple<> is trivially constructible. That is not // required by the Standard, but libc++ provides that guarantee. // UNSUPPORTED: c++98, c++03 #include <tuple> #include <type_traits> static_assert(std::is_trivially_constructible<std::tuple<>>::value, ""); int main(int, char**) { return 0; }
30.391304
80
0.552217
medismailben
a8d8972bac80e68d05e8e6b1cd9287ae3f9dbe91
685
cpp
C++
lab2/Lab2Task4Var4/Lab2Task4Var4/Lab2Task4Var4.cpp
AlexanderChibirev/OOP
e30adebbf961d9573a2d14981e5d8b92466207fd
[ "MIT" ]
null
null
null
lab2/Lab2Task4Var4/Lab2Task4Var4/Lab2Task4Var4.cpp
AlexanderChibirev/OOP
e30adebbf961d9573a2d14981e5d8b92466207fd
[ "MIT" ]
9
2016-02-17T09:08:02.000Z
2016-05-19T12:02:59.000Z
lab2/Lab2Task4Var4/Lab2Task4Var4/Lab2Task4Var4.cpp
AlexanderChibirev/OOP
e30adebbf961d9573a2d14981e5d8b92466207fd
[ "MIT" ]
null
null
null
// Lab2Task4Var4.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "GeneratePrimeNumbersSet.h" int main(int argc, char** argv) { if (argc != 2) { std::cout << "Wrong amount of arguments was proposed\nEnter a correct arguments amount please, for example:\n'upperBound < 0 or upperBound > 10000000'"; return 1; } int upperBound = atoi("asasddd"); //auto upperBound = boost::lexical_cast<int>(argv[1]); if (upperBound < 0 || upperBound > 100000000) { std::cout << "Wrong number\n"; return 1; } std::set<int> primeSet = GeneratePrimeNumbersSet(upperBound); for (int x : primeSet) { std::cout << x << " "; } return 0; }
22.096774
154
0.670073
AlexanderChibirev
a8d8c005a64253a10cb9005070a72d00ef246a2c
9,993
cpp
C++
src/monStaGen/incrementalDeterministicGraphGenerator.cpp
tyrex-team/gmark
e9f16c06d2c9fb76167077a3839d2f10585bc546
[ "MIT" ]
8
2020-01-04T15:12:36.000Z
2021-12-15T16:26:52.000Z
src/monStaGen/incrementalDeterministicGraphGenerator.cpp
tyrex-team/gmark
e9f16c06d2c9fb76167077a3839d2f10585bc546
[ "MIT" ]
2
2019-12-17T18:29:57.000Z
2020-04-09T14:01:37.000Z
src/monStaGen/incrementalDeterministicGraphGenerator.cpp
tyrex-team/gmark
e9f16c06d2c9fb76167077a3839d2f10585bc546
[ "MIT" ]
5
2020-02-22T20:20:13.000Z
2022-01-19T21:12:47.000Z
/* * incrementalDeterministicGraphGenerator.cpp * * Created on: Sep 16, 2016 * Author: wilcovanleeuwen */ #include <vector> #include <algorithm> // std::set_intersection, std::sort #include <chrono> #include "incrementalDeterministicGraphGenerator.h" #include "graphNode.h" namespace std { incrementalDeterministicGraphGenerator::incrementalDeterministicGraphGenerator() { randomGenerator.seed((unsigned int) chrono::system_clock::now().time_since_epoch().count()); // randomGenerator.seed(22); } incrementalDeterministicGraphGenerator::~incrementalDeterministicGraphGenerator() { } void incrementalDeterministicGraphGenerator::addEdge(graphNode &sourceNode, graphNode &targetNode, int predicate) { sourceNode.decrementOpenInterfaceConnections(); targetNode.decrementOpenInterfaceConnections(); edge2 newEdge; newEdge.subjectIterationId = sourceNode.iterationId; newEdge.objectIterationId = targetNode.iterationId; newEdge.subjectId = sourceNode.id; newEdge.predicate = predicate; newEdge.objectId = targetNode.id; newEdge.createdInGraph = graphNumber; edges.push_back(newEdge); } void incrementalDeterministicGraphGenerator::fixSchemaInequality(config::edge & edgeType) { double evOutDistribution = getMeanICsPerNode(edgeType.outgoing_distrib, conf.types[edgeType.subject_type].size[graphNumber]) + outDistrShift; double evInDistribution = getMeanICsPerNode(edgeType.incoming_distrib, conf.types[edgeType.object_type].size[graphNumber]) + inDistrShift; if ((conf.types[edgeType.subject_type].size[graphNumber] * evOutDistribution) > (conf.types[edgeType.object_type].size[graphNumber] * evInDistribution)) { performInDistributionShift(edgeType); } else { performOutDistributionShift(edgeType); } } vector<int> constructNodesVector(vector<graphNode> & nodes) { vector<int> nodesVector; for (graphNode & n: nodes) { // cout << "node" << n.iterationId << " has " << n.getNumberOfOpenInterfaceConnections() << " openICs" << endl; for (int i=0; i<n.getNumberOfOpenInterfaceConnections(); i++) { nodesVector.push_back(n.iterationId); } } return nodesVector; } vector<int> constructNodesVectorMinusOne(vector<graphNode> & nodes) { vector<int> nodesVector; for (graphNode & n: nodes) { // cout << "node" << n.iterationId << " has " << n.getNumberOfOpenInterfaceConnections() << " openICs" << endl; for (int i=0; i<n.getNumberOfOpenInterfaceConnections()-1; i++) { nodesVector.push_back(n.iterationId); } } return nodesVector; } vector<int> constructNodesVectorLastOne(vector<graphNode> & nodes) { vector<int> nodesVector; for (graphNode & n: nodes) { if(n.getNumberOfOpenInterfaceConnections() > 0) { nodesVector.push_back(n.iterationId); } } return nodesVector; } void incrementalDeterministicGraphGenerator::generateEdges(config::edge & edgeType, double prob) { if (edgeType.scale_factor > 0 || !conf.types[edgeType.subject_type].scalable || !conf.types[edgeType.object_type].scalable || edgeType.outgoing_distrib.type == DISTRIBUTION::ZIPFIAN || edgeType.incoming_distrib.type == DISTRIBUTION::ZIPFIAN) { vector<int> subjectNodeIdVector = constructNodesVector(nodes.first); vector<int> objectNodeIdVector = constructNodesVector(nodes.second); if (edgeType.outgoing_distrib.type == DISTRIBUTION::ZIPFIAN || edgeType.incoming_distrib.type == DISTRIBUTION::ZIPFIAN) { performFixingShiftForZipfian(edgeType, subjectNodeIdVector, objectNodeIdVector); } shuffle(subjectNodeIdVector.begin(), subjectNodeIdVector.end(), randomGenerator); shuffle(objectNodeIdVector.begin(), objectNodeIdVector.end(), randomGenerator); for (size_t i=0; i<min(subjectNodeIdVector.size(), objectNodeIdVector.size()); i++) { addEdge(nodes.first[subjectNodeIdVector[i]], nodes.second[objectNodeIdVector[i]], edgeType.predicate); } } else { // Create vectors vector<int> subjectNodeIdVectorMinusOne = constructNodesVectorMinusOne(nodes.first); vector<int> objectNodeIdVectorMinusOne = constructNodesVectorMinusOne(nodes.second); vector<int> subjectNodeIdVectorLastOne = constructNodesVectorLastOne(nodes.first); vector<int> objectNodeIdVectorLastOne = constructNodesVectorLastOne(nodes.second); // Shuffle small vectors shuffle(subjectNodeIdVectorLastOne.begin(), subjectNodeIdVectorLastOne.end(), randomGenerator); shuffle(objectNodeIdVectorLastOne.begin(), objectNodeIdVectorLastOne.end(), randomGenerator); // Add the difference in the lastOne-vector to the minusOne-vector if (subjectNodeIdVectorLastOne.size() > objectNodeIdVectorLastOne.size()) { for (size_t i=objectNodeIdVectorLastOne.size(); i<subjectNodeIdVectorLastOne.size(); i++) { subjectNodeIdVectorMinusOne.push_back(subjectNodeIdVectorLastOne[i]); } } else { for (size_t i=subjectNodeIdVectorLastOne.size(); i<objectNodeIdVectorLastOne.size(); i++) { objectNodeIdVectorMinusOne.push_back(objectNodeIdVectorLastOne[i]); } } // Shuffle large vectors shuffle(subjectNodeIdVectorMinusOne.begin(), subjectNodeIdVectorMinusOne.end(), randomGenerator); shuffle(objectNodeIdVectorMinusOne.begin(), objectNodeIdVectorMinusOne.end(), randomGenerator); // Create edges for (size_t i=0; i<min(subjectNodeIdVectorMinusOne.size(), objectNodeIdVectorMinusOne.size()); i++) { addEdge(nodes.first[subjectNodeIdVectorMinusOne[i]], nodes.second[objectNodeIdVectorMinusOne[i]], edgeType.predicate); } for (size_t i=0; i<min(subjectNodeIdVectorLastOne.size(), objectNodeIdVectorLastOne.size()); i++) { double randomValue = uniformDistr(randomGenerator); if (randomValue > prob) { addEdge(nodes.first[subjectNodeIdVectorLastOne[i]], nodes.second[objectNodeIdVectorLastOne[i]], edgeType.predicate); } } } } void incrementalDeterministicGraphGenerator::incrementGraph(config::edge & edgeType) { // Perform the shifting of the distribution as indecated by the user in the schema if (graphNumber > 0) { performSchemaIndicatedShift(edgeType); if ((conf.types.at(edgeType.subject_type).scalable ^ conf.types.at(edgeType.object_type).scalable) && edgeType.outgoing_distrib.type != DISTRIBUTION::ZIPFIAN && edgeType.incoming_distrib.type != DISTRIBUTION::ZIPFIAN) { performShiftForNonScalableNodes(edgeType); } } // Add subject and object nodes to the graph // Specify the current shift to get the wright amound of ICs nodeGen.addSubjectNodes(edgeType, outDistrShift, graphNumber); nodeGen.addObjectNodes(edgeType, inDistrShift, graphNumber); // Update the ICs for the Zipfian distribution to satisfy the property that influecer nodes will get more ICs when the graph grows if (edgeType.outgoing_distrib.type == DISTRIBUTION::ZIPFIAN) { updateInterfaceConnectionsForZipfianDistributions(edgeType.outgoing_distrib, true); } if (edgeType.incoming_distrib.type == DISTRIBUTION::ZIPFIAN) { updateInterfaceConnectionsForZipfianDistributions(edgeType.incoming_distrib, false); } double prob = 0.25; if (edgeType.correlated_with.size() == 0) { generateEdges(edgeType, prob); } else { vector<edge2> possibleEdges = generateCorrelatedEdgeSet(edgeType); generateCorrelatedEdges(edgeType, prob, possibleEdges); } } int incrementalDeterministicGraphGenerator::processEdgeTypeSingleGraph(config::config configuration, config::edge & edgeType, ofstream & outputFile, string outputFileName_, int graphNumber_, bool printNodeProperties) { cout << "Processing graph " << graphNumber_ << " edge type " << edgeType.edge_type_id << endl; // cout << endl << endl; this->conf = configuration; this->graphNumber = graphNumber_; this->outputFileName = outputFileName_; // cout << "Number of nodes: " << conf.nb_nodes[graphNumber] << endl; if (edgeType.outgoing_distrib.type == DISTRIBUTION::ZIPFIAN && outDistrShift == 0) { outDistrShift = 1; } if (edgeType.incoming_distrib.type == DISTRIBUTION::ZIPFIAN && inDistrShift == 0) { inDistrShift = 1; } if (graphNumber == 0 && edgeType.outgoing_distrib.type != DISTRIBUTION::ZIPFIAN && edgeType.incoming_distrib.type != DISTRIBUTION::ZIPFIAN) { fixSchemaInequality(edgeType); } nodeGen = nodeGenerator(edgeType, nodes.first.size(), nodes.second.size(), &randomGenerator, &nodes, &conf); if (edgeType.correlated_with.size() > 0) { cout << "Assume the following edge-type have been generated: " << endl; for (int etId: edgeType.correlated_with) { cout << " - " << etId << endl; } } incrementGraph(edgeType); // Materialize the edge // cout << "Number of edges: " << edges.size() << endl; for (size_t i=0; i<edges.size(); i++) { edge2 e = edges[i]; outputFile << e.subjectId << " "; if (conf.print_alias) { outputFile << conf.predicates[e.predicate].alias; } else { outputFile << e.predicate; } outputFile << " " << e.objectId << " | " << e.createdInGraph <<"\n"; } outputFile.flush(); if (printNodeProperties) { string subjectsNodesFileName = outputFileName + "_subjects_edgeType" + to_string(edgeType.edge_type_id) + "graphNumber" + to_string(graphNumber_) +".txt"; ofstream subjectNodes; subjectNodes.open(subjectsNodesFileName); subjectNodes << "Global node id, local node id, degree in the graph\n"; for (graphNode subject: nodes.first) { subjectNodes << subject.id << ", " << subject.iterationId << ", " << subject.numberOfInterfaceConnections-subject.numberOfOpenInterfaceConnections << "\n"; } subjectNodes.flush(); string objectsNodesFileName = outputFileName + "_objects_edgeType" + to_string(edgeType.edge_type_id) + "graphNumber" + to_string(graphNumber_) +".txt"; ofstream objectNodes; objectNodes.open(objectsNodesFileName); objectNodes << "Global node id, local node id, degree in the graph\n"; for (graphNode object: nodes.second) { objectNodes << object.id << ", " << object.iterationId << ", " << object.numberOfInterfaceConnections-object.numberOfOpenInterfaceConnections << "\n"; } objectNodes.flush(); } cout << endl; return 0; } } /* namespace std */
35.18662
158
0.749925
tyrex-team
a8da46207fb40fcd8b6a5cda7b0bfc146bef0671
7,681
cpp
C++
bullet-2.81-rev2613/src/BulletFluids/btFluidHfRigidDynamicsWorld.cpp
rtrius/Bullet-FLUIDS
b58dbc5108512e5a4bb0a532284a98128fd8f8ce
[ "Zlib" ]
19
2015-01-18T09:34:48.000Z
2021-07-22T08:00:17.000Z
bullet-2.81-rev2613/src/BulletFluids/btFluidHfRigidDynamicsWorld.cpp
rtrius/Bullet-FLUIDS
b58dbc5108512e5a4bb0a532284a98128fd8f8ce
[ "Zlib" ]
null
null
null
bullet-2.81-rev2613/src/BulletFluids/btFluidHfRigidDynamicsWorld.cpp
rtrius/Bullet-FLUIDS
b58dbc5108512e5a4bb0a532284a98128fd8f8ce
[ "Zlib" ]
8
2015-02-09T08:03:04.000Z
2021-07-22T08:01:54.000Z
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Experimental Buoyancy fluid demo written by John McCutchan */ //This is an altered source version based on the HeightFieldFluidDemo included with Bullet Physics 2.80(bullet-2.80-rev2531). #include "btFluidHfRigidDynamicsWorld.h" #include <stdio.h> #include "LinearMath/btQuickprof.h" #include "LinearMath/btIDebugDraw.h" #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "Hf/btFluidHf.h" #include "Hf/btFluidHfBuoyantConvexShape.h" btFluidHfRigidDynamicsWorld::btFluidHfRigidDynamicsWorld(btDispatcher* dispatcher, btBroadphaseInterface* pairCache, btConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration, btFluidSphSolver* sphSolver) : btFluidRigidDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration, sphSolver) { m_drawMode = DRAWMODE_NORMAL; m_bodyDrawMode = BODY_DRAWMODE_NORMAL; } void btFluidHfRigidDynamicsWorld::internalSingleStepSimulation(btScalar timeStep) { btFluidRigidDynamicsWorld::internalSingleStepSimulation(timeStep); { BT_PROFILE("updateHfFluids"); for(int i = 0; i < m_hfFluids.size(); i++) { btFluidHf* hfFluid = m_hfFluids[i]; hfFluid->stepSimulation(timeStep); } } } void btFluidHfRigidDynamicsWorld::addFluidHf(btFluidHf* body) { m_hfFluids.push_back(body); btCollisionWorld::addCollisionObject(body, btBroadphaseProxy::DefaultFilter, btBroadphaseProxy::AllFilter); } void btFluidHfRigidDynamicsWorld::removeFluidHf(btFluidHf* body) { m_hfFluids.remove(body); btCollisionWorld::removeCollisionObject(body); } void btFluidHfRigidDynamicsWorld::drawFluidHfGround (btIDebugDraw* debugDraw, btFluidHf* fluid) { btVector3 com = fluid->getWorldTransform().getOrigin(); btVector3 color = btVector3(btScalar(0.13f), btScalar(0.13f), btScalar(0.0)); for (int i = 1; i < fluid->getNumNodesX()-1; i++) { for (int j = 1; j < fluid->getNumNodesZ()-1; j++) { int sw = fluid->arrayIndex (i, j); int se = fluid->arrayIndex (i+1, j); int nw = fluid->arrayIndex (i, j+1); int ne = fluid->arrayIndex (i+1, j+1); btVector3 swV = btVector3 (fluid->getCellPosX (i), fluid->getGroundHeight(sw), fluid->getCellPosZ (j)); btVector3 seV = btVector3 (fluid->getCellPosX (i+1), fluid->getGroundHeight(se), fluid->getCellPosZ (j)); btVector3 nwV = btVector3 (fluid->getCellPosX (i), fluid->getGroundHeight(nw), fluid->getCellPosZ (j+1)); btVector3 neV = btVector3 (fluid->getCellPosX (i+1), fluid->getGroundHeight(ne), fluid->getCellPosZ (j+1)); debugDraw->drawTriangle (swV+com, seV+com, nwV+com, color, btScalar(1.0f)); debugDraw->drawTriangle (seV+com, neV+com, nwV+com, color, btScalar(1.0f)); } } } void btFluidHfRigidDynamicsWorld::drawFluidHfVelocity (btIDebugDraw* debugDraw, btFluidHf* fluid) { const btVector3& origin = fluid->getWorldTransform().getOrigin(); const btVector3 red = btVector3(btScalar(1.0f), btScalar(0.0f), btScalar(0.0)); const btVector3 green = btVector3(btScalar(0.0f), btScalar(1.0f), btScalar(0.0)); for (int i = 1; i < fluid->getNumNodesX()-1; i++) { for (int j = 1; j < fluid->getNumNodesZ()-1; j++) { int index = fluid->arrayIndex (i, j); if( !fluid->isActive(index) ) continue; btVector3 from = btVector3 ( fluid->getCellPosX(i), fluid->getCombinedHeight(index) + btScalar(0.1f), fluid->getCellPosZ(j) ); btVector3 velocity( fluid->getVelocityX(index), btScalar(0.0), fluid->getVelocityZ(index) ); velocity.normalize(); btVector3 to = from + velocity; debugDraw->drawLine (from+origin, to+origin, red, green); } } } void btFluidHfRigidDynamicsWorld::drawFluidHfBuoyantConvexShape (btIDebugDraw* debugDrawer, btCollisionObject* object, btFluidHfBuoyantConvexShape* buoyantShape, int voxelDraw) { if (voxelDraw) { const btTransform& xform = object->getWorldTransform(); for (int i = 0; i < buoyantShape->getNumVoxels(); i++) { btVector3 p = xform * buoyantShape->getVoxelPosition(i); debugDrawer->drawSphere( p, buoyantShape->getVoxelRadius(), btVector3(1.0, 0.0, 0.0) ); } } else { btVector3 color(btScalar(255.),btScalar(255.),btScalar(255.)); switch(object->getActivationState()) { case ACTIVE_TAG: color = btVector3(btScalar(255.),btScalar(255.),btScalar(255.)); break; case ISLAND_SLEEPING: color = btVector3(btScalar(0.),btScalar(255.),btScalar(0.));break; case WANTS_DEACTIVATION: color = btVector3(btScalar(0.),btScalar(255.),btScalar(255.));break; case DISABLE_DEACTIVATION: color = btVector3(btScalar(255.),btScalar(0.),btScalar(0.));break; case DISABLE_SIMULATION: color = btVector3(btScalar(255.),btScalar(255.),btScalar(0.));break; default: { color = btVector3(btScalar(255.),btScalar(0.),btScalar(0.)); } }; btConvexShape* convexShape = ((btFluidHfBuoyantConvexShape*)object->getCollisionShape())->getConvexShape(); debugDrawObject(object->getWorldTransform(),(btCollisionShape*)convexShape,color); } } void btFluidHfRigidDynamicsWorld::drawFluidHfNormal (btIDebugDraw* debugDraw, btFluidHf* fluid) { const btVector3& com = fluid->getWorldTransform().getOrigin(); for (int i = 0; i < fluid->getNumNodesX()-1; i++) { for (int j = 0; j < fluid->getNumNodesZ()-1; j++) { int sw = fluid->arrayIndex (i, j); btScalar h = fluid->getFluidHeight(sw); btScalar g = fluid->getGroundHeight(sw); if( h < btScalar(0.03f) ) continue; btVector3 boxMin = btVector3(fluid->getCellPosX (i), g, fluid->getCellPosZ(j)); btVector3 boxMax = btVector3(fluid->getCellPosX(i+1), g+h, fluid->getCellPosZ(j+1)); boxMin += com; boxMax += com; debugDraw->drawBox (boxMin, boxMax, btVector3(btScalar(0.0f), btScalar(0.0f), btScalar(1.0f))); } } } void btFluidHfRigidDynamicsWorld::debugDrawWorld() { if (getDebugDrawer()) { int i; for ( i=0;i<this->m_hfFluids.size();i++) { btFluidHf* phh=(btFluidHf*)this->m_hfFluids[i]; switch (m_drawMode) { case DRAWMODE_NORMAL: //drawFluidHfGround (m_debugDrawer, phh); //drawFluidHfNormal (m_debugDrawer, phh); break; case DRAWMODE_VELOCITY: //drawFluidHfGround (m_debugDrawer, phh); //drawFluidHfNormal (m_debugDrawer, phh); drawFluidHfVelocity (m_debugDrawer, phh); break; default: btAssert (0); break; } } for (i = 0; i < this->m_collisionObjects.size(); i++) { btCollisionShape* shape = m_collisionObjects[i]->getCollisionShape(); if (shape->getShapeType() == HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE) { btFluidHfBuoyantConvexShape* buoyantShape = (btFluidHfBuoyantConvexShape*)shape; drawFluidHfBuoyantConvexShape (m_debugDrawer, m_collisionObjects[i], buoyantShape, m_bodyDrawMode); } } } btFluidRigidDynamicsWorld::debugDrawWorld(); }
36.402844
243
0.728291
rtrius
a8df659c0231eab9f7ce36fbe8fe6c5553ba3673
9,504
cc
C++
src/arg_parse.cc
dstrain115/Stim
82a161741c05d637fe16ea20b1d99a48b4ca4750
[ "Apache-2.0" ]
2
2021-07-24T13:56:07.000Z
2021-11-17T11:03:51.000Z
src/arg_parse.cc
ephxyscj1996/Stim
1f35e36c33a6dba244318e904c35b63a3d82977a
[ "Apache-2.0" ]
null
null
null
src/arg_parse.cc
ephxyscj1996/Stim
1f35e36c33a6dba244318e904c35b63a3d82977a
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 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 // // 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 "arg_parse.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> using namespace stim_internal; const char *stim_internal::require_find_argument(const char *name, int argc, const char **argv) { const char *result = find_argument(name, argc, argv); if (result == 0) { fprintf(stderr, "\033[31mMissing command line argument: '%s'\033[0m\n", name); exit(EXIT_FAILURE); } return result; } const char *stim_internal::find_argument(const char *name, int argc, const char **argv) { // Respect that the "--" argument terminates flags. size_t flag_count = 1; while (flag_count < (size_t)argc && strcmp(argv[flag_count], "--") != 0) { flag_count++; } // Search for the desired flag. size_t n = strlen(name); for (size_t i = 1; i < flag_count; i++) { // Check if argument starts with expected flag. const char *loc = strstr(argv[i], name); if (loc != argv[i] || (loc[n] != '\0' && loc[n] != '=')) { continue; } // If the flag is alone and followed by the end or another flag, no // argument was provided. Return the empty string to indicate this. if (loc[n] == '\0' && ((int)i == argc - 1 || (argv[i + 1][0] == '-' && !isdigit(argv[i + 1][1])))) { return argv[i] + n; } // If the flag value is specified inline with '=', return a pointer to // the start of the value within the flag string. if (loc[n] == '=') { // Argument provided inline. return loc + n + 1; } // The argument value is specified by the next command line argument. return argv[i + 1]; } // Not found. return 0; } void stim_internal::check_for_unknown_arguments( const std::vector<const char *> &known_arguments, const char *for_mode, int argc, const char **argv) { for (int i = 1; i < argc; i++) { // Respect that the "--" argument terminates flags. if (!strcmp(argv[i], "--")) { break; } // Check if there's a matching command line argument. int matched = 0; for (size_t j = 0; j < known_arguments.size(); j++) { const char *loc = strstr(argv[i], known_arguments[j]); size_t n = strlen(known_arguments[j]); if (loc == argv[i] && (loc[n] == '\0' || loc[n] == '=')) { // Skip words that are values for a previous flag. if (loc[n] == '\0' && i < argc - 1 && argv[i + 1][0] != '-') { i++; } matched = 1; break; } } // Print error and exit if flag is not recognized. if (!matched) { if (for_mode == nullptr) { fprintf(stderr, "\033[31mUnrecognized command line argument %s.\n", argv[i]); fprintf(stderr, "Recognized command line arguments:\n"); } else { fprintf(stderr, "\033[31mUnrecognized command line argument %s for mode %s.\n", argv[i], for_mode); fprintf(stderr, "Recognized command line arguments for mode %s:\n", for_mode); } for (size_t j = 0; j < known_arguments.size(); j++) { fprintf(stderr, " %s\n", known_arguments[j]); } fprintf(stderr, "\033[0m"); exit(EXIT_FAILURE); } } } bool stim_internal::find_bool_argument(const char *name, int argc, const char **argv) { const char *text = find_argument(name, argc, argv); if (text == nullptr) { return false; } if (text[0] == '\0') { return true; } fprintf(stderr, "\033[31mGot non-empty value '%s' for boolean flag '%s'.\033[0m\n", text, name); exit(EXIT_FAILURE); } bool parse_int64(const char *data, int64_t *out) { char c = *data; if (c == 0) { return false; } bool negate = false; if (c == '-') { negate = true; data++; c = *data; } uint64_t accumulator = 0; while (c) { if (!(c >= '0' && c <= '9')) { return false; } uint64_t digit = c - '0'; uint64_t next = accumulator * 10 + digit; if (accumulator != (next - digit) / 10) { return false; // Overflow. } accumulator = next; data++; c = *data; } if (negate && accumulator == (uint64_t)INT64_MAX + uint64_t{1}) { *out = INT64_MIN; return true; } if (accumulator > INT64_MAX) { return false; } *out = (int64_t)accumulator; if (negate) { *out *= -1; } return true; } int64_t stim_internal::find_int64_argument( const char *name, int64_t default_value, int64_t min_value, int64_t max_value, int argc, const char **argv) { const char *text = find_argument(name, argc, argv); if (text == nullptr || text[0] == '\0') { if (default_value < min_value || default_value > max_value) { fprintf( stderr, "\033[31m" "Must specify a value for int flag '%s'.\n" "\033[0m", name); exit(EXIT_FAILURE); } return default_value; } // Attempt to parse. int64_t i; if (!parse_int64(text, &i)) { fprintf(stderr, "\033[31mGot non-int64 value '%s' for int64 flag '%s'.\033[0m\n", text, name); exit(EXIT_FAILURE); } // In range? if (i < min_value || i > max_value) { std::cerr << "\033[31mInteger value '" << text << "' for flag '" << name << "' doesn't satisfy " << min_value << " <= " << i << " <= " << max_value << ".\033[0m\n"; exit(EXIT_FAILURE); } return i; } float stim_internal::find_float_argument( const char *name, float default_value, float min_value, float max_value, int argc, const char **argv) { const char *text = find_argument(name, argc, argv); if (text == nullptr) { if (default_value < min_value || default_value > max_value) { fprintf( stderr, "\033[31m" "Must specify a value for float flag '%s'.\n" "\033[0m", name); exit(EXIT_FAILURE); } return default_value; } // Attempt to parse. char *processed; float f = strtof(text, &processed); if (*processed != '\0') { fprintf(stderr, "\033[31mGot non-float value '%s' for float flag '%s'.\033[0m\n", text, name); exit(EXIT_FAILURE); } // In range? if (f < min_value || f > max_value || f != f) { fprintf( stderr, "\033[31mFloat value '%s' for flag '%s' doesn't satisfy %f <= %f <= %f.\033[0m\n", text, name, min_value, f, max_value); exit(EXIT_FAILURE); } return f; } FILE *stim_internal::find_open_file_argument( const char *name, FILE *default_file, const char *mode, int argc, const char **argv) { const char *path = find_argument(name, argc, argv); if (path == nullptr) { if (default_file == nullptr) { std::cerr << "\033[31mMissing command line argument: '" << name << "'\033[0m\n"; exit(EXIT_FAILURE); } return default_file; } if (*path == '\0') { std::cerr << "\033[31mCommand line argument '" << name << "' can't be empty. It's supposed to be a file path.\033[0m\n"; exit(EXIT_FAILURE); } FILE *file = fopen(path, mode); if (file == nullptr) { std::cerr << "\033[31mFailed to open '" << path << "'\033[0m\n"; exit(EXIT_FAILURE); } return file; } ostream_else_cout::ostream_else_cout(std::unique_ptr<std::ostream> &&held) : held(std::move(held)) { } std::ostream &ostream_else_cout::stream() { if (held) { return *held; } else { return std::cout; } } ostream_else_cout stim_internal::find_output_stream_argument( const char *name, bool default_std_out, int argc, const char **argv) { const char *path = find_argument(name, argc, argv); if (path == nullptr) { if (!default_std_out) { std::cerr << "\033[31mMissing command line argument: '" << name << "'\033[0m\n"; exit(EXIT_FAILURE); } return {nullptr}; } if (*path == '\0') { std::cerr << "\033[31mCommand line argument '" << name << "' can't be empty. It's supposed to be a file path.\033[0m\n"; exit(EXIT_FAILURE); } std::unique_ptr<std::ostream> f(new std::ofstream(path)); if (f->fail()) { std::cerr << "\033[31mFailed to open '" << path << "'\033[0m\n"; exit(EXIT_FAILURE); } return {std::move(f)}; }
32.216949
117
0.539983
dstrain115
a8e1a3df1922b5c8d625de3942b1b5e1f9824e29
20,621
hpp
C++
include/vuk/Image.hpp
zacharycarter/vuk
db3808fbbebcbf1912f060b54aad083e0e0168ae
[ "MIT" ]
173
2020-02-25T08:35:12.000Z
2022-03-28T07:48:39.000Z
include/vuk/Image.hpp
zacharycarter/vuk
db3808fbbebcbf1912f060b54aad083e0e0168ae
[ "MIT" ]
42
2020-10-15T12:48:29.000Z
2022-03-19T17:08:58.000Z
include/vuk/Image.hpp
zacharycarter/vuk
db3808fbbebcbf1912f060b54aad083e0e0168ae
[ "MIT" ]
13
2020-05-28T13:28:46.000Z
2022-02-06T09:34:50.000Z
#pragma once #include "Types.hpp" #include "../src/CreateInfo.hpp" namespace vuk { using Image = VkImage; using Sampler = Handle<VkSampler>; enum class ImageTiling { eOptimal = VK_IMAGE_TILING_OPTIMAL, eLinear = VK_IMAGE_TILING_LINEAR, eDrmFormatModifierEXT = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT }; enum class ImageType { e1D = VK_IMAGE_TYPE_1D, e2D = VK_IMAGE_TYPE_2D, e3D = VK_IMAGE_TYPE_3D }; enum class ImageUsageFlagBits : VkImageUsageFlags { eTransferSrc = VK_IMAGE_USAGE_TRANSFER_SRC_BIT, eTransferDst = VK_IMAGE_USAGE_TRANSFER_DST_BIT, eSampled = VK_IMAGE_USAGE_SAMPLED_BIT, eStorage = VK_IMAGE_USAGE_STORAGE_BIT, eColorAttachment = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, eDepthStencilAttachment = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, eTransientAttachment = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT, eInputAttachment = VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, eShadingRateImageNV = VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV, eFragmentDensityMapEXT = VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT }; using ImageUsageFlags = Flags<ImageUsageFlagBits>; inline constexpr ImageUsageFlags operator|(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept { return ImageUsageFlags(bit0) | bit1; } inline constexpr ImageUsageFlags operator&(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept { return ImageUsageFlags(bit0) & bit1; } inline constexpr ImageUsageFlags operator^(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept { return ImageUsageFlags(bit0) ^ bit1; } enum class ImageCreateFlagBits : VkImageCreateFlags { eSparseBinding = VK_IMAGE_CREATE_SPARSE_BINDING_BIT, eSparseResidency = VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT, eSparseAliased = VK_IMAGE_CREATE_SPARSE_ALIASED_BIT, eMutableFormat = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, eCubeCompatible = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, eAlias = VK_IMAGE_CREATE_ALIAS_BIT, eSplitInstanceBindRegions = VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT, e2DArrayCompatible = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT, eBlockTexelViewCompatible = VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT, eExtendedUsage = VK_IMAGE_CREATE_EXTENDED_USAGE_BIT, eProtected = VK_IMAGE_CREATE_PROTECTED_BIT, eDisjoint = VK_IMAGE_CREATE_DISJOINT_BIT, eCornerSampledNV = VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV, eSampleLocationsCompatibleDepthEXT = VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT, eSubsampledEXT = VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT, e2DArrayCompatibleKHR = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR, eAliasKHR = VK_IMAGE_CREATE_ALIAS_BIT_KHR, eBlockTexelViewCompatibleKHR = VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR, eDisjointKHR = VK_IMAGE_CREATE_DISJOINT_BIT_KHR, eExtendedUsageKHR = VK_IMAGE_CREATE_EXTENDED_USAGE_BIT_KHR, eSplitInstanceBindRegionsKHR = VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR }; using ImageCreateFlags = Flags<ImageCreateFlagBits>; inline constexpr ImageCreateFlags operator|(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept { return ImageCreateFlags(bit0) | bit1; } inline constexpr ImageCreateFlags operator&(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept { return ImageCreateFlags(bit0) & bit1; } inline constexpr ImageCreateFlags operator^(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept { return ImageCreateFlags(bit0) ^ bit1; } enum class ImageLayout { eUndefined = VK_IMAGE_LAYOUT_UNDEFINED, eGeneral = VK_IMAGE_LAYOUT_GENERAL, eColorAttachmentOptimal = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, eDepthStencilAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, eDepthStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, eShaderReadOnlyOptimal = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, eTransferSrcOptimal = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, eTransferDstOptimal = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, ePreinitialized = VK_IMAGE_LAYOUT_PREINITIALIZED, eDepthReadOnlyStencilAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, eDepthAttachmentStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, eDepthAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, eDepthReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, eStencilAttachmentOptimal = VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL, eStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL, ePresentSrcKHR = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, eSharedPresentKHR = VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR, eShadingRateOptimalNV = VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV, eFragmentDensityMapOptimalEXT = VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, eDepthAttachmentOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL_KHR, eDepthAttachmentStencilReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR, eDepthReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL_KHR, eDepthReadOnlyStencilAttachmentOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR, eStencilAttachmentOptimalKHR = VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR, eStencilReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL_KHR }; enum class SharingMode { eExclusive = VK_SHARING_MODE_EXCLUSIVE, eConcurrent = VK_SHARING_MODE_CONCURRENT }; struct ImageCreateInfo { static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; VkStructureType sType = structureType; const void* pNext = {}; ImageCreateFlags flags = {}; ImageType imageType = ImageType::e2D; Format format = Format::eUndefined; Extent3D extent = {}; uint32_t mipLevels = 1; uint32_t arrayLayers = 1; SampleCountFlagBits samples = SampleCountFlagBits::e1; ImageTiling tiling = ImageTiling::eOptimal; ImageUsageFlags usage = {}; SharingMode sharingMode = SharingMode::eExclusive; uint32_t queueFamilyIndexCount = {}; const uint32_t* pQueueFamilyIndices = {}; ImageLayout initialLayout = ImageLayout::eUndefined; operator VkImageCreateInfo const& () const noexcept { return *reinterpret_cast<const VkImageCreateInfo*>(this); } operator VkImageCreateInfo& () noexcept { return *reinterpret_cast<VkImageCreateInfo*>(this); } bool operator==(ImageCreateInfo const& rhs) const noexcept { return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (imageType == rhs.imageType) && (format == rhs.format) && (extent == rhs.extent) && (mipLevels == rhs.mipLevels) && (arrayLayers == rhs.arrayLayers) && (samples == rhs.samples) && (tiling == rhs.tiling) && (usage == rhs.usage) && (sharingMode == rhs.sharingMode) && (queueFamilyIndexCount == rhs.queueFamilyIndexCount) && (pQueueFamilyIndices == rhs.pQueueFamilyIndices) && (initialLayout == rhs.initialLayout); } bool operator!=(ImageCreateInfo const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(ImageCreateInfo) == sizeof(VkImageCreateInfo), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<ImageCreateInfo>::value, "struct wrapper is not a standard layout!"); enum class ImageViewCreateFlagBits : VkImageViewCreateFlags { eFragmentDensityMapDynamicEXT = VK_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT }; enum class ImageViewType { e1D = VK_IMAGE_VIEW_TYPE_1D, e2D = VK_IMAGE_VIEW_TYPE_2D, e3D = VK_IMAGE_VIEW_TYPE_3D, eCube = VK_IMAGE_VIEW_TYPE_CUBE, e1DArray = VK_IMAGE_VIEW_TYPE_1D_ARRAY, e2DArray = VK_IMAGE_VIEW_TYPE_2D_ARRAY, eCubeArray = VK_IMAGE_VIEW_TYPE_CUBE_ARRAY }; using ImageViewCreateFlags = Flags<ImageViewCreateFlagBits>; enum class ComponentSwizzle { eIdentity = VK_COMPONENT_SWIZZLE_IDENTITY, eZero = VK_COMPONENT_SWIZZLE_ZERO, eOne = VK_COMPONENT_SWIZZLE_ONE, eR = VK_COMPONENT_SWIZZLE_R, eG = VK_COMPONENT_SWIZZLE_G, eB = VK_COMPONENT_SWIZZLE_B, eA = VK_COMPONENT_SWIZZLE_A }; struct ComponentMapping { ComponentSwizzle r = ComponentSwizzle::eIdentity; ComponentSwizzle g = ComponentSwizzle::eIdentity; ComponentSwizzle b = ComponentSwizzle::eIdentity; ComponentSwizzle a = ComponentSwizzle::eIdentity; operator VkComponentMapping const& () const noexcept { return *reinterpret_cast<const VkComponentMapping*>(this); } operator VkComponentMapping& () noexcept { return *reinterpret_cast<VkComponentMapping*>(this); } bool operator==(ComponentMapping const& rhs) const noexcept { return (r == rhs.r) && (g == rhs.g) && (b == rhs.b) && (a == rhs.a); } bool operator!=(ComponentMapping const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(ComponentMapping) == sizeof(VkComponentMapping), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<ComponentMapping>::value, "struct wrapper is not a standard layout!"); enum class ImageAspectFlagBits : VkImageAspectFlags { eColor = VK_IMAGE_ASPECT_COLOR_BIT, eDepth = VK_IMAGE_ASPECT_DEPTH_BIT, eStencil = VK_IMAGE_ASPECT_STENCIL_BIT, eMetadata = VK_IMAGE_ASPECT_METADATA_BIT, ePlane0 = VK_IMAGE_ASPECT_PLANE_0_BIT, ePlane1 = VK_IMAGE_ASPECT_PLANE_1_BIT, ePlane2 = VK_IMAGE_ASPECT_PLANE_2_BIT, eMemoryPlane0EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT, eMemoryPlane1EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT, eMemoryPlane2EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT, eMemoryPlane3EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT, ePlane0KHR = VK_IMAGE_ASPECT_PLANE_0_BIT_KHR, ePlane1KHR = VK_IMAGE_ASPECT_PLANE_1_BIT_KHR, ePlane2KHR = VK_IMAGE_ASPECT_PLANE_2_BIT_KHR }; using ImageAspectFlags = Flags<ImageAspectFlagBits>; inline constexpr ImageAspectFlags operator|(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept { return ImageAspectFlags(bit0) | bit1; } inline constexpr ImageAspectFlags operator&(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept { return ImageAspectFlags(bit0) & bit1; } inline constexpr ImageAspectFlags operator^(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept { return ImageAspectFlags(bit0) ^ bit1; } struct ImageSubresourceRange { ImageAspectFlags aspectMask = {}; uint32_t baseMipLevel = 0; uint32_t levelCount = 1; uint32_t baseArrayLayer = 0; uint32_t layerCount = 1; operator VkImageSubresourceRange const& () const noexcept { return *reinterpret_cast<const VkImageSubresourceRange*>(this); } operator VkImageSubresourceRange& () noexcept { return *reinterpret_cast<VkImageSubresourceRange*>(this); } bool operator==(ImageSubresourceRange const& rhs) const noexcept { return (aspectMask == rhs.aspectMask) && (baseMipLevel == rhs.baseMipLevel) && (levelCount == rhs.levelCount) && (baseArrayLayer == rhs.baseArrayLayer) && (layerCount == rhs.layerCount); } bool operator!=(ImageSubresourceRange const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(ImageSubresourceRange) == sizeof(VkImageSubresourceRange), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<ImageSubresourceRange>::value, "struct wrapper is not a standard layout!"); struct ImageViewCreateInfo { static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; VkStructureType sType = structureType; const void* pNext = {}; ImageViewCreateFlags flags = {}; Image image = {}; ImageViewType viewType = ImageViewType::e2D; Format format = Format::eUndefined; ComponentMapping components = {}; ImageSubresourceRange subresourceRange = {}; operator VkImageViewCreateInfo const& () const noexcept { return *reinterpret_cast<const VkImageViewCreateInfo*>(this); } operator VkImageViewCreateInfo& () noexcept { return *reinterpret_cast<VkImageViewCreateInfo*>(this); } bool operator==(ImageViewCreateInfo const& rhs) const noexcept { return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (image == rhs.image) && (viewType == rhs.viewType) && (format == rhs.format) && (components == rhs.components) && (subresourceRange == rhs.subresourceRange); } bool operator!=(ImageViewCreateInfo const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(ImageViewCreateInfo) == sizeof(VkImageViewCreateInfo), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<ImageViewCreateInfo>::value, "struct wrapper is not a standard layout!"); struct ImageView { VkImageView payload = VK_NULL_HANDLE; VkImage image; // 64 bits Format format; //32 bits uint32_t id : 29; ImageViewType type : 3; uint32_t base_mip : 4; uint32_t mip_count : 4; uint32_t base_layer : 11; uint32_t layer_count : 11; ComponentMapping components; bool operator==(const ImageView& other) const noexcept { return payload == other.payload; } }; //static_assert(sizeof(ImageView) == 64); template<> class Unique<ImageView> { Context* context; ImageView payload; public: using element_type = ImageView; Unique() : context(nullptr) {} explicit Unique(vuk::Context& ctx, ImageView payload) : context(&ctx), payload(std::move(payload)) {} Unique(Unique const&) = delete; Unique(Unique&& other) noexcept : context(other.context), payload(other.release()) {} ~Unique() noexcept; Unique& operator=(Unique const&) = delete; Unique& operator=(Unique&& other) noexcept { auto tmp = other.context; reset(other.release()); context = tmp; return *this; } explicit operator bool() const noexcept { return payload.payload == VK_NULL_HANDLE; } ImageView const* operator->() const noexcept { return &payload; } ImageView* operator->() noexcept { return &payload; } ImageView const& operator*() const noexcept { return payload; } ImageView& operator*() noexcept { return payload; } const ImageView& get() const noexcept { return payload; } ImageView& get() noexcept { return payload; } void reset(ImageView value = ImageView()) noexcept; ImageView release() noexcept { context = nullptr; return std::move(payload); } void swap(Unique<ImageView>& rhs) noexcept { std::swap(payload, rhs.payload); std::swap(context, rhs.context); } struct SubrangeBuilder { vuk::Context* ctx; vuk::ImageView iv; vuk::ImageViewType type = vuk::ImageViewType(0xdeadbeef); uint32_t base_mip = 0xdeadbeef; // 0xdeadbeef is an out of band value for all uint32_t mip_count = 0xdeadbeef; uint32_t base_layer = 0xdeadbeef; uint32_t layer_count = 0xdeadbeef; SubrangeBuilder& layer_subrange(uint32_t base_layer, uint32_t layer_count) { this->base_layer = base_layer; this->layer_count = layer_count; return *this; } SubrangeBuilder& mip_subrange(uint32_t base_mip, uint32_t mip_count) { this->base_mip = base_mip; this->mip_count = mip_count; return *this; } SubrangeBuilder& view_as(ImageViewType type) { this->type = type; return *this; } Unique<ImageView> apply(); }; // external builder fns SubrangeBuilder layer_subrange(uint32_t base_layer, uint32_t layer_count) { return { .ctx = context, .iv = payload, .base_layer = base_layer, .layer_count = layer_count }; } SubrangeBuilder mip_subrange(uint32_t base_mip, uint32_t mip_count) { return { .ctx = context, .iv = payload, .base_mip = base_mip, .mip_count = mip_count }; } }; enum class SamplerCreateFlagBits : VkSamplerCreateFlags { eSubsampledEXT = VK_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT, eSubsampledCoarseReconstructionEXT = VK_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT }; using SamplerCreateFlags = Flags<SamplerCreateFlagBits>; enum class Filter { eNearest = VK_FILTER_NEAREST, eLinear = VK_FILTER_LINEAR, eCubicIMG = VK_FILTER_CUBIC_IMG, eCubicEXT = VK_FILTER_CUBIC_EXT }; enum class SamplerMipmapMode { eNearest = VK_SAMPLER_MIPMAP_MODE_NEAREST, eLinear = VK_SAMPLER_MIPMAP_MODE_LINEAR }; enum class SamplerAddressMode { eRepeat = VK_SAMPLER_ADDRESS_MODE_REPEAT, eMirroredRepeat = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT, eClampToEdge = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, eClampToBorder = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, eMirrorClampToEdge = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE, eMirrorClampToEdgeKHR = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE_KHR }; enum class CompareOp { eNever = VK_COMPARE_OP_NEVER, eLess = VK_COMPARE_OP_LESS, eEqual = VK_COMPARE_OP_EQUAL, eLessOrEqual = VK_COMPARE_OP_LESS_OR_EQUAL, eGreater = VK_COMPARE_OP_GREATER, eNotEqual = VK_COMPARE_OP_NOT_EQUAL, eGreaterOrEqual = VK_COMPARE_OP_GREATER_OR_EQUAL, eAlways = VK_COMPARE_OP_ALWAYS }; enum class BorderColor { eFloatTransparentBlack = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, eIntTransparentBlack = VK_BORDER_COLOR_INT_TRANSPARENT_BLACK, eFloatOpaqueBlack = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK, eIntOpaqueBlack = VK_BORDER_COLOR_INT_OPAQUE_BLACK, eFloatOpaqueWhite = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, eIntOpaqueWhite = VK_BORDER_COLOR_INT_OPAQUE_WHITE, eFloatCustomEXT = VK_BORDER_COLOR_FLOAT_CUSTOM_EXT, eIntCustomEXT = VK_BORDER_COLOR_INT_CUSTOM_EXT }; struct SamplerCreateInfo { static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; VkStructureType sType = structureType; const void* pNext = {}; SamplerCreateFlags flags = {}; Filter magFilter = Filter::eNearest; Filter minFilter = Filter::eNearest; SamplerMipmapMode mipmapMode = SamplerMipmapMode::eNearest; SamplerAddressMode addressModeU = SamplerAddressMode::eRepeat; SamplerAddressMode addressModeV = SamplerAddressMode::eRepeat; SamplerAddressMode addressModeW = SamplerAddressMode::eRepeat; float mipLodBias = {}; Bool32 anisotropyEnable = {}; float maxAnisotropy = {}; Bool32 compareEnable = {}; CompareOp compareOp = CompareOp::eNever; float minLod = 0.f; float maxLod = VK_LOD_CLAMP_NONE; BorderColor borderColor = BorderColor::eFloatTransparentBlack; Bool32 unnormalizedCoordinates = {}; operator VkSamplerCreateInfo const& () const noexcept { return *reinterpret_cast<const VkSamplerCreateInfo*>(this); } operator VkSamplerCreateInfo& () noexcept { return *reinterpret_cast<VkSamplerCreateInfo*>(this); } bool operator==(SamplerCreateInfo const& rhs) const noexcept { return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (magFilter == rhs.magFilter) && (minFilter == rhs.minFilter) && (mipmapMode == rhs.mipmapMode) && (addressModeU == rhs.addressModeU) && (addressModeV == rhs.addressModeV) && (addressModeW == rhs.addressModeW) && (mipLodBias == rhs.mipLodBias) && (anisotropyEnable == rhs.anisotropyEnable) && (maxAnisotropy == rhs.maxAnisotropy) && (compareEnable == rhs.compareEnable) && (compareOp == rhs.compareOp) && (minLod == rhs.minLod) && (maxLod == rhs.maxLod) && (borderColor == rhs.borderColor) && (unnormalizedCoordinates == rhs.unnormalizedCoordinates); } bool operator!=(SamplerCreateInfo const& rhs) const noexcept { return !operator==(rhs); } }; static_assert(sizeof(SamplerCreateInfo) == sizeof(VkSamplerCreateInfo), "struct and wrapper have different size!"); static_assert(std::is_standard_layout<SamplerCreateInfo>::value, "struct wrapper is not a standard layout!"); template<> struct create_info<Sampler> { using type = vuk::SamplerCreateInfo; }; struct Texture { Unique<Image> image; Unique<ImageView> view; Extent3D extent; Format format; Samples sample_count; }; inline vuk::ImageAspectFlags format_to_aspect(vuk::Format format) noexcept { switch (format) { case vuk::Format::eD16Unorm: case vuk::Format::eD32Sfloat: case vuk::Format::eX8D24UnormPack32: return vuk::ImageAspectFlagBits::eDepth; case vuk::Format::eD16UnormS8Uint: case vuk::Format::eD24UnormS8Uint: case vuk::Format::eD32SfloatS8Uint: return vuk::ImageAspectFlagBits::eDepth | vuk::ImageAspectFlagBits::eStencil; case vuk::Format::eS8Uint: return vuk::ImageAspectFlagBits::eStencil; default: return vuk::ImageAspectFlagBits::eColor; } } }; namespace std { template<> struct hash<vuk::ImageView> { size_t operator()(vuk::ImageView const& x) const noexcept { size_t h = 0; hash_combine(h, x.id, reinterpret_cast<uint64_t>(x.payload)); return h; } }; }
34.83277
124
0.772513
zacharycarter
a8e1d1f51c9a32543413ffbe421b34292acf6167
23,990
cpp
C++
android/android_9/frameworks/av/media/libmediaplayer2/MediaPlayer2AudioOutput.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/av/media/libmediaplayer2/MediaPlayer2AudioOutput.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/av/media/libmediaplayer2/MediaPlayer2AudioOutput.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* ** ** Copyright 2018, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ //#define LOG_NDEBUG 0 #define LOG_TAG "MediaPlayer2AudioOutput" #include <mediaplayer2/MediaPlayer2AudioOutput.h> #include <cutils/properties.h> // for property_get #include <utils/Log.h> #include <media/AudioPolicyHelper.h> #include <media/AudioTrack.h> #include <media/stagefright/foundation/ADebug.h> namespace { const float kMaxRequiredSpeed = 8.0f; // for PCM tracks allow up to 8x speedup. } // anonymous namespace namespace android { // TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround /* static */ int MediaPlayer2AudioOutput::mMinBufferCount = 4; /* static */ bool MediaPlayer2AudioOutput::mIsOnEmulator = false; status_t MediaPlayer2AudioOutput::dump(int fd, const Vector<String16>& args) const { const size_t SIZE = 256; char buffer[SIZE]; String8 result; result.append(" MediaPlayer2AudioOutput\n"); snprintf(buffer, 255, " stream type(%d), left - right volume(%f, %f)\n", mStreamType, mLeftVolume, mRightVolume); result.append(buffer); snprintf(buffer, 255, " msec per frame(%f), latency (%d)\n", mMsecsPerFrame, (mTrack != 0) ? mTrack->latency() : -1); result.append(buffer); snprintf(buffer, 255, " aux effect id(%d), send level (%f)\n", mAuxEffectId, mSendLevel); result.append(buffer); ::write(fd, result.string(), result.size()); if (mTrack != 0) { mTrack->dump(fd, args); } return NO_ERROR; } MediaPlayer2AudioOutput::MediaPlayer2AudioOutput(audio_session_t sessionId, uid_t uid, int pid, const audio_attributes_t* attr, const sp<AudioSystem::AudioDeviceCallback>& deviceCallback) : mCallback(NULL), mCallbackCookie(NULL), mCallbackData(NULL), mStreamType(AUDIO_STREAM_MUSIC), mLeftVolume(1.0), mRightVolume(1.0), mPlaybackRate(AUDIO_PLAYBACK_RATE_DEFAULT), mSampleRateHz(0), mMsecsPerFrame(0), mFrameSize(0), mSessionId(sessionId), mUid(uid), mPid(pid), mSendLevel(0.0), mAuxEffectId(0), mFlags(AUDIO_OUTPUT_FLAG_NONE), mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE), mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE), mDeviceCallbackEnabled(false), mDeviceCallback(deviceCallback) { ALOGV("MediaPlayer2AudioOutput(%d)", sessionId); if (attr != NULL) { mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t)); if (mAttributes != NULL) { memcpy(mAttributes, attr, sizeof(audio_attributes_t)); mStreamType = audio_attributes_to_stream_type(attr); } } else { mAttributes = NULL; } setMinBufferCount(); } MediaPlayer2AudioOutput::~MediaPlayer2AudioOutput() { close(); free(mAttributes); delete mCallbackData; } //static void MediaPlayer2AudioOutput::setMinBufferCount() { char value[PROPERTY_VALUE_MAX]; if (property_get("ro.kernel.qemu", value, 0)) { mIsOnEmulator = true; mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator } } // static bool MediaPlayer2AudioOutput::isOnEmulator() { setMinBufferCount(); // benign race wrt other threads return mIsOnEmulator; } // static int MediaPlayer2AudioOutput::getMinBufferCount() { setMinBufferCount(); // benign race wrt other threads return mMinBufferCount; } ssize_t MediaPlayer2AudioOutput::bufferSize() const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } return mTrack->frameCount() * mFrameSize; } ssize_t MediaPlayer2AudioOutput::frameCount() const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } return mTrack->frameCount(); } ssize_t MediaPlayer2AudioOutput::channelCount() const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } return mTrack->channelCount(); } ssize_t MediaPlayer2AudioOutput::frameSize() const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } return mFrameSize; } uint32_t MediaPlayer2AudioOutput::latency () const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return 0; } return mTrack->latency(); } float MediaPlayer2AudioOutput::msecsPerFrame() const { Mutex::Autolock lock(mLock); return mMsecsPerFrame; } status_t MediaPlayer2AudioOutput::getPosition(uint32_t *position) const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } return mTrack->getPosition(position); } status_t MediaPlayer2AudioOutput::getTimestamp(AudioTimestamp &ts) const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } return mTrack->getTimestamp(ts); } // TODO: Remove unnecessary calls to getPlayedOutDurationUs() // as it acquires locks and may query the audio driver. // // Some calls could conceivably retrieve extrapolated data instead of // accessing getTimestamp() or getPosition() every time a data buffer with // a media time is received. // // Calculate duration of played samples if played at normal rate (i.e., 1.0). int64_t MediaPlayer2AudioOutput::getPlayedOutDurationUs(int64_t nowUs) const { Mutex::Autolock lock(mLock); if (mTrack == 0 || mSampleRateHz == 0) { return 0; } uint32_t numFramesPlayed; int64_t numFramesPlayedAtUs; AudioTimestamp ts; status_t res = mTrack->getTimestamp(ts); if (res == OK) { // case 1: mixing audio tracks and offloaded tracks. numFramesPlayed = ts.mPosition; numFramesPlayedAtUs = ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000; //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAtUs); } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track numFramesPlayed = 0; numFramesPlayedAtUs = nowUs; //ALOGD("getTimestamp: WOULD_BLOCK %d %lld", // numFramesPlayed, (long long)numFramesPlayedAtUs); } else { // case 3: transitory at new track or audio fast tracks. res = mTrack->getPosition(&numFramesPlayed); CHECK_EQ(res, (status_t)OK); numFramesPlayedAtUs = nowUs; numFramesPlayedAtUs += 1000LL * mTrack->latency() / 2; /* XXX */ //ALOGD("getPosition: %u %lld", numFramesPlayed, (long long)numFramesPlayedAtUs); } // CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours. int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000000LL / mSampleRateHz) + nowUs - numFramesPlayedAtUs; if (durationUs < 0) { // Occurs when numFramesPlayed position is very small and the following: // (1) In case 1, the time nowUs is computed before getTimestamp() is called and // numFramesPlayedAtUs is greater than nowUs by time more than numFramesPlayed. // (2) In case 3, using getPosition and adding mAudioSink->latency() to // numFramesPlayedAtUs, by a time amount greater than numFramesPlayed. // // Both of these are transitory conditions. ALOGV("getPlayedOutDurationUs: negative duration %lld set to zero", (long long)durationUs); durationUs = 0; } ALOGV("getPlayedOutDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)", (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAtUs); return durationUs; } status_t MediaPlayer2AudioOutput::getFramesWritten(uint32_t *frameswritten) const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } ExtendedTimestamp ets; status_t status = mTrack->getTimestamp(&ets); if (status == OK || status == WOULD_BLOCK) { *frameswritten = (uint32_t)ets.mPosition[ExtendedTimestamp::LOCATION_CLIENT]; } return status; } status_t MediaPlayer2AudioOutput::setParameters(const String8& keyValuePairs) { Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } return mTrack->setParameters(keyValuePairs); } String8 MediaPlayer2AudioOutput::getParameters(const String8& keys) { Mutex::Autolock lock(mLock); if (mTrack == 0) { return String8::empty(); } return mTrack->getParameters(keys); } void MediaPlayer2AudioOutput::setAudioAttributes(const audio_attributes_t * attributes) { Mutex::Autolock lock(mLock); if (attributes == NULL) { free(mAttributes); mAttributes = NULL; } else { if (mAttributes == NULL) { mAttributes = (audio_attributes_t *) calloc(1, sizeof(audio_attributes_t)); } memcpy(mAttributes, attributes, sizeof(audio_attributes_t)); mStreamType = audio_attributes_to_stream_type(attributes); } } void MediaPlayer2AudioOutput::setAudioStreamType(audio_stream_type_t streamType) { Mutex::Autolock lock(mLock); // do not allow direct stream type modification if attributes have been set if (mAttributes == NULL) { mStreamType = streamType; } } void MediaPlayer2AudioOutput::close_l() { mTrack.clear(); } status_t MediaPlayer2AudioOutput::open( uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask, audio_format_t format, int bufferCount, AudioCallback cb, void *cookie, audio_output_flags_t flags, const audio_offload_info_t *offloadInfo, bool doNotReconnect, uint32_t suggestedFrameCount) { ALOGV("open(%u, %d, 0x%x, 0x%x, %d, %d 0x%x)", sampleRate, channelCount, channelMask, format, bufferCount, mSessionId, flags); // offloading is only supported in callback mode for now. // offloadInfo must be present if offload flag is set if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) && ((cb == NULL) || (offloadInfo == NULL))) { return BAD_VALUE; } // compute frame count for the AudioTrack internal buffer size_t frameCount; if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) { frameCount = 0; // AudioTrack will get frame count from AudioFlinger } else { // try to estimate the buffer processing fetch size from AudioFlinger. // framesPerBuffer is approximate and generally correct, except when it's not :-). uint32_t afSampleRate; size_t afFrameCount; if (AudioSystem::getOutputFrameCount(&afFrameCount, mStreamType) != NO_ERROR) { return NO_INIT; } if (AudioSystem::getOutputSamplingRate(&afSampleRate, mStreamType) != NO_ERROR) { return NO_INIT; } const size_t framesPerBuffer = (unsigned long long)sampleRate * afFrameCount / afSampleRate; if (bufferCount == 0) { // use suggestedFrameCount bufferCount = (suggestedFrameCount + framesPerBuffer - 1) / framesPerBuffer; } // Check argument bufferCount against the mininum buffer count if (bufferCount != 0 && bufferCount < mMinBufferCount) { ALOGV("bufferCount (%d) increased to %d", bufferCount, mMinBufferCount); bufferCount = mMinBufferCount; } // if frameCount is 0, then AudioTrack will get frame count from AudioFlinger // which will be the minimum size permitted. frameCount = bufferCount * framesPerBuffer; } if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) { channelMask = audio_channel_out_mask_from_count(channelCount); if (0 == channelMask) { ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount); return NO_INIT; } } Mutex::Autolock lock(mLock); mCallback = cb; mCallbackCookie = cookie; sp<AudioTrack> t; CallbackData *newcbd = NULL; ALOGV("creating new AudioTrack"); if (mCallback != NULL) { newcbd = new CallbackData(this); t = new AudioTrack( mStreamType, sampleRate, format, channelMask, frameCount, flags, CallbackWrapper, newcbd, 0, // notification frames mSessionId, AudioTrack::TRANSFER_CALLBACK, offloadInfo, mUid, mPid, mAttributes, doNotReconnect, 1.0f, // default value for maxRequiredSpeed mSelectedDeviceId); } else { // TODO: Due to buffer memory concerns, we use a max target playback speed // based on mPlaybackRate at the time of open (instead of kMaxRequiredSpeed), // also clamping the target speed to 1.0 <= targetSpeed <= kMaxRequiredSpeed. const float targetSpeed = std::min(std::max(mPlaybackRate.mSpeed, 1.0f), kMaxRequiredSpeed); ALOGW_IF(targetSpeed != mPlaybackRate.mSpeed, "track target speed:%f clamped from playback speed:%f", targetSpeed, mPlaybackRate.mSpeed); t = new AudioTrack( mStreamType, sampleRate, format, channelMask, frameCount, flags, NULL, // callback NULL, // user data 0, // notification frames mSessionId, AudioTrack::TRANSFER_DEFAULT, NULL, // offload info mUid, mPid, mAttributes, doNotReconnect, targetSpeed, mSelectedDeviceId); } if ((t == 0) || (t->initCheck() != NO_ERROR)) { ALOGE("Unable to create audio track"); delete newcbd; // t goes out of scope, so reference count drops to zero return NO_INIT; } else { // successful AudioTrack initialization implies a legacy stream type was generated // from the audio attributes mStreamType = t->streamType(); } CHECK((t != NULL) && ((mCallback == NULL) || (newcbd != NULL))); mCallbackData = newcbd; ALOGV("setVolume"); t->setVolume(mLeftVolume, mRightVolume); mSampleRateHz = sampleRate; mFlags = flags; mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate); mFrameSize = t->frameSize(); mTrack = t; return updateTrack_l(); } status_t MediaPlayer2AudioOutput::updateTrack_l() { if (mTrack == NULL) { return NO_ERROR; } status_t res = NO_ERROR; // Note some output devices may give us a direct track even though we don't specify it. // Example: Line application b/17459982. if ((mTrack->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) { res = mTrack->setPlaybackRate(mPlaybackRate); if (res == NO_ERROR) { mTrack->setAuxEffectSendLevel(mSendLevel); res = mTrack->attachAuxEffect(mAuxEffectId); } } mTrack->setOutputDevice(mSelectedDeviceId); if (mDeviceCallbackEnabled) { mTrack->addAudioDeviceCallback(mDeviceCallback.promote()); } ALOGV("updateTrack_l() DONE status %d", res); return res; } status_t MediaPlayer2AudioOutput::start() { ALOGV("start"); Mutex::Autolock lock(mLock); if (mCallbackData != NULL) { mCallbackData->endTrackSwitch(); } if (mTrack != 0) { mTrack->setVolume(mLeftVolume, mRightVolume); mTrack->setAuxEffectSendLevel(mSendLevel); status_t status = mTrack->start(); return status; } return NO_INIT; } ssize_t MediaPlayer2AudioOutput::write(const void* buffer, size_t size, bool blocking) { Mutex::Autolock lock(mLock); LOG_ALWAYS_FATAL_IF(mCallback != NULL, "Don't call write if supplying a callback."); //ALOGV("write(%p, %u)", buffer, size); if (mTrack != 0) { return mTrack->write(buffer, size, blocking); } return NO_INIT; } void MediaPlayer2AudioOutput::stop() { ALOGV("stop"); Mutex::Autolock lock(mLock); if (mTrack != 0) { mTrack->stop(); } } void MediaPlayer2AudioOutput::flush() { ALOGV("flush"); Mutex::Autolock lock(mLock); if (mTrack != 0) { mTrack->flush(); } } void MediaPlayer2AudioOutput::pause() { ALOGV("pause"); Mutex::Autolock lock(mLock); if (mTrack != 0) { mTrack->pause(); } } void MediaPlayer2AudioOutput::close() { ALOGV("close"); sp<AudioTrack> track; { Mutex::Autolock lock(mLock); track = mTrack; close_l(); // clears mTrack } // destruction of the track occurs outside of mutex. } void MediaPlayer2AudioOutput::setVolume(float left, float right) { ALOGV("setVolume(%f, %f)", left, right); Mutex::Autolock lock(mLock); mLeftVolume = left; mRightVolume = right; if (mTrack != 0) { mTrack->setVolume(left, right); } } status_t MediaPlayer2AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate) { ALOGV("setPlaybackRate(%f %f %d %d)", rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode); Mutex::Autolock lock(mLock); if (mTrack == 0) { // remember rate so that we can set it when the track is opened mPlaybackRate = rate; return OK; } status_t res = mTrack->setPlaybackRate(rate); if (res != NO_ERROR) { return res; } // rate.mSpeed is always greater than 0 if setPlaybackRate succeeded CHECK_GT(rate.mSpeed, 0.f); mPlaybackRate = rate; if (mSampleRateHz != 0) { mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz); } return res; } status_t MediaPlayer2AudioOutput::getPlaybackRate(AudioPlaybackRate *rate) { ALOGV("setPlaybackRate"); Mutex::Autolock lock(mLock); if (mTrack == 0) { return NO_INIT; } *rate = mTrack->getPlaybackRate(); return NO_ERROR; } status_t MediaPlayer2AudioOutput::setAuxEffectSendLevel(float level) { ALOGV("setAuxEffectSendLevel(%f)", level); Mutex::Autolock lock(mLock); mSendLevel = level; if (mTrack != 0) { return mTrack->setAuxEffectSendLevel(level); } return NO_ERROR; } status_t MediaPlayer2AudioOutput::attachAuxEffect(int effectId) { ALOGV("attachAuxEffect(%d)", effectId); Mutex::Autolock lock(mLock); mAuxEffectId = effectId; if (mTrack != 0) { return mTrack->attachAuxEffect(effectId); } return NO_ERROR; } status_t MediaPlayer2AudioOutput::setOutputDevice(audio_port_handle_t deviceId) { ALOGV("setOutputDevice(%d)", deviceId); Mutex::Autolock lock(mLock); mSelectedDeviceId = deviceId; if (mTrack != 0) { return mTrack->setOutputDevice(deviceId); } return NO_ERROR; } status_t MediaPlayer2AudioOutput::getRoutedDeviceId(audio_port_handle_t* deviceId) { ALOGV("getRoutedDeviceId"); Mutex::Autolock lock(mLock); if (mTrack != 0) { mRoutedDeviceId = mTrack->getRoutedDeviceId(); } *deviceId = mRoutedDeviceId; return NO_ERROR; } status_t MediaPlayer2AudioOutput::enableAudioDeviceCallback(bool enabled) { ALOGV("enableAudioDeviceCallback, %d", enabled); Mutex::Autolock lock(mLock); mDeviceCallbackEnabled = enabled; if (mTrack != 0) { status_t status; if (enabled) { status = mTrack->addAudioDeviceCallback(mDeviceCallback.promote()); } else { status = mTrack->removeAudioDeviceCallback(mDeviceCallback.promote()); } return status; } return NO_ERROR; } // static void MediaPlayer2AudioOutput::CallbackWrapper( int event, void *cookie, void *info) { //ALOGV("callbackwrapper"); CallbackData *data = (CallbackData*)cookie; // lock to ensure we aren't caught in the middle of a track switch. data->lock(); MediaPlayer2AudioOutput *me = data->getOutput(); AudioTrack::Buffer *buffer = (AudioTrack::Buffer *)info; if (me == NULL) { // no output set, likely because the track was scheduled to be reused // by another player, but the format turned out to be incompatible. data->unlock(); if (buffer != NULL) { buffer->size = 0; } return; } switch(event) { case AudioTrack::EVENT_MORE_DATA: { size_t actualSize = (*me->mCallback)( me, buffer->raw, buffer->size, me->mCallbackCookie, CB_EVENT_FILL_BUFFER); // Log when no data is returned from the callback. // (1) We may have no data (especially with network streaming sources). // (2) We may have reached the EOS and the audio track is not stopped yet. // Note that AwesomePlayer/AudioPlayer will only return zero size when it reaches the EOS. // NuPlayer2Renderer will return zero when it doesn't have data (it doesn't block to fill). // // This is a benign busy-wait, with the next data request generated 10 ms or more later; // nevertheless for power reasons, we don't want to see too many of these. ALOGV_IF(actualSize == 0 && buffer->size > 0, "callbackwrapper: empty buffer returned"); buffer->size = actualSize; } break; case AudioTrack::EVENT_STREAM_END: // currently only occurs for offloaded callbacks ALOGV("callbackwrapper: deliver EVENT_STREAM_END"); (*me->mCallback)(me, NULL /* buffer */, 0 /* size */, me->mCallbackCookie, CB_EVENT_STREAM_END); break; case AudioTrack::EVENT_NEW_IAUDIOTRACK : ALOGV("callbackwrapper: deliver EVENT_TEAR_DOWN"); (*me->mCallback)(me, NULL /* buffer */, 0 /* size */, me->mCallbackCookie, CB_EVENT_TEAR_DOWN); break; case AudioTrack::EVENT_UNDERRUN: // This occurs when there is no data available, typically // when there is a failure to supply data to the AudioTrack. It can also // occur in non-offloaded mode when the audio device comes out of standby. // // If an AudioTrack underruns it outputs silence. Since this happens suddenly // it may sound like an audible pop or glitch. // // The underrun event is sent once per track underrun; the condition is reset // when more data is sent to the AudioTrack. ALOGD("callbackwrapper: EVENT_UNDERRUN (discarded)"); break; default: ALOGE("received unknown event type: %d inside CallbackWrapper !", event); } data->unlock(); } audio_session_t MediaPlayer2AudioOutput::getSessionId() const { Mutex::Autolock lock(mLock); return mSessionId; } uint32_t MediaPlayer2AudioOutput::getSampleRate() const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return 0; } return mTrack->getSampleRate(); } int64_t MediaPlayer2AudioOutput::getBufferDurationInUs() const { Mutex::Autolock lock(mLock); if (mTrack == 0) { return 0; } int64_t duration; if (mTrack->getBufferDurationInUs(&duration) != OK) { return 0; } return duration; } } // namespace android
32.953297
99
0.641517
yakuizhao
a8e2677a71bad7cf97c3dcd5ab12238ebcdaf3ab
33,487
cc
C++
zircon/system/ulib/paver/paver.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
zircon/system/ulib/paver/paver.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
zircon/system/ulib/paver/paver.cc
sysidos/fuchsia
0c00fd3c78a9c0111af4689f1e038b3926c4dc9b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "paver.h" #include <dirent.h> #include <fcntl.h> #include <lib/fdio/directory.h> #include <lib/fidl-async/cpp/bind.h> #include <lib/fidl/epitaph.h> #include <lib/fzl/vmo-mapper.h> #include <lib/zx/channel.h> #include <lib/zx/time.h> #include <lib/zx/vmo.h> #include <libgen.h> #include <stddef.h> #include <string.h> #include <zircon/device/block.h> #include <zircon/errors.h> #include <zircon/status.h> #include <zircon/syscalls.h> #include <memory> #include <utility> #include <fbl/algorithm.h> #include <fbl/alloc_checker.h> #include <fbl/span.h> #include <fbl/auto_call.h> #include <fbl/unique_fd.h> #include <fs-management/fvm.h> #include <fs-management/mount.h> #include <zxcrypt/fdio-volume.h> #include "fvm.h" #include "pave-logging.h" #include "stream-reader.h" #include "vmo-reader.h" #define ZXCRYPT_DRIVER_LIB "/boot/driver/zxcrypt.so" namespace paver { namespace { using ::llcpp::fuchsia::paver::Asset; using ::llcpp::fuchsia::paver::Configuration; // Get the architecture of the currently running platform. inline constexpr Arch GetCurrentArch() { #if defined(__x86_64__) return Arch::kX64; #elif defined(__aarch64__) return Arch::kArm64; #else #error "Unknown arch" #endif } Partition PartitionType(Configuration configuration, Asset asset) { switch (asset) { case Asset::KERNEL: { switch (configuration) { case Configuration::A: return Partition::kZirconA; case Configuration::B: return Partition::kZirconB; case Configuration::RECOVERY: return Partition::kZirconR; }; break; } case Asset::VERIFIED_BOOT_METADATA: { switch (configuration) { case Configuration::A: return Partition::kVbMetaA; case Configuration::B: return Partition::kVbMetaB; case Configuration::RECOVERY: return Partition::kVbMetaR; }; break; } }; return Partition::kUnknown; } // Best effort attempt to see if payload contents match what is already inside // of the partition. bool CheckIfSame(PartitionClient* partition, const zx::vmo& vmo, size_t payload_size, size_t block_size) { const size_t payload_size_aligned = fbl::round_up(payload_size, block_size); zx::vmo read_vmo; auto status = zx::vmo::create(fbl::round_up(payload_size_aligned, ZX_PAGE_SIZE), 0, &read_vmo); if (status != ZX_OK) { ERROR("Failed to create VMO: %s\n", zx_status_get_string(status)); return false; } if ((status = partition->Read(read_vmo, payload_size_aligned)) != ZX_OK) { return false; } fzl::VmoMapper first_mapper; fzl::VmoMapper second_mapper; status = first_mapper.Map(vmo, 0, 0, ZX_VM_PERM_READ); if (status != ZX_OK) { ERROR("Error mapping vmo: %s\n", zx_status_get_string(status)); return false; } status = second_mapper.Map(read_vmo, 0, 0, ZX_VM_PERM_READ); if (status != ZX_OK) { ERROR("Error mapping vmo: %s\n", zx_status_get_string(status)); return false; } return memcmp(first_mapper.start(), second_mapper.start(), payload_size) == 0; } #if 0 // Checks first few bytes of buffer to ensure it is a ZBI. // Also validates architecture in kernel header matches the target. bool ValidateKernelZbi(const uint8_t* buffer, size_t size, Arch arch) { const auto payload = reinterpret_cast<const zircon_kernel_t*>(buffer); const uint32_t expected_kernel = (arch == Arch::X64) ? ZBI_TYPE_KERNEL_X64 : ZBI_TYPE_KERNEL_ARM64; const auto crc_valid = [](const zbi_header_t* hdr) { const uint32_t crc = crc32(0, reinterpret_cast<const uint8_t*>(hdr + 1), hdr->length); return hdr->crc32 == crc; }; return size >= sizeof(zircon_kernel_t) && // Container header payload->hdr_file.type == ZBI_TYPE_CONTAINER && payload->hdr_file.extra == ZBI_CONTAINER_MAGIC && (payload->hdr_file.length - offsetof(zircon_kernel_t, hdr_kernel)) <= size && payload->hdr_file.magic == ZBI_ITEM_MAGIC && payload->hdr_file.flags == ZBI_FLAG_VERSION && payload->hdr_file.crc32 == ZBI_ITEM_NO_CRC32 && // Kernel header payload->hdr_kernel.type == expected_kernel && (payload->hdr_kernel.length - offsetof(zircon_kernel_t, data_kernel)) <= size && payload->hdr_kernel.magic == ZBI_ITEM_MAGIC && (payload->hdr_kernel.flags & ZBI_FLAG_VERSION) == ZBI_FLAG_VERSION && ((payload->hdr_kernel.flags & ZBI_FLAG_CRC32) ? crc_valid(&payload->hdr_kernel) : payload->hdr_kernel.crc32 == ZBI_ITEM_NO_CRC32); } // Parses a partition and validates that it matches the expected format. zx_status_t ValidateKernelPayload(const fzl::ResizeableVmoMapper& mapper, size_t vmo_size, Partition partition_type, Arch arch) { // TODO(surajmalhotra): Re-enable this as soon as we have a good way to // determine whether the payload is signed or not. (Might require bootserver // changes). if (false) { const auto* buffer = reinterpret_cast<uint8_t*>(mapper.start()); switch (partition_type) { case Partition::kZirconA: case Partition::kZirconB: case Partition::kZirconR: if (!ValidateKernelZbi(buffer, vmo_size, arch)) { ERROR("Invalid ZBI payload!"); return ZX_ERR_BAD_STATE; } break; default: // TODO(surajmalhotra): Validate non-zbi payloads as well. LOG("Skipping validation as payload is not a ZBI\n"); break; } } return ZX_OK; } #endif // Returns a client for the FVM partition. If the FVM volume doesn't exist, a new // volume will be created, without any associated children partitions. zx_status_t GetFvmPartition(const DevicePartitioner& partitioner, std::unique_ptr<PartitionClient>* client) { constexpr Partition partition = Partition::kFuchsiaVolumeManager; zx_status_t status = partitioner.FindPartition(partition, client); if (status != ZX_OK) { if (status != ZX_ERR_NOT_FOUND) { ERROR("Failure looking for FVM partition: %s\n", zx_status_get_string(status)); return status; } LOG("Could not find FVM Partition on device. Attemping to add new partition\n"); if ((status = partitioner.AddPartition(partition, client)) != ZX_OK) { ERROR("Failure creating FVM partition: %s\n", zx_status_get_string(status)); return status; } } else { LOG("FVM Partition already exists\n"); } return ZX_OK; } zx_status_t FvmPave(const fbl::unique_fd& devfs_root, const DevicePartitioner& partitioner, std::unique_ptr<fvm::ReaderInterface> payload) { LOG("Paving FVM partition.\n"); std::unique_ptr<PartitionClient> partition; zx_status_t status = GetFvmPartition(partitioner, &partition); if (status != ZX_OK) { return status; } if (partitioner.IsFvmWithinFtl()) { LOG("Attempting to format FTL...\n"); status = partitioner.WipeFvm(); if (status != ZX_OK) { ERROR("Failed to format FTL: %s\n", zx_status_get_string(status)); } else { LOG("Formatted partition successfully!\n"); } } LOG("Streaming partitions to FVM...\n"); status = FvmStreamPartitions(devfs_root, std::move(partition), std::move(payload)); if (status != ZX_OK) { ERROR("Failed to stream partitions to FVM: %s\n", zx_status_get_string(status)); return status; } LOG("Completed FVM paving successfully\n"); return ZX_OK; } // Formats the FVM partition and returns a channel to the new volume. zx_status_t FormatFvm(const fbl::unique_fd& devfs_root, const DevicePartitioner& partitioner, zx::channel* channel) { std::unique_ptr<PartitionClient> partition; zx_status_t status = GetFvmPartition(partitioner, &partition); if (status != ZX_OK) { return status; } // TODO(39753): Configuration values should come from the build or environment. fvm::sparse_image_t header = {}; header.slice_size = 1 << 20; fbl::unique_fd fvm_fd( FvmPartitionFormat(devfs_root, partition->block_fd(), header, BindOption::Reformat)); if (!fvm_fd) { ERROR("Couldn't format FVM partition\n"); return ZX_ERR_IO; } status = AllocateEmptyPartitions(devfs_root, fvm_fd); if (status != ZX_OK) { ERROR("Couldn't allocate empty partitions\n"); return status; } status = fdio_get_service_handle(fvm_fd.release(), channel->reset_and_get_address()); if (status != ZX_OK) { ERROR("Couldn't get fvm handle\n"); return ZX_ERR_IO; } return ZX_OK; } // Reads an image from disk into a vmo. zx_status_t PartitionRead(const DevicePartitioner& partitioner, Partition partition_type, zx::vmo* out_vmo, size_t* out_vmo_size) { LOG("Reading partition \"%s\".\n", PartitionName(partition_type)); std::unique_ptr<PartitionClient> partition; if (zx_status_t status = partitioner.FindPartition(partition_type, &partition); status != ZX_OK) { ERROR("Could not find \"%s\" Partition on device: %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } uint64_t partition_size; if (zx_status_t status = partition->GetPartitionSize(&partition_size); status != ZX_OK) { ERROR("Error getting partition \"%s\" size: %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } zx::vmo vmo; if (zx_status_t status = zx::vmo::create(fbl::round_up(partition_size, ZX_PAGE_SIZE), 0, &vmo); status != ZX_OK) { ERROR("Error creating vmo for \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } if (zx_status_t status = partition->Read(vmo, static_cast<size_t>(partition_size)); status != ZX_OK) { ERROR("Error writing partition data for \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } *out_vmo = std::move(vmo); *out_vmo_size = static_cast<size_t>(partition_size); LOG("Completed successfully\n"); return ZX_OK; } zx_status_t ValidatePartitionPayload(const DevicePartitioner& partitioner, const zx::vmo& payload_vmo, size_t payload_size, Partition partition_type) { fzl::VmoMapper payload_mapper; zx_status_t status = payload_mapper.Map(payload_vmo, 0, 0, ZX_VM_PERM_READ); if (status != ZX_OK) { ERROR("Could not map payload into memory: %s\n", zx_status_get_string(status)); return status; } ZX_ASSERT(payload_mapper.size() >= payload_size); auto payload = fbl::Span<const uint8_t>(static_cast<const uint8_t*>(payload_mapper.start()), payload_size); return partitioner.ValidatePayload(partition_type, payload); } // Paves an image onto the disk. zx_status_t PartitionPave(const DevicePartitioner& partitioner, zx::vmo payload_vmo, size_t payload_size, Partition partition_type) { LOG("Paving partition \"%s\".\n", PartitionName(partition_type)); // Perform basic safety checking on the partition before we attempt to write it. zx_status_t status = ValidatePartitionPayload(partitioner, payload_vmo, payload_size, partition_type); if (status != ZX_OK) { ERROR("Failed to validate partition \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } // Find or create the appropriate partition. std::unique_ptr<PartitionClient> partition; if ((status = partitioner.FindPartition(partition_type, &partition)) != ZX_OK) { if (status != ZX_ERR_NOT_FOUND) { ERROR("Failure looking for partition \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } LOG("Could not find \"%s\" Partition on device. Attemping to add new partition\n", PartitionName(partition_type)); if ((status = partitioner.AddPartition(partition_type, &partition)) != ZX_OK) { ERROR("Failure creating partition \"%s\": %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } } else { LOG("Partition \"%s\" already exists\n", PartitionName(partition_type)); } size_t block_size_bytes; if ((status = partition->GetBlockSize(&block_size_bytes)) != ZX_OK) { ERROR("Couldn't get partition \"%s\" block size\n", PartitionName(partition_type)); return status; } if (CheckIfSame(partition.get(), payload_vmo, payload_size, block_size_bytes)) { LOG("Skipping write as partition \"%s\" contents match payload.\n", PartitionName(partition_type)); } else { // Pad payload with 0s to make it block size aligned. if (payload_size % block_size_bytes != 0) { const size_t remaining_bytes = block_size_bytes - (payload_size % block_size_bytes); size_t vmo_size; if ((status = payload_vmo.get_size(&vmo_size)) != ZX_OK) { ERROR("Couldn't get vmo size for \"%s\"\n", PartitionName(partition_type)); return status; } // Grow VMO if it's too small. if (vmo_size < payload_size + remaining_bytes) { const auto new_size = fbl::round_up(payload_size + remaining_bytes, ZX_PAGE_SIZE); status = payload_vmo.set_size(new_size); if (status != ZX_OK) { ERROR("Couldn't grow vmo for \"%s\"\n", PartitionName(partition_type)); return status; } } auto buffer = std::make_unique<uint8_t[]>(remaining_bytes); memset(buffer.get(), 0, remaining_bytes); status = payload_vmo.write(buffer.get(), payload_size, remaining_bytes); if (status != ZX_OK) { ERROR("Failed to write padding to vmo for \"%s\"\n", PartitionName(partition_type)); return status; } payload_size += remaining_bytes; } if ((status = partition->Write(payload_vmo, payload_size)) != ZX_OK) { ERROR("Error writing partition \"%s\" data: %s\n", PartitionName(partition_type), zx_status_get_string(status)); return status; } } if ((status = partitioner.FinalizePartition(partition_type)) != ZX_OK) { ERROR("Failed to finalize partition \"%s\"\n", PartitionName(partition_type)); return status; } LOG("Completed paving partition \"%s\" successfully\n", PartitionName(partition_type)); return ZX_OK; } zx::channel OpenServiceRoot() { zx::channel request, service_root; if (zx::channel::create(0, &request, &service_root) != ZX_OK) { return zx::channel(); } if (fdio_service_connect("/svc/.", request.release()) != ZX_OK) { return zx::channel(); } return service_root; } bool IsBootable(const abr::SlotData& slot) { return slot.priority > 0 && (slot.tries_remaining > 0 || slot.successful_boot); } std::optional<Configuration> GetActiveConfiguration(const abr::Client& abr_client) { const bool config_a_bootable = IsBootable(abr_client.Data().slots[0]); const bool config_b_bootable = IsBootable(abr_client.Data().slots[1]); const uint8_t config_a_priority = abr_client.Data().slots[0].priority; const uint8_t config_b_priority = abr_client.Data().slots[1].priority; // A wins on ties. if (config_a_bootable && (config_a_priority >= config_b_priority || !config_b_bootable)) { return Configuration::A; } else if (config_b_bootable) { return Configuration::B; } else { return std::nullopt; } } } // namespace void Paver::FindDataSink(zx::channel data_sink, FindDataSinkCompleter::Sync _completer) { // Use global devfs if one wasn't injected via set_devfs_root. if (!devfs_root_) { devfs_root_ = fbl::unique_fd(open("/dev", O_RDONLY)); } if (!svc_root_) { svc_root_ = OpenServiceRoot(); } DataSink::Bind(dispatcher_, devfs_root_.duplicate(), std::move(svc_root_), std::move(data_sink)); } void Paver::UseBlockDevice(zx::channel block_device, zx::channel dynamic_data_sink, UseBlockDeviceCompleter::Sync _completer) { // Use global devfs if one wasn't injected via set_devfs_root. if (!devfs_root_) { devfs_root_ = fbl::unique_fd(open("/dev", O_RDONLY)); } if (!svc_root_) { svc_root_ = OpenServiceRoot(); } DynamicDataSink::Bind(dispatcher_, devfs_root_.duplicate(), std::move(svc_root_), std::move(block_device), std::move(dynamic_data_sink)); } void Paver::FindBootManager(zx::channel boot_manager, bool initialize, FindBootManagerCompleter::Sync _completer) { // Use global devfs if one wasn't injected via set_devfs_root. if (!devfs_root_) { devfs_root_ = fbl::unique_fd(open("/dev", O_RDONLY)); } if (!svc_root_) { svc_root_ = OpenServiceRoot(); } BootManager::Bind(dispatcher_, devfs_root_.duplicate(), std::move(svc_root_), std::move(boot_manager), initialize); } void DataSink::ReadAsset(::llcpp::fuchsia::paver::Configuration configuration, ::llcpp::fuchsia::paver::Asset asset, ReadAssetCompleter::Sync completer) { ::llcpp::fuchsia::mem::Buffer buf; zx_status_t status = sink_.ReadAsset(configuration, asset, &buf); if (status == ZX_OK) { completer.ReplySuccess(std::move(buf)); } else { completer.ReplyError(status); } } void DataSink::WipeVolume(WipeVolumeCompleter::Sync completer) { zx::channel out; zx_status_t status = sink_.WipeVolume(&out); if (status == ZX_OK) { completer.ReplySuccess(std::move(out)); } else { completer.ReplyError(status); } } zx_status_t DataSinkImpl::ReadAsset(Configuration configuration, Asset asset, ::llcpp::fuchsia::mem::Buffer* buf) { return PartitionRead(*partitioner_, PartitionType(configuration, asset), &buf->vmo, &buf->size); } zx_status_t DataSinkImpl::WriteAsset(Configuration configuration, Asset asset, ::llcpp::fuchsia::mem::Buffer payload) { return PartitionPave(*partitioner_, std::move(payload.vmo), payload.size, PartitionType(configuration, asset)); } zx_status_t DataSinkImpl::WriteVolumes(zx::channel payload_stream) { std::unique_ptr<StreamReader> reader; zx_status_t status = StreamReader::Create(std::move(payload_stream), &reader); if (status != ZX_OK) { ERROR("Unable to create stream.\n"); return status; } return FvmPave(devfs_root_, *partitioner_, std::move(reader)); } zx_status_t DataSinkImpl::WriteBootloader(::llcpp::fuchsia::mem::Buffer payload) { return PartitionPave(*partitioner_, std::move(payload.vmo), payload.size, Partition::kBootloader); } zx_status_t DataSinkImpl::WriteDataFile(fidl::StringView filename, ::llcpp::fuchsia::mem::Buffer payload) { const char* mount_path = "/volume/data"; const uint8_t data_guid[] = GUID_DATA_VALUE; char minfs_path[PATH_MAX] = {0}; char path[PATH_MAX] = {0}; zx_status_t status = ZX_OK; fbl::unique_fd part_fd( open_partition_with_devfs(devfs_root_.get(), nullptr, data_guid, ZX_SEC(1), path)); if (!part_fd) { ERROR("DATA partition not found in FVM\n"); return ZX_ERR_NOT_FOUND; } auto disk_format = detect_disk_format(part_fd.get()); fbl::unique_fd mountpoint_dev_fd; // By the end of this switch statement, mountpoint_dev_fd needs to be an // open handle to the block device that we want to mount at mount_path. switch (disk_format) { case DISK_FORMAT_MINFS: // If the disk we found is actually minfs, we can just use the block // device path we were given by open_partition. strncpy(minfs_path, path, PATH_MAX); mountpoint_dev_fd.reset(open(minfs_path, O_RDWR)); break; case DISK_FORMAT_ZXCRYPT: { std::unique_ptr<zxcrypt::FdioVolume> zxc_volume; uint8_t slot = 0; if ((status = zxcrypt::FdioVolume::UnlockWithDeviceKey( std::move(part_fd), devfs_root_.duplicate(), static_cast<zxcrypt::key_slot_t>(slot), &zxc_volume)) != ZX_OK) { ERROR("Couldn't unlock zxcrypt volume: %s\n", zx_status_get_string(status)); return status; } // Most of the time we'll expect the volume to actually already be // unsealed, because we created it and unsealed it moments ago to // format minfs. if ((status = zxc_volume->Open(zx::sec(0), &mountpoint_dev_fd)) == ZX_OK) { // Already unsealed, great, early exit. break; } // Ensure zxcrypt volume manager is bound. zx::channel zxc_manager_chan; if ((status = zxc_volume->OpenManager(zx::sec(5), zxc_manager_chan.reset_and_get_address())) != ZX_OK) { ERROR("Couldn't open zxcrypt volume manager: %s\n", zx_status_get_string(status)); return status; } // Unseal. zxcrypt::FdioVolumeManager zxc_manager(std::move(zxc_manager_chan)); if ((status = zxc_manager.UnsealWithDeviceKey(slot)) != ZX_OK) { ERROR("Couldn't unseal zxcrypt volume: %s\n", zx_status_get_string(status)); return status; } // Wait for the device to appear, and open it. if ((status = zxc_volume->Open(zx::sec(5), &mountpoint_dev_fd)) != ZX_OK) { ERROR("Couldn't open block device atop unsealed zxcrypt volume: %s\n", zx_status_get_string(status)); return status; } } break; default: ERROR("unsupported disk format at %s\n", path); return ZX_ERR_NOT_SUPPORTED; } mount_options_t opts(default_mount_options); opts.create_mountpoint = true; if ((status = mount(mountpoint_dev_fd.get(), mount_path, DISK_FORMAT_MINFS, &opts, launch_logs_async)) != ZX_OK) { ERROR("mount error: %s\n", zx_status_get_string(status)); return status; } int filename_size = static_cast<int>(filename.size()); // mkdir any intermediate directories between mount_path and basename(filename). snprintf(path, sizeof(path), "%s/%.*s", mount_path, filename_size, filename.data()); size_t cur = strlen(mount_path); size_t max = strlen(path) - strlen(basename(path)); // note: the call to basename above modifies path, so it needs reconstruction. snprintf(path, sizeof(path), "%s/%.*s", mount_path, filename_size, filename.data()); while (cur < max) { ++cur; if (path[cur] == '/') { path[cur] = 0; // errors ignored, let the open() handle that later. mkdir(path, 0700); path[cur] = '/'; } } // We append here, because the primary use case here is to send SSH keys // which can be appended, but we may want to revisit this choice for other // files in the future. { uint8_t buf[8192]; fbl::unique_fd kfd(open(path, O_CREAT | O_WRONLY | O_APPEND, 0600)); if (!kfd) { umount(mount_path); ERROR("open %.*s error: %s\n", filename_size, filename.data(), strerror(errno)); return ZX_ERR_IO; } VmoReader reader(std::move(payload)); size_t actual; while ((status = reader.Read(buf, sizeof(buf), &actual)) == ZX_OK && actual > 0) { if (write(kfd.get(), buf, actual) != static_cast<ssize_t>(actual)) { umount(mount_path); ERROR("write %.*s error: %s\n", filename_size, filename.data(), strerror(errno)); return ZX_ERR_IO; } } fsync(kfd.get()); } if ((status = umount(mount_path)) != ZX_OK) { ERROR("unmount %s failed: %s\n", mount_path, zx_status_get_string(status)); return status; } LOG("Wrote %.*s\n", filename_size, filename.data()); return ZX_OK; } zx_status_t DataSinkImpl::WipeVolume(zx::channel* out) { std::unique_ptr<PartitionClient> partition; zx_status_t status = GetFvmPartition(*partitioner_, &partition); if (status != ZX_OK) { return status; } // Bind the FVM driver to be in a well known state regarding races with block watcher. // The block watcher will attempt to bind the FVM driver automatically based on // the contents of the partition. However, that operation is not synchronized in // any way with this service so the driver can be loaded at any time. // WipeFvm basically writes underneath that driver, which means that we should // eliminate the races at this point: assuming that the driver can load, either // this call or the block watcher will succeed (and the other one will fail), // but the driver will be loaded before moving on. TryBindToFvmDriver(devfs_root_, partition->block_fd(), zx::sec(3)); status = partitioner_->WipeFvm(); if (status != ZX_OK) { ERROR("Failure wiping partition: %s\n", zx_status_get_string(status)); return status; } zx::channel channel; status = FormatFvm(devfs_root_, *partitioner_, &channel); if (status != ZX_OK) { ERROR("Failure formatting partition: %s\n", zx_status_get_string(status)); return status; } *out = std::move(channel); return ZX_OK; } void DataSink::Bind(async_dispatcher_t* dispatcher, fbl::unique_fd devfs_root, zx::channel svc_root, zx::channel server) { auto partitioner = DevicePartitioner::Create(devfs_root.duplicate(), std::move(svc_root), GetCurrentArch()); if (!partitioner) { ERROR("Unable to initialize a partitioner.\n"); fidl_epitaph_write(server.get(), ZX_ERR_BAD_STATE); return; } auto data_sink = std::make_unique<DataSink>(std::move(devfs_root), std::move(partitioner)); fidl::Bind(dispatcher, std::move(server), std::move(data_sink)); } void DynamicDataSink::Bind(async_dispatcher_t* dispatcher, fbl::unique_fd devfs_root, zx::channel svc_root, zx::channel block_device, zx::channel server) { auto partitioner = DevicePartitioner::Create(devfs_root.duplicate(), std::move(svc_root), GetCurrentArch(), std::move(block_device)); if (!partitioner) { ERROR("Unable to initialize a partitioner.\n"); fidl_epitaph_write(server.get(), ZX_ERR_BAD_STATE); return; } auto data_sink = std::make_unique<DynamicDataSink>(std::move(devfs_root), std::move(partitioner)); fidl::Bind(dispatcher, std::move(server), std::move(data_sink)); } void DynamicDataSink::InitializePartitionTables( InitializePartitionTablesCompleter::Sync completer) { completer.Reply(sink_.partitioner()->InitPartitionTables()); } void DynamicDataSink::WipePartitionTables(WipePartitionTablesCompleter::Sync completer) { completer.Reply(sink_.partitioner()->WipePartitionTables()); } void DynamicDataSink::ReadAsset(::llcpp::fuchsia::paver::Configuration configuration, ::llcpp::fuchsia::paver::Asset asset, ReadAssetCompleter::Sync completer) { ::llcpp::fuchsia::mem::Buffer buf; auto status = sink_.ReadAsset(configuration, asset, &buf); if (status == ZX_OK) { completer.ReplySuccess(std::move(buf)); } else { completer.ReplyError(status); } } void DynamicDataSink::WipeVolume(WipeVolumeCompleter::Sync completer) { zx::channel out; zx_status_t status = sink_.WipeVolume(&out); if (status == ZX_OK) { completer.ReplySuccess(std::move(out)); } else { completer.ReplyError(status); } } void BootManager::Bind(async_dispatcher_t* dispatcher, fbl::unique_fd devfs_root, zx::channel svc_root, zx::channel server, bool initialize) { std::unique_ptr<abr::Client> abr_client; if (zx_status_t status = abr::Client::Create(std::move(devfs_root), std::move(svc_root), &abr_client); status != ZX_OK) { ERROR("Failed to get ABR client: %s\n", zx_status_get_string(status)); fidl_epitaph_write(server.get(), status); return; } const bool valid = abr_client->IsValid(); if (!valid && initialize) { abr::Data data = abr_client->Data(); memset(&data, 0, sizeof(data)); memcpy(data.magic, abr::kMagic, sizeof(abr::kMagic)); data.version_major = abr::kMajorVersion; data.version_minor = abr::kMinorVersion; if (zx_status_t status = abr_client->Persist(data); status != ZX_OK) { ERROR("Unabled to persist ABR metadata %s\n", zx_status_get_string(status)); fidl_epitaph_write(server.get(), status); return; } ZX_DEBUG_ASSERT(abr_client->IsValid()); } else if (!valid) { ERROR("ABR metadata is not valid!\n"); fidl_epitaph_write(server.get(), ZX_ERR_NOT_SUPPORTED); return; } auto boot_manager = std::make_unique<BootManager>(std::move(abr_client)); fidl::Bind(dispatcher, std::move(server), std::move(boot_manager)); } void BootManager::QueryActiveConfiguration(QueryActiveConfigurationCompleter::Sync completer) { std::optional<Configuration> config = GetActiveConfiguration(*abr_client_); if (!config) { completer.ReplyError(ZX_ERR_NOT_SUPPORTED); return; } completer.ReplySuccess(config.value()); } void BootManager::QueryConfigurationStatus(Configuration configuration, QueryConfigurationStatusCompleter::Sync completer) { const abr::SlotData* slot; switch (configuration) { case Configuration::A: slot = &abr_client_->Data().slots[0]; break; case Configuration::B: slot = &abr_client_->Data().slots[1]; break; default: ERROR("Unexpected configuration: %d\n", static_cast<uint32_t>(configuration)); completer.ReplyError(ZX_ERR_INVALID_ARGS); return; } if (!IsBootable(*slot)) { completer.ReplySuccess(::llcpp::fuchsia::paver::ConfigurationStatus::UNBOOTABLE); } else if (slot->successful_boot == 0) { completer.ReplySuccess(::llcpp::fuchsia::paver::ConfigurationStatus::PENDING); } else { completer.ReplySuccess(::llcpp::fuchsia::paver::ConfigurationStatus::HEALTHY); } } void BootManager::SetConfigurationActive(Configuration configuration, SetConfigurationActiveCompleter::Sync completer) { LOG("Setting configuration %d as active\n", static_cast<uint32_t>(configuration)); abr::Data data = abr_client_->Data(); abr::SlotData *primary, *secondary; switch (configuration) { case Configuration::A: primary = &data.slots[0]; secondary = &data.slots[1]; break; case Configuration::B: primary = &data.slots[1]; secondary = &data.slots[0]; break; default: ERROR("Unexpected configuration: %d\n", static_cast<uint32_t>(configuration)); completer.Reply(ZX_ERR_INVALID_ARGS); return; } if (secondary->priority >= abr::kMaxPriority) { // 0 means unbootable, so we reset down to 1 to indicate lowest priority. secondary->priority = 1; } primary->successful_boot = 0; primary->tries_remaining = abr::kMaxTriesRemaining; primary->priority = static_cast<uint8_t>(secondary->priority + 1); if (zx_status_t status = abr_client_->Persist(data); status != ZX_OK) { ERROR("Unabled to persist ABR metadata %s\n", zx_status_get_string(status)); completer.Reply(status); return; } LOG("Set active configuration to %d\n", static_cast<uint32_t>(configuration)); completer.Reply(ZX_OK); } void BootManager::SetConfigurationUnbootable(Configuration configuration, SetConfigurationUnbootableCompleter::Sync completer) { LOG("Setting configuration %d as unbootable\n", static_cast<uint32_t>(configuration)); auto data = abr_client_->Data(); abr::SlotData* slot; switch (configuration) { case Configuration::A: slot = &data.slots[0]; break; case Configuration::B: slot = &data.slots[1]; break; default: ERROR("Unexpected configuration: %d\n", static_cast<uint32_t>(configuration)); completer.Reply(ZX_ERR_INVALID_ARGS); return; } slot->successful_boot = 0; slot->tries_remaining = 0; slot->priority = 0; if (zx_status_t status = abr_client_->Persist(data); status != ZX_OK) { ERROR("Unabled to persist ABR metadata %s\n", zx_status_get_string(status)); completer.Reply(status); return; } LOG("Set %d configuration as unbootable\n", static_cast<uint32_t>(configuration)); completer.Reply(ZX_OK); } void BootManager::SetActiveConfigurationHealthy( SetActiveConfigurationHealthyCompleter::Sync completer) { LOG("Setting active configuration as healthy\n"); abr::Data data = abr_client_->Data(); std::optional<Configuration> config = GetActiveConfiguration(*abr_client_); if (!config) { ERROR("No configuration bootable. Cannot mark as successful boot.\n"); completer.Reply(ZX_ERR_BAD_STATE); return; } abr::SlotData* slot; switch (*config) { case Configuration::A: slot = &data.slots[0]; break; case Configuration::B: slot = &data.slots[1]; break; default: // We've previously validated active is A or B. ZX_ASSERT(false); } slot->tries_remaining = 0; slot->successful_boot = 1; if (zx_status_t status = abr_client_->Persist(data); status != ZX_OK) { ERROR("Unabled to persist ABR metadata %s\n", zx_status_get_string(status)); completer.Reply(status); return; } LOG("Set active configuration as healthy\n"); completer.Reply(ZX_OK); } } // namespace paver
35.776709
100
0.672858
sysidos
a8e89b3a2181f913f0b8d6d9fb35d04715d32ed0
1,447
cxx
C++
src/mlio/data_type.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
null
null
null
src/mlio/data_type.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
2
2020-04-08T01:37:44.000Z
2020-04-14T20:14:07.000Z
src/mlio/data_type.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 "mlio/data_type.h" #include "mlio/parser.h" #include "mlio/util/number.h" namespace mlio { inline namespace v1 { data_type infer_data_type(std::string_view s) noexcept { if (s.empty()) { return data_type::string; } std::int64_t sint64_val{}; parse_result r = try_parse_int<std::int64_t>(s, sint64_val); if (r == parse_result::ok) { return data_type::sint64; } if (r == parse_result::overflowed) { std::uint64_t uint64_val{}; r = try_parse_int<std::uint64_t>(s, uint64_val); if (r == parse_result::ok) { return data_type::uint64; } } double double_val{}; r = try_parse_float<double>(s, double_val); if (r == parse_result::ok) { return data_type::float64; } return data_type::string; } } // namespace v1 } // namespace mlio
25.839286
74
0.656531
rizwangilani
a8efb1646c1d2d5bf11a8a4516d5fbe95fc08062
445
cpp
C++
wliotproxy-src-base/libVDIL/src/core/StopBlock.cpp
ooolms/wl_iot_framework
77f5d577105d505fd1c5a21940f29b72eb3391ea
[ "Apache-2.0" ]
null
null
null
wliotproxy-src-base/libVDIL/src/core/StopBlock.cpp
ooolms/wl_iot_framework
77f5d577105d505fd1c5a21940f29b72eb3391ea
[ "Apache-2.0" ]
null
null
null
wliotproxy-src-base/libVDIL/src/core/StopBlock.cpp
ooolms/wl_iot_framework
77f5d577105d505fd1c5a21940f29b72eb3391ea
[ "Apache-2.0" ]
null
null
null
#include "VDIL/core/StopBlock.h" #include "VDIL/core/Program.h" using namespace WLIOTVDIL; const QString StopBlock::mBlockName="stop"; StopBlock::StopBlock(quint32 blockId) :BaseBlock(blockId) { } QString StopBlock::groupName()const { return Program::reservedCoreGroupName; } QString StopBlock::blockName()const { return mBlockName; } void StopBlock::evalInternal() { if(engineCallbacks()) engineCallbacks()->programStopRequest(); }
15.892857
43
0.761798
ooolms
a8efc9758eab0c4b43bb0207d8cc213a4241e5e6
1,171
hh
C++
tests/using_class/bind.using_class.hh
LLNL/bindee
3df620803ef5b198a32732341e52971342493863
[ "MIT" ]
5
2020-02-19T08:10:46.000Z
2021-02-03T01:28:34.000Z
tests/using_class/bind.using_class.hh
LLNL/bindee
3df620803ef5b198a32732341e52971342493863
[ "MIT" ]
null
null
null
tests/using_class/bind.using_class.hh
LLNL/bindee
3df620803ef5b198a32732341e52971342493863
[ "MIT" ]
null
null
null
// Generated by bindee 2.1.2 from using_class.hh. #ifndef BIND_USING_CLASS_HH #define BIND_USING_CLASS_HH #include <pybind11/pybind11.h> @INCLUDES@ // Records. template <typename Target> void bind_LongName(Target &target); template <typename Target> void bind_Name(Target &target); // Bind functions. template <typename Target> void bind_LongName(Target &target) { namespace py = pybind11; using Class = LongName; std::string className = "LongName"; std::string docString = @DOC_STRING@; py::class_<Class> bindee(target, className.c_str(), docString.c_str()); } template <typename Target> void bind_Name(Target &target) { namespace py = pybind11; using Class = Name; std::string className = "Name"; std::string docString = @DOC_STRING@; py::class_<Class> bindee(target, className.c_str(), docString.c_str()); bindee.def("foo", (LongName & (Class::*)(const LongName *)) &Class::foo, @RETURN_VALUE_POLICY@); bindee.def("funcName", (const Class (Class::*)(Class &)) &Class::funcName); bindee.def("NameName", (Class * (Class::*)(Class)) &Class::NameName, @RETURN_VALUE_POLICY@); } #endif // BIND_USING_CLASS_HH
26.613636
100
0.698548
LLNL
a8f02d009d4a1e7002ae1c6d7d0c5b6936f5146a
2,908
cpp
C++
Source/Hamakaze/idrv/gmer.cpp
mfkiwl/KDU
b33b2338606ebef4c9cbeef5b2fcbc2052f6bfb8
[ "MIT" ]
null
null
null
Source/Hamakaze/idrv/gmer.cpp
mfkiwl/KDU
b33b2338606ebef4c9cbeef5b2fcbc2052f6bfb8
[ "MIT" ]
null
null
null
Source/Hamakaze/idrv/gmer.cpp
mfkiwl/KDU
b33b2338606ebef4c9cbeef5b2fcbc2052f6bfb8
[ "MIT" ]
null
null
null
/******************************************************************************* * * (C) COPYRIGHT AUTHORS, 2022 * * TITLE: GMER.CPP * * VERSION: 1.12 * * DATE: 25 Jan 2022 * * GMER driver routines. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. * *******************************************************************************/ #include "global.h" #include "idrv/gmer.h" /* * GmerRegisterDriver * * Purpose: * * Driver initialization routine. * */ BOOL WINAPI GmerRegisterDriver( _In_ HANDLE DeviceHandle, _In_opt_ PVOID Param) { UNREFERENCED_PARAMETER(Param); BOOL bResult; ULONG ulRegistration = 0; bResult = supCallDriver(DeviceHandle, IOCTL_GMER_REGISTER_CLIENT, &ulRegistration, sizeof(ULONG), &ulRegistration, sizeof(ULONG)); return bResult && (ulRegistration == 1); } /* * GmerReadVirtualMemory * * Purpose: * * Read virtual memory via Gmer. * */ _Success_(return != FALSE) BOOL WINAPI GmerReadVirtualMemory( _In_ HANDLE DeviceHandle, _In_ ULONG_PTR VirtualAddress, _In_reads_bytes_(NumberOfBytes) PVOID Buffer, _In_ ULONG NumberOfBytes) { GMER_READ_REQUEST request; request.VirtualAddress = VirtualAddress; return supCallDriver(DeviceHandle, IOCTL_GMER_READVM, &request, sizeof(GMER_READ_REQUEST), Buffer, NumberOfBytes); } /* * GmerWriteVirtualMemory * * Purpose: * * Write virtual memory via Gmer. * */ _Success_(return != FALSE) BOOL WINAPI GmerWriteVirtualMemory( _In_ HANDLE DeviceHandle, _In_ ULONG_PTR VirtualAddress, _In_reads_bytes_(NumberOfBytes) PVOID Buffer, _In_ ULONG NumberOfBytes) { BOOL bResult = FALSE; SIZE_T size; ULONG value; DWORD dwError = ERROR_SUCCESS; GMER_WRITE_REQUEST* pRequest; value = FIELD_OFFSET(GMER_WRITE_REQUEST, Data) + NumberOfBytes; size = ALIGN_UP_BY(value, PAGE_SIZE); pRequest = (GMER_WRITE_REQUEST*)VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (pRequest) { if (VirtualLock(pRequest, size)) { pRequest->Unused = 0; pRequest->VirtualAddress = VirtualAddress; pRequest->DataSize = NumberOfBytes; RtlCopyMemory(&pRequest->Data, Buffer, NumberOfBytes); bResult = supCallDriver(DeviceHandle, IOCTL_GMER_WRITEVM, pRequest, (ULONG)size, NULL, 0); if (!bResult) dwError = GetLastError(); VirtualUnlock(pRequest, size); } VirtualFree(pRequest, 0, MEM_RELEASE); } SetLastError(dwError); return bResult; }
21.540741
80
0.611761
mfkiwl
a8f1206a684e311f8692318e04eeeb0f28c73f4a
173
hpp
C++
src/intersim/booksim_config.hpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
src/intersim/booksim_config.hpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
src/intersim/booksim_config.hpp
beneslami/Multi-GPU
89101177a29a0f238fa85671943f2f584e82a815
[ "Apache-2.0" ]
null
null
null
#ifndef _BOOKSIM_CONFIG_HPP_ #define _BOOKSIM_CONFIG_HPP_ #include "config_utils.hpp" class BookSimConfig : public Configuration { public: BookSimConfig( ); }; #endif
14.416667
44
0.780347
beneslami
a8f1450e8d56be831e3c0b8fa3c744f83dd959c6
24,470
cpp
C++
nGenEx/Window.cpp
RogerioY/starshatter-open
3a507e08b1d4e5970b27401a7e6517570d529400
[ "BSD-3-Clause" ]
null
null
null
nGenEx/Window.cpp
RogerioY/starshatter-open
3a507e08b1d4e5970b27401a7e6517570d529400
[ "BSD-3-Clause" ]
4
2019-09-05T22:22:57.000Z
2021-03-28T02:09:24.000Z
nGenEx/Window.cpp
RogerioY/starshatter-open
3a507e08b1d4e5970b27401a7e6517570d529400
[ "BSD-3-Clause" ]
null
null
null
/* Starshatter OpenSource Distribution Copyright (c) 1997-2004, Destroyer Studios LLC. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name "Destroyer Studios" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SUBSYSTEM: nGenEx.lib FILE: Window.cpp AUTHOR: John DiCamillo OVERVIEW ======== Window class */ #include "MemDebug.h" #include "Window.h" #include "Bitmap.h" #include "Color.h" #include "Fix.h" #include "Font.h" #include "Polygon.h" #include "Screen.h" #include "Video.h" #include "View.h" static VertexSet vset4(4); // +--------------------------------------------------------------------+ Window::Window(Screen* s, int ax, int ay, int aw, int ah) : screen(s), rect(ax, ay, aw, ah), shown(true), font(0) { } // +--------------------------------------------------------------------+ Window::~Window() { view_list.destroy(); } // +--------------------------------------------------------------------+ bool Window::AddView(View* v) { if (!v) return false; if (!view_list.contains(v)) view_list.append(v); return true; } bool Window::DelView(View* v) { if (!v) return false; return view_list.remove(v) == v; } void Window::MoveTo(const Rect& r) { if (rect.x == r.x && rect.y == r.y && rect.w == r.w && rect.h == r.h) return; rect = r; ListIter<View> v = view_list; while (++v) v->OnWindowMove(); } // +--------------------------------------------------------------------+ void Window::Paint() { ListIter<View> v = view_list; while (++v) v->Refresh(); } // +--------------------------------------------------------------------+ static inline void swap(int& a, int& b) { int tmp=a; a=b; b=tmp; } static inline void sort(int& a, int& b) { if (a>b) swap(a,b); } static inline void swap(double& a, double& b) { double tmp=a; a=b; b=tmp; } static inline void sort(double& a, double& b) { if (a>b) swap(a,b); } Rect Window::ClipRect(const Rect& r) { Rect clip_rect = r; clip_rect.x += rect.x; clip_rect.y += rect.y; if (clip_rect.x < rect.x) { clip_rect.w -= rect.x - clip_rect.x; clip_rect.x = rect.x; } if (clip_rect.y < rect.y) { clip_rect.h -= rect.y - clip_rect.y; clip_rect.y = rect.y; } if (clip_rect.x + clip_rect.w > rect.x + rect.w) clip_rect.w = rect.x + rect.w - clip_rect.x; if (clip_rect.y + clip_rect.h > rect.y + rect.h) clip_rect.h = rect.y + rect.h - clip_rect.y; return clip_rect; } // +--------------------------------------------------------------------+ bool Window::ClipLine(int& x1, int& y1, int& x2, int& y2) { // vertical lines: if (x1==x2) { clip_vertical: sort(y1,y2); if (x1 < 0 || x1 >= rect.w) return false; if (y1 < 0) y1 = 0; if (y2 >= rect.h) y2 = rect.h; return true; } // horizontal lines: if (y1==y2) { clip_horizontal: sort(x1,x2); if (y1 < 0 || y1 >= rect.h) return false; if (x1 < 0) x1 = 0; if (x2 > rect.w) x2 = rect.w; return true; } // general lines: // sort left to right: if (x1 > x2) { swap(x1,x2); swap(y1,y2); } double m = (double)(y2-y1) / (double)(x2-x1); double b = (double) y1 - (m * x1); // clip: if (x1 < 0) { x1 = 0; y1 = (int) b; } if (x1 >= rect.w) return false; if (x2 < 0) return false; if (x2 > rect.w-1) { x2 = rect.w-1; y2 = (int) (m * x2 + b); } if (y1 < 0 && y2 < 0) return false; if (y1 >= rect.h && y2 >= rect.h) return false; if (y1 < 0) { y1 = 0; x1 = (int) (-b/m); } if (y1 >= rect.h) { y1 = rect.h-1; x1 = (int) ((y1-b)/m); } if (y2 < 0) { y2 = 0; x2 = (int) (-b/m); } if (y2 >= rect.h) { y2 = rect.h-1; x2 = (int) ((y2-b)/m); } if (x1 == x2) goto clip_vertical; if (y1 == y2) goto clip_horizontal; return true; } // +--------------------------------------------------------------------+ bool Window::ClipLine(double& x1, double& y1, double& x2, double& y2) { // vertical lines: if (x1==x2) { clip_vertical: sort(y1,y2); if (x1 < 0 || x1 >= rect.w) return false; if (y1 < 0) y1 = 0; if (y2 >= rect.h) y2 = rect.h; return true; } // horizontal lines: if (y1==y2) { clip_horizontal: sort(x1,x2); if (y1 < 0 || y1 >= rect.h) return false; if (x1 < 0) x1 = 0; if (x2 > rect.w) x2 = rect.w; return true; } // general lines: // sort left to right: if (x1 > x2) { swap(x1,x2); swap(y1,y2); } double m = (double)(y2-y1) / (double)(x2-x1); double b = (double) y1 - (m * x1); // clip: if (x1 < 0) { x1 = 0; y1 = b; } if (x1 >= rect.w) return false; if (x2 < 0) return false; if (x2 > rect.w-1) { x2 = rect.w-1; y2 = (m * x2 + b); } if (y1 < 0 && y2 < 0) return false; if (y1 >= rect.h && y2 >= rect.h) return false; if (y1 < 0) { y1 = 0; x1 = (-b/m); } if (y1 >= rect.h) { y1 = rect.h-1; x1 = ((y1-b)/m); } if (y2 < 0) { y2 = 0; x2 = (-b/m); } if (y2 >= rect.h) { y2 = rect.h-1; x2 = ((y2-b)/m); } if (x1 == x2) goto clip_vertical; if (y1 == y2) goto clip_horizontal; return true; } // +--------------------------------------------------------------------+ void Window::DrawLine(int x1, int y1, int x2, int y2, Color color, int blend) { if (!screen || !screen->GetVideo()) return; if (ClipLine(x1,y1,x2,y2)) { float points[4]; points[0] = (float) (rect.x + x1); points[1] = (float) (rect.y + y1); points[2] = (float) (rect.x + x2); points[3] = (float) (rect.y + y2); Video* video = screen->GetVideo(); video->DrawScreenLines(1, points, color, blend); } } // +--------------------------------------------------------------------+ void Window::DrawRect(int x1, int y1, int x2, int y2, Color color, int blend) { if (!screen || !screen->GetVideo()) return; sort(x1,x2); sort(y1,y2); if (x1 > rect.w || x2 < 0 || y1 > rect.h || y2 < 0) return; float points[16]; points[ 0] = (float) (rect.x + x1); points[ 1] = (float) (rect.y + y1); points[ 2] = (float) (rect.x + x2); points[ 3] = (float) (rect.y + y1); points[ 4] = (float) (rect.x + x2); points[ 5] = (float) (rect.y + y1); points[ 6] = (float) (rect.x + x2); points[ 7] = (float) (rect.y + y2); points[ 8] = (float) (rect.x + x2); points[ 9] = (float) (rect.y + y2); points[10] = (float) (rect.x + x1); points[11] = (float) (rect.y + y2); points[12] = (float) (rect.x + x1); points[13] = (float) (rect.y + y2); points[14] = (float) (rect.x + x1); points[15] = (float) (rect.y + y1); Video* video = screen->GetVideo(); video->DrawScreenLines(4, points, color, blend); } void Window::DrawRect(const Rect& r, Color color, int blend) { DrawRect(r.x, r.y, r.x+r.w, r.y+r.h, color, blend); } // +--------------------------------------------------------------------+ void Window::FillRect(int x1, int y1, int x2, int y2, Color color, int blend) { if (!screen || !screen->GetVideo()) return; sort(x1,x2); sort(y1,y2); if (x1 > rect.w || x2 < 0 || y1 > rect.h || y2 < 0) return; vset4.space = VertexSet::SCREEN_SPACE; for (int i = 0; i < 4; i++) { vset4.diffuse[i] = color.Value(); } vset4.s_loc[0].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[0].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[0].z = 0.0f; vset4.rw[0] = 1.0f; vset4.tu[0] = 0.0f; vset4.tv[0] = 0.0f; vset4.s_loc[1].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[1].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[1].z = 0.0f; vset4.rw[1] = 1.0f; vset4.tu[1] = 1.0f; vset4.tv[1] = 0.0f; vset4.s_loc[2].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[2].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[2].z = 0.0f; vset4.rw[2] = 1.0f; vset4.tu[2] = 1.0f; vset4.tv[2] = 1.0f; vset4.s_loc[3].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[3].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[3].z = 0.0f; vset4.rw[3] = 1.0f; vset4.tu[3] = 0.0f; vset4.tv[3] = 1.0f; Poly poly(0); poly.nverts = 4; poly.vertex_set = &vset4; poly.verts[0] = 0; poly.verts[1] = 1; poly.verts[2] = 2; poly.verts[3] = 3; Video* video = screen->GetVideo(); video->DrawScreenPolys(1, &poly, blend); } void Window::FillRect(const Rect& r, Color color, int blend) { FillRect(r.x, r.y, r.x+r.w, r.y+r.h, color, blend); } // +--------------------------------------------------------------------+ void Window::DrawLines(int nPts, POINT* pts, Color color, int blend) { if (nPts < 2 || nPts > 16) return; if (!screen || !screen->GetVideo()) return; float f[64]; int n = 0; for (int i = 0; i < nPts-1; i++) { f[n++] = (float) rect.x + pts[i].x; f[n++] = (float) rect.y + pts[i].y; f[n++] = (float) rect.x + pts[i+1].x; f[n++] = (float) rect.y + pts[i+1].y; } Video* video = screen->GetVideo(); video->DrawScreenLines(nPts-1, f, color, blend); } void Window::DrawPoly(int nPts, POINT* pts, Color color, int blend) { if (nPts < 3 || nPts > 8) return; if (!screen || !screen->GetVideo()) return; float f[32]; int n = 0; for (int i = 0; i < nPts-1; i++) { f[n++] = (float) rect.x + pts[i].x; f[n++] = (float) rect.y + pts[i].y; f[n++] = (float) rect.x + pts[i+1].x; f[n++] = (float) rect.y + pts[i+1].y; } f[n++] = (float) rect.x + pts[nPts-1].x; f[n++] = (float) rect.y + pts[nPts-1].y; f[n++] = (float) rect.x + pts[0].x; f[n++] = (float) rect.y + pts[0].y; Video* video = screen->GetVideo(); video->DrawScreenLines(nPts, f, color, blend); } void Window::FillPoly(int nPts, POINT* pts, Color color, int blend) { if (nPts < 3 || nPts > 4) return; if (!screen || !screen->GetVideo()) return; vset4.space = VertexSet::SCREEN_SPACE; for (int i = 0; i < nPts; i++) { vset4.diffuse[i] = color.Value(); vset4.s_loc[i].x = (float) (rect.x + pts[i].x) - 0.5f; vset4.s_loc[i].y = (float) (rect.y + pts[i].y) - 0.5f; vset4.s_loc[i].z = 0.0f; vset4.rw[i] = 1.0f; vset4.tu[i] = 0.0f; vset4.tv[i] = 0.0f; } Poly poly(0); poly.nverts = nPts; poly.vertex_set = &vset4; poly.verts[0] = 0; poly.verts[1] = 1; poly.verts[2] = 2; poly.verts[3] = 3; Video* video = screen->GetVideo(); video->DrawScreenPolys(1, &poly, blend); } // +--------------------------------------------------------------------+ void Window::DrawBitmap(int x1, int y1, int x2, int y2, Bitmap* img, int blend) { Rect clip_rect; clip_rect.w = rect.w; clip_rect.h = rect.h; ClipBitmap(x1,y1,x2,y2,img,Color::White,blend,clip_rect); } void Window::FadeBitmap(int x1, int y1, int x2, int y2, Bitmap* img, Color c, int blend) { Rect clip_rect; clip_rect.w = rect.w; clip_rect.h = rect.h; ClipBitmap(x1,y1,x2,y2,img,c,blend,clip_rect); } void Window::ClipBitmap(int x1, int y1, int x2, int y2, Bitmap* img, Color c, int blend, const Rect& clip_rect) { if (!screen || !screen->GetVideo() || !img) return; Rect clip = clip_rect; // clip the clip rect to the window rect: if (clip.x < 0) { clip.w -= clip.x; clip.x = 0; } if (clip.x + clip.w > rect.w) { clip.w -= (clip.x + clip.w - rect.w); } if (clip.y < 0) { clip.h -= clip.y; clip.y = 0; } if (clip.y + clip.h > rect.h) { clip.h -= (clip.y + clip.h - rect.h); } // now clip the bitmap to the validated clip rect: sort(x1,x2); sort(y1,y2); if (x1 > clip.x + clip.w || x2 < clip.x || y1 > clip.y + clip.h || y2 < clip.y) return; vset4.space = VertexSet::SCREEN_SPACE; for (int i = 0; i < 4; i++) { vset4.diffuse[i] = c.Value(); } float u1 = 0.0f; float u2 = 1.0f; float v1 = 0.0f; float v2 = 1.0f; float iw = (float) (x2-x1); float ih = (float) (y2-y1); int x3 = clip.x + clip.w; int y3 = clip.y + clip.h; if (x1 < clip.x) { u1 = (clip.x - x1) / iw; x1 = clip.x; } if (x2 > x3) { u2 = 1.0f - (x2 - x3) / iw; x2 = x3; } if (y1 < clip.y) { v1 = (clip.y - y1) / ih; y1 = clip.y; } if (y2 > y3) { v2 = 1.0f - (y2 - y3) / ih; y2 = y3; } vset4.s_loc[0].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[0].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[0].z = 0.0f; vset4.rw[0] = 1.0f; vset4.tu[0] = u1; vset4.tv[0] = v1; vset4.s_loc[1].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[1].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[1].z = 0.0f; vset4.rw[1] = 1.0f; vset4.tu[1] = u2; vset4.tv[1] = v1; vset4.s_loc[2].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[2].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[2].z = 0.0f; vset4.rw[2] = 1.0f; vset4.tu[2] = u2; vset4.tv[2] = v2; vset4.s_loc[3].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[3].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[3].z = 0.0f; vset4.rw[3] = 1.0f; vset4.tu[3] = u1; vset4.tv[3] = v2; Material mtl; mtl.tex_diffuse = img; Poly poly(0); poly.nverts = 4; poly.vertex_set = &vset4; poly.material = &mtl; poly.verts[0] = 0; poly.verts[1] = 1; poly.verts[2] = 2; poly.verts[3] = 3; Video* video = screen->GetVideo(); video->SetRenderState(Video::TEXTURE_WRAP, 0); video->DrawScreenPolys(1, &poly, blend); video->SetRenderState(Video::TEXTURE_WRAP, 1); } // +--------------------------------------------------------------------+ void Window::TileBitmap(int x1, int y1, int x2, int y2, Bitmap* img, int blend) { if (!screen || !screen->GetVideo()) return; if (!img || !img->Width() || !img->Height()) return; vset4.space = VertexSet::SCREEN_SPACE; for (int i = 0; i < 4; i++) { vset4.diffuse[i] = Color::White.Value(); } float xscale = (float) rect.w / (float) img->Width(); float yscale = (float) rect.h / (float) img->Height(); vset4.s_loc[0].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[0].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[0].z = 0.0f; vset4.rw[0] = 1.0f; vset4.tu[0] = 0.0f; vset4.tv[0] = 0.0f; vset4.s_loc[1].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[1].y = (float) (rect.y + y1) - 0.5f; vset4.s_loc[1].z = 0.0f; vset4.rw[1] = 1.0f; vset4.tu[1] = xscale; vset4.tv[1] = 0.0f; vset4.s_loc[2].x = (float) (rect.x + x2) - 0.5f; vset4.s_loc[2].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[2].z = 0.0f; vset4.rw[2] = 1.0f; vset4.tu[2] = xscale; vset4.tv[2] = yscale; vset4.s_loc[3].x = (float) (rect.x + x1) - 0.5f; vset4.s_loc[3].y = (float) (rect.y + y2) - 0.5f; vset4.s_loc[3].z = 0.0f; vset4.rw[3] = 1.0f; vset4.tu[3] = 0.0f; vset4.tv[3] = yscale; Material mtl; mtl.tex_diffuse = img; Poly poly(0); poly.nverts = 4; poly.vertex_set = &vset4; poly.material = &mtl; poly.verts[0] = 0; poly.verts[1] = 1; poly.verts[2] = 2; poly.verts[3] = 3; Video* video = screen->GetVideo(); video->DrawScreenPolys(1, &poly, blend); } // +--------------------------------------------------------------------+ static float ellipse_pts[256]; void Window::DrawEllipse(int x1, int y1, int x2, int y2, Color color, int blend) { Video* video = screen->GetVideo(); if (!video) return; sort(x1,x2); sort(y1,y2); if (x1 > rect.w || x2 < 0 || y1 > rect.h || y2 < 0) return; double w2 = (x2-x1)/2.0; double h2 = (y2-y1)/2.0; double cx = rect.x + x1 + w2; double cy = rect.y + y1 + h2; double r = w2; int ns = 4; int np = 0; if (h2 > r) r = h2; if (r > 2*ns) ns = (int) (r/2); if (ns > 64) ns = 64; double theta = 0; double dt = (PI/2) / ns; // quadrant 1 (lower right): if (cx < (rect.x+rect.w) && cy < (rect.y + rect.h)) { theta = 0; np = 0; for (int i = 0; i < ns; i++) { double ex1 = x1 + w2 + cos(theta) * w2; double ey1 = y1 + h2 + sin(theta) * h2; theta += dt; double ex2 = x1 + w2 + cos(theta) * w2; double ey2 = y1 + h2 + sin(theta) * h2; if (ClipLine(ex1, ey1, ex2, ey2)) { ellipse_pts[np++] = (float) (rect.x + ex1); ellipse_pts[np++] = (float) (rect.y + ey1); ellipse_pts[np++] = (float) (rect.x + ex2); ellipse_pts[np++] = (float) (rect.y + ey2); } } video->DrawScreenLines(np/4, ellipse_pts, color, blend); } // quadrant 2 (lower left): if (cx > rect.x && cy < (rect.y + rect.h)) { theta = 90*DEGREES; np = 0; for (int i = 0; i < ns; i++) { double ex1 = x1 + w2 + cos(theta) * w2; double ey1 = y1 + h2 + sin(theta) * h2; theta += dt; double ex2 = x1 + w2 + cos(theta) * w2; double ey2 = y1 + h2 + sin(theta) * h2; if (ClipLine(ex1, ey1, ex2, ey2)) { ellipse_pts[np++] = (float) (rect.x + ex1); ellipse_pts[np++] = (float) (rect.y + ey1); ellipse_pts[np++] = (float) (rect.x + ex2); ellipse_pts[np++] = (float) (rect.y + ey2); } } video->DrawScreenLines(np/4, ellipse_pts, color, blend); } // quadrant 3 (upper left): if (cx > rect.x && cy > rect.y) { theta = 180*DEGREES; np = 0; for (int i = 0; i < ns; i++) { double ex1 = x1 + w2 + cos(theta) * w2; double ey1 = y1 + h2 + sin(theta) * h2; theta += dt; double ex2 = x1 + w2 + cos(theta) * w2; double ey2 = y1 + h2 + sin(theta) * h2; if (ClipLine(ex1, ey1, ex2, ey2)) { ellipse_pts[np++] = (float) (rect.x + ex1); ellipse_pts[np++] = (float) (rect.y + ey1); ellipse_pts[np++] = (float) (rect.x + ex2); ellipse_pts[np++] = (float) (rect.y + ey2); } } video->DrawScreenLines(np/4, ellipse_pts, color, blend); } // quadrant 4 (upper right): if (cx < (rect.x+rect.w) && cy > rect.y) { theta = 270*DEGREES; np = 0; for (int i = 0; i < ns; i++) { double ex1 = x1 + w2 + cos(theta) * w2; double ey1 = y1 + h2 + sin(theta) * h2; theta += dt; double ex2 = x1 + w2 + cos(theta) * w2; double ey2 = y1 + h2 + sin(theta) * h2; if (ClipLine(ex1, ey1, ex2, ey2)) { ellipse_pts[np++] = (float) (rect.x + ex1); ellipse_pts[np++] = (float) (rect.y + ey1); ellipse_pts[np++] = (float) (rect.x + ex2); ellipse_pts[np++] = (float) (rect.y + ey2); } } video->DrawScreenLines(np/4, ellipse_pts, color, blend); } } void Window::FillEllipse(int x1, int y1, int x2, int y2, Color color, int blend) { Video* video = screen->GetVideo(); if (!video) return; sort(x1,x2); sort(y1,y2); if (x1 > rect.w || x2 < 0 || y1 > rect.h || y2 < 0) return; double w2 = (x2-x1)/2.0; double h2 = (y2-y1)/2.0; double cx = x1 + w2; double cy = y1 + h2; double r = w2; int ns = 4; int np = 0; if (h2 > r) r = h2; if (r > 2*ns) ns = (int) (r/2); if (ns > 64) ns = 64; double theta = -PI / 2; double dt = PI / ns; for (int i = 0; i < ns; i++) { double ex1 = cos(theta) * w2; double ey1 = sin(theta) * h2; theta += dt; double ex2 = cos(theta) * w2; double ey2 = sin(theta) * h2; POINT pts[4]; pts[0].x = (int) (cx - ex1); pts[0].y = (int) (cy + ey1); pts[1].x = (int) (cx + ex1); pts[1].y = (int) (cy + ey1); pts[2].x = (int) (cx + ex2); pts[2].y = (int) (cy + ey2); pts[3].x = (int) (cx - ex2); pts[3].y = (int) (cy + ey2); if (pts[0].x > rect.w && pts[3].x > rect.w) continue; if (pts[1].x < 0 && pts[2].x < 0) continue; if (pts[0].y > rect.h) return; if (pts[2].y < 0) continue; if (pts[0].x < 0) pts[0].x = 0; if (pts[3].x < 0) pts[3].x = 0; if (pts[1].x > rect.w) pts[1].x = rect.w; if (pts[2].x > rect.w) pts[2].x = rect.w; if (pts[0].y < 0) pts[0].y = 0; if (pts[1].y < 0) pts[1].y = 0; if (pts[2].y > rect.h) pts[2].y = rect.h; if (pts[3].y > rect.h) pts[3].y = rect.h; FillPoly(4, pts, color, blend); } } // +--------------------------------------------------------------------+ void Window::Print(int x1, int y1, const char* fmt, ...) { if (!font || x1<0 || y1<0 || x1>=rect.w || y1>=rect.h || !fmt) return; x1 += rect.x; y1 += rect.y; char msgbuf[512]; vsprintf_s(msgbuf, fmt, (char *)(&fmt+1)); font->DrawString(msgbuf, strlen(msgbuf), x1, y1, rect); } void Window::DrawText(const char* txt, int count, Rect& txt_rect, DWORD flags) { if (!font) return; if (txt && !count) count = strlen(txt); // clip the rect: Rect clip_rect = txt_rect; if (clip_rect.x < 0) { int dx = -clip_rect.x; clip_rect.x += dx; clip_rect.w -= dx; } if (clip_rect.y < 0) { int dy = -clip_rect.y; clip_rect.y += dy; clip_rect.h -= dy; } if (clip_rect.w < 1 || clip_rect.h < 1) return; if (clip_rect.x + clip_rect.w > rect.w) clip_rect.w = rect.w - clip_rect.x; if (clip_rect.y + clip_rect.h > rect.h) clip_rect.h = rect.h - clip_rect.y; clip_rect.x += rect.x; clip_rect.y += rect.y; if (font && txt && count) { font->DrawText(txt, count, clip_rect, flags); font->SetAlpha(1); } // if calc only, update the rectangle: if (flags & DT_CALCRECT) { txt_rect.h = clip_rect.h; txt_rect.w = clip_rect.w; } }
25.463059
106
0.479403
RogerioY
5ef47ed827fd88cd573bd7c95daec49cb7a816ee
1,170
cpp
C++
qtgui/ResultImage.cpp
starturtle/one-bit
32138249e20c42bd164c1d91a209f338087730f9
[ "MIT" ]
null
null
null
qtgui/ResultImage.cpp
starturtle/one-bit
32138249e20c42bd164c1d91a209f338087730f9
[ "MIT" ]
25
2020-03-18T22:50:22.000Z
2020-10-30T10:49:16.000Z
qtgui/ResultImage.cpp
starturtle/one-bit
32138249e20c42bd164c1d91a209f338087730f9
[ "MIT" ]
null
null
null
#include "ResultImage.h" #include "logging.h" #include <algorithm> #include <QMouseEvent> ResultImage::ResultImage(QQuickItem* parent) : QQuickPaintedItem() , image{} { } void ResultImage::setData(const QImage& data) { if (data.isNull()) { logging::logger() << logging::Level::NOTE << "Input Image empty!" << logging::Level::OFF; } else { logging::logger() << logging::Level::DEBUG << "Setting Result Image" << logging::Level::OFF; } image = data; if (image.isNull()) { logging::logger() << logging::Level::WARNING << "Result Image empty!" << logging::Level::OFF; } else { logging::logger() << logging::Level::DEBUG << "Set Result Image" << logging::Level::OFF; } update(); } void ResultImage::paint(QPainter* painter){ QRectF bounds = boundingRect(); if(image.isNull()) { painter->fillRect(bounds, Qt::green); return; } QImage scaled = image.scaledToWidth(bounds.width()); QPointF center = bounds.center() - scaled.rect().center(); if(center.x() < 0) center.setX(0); if(center.y() < 0) center.setY(0); painter->drawImage(center, scaled); } QImage ResultImage::data() const { return image; }
21.666667
97
0.642735
starturtle
5ef76395fe577771422a3fe5adc717b25613601f
5,459
cpp
C++
src/test_array_of_ordered.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
275
2019-04-28T18:53:01.000Z
2022-03-29T23:10:14.000Z
src/test_array_of_ordered.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
78
2019-11-15T16:20:11.000Z
2022-02-23T01:24:49.000Z
src/test_array_of_ordered.cpp
mheyman/daw_json_link_vcpkg_tests
efb56c122bec2f1a80d6a1843752510a2a8ca956
[ "BSL-1.0" ]
15
2019-06-20T10:28:47.000Z
2022-03-10T16:45:10.000Z
// Copyright (c) Darrell Wright // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/beached/daw_json_link // #include <daw/json/daw_json_link.h> #include <cstdint> #include <iostream> #include <string> #include <string_view> #include <vector> struct Fixed8JsonConverter { double operator( )( std::string_view sv ) const { return stod( std::string( sv ) ); } template<typename OutputIterator> constexpr OutputIterator operator( )( OutputIterator _it, double _f ) const { return daw::json::utils::copy_to_iterator( _it, std::to_string( _f ) ); } }; template<JSONNAMETYPE name> using json_fixed8 = daw::json::json_custom<name, double, Fixed8JsonConverter, Fixed8JsonConverter>; struct Change { double rate; double amount; }; namespace daw::json { template<> struct json_data_contract<Change> { using type = json_ordered_member_list<json_fixed8<no_name>, json_fixed8<no_name>>; }; } // namespace daw::json class DepthUpdateJson { public: std::int64_t time; // E std::string pairName; // s std::int64_t idTo; // u std::int64_t idFrom; // U std::vector<Change> bid; // b std::vector<Change> ask; // a }; namespace daw::json { template<> struct json_data_contract<DepthUpdateJson> { static constexpr char const E[] = "E"; static constexpr char const s[] = "s"; static constexpr char const u[] = "u"; static constexpr char const U[] = "U"; static constexpr char const b[] = "b"; static constexpr char const a[] = "a"; using type = json_member_list<json_number<E, std::int64_t>, json_string<s>, json_number<u, std::int64_t>, json_number<U, std::int64_t>, json_array<b, Change>, json_array<a, Change>>; }; } // namespace daw::json int main( ) { try { std::string testJson1 = R"({"e":"depthUpdate","E":1609884707320,"s":"BTCBUSD","U":2544556159,"u":2544556219,"a":[["34198.19000000","0.00000000"],["34198.23000000","0.00000000"],["34198.25000000","0.00000000"],["34198.27000000","0.00000000"],["34198.30000000","0.00000000"],["34198.32000000","0.00958500"],["34198.40000000","0.01232200"],["34198.41000000","0.01000000"],["34198.87000000","0.00000000"],["34199.12000000","0.00000000"],["34199.16000000","0.00000000"],["34199.42000000","0.00000000"],["34200.25000000","0.00000000"],["34200.71000000","0.03199900"],["34201.27000000","0.03100000"],["34201.62000000","0.00000000"],["34202.58000000","0.00000000"],["34204.45000000","0.00952700"],["34207.64000000","0.00000000"],["34207.74000000","0.00000000"],["34209.77000000","0.00000000"],["34209.81000000","0.20400000"],["34225.94000000","0.20200000"],["34226.60000000","0.91050000"],["34236.08000000","0.30000000"]],"b":[["34198.31000000","0.00000000"],["34196.54000000","0.00453200"],["34193.34000000","0.00000000"],["34189.89000000","0.00000000"],["34188.82000000","0.00000000"],["34185.32000000","0.00000000"],["34184.84000000","0.06350200"],["34184.83000000","0.20000000"],["34180.61000000","0.08622700"],["34180.60000000","0.00000000"],["34180.59000000","0.19200000"],["34180.02000000","0.00000000"],["34180.01000000","0.00000000"],["34176.88000000","0.00000000"],["34166.48000000","0.00000000"],["34166.47000000","0.00000000"],["34159.85000000","0.03317500"],["34159.24000000","0.09394900"],["34158.29000000","1.00000000"],["34154.86000000","0.00000000"]]})"; std::string testJson2 = R"({"e":"depthUpdate","E":1609884707320,"s":"BTCBUSD","U":2544556159,"u":2544556219,"b":[["34198.31000000","0.00000000"],["34196.54000000","0.00453200"],["34193.34000000","0.00000000"],["34189.89000000","0.00000000"],["34188.82000000","0.00000000"],["34185.32000000","0.00000000"],["34184.84000000","0.06350200"],["34184.83000000","0.20000000"],["34180.61000000","0.08622700"],["34180.60000000","0.00000000"],["34180.59000000","0.19200000"],["34180.02000000","0.00000000"],["34180.01000000","0.00000000"],["34176.88000000","0.00000000"],["34166.48000000","0.00000000"],["34166.47000000","0.00000000"],["34159.85000000","0.03317500"],["34159.24000000","0.09394900"],["34158.29000000","1.00000000"],["34154.86000000","0.00000000"]],"a":[["34198.19000000","0.00000000"],["34198.23000000","0.00000000"],["34198.25000000","0.00000000"],["34198.27000000","0.00000000"],["34198.30000000","0.00000000"],["34198.32000000","0.00958500"],["34198.40000000","0.01232200"],["34198.41000000","0.01000000"],["34198.87000000","0.00000000"],["34199.12000000","0.00000000"],["34199.16000000","0.00000000"],["34199.42000000","0.00000000"],["34200.25000000","0.00000000"],["34200.71000000","0.03199900"],["34201.27000000","0.03100000"],["34201.62000000","0.00000000"],["34202.58000000","0.00000000"],["34204.45000000","0.00952700"],["34207.64000000","0.00000000"],["34207.74000000","0.00000000"],["34209.77000000","0.00000000"],["34209.81000000","0.20400000"],["34225.94000000","0.20200000"],["34226.60000000","0.91050000"],["34236.08000000","0.30000000"]])"; auto parsed = daw::json::from_json<DepthUpdateJson>( testJson1 ); std::cout << ""; } catch( daw::json::json_exception const &e ) { std::cout << "formatted: " << to_formatted_string( e ) << "\n\n"; std::cout << "daw error: " << e.reason( ) << " near: '" << e.parse_location( ) << "'" << std::endl; } }
62.747126
1,543
0.66111
mheyman
5ef78d02c64c47f4d9c91d76878ca14bf8b2679d
8,274
cpp
C++
generator/maxspeeds_builder.cpp
sthirvela/organicmaps
14885ba070ac9d1b7241ebb89eeefa46c9fdc1e4
[ "Apache-2.0" ]
3,062
2021-04-09T16:51:55.000Z
2022-03-31T21:02:51.000Z
generator/maxspeeds_builder.cpp
MAPSWorks/organicmaps
b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f
[ "Apache-2.0" ]
1,396
2021-04-08T07:26:49.000Z
2022-03-31T20:27:46.000Z
generator/maxspeeds_builder.cpp
MAPSWorks/organicmaps
b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f
[ "Apache-2.0" ]
242
2021-04-10T17:10:46.000Z
2022-03-31T13:41:07.000Z
#include "generator/maxspeeds_builder.hpp" #include "generator/maxspeeds_parser.hpp" #include "generator/routing_helpers.hpp" #include "routing/index_graph.hpp" #include "routing/maxspeeds_serialization.hpp" #include "routing/routing_helpers.hpp" #include "routing_common/maxspeed_conversion.hpp" #include "indexer/feature.hpp" #include "indexer/feature_data.hpp" #include "indexer/feature_processor.hpp" #include "coding/files_container.hpp" #include "coding/file_writer.hpp" #include "platform/measurement_utils.hpp" #include "base/assert.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include <algorithm> #include <fstream> #include <sstream> #include <utility> #include "defines.hpp" using namespace feature; using namespace generator; using namespace routing; using namespace std; namespace { char const kDelim[] = ", \t\r\n"; bool ParseOneSpeedValue(strings::SimpleTokenizer & iter, MaxspeedType & value) { if (!iter) return false; uint64_t parsedSpeed = 0; if (!strings::to_uint64(*iter, parsedSpeed)) return false; if (parsedSpeed > routing::kInvalidSpeed) return false; value = static_cast<MaxspeedType>(parsedSpeed); ++iter; return true; } FeatureMaxspeed ToFeatureMaxspeed(uint32_t featureId, Maxspeed const & maxspeed) { return FeatureMaxspeed(featureId, maxspeed.GetUnits(), maxspeed.GetForward(), maxspeed.GetBackward()); } /// \brief Collects all maxspeed tag values of specified mwm based on maxspeeds.csv file. class MaxspeedsMwmCollector { vector<FeatureMaxspeed> m_maxspeeds; public: MaxspeedsMwmCollector(IndexGraph * graph, string const & dataPath, map<uint32_t, base::GeoObjectId> const & featureIdToOsmId, string const & maxspeedCsvPath) { OsmIdToMaxspeed osmIdToMaxspeed; CHECK(ParseMaxspeeds(maxspeedCsvPath, osmIdToMaxspeed), (maxspeedCsvPath)); auto const GetOsmID = [&](uint32_t fid) -> base::GeoObjectId { auto const osmIdIt = featureIdToOsmId.find(fid); if (osmIdIt == featureIdToOsmId.cend()) return base::GeoObjectId(); return osmIdIt->second; }; auto const GetSpeed = [&](uint32_t fid) -> Maxspeed * { auto osmid = GetOsmID(fid); if (osmid.GetType() == base::GeoObjectId::Type::Invalid) return nullptr; auto const maxspeedIt = osmIdToMaxspeed.find(osmid); if (maxspeedIt == osmIdToMaxspeed.cend()) return nullptr; return &maxspeedIt->second; }; auto const GetRoad = [&](uint32_t fid) -> routing::RoadGeometry const & { return graph->GetGeometry().GetRoad(fid); }; auto const GetLastIndex = [&](uint32_t fid) { return GetRoad(fid).GetPointsCount() - 2; }; auto const GetOpposite = [&](Segment const & seg) { // Assume that links are connected with main roads in first or last point, always. uint32_t const fid = seg.GetFeatureId(); return Segment(0, fid, seg.GetSegmentIdx() > 0 ? 0 : GetLastIndex(fid), seg.IsForward()); }; ForEachFeature(dataPath, [&](FeatureType & ft, uint32_t fid) { if (!routing::IsCarRoad(TypesHolder(ft))) return; Maxspeed * maxSpeed = GetSpeed(fid); if (!maxSpeed) return; auto const osmid = GetOsmID(fid).GetSerialId(); // Recalculate link speed accordint to the ingoing highway. // See MaxspeedsCollector::CollectFeature. if (maxSpeed->GetForward() == routing::kCommonMaxSpeedValue) { // Check if we are in unit tests. if (graph == nullptr) return; // 0 - not updated, 1 - goto next iteration, 2 - updated int status; // Check ingoing first, then - outgoing. for (bool direction : { false, true }) { Segment seg(0, fid, 0, true); if (direction) seg = GetOpposite(seg); std::unordered_set<uint32_t> reviewed; do { status = 0; reviewed.insert(seg.GetFeatureId()); IndexGraph::SegmentEdgeListT edges; graph->GetEdgeList(seg, direction, true /* useRoutingOptions */, edges); for (auto const & e : edges) { Segment const target = e.GetTarget(); Maxspeed * s = GetSpeed(target.GetFeatureId()); if (s) { if (s->GetForward() != routing::kCommonMaxSpeedValue) { status = 2; maxSpeed->SetForward(s->GetForward()); // In theory, we should iterate on forward and backward segments/speeds separately, // but I don't see any reason for this complication. if (!GetRoad(fid).IsOneWay()) maxSpeed->SetBackward(s->GetForward()); LOG(LINFO, ("Updated link speed for way", osmid, "with", *maxSpeed)); break; } else if (reviewed.find(target.GetFeatureId()) == reviewed.end()) { // Found another input link. Save it for the next iteration. status = 1; seg = GetOpposite(target); } } } } while (status == 1); if (status == 2) break; } if (status == 0) { LOG(LWARNING, ("Didn't find connected edge with speed for way", osmid)); return; } } m_maxspeeds.push_back(ToFeatureMaxspeed(fid, *maxSpeed)); }); } vector<FeatureMaxspeed> const & GetMaxspeeds() { CHECK(is_sorted(m_maxspeeds.cbegin(), m_maxspeeds.cend(), IsFeatureIdLess), ()); return m_maxspeeds; } }; } // namespace namespace routing { bool ParseMaxspeeds(string const & maxspeedsFilename, OsmIdToMaxspeed & osmIdToMaxspeed) { osmIdToMaxspeed.clear(); ifstream stream(maxspeedsFilename); if (!stream) return false; string line; while (getline(stream, line)) { strings::SimpleTokenizer iter(line, kDelim); if (!iter) // the line is empty return false; // @TODO(bykoianko) strings::to_uint64 returns not-zero value if |*iter| is equal to // a too long string of numbers. But ParseMaxspeeds() should return false in this case. uint64_t osmId = 0; if (!strings::to_uint64(*iter, osmId)) return false; ++iter; if (!iter) return false; Maxspeed speed; speed.SetUnits(StringToUnits(*iter)); ++iter; MaxspeedType forward = 0; if (!ParseOneSpeedValue(iter, forward)) return false; speed.SetForward(forward); if (iter) { // There's backward maxspeed limit. MaxspeedType backward = 0; if (!ParseOneSpeedValue(iter, backward)) return false; speed.SetBackward(backward); if (iter) return false; } auto const res = osmIdToMaxspeed.insert(make_pair(base::MakeOsmWay(osmId), speed)); if (!res.second) return false; } return true; } void SerializeMaxspeeds(string const & dataPath, vector<FeatureMaxspeed> const & speeds) { if (speeds.empty()) return; FilesContainerW cont(dataPath, FileWriter::OP_WRITE_EXISTING); auto writer = cont.GetWriter(MAXSPEEDS_FILE_TAG); MaxspeedsSerializer::Serialize(speeds, *writer); LOG(LINFO, ("SerializeMaxspeeds(", dataPath, ", ...) serialized:", speeds.size(), "maxspeed tags.")); } void BuildMaxspeedsSection(IndexGraph * graph, string const & dataPath, map<uint32_t, base::GeoObjectId> const & featureIdToOsmId, string const & maxspeedsFilename) { MaxspeedsMwmCollector collector(graph, dataPath, featureIdToOsmId, maxspeedsFilename); SerializeMaxspeeds(dataPath, collector.GetMaxspeeds()); } void BuildMaxspeedsSection(IndexGraph * graph, string const & dataPath, string const & osmToFeaturePath, string const & maxspeedsFilename) { map<uint32_t, base::GeoObjectId> featureIdToOsmId; CHECK(ParseWaysFeatureIdToOsmIdMapping(osmToFeaturePath, featureIdToOsmId), ()); BuildMaxspeedsSection(graph, dataPath, featureIdToOsmId, maxspeedsFilename); } } // namespace routing
29.236749
103
0.630771
sthirvela
5ef794e29145b5cc25e08d018a5106b6718e7650
2,485
cpp
C++
cpuBoosters/bmv2/booster_switch/memcached_booster_primitives.cpp
CSEYJ/Flightplan
e1424f42c8f06446094941c38ef5989a76b7ee0a
[ "Apache-2.0" ]
20
2020-10-06T08:37:22.000Z
2022-03-28T07:32:23.000Z
cpuBoosters/bmv2/booster_switch/memcached_booster_primitives.cpp
CSEYJ/Flightplan
e1424f42c8f06446094941c38ef5989a76b7ee0a
[ "Apache-2.0" ]
1
2021-01-24T15:51:40.000Z
2021-01-24T15:51:40.000Z
cpuBoosters/bmv2/booster_switch/memcached_booster_primitives.cpp
CSEYJ/Flightplan
e1424f42c8f06446094941c38ef5989a76b7ee0a
[ "Apache-2.0" ]
3
2021-01-06T03:43:50.000Z
2021-10-15T20:09:32.000Z
#include "booster_primitives.hpp" #include "memcached.h" #include "simple_switch.h" #include <bm/bm_sim/actions.h> #include <bm/bm_sim/data.h> #include <bm/bm_sim/packet.h> using bm::Data; using bm::Packet; using bm::Header; template <typename... Args> using BoosterExtern = boosters::BoosterExtern<Args...>; template <typename ...Args> class memcached_core : public BoosterExtern<Data &, Args...> { using BoosterExtern<Data &, Args...>::BoosterExtern; protected: void core(Data &forward_d, Header *fp_h) { if (this->is_generated()) { forward_d.set(true); if (fp_h != nullptr) { fp_h->mark_valid(); } return; } Packet &packet = this->get_packet(); int egress_port = this->phv->get_field("standard_metadata.egress_spec").get_int(); int ingress_port = this->phv->get_field("standard_metadata.ingress_port").get_int(); if (fp_h != nullptr) fp_h->mark_invalid(); // Must save packet state so it can be restored after deparsing const Packet::buffer_state_t packet_in_state = this->deparse_packet(); char *buff = packet.data(); size_t buff_size = packet.get_data_size(); auto forwarder = [&](char *payload, size_t len, int reverse) { int new_ingress = reverse == 0 ? ingress_port : egress_port; int new_egress = reverse == 0 ? egress_port : ingress_port; this->generate_packet(payload, len, new_ingress, new_egress); }; bool drop = call_memcached((char*)buff, buff_size, forwarder); this->reparse_packet(packet_in_state); if (drop) { forward_d.set(false); } else { forward_d.set(true); } // Drop the packet if another was forwarded if (fp_h != nullptr) fp_h->mark_valid(); } }; class memcached : public memcached_core<> { // Inherit constructor using memcached_core::memcached_core; void operator ()(Data &forward_d) { core(forward_d, nullptr); } }; class memcached_fp : public memcached_core<Header &> { // Inherit constructor using memcached_core::memcached_core; void operator ()(Data &forward_d, Header &fp_h) { core(forward_d, &fp_h); } }; void import_memcached_booster_primitives(SimpleSwitch *sswitch) { REGISTER_BOOSTER_EXTERN(memcached, sswitch); REGISTER_BOOSTER_EXTERN(memcached_fp, sswitch); }
27.921348
92
0.632596
CSEYJ
5ef91b0debb6fa7dde8c828d2b821777420bdb49
1,165
cpp
C++
src/tests/thirdparty/t_silo_smoke.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
120
2015-12-09T00:58:22.000Z
2022-03-25T00:14:39.000Z
src/tests/thirdparty/t_silo_smoke.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
808
2016-02-27T22:25:15.000Z
2022-03-30T23:42:12.000Z
src/tests/thirdparty/t_silo_smoke.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
49
2016-02-12T17:19:16.000Z
2022-02-01T14:36:21.000Z
// Copyright (c) Lawrence Livermore National Security, LLC and other Conduit // Project developers. See top-level LICENSE AND COPYRIGHT files for dates and // other details. No copyright assignment is required to contribute to Conduit. //----------------------------------------------------------------------------- /// /// file: silo_smoke.cpp /// //----------------------------------------------------------------------------- #include <silo.h> #include <iostream> #include "gtest/gtest.h" //----------------------------------------------------------------------------- TEST(silo_smoke, basic_use) { DBfile *dbfile = DBCreate("silo_smoke_test.silo", 0, DB_LOCAL, "test", DB_HDF5); std::string twrite = "test_string"; int twrite_len = twrite.size()+1; DBWrite (dbfile, "tdata", twrite.c_str(), &twrite_len, 1, DB_CHAR); DBClose(dbfile); dbfile = DBOpen("silo_smoke_test.silo", DB_HDF5, DB_READ); int tread_len = DBGetVarLength(dbfile, "tdata"); char *tread = new char[tread_len]; DBReadVar(dbfile, "tdata", tread); DBClose(dbfile); EXPECT_EQ(twrite,std::string(tread)); delete [] tread; }
31.486486
84
0.538197
adrienbernede
5efa026717b62246a310b684745fda4e85d07fb8
2,160
hpp
C++
rtcf/include/rtcf/rt_rosconsole_logging.hpp
daoran/RTCF
dd4faebe13a733cd6ef93074d4b909aa831f4c57
[ "MIT" ]
11
2021-04-26T17:30:20.000Z
2022-03-27T14:15:10.000Z
rtcf/include/rtcf/rt_rosconsole_logging.hpp
daoran/RTCF
dd4faebe13a733cd6ef93074d4b909aa831f4c57
[ "MIT" ]
12
2021-03-29T10:15:37.000Z
2021-05-21T16:25:58.000Z
rtcf/include/rtcf/rt_rosconsole_logging.hpp
daoran/RTCF
dd4faebe13a733cd6ef93074d4b909aa831f4c57
[ "MIT" ]
2
2021-07-05T16:22:02.000Z
2021-12-29T10:05:25.000Z
#ifndef RT_ROSONSOLE_LOGGING_HPP #define RT_ROSONSOLE_LOGGING_HPP #include <ros/ros.h> #include <roscpp/SetLoggerLevel.h> #include "rtcf/macros.hpp" OROCOS_HEADERS_BEGIN // this is a workaround for old log4cpp version that do not compile in C++17 due to usage of deprecated features #define throw(...) #include <log4cpp/HierarchyMaintainer.hh> #undef throw #include <ocl/Category.hpp> #include <ocl/LoggingEvent.hpp> #include <rtt/InputPort.hpp> #include <rtt/TaskContext.hpp> OROCOS_HEADERS_END #include "tlsf_memory_pool.hpp" class RtRosconsoleLogging : public RTT::TaskContext { public: static RtRosconsoleLogging& getInstance(); static constexpr size_t MEMORY_POOL_SIZE = 1024 * 1024; // 1 MByte static bool setLoggerLevel(const std::string& name, ros::console::levels::Level level); static OCL::logging::Category* getLoggerInstance(const std::string& name); static ros::console::Level levelRTT2ROS(const log4cpp::Priority::Value& prio); static log4cpp::Priority::Value levelROS2RTT(const ros::console::Level& prio); protected: RtRosconsoleLogging(); virtual bool configureHook(); virtual bool startHook(); virtual void updateHook(); virtual void stopHook(); virtual void cleanupHook(); void drainBuffer(); RTT::InputPort<OCL::logging::LoggingEvent> log_port_; TlsfMemoryPool rt_memory_pool_; ros::ServiceServer logger_level_service_; static bool setLoggerLevelCallback(roscpp::SetLoggerLevel::Request& req, roscpp::SetLoggerLevel::Response&); static bool setRTLoggerLevel(const std::string& name, ros::console::levels::Level); private: static std::shared_ptr<RtRosconsoleLogging> instance; // TODO: // - create macros in RTCF extension // DONE: // - unload logger gracefully // - test // - load logger at the right places // - remove code from RTCF extension // - push everything that arrives to rosconsole // - create event port for ros.rtcf // - setup log4cpp // - intercept rosconsole-loggerlevel callbacks // - create ros.rtcf logger with properties active in ROS }; #endif // RT_ROSONSOLE_LOGGING_HPP
30.422535
112
0.72963
daoran
5efbeea1d451979703edf492de43826be70fc94f
2,018
cpp
C++
number theory/segmented_sieve.cpp
ferdouszislam/Algorithms
bfae54231a3a27bcc69aa6585574e9ec8863e8ba
[ "MIT" ]
1
2020-10-15T10:55:45.000Z
2020-10-15T10:55:45.000Z
number theory/segmented_sieve.cpp
ferdouszislam/Algorithms
bfae54231a3a27bcc69aa6585574e9ec8863e8ba
[ "MIT" ]
null
null
null
number theory/segmented_sieve.cpp
ferdouszislam/Algorithms
bfae54231a3a27bcc69aa6585574e9ec8863e8ba
[ "MIT" ]
null
null
null
/** Segmented Sieve Find all prime numbers in the range- [a, b] where (a, b)<=10^14 and b-a<=10^5 Complexity: O(loglogN) **/ #include <bits/stdc++.h> using namespace std; ///------------------- Segmented Sieve start -------------------/// vector<int> primes; // Sieve Of Eratosthenes to find primes upto 10^7 // and populate the vector 'primes' void findPrimesUpto(int n) { primes.clear(); vector<bool> prime(n+1, true); //bool prime[n + 1]; //memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++){ if (prime[p] == true){ for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int p = 2; p <= n; p++) if (prime[p]) primes.push_back(p); } vector<long long> primesInSegment; void findPrimesInSegment(long long a, long long b){ primesInSegment.clear(); if (a == 1) a++; int sqrtn = sqrt(b); findPrimesUpto(sqrtn); vector<bool> prime(b-a+1, true); //bool prime[b-a+1]; //memset(prime, true, sizeof prime); for (int i = 0; i < primes.size() && primes[i] <= sqrtn; i++) { long long p = primes[i]; long long j = p * p; // If j is smaller than a, then shift it inside of segment [a,b] if (j < a) j = ( ( a + p - 1 ) / p ) * p; for ( ; j <= b; j += p ) { prime[j-a] = false; } } for (long long i = a; i <= b; i++) { int pos = i-a; if (prime[pos]) primesInSegment.push_back(i); } } ///------------------- Segmented Sieve end -------------------/// int getRandomNumberInRange(int lower, int upper){ // generate a random number in the range- ['lower', 'upper'] srand(time(0)); return rand()%(upper-lower+1)+lower; } void exec(){ // execute the algorithm long long a = 10e14-1000; long long b = 10e14-100; findPrimesInSegment(a, b); for(long long x : primesInSegment) cout<<x<<"\n"; } int main() { exec(); return 0; }
19.784314
81
0.512884
ferdouszislam
6f06c982cb4f6df43487f4be1d7153ba54206d82
1,206
cpp
C++
Timus/Devices.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
1
2019-09-29T03:58:35.000Z
2019-09-29T03:58:35.000Z
Timus/Devices.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
Timus/Devices.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #ifdef ONLINE_JUDGE #define DB(x) #define DBL(x) #define EL #else #define DB(x) cerr << "#" << (#x) << ": " << (x) << " "; #define DBL(x) cerr << "#" << (#x) << ": " << (x) << endl; #define EL cerr << endl; #endif #define EPS 1e-11 #define X first #define Y second #define PB push_back #define SQ(x) ((x)*(x)) #define GB(m, x) ((m) & (1<<(x))) #define SB(m, x) ((m) | (1<<(x))) #define CB(m, x) ((m) & (~(1<<(x)))) #define TB(m, x) ((m) ^ (1<<(x))) using namespace std; typedef string string; typedef long double ld; typedef unsigned long long ull; typedef long long ll; typedef pair<ll, ll> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vi> vvi; typedef vector<ll> vll; typedef pair<string, string> ss; const static ll MX = 54322, MN = 780; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); string A, B; int p, i, j; map<string, set<int>> M; while(cin >> A >> B >> p){ M[B].insert(p); } int m, mm; m = 0; mm = INT_MAX; for(auto x : M){ if(x.Y.size() > m || (x.Y.size() == m && *x.Y.begin() < mm)) { m = x.Y.size(); mm = *x.Y.begin(); A = x.X; } } cout << A << endl; }
23.647059
64
0.548093
MartinAparicioPons
6f08483d4f17cb075d9126823f81938f1bbdd3e3
1,226
cpp
C++
src/CefWing/CefRenderApp/CefViewAppBase.cpp
klarso-gmbh/CefView_CefViewCore
18958c0dbcc44e851ce8569909b098a13ea37953
[ "MIT" ]
null
null
null
src/CefWing/CefRenderApp/CefViewAppBase.cpp
klarso-gmbh/CefView_CefViewCore
18958c0dbcc44e851ce8569909b098a13ea37953
[ "MIT" ]
null
null
null
src/CefWing/CefRenderApp/CefViewAppBase.cpp
klarso-gmbh/CefView_CefViewCore
18958c0dbcc44e851ce8569909b098a13ea37953
[ "MIT" ]
null
null
null
// // CefWingAppBase.cpp // CeViewfWing // // Created by Sheen Tian on 2020/6/17. // #pragma region project_heasers #include "CefViewAppBase.h" #pragma endregion project_heasers #pragma region mac_headers #include <Common/CefViewCoreLog.h> #pragma endregion mac_headers #include <CefViewCoreProtocol.h> // These flags must match the Chromium values. const char kProcessType[] = "type"; const char kRendererProcess[] = "renderer"; CefViewAppBase::CefViewAppBase() {} // static CefViewAppBase::ProcessType CefViewAppBase::GetProcessType(CefRefPtr<CefCommandLine> command_line) { // The command-line flag won't be specified for the browser process. if (!command_line->HasSwitch(kProcessType)) return UnkownProcess; const std::string& process_type = command_line->GetSwitchValue(kProcessType); logI("process type parameter is: %s", process_type.c_str()); return (process_type == kRendererProcess) ? RendererProcess : OtherProcess; } std::string CefViewAppBase::GetBridgeObjectName(CefRefPtr<CefCommandLine> command_line) { if (!command_line->HasSwitch(CEFVIEW_BRIDGE_OBJ_NAME_KEY)) return ""; const std::string& name = command_line->GetSwitchValue(CEFVIEW_BRIDGE_OBJ_NAME_KEY); return name; }
26.652174
86
0.769984
klarso-gmbh
6f0a060710a429c01f573ee16ab3dfa63d96f9be
6,332
cc
C++
arch/testing/rcu_protected_test.cc
kstepanmpmg/mldb
f78791cd34d01796705c0f173a14359ec1b2e021
[ "Apache-2.0" ]
1
2019-04-29T12:39:34.000Z
2019-04-29T12:39:34.000Z
arch/testing/rcu_protected_test.cc
tomzhang/mldb
a09cf2d9ca454d1966b9e49ae69f2fe6bf571494
[ "Apache-2.0" ]
2
2021-03-20T05:52:26.000Z
2021-11-15T17:52:54.000Z
arch/testing/rcu_protected_test.cc
matebestek/mldb
f78791cd34d01796705c0f173a14359ec1b2e021
[ "Apache-2.0" ]
1
2018-11-23T20:03:38.000Z
2018-11-23T20:03:38.000Z
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. /* rcu_protected_test.cc Jeremy Barnes, 12 April 2014 Copyright (c) 2014 mldb.ai inc. All rights reserved. */ #include "mldb/arch/rcu_protected.h" #include "mldb/utils/vector_utils.h" #include <thread> #include <map> #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> using namespace std; using namespace MLDB; struct Collection1 { Collection1() : entries(entriesLock) { entries.replace(new Entries()); } bool addEntry(const std::string & key, std::shared_ptr<std::string> value, bool mustAdd) { GcLock::SharedGuard guard(entriesLock); for (;;) { auto oldEntries = entries(); ExcAssert(entriesLock.isLockedShared()); auto it = oldEntries->find(key); if (it != oldEntries->end()) return false; std::unique_ptr<Entries> newEntries(new Entries(*oldEntries)); (*newEntries)[key] = *value; if (entries.cmp_xchg(oldEntries, newEntries, true /* defer */)) { return true; } // RCU raced } } void recycleEntries() { GcLock::SharedGuard guard(entriesLock); for (;;) { auto oldEntries = entries(); ExcAssert(entriesLock.isLockedShared()); std::unique_ptr<Entries> newEntries(new Entries(*oldEntries)); ExcAssertEqual(newEntries->size(), oldEntries->size()); if (entries.cmp_xchg(oldEntries, newEntries, true /* defer */)) { return; } // RCU raced } } bool deleteEntry(const std::string & key) { GcLock::SharedGuard guard(entriesLock); for (;;) { auto oldEntries = entries(); ExcAssert(entriesLock.isLockedShared()); auto it = oldEntries->find(key); if (it == oldEntries->end()) return false; std::unique_ptr<Entries> newEntries(new Entries(*oldEntries)); ExcAssert(newEntries->count(key)); //auto entry = (*newEntries)[key]; newEntries->erase(key); if (entries.cmp_xchg(oldEntries, newEntries, true /* defer */)) { return true; } // RCU raced } } bool forEachEntry(const std::function<bool (std::string, std::string)> & fn) { GcLock::SharedGuard guard(entriesLock); auto es = entries(); for (auto & e: *es) { ExcAssert(entriesLock.isLockedShared()); if (!fn(e.first, e.second)) return false; } return true; } typedef std::map<std::string, std::string> Entries; GcLock entriesLock; RcuProtected<Entries> entries; }; BOOST_AUTO_TEST_CASE( test_one_writer_one_reader ) { Collection1 collection; volatile bool shutdown = false; for (unsigned i = 0; i < 20; ++i) collection.addEntry("item" + to_string(i), std::make_shared<std::string>("hello"), false /* mustAdd */); auto writerThread = [&] () { while (!shutdown) { // Add a random entry collection.addEntry("item" + to_string(random() % 20), std::make_shared<std::string>("hello"), false /* mustAdd */); auto onEntry = [&] (string key, string value) { ExcAssertEqual(value, "hello"); return true; }; // Check that we can iterate them properly collection.forEachEntry(onEntry); // Try to purturb things a bit collection.recycleEntries(); // Now delete a random entry collection.deleteEntry("item" + to_string(random() % 20)); }; cerr << "finished writer thread" << endl; }; auto readerThread = [&] () { while (!shutdown) { auto onEntry = [&] (string key, string value) { ExcAssertEqual(value, "hello"); return true; }; // Check that we can iterate them properly collection.forEachEntry(onEntry); }; cerr << "finished reader thread" << endl; }; std::thread reader(readerThread); std::thread writer(writerThread); ::sleep(5); shutdown = true; reader.join(); writer.join(); } #if 1 BOOST_AUTO_TEST_CASE( test_multithreaded_access ) { Collection1 collection; volatile bool shutdown = false; for (unsigned i = 0; i < 20; ++i) collection.addEntry("item" + to_string(i), std::make_shared<std::string>("hello"), false /* mustAdd */); auto workerThread = [&] () { while (!shutdown) { // Add a random entry collection.addEntry("item" + to_string(random() % 20), std::make_shared<std::string>("hello"), false /* mustAdd */); auto onEntry = [&] (string key, string value) { ExcAssertEqual(value, "hello"); return true; }; // Check that we can iterate them properly collection.forEachEntry(onEntry); // Try to purturb things a bit collection.recycleEntries(); // Now delete a random entry collection.deleteEntry("item" + to_string(random() % 20)); }; cerr << "finished work thread" << endl; }; int numThreads = 10; std::vector<std::thread> threads; for (unsigned i = 0; i < numThreads; ++i) { threads.emplace_back(workerThread); } ::sleep(5); shutdown = true; for (auto & t: threads) t.join(); } #endif
25.95082
80
0.501421
kstepanmpmg
6f0d8852d96eb107a385ea7ca3e1c83189e2f07a
11,150
cpp
C++
tests/GrCCPRTest.cpp
lightbell/skia
37aea440fdb0257a4cffb0b41ab9745a9fc4d4fa
[ "BSD-3-Clause" ]
null
null
null
tests/GrCCPRTest.cpp
lightbell/skia
37aea440fdb0257a4cffb0b41ab9745a9fc4d4fa
[ "BSD-3-Clause" ]
null
null
null
tests/GrCCPRTest.cpp
lightbell/skia
37aea440fdb0257a4cffb0b41ab9745a9fc4d4fa
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #include "Test.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrContextPriv.h" #include "GrClip.h" #include "GrDrawingManager.h" #include "GrPathRenderer.h" #include "GrPaint.h" #include "GrRenderTargetContext.h" #include "GrRenderTargetContextPriv.h" #include "GrShape.h" #include "SkMatrix.h" #include "SkPathPriv.h" #include "SkRect.h" #include "ccpr/GrCoverageCountingPathRenderer.h" #include "mock/GrMockTypes.h" #include <cmath> static constexpr int kCanvasSize = 100; class CCPRClip : public GrClip { public: CCPRClip(GrCoverageCountingPathRenderer* ccpr, const SkPath& path) : fCCPR(ccpr), fPath(path) {} private: bool apply(GrContext* context, GrRenderTargetContext* rtc, bool, bool, GrAppliedClip* out, SkRect* bounds) const override { GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider(); out->addCoverageFP(fCCPR->makeClipProcessor(proxyProvider, rtc->priv().testingOnly_getOpListID(), fPath, SkIRect::MakeWH(rtc->width(), rtc->height()), rtc->width(), rtc->height())); return true; } bool quickContains(const SkRect&) const final { return false; } bool isRRect(const SkRect& rtBounds, SkRRect* rr, GrAA*) const final { return false; } void getConservativeBounds(int width, int height, SkIRect* rect, bool* iior) const final { rect->set(0, 0, width, height); if (iior) { *iior = false; } } GrCoverageCountingPathRenderer* const fCCPR; const SkPath fPath; }; class CCPRPathDrawer { public: CCPRPathDrawer(GrContext* ctx, skiatest::Reporter* reporter) : fCtx(ctx) , fCCPR(fCtx->contextPriv().drawingManager()->getCoverageCountingPathRenderer()) , fRTC(fCtx->contextPriv().makeDeferredRenderTargetContext( SkBackingFit::kExact, kCanvasSize, kCanvasSize, kRGBA_8888_GrPixelConfig, nullptr)) { if (!fCCPR) { ERRORF(reporter, "ccpr not enabled in GrContext for ccpr tests"); } if (!fRTC) { ERRORF(reporter, "failed to create GrRenderTargetContext for ccpr tests"); } } bool valid() const { return fCCPR && fRTC; } void clear() const { fRTC->clear(nullptr, 0, GrRenderTargetContext::CanClearFullscreen::kYes); } void abandonGrContext() { fCtx = nullptr; fCCPR = nullptr; fRTC = nullptr; } void drawPath(SkPath path, GrColor4f color = GrColor4f(0, 1, 0, 1)) const { SkASSERT(this->valid()); GrPaint paint; paint.setColor4f(color); GrNoClip noClip; SkIRect clipBounds = SkIRect::MakeWH(kCanvasSize, kCanvasSize); SkMatrix matrix = SkMatrix::I(); path.setIsVolatile(true); GrShape shape(path); fCCPR->drawPath({fCtx, std::move(paint), &GrUserStencilSettings::kUnused, fRTC.get(), &noClip, &clipBounds, &matrix, &shape, GrAAType::kCoverage, false}); } void clipFullscreenRect(SkPath clipPath, GrColor4f color = GrColor4f(0, 1, 0, 1)) { SkASSERT(this->valid()); GrPaint paint; paint.setColor4f(color); fRTC->drawRect(CCPRClip(fCCPR, clipPath), std::move(paint), GrAA::kYes, SkMatrix::I(), SkRect::MakeIWH(kCanvasSize, kCanvasSize)); } void flush() const { SkASSERT(this->valid()); fCtx->flush(); } private: GrContext* fCtx; GrCoverageCountingPathRenderer* fCCPR; sk_sp<GrRenderTargetContext> fRTC; }; class CCPRTest { public: void run(skiatest::Reporter* reporter) { GrMockOptions mockOptions; mockOptions.fInstanceAttribSupport = true; mockOptions.fMapBufferFlags = GrCaps::kCanMap_MapFlag; mockOptions.fConfigOptions[kAlpha_half_GrPixelConfig].fRenderability = GrMockOptions::ConfigOptions::Renderability::kNonMSAA; mockOptions.fConfigOptions[kAlpha_half_GrPixelConfig].fTexturable = true; mockOptions.fGeometryShaderSupport = true; mockOptions.fIntegerSupport = true; mockOptions.fFlatInterpolationSupport = true; this->customizeMockOptions(&mockOptions); GrContextOptions ctxOptions; ctxOptions.fAllowPathMaskCaching = false; ctxOptions.fGpuPathRenderers = GpuPathRenderers::kCoverageCounting; fMockContext = GrContext::MakeMock(&mockOptions, ctxOptions); if (!fMockContext) { ERRORF(reporter, "could not create mock context"); return; } if (!fMockContext->unique()) { ERRORF(reporter, "mock context is not unique"); return; } CCPRPathDrawer ccpr(fMockContext.get(), reporter); if (!ccpr.valid()) { return; } fPath.moveTo(0, 0); fPath.cubicTo(50, 50, 0, 50, 50, 0); this->onRun(reporter, ccpr); } virtual ~CCPRTest() {} protected: virtual void customizeMockOptions(GrMockOptions*) {} virtual void onRun(skiatest::Reporter* reporter, CCPRPathDrawer& ccpr) = 0; sk_sp<GrContext> fMockContext; SkPath fPath; }; #define DEF_CCPR_TEST(name) \ DEF_GPUTEST(name, reporter, /* options */) { \ name test; \ test.run(reporter); \ } class GrCCPRTest_cleanup : public CCPRTest { void onRun(skiatest::Reporter* reporter, CCPRPathDrawer& ccpr) override { REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); // Ensure paths get unreffed. for (int i = 0; i < 10; ++i) { ccpr.drawPath(fPath); ccpr.clipFullscreenRect(fPath); } REPORTER_ASSERT(reporter, !SkPathPriv::TestingOnly_unique(fPath)); ccpr.flush(); REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); // Ensure paths get unreffed when we delete the context without flushing. for (int i = 0; i < 10; ++i) { ccpr.drawPath(fPath); ccpr.clipFullscreenRect(fPath); } ccpr.abandonGrContext(); REPORTER_ASSERT(reporter, !SkPathPriv::TestingOnly_unique(fPath)); fMockContext.reset(); REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); } }; DEF_CCPR_TEST(GrCCPRTest_cleanup) class GrCCPRTest_cleanupWithTexAllocFail : public GrCCPRTest_cleanup { void customizeMockOptions(GrMockOptions* options) override { options->fFailTextureAllocations = true; } }; DEF_CCPR_TEST(GrCCPRTest_cleanupWithTexAllocFail) class GrCCPRTest_unregisterCulledOps : public CCPRTest { void onRun(skiatest::Reporter* reporter, CCPRPathDrawer& ccpr) override { REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); // Ensure Ops get unregistered from CCPR when culled early. ccpr.drawPath(fPath); REPORTER_ASSERT(reporter, !SkPathPriv::TestingOnly_unique(fPath)); ccpr.clear(); // Clear should delete the CCPR Op. REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); ccpr.flush(); // Should not crash (DrawPathsOp should have unregistered itself). // Ensure Op unregisters work when we delete the context without flushing. ccpr.drawPath(fPath); REPORTER_ASSERT(reporter, !SkPathPriv::TestingOnly_unique(fPath)); ccpr.clear(); // Clear should delete the CCPR DrawPathsOp. REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); ccpr.abandonGrContext(); fMockContext.reset(); // Should not crash (DrawPathsOp should have unregistered itself). } }; DEF_CCPR_TEST(GrCCPRTest_unregisterCulledOps) class GrCCPRTest_parseEmptyPath : public CCPRTest { void onRun(skiatest::Reporter* reporter, CCPRPathDrawer& ccpr) override { REPORTER_ASSERT(reporter, SkPathPriv::TestingOnly_unique(fPath)); // Make a path large enough that ccpr chooses to crop it by the RT bounds, and ends up with // an empty path. SkPath largeOutsidePath; largeOutsidePath.moveTo(-1e30f, -1e30f); largeOutsidePath.lineTo(-1e30f, +1e30f); largeOutsidePath.lineTo(-1e10f, +1e30f); ccpr.drawPath(largeOutsidePath); // Normally an empty path is culled before reaching ccpr, however we use a back door for // testing so this path will make it. SkPath emptyPath; SkASSERT(emptyPath.isEmpty()); ccpr.drawPath(emptyPath); // This is the test. It will exercise various internal asserts and verify we do not crash. ccpr.flush(); // Now try again with clips. ccpr.clipFullscreenRect(largeOutsidePath); ccpr.clipFullscreenRect(emptyPath); ccpr.flush(); // ... and both. ccpr.drawPath(largeOutsidePath); ccpr.clipFullscreenRect(largeOutsidePath); ccpr.drawPath(emptyPath); ccpr.clipFullscreenRect(emptyPath); ccpr.flush(); } }; DEF_CCPR_TEST(GrCCPRTest_parseEmptyPath) class CCPRRenderingTest { public: void run(skiatest::Reporter* reporter, GrContext* ctx) const { if (!ctx->contextPriv().drawingManager()->getCoverageCountingPathRenderer()) { return; // CCPR is not enabled on this GPU. } CCPRPathDrawer ccpr(ctx, reporter); if (!ccpr.valid()) { return; } this->onRun(reporter, ccpr); } virtual ~CCPRRenderingTest() {} protected: virtual void onRun(skiatest::Reporter* reporter, const CCPRPathDrawer& ccpr) const = 0; }; #define DEF_CCPR_RENDERING_TEST(name) \ DEF_GPUTEST_FOR_RENDERING_CONTEXTS(name, reporter, ctxInfo) { \ name test; \ test.run(reporter, ctxInfo.grContext()); \ } class GrCCPRTest_busyPath : public CCPRRenderingTest { void onRun(skiatest::Reporter* reporter, const CCPRPathDrawer& ccpr) const override { static constexpr int kNumBusyVerbs = 1 << 17; ccpr.clear(); SkPath busyPath; busyPath.moveTo(0, 0); // top left busyPath.lineTo(kCanvasSize, kCanvasSize); // bottom right for (int i = 2; i < kNumBusyVerbs; ++i) { float offset = i * ((float)kCanvasSize / kNumBusyVerbs); busyPath.lineTo(kCanvasSize - offset, kCanvasSize + offset); // offscreen } ccpr.drawPath(busyPath); ccpr.flush(); // If this doesn't crash, the test passed. // If it does, maybe fiddle with fMaxInstancesPerDrawArraysWithoutCrashing in // your platform's GrGLCaps. } }; DEF_CCPR_RENDERING_TEST(GrCCPRTest_busyPath) #endif
36.201299
100
0.634978
lightbell
6f10c3ca253ea68208faa87e31d11465acb79831
9,178
hpp
C++
proton-c/bindings/cpp/include/proton/container.hpp
aikchar/qpid-proton
10df4133e8877ee535e24b494738356369dcd24c
[ "Apache-2.0" ]
null
null
null
proton-c/bindings/cpp/include/proton/container.hpp
aikchar/qpid-proton
10df4133e8877ee535e24b494738356369dcd24c
[ "Apache-2.0" ]
null
null
null
proton-c/bindings/cpp/include/proton/container.hpp
aikchar/qpid-proton
10df4133e8877ee535e24b494738356369dcd24c
[ "Apache-2.0" ]
1
2020-12-17T15:47:50.000Z
2020-12-17T15:47:50.000Z
#ifndef PROTON_CONTAINER_HPP #define PROTON_CONTAINER_HPP /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ #include "./fwd.hpp" #include "./types_fwd.hpp" #include "./internal/config.hpp" #include "./internal/export.hpp" #include "./internal/pn_unique_ptr.hpp" #ifdef PN_CPP_HAS_STD_FUNCTION #include <functional> #endif #include <string> namespace proton { /// A top-level container of connections, sessions, senders, and /// receivers. /// /// A container gives a unique identity to each communicating peer. It /// is often a process-level object. /// /// It serves as an entry point to the API, allowing connections, /// senders, and receivers to be established. It can be supplied with /// an event handler in order to intercept important messaging events, /// such as newly received messages or newly issued credit for sending /// messages. class PN_CPP_CLASS_EXTERN container { public: /// Create a container. PN_CPP_EXTERN container(messaging_handler& h, const std::string& id=""); /// Create a container. PN_CPP_EXTERN container(const std::string& id=""); PN_CPP_EXTERN ~container(); /// Connect to `url` and send an open request to the remote peer. /// /// Options are applied to the connection as follows, values in later /// options override earlier ones: /// /// 1. client_connection_options() /// 2. options passed to connect() /// /// The handler in the composed options is used to call /// proton::messaging_handler::on_connection_open() when the remote peer's /// open response is received. PN_CPP_EXTERN returned<connection> connect(const std::string& url, const connection_options &); /// Connect to `url` and send an open request to the remote peer. PN_CPP_EXTERN returned<connection> connect(const std::string& url); /// @cond INTERNAL /// Stop listening on url, must match the url string given to listen(). /// You can also use the proton::listener object returned by listen() PN_CPP_EXTERN void stop_listening(const std::string& url); /// @endcond /// Start listening on url. /// /// Calls to the @ref listen_handler are serialized for this listener, /// but handlers attached to separate listeners may be called concurrently. /// /// @param url identifies a listening url. /// @param lh handles listening events /// @return listener lets you stop listening PN_CPP_EXTERN listener listen(const std::string& url, listen_handler& lh); /// Listen with a fixed set of options for all accepted connections. /// See listen(const std::string&, listen_handler&) PN_CPP_EXTERN listener listen(const std::string& url, const connection_options&); /// Start listening on URL. /// New connections will use the handler from server_connection_options() PN_CPP_EXTERN listener listen(const std::string& url); /// Run the container in this thread. /// Returns when the container stops. /// @see auto_stop() and stop(). /// /// With a multithreaded container, call run() in multiple threads to create a thread pool. PN_CPP_EXTERN void run(); /// If true, stop the container when all active connections and listeners are closed. /// If false the container will keep running till stop() is called. /// /// auto_stop is set by default when a new container is created. PN_CPP_EXTERN void auto_stop(bool); /// **Experimental** - Stop the container with an error_condition /// err. /// /// - Abort all open connections and listeners. /// - Process final handler events and injected functions /// - If `!err.empty()`, handlers will receive on_transport_error /// - run() will return in all threads. PN_CPP_EXTERN void stop(const error_condition& err); /// **Experimental** - Stop the container with an empty error /// condition. /// /// @see stop(const error_condition&) PN_CPP_EXTERN void stop(); /// Open a connection and sender for `url`. PN_CPP_EXTERN returned<sender> open_sender(const std::string &url); /// Open a connection and sender for `url`. /// /// Supplied sender options will override the container's /// template options. PN_CPP_EXTERN returned<sender> open_sender(const std::string &url, const proton::sender_options &o); /// Open a connection and sender for `url`. /// /// Supplied connection options will override the /// container's template options. PN_CPP_EXTERN returned<sender> open_sender(const std::string &url, const connection_options &c); /// Open a connection and sender for `url`. /// /// Supplied sender or connection options will override the /// container's template options. PN_CPP_EXTERN returned<sender> open_sender(const std::string &url, const proton::sender_options &o, const connection_options &c); /// Open a connection and receiver for `url`. PN_CPP_EXTERN returned<receiver> open_receiver(const std::string&url); /// Open a connection and receiver for `url`. /// /// Supplied receiver options will override the container's /// template options. PN_CPP_EXTERN returned<receiver> open_receiver(const std::string&url, const proton::receiver_options &o); /// Open a connection and receiver for `url`. /// /// Supplied receiver or connection options will override the /// container's template options. PN_CPP_EXTERN returned<receiver> open_receiver(const std::string&url, const connection_options &c); /// Open a connection and receiver for `url`. /// /// Supplied receiver or connection options will override the /// container's template options. PN_CPP_EXTERN returned<receiver> open_receiver(const std::string&url, const proton::receiver_options &o, const connection_options &c); /// A unique identifier for the container. PN_CPP_EXTERN std::string id() const; /// Connection options that will be to outgoing connections. These /// are applied first and overriden by options provided in /// connect() and messaging_handler::on_connection_open(). PN_CPP_EXTERN void client_connection_options(const connection_options &); /// @copydoc client_connection_options PN_CPP_EXTERN connection_options client_connection_options() const; /// Connection options that will be applied to incoming /// connections. These are applied first and overridden by options /// provided in listen(), listen_handler::on_accept() and /// messaging_handler::on_connection_open(). PN_CPP_EXTERN void server_connection_options(const connection_options &); /// @copydoc server_connection_options PN_CPP_EXTERN connection_options server_connection_options() const; /// Sender options applied to senders created by this /// container. They are applied before messaging_handler::on_sender_open() /// and can be overridden. PN_CPP_EXTERN void sender_options(const class sender_options &); /// @copydoc sender_options PN_CPP_EXTERN class sender_options sender_options() const; /// Receiver options applied to receivers created by this /// container. They are applied before messaging_handler::on_receiver_open() /// and can be overridden. PN_CPP_EXTERN void receiver_options(const class receiver_options &); /// @copydoc receiver_options PN_CPP_EXTERN class receiver_options receiver_options() const; /// Schedule a function to be called after the duration. C++03 /// compatible, for C++11 use schedule(duration, /// std::function<void()>) PN_CPP_EXTERN void schedule(duration, void_function0&); #if PN_CPP_HAS_STD_FUNCTION /// Schedule a function to be called after the duration PN_CPP_EXTERN void schedule(duration, std::function<void()>); #endif private: class impl; internal::pn_unique_ptr<impl> impl_; friend class connection_options; friend class session_options; friend class receiver_options; friend class sender_options; }; } // proton #endif // PROTON_CONTAINER_HPP
38.563025
99
0.686097
aikchar
6f113c7ceaf012d43d811725ee60a28738cd04cf
67,271
cpp
C++
frameworks/av/media/libcedarx/android_adapter/awplayer/awplayer.cpp
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
10
2020-04-17T04:02:36.000Z
2021-11-23T11:38:42.000Z
frameworks/av/media/libcedarx/android_adapter/awplayer/awplayer.cpp
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
3
2020-02-19T16:53:25.000Z
2021-04-29T07:28:40.000Z
frameworks/av/media/libcedarx/android_adapter/awplayer/awplayer.cpp
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
5
2019-12-25T04:05:02.000Z
2022-01-14T16:57:55.000Z
/* * Copyright (c) 2008-2016 Allwinner Technology Co. Ltd. * All rights reserved. * * File : awplayer.cpp * Description : mediaplayer adapter for operator * History : * Author : AL3 * Date : 2015/05/05 * Comment : first version * */ #define LOG_TAG "awplayer" #include "cdx_log.h" #include "awplayer.h" #include "subtitleUtils.h" #include "awStreamingSource.h" #include <string.h> #include <media/Metadata.h> #include <media/mediaplayer.h> #include <binder/IPCThreadState.h> #include <media/IAudioFlinger.h> #include <fcntl.h> #include <cutils/properties.h> // for property_get #include <hardware/hwcomposer.h> #include <version.h> #include "xplayer.h" #include "player.h" #include "mediaInfo.h" #include "AwMessageQueue.h" #include "awLogRecorder.h" #include "AwHDCPModule.h" #include "outputCtrl.h" #include "awLogRecorder.h" #include "cdx_config.h" #include "soundControl.h" //wasu livemode4 , apk set seekTo after start, we should call start after seek #define CMCC_LIVEMODE_4_BUG (1) // the cmcc apk bug, change channel when buffering icon is displayed, // the buffering icon is not diappered, so we send a buffer end message in prepare/prepareAsync #define BUFFERING_ICON_BUG (1) // pause then start to display, the cmcc apk call seekTo, it will flush the buffering cache(livemod) // or seek some frames in cache ( vod) , it will discontinue #define PAUSE_THEN_SEEK_BUG (1) #if (!((CONF_ANDROID_MAJOR_VER == 4)&&(CONF_ANDROID_SUB_VER == 2))) //* android 4.4 use IGraphicBufferProducer instead of ISurfaceTexture in android 4.2. #include <gui/IGraphicBufferProducer.h> #include <gui/Surface.h> #endif static const char *WASU_APP_NAME = "net.sunniwell.app.ott.chinamobile"; static const char *CMCC_LOCAL_APP_NAME = "net.sunniwell.app.swplayer"; static const char *TVD_FILE_MANAGER_APP_NAME = "com.softwinner.TvdFileManager"; // static const char *MANGGUO_APP_NAME = "com.starcor.hunan"; static int XPlayerCallbackProcess(void* pUser, int eMessageId, int ext1, void* ext2); static int GetCallingApkName(char* strApkName, int nMaxNameSize); static int SubCallbackProcess(void* pUser, int eMessageId, void* param); typedef struct PlayerPriData { XPlayer* mXPlayer; XPlayerConfig_t mConfigInfo; uid_t mUID; //* no use. //* surface. #if (!((CONF_ANDROID_MAJOR_VER == 4)&&(CONF_ANDROID_SUB_VER == 2))) //* android 4.4 use IGraphicBufferProducer instead of ISurfaceTexture in android 4.2. sp<IGraphicBufferProducer> mGraphicBufferProducer; #else sp<ISurfaceTexture> mSurfaceTexture; #endif sp<ANativeWindow> mNativeWindow; LayerCtrl* mlc; char strApkName[128]; #if (CONF_ANDROID_MAJOR_VER >= 5) sp<IMediaHTTPService> mHTTPService; #endif //* record the id of subtitle which is displaying //* we set the Nums to 64 .(32 may be not enough) unsigned int mSubtitleDisplayIds[64]; int mSubtitleDisplayIdsUpdateIndex; //* note whether the sutitle is in text or in bitmap format. int mIsSubtitleInTextFormat; //* text codec format of the subtitle, used to transform subtitle text to //* utf8 when the subtitle text codec format is unknown. char mDefaultTextFormat[32]; //* whether enable subtitle show. int mIsSubtitleDisable; //* file descriptor of .idx file of index+sub subtitle. //* we save the .idx file's fd here because application set .idx file and .sub file //* seperately, we need to wait for the .sub file's fd, see //* INVOKE_ID_ADD_EXTERNAL_SOURCE_FD command in invoke() method. int mIndexFileHasBeenSet; int mIndexFileFdOfIndexSubtitle; //* save the currentSelectTrackIndex; int mCurrentSelectVidoeTrackIndex; int mCurrentSelectAudioTrackIndex; int mCurrentSelectSubTrackIndex; AwLogRecorder* mLogRecorder; int mbIsDiagnose; int64_t mPlayTimeMs; int64_t mBufferTimeMs; int mFirstStart; int mKeepLastFrame; static int contentID; int dupContentID; }PlayerPriData; static int resumeMediaScanner(const char* strApkName) { CEDARX_UNUSE(strApkName); return property_set("mediasw.stopscaner", "0"); } static int pauseMediaScanner(const char* strApkName) { CEDARX_UNUSE(strApkName); return property_set("mediasw.stopscaner", "1"); } void enableMediaBoost(MediaInfo* mi); void disableMediaBoost(); AwPlayer::Instance AwPlayer::instance = {0, PTHREAD_MUTEX_INITIALIZER}; int PlayerPriData::contentID = time(NULL); AwPlayer::AwPlayer() { logd("AwPlayer construct."); pthread_mutex_lock(&instance.lock); instance.count++; pthread_mutex_unlock(&instance.lock); mPriData = (PlayerPriData*)malloc(sizeof(PlayerPriData)); memset(mPriData,0x00,sizeof(PlayerPriData)); mPriData->mLogRecorder = NULL; mPriData->mIsSubtitleDisable = 1; #if (!((CONF_ANDROID_MAJOR_VER == 4)&&(CONF_ANDROID_SUB_VER == 2))) //* android 4.4 use IGraphicBufferProducer instead of ISurfaceTexture in android 4.2. mPriData->mGraphicBufferProducer = NULL; #else mPriData->mSurfaceTexture = NULL; #endif mPriData->mNativeWindow = NULL; mPriData->mKeepLastFrame = 0; GetCallingApkName(mPriData->strApkName, sizeof(mPriData->strApkName)); mPriData->mXPlayer = XPlayerCreate(); if(mPriData->mXPlayer != NULL) { struct HdcpOpsS hdcpOps; hdcpOps.init = HDCP_Init; hdcpOps.deinit = HDCP_Deinit; hdcpOps.decrypt = HDCP_Decrypt; XPlayerSetHdcpOps(mPriData->mXPlayer, &hdcpOps); XPlayerSetNotifyCallback(mPriData->mXPlayer, XPlayerCallbackProcess, this); SubCtrl* pSubCtrl = NULL; if (!strcmp(mPriData->strApkName, CMCC_LOCAL_APP_NAME)) pSubCtrl = SubNativeRenderCreate(); else pSubCtrl = SubtitleCreate(SubCallbackProcess, this); XPlayerSetSubCtrl(mPriData->mXPlayer, pSubCtrl); Deinterlace* di = DeinterlaceCreate(); XPlayerSetDeinterlace(mPriData->mXPlayer, di); } mPriData->mFirstStart = 1; strcpy(mPriData->mDefaultTextFormat, "GBK"); //* clear the mSubtitleDisplayIds memset(mPriData->mSubtitleDisplayIds,0xff,64*sizeof(unsigned int)); mPriData->mSubtitleDisplayIdsUpdateIndex = 0; mPriData->dupContentID = mPriData->contentID++; } AwPlayer::~AwPlayer() { if(mPriData->mLogRecorder) { AwLogRecorderDestroy(mPriData->mLogRecorder); mPriData->mLogRecorder = NULL; } if(mPriData->mXPlayer != NULL) XPlayerDestroy(mPriData->mXPlayer); free(mPriData); mPriData = NULL; pthread_mutex_lock(&instance.lock); instance.count--; if (instance.count == 0) disableMediaBoost(); pthread_mutex_unlock(&instance.lock); logd("~AwPlayer"); } status_t AwPlayer::initCheck() { logv("initCheck"); if(mPriData->mXPlayer == NULL) { loge("initCheck() fail, XPlayer::mplayer = %p", mPriData->mXPlayer); return NO_INIT; } return (status_t)XPlayerInitCheck(mPriData->mXPlayer); } status_t AwPlayer::setUID(uid_t uid) { logv("setUID(), uid = %d", uid); mPriData->mUID = uid; return OK; } static int cmccParseHeaders(CdxKeyedVectorT **header, const KeyedVector<String8, String8>* pHeaders) { int nHeaderSize; int i; if (pHeaders == NULL) return 0; //*remove "x-hide-urls-from-log" ? nHeaderSize = pHeaders->size(); if (nHeaderSize <= 0) return -1; *header = CdxKeyedVectorCreate(nHeaderSize); if (*header == NULL) { logw("CdxKeyedVectorCreate() failed"); return -1; } String8 key; String8 value; for (i = 0; i < nHeaderSize; i++) { key = pHeaders->keyAt(i); value = pHeaders->valueAt(i); if (CdxKeyedVectorAdd(*header, key.string(), value.string()) != 0) { CdxKeyedVectorDestroy(*header); return -1; } } return 0; } #if (CONF_ANDROID_MAJOR_VER >= 5) status_t AwPlayer::setDataSource(const sp<IMediaHTTPService> &httpService, const char* pUrl, const KeyedVector<String8, String8>* pHeaders) #else status_t AwPlayer::setDataSource(const char* pUrl, const KeyedVector<String8, String8>* pHeaders) #endif { logd("setDataSource(url), url='%s'", pUrl); void* pHttpService = NULL; CdxKeyedVectorT* header = NULL; #if (CONF_ANDROID_MAJOR_VER >= 5) pHttpService = (void*)httpService.get(); #endif int ret = cmccParseHeaders(&header, pHeaders); if (ret < 0) { loge("parse Headers failed."); return NO_MEMORY; } int livemode; if(strstr(pUrl, "livemode=1")) { livemode = 1; } else if(strstr(pUrl, "livemode=2")) { livemode = 2; } else if(strstr(pUrl, "livemode=4")) { livemode = 4; } else { livemode = 0; } if (strstr(pUrl, "diagnose=deep")) { logd("In cmcc deep diagnose"); mPriData->mbIsDiagnose = 1; } else { mPriData->mbIsDiagnose = 0; } mPriData->mConfigInfo.livemode = livemode; if (!strcmp(mPriData->strApkName, WASU_APP_NAME)) mPriData->mConfigInfo.appType = APP_CMCC_WASU; else mPriData->mConfigInfo.appType = APP_DEFAULT; mPriData->mLogRecorder = NULL; #if defined(CONF_CMCC) mPriData->mLogRecorder = AwLogRecorderCreate(); #endif if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; snprintf(cmccLog, sizeof(cmccLog), "[info][%s %s %d]setDataSource, url: %s", LOG_TAG, __FUNCTION__, __LINE__, pUrl); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); snprintf(cmccLog, sizeof(cmccLog), "[info][%s %s %d]create a new player", LOG_TAG, __FUNCTION__, __LINE__); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } XPlayerConfig(mPriData->mXPlayer, &mPriData->mConfigInfo); XPlayerSetDataSourceUrl(mPriData->mXPlayer, pUrl, pHttpService, header); CdxKeyedVectorDestroy(header); return OK; } //* Warning: The filedescriptor passed into this method will only be valid until //* the method returns, if you want to keep it, dup it! status_t AwPlayer::setDataSource(int fd, int64_t offset, int64_t length) { int ret; if (!strcmp(mPriData->strApkName, CMCC_LOCAL_APP_NAME)) mPriData->mConfigInfo.appType = APP_CMCC_LOCAL; else if (!strcmp(mPriData->strApkName, TVD_FILE_MANAGER_APP_NAME)) mPriData->mConfigInfo.appType = APP_TVD_FILE_MANAGER; else mPriData->mConfigInfo.appType = APP_DEFAULT; XPlayerConfig(mPriData->mXPlayer, &mPriData->mConfigInfo); ret = XPlayerSetDataSourceFd(mPriData->mXPlayer, fd, offset, length); return (status_t)ret; } status_t AwPlayer::setDataSource(const sp<IStreamSource> &source) { int ret; logd("setDataSource(IStreamSource)"); unsigned int numBuffer, bufferSize; const char *suffix = ""; if(!strcmp(mPriData->strApkName, "com.hpplay.happyplay.aw")) { numBuffer = 32; bufferSize = 32*1024; suffix = ".awts"; } else if(!strcmp(mPriData->strApkName, "com.softwinner.miracastReceiver")) { numBuffer = 1024; bufferSize = 188*8; suffix = ".ts"; } else { CDX_LOGW("this type is unknown."); numBuffer = 16; bufferSize = 4*1024; } CdxStreamT *stream = StreamingSourceOpen(source, numBuffer, bufferSize); if(stream == NULL) { loge("StreamingSourceOpen fail!"); return UNKNOWN_ERROR; } char str[128]; sprintf(str, "customer://%p%s",stream, suffix); //* send a set data source message. mPriData->mConfigInfo.appType = APP_STREAMING; XPlayerConfig(mPriData->mXPlayer, &mPriData->mConfigInfo); ret = XPlayerSetDataSourceStream(mPriData->mXPlayer, str); return (status_t)ret; } #if (!((CONF_ANDROID_MAJOR_VER == 4)&&(CONF_ANDROID_SUB_VER == 2))) //* android 4.4 use IGraphicBufferProducer instead of ISurfaceTexture in android 4.2. status_t AwPlayer::setVideoSurfaceTexture(const sp<IGraphicBufferProducer>& bufferProducer) #else status_t AwPlayer::setVideoSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) #endif { int ret; sp<ANativeWindow> anw; logd("process message AWPLAYER_COMMAND_SET_SURFACE."); //* set native window before delete the old one. //* because the player's render thread may use the old surface //* before it receive the new surface. #if (!((CONF_ANDROID_MAJOR_VER == 4)&&(CONF_ANDROID_SUB_VER == 2))) if(bufferProducer.get() != NULL) anw = new Surface(bufferProducer); #else if(surfaceTexture.get() != NULL) anw = new SurfaceTextureClient(surfaceTexture); #endif else anw = NULL; if(anw == NULL) { logd("anw=NULL"); //not return but go ahead, in order to return the buffers owned by gpu. } if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]setVideoSurfaceTexture", LOG_TAG, __FUNCTION__, __LINE__); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } if(mPriData->mlc == NULL) mPriData->mlc = LayerCreate(); LayerControl(mPriData->mlc, CDX_LAYER_CMD_SET_NATIVE_WINDOW, (anw == NULL) ? NULL : anw.get()); ret = XPlayerSetVideoSurfaceTexture(mPriData->mXPlayer, mPriData->mlc); //* save the new surface. #if (!((CONF_ANDROID_MAJOR_VER == 4)&&(CONF_ANDROID_SUB_VER == 2))) mPriData->mGraphicBufferProducer = bufferProducer; #else mPriData->mSurfaceTexture = surfaceTexture; #endif if(mPriData->mNativeWindow != NULL) native_window_api_disconnect(mPriData->mNativeWindow.get(), NATIVE_WINDOW_API_MEDIA); mPriData->mNativeWindow = anw; return (status_t)ret; } void AwPlayer::setAudioSink(const sp<AudioSink> &audioSink) { logv("setAudioSink"); SoundCtrl* sc = SoundDeviceCreate(audioSink.get()); //SoundCtrl* sc = DefaultSoundDeviceCreate(); XPlayerSetAudioSink(mPriData->mXPlayer, sc); //* super class MediaPlayerInterface has mAudioSink. MediaPlayerInterface::setAudioSink(audioSink); return; } #if defined(CONF_PLAY_RATE) status_t AwPlayer::setPlaybackSettings(const AudioPlaybackRate &rate) { XAudioPlaybackRate xrate; xrate.mSpeed = rate.mSpeed; xrate.mPitch= rate.mPitch; xrate.mStretchMode= (XAudioTimestretchStretchMode)rate.mStretchMode; xrate.mFallbackMode= (XAudioTimestretchFallbackMode)rate.mFallbackMode; int ret=XPlayerSetPlaybackSettings(mPriData->mXPlayer,&xrate); return ret; } status_t AwPlayer::getPlaybackSettings(AudioPlaybackRate *rate) { XAudioPlaybackRate xrate; XPlayerGetPlaybackSettings(mPriData->mXPlayer,&xrate); rate->mSpeed = xrate.mSpeed; rate->mPitch = xrate.mPitch; rate->mStretchMode = (AudioTimestretchStretchMode)xrate.mStretchMode; rate->mFallbackMode = (AudioTimestretchFallbackMode)xrate.mFallbackMode; return 0; } #endif status_t AwPlayer::prepareAsync() { int ret; logd("prepareAsync"); char prop_value[512]; int displayRatio = 1; //* set scaling mode by default setting. property_get("epg.default_screen_ratio", prop_value, "1"); if(atoi(prop_value) == 0) { logd("++++++++ IPTV_PLAYER_CONTENTMODE_LETTERBOX"); displayRatio = 0; } else { logd( "+++++++ IPTV_PLAYER_CONTENTMODE_FULL"); displayRatio = 1; } #if defined(CONF_PRODUCT_STB) if(mPriData->mNativeWindow != NULL) { mPriData->mNativeWindow.get()->perform(mPriData->mNativeWindow.get(), NATIVE_WINDOW_SETPARAMETER, DISPLAY_CMD_SETSCREENRADIO, displayRatio); } #endif struct timeval tv; int64_t startTimeMs = 0; int64_t endTimeMs; if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]prepareAysnc start", LOG_TAG, __FUNCTION__, __LINE__); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); gettimeofday(&tv, NULL); startTimeMs = (tv.tv_sec * 1000000ll + tv.tv_usec)/1000; } ret = XPlayerPrepareAsync(mPriData->mXPlayer); if(0 == ret && mPriData->mLogRecorder != NULL) { gettimeofday(&tv, NULL); endTimeMs = (tv.tv_sec * 1000000ll + tv.tv_usec)/1000; char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]Playback is ready, spend time: %lldms", LOG_TAG, __FUNCTION__, __LINE__, (long long int)(endTimeMs - startTimeMs)); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } return (status_t)ret; } status_t AwPlayer::prepare() { int ret; logd("prepare"); char prop_value[512]; int displayRatio = 1; //* set scaling mode by default setting. property_get("epg.default_screen_ratio", prop_value, "1"); if(atoi(prop_value) == 0) { logd("++++++++ IPTV_PLAYER_CONTENTMODE_LETTERBOX"); displayRatio = 0; } else { logd( "+++++++ IPTV_PLAYER_CONTENTMODE_FULL"); displayRatio = 1; } #if defined(CONF_PRODUCT_STB) if(mPriData->mNativeWindow != NULL) { mPriData->mNativeWindow.get()->perform(mPriData->mNativeWindow.get(), NATIVE_WINDOW_SETPARAMETER, DISPLAY_CMD_SETSCREENRADIO, displayRatio); } #endif ret = XPlayerPrepare(mPriData->mXPlayer); return (status_t)ret; } status_t AwPlayer::start() { int ret; MediaInfo* mi; logd("start"); pauseMediaScanner(mPriData->strApkName); mi = XPlayerGetMediaInfo(mPriData->mXPlayer); enableMediaBoost(mi); mPriData->mCurrentSelectVidoeTrackIndex = 0; mPriData->mCurrentSelectAudioTrackIndex = mi->nVideoStreamNum; mPriData->mCurrentSelectSubTrackIndex = mi->nVideoStreamNum + mi->nAudioStreamNum; // for livemode 4, cmcc apk invoke start before seekTo, // it will get a frame between start and seekTo, #if CMCC_LIVEMODE_4_BUG if(mPriData->mConfigInfo.livemode == 4 && mPriData->mFirstStart && mPriData->mConfigInfo.appType == APP_CMCC_WASU) { return 0; } #endif ret = XPlayerStart(mPriData->mXPlayer); if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]start", LOG_TAG, __FUNCTION__, __LINE__); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); struct timeval tv; gettimeofday(&tv, NULL); mPriData->mPlayTimeMs = (tv.tv_sec * 1000000ll + tv.tv_usec)/1000; } return (status_t)ret; } status_t AwPlayer::stop() { int ret; if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]stop", LOG_TAG, __FUNCTION__, __LINE__); logd("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]destory this player", LOG_TAG, __FUNCTION__, __LINE__); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } ret = XPlayerStop(mPriData->mXPlayer); if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]Playback end", LOG_TAG, __FUNCTION__, __LINE__); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } //* clear the mSubtitleDisplayIds memset(mPriData->mSubtitleDisplayIds,0xff,64*sizeof(unsigned int)); mPriData->mSubtitleDisplayIdsUpdateIndex = 0; return (status_t)ret; } status_t AwPlayer::pause() { int ret; logd(" pause "); if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]pause", LOG_TAG, __FUNCTION__, __LINE__); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } ret = XPlayerPause(mPriData->mXPlayer); return (status_t)ret; } status_t AwPlayer::seekTo(int nSeekTimeMs) { logd("==== seekTo"); int ret; if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]seekTo, totime: %dms", LOG_TAG, __FUNCTION__, __LINE__, nSeekTimeMs); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } #if CMCC_LIVEMODE_4_BUG //for livemode4 , apk set seekTo after start, we should call start after seek if(mPriData->mConfigInfo.livemode == 4 && mPriData->mFirstStart && mPriData->mConfigInfo.appType == APP_CMCC_WASU) { int status; mPriData->mFirstStart = 0; status = XPlayerSeekTo(mPriData->mXPlayer, nSeekTimeMs); XPlayerStart(mPriData->mXPlayer); return status; } #endif /* 用户seek到约最后一秒,我们认为用户真正的意图是seek到最后,相关的bug有三个: * * 1. 某些parser内部的duration单位是微妙,比如60000123 us,上报给应用的 * duration是毫秒,比如60000 ms,在“舍入”或“只舍不入”的影响下,应用始终无法 * seek到最后;由于关键帧位置的影响,又退回前面。 * * 2. yunos上的应用在seek到最后时,把duration - 1000 ms作为seekto的位置。在 * HLS不开启切片内seek时,会seek到duration - 10 * 1000 ms的位置,此现象被当 * 成bug报出来 * * 3. cmcc本地播放器舍去了duration里小于1秒的零头,导致无法seek到最后。测试 * 关键帧间隔较大的mp4视频,会反复退回到离末尾较远的位置,会被当成seek失败 */ if (mPriData->mConfigInfo.livemode == 0) { int dura = 0; ret = XPlayerGetDuration(mPriData->mXPlayer, &dura); int n = nSeekTimeMs + 1000; if (ret == 0 && dura > 0 && n >= dura) { logd("change seek position from %d to %d", nSeekTimeMs, n); nSeekTimeMs = n; } } ret = XPlayerSeekTo(mPriData->mXPlayer, nSeekTimeMs); if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]seek complete", LOG_TAG, __FUNCTION__, __LINE__); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } return (status_t)ret; } status_t AwPlayer::reset() { int ret; logd("... reset"); resumeMediaScanner(mPriData->strApkName); ret = XPlayerReset(mPriData->mXPlayer); //* clear suface. if(mPriData->mKeepLastFrame == 0) { if(mPriData->mNativeWindow != NULL) native_window_api_disconnect(mPriData->mNativeWindow.get(), NATIVE_WINDOW_API_MEDIA); mPriData->mNativeWindow.clear(); #if (!((CONF_ANDROID_MAJOR_VER == 4)&&(CONF_ANDROID_SUB_VER == 2))) mPriData->mGraphicBufferProducer.clear(); #else mPriData->mSurfaceTexture.clear(); #endif } //* clear audio sink. mAudioSink.clear(); //* clear the mSubtitleDisplayIds memset(mPriData->mSubtitleDisplayIds,0xff,64*sizeof(unsigned int)); mPriData->mSubtitleDisplayIdsUpdateIndex = 0; return (status_t)ret; } status_t AwPlayer::setSpeed(int nSpeed) { int ret; ret = XPlayerSetSpeed(mPriData->mXPlayer, nSpeed); return (status_t)ret; } bool AwPlayer::isPlaying() { int ret; ret = XPlayerIsPlaying(mPriData->mXPlayer); return (ret == 1)? true : false; } status_t AwPlayer::getCurrentPosition(int* msec) { int ret; ret = XPlayerGetCurrentPosition(mPriData->mXPlayer, msec); if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]current playtime: %dms", LOG_TAG, __FUNCTION__, __LINE__, *msec); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } return (status_t)ret; } status_t AwPlayer::getDuration(int *msec) { int ret; ret = XPlayerGetDuration(mPriData->mXPlayer, msec); return (status_t)ret; } status_t AwPlayer::setLooping(int loop) { int ret; ret = XPlayerSetLooping(mPriData->mXPlayer, loop); return (status_t)ret; } player_type AwPlayer::playerType() { logv("playerType"); return AW_PLAYER; } status_t AwPlayer::invoke(const Parcel &request, Parcel *reply) { int nMethodId; int ret; MediaInfo* mi; logv("invoke()"); ret = request.readInt32(&nMethodId); if(ret != OK) return ret; mi = XPlayerGetMediaInfo(mPriData->mXPlayer); switch(nMethodId) { case INVOKE_ID_GET_TRACK_INFO: //* get media stream counts. { logv("invode::INVOKE_ID_GET_TRACK_INFO"); if(mi == NULL) { return NO_INIT; } else { int i; int nTrackCount; const char* lang; nTrackCount = mi->nVideoStreamNum + mi->nAudioStreamNum + mi->nSubtitleStreamNum; #if AWPLAYER_CONFIG_DISABLE_VIDEO nTrackCount -= mi->nVideoStreamNum; #endif #if AWPLAYER_CONFIG_DISABLE_AUDIO nTrackCount -= mi->nAudioStreamNum; #endif #if AWPLAYER_CONFIG_DISABLE_SUBTITLE nTrackCount -= mi->nSubtitleStreamNum; #endif reply->writeInt32(nTrackCount); #if !AWPLAYER_CONFIG_DISABLE_VIDEO for(i=0; i<mi->nVideoStreamNum; i++) { reply->writeInt32(2); reply->writeInt32(MEDIA_TRACK_TYPE_VIDEO); #if (CONF_ANDROID_MAJOR_VER >= 6) reply->writeString16(String16("video/")); #endif lang = " "; reply->writeString16(String16(lang)); } #endif #if !AWPLAYER_CONFIG_DISABLE_AUDIO for(i=0; i<mi->nAudioStreamNum; i++) { reply->writeInt32(2); reply->writeInt32(MEDIA_TRACK_TYPE_AUDIO); #if (CONF_ANDROID_MAJOR_VER >= 6) reply->writeString16(String16("audio/")); #endif if(mi->pAudioStreamInfo[i].strLang[0] != 0) { lang = (const char*)mi->pAudioStreamInfo[i].strLang; reply->writeString16(String16(lang)); } else { lang = ""; reply->writeString16(String16(lang)); } } #endif #if !AWPLAYER_CONFIG_DISABLE_SUBTITLE for(i=0; i<mi->nSubtitleStreamNum; i++) { reply->writeInt32(2); reply->writeInt32(MEDIA_TRACK_TYPE_TIMEDTEXT); #if (CONF_ANDROID_MAJOR_VER >= 6) reply->writeString16(String16("text/3gpp-tt")); #endif if (mi->pSubtitleStreamInfo[i].strLang[0] != 0) { lang = (const char*)mi->pSubtitleStreamInfo[i].strLang; reply->writeString16(String16(lang)); } else { lang = ""; reply->writeString16(String16(lang)); } } #endif return OK; } } case INVOKE_ID_ADD_EXTERNAL_SOURCE: case INVOKE_ID_ADD_EXTERNAL_SOURCE_FD: { logd("=== INVOKE_ID_ADD_EXTERNAL_SOURCE"); int fd; int64_t nOffset; int64_t nLength; int fdSub; if(nMethodId == INVOKE_ID_ADD_EXTERNAL_SOURCE) { //* string values written in Parcel are UTF-16 values. String8 uri(request.readString16()); String8 mimeType(request.readString16()); //* if mimeType == "application/sub" and mIndexFileHasBeenSet == 0, //* the .sub file is a common .sub subtitle, not index+sub subtitle. if(strcmp((char*)mimeType.string(), "application/sub") == 0 && mPriData->mIndexFileHasBeenSet == 1) { //* the .sub file of index+sub subtitle. //* no need to use the .sub file url, because subtitle decoder will //* find the .sub file by itself by using the .idx file's url. //* mimetype "application/sub" is defined in //* "android/base/media/java/android/media/MediaPlayer.java". //* clear the flag for adding more subtitle. mPriData->mIndexFileHasBeenSet = 0; return OK; } else if(strcmp((char*)mimeType.string(), "application/idx+sub") == 0) { //* set this flag to process the .sub file passed in at next call. mPriData->mIndexFileHasBeenSet = 1; } //* probe subtitle info XPlayerSetExternalSubUrl(mPriData->mXPlayer, uri.string()); } else { fd = request.readFileDescriptor(); nOffset = request.readInt64(); nLength = request.readInt64(); fdSub = -1; String8 mimeType(request.readString16()); //* if mimeType == "application/sub" and mIndexFileHasBeenSet == 0, //* the .sub file is a common .sub subtitle, not index+sub subtitle. if(strcmp((char*)mimeType.string(), "application/idx-sub") == 0) { //* the .idx file of index+sub subtitle. mPriData->mIndexFileFdOfIndexSubtitle = dup(fd); mPriData->mIndexFileHasBeenSet = 1; return OK; } else if(strcmp((char*)mimeType.string(), "application/sub") == 0 && mPriData->mIndexFileHasBeenSet == 1) { //* the .sub file of index+sub subtitle. //* for index+sub subtitle, PlayerProbeSubtitleStreamInfoFd() method need //* the .idx file's descriptor for probe. fdSub = fd; //* save the .sub file's descriptor to fdSub. //* set the .idx file's descriptor to fd. fd = mPriData->mIndexFileFdOfIndexSubtitle; mPriData->mIndexFileFdOfIndexSubtitle = -1; mPriData->mIndexFileHasBeenSet = 0;//* clear the flag for adding more subtitle. } //* probe subtitle info XPlayerSetExternalSubFd(mPriData->mXPlayer, fd,nOffset,nLength, fdSub); } break; } case INVOKE_ID_SELECT_TRACK: case INVOKE_ID_UNSELECT_TRACK: { int nStreamIndex; int nTrackCount; nStreamIndex = request.readInt32(); logd("invode::INVOKE_ID_SELECT_TRACK, stream index = %d", nStreamIndex); if(mi == NULL) { loge("can not switch audio or subtitle, there is no media stream."); return NO_INIT; } nTrackCount = mi->nVideoStreamNum + mi->nAudioStreamNum + mi->nSubtitleStreamNum; if(nTrackCount == 0) { loge("can not switch audio or subtitle, there is no media stream."); return NO_INIT; } if(nStreamIndex >= mi->nVideoStreamNum && nStreamIndex < (mi->nVideoStreamNum + mi->nAudioStreamNum)) { if(nMethodId == INVOKE_ID_SELECT_TRACK) { //* switch audio. mPriData->mCurrentSelectAudioTrackIndex = nStreamIndex; nStreamIndex -= mi->nVideoStreamNum; if(XPlayerSwitchAudio(mPriData->mXPlayer, nStreamIndex) != 0) { loge("can not switch audio, call PlayerSwitchAudio() return fail."); return UNKNOWN_ERROR; } } else { mPriData->mCurrentSelectAudioTrackIndex = -1; loge("Deselect an audio track (%d) is not supported", nStreamIndex); return INVALID_OPERATION; } return OK; } else if(nStreamIndex >= (mi->nVideoStreamNum + mi->nAudioStreamNum) && nStreamIndex < nTrackCount) { if(nMethodId == INVOKE_ID_SELECT_TRACK) { logv("==== INVOKE_ID_SELECT_TRACK, nStreamIndex: %d", nStreamIndex); //* enable subtitle. mPriData->mIsSubtitleDisable = 0; mPriData->mCurrentSelectSubTrackIndex = nStreamIndex; //* switch subtitle. nStreamIndex -= (mi->nVideoStreamNum + mi->nAudioStreamNum); if(XPlayerSwitchSubtitle(mPriData->mXPlayer, nStreamIndex) != 0) { loge("can not switch subtitle, call PlayerSwitchSubtitle() return fail."); return UNKNOWN_ERROR; } } else { logv("==== INVOKE_ID_DESELECT_TRACK, nStreamIndex: %d", nStreamIndex); if(mPriData->mCurrentSelectSubTrackIndex != nStreamIndex) { logw("the unselectTrack is not right: %d, %d", mPriData->mCurrentSelectSubTrackIndex,nStreamIndex); return INVALID_OPERATION; } mPriData->mIsSubtitleDisable = 1; //* disable subtitle show. sendEvent(MEDIA_TIMED_TEXT);//* clear all the displaying subtitle //* clear the mSubtitleDisplayIds memset(mPriData->mSubtitleDisplayIds,0xff,64*sizeof(unsigned int)); mPriData->mSubtitleDisplayIdsUpdateIndex = 0; mPriData->mCurrentSelectSubTrackIndex = -1; } return OK; } if(nMethodId == INVOKE_ID_SELECT_TRACK) { loge("can not switch audio or subtitle to track %d, \ stream index exceed.(%d stream in total).", nStreamIndex, nTrackCount); } else { loge("can not unselect track %d, stream index exceed.(%d stream in total).", nStreamIndex, nTrackCount); } return BAD_INDEX; break; } case INVOKE_ID_SET_VIDEO_SCALING_MODE: { int nStreamIndex; nStreamIndex = request.readInt32(); logv("invode::INVOKE_ID_SET_VIDEO_SCALING_MODE"); //* TODO. return OK; } #if defined(CONF_PRODUCT_STB) case INVOKE_ID_SET_3D_MODE: { logd(" donot set 3d mode"); break; } case INVOKE_ID_GET_3D_MODE: { break; } #endif #if (CONF_ANDROID_MAJOR_VER >= 5) case INVOKE_ID_GET_SELECTED_TRACK: { int trackType = request.readInt32(); logd("==== invoke: INVOKE_ID_GET_SELECTED_TRACK, trackType(%d)", trackType); logd("=== mCurrentSelectSubTrackIndex: %d", mPriData->mCurrentSelectSubTrackIndex); if(trackType == MEDIA_TRACK_TYPE_VIDEO) reply->writeInt32(mPriData->mCurrentSelectVidoeTrackIndex); else if(trackType == MEDIA_TRACK_TYPE_AUDIO) reply->writeInt32(mPriData->mCurrentSelectAudioTrackIndex); else if(trackType == MEDIA_TRACK_TYPE_TIMEDTEXT || trackType == MEDIA_TRACK_TYPE_SUBTITLE) reply->writeInt32(mPriData->mCurrentSelectSubTrackIndex); else logw("invoke: INVOKE_ID_GET_SELECTED_TRACK, trackType(%d) unkown", trackType); break; } #endif case INVOKE_ID_GET_CONTENT_ID: // softdetector { reply->writeInt32(mPriData->dupContentID); return OK; } case INVOKE_ID_GET_BITRATE: // softdetector { int bitRate = 0; if(mi != NULL) bitRate = mi->nBitrate; if(bitRate <= 0 && mPriData->mXPlayer != NULL) bitRate = XPlayerGetBitrate(mPriData->mXPlayer); reply->writeInt32(bitRate); return OK; } case INVOKE_ID_GET_MIME: // softdetector { const char *mime = ""; int containerType = mi->eContainerType; switch(containerType) { case CONTAINER_TYPE_HLS: mime = "application/vnd.apple.mpegurl"; break; case CONTAINER_TYPE_TS: mime = "video/MP2T"; break; case CONTAINER_TYPE_MOV: mime = "video/mp4"; break; } reply->writeString16(String16(mime)); return OK; } case INVOKE_ID_GET_CACHEBYTES: //softdetector { int bytes = 0; if(mPriData->mXPlayer) bytes = XPlayerGetCacheSize(mPriData->mXPlayer); reply->writeInt32(bytes); return OK; } default: { logv("unknown invode command %d", nMethodId); return UNKNOWN_ERROR; } } return OK; } status_t AwPlayer::setParameter(int key, const Parcel &request) { logv("setParameter(key=%d)", key); (void)key; (void)request; return OK; #if 0 switch(key) { case KEY_PARAMETER_CACHE_STAT_COLLECT_FREQ_MS: { int nCacheReportIntervalMs; logv("setParameter::KEY_PARAMETER_CACHE_STAT_COLLECT_FREQ_MS"); nCacheReportIntervalMs = request.readInt32(); if(DemuxCompSetCacheStatReportInterval(mPriData->mDemux, nCacheReportIntervalMs) == 0) return OK; else return UNKNOWN_ERROR; } case KEY_PARAMETER_PLAYBACK_RATE_PERMILLE: { logv("setParameter::KEY_PARAMETER_PLAYBACK_RATE_PERMILLE"); //* TODO. return OK; } default: { logv("unknown setParameter command %d", key); return UNKNOWN_ERROR; } } #endif } status_t AwPlayer::getParameter(int key, Parcel *reply) { logv("getParameter"); (void)(key); (void)(reply); return OK; #if 0 switch(key) { case KEY_PARAMETER_AUDIO_CHANNEL_COUNT: { logv("getParameter::KEY_PARAMETER_AUDIO_CHANNEL_COUNT"); //* TODO. return OK; } #if // use define CONF_PRODUCT_STB/CONF_CMCC/CONF_YUNOS instead case KEY_PARAMETER_GET_CURRENT_BITRATE: { logd("getParameter::PARAM_KEY_GET_CURRENT_BITRATE"); if(mPriData->mXPlayer != NULL) { int currentVideoBitrate = 0; int currentAudioBitrate = 0; int currentBitrate = 0; currentVideoBitrate = PlayerGetVideoBitrate(mPriData->mXPlayer); currentAudioBitrate = PlayerGetAudioBitrate(mPriData->mXPlayer); currentBitrate = currentVideoBitrate + currentAudioBitrate; logd("current Bitrate: video(%d)b/s + audio(%d)b/s = (%d)b/s", currentVideoBitrate, currentAudioBitrate, currentBitrate); reply->writeInt32(currentBitrate); } return OK; } case KEY_PARAMETER_GET_CURRENT_CACHE_DATA_DURATION: { logv("getParameter::PARAM_KEY_GET_CURRENT_CACHE_DATA_DURATION"); if(mPriData->mXPlayer != NULL) { int currentBitrate = 0; int currentCacheDataSize = 0; int currentCacheDataDuration = 0; currentBitrate = PlayerGetVideoBitrate(mPriData->mXPlayer) + PlayerGetAudioBitrate(mPriData->mXPlayer); currentCacheDataSize = DemuxCompGetCacheSize(mPriData->mDemux); if(currentBitrate <= 0) { currentCacheDataDuration = 0; reply->writeInt32((int)currentCacheDataDuration); } else { int64_t tmp = (float)currentCacheDataSize*8.0*1000.0; tmp /= (float)currentBitrate; currentCacheDataDuration = (int)tmp; reply->writeInt32((int)currentCacheDataDuration); } logd("currentDataSize(%d)B currentBitrate(%d)b/s currentDataDuration(%d)ms", currentCacheDataSize, currentBitrate, currentCacheDataDuration); } return OK; } #endif default: { loge("unknown getParameter command %d", key); return UNKNOWN_ERROR; } } #endif } status_t AwPlayer::getMetadata(const media::Metadata::Filter& ids, Parcel *records) { using media::Metadata; Metadata metadata(records); MediaInfo* mi; mi = XPlayerGetMediaInfo(mPriData->mXPlayer); CEDARX_UNUSE(ids); if(mi == NULL) { return NO_INIT; } if(mi->nDurationMs > 0) metadata.appendBool(Metadata::kPauseAvailable , true); else metadata.appendBool(Metadata::kPauseAvailable , false); //* live stream, can not pause. if(mi->bSeekable) { metadata.appendBool(Metadata::kSeekBackwardAvailable, true); metadata.appendBool(Metadata::kSeekForwardAvailable, true); metadata.appendBool(Metadata::kSeekAvailable, true); } else { metadata.appendBool(Metadata::kSeekBackwardAvailable, false); metadata.appendBool(Metadata::kSeekForwardAvailable, false); metadata.appendBool(Metadata::kSeekAvailable, false); } return OK; //* other metadata in include/media/Metadata.h, Keep in sync with android/media/Metadata.java. /* Metadata::kTitle; // String Metadata::kComment; // String Metadata::kCopyright; // String Metadata::kAlbum; // String Metadata::kArtist; // String Metadata::kAuthor; // String Metadata::kComposer; // String Metadata::kGenre; // String Metadata::kDate; // Date Metadata::kDuration; // Integer(millisec) Metadata::kCdTrackNum; // Integer 1-based Metadata::kCdTrackMax; // Integer Metadata::kRating; // String Metadata::kAlbumArt; // byte[] Metadata::kVideoFrame; // Bitmap Metadata::kBitRate; // Integer, Aggregate rate of Metadata::kAudioBitRate; // Integer, bps Metadata::kVideoBitRate; // Integer, bps Metadata::kAudioSampleRate; // Integer, Hz Metadata::kVideoframeRate; // Integer, Hz // See RFC2046 and RFC4281. Metadata::kMimeType; // String Metadata::kAudioCodec; // String Metadata::kVideoCodec; // String Metadata::kVideoHeight; // Integer Metadata::kVideoWidth; // Integer Metadata::kNumTracks; // Integer Metadata::kDrmCrippled; // Boolean */ } status_t AwPlayer::setSubCharset(const char* strFormat) { if(strFormat != NULL) { int i; for(i=0; strTextCodecFormats[i]; i++) { if(!strcmp(strTextCodecFormats[i], strFormat)) break; } if(strTextCodecFormats[i] != NULL) strcpy(mPriData->mDefaultTextFormat, strTextCodecFormats[i]); } else strcpy(mPriData->mDefaultTextFormat, "UTF-8"); return OK; } status_t AwPlayer::getSubCharset(char *charset) { if(mPriData->mXPlayer == NULL) { return -1; } strcpy(charset, mPriData->mDefaultTextFormat); return OK; } status_t AwPlayer::setSubDelay(int nTimeMs) { if(mPriData->mXPlayer == NULL) { return -1; } return XPlayerSetSubDelay(mPriData->mXPlayer, nTimeMs); } int AwPlayer::getSubDelay() { if(mPriData->mXPlayer == NULL) { return -1; } return XPlayerGetSubDelay(mPriData->mXPlayer); } status_t AwPlayer::callbackProcess(int messageId, int ext1, void* param) { switch(messageId) { case AWPLAYER_MEDIA_PREPARED: { #if BUFFERING_ICON_BUG if (!mPriData->mbIsDiagnose && mPriData->mConfigInfo.appType == APP_CMCC_WASU) { sendEvent(MEDIA_INFO, MEDIA_INFO_BUFFERING_END); } #endif sendEvent(MEDIA_PREPARED, 0, 0); break; } case AWPLAYER_MEDIA_PLAYBACK_COMPLETE: { int playTime; getDuration(&playTime); sendEvent(MEDIA_PLAYBACK_COMPLETE,playTime, 0);//notify the duration. break; } case AWPLAYER_MEDIA_SEEK_COMPLETE: { sendEvent(MEDIA_SEEK_COMPLETE, 0, 0); break; } case AWPLAYER_MEDIA_LOG_RECORDER: { if(mPriData->mLogRecorder != NULL) { logv("AwLogRecorderRecord %s.", (char*)param); AwLogRecorderRecord(mPriData->mLogRecorder, (char*)param); } break; } case AWPLAYER_MEDIA_BUFFERING_UPDATE: { int nTotalPercentage; int nBufferPercentage; int nLoadingPercentage; nTotalPercentage = ((int*)param)[0]; //* read positon to total file size. nBufferPercentage = ((int*)param)[1]; //* cache buffer fullness. nLoadingPercentage = ((int*)param)[2]; //* loading percentage to start play. sendEvent(MEDIA_BUFFERING_UPDATE, nTotalPercentage, nBufferPercentage<<16 | nLoadingPercentage); break; } case AWPLAYER_MEDIA_ERROR: { if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[error][%s %s %d]Error happened, event: %d", LOG_TAG, __FUNCTION__, __LINE__, ext1); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } #if defined(CONF_PRODUCT_STB) if(ext1 == AW_MEDIA_ERROR_UNKNOWN) sendEvent(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0); else if(ext1 == AW_MEDIA_ERROR_IO) sendEvent(MEDIA_ERROR, MEDIA_ERROR_IO, 0); else if(ext1 == AW_MEDIA_ERROR_UNSUPPORTED) sendEvent(MEDIA_ERROR, MEDIA_ERROR_UNSUPPORTED, 0); else { logw("unkown ext1: %d", ext1); sendEvent(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0); } #else sendEvent(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, 0); #endif break; } case AWPLAYER_MEDIA_INFO: { switch(ext1) { case AW_MEDIA_INFO_UNKNOWN: sendEvent(MEDIA_INFO, MEDIA_INFO_UNKNOWN); break; case AW_MEDIA_INFO_RENDERING_START: { if(mPriData->mLogRecorder != NULL) { struct timeval tv; int64_t renderTimeMs; gettimeofday(&tv, NULL); renderTimeMs = (tv.tv_sec * 1000000ll + tv.tv_usec)/1000; char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]show the first video frame," " spend time: %lldms", LOG_TAG, __FUNCTION__, __LINE__, (long long int)(renderTimeMs - mPriData->mPlayTimeMs)); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } sendEvent(MEDIA_INFO, MEDIA_INFO_RENDERING_START, 0); break; } case AW_MEDIA_INFO_BUFFERING_START: { if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; int *pNeedBufferSize = (int*)param; sprintf(cmccLog, "[info][%s %s %d]buffering start, " "need buffer data size: %.2fMB", LOG_TAG, __FUNCTION__, __LINE__, *pNeedBufferSize/(1024*1024.0f)); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); struct timeval tv; gettimeofday(&tv, NULL); mPriData->mBufferTimeMs = (tv.tv_sec * 1000000ll + tv.tv_usec)/1000; } sendEvent(MEDIA_INFO, MEDIA_INFO_BUFFERING_START); break; } case AW_MEDIA_INFO_BUFFERING_END: { if(mPriData->mLogRecorder != NULL) { struct timeval tv; gettimeofday(&tv, NULL); int64_t bufferEndTimeMs = (tv.tv_sec * 1000000ll + tv.tv_usec)/1000; char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]buffering end, lasting time: %lldms", LOG_TAG, __FUNCTION__, __LINE__, (long long int)(bufferEndTimeMs - mPriData->mBufferTimeMs)); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } sendEvent(MEDIA_INFO, MEDIA_INFO_BUFFERING_END); break; } case AW_MEDIA_INFO_NOT_SEEKABLE: sendEvent(MEDIA_INFO, MEDIA_INFO_NOT_SEEKABLE, 0); break; #if defined(CONF_PRODUCT_STB) case AW_MEDIA_INFO_DOWNLOAD_START: { DownloadObject* obj = (DownloadObject*)param; if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]ts segment download is start, " "number: %d, filesize: %.2fMB, duration: %lldms", LOG_TAG, __FUNCTION__, __LINE__, obj->seqNum, (float)obj->seqSize/(1024*1024.0f), obj->seqDuration/1000); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } sendEvent(MEDIA_INFO, MEDIA_INFO_DOWNLOAD_START, obj->seqNum); break; } case AW_MEDIA_INFO_DOWNLOAD_END: { DownloadObject* obj = (DownloadObject*)param; if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[info][%s %s %d]ts segment download is complete, " "recvsize: %.2fMB, spend time: %lldms, rate: %lldbps", LOG_TAG, __FUNCTION__, __LINE__, (float)obj->seqSize/(1024*1024.0f), obj->spendTime, obj->rate); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } sendEvent(MEDIA_INFO, MEDIA_INFO_DOWNLOAD_END, (int)obj->spendTime); break; } case AW_MEDIA_INFO_DOWNLOAD_ERROR: { DownloadObject* obj = (DownloadObject*)param; if(mPriData->mLogRecorder != NULL) { char cmccLog[4096] = ""; sprintf(cmccLog, "[error][%s %s %d]Error happened, event: %d", LOG_TAG, __FUNCTION__, __LINE__, MEDIA_INFO_DOWNLOAD_ERROR); logv("AwLogRecorderRecord %s.", cmccLog); AwLogRecorderRecord(mPriData->mLogRecorder, cmccLog); } sendEvent(MEDIA_INFO, MEDIA_INFO_DOWNLOAD_ERROR, obj->statusCode); break; } #endif default: logw("unkown info msg"); break; } break; } #if !(defined(CONF_NEW_BDMV_STREAM)) case AWPLAYER_EXTEND_MEDIA_INFO: { switch(ext1) { case AW_EX_IOREQ_ACCESS: { char *filePath = (char *)((uintptr_t *)param)[0]; int mode = ((uintptr_t *)param)[1]; int *pRet = (int *)((uintptr_t *)param)[2]; Parcel parcel; Parcel replyParcel; *pRet = -1; // write path string as a byte array parcel.writeInt32(strlen(filePath)); parcel.write(filePath, strlen(filePath)); parcel.writeInt32(mode); sendEvent(AWEXTEND_MEDIA_INFO, AWEXTEND_MEDIA_INFO_CHECK_ACCESS_RIGHRS, 0, &parcel, &replyParcel); replyParcel.setDataPosition(0); *pRet = replyParcel.readInt32(); break; } case AW_EX_IOREQ_OPEN: { char *filePath = (char *)((uintptr_t *)param)[0]; int *pFd = (int *)((uintptr_t *)param)[1]; int fd = -1; Parcel parcel; Parcel replyParcel; bool bFdValid = false; *pFd = -1; // write path string as a byte array parcel.writeInt32(strlen(filePath)); parcel.write(filePath, strlen(filePath)); sendEvent(AWEXTEND_MEDIA_INFO, AWEXTEND_MEDIA_INFO_REQUEST_OPEN_FILE, 0, &parcel, &replyParcel); replyParcel.setDataPosition(0); bFdValid = replyParcel.readInt32(); if (bFdValid == true) { fd = replyParcel.readFileDescriptor(); if (fd < 0) { loge("invalid fd '%d'", fd); *pFd = -1; break; } *pFd = dup(fd); if (*pFd < 0) { loge("dup fd failure, errno(%d) '%d'", errno, fd); } close(fd); } break; } case AW_EX_IOREQ_OPENDIR: { char *dirPath = (char *)((uintptr_t *)param)[0]; int *pDirId = (int *)((uintptr_t *)param)[1]; Parcel parcel; Parcel replyParcel; *pDirId = -1; // write path string as a byte array parcel.writeInt32(strlen(dirPath)); parcel.write(dirPath, strlen(dirPath)); sendEvent(AWEXTEND_MEDIA_INFO, AWEXTEND_MEDIA_INFO_REQUEST_OPEN_DIR, 0, &parcel, &replyParcel); replyParcel.setDataPosition(0); *pDirId = replyParcel.readInt32(); break; } case AW_EX_IOREQ_READDIR: { int dirId = ((uintptr_t *)param)[0]; int *pRet = (int *)((uintptr_t *)param)[1]; char *buf = (char *)((uintptr_t *)param)[2]; int bufLen = ((uintptr_t *)param)[3]; loge("** aw-read-dir: dirId = %d, buf = %p, bufLen = %d", dirId,buf,bufLen); Parcel parcel; Parcel replyParcel; int fileNameLen = -1; int32_t replyRet = -1; *pRet = -1; // write path string as a byte array parcel.writeInt32(dirId); sendEvent(AWEXTEND_MEDIA_INFO, AWEXTEND_MEDIA_INFO_REQUEST_READ_DIR, 0, &parcel, &replyParcel); replyParcel.setDataPosition(0); replyRet = replyParcel.readInt32(); if (0 == replyRet) { fileNameLen = replyParcel.readInt32(); if (fileNameLen > 0 && fileNameLen < bufLen) { const char* strdata = (const char*)replyParcel.readInplace(fileNameLen); memcpy(buf, strdata, fileNameLen); buf[fileNameLen] = 0; *pRet = 0; } } break; } case AW_EX_IOREQ_CLOSEDIR: { int dirId = ((uintptr_t *)param)[0]; int *pRet = (int *)((uintptr_t *)param)[1]; Parcel parcel; Parcel replyParcel; // write path string as a byte array parcel.writeInt32(dirId); sendEvent(AWEXTEND_MEDIA_INFO, AWEXTEND_MEDIA_INFO_REQUEST_CLOSE_DIR, 0, &parcel, &replyParcel); replyParcel.setDataPosition(0); *pRet = replyParcel.readInt32(); break; } } } #endif case SUBCTRL_SUBTITLE_AVAILABLE: { Parcel parcel; unsigned int nSubtitleId = (unsigned int)((uintptr_t*)param)[0]; SubtitleItem* pSubtitleItem = (SubtitleItem*)((uintptr_t*)param)[1]; logd("subtitle available. id = %d, pSubtitleItem = %p",nSubtitleId,pSubtitleItem); if(pSubtitleItem == NULL) { logw("pSubtitleItem == NULL"); break; } mPriData->mIsSubtitleInTextFormat = !!pSubtitleItem->bText; //* 0 or 1. if(mPriData->mIsSubtitleDisable == 0) { if(mPriData->mIsSubtitleInTextFormat) { SubtitleUtilsFillTextSubtitleToParcel(&parcel, pSubtitleItem, nSubtitleId, mPriData->mDefaultTextFormat); } else { //* clear the mSubtitleDisplayIds memset(mPriData->mSubtitleDisplayIds,0xff,64*sizeof(unsigned int)); mPriData->mSubtitleDisplayIdsUpdateIndex = 0; sendEvent(MEDIA_TIMED_TEXT); //* clear bmp subtitle first SubtitleUtilsFillBitmapSubtitleToParcel(&parcel, pSubtitleItem, nSubtitleId); } //*record subtitile id mPriData->mSubtitleDisplayIds[mPriData->mSubtitleDisplayIdsUpdateIndex] = nSubtitleId; mPriData->mSubtitleDisplayIdsUpdateIndex++; if(mPriData->mSubtitleDisplayIdsUpdateIndex>=64) mPriData->mSubtitleDisplayIdsUpdateIndex = 0; logd("notify available message."); sendEvent(MEDIA_TIMED_TEXT, 0, 0, &parcel); } break; } case SUBCTRL_SUBTITLE_EXPIRED: { logd("subtitle expired."); Parcel parcel; unsigned int nSubtitleId; int i; nSubtitleId = *(unsigned int*)param; if(mPriData->mIsSubtitleDisable == 0) { //* match the subtitle id which is displaying ,or we may clear null subtitle for(i=0;i<64;i++) { if(nSubtitleId==mPriData->mSubtitleDisplayIds[i]) break; } if(i!=64) { mPriData->mSubtitleDisplayIds[i] = 0xffffffff; if(mPriData->mIsSubtitleInTextFormat == 1) { #if !defined(ANDROID_STRICT_COMPATIBLE) //* set subtitle id parcel.writeInt32(KEY_GLOBAL_SETTING); //* nofity app to hide this subtitle parcel.writeInt32(KEY_STRUCT_AWEXTEND_HIDESUB); parcel.writeInt32(1); parcel.writeInt32(KEY_SUBTITLE_ID); parcel.writeInt32(nSubtitleId); #endif logd("notify text expired message."); sendEvent(MEDIA_TIMED_TEXT, 0, 0, &parcel); } else { //* clear the mSubtitleDisplayIds memset(mPriData->mSubtitleDisplayIds,0xff,64*sizeof(unsigned int)); mPriData->mSubtitleDisplayIdsUpdateIndex = 0; //* if the sub is bmp ,we just send "clear all" command, //* nSubtitleId is not sent. logd("notify subtitle expired message."); sendEvent(MEDIA_TIMED_TEXT); } } } break; } case AWPLAYER_MEDIA_SET_VIDEO_SIZE: { int nWidth = ((int*)param)[0]; int nHeight = ((int*)param)[1]; logd("=== set videosize (%d, %d)", nWidth, nHeight); sendEvent(MEDIA_SET_VIDEO_SIZE, nWidth, nHeight); break; } default: { logw("message 0x%x not handled.", messageId); break; } } return OK; } static int XPlayerCallbackProcess(void* pUser, int eMessageId, int ext1, void* param) { AwPlayer *p = (AwPlayer*)pUser; p->callbackProcess(eMessageId, ext1, param); return 0; } static int SubCallbackProcess(void* pUser, int eMessageId, void* param) { AwPlayer* p = (AwPlayer*)pUser; p->callbackProcess(eMessageId, 0, param); return 0; } static int GetCallingApkName(char* strApkName, int nMaxNameSize) { int fd; snprintf(strApkName, nMaxNameSize, "/proc/%d/cmdline", IPCThreadState::self()->getCallingPid()); fd = ::open(strApkName, O_RDONLY); strApkName[0] = '\0'; if (fd >= 0) { strApkName[nMaxNameSize - 1] = '\0'; ::read(fd, strApkName, nMaxNameSize - 1); ::close(fd); logd("Calling process is: %s", strApkName); } return 0; } void enableMediaBoost(MediaInfo* mi) { char cmd[PROP_VALUE_MAX] = {0}; int total = 0; struct ScMemOpsS *memops = NULL; if(mi == NULL || mi->pVideoStreamInfo == NULL) { logd("input invalid args."); return; } #if defined(CONF_MEDIA_BOOST_MEM) if(mi->pVideoStreamInfo->bSecureStreamFlagLevel1 == 1) { memops = SecureMemAdapterGetOpsS(); } else { memops = MemAdapterGetOpsS(); } CdcMemOpen(memops); total = CdcMemTotalSize(memops); CdcMemClose(memops); //set the mem property if((mi->pVideoStreamInfo->nWidth >= WIDTH_4K || mi->pVideoStreamInfo->nHeight >= HEIGHT_4K) && total < 190000 ) { sprintf(cmd, "model%d:3", getpid()); logd("setprop media.boost.pref %s", cmd); property_set("media.boost.pref", cmd); } #endif //setprop media.boost.pref mode123:0:c:num //attention!!! Just for h5, num(1,2,3,4) lock cpu num; num(5) lock freq. #if defined(CONF_MEDIA_BOOST_CPU) #if (CONF_MEDIA_BOOST_CPU_MODE == 1) // h5 sprintf(cmd, "mode%d:0:c:5", getpid()); #elif (CONF_MEDIA_BOOST_CPU_MODE == 2) // h6 sprintf(cmd, "mode%d:1:c:3", getpid()); #endif logd("setprop media.boost.pref %s", cmd); property_set("media.boost.pref", cmd); #endif } void disableMediaBoost() { char cmd[PROP_VALUE_MAX] = {0}; sprintf(cmd, "mode%d:0:c:0", getpid()); logd("setprop media.boost.pref %s", cmd); property_set("media.boost.pref", cmd); }
32.419759
100
0.547963
ghsecuritylab
6f1759908d4bb42a1f3f7b6639aca363236a09ab
4,484
cpp
C++
Source/Scripting/bsfScript/Generated/BsScriptParticleDepthCollisionSettings.generated.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
1,745
2018-03-16T02:10:28.000Z
2022-03-26T17:34:21.000Z
Source/Scripting/bsfScript/Generated/BsScriptParticleDepthCollisionSettings.generated.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
395
2018-03-16T10:18:20.000Z
2021-08-04T16:52:08.000Z
Source/Scripting/bsfScript/Generated/BsScriptParticleDepthCollisionSettings.generated.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
267
2018-03-17T19:32:54.000Z
2022-02-17T16:55:50.000Z
//********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "BsScriptParticleDepthCollisionSettings.generated.h" #include "BsMonoMethod.h" #include "BsMonoClass.h" #include "BsMonoUtil.h" namespace bs { ScriptParticleDepthCollisionSettings::ScriptParticleDepthCollisionSettings(MonoObject* managedInstance, const SPtr<ParticleDepthCollisionSettings>& value) :TScriptReflectable(managedInstance, value) { } void ScriptParticleDepthCollisionSettings::initRuntimeData() { metaData.scriptClass->addInternalCall("Internal_ParticleDepthCollisionSettings", (void*)&ScriptParticleDepthCollisionSettings::Internal_ParticleDepthCollisionSettings); metaData.scriptClass->addInternalCall("Internal_getenabled", (void*)&ScriptParticleDepthCollisionSettings::Internal_getenabled); metaData.scriptClass->addInternalCall("Internal_setenabled", (void*)&ScriptParticleDepthCollisionSettings::Internal_setenabled); metaData.scriptClass->addInternalCall("Internal_getrestitution", (void*)&ScriptParticleDepthCollisionSettings::Internal_getrestitution); metaData.scriptClass->addInternalCall("Internal_setrestitution", (void*)&ScriptParticleDepthCollisionSettings::Internal_setrestitution); metaData.scriptClass->addInternalCall("Internal_getdampening", (void*)&ScriptParticleDepthCollisionSettings::Internal_getdampening); metaData.scriptClass->addInternalCall("Internal_setdampening", (void*)&ScriptParticleDepthCollisionSettings::Internal_setdampening); metaData.scriptClass->addInternalCall("Internal_getradiusScale", (void*)&ScriptParticleDepthCollisionSettings::Internal_getradiusScale); metaData.scriptClass->addInternalCall("Internal_setradiusScale", (void*)&ScriptParticleDepthCollisionSettings::Internal_setradiusScale); } MonoObject* ScriptParticleDepthCollisionSettings::create(const SPtr<ParticleDepthCollisionSettings>& value) { if(value == nullptr) return nullptr; bool dummy = false; void* ctorParams[1] = { &dummy }; MonoObject* managedInstance = metaData.scriptClass->createInstance("bool", ctorParams); new (bs_alloc<ScriptParticleDepthCollisionSettings>()) ScriptParticleDepthCollisionSettings(managedInstance, value); return managedInstance; } void ScriptParticleDepthCollisionSettings::Internal_ParticleDepthCollisionSettings(MonoObject* managedInstance) { SPtr<ParticleDepthCollisionSettings> instance = bs_shared_ptr_new<ParticleDepthCollisionSettings>(); new (bs_alloc<ScriptParticleDepthCollisionSettings>())ScriptParticleDepthCollisionSettings(managedInstance, instance); } bool ScriptParticleDepthCollisionSettings::Internal_getenabled(ScriptParticleDepthCollisionSettings* thisPtr) { bool tmp__output; tmp__output = thisPtr->getInternal()->enabled; bool __output; __output = tmp__output; return __output; } void ScriptParticleDepthCollisionSettings::Internal_setenabled(ScriptParticleDepthCollisionSettings* thisPtr, bool value) { thisPtr->getInternal()->enabled = value; } float ScriptParticleDepthCollisionSettings::Internal_getrestitution(ScriptParticleDepthCollisionSettings* thisPtr) { float tmp__output; tmp__output = thisPtr->getInternal()->restitution; float __output; __output = tmp__output; return __output; } void ScriptParticleDepthCollisionSettings::Internal_setrestitution(ScriptParticleDepthCollisionSettings* thisPtr, float value) { thisPtr->getInternal()->restitution = value; } float ScriptParticleDepthCollisionSettings::Internal_getdampening(ScriptParticleDepthCollisionSettings* thisPtr) { float tmp__output; tmp__output = thisPtr->getInternal()->dampening; float __output; __output = tmp__output; return __output; } void ScriptParticleDepthCollisionSettings::Internal_setdampening(ScriptParticleDepthCollisionSettings* thisPtr, float value) { thisPtr->getInternal()->dampening = value; } float ScriptParticleDepthCollisionSettings::Internal_getradiusScale(ScriptParticleDepthCollisionSettings* thisPtr) { float tmp__output; tmp__output = thisPtr->getInternal()->radiusScale; float __output; __output = tmp__output; return __output; } void ScriptParticleDepthCollisionSettings::Internal_setradiusScale(ScriptParticleDepthCollisionSettings* thisPtr, float value) { thisPtr->getInternal()->radiusScale = value; } }
40.763636
170
0.807538
bsf2dev
6f195701b3d8b036667764a16c9d86cd5153be77
20,347
cpp
C++
inetsrv/iis/svcs/cmp/asp/ie449.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/svcs/cmp/asp/ie449.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/svcs/cmp/asp/ie449.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*=================================================================== Microsoft IIS 5.0 (ASP) Microsoft Confidential. Copyright 1998 Microsoft Corporation. All Rights Reserved. Component: 449 negotiations w/IE File: ie449.cpp Owner: DmitryR This file contains the implementation of the 449 negotiations w/IE ===================================================================*/ #include "denpre.h" #pragma hdrstop #include "ie449.h" #include "memchk.h" /*=================================================================== Globals ===================================================================*/ C449FileMgr *m_p449FileMgr = NULL; /*=================================================================== Internal funcitons ===================================================================*/ inline BOOL FindCookie ( char *szCookiesBuf, char *szCookie, DWORD cbCookie ) { char *pch = szCookiesBuf; if (pch == NULL || *pch == '\0') return FALSE; while (1) { if (strnicmp(pch, szCookie, cbCookie) == 0) { if (pch[cbCookie] == '=') // next char must be '=' return TRUE; } // next cookie pch = strchr(pch, ';'); if (pch == NULL) break; while (*(++pch) == ' ') // skip ; and any spaces ; } return FALSE; } /*=================================================================== The API ===================================================================*/ /*=================================================================== Init449 ===================================================================*/ HRESULT Init449() { // init hash table m_p449FileMgr = new C449FileMgr; if (m_p449FileMgr == NULL) return E_OUTOFMEMORY; HRESULT hr = m_p449FileMgr->Init(); if (FAILED(hr)) { delete m_p449FileMgr; m_p449FileMgr = NULL; return hr; } return S_OK; } /*=================================================================== UnInit449 ===================================================================*/ HRESULT UnInit449() { if (m_p449FileMgr != NULL) { delete m_p449FileMgr; m_p449FileMgr = NULL; } return S_OK; } /*=================================================================== Create449Cookie Get an existing 449 cookie from cache or create a new one Parameters szName cookie name szFile script file pp449 [out] the cookie Returns HRESULT ===================================================================*/ HRESULT Create449Cookie ( char *szName, TCHAR *szFile, C449Cookie **pp449 ) { HRESULT hr = S_OK; // Get the file first C449File *pFile = NULL; hr = m_p449FileMgr->GetFile(szFile, &pFile); if (FAILED(hr)) return hr; // Create the cookie hr = C449Cookie::Create449Cookie(szName, pFile, pp449); if (FAILED(hr)) pFile->Release(); // GetFile gave it addref'd return hr; } /*=================================================================== Do449Processing Check if the browser is IE5+ there's no echo-reply: header all the cookies are present Construct and send 449 response if needed When the response is sent, HitObj is marked as 'done with session' Parameters pHitObj the request rgpCookies array of cookie requirements cCookies number of cookie requirements Returns HRESULT ===================================================================*/ HRESULT Do449Processing ( CHitObj *pHitObj, C449Cookie **rgpCookies, DWORD cCookies ) { HRESULT hr = S_OK; if (cCookies == 0) return hr; ////////////////////////////////////////// // check the browser BOOL fBrowser = FALSE; char *szBrowser = pHitObj->PIReq()->QueryPszUserAgent(); if (szBrowser == NULL || szBrowser[0] == '\0') return S_OK; // bad browser char *szMSIE = strstr(szBrowser, "MSIE "); if (szMSIE) { char chVersion = szMSIE[5]; if (chVersion >= '5' && chVersion <= '9') fBrowser = TRUE; } #ifdef TINYGET449 if (strcmp(szBrowser, "WBCLI") == 0) fBrowser = TRUE; #endif if (!fBrowser) // bad browser return S_OK; ////////////////////////////////////////// // check the cookies char *szCookie = pHitObj->PIReq()->QueryPszCookie(); // collect the arrays of pointers and sizes for not found cookies. // arrays size to at most number of cookies in the template. DWORD cNotFound = 0; DWORD cbNotFound = 0; STACK_BUFFER( tempCookies, 128 ); if (!tempCookies.Resize(cCookies * sizeof(WSABUF))) { return E_OUTOFMEMORY; } LPWSABUF rgpNotFound = (LPWSABUF)tempCookies.QueryPtr(); for (DWORD i = 0; SUCCEEDED(hr) && (i < cCookies); i++) { if (!FindCookie(szCookie, rgpCookies[i]->SzCookie(), rgpCookies[i]->CbCookie())) { // cookie not found -- append to the list hr = rgpCookies[i]->LoadFile(); if (SUCCEEDED(hr)) // ignore bad files { rgpNotFound[cNotFound].buf = rgpCookies[i]->SzBuffer(); rgpNotFound[cNotFound].len = rgpCookies[i]->CbBuffer(); cbNotFound += rgpCookies[i]->CbBuffer(); cNotFound++; } } } if (!SUCCEEDED(hr)) return hr; if (cNotFound == 0) return S_OK; // everything's found ////////////////////////////////////////// // check echo-reply header char szEcho[80]; DWORD dwEchoLen = sizeof(szEcho); if (pHitObj->PIReq()->GetServerVariableA("HTTP_MS_ECHO_REPLY", szEcho, &dwEchoLen) || GetLastError() == ERROR_INSUFFICIENT_BUFFER) { return S_OK; // already in response cycle } ////////////////////////////////////////// // send the 449 response CResponse::WriteBlocksResponse ( pHitObj->PIReq(), // WAM_EXEC_INFO cNotFound, // number of blocks rgpNotFound, // array of blocks cbNotFound, // total number of bytes in blocks NULL, // text/html "449 Retry with", // status "ms-echo-request: execute opaque=\"0\" location=\"BODY\"\r\n" // extra header ); ////////////////////////////////////////// // tell HitObj no to write anything else pHitObj->SetDoneWithSession(); return S_OK; } /*=================================================================== Do449ChangeNotification Change notification processing Parameters szFile file changed or NULL for all Returns HRESULT ===================================================================*/ HRESULT Do449ChangeNotification ( TCHAR *szFile ) { // if m_p449FileMgr is NULL, we're likely getting called after // the 449 manager has been UnInited. Return S_OK in this case. if (m_p449FileMgr == NULL) return S_OK; if (szFile) return m_p449FileMgr->Flush(szFile); else return m_p449FileMgr->FlushAll(); } /*=================================================================== Class C449File ===================================================================*/ /*=================================================================== C449File::C449File Constructor ===================================================================*/ C449File::C449File() { m_cRefs = 0; m_fNeedLoad = 1; m_szFile = NULL; m_szBuffer = NULL; m_cbBuffer = 0; m_pDME = NULL; m_hFileReadyForUse=NULL; m_hrLoadResult= E_FAIL; } /*=================================================================== C449File::~C449File Destructor ===================================================================*/ C449File::~C449File() { Assert(m_cRefs == 0); if (m_szFile) free(m_szFile); if (m_szBuffer) free(m_szBuffer); if (m_pDME) m_pDME->Release(); if(m_hFileReadyForUse != NULL) CloseHandle(m_hFileReadyForUse); } /*=================================================================== C449File::Init Init strings, Load file for the first time, Start change notifications ===================================================================*/ HRESULT C449File::Init ( TCHAR *szFile ) { // remember the name m_szFile = StringDup(szFile); if (m_szFile == NULL) return E_OUTOFMEMORY; // init link element CLinkElem::Init(m_szFile, _tcslen(m_szFile)*sizeof(TCHAR)); // Create event: manual-reset, ready-for-use event; non-signaled // Better create event before using it. m_hFileReadyForUse = IIS_CREATE_EVENT( "C449File::m_hFileReadyForUse", this, TRUE, // flag for manual-reset event FALSE // flag for initial state ); if (!m_hFileReadyForUse) return E_OUTOFMEMORY; // load m_fNeedLoad = 1; HRESULT hr = Load(); if (FAILED(hr)) return hr; // start directory notifications TCHAR *pch = _tcsrchr(m_szFile, _T('\\')); // last backslash if (pch == NULL) return E_FAIL; // bogus filename? CASPDirMonitorEntry *pDME = NULL; *pch = _T('\0'); RegisterASPDirMonitorEntry(m_szFile, &pDME); *pch = _T('\\'); m_pDME = pDME; // done return S_OK; } /*=================================================================== C449File::Load Load the file if needed ===================================================================*/ HRESULT C449File::Load() { HRESULT hr = S_OK; HANDLE hFile = INVALID_HANDLE_VALUE; HANDLE hMap = NULL; BYTE *pbBytes = NULL; DWORD dwSize = 0; // check if this thread needs to load the file if (InterlockedExchange(&m_fNeedLoad, 0) == 0) { WaitForSingleObject(m_hFileReadyForUse, INFINITE); return m_hrLoadResult; } // cleanup the existing data if any if (m_szBuffer) free(m_szBuffer); m_szBuffer = NULL; m_cbBuffer = 0; // open the file if (SUCCEEDED(hr)) { hFile = AspCreateFile( m_szFile, GENERIC_READ, // access (read-write) mode FILE_SHARE_READ, // share mode NULL, // pointer to security descriptor OPEN_EXISTING, // how to create FILE_ATTRIBUTE_NORMAL, // file attributes NULL // handle to file with attributes to copy ); if (hFile == INVALID_HANDLE_VALUE) hr = E_FAIL; } // get file size if (SUCCEEDED(hr)) { dwSize = GetFileSize(hFile, NULL); if (dwSize == 0 || dwSize == 0xFFFFFFFF) hr = E_FAIL; } // create mapping if (SUCCEEDED(hr)) { hMap = CreateFileMapping( hFile, // handle to file to map NULL, // optional security attributes PAGE_READONLY, // protection for mapping object 0, // high-order 32 bits of object size 0, // low-order 32 bits of object size NULL // name of file-mapping object ); if (hMap == NULL) hr = E_FAIL; } // map the file if (SUCCEEDED(hr)) { pbBytes = (BYTE *)MapViewOfFile( hMap, // file-mapping object to map into address space FILE_MAP_READ, // access mode 0, // high-order 32 bits of file offset 0, // low-order 32 bits of file offset 0 // number of bytes to map ); if (pbBytes == NULL) hr = E_FAIL; } // remember the bytes if (SUCCEEDED(hr)) { m_szBuffer = (char *)malloc(dwSize); if (m_szBuffer != NULL) { memcpy(m_szBuffer, pbBytes, dwSize); m_cbBuffer = dwSize; } else { hr = E_OUTOFMEMORY; } } // cleanup if (pbBytes != NULL) UnmapViewOfFile(pbBytes); if (hMap != NULL) CloseHandle(hMap); if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); // Set the Need Load flag or flag the read event as successful. m_hrLoadResult = hr; SetEvent(m_hFileReadyForUse); return m_hrLoadResult; } /*=================================================================== C449File::Create449File static constructor ===================================================================*/ HRESULT C449File::Create449File ( TCHAR *szFile, C449File **ppFile ) { HRESULT hr = S_OK; C449File *pFile = new C449File; if (pFile == NULL) hr = E_OUTOFMEMORY; if (SUCCEEDED(hr)) { hr = pFile->Init(szFile); } if (SUCCEEDED(hr)) { pFile->AddRef(); *ppFile = pFile; } else if (pFile) { delete pFile; } return hr; } /*=================================================================== C449File::QueryInterface C449File::AddRef C449File::Release IUnknown members for C449File object. ===================================================================*/ STDMETHODIMP C449File::QueryInterface(REFIID riid, VOID **ppv) { // should never be called Assert(FALSE); *ppv = NULL; return E_NOINTERFACE; } STDMETHODIMP_(ULONG) C449File::AddRef() { return InterlockedIncrement(&m_cRefs); } STDMETHODIMP_(ULONG) C449File::Release() { LONG cRefs = InterlockedDecrement(&m_cRefs); if (cRefs) return cRefs; delete this; return 0; } /*=================================================================== Class C449FileMgr ===================================================================*/ /*=================================================================== C449FileMgr::C449FileMgr Constructor ===================================================================*/ C449FileMgr::C449FileMgr() { INITIALIZE_CRITICAL_SECTION(&m_csLock); } /*=================================================================== C449FileMgr::~C449FileMgr Destructor ===================================================================*/ C449FileMgr::~C449FileMgr() { FlushAll(); m_ht449Files.UnInit(); DeleteCriticalSection(&m_csLock); } /*=================================================================== C449FileMgr::Init Initialization ===================================================================*/ HRESULT C449FileMgr::Init() { return m_ht449Files.Init(199); } /*=================================================================== C449FileMgr::GetFile Find file in the hash table, or create a new one ===================================================================*/ HRESULT C449FileMgr::GetFile ( TCHAR *szFile, C449File **ppFile ) { C449File *pFile = NULL; CLinkElem *pElem; Lock(); pElem = m_ht449Files.FindElem(szFile, _tcslen(szFile)*sizeof(TCHAR)); if (pElem) { // found pFile = static_cast<C449File *>(pElem); if (!SUCCEEDED(pFile->Load())) pFile = NULL; else pFile->AddRef(); // 1 ref to hand out } else if (SUCCEEDED(C449File::Create449File(szFile, &pFile))) { if (m_ht449Files.AddElem(pFile)) pFile->AddRef(); // 1 for hash table + 1 to hand out } UnLock(); *ppFile = pFile; return (pFile != NULL) ? S_OK : E_FAIL; } /*=================================================================== C449FileMgr::Flush Change notification for a single file ===================================================================*/ HRESULT C449FileMgr::Flush ( TCHAR *szFile ) { Lock(); CLinkElem *pElem = m_ht449Files.FindElem(szFile, _tcslen(szFile)*sizeof(TCHAR)); if (pElem) { C449File *pFile = static_cast<C449File *>(pElem); pFile->SetNeedLoad(); // next time reload } UnLock(); return S_OK; } /*=================================================================== C449FileMgr::FlushAll Remove all files FlushAll is always together with template flush ===================================================================*/ HRESULT C449FileMgr::FlushAll() { // Unlink from hash table first Lock(); CLinkElem *pElem = m_ht449Files.Head(); m_ht449Files.ReInit(); UnLock(); // Walk the list to remove all while (pElem) { C449File *pFile = static_cast<C449File *>(pElem); pElem = pElem->m_pNext; pFile->Release(); } return S_OK; } /*=================================================================== Class C449Cookie ===================================================================*/ /*=================================================================== C449Cookie::C449Cookie Constructor ===================================================================*/ C449Cookie::C449Cookie() { m_cRefs = 0; m_szName = NULL; m_cbName = 0; m_pFile = NULL; } /*=================================================================== C449Cookie::~C449Cookie Destructor ===================================================================*/ C449Cookie::~C449Cookie() { Assert(m_cRefs == 0); if (m_szName) free(m_szName); if (m_pFile) m_pFile->Release(); } /*=================================================================== C449Cookie::Init Initialize ===================================================================*/ HRESULT C449Cookie::Init ( char *szName, C449File *pFile ) { m_szName = StringDupA(szName); if (m_szName == NULL) return E_OUTOFMEMORY; m_cbName = strlen(m_szName); m_pFile = pFile; return S_OK; } /*=================================================================== C449Cookie::Create449Cookie static constructor ===================================================================*/ HRESULT C449Cookie::Create449Cookie ( char *szName, C449File *pFile, C449Cookie **pp449Cookie ) { HRESULT hr = S_OK; C449Cookie *pCookie = new C449Cookie; if (pCookie == NULL) hr = E_OUTOFMEMORY; if (SUCCEEDED(hr)) { hr = pCookie->Init(szName, pFile); } if (SUCCEEDED(hr)) { pCookie->AddRef(); *pp449Cookie = pCookie; } else if (pCookie) { delete pCookie; } return hr; } /*=================================================================== C449Cookie::QueryInterface C449Cookie::AddRef C449Cookie::Release IUnknown members for C449Cookie object. ===================================================================*/ STDMETHODIMP C449Cookie::QueryInterface(REFIID riid, VOID **ppv) { // should never be called Assert(FALSE); *ppv = NULL; return E_NOINTERFACE; } STDMETHODIMP_(ULONG) C449Cookie::AddRef() { return InterlockedIncrement(&m_cRefs); } STDMETHODIMP_(ULONG) C449Cookie::Release() { LONG cRefs = InterlockedDecrement(&m_cRefs); if (cRefs) return cRefs; delete this; return 0; }
25.625945
89
0.436625
npocmaka
6f1bcda59f47ce894a61e4f743de58b2941f4687
20,321
cpp
C++
lv_cpp/core/LvObj.cpp
lvgl/lv_binding_cpp
5ce27254ac8526dd1ca61e883785ed2606076a68
[ "MIT" ]
7
2021-07-26T12:26:48.000Z
2022-03-19T16:30:56.000Z
lv_cpp/core/LvObj.cpp
lvgl/lv_binding_cpp
5ce27254ac8526dd1ca61e883785ed2606076a68
[ "MIT" ]
4
2021-07-15T21:31:48.000Z
2022-02-03T11:48:16.000Z
lv_cpp/core/LvObj.cpp
kisvegabor/lv_binding_cpp
5ce27254ac8526dd1ca61e883785ed2606076a68
[ "MIT" ]
2
2021-10-06T00:59:52.000Z
2022-02-18T15:03:51.000Z
/* * LvObj.cpp * * Created on: Jun 24, 2021 * Author: fstuffdev */ #include "LvObj.h" namespace lvglpp { LvObj::LvObj() : LvObj(NULL){ } LvObj::LvObj(LvObj* Parent) { if(Parent) cObj.reset(lv_obj_create(Parent->raw())); else cObj.reset(lv_obj_create(lv_scr_act())); } lv_obj_t* LvObj::raw() { return cObj.get(); } LvObj::~LvObj() { } LvObj& LvObj::setCObj(lv_obj_t* _cObj) { if(_cObj) cObj.reset(_cObj); return *this; } LvObj& LvObj::setUserData(void *user_data){ lv_obj_set_user_data(cObj.get(),user_data); return *this; } void *LvObj::getUserData() const noexcept { return lv_obj_get_user_data(cObj.get()); } lv_coord_t LvObj::dpx(lv_coord_t n){ return lv_obj_dpx(cObj.get(),n); } LvObj& LvObj::del(){ lv_obj_del(cObj.get()); return *this; } LvObj& LvObj::clean(){ lv_obj_clean(cObj.get()); return *this; } LvObj& LvObj::delDelayed(uint32_t delay_ms){ lv_obj_del_delayed(cObj.get(),delay_ms); return *this; } LvObj& LvObj::delAsync(){ lv_obj_del_async(cObj.get()); return *this; } LvObj& LvObj::setParent(LvObj *parent){ lv_obj_set_parent(cObj.get(),parent->raw()); return *this; } LvObj& LvObj::moveToIndex(int32_t index){ lv_obj_move_to_index(cObj.get(),index); return *this; } lv_obj_t *LvObj::getScreen() const noexcept { return lv_obj_get_screen(cObj.get()); } lv_disp_t *LvObj::getDisp() const noexcept { return lv_obj_get_disp(cObj.get()); } lv_obj_t *LvObj::getParent() const noexcept { return lv_obj_get_parent(cObj.get()); } lv_obj_t *LvObj::getChild(int32_t id) const noexcept { return lv_obj_get_child(cObj.get(),id); } uint32_t LvObj::getChildCnt() const noexcept { return lv_obj_get_child_cnt(cObj.get()); } uint32_t LvObj::getIndex() const noexcept { return lv_obj_get_index(cObj.get()); } LvObj& LvObj::moveForeground(){ lv_obj_move_foreground(cObj.get()); return *this; } LvObj& LvObj::moveBackground(){ lv_obj_move_background(cObj.get()); return *this; } lv_flex_flow_t LvObj::getStyleFlexFlow(uint32_t part) const noexcept { return lv_obj_get_style_flex_flow(cObj.get(),part); } lv_flex_align_t LvObj::getStyleFlexMainPlace(uint32_t part) const noexcept { return lv_obj_get_style_flex_main_place(cObj.get(),part); } lv_flex_align_t LvObj::getStyleFlexCrossPlace(uint32_t part) const noexcept { return lv_obj_get_style_flex_cross_place(cObj.get(),part); } lv_flex_align_t LvObj::getStyleFlexTrackPlace(uint32_t part) const noexcept { return lv_obj_get_style_flex_track_place(cObj.get(),part); } uint8_t LvObj::getStyleFlexGrow(uint32_t part) const noexcept { return lv_obj_get_style_flex_grow(cObj.get(),part); } const lv_coord_t *LvObj::getStyleGridRowDscArray(uint32_t part) const noexcept { return lv_obj_get_style_grid_row_dsc_array(cObj.get(),part); } const lv_coord_t *LvObj::getStyleGridColumnDscArray(uint32_t part) const noexcept { return lv_obj_get_style_grid_column_dsc_array(cObj.get(),part); } lv_grid_align_t LvObj::getStyleGridRowAlign(uint32_t part) const noexcept { return lv_obj_get_style_grid_row_align(cObj.get(),part); } lv_grid_align_t LvObj::getStyleGridColumnAlign(uint32_t part) const noexcept { return lv_obj_get_style_grid_column_align(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellColumnPos(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_column_pos(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellColumnSpan(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_column_span(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellRowPos(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_row_pos(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellRowSpan(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_row_span(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellXAlign(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_x_align(cObj.get(),part); } lv_coord_t LvObj::getStyleGridCellYAlign(uint32_t part) const noexcept { return lv_obj_get_style_grid_cell_y_align(cObj.get(),part); } lv_theme_t *LvObj::getTheme() const noexcept { return lv_theme_get_from_obj(cObj.get()); } struct _lv_event_dsc_t *LvObj::addEventCb(lv_event_cb_t event_cb, lv_event_code_t filter, void *user_data){ return lv_obj_add_event_cb(cObj.get(),event_cb,filter,user_data); } bool LvObj::removeEventCb(lv_event_cb_t event_cb){ return lv_obj_remove_event_cb(cObj.get(),event_cb); } bool LvObj::removeEventCbWithUserData(lv_event_cb_t event_cb, const void *user_data){ return lv_obj_remove_event_cb_with_user_data(cObj.get(),event_cb,user_data); } bool LvObj::removeEventDsc(struct _lv_event_dsc_t *event_dsc){ return lv_obj_remove_event_dsc(cObj.get(),event_dsc); } LvObj& LvObj::classInitObj(){ lv_obj_class_init_obj(cObj.get()); return *this; } LvObj& LvObj::destruct(){ _lv_obj_destruct(cObj.get()); return *this; } bool LvObj::isEditable(){ return lv_obj_is_editable(cObj.get()); } bool LvObj::isGroupDef(){ return lv_obj_is_group_def(cObj.get()); } LvObj& LvObj::addFlag(lv_obj_flag_t f){ lv_obj_add_flag(cObj.get(),f); return *this; } LvObj& LvObj::clearFlag(lv_obj_flag_t f){ lv_obj_clear_flag(cObj.get(),f); return *this; } LvObj& LvObj::addState(lv_state_t state){ lv_obj_add_state(cObj.get(),state); return *this; } LvObj& LvObj::clearState(lv_state_t state){ lv_obj_clear_state(cObj.get(),state); return *this; } bool LvObj::hasFlag(lv_obj_flag_t f){ return lv_obj_has_flag(cObj.get(),f); } bool LvObj::hasFlagAny(lv_obj_flag_t f){ return lv_obj_has_flag_any(cObj.get(),f); } lv_state_t LvObj::getState() const noexcept { return lv_obj_get_state(cObj.get()); } bool LvObj::hasState(lv_state_t state){ return lv_obj_has_state(cObj.get(),state); } void *LvObj::getGroup() const noexcept { return lv_obj_get_group(cObj.get()); } LvObj& LvObj::allocateSpecAttr(){ lv_obj_allocate_spec_attr(cObj.get()); return *this; } bool LvObj::checkType(const lv_obj_class_t *class_p){ return lv_obj_check_type(cObj.get(),class_p); } bool LvObj::hasClass(const lv_obj_class_t *class_p){ return lv_obj_has_class(cObj.get(),class_p); } const lv_obj_class_t *LvObj::getClass() const noexcept { return lv_obj_get_class(cObj.get()); } bool LvObj::isValid(){ return lv_obj_is_valid(cObj.get()); } LvObj& LvObj::setScrollbarMode(lv_scrollbar_mode_t mode){ lv_obj_set_scrollbar_mode(cObj.get(),mode); return *this; } LvObj& LvObj::setScrollDir(lv_dir_t dir){ lv_obj_set_scroll_dir(cObj.get(),dir); return *this; } LvObj& LvObj::setScrollSnapX(lv_scroll_snap_t align){ lv_obj_set_scroll_snap_x(cObj.get(),align); return *this; } LvObj& LvObj::setScrollSnapY(lv_scroll_snap_t align){ lv_obj_set_scroll_snap_y(cObj.get(),align); return *this; } lv_scrollbar_mode_t LvObj::getScrollbarMode() const noexcept { return lv_obj_get_scrollbar_mode(cObj.get()); } lv_dir_t LvObj::getScrollDir() const noexcept { return lv_obj_get_scroll_dir(cObj.get()); } lv_scroll_snap_t LvObj::getScrollSnapX() const noexcept { return lv_obj_get_scroll_snap_x(cObj.get()); } lv_scroll_snap_t LvObj::getScrollSnapY() const noexcept { return lv_obj_get_scroll_snap_y(cObj.get()); } lv_coord_t LvObj::getScrollX() const noexcept { return lv_obj_get_scroll_x(cObj.get()); } lv_coord_t LvObj::getScrollY() const noexcept { return lv_obj_get_scroll_y(cObj.get()); } lv_coord_t LvObj::getScrollTop() const noexcept { return lv_obj_get_scroll_top(cObj.get()); } lv_coord_t LvObj::getScrollBottom() const noexcept { return lv_obj_get_scroll_bottom(cObj.get()); } lv_coord_t LvObj::getScrollLeft() const noexcept { return lv_obj_get_scroll_left(cObj.get()); } lv_coord_t LvObj::getScrollRight() const noexcept { return lv_obj_get_scroll_right(cObj.get()); } LvObj& LvObj::scrollBy(lv_coord_t x, lv_coord_t y, lv_anim_enable_t anim_en){ lv_obj_scroll_by(cObj.get(),x,y,anim_en); return *this; } LvObj& LvObj::scrollTo(lv_coord_t x, lv_coord_t y, lv_anim_enable_t anim_en){ lv_obj_scroll_to(cObj.get(),x,y,anim_en); return *this; } LvObj& LvObj::scrollToX(lv_coord_t x, lv_anim_enable_t anim_en){ lv_obj_scroll_to_x(cObj.get(),x,anim_en); return *this; } LvObj& LvObj::scrollToY(lv_coord_t y, lv_anim_enable_t anim_en){ lv_obj_scroll_to_y(cObj.get(),y,anim_en); return *this; } LvObj& LvObj::scrollToView(lv_anim_enable_t anim_en){ lv_obj_scroll_to_view(cObj.get(),anim_en); return *this; } LvObj& LvObj::scrollToViewRecursive(lv_anim_enable_t anim_en){ lv_obj_scroll_to_view_recursive(cObj.get(),anim_en); return *this; } bool LvObj::isScrolling(){ return lv_obj_is_scrolling(cObj.get()); } LvObj& LvObj::updateSnap(lv_anim_enable_t anim_en){ lv_obj_update_snap(cObj.get(),anim_en); return *this; } LvObj& LvObj::getScrollbarArea(lv_area_t *hor_area, lv_area_t *ver_area){ lv_obj_get_scrollbar_area(cObj.get(),hor_area,ver_area); return *this; } LvObj& LvObj::scrollbarInvalidate(){ lv_obj_scrollbar_invalidate(cObj.get()); return *this; } LvObj& LvObj::readjustScroll(lv_anim_enable_t anim_en){ lv_obj_readjust_scroll(cObj.get(),anim_en); return *this; } lv_obj_t *LvObj::lvIndevSearchObj(lv_point_t *point){ return lv_indev_search_obj(cObj.get(),point); } LvObj& LvObj::lvGroupRemoveObj(){ lv_group_remove_obj(cObj.get()); return *this; } LvObj& LvObj::lvGroupFocusObj(){ lv_group_focus_obj(cObj.get()); return *this; } LvObj& LvObj::setPos(lv_coord_t x, lv_coord_t y){ lv_obj_set_pos(cObj.get(),x,y); return *this; } LvObj& LvObj::setX(lv_coord_t x){ lv_obj_set_x(cObj.get(),x); return *this; } LvObj& LvObj::setY(lv_coord_t y){ lv_obj_set_y(cObj.get(),y); return *this; } bool LvObj::refrSize(){ return lv_obj_refr_size(cObj.get()); } LvObj& LvObj::setSize(lv_coord_t w, lv_coord_t h){ lv_obj_set_size(cObj.get(),w,h); return *this; } LvObj& LvObj::setWidth(lv_coord_t w){ lv_obj_set_width(cObj.get(),w); return *this; } LvObj& LvObj::setHeight(lv_coord_t h){ lv_obj_set_height(cObj.get(),h); return *this; } LvObj& LvObj::setContentWidth(lv_coord_t w){ lv_obj_set_content_width(cObj.get(),w); return *this; } LvObj& LvObj::setContentHeight(lv_coord_t h){ lv_obj_set_content_height(cObj.get(),h); return *this; } LvObj& LvObj::setLayout(uint32_t layout){ lv_obj_set_layout(cObj.get(),layout); return *this; } bool LvObj::isLayoutPositioned(){ return lv_obj_is_layout_positioned(cObj.get()); } LvObj& LvObj::markLayoutAsDirty(){ lv_obj_mark_layout_as_dirty(cObj.get()); return *this; } LvObj& LvObj::updateLayout(){ lv_obj_update_layout(cObj.get()); return *this; } LvObj& LvObj::setAlign(lv_align_t align){ lv_obj_set_align(cObj.get(),align); return *this; } LvObj& LvObj::align(lv_align_t align, lv_coord_t x_ofs, lv_coord_t y_ofs){ lv_obj_align(cObj.get(),align,x_ofs,y_ofs); return *this; } LvObj& LvObj::alignTo(const lv_obj_t *base, lv_align_t align, lv_coord_t x_ofs, lv_coord_t y_ofs){ lv_obj_align_to(cObj.get(),base,align,x_ofs,y_ofs); return *this; } LvObj& LvObj::getCoords(lv_area_t *coords){ lv_obj_get_coords(cObj.get(),coords); return *this; } lv_coord_t LvObj::getX() const noexcept { return lv_obj_get_x(cObj.get()); } lv_coord_t LvObj::getX2() const noexcept { return lv_obj_get_x2(cObj.get()); } lv_coord_t LvObj::getY() const noexcept { return lv_obj_get_y(cObj.get()); } lv_coord_t LvObj::getY2() const noexcept { return lv_obj_get_y2(cObj.get()); } lv_coord_t LvObj::getWidth() const noexcept { return lv_obj_get_width(cObj.get()); } lv_coord_t LvObj::getHeight() const noexcept { return lv_obj_get_height(cObj.get()); } lv_coord_t LvObj::getContentWidth() const noexcept { return lv_obj_get_content_width(cObj.get()); } lv_coord_t LvObj::getContentHeight() const noexcept { return lv_obj_get_content_height(cObj.get()); } LvObj& LvObj::getContentCoords(lv_area_t *area){ lv_obj_get_content_coords(cObj.get(),area); return *this; } lv_coord_t LvObj::getSelfWidth() const noexcept { return lv_obj_get_self_width(cObj.get()); } lv_coord_t LvObj::getSelfHeight() const noexcept { return lv_obj_get_self_height(cObj.get()); } bool LvObj::refreshSelfSize(){ return lv_obj_refresh_self_size(cObj.get()); } LvObj& LvObj::refrPos(){ lv_obj_refr_pos(cObj.get()); return *this; } LvObj& LvObj::moveTo(lv_coord_t x, lv_coord_t y){ lv_obj_move_to(cObj.get(),x,y); return *this; } LvObj& LvObj::moveChildrenBy(lv_coord_t x_diff, lv_coord_t y_diff, bool ignore_floating){ lv_obj_move_children_by(cObj.get(),x_diff,y_diff,ignore_floating); return *this; } LvObj& LvObj::invalidateArea(const lv_area_t *area){ lv_obj_invalidate_area(cObj.get(),area); return *this; } LvObj& LvObj::invalidate(){ lv_obj_invalidate(cObj.get()); return *this; } bool LvObj::areaIsVisible(lv_area_t *area){ return lv_obj_area_is_visible(cObj.get(),area); } bool LvObj::isVisible(){ return lv_obj_is_visible(cObj.get()); } LvObj& LvObj::setExtClickArea(lv_coord_t size){ lv_obj_set_ext_click_area(cObj.get(),size); return *this; } LvObj& LvObj::getClickArea(lv_area_t *area){ lv_obj_get_click_area(cObj.get(),area); return *this; } bool LvObj::hitTest(const lv_point_t *point){ return lv_obj_hit_test(cObj.get(),point); } LvObj& LvObj::addStyle(LvStyle *style, lv_style_selector_t selector){ lv_obj_add_style(cObj.get(),style->raw(),selector); return *this; } LvObj& LvObj::removeStyle(LvStyle *style, lv_style_selector_t selector){ lv_obj_remove_style(cObj.get(),style->raw(),selector); return *this; } LvObj& LvObj::refreshStyle(lv_style_selector_t selector, lv_style_prop_t prop){ lv_obj_refresh_style(cObj.get(),selector,prop); return *this; } lv_style_value_t LvObj::getStyleProp(lv_part_t part, lv_style_prop_t prop) const noexcept { return lv_obj_get_style_prop(cObj.get(),part,prop); } LvObj& LvObj::setLocalStyleProp(lv_style_prop_t prop, lv_style_value_t value, lv_style_selector_t selector){ lv_obj_set_local_style_prop(cObj.get(),prop,value,selector); return *this; } lv_res_t LvObj::getLocalStyleProp(lv_style_prop_t prop, lv_style_value_t *value, lv_style_selector_t selector) const noexcept { return lv_obj_get_local_style_prop(cObj.get(),prop,value,selector); } bool LvObj::removeLocalStyleProp(lv_style_prop_t prop, lv_style_selector_t selector){ return lv_obj_remove_local_style_prop(cObj.get(),prop,selector); } LvObj& LvObj::styleCreateTransition(lv_part_t part, lv_state_t prev_state, lv_state_t new_state, const _lv_obj_style_transition_dsc_t *tr_dsc){ _lv_obj_style_create_transition(cObj.get(),part,prev_state,new_state,tr_dsc); return *this; } _lv_style_state_cmp_t LvObj::styleStateCompare(lv_state_t state1, lv_state_t state2){ return _lv_obj_style_state_compare(cObj.get(),state1,state2); } LvObj& LvObj::fadeIn(uint32_t time, uint32_t delay){ lv_obj_fade_in(cObj.get(),time,delay); return *this; } LvObj& LvObj::fadeOut(uint32_t time, uint32_t delay){ lv_obj_fade_out(cObj.get(),time,delay); return *this; } LvObj& LvObj::initDrawRectDsc(uint32_t part, lv_draw_rect_dsc_t *draw_dsc){ lv_obj_init_draw_rect_dsc(cObj.get(),part,draw_dsc); return *this; } LvObj& LvObj::initDrawLabelDsc(uint32_t part, lv_draw_label_dsc_t *draw_dsc){ lv_obj_init_draw_label_dsc(cObj.get(),part,draw_dsc); return *this; } LvObj& LvObj::initDrawImgDsc(uint32_t part, lv_draw_img_dsc_t *draw_dsc){ lv_obj_init_draw_img_dsc(cObj.get(),part,draw_dsc); return *this; } LvObj& LvObj::initDrawLineDsc(uint32_t part, lv_draw_line_dsc_t *draw_dsc){ lv_obj_init_draw_line_dsc(cObj.get(),part,draw_dsc); return *this; } LvObj& LvObj::initDrawArcDsc(uint32_t part, lv_draw_arc_dsc_t *draw_dsc){ lv_obj_init_draw_arc_dsc(cObj.get(),part,draw_dsc); return *this; } lv_coord_t LvObj::calculateExtDrawSize(uint32_t part){ return lv_obj_calculate_ext_draw_size(cObj.get(),part); } LvObj& LvObj::refreshExtDrawSize(){ lv_obj_refresh_ext_draw_size(cObj.get()); return *this; } lv_coord_t LvObj::getExtDrawSize() const noexcept { return _lv_obj_get_ext_draw_size(cObj.get()); } LvObj& LvObj::setFlexFlow(lv_flex_flow_t flow){ lv_obj_set_flex_flow(cObj.get(),flow); return *this; } LvObj& LvObj::setFlexAlign(lv_flex_align_t main_place, lv_flex_align_t cross_place, lv_flex_align_t track_place){ lv_obj_set_flex_align(cObj.get(),main_place,cross_place,track_place); return *this; } LvObj& LvObj::setFlexGrow(uint8_t grow){ lv_obj_set_flex_grow(cObj.get(),grow); return *this; } LvObj& LvObj::setStyleFlexFlow(lv_flex_flow_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_flow(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleFlexMainPlace(lv_flex_align_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_main_place(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleFlexCrossPlace(lv_flex_align_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_cross_place(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleFlexTrackPlace(lv_flex_align_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_track_place(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleFlexGrow(uint8_t value, lv_style_selector_t selector){ lv_obj_set_style_flex_grow(cObj.get(),value,selector); return *this; } LvObj& LvObj::setGridDscArray(const lv_coord_t col_dsc[], const lv_coord_t row_dsc[]){ lv_obj_set_grid_dsc_array(cObj.get(),col_dsc,row_dsc); return *this; } LvObj& LvObj::setGridAlign(lv_grid_align_t column_align, lv_grid_align_t row_align){ lv_obj_set_grid_align(cObj.get(),column_align,row_align); return *this; } LvObj& LvObj::setGridCell(lv_grid_align_t x_align, uint8_t col_pos, uint8_t col_span, lv_grid_align_t y_align, uint8_t row_pos, uint8_t row_span){ lv_obj_set_grid_cell(cObj.get(),x_align,col_pos,col_span,y_align,row_pos,row_span); return *this; } LvObj& LvObj::setStyleGridRowDscArray(const lv_coord_t value[], lv_style_selector_t selector){ lv_obj_set_style_grid_row_dsc_array(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridColumnDscArray(const lv_coord_t value[], lv_style_selector_t selector){ lv_obj_set_style_grid_column_dsc_array(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridRowAlign(lv_grid_align_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_row_align(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridColumnAlign(lv_grid_align_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_column_align(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellColumnPos(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_column_pos(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellColumnSpan(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_column_span(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellRowPos(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_row_pos(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellRowSpan(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_row_span(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellXAlign(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_x_align(cObj.get(),value,selector); return *this; } LvObj& LvObj::setStyleGridCellYAlign(lv_coord_t value, lv_style_selector_t selector){ lv_obj_set_style_grid_cell_y_align(cObj.get(),value,selector); return *this; } /* The Cpp event dispatcher */ void LvObj::EventDispatcher(lv_event_t *e) { LvObj *_Obj = static_cast<LvObj*>(e->user_data); std::list<eventBind_t>::iterator eventIter; if (_Obj) { /* Search in registered events */ for (eventIter = _Obj->eventRegister.begin(); eventIter != _Obj->eventRegister.end(); eventIter++) { if (eventIter->evCode == e->code) { /* Call the event */ if (eventIter->evCallback) (*(eventIter->evCallback))(e); } } } } /* Enable the related code Callback */ LvObj& LvObj::setCallback(lv_event_code_t code, LvEvent *Cb) { eventBind_t eventToRegister; eventToRegister.evCallback = Cb; eventToRegister.evCode = code; /* Setting Callback to EventDispatcher sacrificing user_data of callback */ this->addEventCb(LvObj::EventDispatcher, code, (void*) this); eventRegister.push_back(eventToRegister); return *this; } } /* namespace lvglpp */
28.341702
146
0.771763
lvgl
6f1ce37f18f27a5a0216f1df4ca5e79255e52500
3,475
hh
C++
include/util/Singleton.hh
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
1
2018-04-14T08:53:04.000Z
2018-04-14T08:53:04.000Z
include/util/Singleton.hh
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
23
2015-01-13T10:57:36.000Z
2015-11-25T17:49:27.000Z
include/util/Singleton.hh
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
null
null
null
#ifndef SINGLETON_HH #define SINGLETON_HH #include <stdexcept> #include <cstdlib> #include <mutex> namespace g4 { namespace util { template<typename T> bool instanceExists(); /** * @short A simple, non-thread-safe singleton template. * * You have to inherit it with the class being declared as parameter. * * The creation is protected at runtime level (just one instance), * compile-time protection can be achieved by having a private * constructor in the class and making the template friend. * * The instance is automatically destroyed when the program ends. * * Inspiration: http://www.codeproject.com/Articles/4750/Singleton-Pattern-A-review-and-analysis-of-existin * * According to Alexandrescu's terminology (see Modern C++ Design), this is a create-new, * phoenix, non-thread-safe singleton. * * TODO: Check this thread-safety after the change. * * @code * class AClass : public Singleton<AClass> { }; * AClass::Instance().DoSomething(); * * class AnotherClass : public Singleton<AnotherClass> { * private: * AnotherClass() { } * friend class Singleton<AnotherClass>; * } * @endcode */ template<typename T> class Singleton { public: /** * @short Get reference to the valid instance. */ static T& Instance() { if (!_instance) { #ifdef G4MULTITHREADED _mutex.lock(); #endif if (!_instance) { _instance = new T(); } #ifdef G4MULTITHREADED _mutex.unlock(); #endif } return *_instance; } friend bool instanceExists<T>(); protected: Singleton() { if (_instance) { throw std::runtime_error("Attempt to create multiple instances of the singleton class."); } _instance = static_cast<T*>(this); // atexit(Singleton<T>::Destroy); } virtual ~Singleton() { _instance = 0; // enables further re-creation } private: Singleton(const Singleton&); Singleton& operator= (const Singleton&); static T* _instance; static void Destroy() // TODO: Reconsider using it { delete _instance; } #ifdef G4MULTITHREADED static std::mutex _mutex; #endif }; template<typename T> T* Singleton<T>::_instance = 0; #ifdef G4MULTITHREADED template<typename T> std::mutex Singleton<T>::_mutex; #endif /** * @short Is an instance of singleton class T already created? * * Defined outside the class not to spoil the class namespace. */ template<typename T> bool instanceExists() { return T::_instance != 0; } } } #endif // SINGLETON_HH
28.958333
116
0.488345
janpipek
6f1dd15915c59fcca8fb365fc00616914ba42b0d
2,152
cc
C++
chromecast/browser/extensions/cast_extension_host_delegate.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chromecast/browser/extensions/cast_extension_host_delegate.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chromecast/browser/extensions/cast_extension_host_delegate.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/browser/extensions/cast_extension_host_delegate.h" #include "base/logging.h" #include "base/no_destructor.h" #include "chromecast/browser/extensions/cast_extension_web_contents_observer.h" #include "extensions/browser/media_capture_util.h" #include "extensions/browser/serial_extension_host_queue.h" namespace extensions { CastExtensionHostDelegate::CastExtensionHostDelegate() {} CastExtensionHostDelegate::~CastExtensionHostDelegate() {} void CastExtensionHostDelegate::OnExtensionHostCreated( content::WebContents* web_contents) { CastExtensionWebContentsObserver::CreateForWebContents(web_contents); } void CastExtensionHostDelegate::OnRenderViewCreatedForBackgroundPage( ExtensionHost* host) {} content::JavaScriptDialogManager* CastExtensionHostDelegate::GetJavaScriptDialogManager() { NOTREACHED(); return nullptr; } void CastExtensionHostDelegate::CreateTab( std::unique_ptr<content::WebContents> web_contents, const std::string& extension_id, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture) { NOTREACHED(); } void CastExtensionHostDelegate::ProcessMediaAccessRequest( content::WebContents* web_contents, const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback, const Extension* extension) { // Allow access to the microphone and/or camera. media_capture_util::GrantMediaStreamRequest( web_contents, request, callback, extension); } bool CastExtensionHostDelegate::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, content::MediaStreamType type, const Extension* extension) { return media_capture_util::CheckMediaAccessPermission(type, extension); } ExtensionHostQueue* CastExtensionHostDelegate::GetExtensionHostQueue() const { static base::NoDestructor<SerialExtensionHostQueue> queue; return queue.get(); } } // namespace extensions
32.606061
79
0.798792
zipated
6f1e713f595884b4d652c9ae231061b70f145424
805
hpp
C++
inc/GraphicsLib/ImGui/ImGuiImage.hpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
1
2020-07-13T18:10:33.000Z
2020-07-13T18:10:33.000Z
inc/GraphicsLib/ImGui/ImGuiImage.hpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
null
null
null
inc/GraphicsLib/ImGui/ImGuiImage.hpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
null
null
null
#pragma once #include <GraphicsLib/Graphics/GPUResource/ShaderResource/Texture/Texture2D/Base/ITexture2D.hpp> #include <GraphicsLib/Graphics/GPUResource/RenderTarget/IRenderTarget.hpp> #include <GraphicsLib/Graphics/GPUResource/MultipleRenderTargets/IMultipleRenderTargets.hpp> #include <ThirdParty/ExtendedImGui/ImGui/imgui.h> namespace ImGui { void Image(std::shared_ptr<cg::ITexture2D> texture, const ImVec2& size); void Image(std::shared_ptr<cg::IRenderTarget> renderTarget, const ImVec2& size); void Image(std::shared_ptr<cg::IMultipleRenderTargets> mrt, int index, const ImVec2& size); void ImageDepth(std::shared_ptr<cg::IDepthStencilBuffer> depthStencilBuffer, const ImVec2& size); void ImageStencil(std::shared_ptr<cg::IDepthStencilBuffer> depthStencilBuffer, const ImVec2& size); }
40.25
100
0.81118
Sushiwave
6f1ece7ed80cb3a9c5d6e23c842ca150dc61a491
2,627
cpp
C++
QTfrontend/ui/widget/databrowser.cpp
roman-murashov/hedgewars
74f633d76bf95674f68f6872472bd21825f1f8c0
[ "Apache-2.0" ]
null
null
null
QTfrontend/ui/widget/databrowser.cpp
roman-murashov/hedgewars
74f633d76bf95674f68f6872472bd21825f1f8c0
[ "Apache-2.0" ]
null
null
null
QTfrontend/ui/widget/databrowser.cpp
roman-murashov/hedgewars
74f633d76bf95674f68f6872472bd21825f1f8c0
[ "Apache-2.0" ]
null
null
null
/* * Hedgewars, a free turn based strategy game * Copyright (c) 2004-2015 Andrey Korotaev <unC0Rr@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @brief DataBrowser class implementation */ #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QDebug> #include <QUrl> #include "databrowser.h" const QNetworkRequest::Attribute typeAttribute = (QNetworkRequest::Attribute)(QNetworkRequest::User + 1); const QNetworkRequest::Attribute urlAttribute = (QNetworkRequest::Attribute)(QNetworkRequest::User + 2); DataBrowser::DataBrowser(QWidget *parent) : QTextBrowser(parent) { manager = new QNetworkAccessManager(this); } QVariant DataBrowser::loadResource(int type, const QUrl & name) { if(type == QTextDocument::ImageResource || type == QTextDocument::StyleSheetResource) { if(resources.contains(name.toString())) { return resources.take(name.toString()); } else if(!requestedResources.contains(name.toString())) { qDebug() << "Requesting resource" << name.toString(); requestedResources.insert(name.toString()); QNetworkRequest newRequest(QUrl("http://www.hedgewars.org" + name.toString())); newRequest.setAttribute(typeAttribute, type); newRequest.setAttribute(urlAttribute, name); QNetworkReply *reply = manager->get(newRequest); connect(reply, SIGNAL(finished()), this, SLOT(resourceDownloaded())); } } return QVariant(); } void DataBrowser::resourceDownloaded() { QNetworkReply * reply = qobject_cast<QNetworkReply *>(sender()); if(reply) { int type = reply->request().attribute(typeAttribute).toInt(); QUrl url = reply->request().attribute(urlAttribute).toUrl(); resources.insert(url.toString(), reply->readAll()); document()->addResource(type, reply->request().url(), QVariant()); update(); } }
32.8375
105
0.686334
roman-murashov
6f1f9856c88581221b21b119acd2e35b70ba3ee1
3,029
cpp
C++
BashuOJ-Code/3829.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/3829.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/3829.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<iomanip> #include<algorithm> #include<queue> #include<stack> #include<vector> #define ri register int #define ll long long using namespace std; const int MAXN=35; const int INF=0x7fffffff/2; struct que{int x,y;}; struct node{int x,y,dir;}; int n,m,q; bool map[MAXN][MAXN]; int f[MAXN][MAXN][MAXN][MAXN][4]; //空格在(Ex,Ey),走到(x,y)且(x,y)在(Ex,Ey)d方向的代价 int dist[MAXN][MAXN][4]; //棋子从起始点到(x,y)且(x,y)在空格d方向的代价 int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1}; bool vst[MAXN][MAXN]; bool ext[MAXN][MAXN][4]; int Sx,Sy,Ex,Ey,Tx,Ty; namespace FastIO { const ll L=1<<15; char buffer[L],*S,*T; inline char getchar() { if(S==T){T=(S=buffer)+fread(buffer,1,L,stdin);if(S==T)return EOF;} return *S++; } inline int getint() { ri num=0,bj=1; register char c=getchar(); while(!isdigit(c))bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(isdigit(c))num=num*10+c-'0',c=getchar(); return num*bj; } }using FastIO::getint; void BFS(int x,int y,int dir)//预处理 { queue<que>q; memset(vst,0,sizeof(vst)); for(ri i=1;i<=n;i++) for(ri j=1;j<=m;j++) f[x][y][i][j][dir]=INF; vst[x][y]=1; int fx=x+dx[dir],fy=y+dy[dir];//限制第一步的方向 if(map[fx][fy]) { f[x][y][fx][fy][dir]=0; q.push((que){fx,fy}); } while(!q.empty())//以空格为中心搜索空格可到达的点 { que now=q.front();q.pop(); if(vst[now.x][now.y])continue; vst[now.x][now.y]=1; for(ri i=0;i<4;i++) { que next=(que){now.x+dx[i],now.y+dy[i]}; if(!vst[next.x][next.y]&&map[next.x][next.y]) { f[x][y][next.x][next.y][dir]=f[x][y][now.x][now.y][dir]+1; q.push(next); } } } } void SPFA() { queue<node>q; for(ri i=1;i<=n;i++) for(ri j=1;j<=m;j++) for(ri k=0;k<4;k++)dist[i][j][k]=INF,ext[i][j][k]=0; for(ri i=0;i<4;i++) { dist[Sx][Sy][i]=f[Sx][Sy][Ex][Ey][i];//初始化dist(包括空格走到(Sx,Sy)d方向上的代价) q.push((node){Sx,Sy,i}); ext[Sx][Sy][i]=1; } while(!q.empty()) { node now=q.front();q.pop();ext[now.x][now.y][now.dir]=0; for(ri i=0;i<4;i++) { node next=(node){now.x+dx[i],now.y+dy[i],i^1}; if(!map[next.x][next.y])continue; if(dist[next.x][next.y][next.dir]>dist[now.x][now.y][now.dir]+f[now.x][now.y][next.x][next.y][now.dir]+1) { dist[next.x][next.y][next.dir]=dist[now.x][now.y][now.dir]+f[now.x][now.y][next.x][next.y][now.dir]+1; //空格从起始点移动到目标点的次数+空格和棋子交换了1次 //空格的发生了相对方向变化 if(!ext[next.x][next.y][next.dir]) { q.push(next); ext[next.x][next.y][next.dir]=1; } } } } } int main() { n=getint(),m=getint(),q=getint(); for(ri i=1;i<=n;i++) for(ri j=1;j<=m;j++) map[i][j]=getint(); for(ri i=1;i<=n;i++) for(ri j=1;j<=m;j++) for(ri k=0;k<4;k++) if(map[i][j])BFS(i,j,k); for(ri i=1;i<=q;i++) { int Ans=INF; Ex=getint(),Ey=getint(); Sx=getint(),Sy=getint(); Tx=getint(),Ty=getint(); if(Sx==Tx&&Sy==Ty){printf("0\n");continue;} SPFA(); for(ri j=0;j<4;j++) Ans=min(dist[Tx][Ty][j],Ans); printf("%d\n",Ans==INF?-1:Ans); } return 0; }
22.774436
108
0.563222
magicgh
6f20dd329fa70ab578a7ed420ddc2d0fdcf0ceff
17,714
cpp
C++
src/graph-lib/homology/_Perseus/Complexes/DenseCToplex.cpp
mitxael/SSHIVA
2cdcadb2ba49cc47d0860b88378e11a67b2cb8ed
[ "MIT" ]
1
2018-04-12T11:19:50.000Z
2018-04-12T11:19:50.000Z
src/graph-lib/homology/_Perseus/Complexes/DenseCToplex.cpp
mitxael/SSHIVA
2cdcadb2ba49cc47d0860b88378e11a67b2cb8ed
[ "MIT" ]
null
null
null
src/graph-lib/homology/_Perseus/Complexes/DenseCToplex.cpp
mitxael/SSHIVA
2cdcadb2ba49cc47d0860b88378e11a67b2cb8ed
[ "MIT" ]
null
null
null
/* * DenseCToplex.hpp * * Created on: Dec 23, 2010 * Author: Vidit */ #include "DenseCToplex.h" // makes face links and inherits birth times for lower cubes once top cubes are populated! template <typename C, typename BT> bool DenseCToplex<C,BT>::makeFaces(bool incbirth = false) { if (faced) return false; // don't make faces again, please. // iterate backwards through cube structure, adding boundary links to lower addins CVEC* curvec; // current cube vector corresponding to this addin //num topdim = cube.size(); std::vector<num> curaddin, curanch, curext; num cursz; // size of current cube vector num i; num csz = cube.size(); // backward iteration bool istop; typename CGRID::reverse_iterator rit; for (rit = cube.rbegin(); rit != cube.rend(); ++rit) { istop = (rit == cube.rbegin()) ? true : false; i = csz - (rit - cube.rbegin()) - 1; // get the addin vector for this position getAddin(i,curaddin); if (DCFACETALK) {std::cout<<"\n***** Facing: "; c_print<std::vector<num> >(curaddin);} // extract extent vector for this addin getExtForAddin(curaddin,curext); //cout<<"\n gots addin"; cin.get(); curvec = cube.at(i); // extract current vector of cubes if (curvec == NULL) {continue;} // and ignore if NULL // iterate over current vector of cubes! cursz = curvec->size(); for (num j = 0; j < cursz; ++j) { //cout<<"\ntesting position ["<<i<<","<<j<<"]"; if (cube.at(i)->at(j) == NULL) {continue;} // exclude NULL cubes if (istop && incbirth) cube.at(i)->at(j)->birth += (INITBT + 1); // get anchor for this cube getAnchorFast(j, curext, curanch); //cout<<"\n*************************anch: "; c_print<vector<num> >(curanch); // make face connections for this cell! makeFaceLinks(cube.at(i)->at(j), curaddin, curanch); } } faced = true; return faced; } template <typename C, typename BT> num DenseCToplex<C,BT>::getAddinPosFast(const std::vector<num>& advec) const { // first we add all C(n,k) for all k < size(anch)... num toret = 0; for (num i=0; i<(num)advec.size();++i) { toret += nChoosek(extent.size(),i); } return toret + lexicoPosRev(extent.size(), advec); } // writes cubical toplex to morse cell complex template <typename C, typename BT> void DenseCToplex<C,BT>::writeComplex(MComplex<C,BT>& mycomp, bool killself = true) { CVEC* curvec; for (num i = 0; i < (num)cube.size(); ++i) { curvec = cube.at(i); for (num j = 0; j < (num) curvec->size(); ++j) { if (curvec->at(j) == NULL) continue; // ignore null cubes mycomp.insertCell(curvec->at(j)); } if (killself) curvec->clear(); // remove cell vector from toplex to save memory } cube.clear(); } template <typename C, typename BT> void DenseCToplex<C,BT>::makeFaceLinks(Cell<C,BT>* curcb, const std::vector<num>& addin, const std::vector<num>& anch) { std::vector<num> fcaddin, fcanch; // face addin and anchor num cubeDim = addin.size(); Cell<C,BT>* face; C coeff; // face incidence num fcaddpos, fcancpos; if (DCFACETALK) { std::cout<<"\n\nFACING "<<*curcb<<" with addin "; c_print<std::vector<num> >(addin); std::cout<<" and anchor "; c_print<std::vector<num> >(anch); std::cin.get(); } for (num cdim = 0; cdim < 2*cubeDim; cdim+=2) { coeff = ((cdim/2) % 2 == 0) ? 1:-1; // ADDIN VECTOR: fcaddin = addin; // and remove cdim/2 th entry fcaddin.erase(fcaddin.begin()+(cdim/2)); fcaddpos = getAddinPosFast(fcaddin); // FIRST FACE fcanch = anch; fcancpos = getAnchPos(fcanch,fcaddin); if (DCFACETALK) { std::cout<<"\n>>>>> lower face, coeff "<<-coeff<<" has addin "; c_print<std::vector<num> >(fcaddin); std::cout<<" and anchor "; c_print<std::vector<num> >(fcanch); std::cout<<" at pos ["<<fcaddpos<<","<<fcancpos<<"]"; std::cin.get(); } face = cube.at(fcaddpos)->at(fcancpos); // create face if null and add boundary link if (face == NULL) { face = new Cell<C,BT>(cubeDim-1); cube.at(fcaddpos)->at(fcancpos) = face; } curcb->addBDLink(face,-coeff); // SECOND FACE fcanch = anch; fcanch.at(addin.at(cdim/2)) += ES; fcancpos = getAnchPos(fcanch,fcaddin); if (DCFACETALK) { std::cout<<"\n>>>>> upper face, coeff "<<coeff<<" has addin "; c_print<std::vector<num> >(fcaddin); std::cout<<" and anchor "; c_print<std::vector<num> >(fcanch); std::cout<<" at pos ["<<fcaddpos<<","<<fcancpos<<"]"; std::cin.get(); } face = cube.at(fcaddpos)->at(fcancpos); // create face if null and add boundary link if (face == NULL) { face = new Cell<C,BT>(cubeDim-1); cube.at(fcaddpos)->at(fcancpos) = face; } curcb->addBDLink(face,coeff); } //if (curcb->getBD().size() != 2*cubeDim) cout<<"\ncube: "<<*curcb<<" and bd "<<curcb->getBD(); } template <typename C, typename BT> void DenseCToplex<C,BT>::Destroy() { num addnum = cube.size(); //cout<<"Destroying with size: "<<addnum; cin.get(); for (num i = 0; i < (num)addnum; ++i) { // deallocate vector of cubes corresponding to this addin vector! cube.at(i)->clear(); CVEC(*(cube.at(i))).swap(*(cube.at(i))); delete cube.at(i); } cube.clear(); CGRID(cube).swap(cube); } template <typename C, typename BT> void DenseCToplex<C,BT>::Init(const std::vector<num>& ext) { num topdim = ext.size(); for (num i=0; i<topdim; i++) { extent.push_back(ext.at(i)+1); } // first make as many inner vectors as the number of addins... \sum_{j=0}^n C(n,j) = 2^n double addnum = pow((float)2,(float)topdim); if (DCTTALK) { std::cout<<"\n\n *** Init DCT with ext vec "; c_print<std::vector<num> >(ext); std::cout<<"\n *** Extent: "; c_print<std::vector<num> >(extent); std::cout<<'\n'; std::cout<<"\n *** adnum: " << addnum; } std::vector<num> curaddin, curext; CVEC* curvec; for (num i = 0; i < (num)addnum; ++i) { // extract addin vector for this dimension if(!getAddin(i,curaddin)) continue; // determine extents vector for this addin vector getExtForAddin(curaddin,curext); // now allocate appropriate sized cell vector, populate with NULLS curvec = new CVEC(vProd<num>(curext),(Cell<C,BT>*)NULL); if (DCTTALK) { std::cout<<"\n#"<<i<<", addin: "; c_print<std::vector<num> >(curaddin); std::cout<<" and extent: "; c_print<std::vector<num> >(curext); std::cout<<"\n&&&& alloc vec of size "<<vProd<num>(curext)<<" for addin "; c_print<std::vector<num> >(curaddin); std::cin.get(); } // and add curvec to "img" of addin vector cube.push_back(curvec); } } template <typename C, typename BT> bool DenseCToplex<C,BT>::getAddin(num pos, std::vector<num>& add) const // recover addin vector from lexico position { pos++; num dimpos = 0; num k = 0; num n = extent.size(); if (DCTTALK) std::cout<<"\nExtracting addin for position "<<pos; // first determine the eventual size from position do { dimpos += nChoosek(n,k); if (DCTTALK) std::cout<<"\n>>>>>>>>>>>>> n "<<n<<" k "<<k<<" dimpos "<<dimpos; if (pos <= dimpos) break; k++; } while (k <= n); // check validity of k if (k > n) return false; // adjust dimpos to be less than pos again dimpos -= (nChoosek(n,k)); num p = pos - dimpos; if (p==0) k--; // finally call lexicopos lexicoPos (n,k,p,add); if (DCTTALK) { std::cout<<"\n ... getting Addin, lexicopos call with n "<<n<<" k "<<k<<" p "<<p<<" returning "; c_print<std::vector<num> >(add); } return true; } // recovers anchor point from given position "pos" and addin vector "advec". // stores in "ans". template <typename C, typename BT> bool DenseCToplex<C,BT>::getAnchor(num pos, const std::vector<num>& advec, std::vector<num>& ans) const // recover anchor point from lexico position { std::vector<num> dext; // first, determine the extents for this addin vector! getExtForAddin(advec,dext); // now we have the extents, and can decompose to recover the anchor point! decompose<num,num>(pos, dext, ans); return true; } // recovers anchor point from given position "pos" and extents vector "ext". // stores in "ans". template <typename C, typename BT> bool DenseCToplex<C,BT>::getAnchorFast(num pos, const std::vector<num>& ext, std::vector<num>& ans) const // recover anchor point from lexico position { // now we have the extents, and can decompose to recover the anchor point! decompose<num,num>(pos, ext, ans); return true; } // recovers anchor point from given position "pos" and addin vector index "addind". // stores in "ans". template <typename C, typename BT> bool DenseCToplex<C,BT>::getAnchor(num pos, const num addind, std::vector<num>& ans) const // recover anchor point from lexico position { // extract addin vector from index! std::vector<num> advec; if (!getAddin(addind,advec)) return false; return getAnchor(pos,advec,ans); } template <typename C, typename BT> void DenseCToplex<C,BT>::getExtForAddin(const std::vector<num>& advec, std::vector<num>& ext) const { ext = extent; // inherit max possible extent... //go over addin vector, decrementing extent at each dimension found num dim = advec.size(); for (num i=0; i<dim; i++) { // if this dimension shows up in the addin vector, decrement the extent! ext.at(advec.at(i))--; } } template <typename C, typename BT> num DenseCToplex<C,BT>::getAnchPos(const std::vector<num>& anch, const num addpos) const { // recover addin vector for this addin position std::vector<num> advec; if(!getAddin(addpos,advec)) return 0; // now call the function to recover anchor position from addin vector return getAnchPos(anch,advec); } template <typename C, typename BT> num DenseCToplex<C,BT>::getAnchPos(const std::vector<num>& anch, const std::vector<num>& advec) const { num toret = 0; // now use this addin to generate extents vector std::vector<num> dext; getExtForAddin(advec,dext); // finally, use this extent vector to recompose the answer toret = recompose<num>(anch,dext); return toret; } template <typename C, typename BT> num DenseCToplex<C,BT>::getAnchPosFast(const std::vector<num>& anch, const std::vector<num>& ext) const { return recompose<num>(anch,ext); } template <typename C, typename BT> std::pair<num,bool> DenseCToplex<C,BT>::makeFromFile (std::ifstream& infile) { if (CUBTOPTALK) { std::cout<<"\n file reading "; std::cin.get(); } num topdim=0; // get top dimension of cubical set from the first line of input file if(!infile.eof()) infile >> topdim; else return std::make_pair(0,false); if(topdim<0) return std::make_pair(0,false); // negative dimension count??? i quit! std::vector<num> ext; num extval; // stores extent value num totnum = 1; // build dimension-bounding vector for(int i=0; i<topdim; i++) { // add every dimension to addins since cubes are maximal if(infile.good()) { infile >> extval; if (extval <= 0) // ignore non-positive dimension! { topdim--; if (topdim == 0) { return std::make_pair(0,false); } continue; } totnum*=extval; ext.push_back(extval); } else { // if file finishes prematurely, then the declared topdim is wrong return std::make_pair(0,false); } } // now initialize with this extent vector! Init(ext); bool incb = false; // increment births while making faces in case INITBT is encountered... // store top cube information into the appropriate spot of cube structure! num count = 0, actct = 0; num topadd = (num) pow ((float)2, (float)topdim); CVEC* topvec = cube.at(topadd-1); BT birthtime; //cout<<"\ntotnum = "<<totnum; while(infile.good() && count < totnum) { count++; // get current birth-time from file infile >> birthtime; //if (birthtime == 510) cout<<" \n 510 encountered at "<<count; //if (infile.eof()) break; if (birthtime == BANBT) continue; // ignore "banned" birthtime, as defined in Global/Pflags.h // kelly test... //if (birthtime > 513) continue; if (birthtime == INITBT) incb = true; // if INITBT is found, set flag to increment all // create new top cube and set its birth time topvec->at(count-1) = new Cell<C,BT>(topdim); topvec->at(count-1)->birth = birthtime; actct++; } if(CUBTOPTALK) { std::cout<<" File read... "; std::cin.get(); } // with top cubes loaded, make faces! makeFaces(incb); //cout<<*this; //cin.get(); return std::make_pair(actct,true); } // warning: enabling savemem kills original toplex while copying over cells to complex template <typename C, typename BT> bool DenseCToplex<C,BT>::quickWriteComplex(MComplex<C,BT>& mycomp, bool savemem = true) { if (cube.size()==0) return false; // nothing to write // obtain top dimension: num topdim = extent.size(); if (DCTSPEEDTALK){std::cout<<"\n\n *** quicksert with topdim = "<<topdim; std::cin.get();} std::set<BT> births; // now extract set of all birthtimes: CVEC* topvec = cube.at(cube.size()-1); if (topvec == NULL) return false; // no top cubes! if (DCTSPEEDTALK){std::cout<<"\n inserting births "<<topdim; std::cin.get();} // iterate over top dimensional cubes, make a set of all birth times! typename CVEC::const_iterator topit; for (topit = topvec->begin(); topit != topvec->end(); ++topit) { if(*topit != NULL) births.insert((*topit)->birth); } // and get total number of birth times encountered: // create birth vector for position lookup std::vector<BT> bvec; bvec.assign(births.begin(), births.end()); num bsize = bvec.size(); births.clear(); // create 3d array of cubes, a vector for each by birth and dimension: std::vector<std::vector<CVEC*>*> insertArray; make3Dvector<Cell<C,BT>*>(bsize,topdim,insertArray); // allocate array space... if (DCTSPEEDTALK) { std::cout<<"\n 3d vec called with "<<bsize<<" and "<<topdim; std::cin.get(); } // now loop over cube structure, and copy over cells to the insert Array at the appropriate spots typename CGRID::const_iterator grit; // grid iterator typename CVEC::const_iterator vit; // vector iterator CVEC* curvec; // current cube vector Cell<C,BT>* curcell; //cout<<"\nReordering..."; cin.get(); for(grit = cube.begin(); grit != cube.end(); ++grit) { curvec = *grit; if (curvec == NULL) continue; for (vit = curvec->begin(); vit != curvec->end(); ++vit) { curcell = *vit; // add current cube (if non null) to insertion structure: if (curcell == NULL) continue; // okay, this is complicated: the first dim of insertArray is the birth time, and to // find the position corresponding to the current birth we must look up the sorted // vector of births, i.e. bvec. the second dim of insertArray is just the cell dimension //print bdry of cube in case of 2 coefficients! // if (curcell->getDim() == 2) // { // //cout<<"\n bd of insert: "<<*curcell<<" is "<<curcell->getBD(); // } //cout<<"\n insert of "<<*curcell<<" attempted at: "<<getVPos<BT>(bvec,curcell->birth)<<", "<<curcell->getDim(); cin.get(); insertArray.at(getVPos<BT>(bvec,curcell->birth))->at(curcell->getDim())->push_back(curcell); } if (DCTSPEEDTALK) {std::cout<<" end of line, clearing "; std::cin.get();} if (savemem) { curvec->clear(); CVEC(*curvec).swap(*curvec); } } //cout<<"Done!"; cin.get(); if( DCTSPEEDTALK) { std::cout<<"\n Insert to cell complex.... "; std::cin.get(); } // at this point, we have the cell info stored in insertArray. // lastly, insert using insertArray! for (num btime = 0; btime < bsize; ++btime) { if (DCTSPEEDTALK) std::cout<<"\n Inserting birth: "<<bvec.at(btime); for (num curdim = 0; curdim < topdim; ++curdim) { if (DCTSPEEDTALK) { std::cout<<"\n dim: "<<curdim<<", size: "<<insertArray.at(btime)->at(curdim)->size(); //cin.get(); std::cin.get(); } mycomp.quicksert(*(insertArray.at(btime)->at(curdim))); insertArray.at(btime)->at(curdim)->clear(); } //insertArray.at(btime)->clear(); } // deallocate insertArray structure! std::vector<CVEC*>* cur2dvec; CVEC* cur1dvec; for (num i = 0; i < (num) insertArray.size(); ++i) { cur2dvec = insertArray.at(i); for (num j = 0; j < (num) cur2dvec->size(); ++j) { cur1dvec = cur2dvec->at(j); delete cur1dvec; } cur2dvec->clear(); std::vector<CVEC*>(*cur2dvec).swap(*cur2dvec); delete cur2dvec; } insertArray.clear(); vector<std::vector<CVEC*>*>(insertArray).swap(insertArray); return true; // done } // adds a single top cube via its coordinates and birth time. Call AFTER init() template<typename C, typename BT> void DenseCToplex<C,BT>::addTopCube(const std::vector<num>& coords, const BT& btime) { BT birth = btime; // store top cube information into the appropriate spot of cube structure! num topdim = coords.size(); num addinpos = (num) pow ((float)2, (float)topdim) - 1; CVEC* topvec = cube.at(addinpos); Cell<C,BT>* toins; if (birth != BANBT) { // create new top cube and set its birth time toins = new Cell<C,BT>(topdim); toins->birth = birth; //cout<<" ins pos: "<<getAnchPos(coords,addinpos)<<" vs sz "<<topvec->size(); //cin.get(); topvec->at(getAnchPos(coords,addinpos)) = toins; } } // call after Init() and AddCube() template<typename C, typename BT> void DenseCToplex<C,BT>::ComputePersistence(std::string fname = "output") { // make faces from top cubes: since only miro uses this, and he can not // stop putting in zeros, increment all the birth times just in case makeFaces(true); // write to complex MComplex<C,BT>* cptr = new MComplex<C,BT>; this->writeComplex(*cptr); //cout<<" about to cored: "; cin.get(); // perform morse coreductions AlternateAndUpdate(cptr, false, 0.2); //cubcomp.MorseWrapper_Cored(false); // compute persistence intervals of reduced complex PComplex<C,BT> pcomp; pcomp.COMPUTE_INTERVALS(*cptr); // generate output // pcomp.showBetti(); pcomp.makeOutputFiles(fname); delete cptr; }
29.47421
150
0.653099
mitxael
6f21551664d6a4ffe76fb75a24f400a79177f9f0
1,036
cpp
C++
leetcode/cpp/390_elimination_game.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/390_elimination_game.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/390_elimination_game.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/* There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers. We keep repeating the steps again, alternating left to right and right to left, until a single number remains. Find the last number that remains starting with a list of length n. Example: Input: n = 9, 1 2 3 4 5 6 7 8 9 2 4 6 8 2 6 6 Output: 6 */ // 每次操作之后仍然是等差数列,因此可以通过 // 记录初始值、间隔以及数目来表示整个数列,无需记录数列所有值 // class Solution { public: int lastRemaining(int n) { int start = 1; //当前序列的初始值 int delta = 1; //等差数列相邻数字间隔 int count = n; //等差数列当前数字个数 bool l2r = true; //从左往右 while(count > 1) { if(l2r || (count%2)) start+=delta; delta *= 2; count -= (count+1)/2; l2r = !l2r; } return start; } };
23.545455
170
0.632239
qiaotian
6f2729a5e8dce03a714376c2442e5fb626b833e2
5,644
cpp
C++
modfile/records/SrDebrRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
11
2015-07-19T08:33:00.000Z
2021-07-28T17:40:26.000Z
modfile/records/SrDebrRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
null
null
null
modfile/records/SrDebrRecord.cpp
uesp/tes5lib
07b052983f2e26b9ba798f234ada00f83c90e9a4
[ "MIT" ]
1
2015-02-28T22:52:18.000Z
2015-02-28T22:52:18.000Z
/*=========================================================================== * * File: SrDebrRecord.CPP * Author: Dave Humphrey (dave@uesp.net) * Created On: 5 December 2011 * * Description * *=========================================================================*/ /* Include Files */ #include "srDebrrecord.h" /*=========================================================================== * * Begin Subrecord Creation Array * *=========================================================================*/ BEGIN_SRSUBRECCREATE(CSrDebrRecord, CSrIdRecord) DEFINE_SRSUBRECCREATE(SR_NAME_DATA, CSrDataSubrecord::Create) DEFINE_SRSUBRECCREATE(SR_NAME_MODT, CSrDataSubrecord::Create) END_SRSUBRECCREATE() /*=========================================================================== * End of Subrecord Creation Array *=========================================================================*/ /*=========================================================================== * * Begin CSrRecord Field Map * *=========================================================================*/ BEGIN_SRFIELDMAP(CSrDebrRecord, CSrIdRecord) END_SRFIELDMAP() /*=========================================================================== * End of CObRecord Field Map *=========================================================================*/ /*=========================================================================== * * Class CSrDebrRecord Constructor * *=========================================================================*/ CSrDebrRecord::CSrDebrRecord () { } /*=========================================================================== * End of Class CSrDebrRecord Constructor *=========================================================================*/ /*=========================================================================== * * Class CSrDebrRecord Method - void Destroy (void); * *=========================================================================*/ void CSrDebrRecord::Destroy (void) { CSrIdRecord::Destroy(); } /*=========================================================================== * End of Class Method CSrDebrRecord::Destroy() *=========================================================================*/ /*=========================================================================== * * Class CSrDebrRecord Method - void InitializeNew (void); * *=========================================================================*/ void CSrDebrRecord::InitializeNew (void) { CSrIdRecord::InitializeNew(); } /*=========================================================================== * End of Class Method CSrDebrRecord::InitializeNew() *=========================================================================*/ /*=========================================================================== * * Class CSrDebrRecord Event - void OnAddSubrecord (pSubrecord); * *=========================================================================*/ void CSrDebrRecord::OnAddSubrecord (CSrSubrecord* pSubrecord) { if (pSubrecord->GetRecordType() == SR_NAME_DATA) { m_pDataData = SrCastClass(CSrDataSubrecord, pSubrecord); } else if (pSubrecord->GetRecordType() == SR_NAME_MODT) { m_pModtData = SrCastClass(CSrDataSubrecord, pSubrecord); } else { CSrIdRecord::OnAddSubrecord(pSubrecord); } } /*=========================================================================== * End of Class Event CSrDebrRecord::OnAddSubRecord() *=========================================================================*/ /*=========================================================================== * * Class CSrDebrRecord Event - void OnDeleteSubrecord (pSubrecord); * *=========================================================================*/ void CSrDebrRecord::OnDeleteSubrecord (CSrSubrecord* pSubrecord) { if (m_pDataData == pSubrecord) m_pDataData = NULL; else if (m_pModtData == pSubrecord) m_pModtData = NULL; else CSrIdRecord::OnDeleteSubrecord(pSubrecord); } /*=========================================================================== * End of Class Event CSrDebrRecord::OnDeleteSubrecord() *=========================================================================*/ /*=========================================================================== * * Begin CSrDebrRecord Get Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrDebrRecord Get Field Methods *=========================================================================*/ /*=========================================================================== * * Begin CSrDebrRecord Compare Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrDebrRecord Compare Field Methods *=========================================================================*/ /*=========================================================================== * * Begin CSrDebrRecord Set Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrDebrRecord Set Field Methods *=========================================================================*/
36.179487
78
0.289511
uesp
6f279f381c5517f9ddf7302f692f61c63fb0a09e
9,563
cpp
C++
ext/d3_queue.cpp
SymbioticLab/YAPS
1bf25abe0fe1ea7c7dec60645dda49ffcc59c7a0
[ "BSD-3-Clause" ]
null
null
null
ext/d3_queue.cpp
SymbioticLab/YAPS
1bf25abe0fe1ea7c7dec60645dda49ffcc59c7a0
[ "BSD-3-Clause" ]
1
2021-06-18T19:12:19.000Z
2021-06-18T19:12:19.000Z
ext/d3_queue.cpp
SymbioticLab/YAPS
1bf25abe0fe1ea7c7dec60645dda49ffcc59c7a0
[ "BSD-3-Clause" ]
1
2021-06-18T07:01:16.000Z
2021-06-18T07:01:16.000Z
#include "d3_queue.h" #include <assert.h> #include <iostream> #include <stdlib.h> #include <math.h> #include <iomanip> #include "../coresim/event.h" #include "../coresim/flow.h" #include "../coresim/packet.h" #include "../run/params.h" extern double get_current_time(); extern void add_to_event_queue(Event* ev); extern uint32_t dead_packets; extern DCExpParams params; extern std::vector<double> D3_allocation_counter_per_queue; extern std::vector<uint32_t> D3_num_allocations_per_queue; /* D3Queues */ D3Queue::D3Queue(uint32_t id, double rate, uint32_t limit_bytes, int location) : Queue(id, rate, limit_bytes, location) { this->demand_counter = 0; this->allocation_counter = 0; this->base_rate = 0; // base_rate is a very small value that can only send out a header-only pkt; // We set the value of base_rate used in the rate allocation algo to be set to 0 to prevent allocation_counter > rate } //D3Queue::~D3Queue() {}; void D3Queue::enque(Packet *packet) { packet->hop_count++; // hop_count starts from -1 p_arrivals += 1; b_arrivals += packet->size; if (bytes_in_queue + packet->size <= limit_bytes) { packets.push_back(packet); bytes_in_queue += packet->size; } else { // We will still keep the header (with 0 size) if the packet contains rate request if (packet->has_rrq && packet->size != 0) { assert(packet->type == NORMAL_PACKET); packet->size = 0; packets.push_back(packet); } pkt_drop++; drop(packet); // drop the payload; also count as 'drop' } packet->enque_queue_size = b_arrivals; } Packet *D3Queue::deque(double deque_time) { // since in D3 some packets has 0 size (e.g., syn, syn_ack, empty data pkts), we can't check with bytes_in_queue //if (bytes_in_queue > 0) { if (!packets.empty()) { Packet *p = packets.front(); packets.pop_front(); bytes_in_queue -= p->size; p_departures += 1; b_departures += p->size; // calculate allocated rate (a_{t+1}) if the packet is an RRQ (SYN/FIN/DATA_pkt_with_rrq) if (p->has_rrq) { allocate_rate(p); // Note: one can also allocate rate inside enque(), which doesn't affect performance (verified) } return p; } return NULL; } // rtt ~ 300 us in original D3 paper? // D3Queue::allocate_rate() follows "Snippet 1" in the original D3 paper void D3Queue::allocate_rate(Packet *packet) { assert(packet->type != ACK_PACKET && packet->type != SYN_ACK_PACKET); double rate_to_allocate = 0; double left_capacity = 0; double fair_share = 0; if (packet->type == SYN_PACKET) { // if new flow joins; assuming no duplicated SYN pkts num_active_flows++; } allocation_counter -= packet->prev_allocated_rate; demand_counter = demand_counter - packet->prev_desired_rate + packet->desired_rate; left_capacity = rate - allocation_counter; // Sometimes some counter will be negative but very close to 0. Let's treat it as within the normal error range instead of a bug //assert(allocation_counter >= 0 && demand_counter >= 0 && left_capacity >= 0); //if (allocation_counter < 0 || demand_counter < 0 || left_capacity < 0) { // std::cout << "PUPU" << std::endl; //} if (packet->type == FIN_PACKET) { // for FIN packet, exit the algorithm after returning past info & decrementing flow counter num_active_flows--; if (params.debug_event_info || (params.enable_flow_lookup && params.flow_lookup_id == packet->flow->id)) { std::cout << "At D3 Queue[" << unique_id << "]: handling FIN packet[" << packet->unique_id << "] from Flow[" << packet->flow->id << "]" << std::endl; std::cout << std::setprecision(2) << std::fixed; std::cout << "num_active_flows = " << num_active_flows << "; prev allocated = " << packet->prev_allocated_rate/1e9 << "; prev desired = " << packet->prev_desired_rate/1e9 << "; desired = " << packet->desired_rate/1e9 << std::endl; std::cout << "allocation_counter = " << allocation_counter/1e9 << "; demand_counter = " << demand_counter/1e9 << "; left_capacity = " << left_capacity/1e9 << std::endl; std::cout << std::setprecision(15) << std::fixed; } return; } fair_share = (rate - demand_counter) / num_active_flows; if (fair_share < 0) { // happens when demand_counter is > rate fair_share = 0; } if (params.debug_event_info || (params.enable_flow_lookup && params.flow_lookup_id == packet->flow->id)) { std::cout << std::setprecision(2) << std::fixed; std::cout << "At D3 Queue[" << unique_id << "]:" << std::endl; std::cout << "allocate rate for Packet[" << packet->unique_id << "]{" << packet->seq_no << "} from Flow["<< packet->flow->id << "]; type = " << packet->type << "; size = " << packet->size << " at Queue[" << unique_id << "]" << std::endl; std::cout << "num_active_flows = " << num_active_flows << "; prev allocated = " << packet->prev_allocated_rate/1e9 << "; prev desired = " << packet->prev_desired_rate/1e9 << "; desired = " << packet->desired_rate/1e9 << std::endl; std::cout << "allocation_counter = " << allocation_counter/1e9 << "; demand_counter = " << demand_counter/1e9 << "; left_capacity = " << left_capacity/1e9 << "; fair_share = " << fair_share/1e9 << std::endl; } if (left_capacity > packet->desired_rate) { rate_to_allocate = packet->desired_rate + fair_share; } else { rate_to_allocate = left_capacity; // when desired_rate can't be satisfied, do in a greedy way (FCFS) } rate_to_allocate = std::max(rate_to_allocate, base_rate); if (rate_to_allocate == base_rate) { // this happens when 'rate_to_allocate' = 0 packet->marked_base_rate = true; if (params.debug_event_info || (params.enable_flow_lookup && params.flow_lookup_id == packet->flow->id)) { std::cout << "assign packet[" << packet->unique_id << "] from Flow[" << packet->flow->id << "] base rate" << std::endl; } } // Yiwen: set base_rate value to be 0 to prevent allocation_counter > rate; otherwise left_capacity becomes negative in next RTT allocation_counter += rate_to_allocate; if (params.debug_event_info || (params.enable_flow_lookup && params.flow_lookup_id == packet->flow->id)) { std::cout << "rate_to_allocate = " << rate_to_allocate/1e9 << " Gbps; allocation counter = " << allocation_counter/1e9 << " Gbps." << std::endl; std::cout << std::setprecision(15) << std::fixed; } // logging if (params.big_switch && params.traffic_pattern == 1) { D3_allocation_counter_per_queue[unique_id] += (allocation_counter/1e9); D3_num_allocations_per_queue[unique_id]++; if (allocation_counter/1e9 > 1000) { // watch for unusual allocation counter value std::cout << "PUPU: allocation counter = " << allocation_counter/1e9 << std::endl; std::cout << std::setprecision(2) << std::fixed; std::cout << "At D3 Queue[" << unique_id << "]:" << std::endl; std::cout << "allocate rate for Packet[" << packet->unique_id << "] from Flow["<< packet->flow->id << "]; type = " << packet->type << " at Queue[" << unique_id << "]" << std::endl; std::cout << "num_active_flows = " << num_active_flows << "; prev allocated = " << packet->prev_allocated_rate/1e9 << "; prev desired = " << packet->prev_desired_rate/1e9 << "; desired = " << packet->desired_rate/1e9 << std::endl; std::cout << "; demand_counter = " << demand_counter/1e9 << "; left_capacity = " << left_capacity/1e9 << "; fair_share = " << fair_share/1e9 << std::endl; std::cout << "rate_to_allocate = " << rate_to_allocate/1e9 << " Gbps; allocation counter = " << allocation_counter/1e9 << " Gbps." << std::endl; std::cout << std::setprecision(15) << std::fixed; } } packet->curr_rates_per_hop.push_back(rate_to_allocate); } double D3Queue::get_transmission_delay(Packet *packet) { double td; if (packet->has_rrq && packet->size == 0) { // add back hdr_size when handling hdr_only RRQ packets (their packet->size is set to 0 to avoid dropping) ////|| packet->ack_pkt_with_rrq) { // ACK to DATA RRQ is also made 0 size td = params.hdr_size * 8.0 / rate; } else { // D3 router forwards other packet normally td = packet->size * 8.0 / rate; } return td; } void D3Queue::drop(Packet *packet) { packet->flow->pkt_drop++; if (packet->seq_no < packet->flow->size) { packet->flow->data_pkt_drop++; } if (packet->type == SYN_PACKET) { assert(false); } if (packet->type == SYN_ACK_PACKET) { assert(false); } if (packet->type == ACK_PACKET) { packet->flow->ack_pkt_drop++; if (packet->ack_pkt_with_rrq) { assert(false); // need to handle it if failed } } if (location != 0 && packet->type == NORMAL_PACKET) { dead_packets += 1; } // if it's a DATA rrq whose payload gets removed due to being dropped by the queue, don't delete the packet. We'll still need to receive it (the rrq part). if (packet->type == NORMAL_PACKET && packet->size == 0) { return; } delete packet; }
47.341584
192
0.615184
SymbioticLab
6f2812c72819a586601a26520e68c02418434c2d
51,157
cxx
C++
libbuild2/variable.cxx
build2/build2
af662849b756ef2ff0f3d5148a6771acab78fd80
[ "MIT" ]
422
2018-05-30T12:00:00.000Z
2022-03-29T07:29:56.000Z
libbuild2/variable.cxx
build2/build2
af662849b756ef2ff0f3d5148a6771acab78fd80
[ "MIT" ]
183
2018-07-02T20:38:30.000Z
2022-03-31T09:54:35.000Z
libbuild2/variable.cxx
build2/build2
af662849b756ef2ff0f3d5148a6771acab78fd80
[ "MIT" ]
14
2019-01-09T12:34:02.000Z
2021-03-16T09:10:53.000Z
// file : libbuild2/variable.cxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #include <libbuild2/variable.hxx> #include <cstring> // memcmp() #include <libbutl/path-pattern.hxx> #include <libbuild2/target.hxx> #include <libbuild2/diagnostics.hxx> using namespace std; namespace build2 { // variable_visibility // string to_string (variable_visibility v) { string r; switch (v) { case variable_visibility::global: r = "global"; break; case variable_visibility::project: r = "project"; break; case variable_visibility::scope: r = "scope"; break; case variable_visibility::target: r = "target"; break; case variable_visibility::prereq: r = "prerequisite"; break; } return r; } // value // void value:: reset () { if (type == nullptr) as<names> ().~names (); else if (type->dtor != nullptr) type->dtor (*this); null = true; } value:: value (value&& v) : type (v.type), null (v.null), extra (v.extra) { if (!null) { if (type == nullptr) new (&data_) names (move (v).as<names> ()); else if (type->copy_ctor != nullptr) type->copy_ctor (*this, v, true); else data_ = v.data_; // Copy as POD. } } value:: value (const value& v) : type (v.type), null (v.null), extra (v.extra) { if (!null) { if (type == nullptr) new (&data_) names (v.as<names> ()); else if (type->copy_ctor != nullptr) type->copy_ctor (*this, v, false); else data_ = v.data_; // Copy as POD. } } value& value:: operator= (value&& v) { if (this != &v) { // Prepare the receiving value. // if (type != v.type) { *this = nullptr; type = v.type; } // Now our types are the same. If the receiving value is NULL, then call // copy_ctor() instead of copy_assign(). // if (v) { if (type == nullptr) { if (null) new (&data_) names (move (v).as<names> ()); else as<names> () = move (v).as<names> (); } else if (auto f = null ? type->copy_ctor : type->copy_assign) f (*this, v, true); else data_ = v.data_; // Assign as POD. null = v.null; } else *this = nullptr; } return *this; } value& value:: operator= (const value& v) { if (this != &v) { // Prepare the receiving value. // if (type != v.type) { *this = nullptr; type = v.type; } // Now our types are the same. If the receiving value is NULL, then call // copy_ctor() instead of copy_assign(). // if (v) { if (type == nullptr) { if (null) new (&data_) names (v.as<names> ()); else as<names> () = v.as<names> (); } else if (auto f = null ? type->copy_ctor : type->copy_assign) f (*this, v, false); else data_ = v.data_; // Assign as POD. null = v.null; } else *this = nullptr; } return *this; } void value:: assign (names&& ns, const variable* var) { assert (type == nullptr || type->assign != nullptr); if (type == nullptr) { if (null) new (&data_) names (move (ns)); else as<names> () = move (ns); } else type->assign (*this, move (ns), var); null = false; } void value:: append (names&& ns, const variable* var) { if (type == nullptr) { if (null) new (&data_) names (move (ns)); else { names& p (as<names> ()); if (p.empty ()) p = move (ns); else if (!ns.empty ()) { p.insert (p.end (), make_move_iterator (ns.begin ()), make_move_iterator (ns.end ())); } } } else { if (type->append == nullptr) { diag_record dr (fail); dr << "cannot append to " << type->name << " value"; if (var != nullptr) dr << " in variable " << var->name; } type->append (*this, move (ns), var); } null = false; } void value:: prepend (names&& ns, const variable* var) { if (type == nullptr) { if (null) new (&data_) names (move (ns)); else { names& p (as<names> ()); if (p.empty ()) p = move (ns); else if (!ns.empty ()) { ns.insert (ns.end (), make_move_iterator (p.begin ()), make_move_iterator (p.end ())); p = move (ns); } } } else { if (type->prepend == nullptr) { diag_record dr (fail); dr << "cannot prepend to " << type->name << " value"; if (var != nullptr) dr << " in variable " << var->name; } type->prepend (*this, move (ns), var); } null = false; } bool operator== (const value& x, const value& y) { bool xn (x.null); bool yn (y.null); assert (x.type == y.type || (xn && x.type == nullptr) || (yn && y.type == nullptr)); if (xn || yn) return xn == yn; if (x.type == nullptr) return x.as<names> () == y.as<names> (); if (x.type->compare == nullptr) return memcmp (&x.data_, &y.data_, x.type->size) == 0; return x.type->compare (x, y) == 0; } bool operator< (const value& x, const value& y) { bool xn (x.null); bool yn (y.null); assert (x.type == y.type || (xn && x.type == nullptr) || (yn && y.type == nullptr)); // NULL value is always less than non-NULL. // if (xn || yn) return xn > yn; // !xn < !yn if (x.type == nullptr) return x.as<names> () < y.as<names> (); if (x.type->compare == nullptr) return memcmp (&x.data_, &y.data_, x.type->size) < 0; return x.type->compare (x, y) < 0; } bool operator> (const value& x, const value& y) { bool xn (x.null); bool yn (y.null); assert (x.type == y.type || (xn && x.type == nullptr) || (yn && y.type == nullptr)); // NULL value is always less than non-NULL. // if (xn || yn) return xn < yn; // !xn > !yn if (x.type == nullptr) return x.as<names> () > y.as<names> (); if (x.type->compare == nullptr) return memcmp (&x.data_, &y.data_, x.type->size) > 0; return x.type->compare (x, y) > 0; } void typify (value& v, const value_type& t, const variable* var, memory_order mo) { if (v.type == nullptr) { if (v) { // Note: the order in which we do things here is important. // names ns (move (v).as<names> ()); v = nullptr; // Use value_type::assign directly to delay v.type change. // t.assign (v, move (ns), var); v.null = false; } else v.type = &t; v.type.store (&t, mo); } else if (v.type != &t) { diag_record dr (fail); dr << "type mismatch"; if (var != nullptr) dr << " in variable " << var->name; dr << info << "value type is " << v.type->name; dr << info << (var != nullptr && &t == var->type ? "variable" : "new") << " type is " << t.name; } } void typify_atomic (context& ctx, value& v, const value_type& t, const variable* var) { // Typification is kind of like caching so we reuse that mutex shard. // shared_mutex& m ( ctx.mutexes.variable_cache[ hash<value*> () (&v) % ctx.mutexes.variable_cache_size]); // Note: v.type is rechecked by typify() under lock. // ulock l (m); typify (v, t, var, memory_order_release); } void untypify (value& v) { if (v.type == nullptr) return; if (v.null) { v.type = nullptr; return; } names ns; names_view nv (v.type->reverse (v, ns)); if (nv.empty () || nv.data () == ns.data ()) { // If the data is in storage, then we are all set. // ns.resize (nv.size ()); // Just to be sure. } else { // If the data is somewhere in the value itself, then steal it. // auto b (const_cast<name*> (nv.data ())); ns.assign (make_move_iterator (b), make_move_iterator (b + nv.size ())); } v = nullptr; // Free old data. v.type = nullptr; // Change type. v.assign (move (ns), nullptr); // Assign new data. } [[noreturn]] void convert_throw (const value_type* from, const value_type& to) { string m ("invalid "); m += to.name; m += " value: "; if (from != nullptr) { m += "conversion from "; m += from->name; } else m += "null"; throw invalid_argument (move (m)); } // Throw invalid_argument for an invalid simple value. // [[noreturn]] static void throw_invalid_argument (const name& n, const name* r, const char* type, bool pair_ok = false) { string m; string t (type); // Note that the message should be suitable for appending "in variable X". // if (!pair_ok && r != nullptr) m = "pair in " + t + " value"; else if (n.pattern || (r != nullptr && r->pattern)) m = "pattern in " + t + " value"; else { m = "invalid " + t + " value "; if (n.simple ()) m += "'" + n.value + "'"; else if (n.directory ()) m += "'" + n.dir.representation () + "'"; else m += "name '" + to_string (n) + "'"; } throw invalid_argument (m); } // names // const names& value_traits<names>::empty_instance = empty_names; // bool value // bool value_traits<bool>:: convert (const name& n, const name* r) { if (r == nullptr && !n.pattern && n.simple () ) { const string& s (n.value); if (s == "true") return true; if (s == "false") return false; // Fall through. } throw_invalid_argument (n, r, "bool"); } const char* const value_traits<bool>::type_name = "bool"; const value_type value_traits<bool>::value_type { type_name, sizeof (bool), nullptr, // No base. nullptr, // No element. nullptr, // No dtor (POD). nullptr, // No copy_ctor (POD). nullptr, // No copy_assign (POD). &simple_assign<bool>, &simple_append<bool>, &simple_append<bool>, // Prepend same as append. &simple_reverse<bool>, nullptr, // No cast (cast data_ directly). nullptr, // No compare (compare as POD). nullptr // Never empty. }; // int64_t value // int64_t value_traits<int64_t>:: convert (const name& n, const name* r) { if (r == nullptr && !n.pattern && n.simple ()) { try { // May throw invalid_argument or out_of_range. // size_t i; int64_t r (stoll (n.value, &i)); if (i == n.value.size ()) return r; // Fall through. } catch (const std::exception&) { // Fall through. } } throw_invalid_argument (n, r, "int64"); } const char* const value_traits<int64_t>::type_name = "int64"; const value_type value_traits<int64_t>::value_type { type_name, sizeof (int64_t), nullptr, // No base. nullptr, // No element. nullptr, // No dtor (POD). nullptr, // No copy_ctor (POD). nullptr, // No copy_assign (POD). &simple_assign<int64_t>, &simple_append<int64_t>, &simple_append<int64_t>, // Prepend same as append. &simple_reverse<int64_t>, nullptr, // No cast (cast data_ directly). nullptr, // No compare (compare as POD). nullptr // Never empty. }; // uint64_t value // uint64_t value_traits<uint64_t>:: convert (const name& n, const name* r) { if (r == nullptr && !n.pattern && n.simple ()) { try { // May throw invalid_argument or out_of_range. // size_t i; uint64_t r (stoull (n.value, &i)); if (i == n.value.size ()) return r; // Fall through. } catch (const std::exception&) { // Fall through. } } throw_invalid_argument (n, r, "uint64"); } const char* const value_traits<uint64_t>::type_name = "uint64"; const value_type value_traits<uint64_t>::value_type { type_name, sizeof (uint64_t), nullptr, // No base. nullptr, // No element. nullptr, // No dtor (POD). nullptr, // No copy_ctor (POD). nullptr, // No copy_assign (POD). &simple_assign<uint64_t>, &simple_append<uint64_t>, &simple_append<uint64_t>, // Prepend same as append. &simple_reverse<uint64_t>, nullptr, // No cast (cast data_ directly). nullptr, // No compare (compare as POD). nullptr // Never empty. }; // string value // string value_traits<string>:: convert (name&& n, name* r) { // The goal is to reverse the name into its original representation. The // code is a bit convoluted because we try to avoid extra allocations for // the common cases (unqualified, unpaired simple name or directory). // // We can only convert project-qualified simple and directory names. // if (n.pattern || !(n.simple (true) || n.directory (true))) throw_invalid_argument (n, nullptr, "string"); if (r != nullptr) { if (r->pattern || !(r->simple (true) || r->directory (true))) throw_invalid_argument (*r, nullptr, "string"); } string s; if (n.directory (true)) // Note that here we cannot assume what's in dir is really a // path (think s/foo/bar/) so we have to reverse it exactly. // s = move (n.dir).representation (); // Move out of path. else s.swap (n.value); // Convert project qualification to its string representation. // if (n.qualified ()) { string p (move (*n.proj).string ()); p += '%'; p += s; p.swap (s); } // The same for the RHS of a pair, if we have one. // if (r != nullptr) { s += '@'; if (r->qualified ()) { s += r->proj->string (); s += '%'; } if (r->directory (true)) s += move (r->dir).representation (); else s += r->value; } return s; } const string& value_traits<string>::empty_instance = empty_string; const char* const value_traits<string>::type_name = "string"; const value_type value_traits<string>::value_type { type_name, sizeof (string), nullptr, // No base. nullptr, // No element. &default_dtor<string>, &default_copy_ctor<string>, &default_copy_assign<string>, &simple_assign<string>, &simple_append<string>, &simple_prepend<string>, &simple_reverse<string>, nullptr, // No cast (cast data_ directly). &simple_compare<string>, &default_empty<string> }; // path value // path value_traits<path>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern) { // A directory path is a path. // if (n.directory ()) return move (n.dir); if (n.simple ()) { try { return path (move (n.value)); } catch (invalid_path& e) { n.value = move (e.path); // Restore the name object for diagnostics. // Fall through. } } // Reassemble split dir/value. // if (n.untyped () && n.unqualified ()) { try { return n.dir / n.value; } catch (const invalid_path&) { // Fall through. } } // Fall through. } throw_invalid_argument (n, r, "path"); } const path& value_traits<path>::empty_instance = empty_path; const char* const value_traits<path>::type_name = "path"; const value_type value_traits<path>::value_type { type_name, sizeof (path), nullptr, // No base. nullptr, // No element. &default_dtor<path>, &default_copy_ctor<path>, &default_copy_assign<path>, &simple_assign<path>, &simple_append<path>, &simple_prepend<path>, &simple_reverse<path>, nullptr, // No cast (cast data_ directly). &simple_compare<path>, &default_empty<path> }; // dir_path value // dir_path value_traits<dir_path>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern) { if (n.directory ()) return move (n.dir); if (n.simple ()) { try { return dir_path (move (n.value)); } catch (invalid_path& e) { n.value = move (e.path); // Restore the name object for diagnostics. // Fall through. } } // Reassemble split dir/value. // if (n.untyped () && n.unqualified ()) { try { n.dir /= n.value; return move (n.dir); } catch (const invalid_path&) { // Fall through. } } // Fall through. } throw_invalid_argument (n, r, "dir_path"); } const dir_path& value_traits<dir_path>::empty_instance = empty_dir_path; const char* const value_traits<dir_path>::type_name = "dir_path"; const value_type value_traits<dir_path>::value_type { type_name, sizeof (dir_path), &value_traits<path>::value_type, // Base (assuming direct cast works for // both). nullptr, // No element. &default_dtor<dir_path>, &default_copy_ctor<dir_path>, &default_copy_assign<dir_path>, &simple_assign<dir_path>, &simple_append<dir_path>, &simple_prepend<dir_path>, &simple_reverse<dir_path>, nullptr, // No cast (cast data_ directly). &simple_compare<dir_path>, &default_empty<dir_path> }; // abs_dir_path value // abs_dir_path value_traits<abs_dir_path>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern && (n.simple () || n.directory ())) { try { dir_path d (n.simple () ? dir_path (move (n.value)) : move (n.dir)); if (!d.empty ()) { if (d.relative ()) d.complete (); d.normalize (true); // Actualize. } return abs_dir_path (move (d)); } catch (const invalid_path&) {} // Fall through. } throw_invalid_argument (n, r, "abs_dir_path"); } const char* const value_traits<abs_dir_path>::type_name = "abs_dir_path"; const value_type value_traits<abs_dir_path>::value_type { type_name, sizeof (abs_dir_path), &value_traits<dir_path>::value_type, // Base (assuming direct cast works // for both). nullptr, // No element. &default_dtor<abs_dir_path>, &default_copy_ctor<abs_dir_path>, &default_copy_assign<abs_dir_path>, &simple_assign<abs_dir_path>, &simple_append<abs_dir_path>, nullptr, // No prepend. &simple_reverse<abs_dir_path>, nullptr, // No cast (cast data_ directly). &simple_compare<abs_dir_path>, &default_empty<abs_dir_path> }; // name value // name value_traits<name>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern) return move (n); throw_invalid_argument (n, r, "name"); } static names_view name_reverse (const value& v, names&) { const name& n (v.as<name> ()); return n.empty () ? names_view (nullptr, 0) : names_view (&n, 1); } const char* const value_traits<name>::type_name = "name"; const value_type value_traits<name>::value_type { type_name, sizeof (name), nullptr, // No base. nullptr, // No element. &default_dtor<name>, &default_copy_ctor<name>, &default_copy_assign<name>, &simple_assign<name>, nullptr, // Append not supported. nullptr, // Prepend not supported. &name_reverse, nullptr, // No cast (cast data_ directly). &simple_compare<name>, &default_empty<name> }; // name_pair // name_pair value_traits<name_pair>:: convert (name&& n, name* r) { if (n.pattern || (r != nullptr && r->pattern)) throw_invalid_argument (n, r, "name_pair", true /* pair_ok */); n.pair = '\0'; // Keep "unpaired" in case r is empty. return name_pair (move (n), r != nullptr ? move (*r) : name ()); } static void name_pair_assign (value& v, names&& ns, const variable* var) { using traits = value_traits<name_pair>; size_t n (ns.size ()); if (n <= 2) { try { traits::assign ( v, (n == 0 ? name_pair () : traits::convert (move (ns[0]), n == 2 ? &ns[1] : nullptr))); return; } catch (const invalid_argument&) {} // Fall through. } diag_record dr (fail); dr << "invalid name_pair value '" << ns << "'"; if (var != nullptr) dr << " in variable " << var->name; } static names_view name_pair_reverse (const value& v, names& ns) { const name_pair& p (v.as<name_pair> ()); const name& f (p.first); const name& s (p.second); if (f.empty () && s.empty ()) return names_view (nullptr, 0); if (f.empty ()) return names_view (&s, 1); if (s.empty ()) return names_view (&f, 1); ns.push_back (f); ns.back ().pair = '@'; ns.push_back (s); return ns; } const char* const value_traits<name_pair>::type_name = "name_pair"; const value_type value_traits<name_pair>::value_type { type_name, sizeof (name_pair), nullptr, // No base. nullptr, // No element. &default_dtor<name_pair>, &default_copy_ctor<name_pair>, &default_copy_assign<name_pair>, &name_pair_assign, nullptr, // Append not supported. nullptr, // Prepend not supported. &name_pair_reverse, nullptr, // No cast (cast data_ directly). &simple_compare<name_pair>, &default_empty<name_pair> }; // process_path value // template <typename T> static T process_path_convert (name&& n, name* r, const char* what) { if ( !n.pattern && n.untyped () && n.unqualified () && !n.empty () && (r == nullptr || (!r->pattern && r->untyped () && r->unqualified () && !r->empty ()))) { path rp (move (n.dir)); if (rp.empty ()) rp = path (move (n.value)); else rp /= n.value; path ep; if (r != nullptr) { ep = move (r->dir); if (ep.empty ()) ep = path (move (r->value)); else ep /= r->value; } T pp (nullptr, move (rp), move (ep)); pp.initial = pp.recall.string ().c_str (); return pp; } throw_invalid_argument (n, r, what, true /* pair_ok */); } process_path value_traits<process_path>:: convert (name&& n, name* r) { return process_path_convert<process_path> (move (n), r, "process_path"); } static void process_path_assign (value& v, names&& ns, const variable* var) { using traits = value_traits<process_path>; size_t n (ns.size ()); if (n <= 2) { try { traits::assign ( v, (n == 0 ? process_path () : traits::convert (move (ns[0]), n == 2 ? &ns[1] : nullptr))); return; } catch (const invalid_argument&) {} // Fall through. } diag_record dr (fail); dr << "invalid process_path value '" << ns << "'"; if (var != nullptr) dr << " in variable " << var->name; } template <typename T> static void process_path_copy_ctor (value& l, const value& r, bool m) { const auto& rhs (r.as<T> ()); if (m) new (&l.data_) T (move (const_cast<T&> (rhs))); else { auto& lhs ( *new (&l.data_) T ( nullptr, path (rhs.recall), path (rhs.effect))); lhs.initial = lhs.recall.string ().c_str (); } } static void process_path_copy_assign (value& l, const value& r, bool m) { auto& lhs (l.as<process_path> ()); const auto& rhs (r.as<process_path> ()); if (m) lhs = move (const_cast<process_path&> (rhs)); else { lhs.recall = rhs.recall; lhs.effect = rhs.effect; lhs.initial = lhs.recall.string ().c_str (); } } static void process_path_reverse_impl (const process_path& x, names& s) { s.push_back (name (x.recall.directory (), string (), x.recall.leaf ().string ())); if (!x.effect.empty ()) { s.back ().pair = '@'; s.push_back (name (x.effect.directory (), string (), x.effect.leaf ().string ())); } } static names_view process_path_reverse (const value& v, names& s) { const auto& x (v.as<process_path> ()); if (!x.empty ()) { s.reserve (x.effect.empty () ? 1 : 2); process_path_reverse_impl (x, s); } return s; } const char* const value_traits<process_path>::type_name = "process_path"; const value_type value_traits<process_path>::value_type { type_name, sizeof (process_path), nullptr, // No base. nullptr, // No element. &default_dtor<process_path>, &process_path_copy_ctor<process_path>, &process_path_copy_assign, &process_path_assign, nullptr, // Append not supported. nullptr, // Prepend not supported. &process_path_reverse, nullptr, // No cast (cast data_ directly). &simple_compare<process_path>, &default_empty<process_path> }; // process_path_ex value // process_path_ex value_traits<process_path_ex>:: convert (names&& ns) { if (ns.empty ()) return process_path_ex (); bool p (ns[0].pair); process_path_ex pp ( process_path_convert<process_path_ex> ( move (ns[0]), p ? &ns[1] : nullptr, "process_path_ex")); for (auto i (ns.begin () + (p ? 2 : 1)); i != ns.end (); ++i) { if (!i->pair) throw invalid_argument ("non-pair in process_path_ex value"); if (i->pattern || !i->simple ()) throw_invalid_argument (*i, nullptr, "process_path_ex"); const string& k ((i++)->value); // NOTE: see also find_end() below. // if (k == "name") { if (i->pattern || !i->simple ()) throw_invalid_argument (*i, nullptr, "process_path_ex name"); pp.name = move (i->value); } else if (k == "checksum") { if (i->pattern || !i->simple ()) throw_invalid_argument ( *i, nullptr, "process_path_ex executable checksum"); pp.checksum = move (i->value); } else if (k == "env-checksum") { if (i->pattern || !i->simple ()) throw_invalid_argument ( *i, nullptr, "process_path_ex environment checksum"); pp.env_checksum = move (i->value); } else throw invalid_argument ( "unknown key '" + k + "' in process_path_ex value"); } return pp; } names::iterator value_traits<process_path_ex>:: find_end (names& ns) { auto b (ns.begin ()), i (b), e (ns.end ()); for (i += i->pair ? 2 : 1; i != e && i->pair; i += 2) { if (!i->simple () || (i->value != "name" && i->value != "checksum" && i->value != "env-checksum")) break; } return i; } static void process_path_ex_assign (value& v, names&& ns, const variable* var) { using traits = value_traits<process_path_ex>; try { traits::assign (v, traits::convert (move (ns))); } catch (const invalid_argument& e) { // Note: ns is not guaranteed to be valid. // diag_record dr (fail); dr << "invalid process_path_ex value"; if (var != nullptr) dr << " in variable " << var->name; dr << ": " << e; } } static void process_path_ex_copy_ex (value& l, const value& r, bool m) { auto& lhs (l.as<process_path_ex> ()); if (m) { const auto& rhs (const_cast<value&> (r).as<process_path_ex> ()); lhs.name = move (rhs.name); lhs.checksum = move (rhs.checksum); lhs.env_checksum = move (rhs.env_checksum); } else { const auto& rhs (r.as<process_path_ex> ()); lhs.name = rhs.name; lhs.checksum = rhs.checksum; lhs.env_checksum = rhs.env_checksum; } } static void process_path_ex_copy_ctor (value& l, const value& r, bool m) { process_path_copy_ctor<process_path_ex> (l, r, m); if (!m) process_path_ex_copy_ex (l, r, false); } static void process_path_ex_copy_assign (value& l, const value& r, bool m) { process_path_copy_assign (l, r, m); process_path_ex_copy_ex (l, r, m); } static names_view process_path_ex_reverse (const value& v, names& s) { const auto& x (v.as<process_path_ex> ()); if (!x.empty ()) { s.reserve ((x.effect.empty () ? 1 : 2) + (x.name ? 2 : 0) + (x.checksum ? 2 : 0) + (x.env_checksum ? 2 : 0)); process_path_reverse_impl (x, s); if (x.name) { s.push_back (name ("name")); s.back ().pair = '@'; s.push_back (name (*x.name)); } if (x.checksum) { s.push_back (name ("checksum")); s.back ().pair = '@'; s.push_back (name (*x.checksum)); } if (x.env_checksum) { s.push_back (name ("env-checksum")); s.back ().pair = '@'; s.push_back (name (*x.env_checksum)); } } return s; } const char* const value_traits<process_path_ex>::type_name = "process_path_ex"; const value_type value_traits<process_path_ex>::value_type { type_name, sizeof (process_path_ex), &value_traits< // Base (assuming direct cast works process_path>::value_type, // for both). nullptr, // No element. &default_dtor<process_path_ex>, &process_path_ex_copy_ctor, &process_path_ex_copy_assign, &process_path_ex_assign, nullptr, // Append not supported. nullptr, // Prepend not supported. &process_path_ex_reverse, nullptr, // No cast (cast data_ directly). &simple_compare<process_path>, // For now compare as process_path. &default_empty<process_path_ex> }; // target_triplet value // target_triplet value_traits<target_triplet>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern && n.simple ()) { try { return n.empty () ? target_triplet () : target_triplet (n.value); } catch (const invalid_argument& e) { throw invalid_argument ( string ("invalid target_triplet value: ") + e.what ()); } } throw_invalid_argument (n, r, "target_triplet"); } const char* const value_traits<target_triplet>::type_name = "target_triplet"; const value_type value_traits<target_triplet>::value_type { type_name, sizeof (target_triplet), nullptr, // No base. nullptr, // No element. &default_dtor<target_triplet>, &default_copy_ctor<target_triplet>, &default_copy_assign<target_triplet>, &simple_assign<target_triplet>, nullptr, // Append not supported. nullptr, // Prepend not supported. &simple_reverse<target_triplet>, nullptr, // No cast (cast data_ directly). &simple_compare<target_triplet>, &default_empty<target_triplet> }; // project_name value // project_name value_traits<project_name>:: convert (name&& n, name* r) { if (r == nullptr && !n.pattern && n.simple ()) { try { return n.empty () ? project_name () : project_name (move (n.value)); } catch (const invalid_argument& e) { throw invalid_argument ( string ("invalid project_name value: ") + e.what ()); } } throw_invalid_argument (n, r, "project_name"); } const project_name& value_traits<project_name>::empty_instance = empty_project_name; const char* const value_traits<project_name>::type_name = "project_name"; const value_type value_traits<project_name>::value_type { type_name, sizeof (project_name), nullptr, // No base. nullptr, // No element. &default_dtor<project_name>, &default_copy_ctor<project_name>, &default_copy_assign<project_name>, &simple_assign<project_name>, nullptr, // Append not supported. nullptr, // Prepend not supported. &simple_reverse<project_name>, nullptr, // No cast (cast data_ directly). &simple_compare<project_name>, &default_empty<project_name> }; // variable_pool // void variable_pool:: update (variable& var, const build2::value_type* t, const variable_visibility* v, const bool* o) const { // Check overridability (all overrides, if any, should already have // been entered; see context ctor for details). // if (o != nullptr && var.overrides != nullptr && !*o) fail << "variable " << var.name << " cannot be overridden"; bool ut (t != nullptr && var.type != t); bool uv (v != nullptr && var.visibility != *v); // Variable should not be updated post-aliasing. // assert (var.aliases == &var || (!ut && !uv)); // Update type? // if (ut) { assert (var.type == nullptr); var.type = t; } // Change visibility? While this might at first seem like a bad idea, it // can happen that the variable lookup happens before any values were set // in which case the variable will be entered with the default (project) // visibility. // // For example, a buildfile, for some reason, could reference a target- // specific variable (say, test) before loading a module (say, test) that // sets this visibility. While strictly speaking we could have potentially // already made a lookup using the wrong visibility, presumably this // should be harmless. // // @@ But consider a situation where this test is set on scope prior to // loading the module: now this value will effectively be unreachable // without any diagnostics. So maybe we should try to clean this up. // But we will need proper diagnostics instead of assert (which means // we would probably need to track the location where the variable // was first entered). // // Note also that this won't work well for global visibility since we only // allow restrictions. The thinking is that global visibility is special // and requiring special arrangements (like variable patterns, similar to // how we've done it for config.*) is reasonable. In fact, it feels like // only the build system core should be allowed to use global visibility // (see the context ctor for details). // if (uv) { assert (*v > var.visibility); var.visibility = *v; } } static bool match_pattern (const string& n, const string& p, const string& s, bool multi) { size_t nn (n.size ()), pn (p.size ()), sn (s.size ()); if (nn < pn + sn + 1) return false; if (pn != 0) { if (n.compare (0, pn, p) != 0) return false; } if (sn != 0) { if (n.compare (nn - sn, sn, s) != 0) return false; } // Make sure the stem is a single name unless instructed otherwise. // return multi || string::traits_type::find (n.c_str () + pn, nn - pn - sn, '.') == nullptr; } static inline void merge_pattern (const variable_pool::pattern& p, const build2::value_type*& t, const variable_visibility*& v, const bool*& o) { if (p.type) { if (t == nullptr) t = *p.type; else if (p.match) assert (t == *p.type); } if (p.visibility) { if (v == nullptr) v = &*p.visibility; else if (p.match) { // Allow the pattern to restrict but not relax. // if (*p.visibility > *v) v = &*p.visibility; else assert (*v == *p.visibility); } } if (p.overridable) { if (o == nullptr) o = &*p.overridable; else if (p.match) { // Allow the pattern to restrict but not relax. // if (*o) o = &*p.overridable; else assert (*o == *p.overridable); } } } pair<variable&, bool> variable_pool:: insert (string n, const build2::value_type* t, const variable_visibility* v, const bool* o, bool pat) { assert (!global_ || global_->phase == run_phase::load); // Apply pattern. // const pattern* pa (nullptr); auto pt (t); auto pv (v); auto po (o); if (pat) { if (n.find ('.') != string::npos) { // Reverse means from the "largest" (most specific). // for (const pattern& p: reverse_iterate (patterns_)) { if (match_pattern (n, p.prefix, p.suffix, p.multi)) { merge_pattern (p, pt, pv, po); pa = &p; break; } } } } auto r ( insert ( variable { move (n), nullptr, pt, nullptr, pv != nullptr ? *pv : variable_visibility::project})); variable& var (r.first->second); if (r.second) var.aliases = &var; else // Note: overridden variable will always exist. { // This is tricky: if the pattern does not require a match, then we // should re-merge it with values that came from the variable. // bool vo; if (pa != nullptr && !pa->match) { pt = t != nullptr ? t : var.type; pv = v != nullptr ? v : &var.visibility; po = o != nullptr ? o : &(vo = true); merge_pattern (*pa, pt, pv, po); } if (po == nullptr) // NULL overridable falls back to false. po = &(vo = false); update (var, pt, pv, po); // Not changing the key. } return pair<variable&, bool> (var, r.second); } const variable& variable_pool:: insert_alias (const variable& var, string n) { assert (var.aliases != nullptr && var.overrides == nullptr); variable& a (insert (move (n), var.type, &var.visibility, nullptr /* override */, false /* pattern */).first); assert (a.overrides == nullptr); if (a.aliases == &a) // Not aliased yet. { a.aliases = var.aliases; const_cast<variable&> (var).aliases = &a; } else assert (a.alias (var)); // Make sure it is already an alias of var. return a; } void variable_pool:: insert_pattern (const string& p, optional<const value_type*> t, optional<bool> o, optional<variable_visibility> v, bool retro, bool match) { assert (!global_ || global_->phase == run_phase::load); size_t pn (p.size ()); size_t w (p.find ('*')); assert (w != string::npos); bool multi (w + 1 != pn && p[w + 1] == '*'); // Extract prefix and suffix. // string pfx, sfx; if (w != 0) { assert (p[w - 1] == '.' && w != 1); pfx.assign (p, 0, w); } w += multi ? 2 : 1; // First suffix character. size_t sn (pn - w); // Suffix length. if (sn != 0) { assert (p[w] == '.' && sn != 1); sfx.assign (p, w, sn); } auto i ( patterns_.insert ( pattern {move (pfx), move (sfx), multi, match, t, v, o})); // Apply retrospectively to existing variables. // if (retro) { for (auto& p: map_) { variable& var (p.second); if (match_pattern (var.name, i->prefix, i->suffix, i->multi)) { // Make sure that none of the existing more specific patterns // match. // auto j (i), e (patterns_.end ()); for (++j; j != e; ++j) { if (match_pattern (var.name, j->prefix, j->suffix, j->multi)) break; } if (j == e) update (var, t ? *t : nullptr, v ? &*v : nullptr, o ? &*o : nullptr); // Not changing the key. } } } } // variable_map // const variable_map empty_variable_map (nullptr /* context */); auto variable_map:: lookup (const variable& var, bool typed, bool aliased) const -> pair<const value_data*, const variable&> { const variable* v (&var); const value_data* r (nullptr); do { // @@ Should we verify that there are no distinct values for aliases? // This can happen if the values were entered before the variables // were aliased. Possible but probably highly unlikely. // auto i (m_.find (*v)); if (i != m_.end ()) { r = &i->second; break; } if (aliased) v = v->aliases; } while (v != &var && v != nullptr); // Check if this is the first access after being assigned a type. // if (r != nullptr && typed && v->type != nullptr) typify (*r, *v); return pair<const value_data*, const variable&> ( r, r != nullptr ? *v : var); } auto variable_map:: lookup_to_modify (const variable& var, bool typed) -> pair<value_data*, const variable&> { auto p (lookup (var, typed)); auto* r (const_cast<value_data*> (p.first)); if (r != nullptr) r->version++; return pair<value_data*, const variable&> (r, p.second); } pair<value&, bool> variable_map:: insert (const variable& var, bool typed) { assert (!global_ || ctx->phase == run_phase::load); auto p (m_.emplace (var, value_data (typed ? var.type : nullptr))); value_data& r (p.first->second); if (!p.second) { // Check if this is the first access after being assigned a type. // // Note: we still need atomic in case this is not a global state. // if (typed && var.type != nullptr) typify (r, var); } r.version++; return pair<value&, bool> (r, p.second); } bool variable_map:: erase (const variable& var) { assert (!global_ || ctx->phase == run_phase::load); return m_.erase (var) != 0; } // variable_pattern_map // variable_map& variable_pattern_map:: insert (pattern_type type, string&& text) { auto r (map_.emplace (pattern {type, false, move (text), {}}, variable_map (ctx, global_))); // Compile the regex. // if (r.second && type == pattern_type::regex_pattern) { // On exception restore the text argument (so that it's available for // diagnostics) and remove the element from the map. // auto eg (make_exception_guard ( [&text, &r, this] () { text = r.first->first.text; map_.erase (r.first); })); const string& t (r.first->first.text); size_t n (t.size ()), p (t.rfind (t[0])); // Convert flags. // regex::flag_type f (regex::ECMAScript); for (size_t i (p + 1); i != n; ++i) { switch (t[i]) { case 'i': f |= regex::icase; break; case 'e': r.first->first.match_ext = true; break; } } // Skip leading delimiter as well as trailing delimiter and flags. // r.first->first.regex = regex (t.c_str () + 1, p - 1, f); } return r.first->second; } // variable_type_map // lookup variable_type_map:: find (const target_key& tk, const variable& var, optional<string>& oname) const { // Compute and cache "effective" name that we will be matching. // // See also the additional match_ext logic below. // auto name = [&tk, &oname] () -> const string& { if (!oname) { const target_type& tt (*tk.type); // Note that if the name is not empty, then we always use that, even // if the type is dir/fsdir. // if (tk.name->empty () && (tt.is_a<dir> () || tt.is_a<fsdir> ())) { oname = tk.dir->leaf ().string (); } // If we have the extension and the type expects the extension to be // always specified explicitly by the user, then add it to the name. // // Overall, we have the following cases: // // 1. Extension is fixed: man1{}. // // 2. Extension is always specified by the user: file{}. // // 3. Default extension that may be overridden by the user: hxx{}. // // 4. Extension assigned by the rule but may be overridden by the // user: obje{}. // // By default we only match the extension for (2). // else if (tk.ext && !tk.ext->empty () && (tt.fixed_extension == &target_extension_none || tt.fixed_extension == &target_extension_must)) { oname = *tk.name + '.' + *tk.ext; } else oname = string (); // Use tk.name as is. } return oname->empty () ? *tk.name : *oname; }; // Search across target type hierarchy. // for (auto tt (tk.type); tt != nullptr; tt = tt->base) { auto i (map_.find (*tt)); if (i == end ()) continue; // Try to match the pattern, starting from the longest values. // const variable_pattern_map& m (i->second); for (auto j (m.rbegin ()); j != m.rend (); ++j) { using pattern = variable_pattern_map::pattern; using pattern_type = variable_pattern_map::pattern_type; const pattern& pat (j->first); bool r, e (false); if (pat.type == pattern_type::path) { r = pat.text == "*" || butl::path_match (name (), pat.text); } else { const string& n (name ()); // Deal with match_ext: first see if the extension would be added by // default. If not, then temporarily add it in oname and then clean // it up if there is no match (to prevent another pattern from using // it). While we may keep adding it if there are multiple patterns // with such a flag, we will at least reuse the buffer in oname. // e = pat.match_ext && tk.ext && !tk.ext->empty () && oname->empty (); if (e) { *oname = *tk.name; *oname += '.'; *oname += *tk.ext; } r = regex_match (e ? *oname : n, *pat.regex); } // Ok, this pattern matches. But is there a variable? // // Since we store append/prepend values untyped, instruct find() not // to automatically type it. And if it is assignment, then typify it // ourselves. // if (r) { const variable_map& vm (j->second); auto p (vm.lookup (var, false)); if (const variable_map::value_data* v = p.first) { // Check if this is the first access after being assigned a type. // if (v->extra == 0 && var.type != nullptr) vm.typify (*v, var); // Make sure the effective name is computed if this is // append/prepend (it is used as a cache key). // if (v->extra != 0 && !oname) name (); return lookup (*v, p.second, vm); } } if (e) oname->clear (); } } return lookup (); } template struct LIBBUILD2_DEFEXPORT value_traits<strings>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<name>>; template struct LIBBUILD2_DEFEXPORT value_traits<paths>; template struct LIBBUILD2_DEFEXPORT value_traits<dir_paths>; template struct LIBBUILD2_DEFEXPORT value_traits<int64s>; template struct LIBBUILD2_DEFEXPORT value_traits<uint64s>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<pair<string, string>>>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<pair<string, optional<string>>>>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<pair<optional<string>, string>>>; template struct LIBBUILD2_DEFEXPORT value_traits<vector<pair<string, optional<bool>>>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<string, string>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<string, optional<string>>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<optional<string>, string>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<string, optional<bool>>>; template struct LIBBUILD2_DEFEXPORT value_traits<map<project_name, dir_path>>; }
25.425944
94
0.523487
build2
6f285d643ccafd41d15127989f6c9aa7e022512d
243
cpp
C++
Day 15/Q.2]/RAO.cpp
gopalshendge18/Practice-Question
c0dfefb4b6d7c3c5344d09b23d311f07a4444149
[ "MIT" ]
1
2022-01-03T14:04:26.000Z
2022-01-03T14:04:26.000Z
Day 15/Q.2]/RAO.cpp
gopalshendge18/Practice-Question
c0dfefb4b6d7c3c5344d09b23d311f07a4444149
[ "MIT" ]
null
null
null
Day 15/Q.2]/RAO.cpp
gopalshendge18/Practice-Question
c0dfefb4b6d7c3c5344d09b23d311f07a4444149
[ "MIT" ]
8
2021-11-03T04:12:17.000Z
2021-12-11T09:28:54.000Z
class Solution { public: void moveZeroes(vector<int>& A) { int num = 0; for(int i=0; i<A.size(); i++){ if(A[i]!=0) A[num++] = A[i]; } while(num<A.size()) A[num++] = 0; } };
18.692308
41
0.386831
gopalshendge18
6f2a0a323650e354c611b51725880cc698fbda16
901
cpp
C++
topic_wise/backtracking/subsets.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
topic_wise/backtracking/subsets.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
topic_wise/backtracking/subsets.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
/** * @author : archit * @GitHub : archit-1997 * @email : architsingh456@gmail.com * @file : subsets.cpp * @created : Wednesday Jul 28, 2021 12:47:45 IST */ #include <bits/stdc++.h> using namespace std; class Solution { public: void findSubsets(vector<vector<int>> &ans,vector<int> tmp,int index,vector<int> &nums){ //if we have reached the last index if(index==nums.size()){ ans.push_back(tmp); return; } //exclude this element findSubsets(ans,tmp,index+1,nums); //include the element at index tmp.push_back(nums[index]); findSubsets(ans,tmp,index+1,nums); } vector<vector<int>> subsets(vector<int>& nums) { int n=nums.size(); vector<vector<int>> ans; vector<int> tmp; findSubsets(ans,tmp,0,nums); return ans; } };
23.102564
91
0.564928
archit-1997
6f2c9fcc66e881bee573ecd9d925125b19c9fae0
11,409
cc
C++
pigasus/software/tools/snort2lua/preprocessor_states/pps_smtp.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
pigasus/software/tools/snort2lua/preprocessor_states/pps_smtp.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
pigasus/software/tools/snort2lua/preprocessor_states/pps_smtp.cc
zhipengzhaocmu/fpga2022_artifact
0ac088a5b04c5c75ae6aef25202b66b0f674acd3
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
//-------------------------------------------------------------------------- // Copyright (C) 2015-2018 Cisco and/or its affiliates. All rights reserved. // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License Version 2 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- // pps_smtp.cc author Bhagya Bantwal <bbantwal@cisco.com> #include <sstream> #include <vector> #include "conversion_state.h" #include "helpers/s2l_util.h" #include "helpers/util_binder.h" namespace preprocessors { namespace { class Smtp : public ConversionState { public: Smtp(Converter& c) : ConversionState(c) { } bool convert(std::istringstream& data_stream) override; private: struct Command { std::string name; std::string format; int length; Command() : name(std::string()), format(std::string()), length(command_default_len) { } }; static const int command_default_len = -1; std::vector<Command> commands; bool parse_alt_max_cmd(std::istringstream& data_stream); std::vector<Command>::iterator get_command(const std::string& cmd_name, std::vector<Smtp::Command>::iterator it); }; } // namespace std::vector<Smtp::Command>::iterator Smtp::get_command( const std::string& cmd_name, std::vector<Smtp::Command>::iterator it) { for (; it != commands.end(); ++it) if (cmd_name == (*it).name) return it; return commands.end(); } bool Smtp::parse_alt_max_cmd(std::istringstream& stream) { int len; std::string elem; if (!(stream >> len)) return false; if (!(stream >> elem) || (elem != "{")) return false; while (stream >> elem && elem != "}") { auto it = get_command(elem, commands.begin()); if (it == commands.end()) { Command c; c.name = std::string(elem); c.length = len; commands.push_back(c); } else { // change the length for every command do { if ((*it).length < len) (*it).length = len; it = get_command(elem, ++it); } while (it != commands.end()); } } if (elem == "}") return true; return false; } bool Smtp::convert(std::istringstream& data_stream) { std::string keyword; bool retval = true; bool ports_set = false; auto& bind = cv.make_binder(); bind.set_when_proto("tcp"); bind.set_use_type("smtp"); table_api.open_table("smtp"); // parse the file configuration while (data_stream >> keyword) { bool tmpval = true; if (keyword == "disabled") { table_api.add_deleted_comment("disabled"); } else if (keyword == "inspection_type") { table_api.add_deleted_comment("inspection_type"); data_stream >> keyword; } else if (keyword == "enable_mime_decoding") { table_api.add_deleted_comment("enable_mime_decoding"); } else if (keyword == "max_mime_depth") { table_api.add_deleted_comment("max_mime_depth"); data_stream >> keyword; } else if (keyword == "no_alerts") { table_api.add_deleted_comment("no_alerts"); } else if (keyword == "print_cmds") { table_api.add_deleted_comment("print_cmds"); } else if (keyword == "alert_unknown_cmds") { table_api.add_deleted_comment("alert_unknown_cmds"); } else if (keyword == "memcap") { table_api.add_deleted_comment("memcap"); data_stream >> keyword; } else if (keyword == "max_mime_mem") { table_api.add_deleted_comment("max_mime_mem"); data_stream >> keyword; } else if (keyword == "b64_decode_depth") { tmpval = parse_int_option_reverse_m10("b64_decode_depth", data_stream); } else if (keyword == "qp_decode_depth") { tmpval = parse_int_option_reverse_m10("qp_decode_depth", data_stream); } else if (keyword == "bitenc_decode_depth") { tmpval = parse_int_option_reverse_m10("bitenc_decode_depth", data_stream); } else if (keyword == "uu_decode_depth") { tmpval = parse_int_option_reverse_m10("uu_decode_depth", data_stream); } else if (keyword == "alt_max_command_line_len") { tmpval = parse_alt_max_cmd(data_stream); } else if (keyword == "ignore_data") { tmpval = table_api.add_option("ignore_data", true); } else if (keyword == "ignore_tls_data") { tmpval = table_api.add_option("ignore_tls_data", true); } else if (keyword == "log_filename") { tmpval = table_api.add_option("log_filename", true); } else if (keyword == "log_mailfrom") { tmpval = table_api.add_option("log_mailfrom", true); } else if (keyword == "log_rcptto") { tmpval = table_api.add_option("log_rcptto", true); } else if (keyword == "log_email_hdrs") { tmpval = table_api.add_option("log_email_hdrs", true); } else if (keyword == "email_hdrs_log_depth") { tmpval = parse_int_option("email_hdrs_log_depth", data_stream, false); } else if (keyword == "max_auth_command_line_len") { tmpval = parse_int_option("max_auth_command_line_len", data_stream, false); } else if (keyword == "max_command_line_len") { tmpval = parse_int_option("max_command_line_len", data_stream, false); } else if (keyword == "max_header_line_len") { tmpval = parse_int_option("max_header_line_len", data_stream, false); } else if (keyword == "max_response_line_len") { tmpval = parse_int_option("max_response_line_len", data_stream, false); } else if (keyword == "normalize") { std::string norm_type; if (!(data_stream >> norm_type)) data_api.failed_conversion(data_stream, "smtp: normalize <missing_arg>"); else if (norm_type == "none") table_api.add_option("normalize", "none"); else if (norm_type == "all") table_api.add_option("normalize", "all"); else if (norm_type == "cmds") table_api.add_option("normalize", "cmds"); else { data_api.failed_conversion(data_stream, "smtp: normalize " + norm_type); } } else if (keyword == "xlink2state") { if ((data_stream >> keyword) && keyword == "{") { std::string state_type; if (!(data_stream >> state_type)) data_api.failed_conversion(data_stream, "smtp: xlink2state <missing_arg>"); else if (state_type == "disable") table_api.add_option("xlink2state", "disable"); else if (state_type == "enabled") table_api.add_option("xlink2state", "alert"); else if (state_type == "drop") table_api.add_option("xlink2state", "drop"); else { data_api.failed_conversion(data_stream, "smtp: xlink2state " + state_type); } if ((data_stream >> keyword) && keyword != "}") { data_api.failed_conversion(data_stream, "smtp: xlink2state " + state_type); } } else { data_api.failed_conversion(data_stream, "smtp: xlink2state " + keyword); } } else if (keyword == "auth_cmds") { tmpval = parse_curly_bracket_list("auth_cmds", data_stream); } else if (keyword == "binary_data_cmds") { tmpval = parse_curly_bracket_list("binary_data_cmds", data_stream); } else if (keyword == "data_cmds") { tmpval = parse_curly_bracket_list("data_cmds", data_stream); } else if (keyword == "normalize_cmds") { tmpval = parse_curly_bracket_list("normalize_cmds", data_stream); } else if (keyword == "invalid_cmds") { tmpval = parse_curly_bracket_list("invalid_cmds", data_stream); } else if (keyword == "valid_cmds") { tmpval = parse_curly_bracket_list("valid_cmds", data_stream); } else if (keyword == "ports") { table_api.add_diff_option_comment("ports", "bindings"); if ((data_stream >> keyword) && keyword == "{") { while (data_stream >> keyword && keyword != "}") { ports_set = true; bind.add_when_port(keyword); } } else { data_api.failed_conversion(data_stream, "ports <bracketed_port_list>"); retval = false; } } else { tmpval = false; } if (!tmpval) { data_api.failed_conversion(data_stream, keyword); retval = false; } } if (!commands.empty()) { table_api.open_table("alt_max_command_line_len"); for (auto c : commands) { table_api.open_table(); bool tmpval1 = table_api.add_option("command", c.name); bool tmpval2 = true; if (c.length != command_default_len) tmpval2 = table_api.add_option("length", c.length); table_api.close_table(); if (!tmpval1 || !tmpval2 ) retval = false; } table_api.close_table(); } if (!ports_set) bind.add_when_port("25"); bind.add_when_port("465"); bind.add_when_port("587"); bind.add_when_port("691"); return retval; } /************************** ******* A P I *********** **************************/ static ConversionState* ctor(Converter& c) { return new Smtp(c); } static const ConvertMap preprocessor_smtp = { "smtp", ctor, }; const ConvertMap* smtp_map = &preprocessor_smtp; }
29.944882
96
0.537733
zhipengzhaocmu
6f2fdd220abe67337e0a805327cedbdda42266f8
1,830
cpp
C++
src/GameState/PhysicalObject/Enemies/Enemy.cpp
Heaven31415/SpaceShooter
385e43aa2deb8720c1b0a23834ad31de97fd25eb
[ "Zlib" ]
null
null
null
src/GameState/PhysicalObject/Enemies/Enemy.cpp
Heaven31415/SpaceShooter
385e43aa2deb8720c1b0a23834ad31de97fd25eb
[ "Zlib" ]
null
null
null
src/GameState/PhysicalObject/Enemies/Enemy.cpp
Heaven31415/SpaceShooter
385e43aa2deb8720c1b0a23834ad31de97fd25eb
[ "Zlib" ]
null
null
null
#include "Enemy.hpp" #include "../../../Game.hpp" #include "../../../Common/Randomizer.hpp" Enemy::Enemy(Context& context, World& world, LaserFactory& laserFactory) : PhysicalObject(context, world, Type::Enemy, context.textures.get("EnemyShip")) , m_laserFactory(laserFactory) , m_manager(nullptr) { setVelocity({0.f, 0.f}); setMaxVelocity(Game::Config.enemySpeed); /* for now, they doesn't use configuration for their health setMaxHealth(Game::Config.enemyHealth); setHealth(getMaxHealth()); */ centerOrigin(); // this shouldn't be here sf::Vector2f mapSize = static_cast<sf::Vector2f>(Game::Config.windowSize); sf::Vector2f position = { Random::Real(1.f / 10.f * mapSize.x, 9.f / 10.f * mapSize.x), Random::Real(-mapSize.y / 10, 0.f) }; setPosition(position); } void Enemy::collision(PhysicalObject* object) { if (object->getType() == Type::Player) { object->takeDamage(1); takeDamage(1); } getContext().soundSystem.playSound("Explosion"); } void Enemy::update(sf::Time dt) { Object::update(dt); if (!isDestroyed() && m_manager) m_manager->update(this, dt); } void Enemy::changeState(unsigned state) { if(m_manager) m_manager->changeState(state); } void Enemy::addLaser() { auto laser = m_laserFactory.build("enemyLaser"); laser->setOwner(getGUID()); laser->setPosition(getPosition()); addChild(laser->getGUID()); getWorld().add(std::move(laser)); } std::size_t Enemy::countLasers() { std::size_t count = 0; for (auto& child : m_children) { auto* object = getWorld().getObject(child); if (object && object->getType() == Type::EnemyWeapon) count++; } return count; } void Enemy::setAI(EnemyStateManager::Ptr manager) { m_manager.swap(manager); }
24.72973
129
0.644809
Heaven31415
6f3253248ac38b5e8fdff4ca2f25591258362cbb
5,685
cc
C++
tc/core/polyhedral/reduction_matcher.cc
abdullah1908/TensorComprehensions
90360b9290244ff96f8a89d5311dc75981f70bb7
[ "Apache-2.0" ]
1
2021-08-28T17:59:20.000Z
2021-08-28T17:59:20.000Z
tc/core/polyhedral/reduction_matcher.cc
abdullah1908/TensorComprehensions
90360b9290244ff96f8a89d5311dc75981f70bb7
[ "Apache-2.0" ]
null
null
null
tc/core/polyhedral/reduction_matcher.cc
abdullah1908/TensorComprehensions
90360b9290244ff96f8a89d5311dc75981f70bb7
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tc/core/polyhedral/schedule_tree_matcher.h" #include <unordered_set> #include "tc/core/polyhedral/cuda/mapped_scop.h" #include "tc/core/polyhedral/schedule_tree.h" #include "tc/core/polyhedral/scop.h" #include "tc/external/isl.h" namespace tc { namespace polyhedral { using detail::ScheduleTree; using detail::ScheduleTreeElemBand; using detail::ScheduleTreeElemFilter; namespace { /* * Does the given statement perform a supported type of reduction? * Only addition is supported for now since it is not clear * if other types are supported by the CUB reduction wrapper. */ bool isSupportedReduction(Halide::Internal::Stmt stmt) { auto provide = stmt.as<Halide::Internal::Provide>(); auto call = provide->values[0].as<Halide::Internal::Call>(); if (call && call->args[0].as<Halide::Internal::Add>()) { return true; } return false; } // TODO: the function currently available in Scop only works _after_ inserting // the reduction. that is a kind of internal state dependence we want to avoid // If id is the statement identifier of an update statement // of a supported type of reduction, // then return the corresponding init statement in init and // the corresponding reduction dimensions in reductionDims. bool isReductionUpdateId( isl::id id, const Scop& scop, Halide::Internal::Stmt& init, std::vector<size_t>& reductionDims) { CHECK_EQ(scop.halide.statements.count(id), 1u) << "id is not a statement in scop" << id; auto provideNode = scop.halide.statements.at(id); if (!isSupportedReduction(provideNode)) { return false; } for (auto const& iup : scop.halide.reductions) { if (iup.update.same_as(provideNode)) { init = iup.init; reductionDims = iup.dims; return true; } } return false; } /* * Does "aff" only involve the specified input dimension (and not * any other input dimensions). */ bool pwAffInvolvesOnlyInputDim(isl::pw_aff pa, int redDimIdx) { auto space = pa.get_space(); if (!pa.involves_dims(isl::dim_type::in, redDimIdx, 1)) { return false; } if (pa.involves_dims(isl::dim_type::in, 0, redDimIdx) || pa.involves_dims( isl::dim_type::in, redDimIdx + 1, space.dim(isl::dim_type::in) - redDimIdx - 1)) { return false; } return true; } // Does pa have the form S(...) -> [(K*r)] where S is either a reduction init // or update statement and r is a known reduction loop in Scop? // // FIXME: now, K can be any value, including nested integer divisions, to // support detection after tiling; tighten this. bool isAlmostIdentityReduction(isl::pw_aff pa, const Scop& scop) { auto space = pa.get_space(); if (!space.has_tuple_id(isl::dim_type::in)) { return false; } auto stmtId = space.get_tuple_id(isl::dim_type::in); Halide::Internal::Stmt init; std::vector<size_t> reductionDims; if (!isReductionUpdateId(stmtId, scop, init, reductionDims)) { return false; } for (auto redDimIdx : reductionDims) { if (pwAffInvolvesOnlyInputDim(pa, redDimIdx)) { return true; } } return false; } /* * Return the identifier that maps to "stmt". */ isl::id statementId(const Scop& scop, const Halide::Internal::Stmt& stmt) { for (auto kvp : scop.halide.statements) { if (kvp.second.same_as(stmt)) { return kvp.first; } } CHECK(false) << "no id recorded for statement" << stmt; return isl::id(); } } // namespace std::pair<isl::union_set, isl::union_set> reductionInitsUpdates( isl::union_set domain, const Scop& scop) { auto initUnion = isl::union_set::empty(domain.get_space()); auto update = initUnion; std::unordered_set<isl::id, isl::IslIdIslHash> init; std::vector<isl::set> nonUpdate; // First collect all the update statements, // the corresponding init statement and all non-update statements. domain.foreach_set([&init, &update, &nonUpdate, &scop](isl::set set) { auto setId = set.get_tuple_id(); Halide::Internal::Stmt initStmt; std::vector<size_t> reductionDims; if (isReductionUpdateId(setId, scop, initStmt, reductionDims)) { update = update.unite(set); init.emplace(statementId(scop, initStmt)); } else { nonUpdate.emplace_back(set); } }); // Then check if all the non-update statements are init statements // that correspond to the update statements found. // If not, return an empty list of update statements. for (auto set : nonUpdate) { if (init.count(set.get_tuple_id()) != 1) { return std::pair<isl::union_set, isl::union_set>( initUnion, isl::union_set::empty(domain.get_space())); } initUnion = initUnion.unite(set); } return std::pair<isl::union_set, isl::union_set>(initUnion, update); } bool isReductionMember( isl::union_pw_aff member, isl::union_set domain, const Scop& scop) { return domain.every_set([member, &scop](isl::set set) { auto pa = member.extract_on_domain(set.get_space()); return isAlmostIdentityReduction(pa, scop); }); } } // namespace polyhedral } // namespace tc
31.236264
79
0.692876
abdullah1908
6f33423b21c98d04085a3b6dbe585b8062842975
1,208
cpp
C++
CodeForces/Complete/1000-1099/1006E-MilitaryProblem-OLD.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/1000-1099/1006E-MilitaryProblem-OLD.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/1000-1099/1006E-MilitaryProblem-OLD.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> #include <vector> #include <algorithm> void dfs(const std::vector<std::vector<long>> &g, long cur, std::vector<long> &below){ below[cur] = 1; for(long p = 0; p < g[cur].size(); p++){ long node = g[cur][p]; dfs(g, g[cur][p], below); below[cur] += below[node]; } } long find(const std::vector<std::vector<long>> &g, const std::vector<long> &below, long node, long rem){ if(rem <= 0){return -1;} if(rem == 1){return node;} --rem; for(long p = 0; p < g[node].size(); p++){ long nx = g[node][p]; if(rem > below[nx]){rem -= below[nx];} else{return find(g, below, nx, rem);} } return -1; } int main(){ long n, q; scanf("%ld %ld", &n, &q); std::vector<std::vector<long>> g(n + 1); for(long p = 2; p <= n; p++){ long x; scanf("%ld", &x); g[x].push_back(p); } for(long p = 1; p <= n; p++){sort(g[p].begin(), g[p].end());} std::vector<long> v(n + 1); std::vector<long> cnt(n + 1, 0); dfs(g, 1, cnt); while(q--){ long u, k; scanf("%ld %ld", &u, &k); long res = find(g, cnt, u, k); printf("%ld\n", res); } return 0; }
22.792453
104
0.481788
Ashwanigupta9125
6f36ba3779fc499e30c0d77e201cc4ead021382f
1,621
cpp
C++
command.cpp
KonradCzerw/portal2util
07bd8fbafe887bed35b076434a899db6444f901d
[ "MIT" ]
null
null
null
command.cpp
KonradCzerw/portal2util
07bd8fbafe887bed35b076434a899db6444f901d
[ "MIT" ]
null
null
null
command.cpp
KonradCzerw/portal2util
07bd8fbafe887bed35b076434a899db6444f901d
[ "MIT" ]
null
null
null
#include <command.hpp> #include <utils.hpp> #include <tier1.hpp> std::vector<Command*>& Command::GetList() { static std::vector<Command*> list; return list; } Command::Command() : ptr(nullptr), version(0), isRegistered(false), isReference(false) {} Command::~Command() { if(!this->isReference) SAFE_DELETE(this->ptr); } ConCommand* Command::ThisPtr() { return this->ptr; } Command::Command(const char *name) { this->ptr = reinterpret_cast<ConCommand *>(tier1->FindCommandBase(tier1->g_pCVar->ThisPtr(), name)); this->isReference = true; } Command::Command(const char* pName, _CommandCallback callback, const char* pHelpString, int flags, _CommandCompletionCallback completionFunc) : version(0), isRegistered(false), isReference(false) { this->ptr = new ConCommand(pName, callback, pHelpString, flags, completionFunc); Command::GetList().push_back(this); } void Command::Register() { if(!this->isRegistered) { this->ptr->ConCommandBase_VTable = tier1->ConCommand_VTable; tier1->RegisterConCommand(tier1->g_pCVar->ThisPtr(), this->ptr); tier1->m_pConCommandList = this->ptr; } this->isRegistered = true; } void Command::Unregister() { if(this->isRegistered) { tier1->UnregisterConCommand(tier1->g_pCVar->ThisPtr(), this->ptr); } this->isRegistered = false; } bool Command::operator!() { return this->ptr == nullptr; } int Command::RegisterAll() { auto result = 0; for(const auto& command : Command::GetList()) { command->Register(); ++result; } return result; } void Command::UnregisterAll() { for(const auto& command : Command::GetList()) { command->Unregister(); } }
21.905405
143
0.705737
KonradCzerw
6f3be101b8b0473963ac5727bedbfb2520a03c5f
7,133
cpp
C++
AwsGameKit/Source/AwsGameKitEditor/Private/AwsGameKitStyleSet.cpp
aws/aws-gamekit-unreal
72ecf02081e06f2926a5db9269e551f86df9bd10
[ "Apache-2.0" ]
17
2022-03-23T18:30:33.000Z
2022-03-31T19:59:27.000Z
AwsGameKit/Source/AwsGameKitEditor/Private/AwsGameKitStyleSet.cpp
aws/aws-gamekit-unreal
72ecf02081e06f2926a5db9269e551f86df9bd10
[ "Apache-2.0" ]
null
null
null
AwsGameKit/Source/AwsGameKitEditor/Private/AwsGameKitStyleSet.cpp
aws/aws-gamekit-unreal
72ecf02081e06f2926a5db9269e551f86df9bd10
[ "Apache-2.0" ]
4
2022-03-24T00:52:16.000Z
2022-03-28T18:09:08.000Z
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // GameKit #include "AwsGameKitStyleSet.h" // Unreal #include <Interfaces/IPluginManager.h> #include <Styling/SlateStyle.h> #include <Styling/SlateStyleRegistry.h> #include <Styling/SlateTypes.h> TSharedPtr<FSlateStyleSet> AwsGameKitStyleSet::Style; AwsGameKitStyleSet::AwsGameKitStyleSet() { if (Style.IsValid()) { return; } Style = MakeShareable(new FSlateStyleSet("AwsGameKitStyle")); Style->SetContentRoot(IPluginManager::Get().FindPlugin("AwsGameKit")->GetBaseDir() / TEXT("Resources") / TEXT("icons")); // Fonts Style->Set("RobotoRegular8", FSlateFontInfo(FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Regular.ttf"), 8)); Style->Set("RobotoRegular10", FSlateFontInfo(FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Regular.ttf"), 10)); Style->Set("RobotoRegular12", FSlateFontInfo(FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Regular.ttf"), 12)); Style->Set("RobotoBold10", FSlateFontInfo(FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Bold.ttf"), 10)); Style->Set("RobotoBold11", FSlateFontInfo(FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Bold.ttf"), 11)); Style->Set("RobotoBold12", FSlateFontInfo(FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Bold.ttf"), 12)); // Colors Style->Set("ButtonGreen", FColor::FromHex("#2F8C00")); Style->Set("ButtonGrey", FColor::FromHex("#EEEEEE")); Style->Set("ButtonRed", FColor::FromHex("#CC0000")); Style->Set("BackgroundGrey", FColor::FromHex("#333333")); Style->Set("ModalDialogBackground", FColor::FromHex("#3E3E3E")); Style->Set("Black", FColor::FromHex("#000000")); Style->Set("DarkGrey", FColor::FromHex("#191919")); Style->Set("MediumGrey", FColor::FromHex("#666666")); Style->Set("TextMediumGrey", FColor::FromHex("#AAAAAA")); Style->Set("LightGrey", FColor::FromHex("#CCCCCC")); Style->Set("White", FColor::FromHex("#FCFCFC")); Style->Set("ErrorRed", FColor::FromHex("#D13212")); Style->Set("InfoBlue", FColor::FromHex("#0073D9")); // Brushes FSlateColorBrush* darkGreyBrush = new FSlateColorBrush(Style->GetColor("DarkGrey")); Style->Set("DarkGreyBrush", darkGreyBrush); FSlateColorBrush* mediumGreyBrush = new FSlateColorBrush(Style->GetColor("MediumGrey")); Style->Set("MediumGreyBrush", mediumGreyBrush); FSlateColorBrush* backgroundGreyBrush = new FSlateColorBrush(Style->GetColor("BackgroundGrey")); Style->Set("BackgroundGreyBrush", backgroundGreyBrush); FSlateColorBrush* backgroundModalDialog = new FSlateColorBrush(Style->GetColor("ModalDialogBackground")); Style->Set("BackgroundModalDialogBrush", backgroundModalDialog); FSlateColorBrush* errorRedBrush = new FSlateColorBrush(Style->GetColor("ErrorRed")); Style->Set("ErrorRedBrush", errorRedBrush); FSlateColorBrush* infoBlueBrush = new FSlateColorBrush(Style->GetColor("InfoBlue")); Style->Set("InfoBlueBrush", infoBlueBrush); // Text const FTextBlockStyle& NormalText = FEditorStyle::Get().GetWidgetStyle<FTextBlockStyle>("NormalText"); Style->Set("DescriptionText", FTextBlockStyle(NormalText) .SetFont(Style->GetFontStyle("RobotoRegular10")) .SetColorAndOpacity(Style->GetColor("TextMediumGrey"))); Style->Set("DescriptionBoldText", FTextBlockStyle(NormalText) .SetFont(Style->GetFontStyle("RobotoBold10"))); Style->Set("ModalDialogText", FTextBlockStyle(NormalText) .SetFont(FEditorStyle::GetFontStyle("StandardDialog.LargeFont")) .SetColorAndOpacity(Style->GetColor("White"))); Style->Set("Button.WhiteText", FTextBlockStyle(NormalText) .SetFont(Style->GetFontStyle("RobotoBold10")) .SetColorAndOpacity(Style->GetColor("White")) .SetShadowOffset(FVector2D(1.0f, 1.0f))); Style->Set("Button.NormalText", FTextBlockStyle(NormalText)); // Hyperlinks Style->Set("Hyperlink", FCoreStyle::Get().GetWidgetStyle<FHyperlinkStyle>("Hyperlink")); FHyperlinkStyle modalDialogHyperLink = FCoreStyle::Get().GetWidgetStyle<FHyperlinkStyle>("Hyperlink"); modalDialogHyperLink.TextStyle.Font = FEditorStyle::GetFontStyle("StandardDialog.LargeFont"); Style->Set("ModalHyperlink", modalDialogHyperLink); // Icons FSlateImageBrush* deployedIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("success.png")), FVector2D(15, 15)); Style->Set("DeployedIcon", deployedIconBrush); FSlateImageBrush* waitingIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("waiting.png")), FVector2D(15, 15)); Style->Set("WaitingIcon", waitingIconBrush); FSlateImageBrush* errorIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("error.png")), FVector2D(15, 15)); Style->Set("ErrorIcon", errorIconBrush); FSlateImageBrush* progressIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("working.png")), FVector2D(15, 15)); Style->Set("ProgressIcon", progressIconBrush); FSlateImageBrush* unsynchronizedIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("unsynchronized.png")), FVector2D(15, 15)); Style->Set("UnsynchronizedIcon", unsynchronizedIconBrush); FSlateImageBrush* deleteIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("garbage.png")), FVector2D(15,15)); Style->Set("DeleteIcon", deleteIconBrush); FSlateImageBrush* cloudIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("cloud.png")), FVector2D(20,15)); Style->Set("CloudIcon", cloudIconBrush); FSlateImageBrush* warningIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("warning.png")), FVector2D(20,20)); Style->Set("WarningIcon", warningIconBrush); FSlateImageBrush* warningIconBrushSmall = new FSlateImageBrush(Style->RootToContentDir(TEXT("warning_16x16.png")), FVector2D(12, 12)); Style->Set("WarningIconSmall", warningIconBrushSmall); FSlateImageBrush* warningIconBrushInline = new FSlateImageBrush(Style->RootToContentDir(TEXT("warning_inline.png")), FVector2D(10, 10)); Style->Set("WarningIconInline", warningIconBrushInline); FSlateImageBrush* externalIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("external.png")), FVector2D(20, 20)); Style->Set("ExternalIcon", externalIconBrush); FSlateImageBrush* refreshIconBrush = new FSlateImageBrush(Style->RootToContentDir(TEXT("refresh.png")), FVector2D(15, 15)); Style->Set("RefreshIcon", refreshIconBrush); // Inline text image FInlineTextImageStyle inlineTextImageStyle = FInlineTextImageStyle() .SetImage(*warningIconBrushInline); Style->Set("WarningIconInline", inlineTextImageStyle); FButtonStyle helpButtonStyle = FButtonStyle() .SetPressed(*FEditorStyle::GetBrush("HelpIcon.Pressed")) .SetNormal(*FEditorStyle::GetBrush("HelpIcon")) .SetHovered(*FEditorStyle::GetBrush("HelpIcon.Hovered")); Style->Set("HelpButtonStyle", helpButtonStyle); FSlateStyleRegistry::RegisterSlateStyle(*Style.Get()); }
50.95
141
0.730408
aws
6f3dd367e6ef4ffc34e6c37a711ee907ac0db512
20,019
cc
C++
ncrack/timing.cc
Adam-K-P/dwm
7a95bb7e68abe713c4fd45809897ab19b33e65f7
[ "MIT" ]
null
null
null
ncrack/timing.cc
Adam-K-P/dwm
7a95bb7e68abe713c4fd45809897ab19b33e65f7
[ "MIT" ]
null
null
null
ncrack/timing.cc
Adam-K-P/dwm
7a95bb7e68abe713c4fd45809897ab19b33e65f7
[ "MIT" ]
null
null
null
/*************************************************************************** * timing.cc -- Functions related to computing crack timing and keeping * * track of rates. * * * ***********************IMPORTANT NMAP LICENSE TERMS************************ * * * The Nmap Security Scanner is (C) 1996-2011 Insecure.Com LLC. Nmap is * * also a registered trademark of Insecure.Com LLC. This program is free * * software; you may redistribute and/or modify it under the terms of the * * GNU General Public License as published by the Free Software * * Foundation; Version 2 with the clarifications and exceptions described * * below. This guarantees your right to use, modify, and redistribute * * this software under certain conditions. If you wish to embed Nmap * * technology into proprietary software, we sell alternative licenses * * (contact sales@insecure.com). Dozens of software vendors already * * license Nmap technology such as host discovery, port scanning, OS * * detection, and version detection. * * * * Note that the GPL places important restrictions on "derived works", yet * * it does not provide a detailed definition of that term. To avoid * * misunderstandings, we consider an application to constitute a * * "derivative work" for the purpose of this license if it does any of the * * following: * * o Integrates source code from Nmap * * o Reads or includes Nmap copyrighted data files, such as * * nmap-os-db or nmap-service-probes. * * o Executes Nmap and parses the results (as opposed to typical shell or * * execution-menu apps, which simply display raw Nmap output and so are * * not derivative works.) * * o Integrates/includes/aggregates Nmap into a proprietary executable * * installer, such as those produced by InstallShield. * * o Links to a library or executes a program that does any of the above * * * * The term "Nmap" should be taken to also include any portions or derived * * works of Nmap. This list is not exclusive, but is meant to clarify our * * interpretation of derived works with some common examples. Our * * interpretation applies only to Nmap--we don't speak for other people's * * GPL works. * * * * If you have any questions about the GPL licensing restrictions on using * * Nmap in non-GPL works, we would be happy to help. As mentioned above, * * we also offer alternative license to integrate Nmap into proprietary * * applications and appliances. These contracts have been sold to dozens * * of software vendors, and generally include a perpetual license as well * * as providing for priority support and updates as well as helping to * * fund the continued development of Nmap technology. Please email * * sales@insecure.com for further information. * * * * As a special exception to the GPL terms, Insecure.Com LLC grants * * permission to link the code of this program with any version of the * * OpenSSL library which is distributed under a license identical to that * * listed in the included docs/licenses/OpenSSL.txt file, and distribute * * linked combinations including the two. You must obey the GNU GPL in all * * respects for all of the code used other than OpenSSL. If you modify * * this file, you may extend this exception to your version of the file, * * but you are not obligated to do so. * * * * If you received these files with a written license agreement or * * contract stating terms other than the terms above, then that * * alternative license agreement takes precedence over these comments. * * * * Source is provided to this software because we believe users have a * * right to know exactly what a program is going to do before they run it. * * This also allows you to audit the software for security holes (none * * have been found so far). * * * * Source code also allows you to port Nmap to new platforms, fix bugs, * * and add new features. You are highly encouraged to send your changes * * to nmap-dev@insecure.org for possible incorporation into the main * * distribution. By sending these changes to Fyodor or one of the * * Insecure.Org development mailing lists, it is assumed that you are * * offering the Nmap Project (Insecure.Com LLC) the unlimited, * * non-exclusive right to reuse, modify, and relicense the code. Nmap * * will always be available Open Source, but this is important because the * * inability to relicense code has caused devastating problems for other * * Free Software projects (such as KDE and NASM). We also occasionally * * relicense the code to third parties as discussed above. If you wish to * * specify special license conditions of your contributions, just say so * * when you send them. * * * * 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 v2.0 for more details at * * http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file * * included with Nmap. * * * ***************************************************************************/ /* $Id: timing.cc 12955 2009-04-15 00:37:03Z fyodor $ */ #include "timing.h" #include "NcrackOps.h" #include "utils.h" #include "time.h" extern NcrackOps o; /* current_rate_history defines how far back (in seconds) we look when calculating the current rate. */ RateMeter::RateMeter(double current_rate_history) { this->current_rate_history = current_rate_history; start_tv.tv_sec = 0; start_tv.tv_usec = 0; stop_tv.tv_sec = 0; stop_tv.tv_usec = 0; last_update_tv.tv_sec = 0; last_update_tv.tv_usec = 0; total = 0.0; current_rate = 0.0; assert(!isSet(&start_tv)); assert(!isSet(&stop_tv)); } void RateMeter::start(const struct timeval *now) { assert(!isSet(&start_tv)); assert(!isSet(&stop_tv)); if (now == NULL) gettimeofday(&start_tv, NULL); else start_tv = *now; } void RateMeter::stop(const struct timeval *now) { assert(isSet(&start_tv)); assert(!isSet(&stop_tv)); if (now == NULL) gettimeofday(&stop_tv, NULL); else stop_tv = *now; } /* Update the rates to reflect the given amount added to the total at the time now. If now is NULL, get the current time with gettimeofday. */ void RateMeter::update(double amount, const struct timeval *now) { struct timeval tv; double diff; double interval; double count; assert(isSet(&start_tv)); assert(!isSet(&stop_tv)); /* Update the total. */ total += amount; if (now == NULL) { gettimeofday(&tv, NULL); now = &tv; } if (!isSet(&last_update_tv)) last_update_tv = start_tv; /* Calculate the approximate moving average of how much was recorded in the last current_rate_history seconds. This average is what is returned as the "current" rate. */ /* How long since the last update? */ diff = TIMEVAL_SUBTRACT(*now, last_update_tv) / 1000000.0; if (diff < -current_rate_history) /* This happened farther in the past than we care about. */ return; if (diff < 0.0) { /* If the event happened in the past, just add it into the total and don't change last_update_tv, as if it had happened at the same time as the most recent event. */ now = &last_update_tv; diff = 0.0; } /* Find out how far back in time to look. We want to look back current_rate_history seconds, or to when the last update occurred, whichever is longer. However, we never look past the start. */ struct timeval tmp; /* Find the time current_rate_history seconds after the start. That's our threshold for deciding how far back to look. */ TIMEVAL_ADD(tmp, start_tv, (time_t) (current_rate_history * 1000000.0)); if (TIMEVAL_AFTER(*now, tmp)) interval = MAX(current_rate_history, diff); else interval = TIMEVAL_SUBTRACT(*now, start_tv) / 1000000.0; assert(diff <= interval); /* If we record an amount in the very same instant that the timer is started, there's no way to calculate meaningful rates. Ignore it. */ if (interval == 0.0) return; /* To calculate the approximate average of the rate over the last interval seconds, we assume that the rate was constant over that interval. We calculate how much would have been received in that interval, ignoring the first diff seconds' worth: (interval - diff) * current_rate. Then we add how much was received in the most recent diff seconds. Divide by the width of the interval to get the average. */ count = (interval - diff) * current_rate + amount; current_rate = count / interval; last_update_tv = *now; } double RateMeter::getOverallRate(const struct timeval *now) const { double elapsed; elapsed = elapsedTime(now); if (elapsed <= 0.0) return 0.0; else return total / elapsed; } /* Get the "current" rate (actually a moving average of the last current_rate_history seconds). If update is true (its default value), lower the rate to account for the time since the last record. */ double RateMeter::getCurrentRate(const struct timeval *now, bool update) { if (update) this->update(0.0, now); return current_rate; } double RateMeter::getTotal(void) const { return total; } /* Get the number of seconds the meter has been running: if it has been stopped, the amount of time between start and stop, or if it is still running, the amount of time between start and now. */ double RateMeter::elapsedTime(const struct timeval *now) const { struct timeval tv; const struct timeval *end_tv; assert(isSet(&start_tv)); if (isSet(&stop_tv)) { end_tv = &stop_tv; } else if (now == NULL) { gettimeofday(&tv, NULL); end_tv = &tv; } else { end_tv = now; } return TIMEVAL_SUBTRACT(*end_tv, start_tv) / 1000000.0; } /* Returns true if tv has been initialized; i.e., its members are not all zero. */ bool RateMeter::isSet(const struct timeval *tv) { return tv->tv_sec != 0 || tv->tv_usec != 0; } PacketRateMeter::PacketRateMeter(double current_rate_history) { packet_rate_meter = RateMeter(current_rate_history); byte_rate_meter = RateMeter(current_rate_history); } void PacketRateMeter::start(const struct timeval *now) { packet_rate_meter.start(now); byte_rate_meter.start(now); } void PacketRateMeter::stop(const struct timeval *now) { packet_rate_meter.stop(now); byte_rate_meter.stop(now); } /* Record one packet of length len. */ void PacketRateMeter::update(u32 len, const struct timeval *now) { packet_rate_meter.update(1, now); byte_rate_meter.update(len, now); } double PacketRateMeter::getOverallPacketRate(const struct timeval *now) const { return packet_rate_meter.getOverallRate(now); } double PacketRateMeter::getCurrentPacketRate(const struct timeval *now, bool update) { return packet_rate_meter.getCurrentRate(now, update); } double PacketRateMeter::getOverallByteRate(const struct timeval *now) const { return byte_rate_meter.getOverallRate(now); } double PacketRateMeter::getCurrentByteRate(const struct timeval *now, bool update) { return byte_rate_meter.getCurrentRate(now, update); } unsigned long long PacketRateMeter::getNumPackets(void) const { return (unsigned long long) packet_rate_meter.getTotal(); } unsigned long long PacketRateMeter::getNumBytes(void) const { return (unsigned long long) byte_rate_meter.getTotal(); } ScanProgressMeter::ScanProgressMeter() { gettimeofday(&begin, NULL); last_print_test = begin; memset(&last_print, 0, sizeof(last_print)); memset(&last_est, 0, sizeof(last_est)); beginOrEndTask(&begin, NULL, true); } ScanProgressMeter::~ScanProgressMeter() { ; } /* Decides whether a timing report is likely to even be printed. There are stringent limitations on how often they are printed, as well as the verbosity level that must exist. So you might as well check this before spending much time computing progress info. now can be NULL if caller doesn't have the current time handy. Just because this function returns true does not mean that the next printStatsIfNecessary will always print something. It depends on whether time estimates have changed, which this func doesn't even know about. */ bool ScanProgressMeter::mayBePrinted(const struct timeval *now) { struct timeval tv; if (!o.verbose) return false; if (!now) { gettimeofday(&tv, NULL); now = (const struct timeval *) &tv; } if (last_print.tv_sec == 0) { /* We've never printed before -- the rules are less stringent */ if (difftime(now->tv_sec, begin.tv_sec) > 30) return true; else return false; } if (difftime(now->tv_sec, last_print_test.tv_sec) < 3) return false; /* No point even checking too often */ /* We'd never want to print more than once per 30 seconds */ if (difftime(now->tv_sec, last_print.tv_sec) < 30) return false; return true; } /* Return an estimate of the time remaining if a process was started at begin and is perc_done of the way finished. Returns inf if perc_done == 0.0. */ static double estimate_time_left(double perc_done, const struct timeval *begin, const struct timeval *now) { double time_used_s; double time_needed_s; time_used_s = difftime(now->tv_sec, begin->tv_sec); time_needed_s = time_used_s / perc_done; return time_needed_s - time_used_s; } /* Prints an estimate of when this scan will complete. It only does so if mayBePrinted() is true, and it seems reasonable to do so because the estimate has changed significantly. Returns whether or not a line was printed.*/ bool ScanProgressMeter::printStatsIfNecessary(double perc_done, const struct timeval *now) { struct timeval tvtmp; double time_left_s; bool printit = false; if (!now) { gettimeofday(&tvtmp, NULL); now = (const struct timeval *) &tvtmp; } if (!mayBePrinted(now)) return false; last_print_test = *now; if (perc_done <= 0.003) return false; /* Need more info first */ assert(perc_done <= 1.0); time_left_s = estimate_time_left(perc_done, &begin, now); if (time_left_s < 30) return false; /* No point in updating when it is virtually finished. */ if (last_est.tv_sec == 0) { /* We don't have an estimate yet (probably means a low completion). */ printit = true; } else if (TIMEVAL_AFTER(*now, last_est)) { /* The last estimate we printed has passed. Print a new one. */ printit = true; } else { /* If the estimate changed by more than 3 minutes, and if that change represents at least 5% of the total time, print it. */ double prev_est_total_time_s = difftime(last_est.tv_sec, begin.tv_sec); double prev_est_time_left_s = difftime(last_est.tv_sec, last_print.tv_sec); double change_abs_s = ABS(prev_est_time_left_s - time_left_s); if (o.debugging || (change_abs_s > 15 && change_abs_s > .05 * prev_est_total_time_s)) printit = true; } if (printit) { return printStats(perc_done, now); } return false; } /* Prints an estimate of when this scan will complete. */ bool ScanProgressMeter::printStats(double perc_done, const struct timeval *now) { struct timeval tvtmp; double time_left_s; time_t timet; struct tm *ltime; if (!now) { gettimeofday(&tvtmp, NULL); now = (const struct timeval *) &tvtmp; } last_print = *now; // If we're less than 1% done we probably don't have enough // data for decent timing estimates. Also with perc_done == 0 // these elements will be nonsensical. if (perc_done < 0.01) { log_write(LOG_STDOUT, "About %.2f%% done\n", perc_done * 100); log_flush(LOG_STDOUT); return true; } /* Add 0.5 to get the effect of rounding in integer calculations. */ time_left_s = estimate_time_left(perc_done, &begin, now) + 0.5; last_est = *now; last_est.tv_sec += (time_t)time_left_s; /* Get the estimated time of day at completion */ timet = last_est.tv_sec; ltime = localtime(&timet); assert(ltime); log_write(LOG_STDOUT, "About %.2f%% done; ETC: %02d:%02d " "(%.f:%02.f:%02.f remaining)\n", perc_done * 100, ltime->tm_hour, ltime->tm_min, floor(time_left_s / 60.0 / 60.0), floor(fmod(time_left_s / 60.0, 60.0)), floor(fmod(time_left_s, 60.0))); /*log_write(LOG_XML, "<taskprogress task=\"%s\" time=\"%lu\" percent=\"%.2f\" remaining=\"%.f\" etc=\"%lu\" />\n", scantypestr, (unsigned long) now->tv_sec, perc_done * 100, time_left_s, (unsigned long) last_est.tv_sec); */ log_flush(LOG_STDOUT|LOG_XML); return true; } /* Indicates that the task is beginning or ending, and that a message should be generated if appropriate. Returns whether a message was printed. now may be NULL, if the caller doesn't have the current time handy. additional_info may be NULL if no additional information is necessary. */ bool ScanProgressMeter::beginOrEndTask(const struct timeval *now, const char *additional_info, bool beginning) { struct timeval tvtmp; //struct tm *tm; //time_t tv_sec; if (!o.verbose) { return false; } if (!now) { gettimeofday(&tvtmp, NULL); now = (const struct timeval *) &tvtmp; } //tv_sec = now->tv_sec; //tm = localtime(&tv_sec); if (beginning) { // log_write(LOG_STDOUT, "Initiating %s at %02d:%02d", scantypestr, tm->tm_hour, tm->tm_min); // log_write(LOG_XML, "<taskbegin task=\"%s\" time=\"%lu\"", scantypestr, (unsigned long) now->tv_sec); if (additional_info) { log_write(LOG_STDOUT, " (%s)", additional_info); log_write(LOG_XML, " extrainfo=\"%s\"", additional_info); } log_write(LOG_STDOUT, "\n"); log_write(LOG_XML, " />\n"); } else { //log_write(LOG_STDOUT, "Completed %s at %02d:%02d, %.2fs elapsed", scantypestr, tm->tm_hour, tm->tm_min, TIMEVAL_MSEC_SUBTRACT(*now, begin) / 1000.0); // log_write(LOG_XML, "<taskend task=\"%s\" time=\"%lu\"", scantypestr, (unsigned long) now->tv_sec); if (additional_info) { log_write(LOG_STDOUT, " (%s)", additional_info); log_write(LOG_XML, " extrainfo=\"%s\"", additional_info); } log_write(LOG_STDOUT, "\n"); log_write(LOG_XML, " />\n"); } log_flush(LOG_STDOUT|LOG_XML); return true; }
38.572254
155
0.636445
Adam-K-P
6f3ddcedff81425b1bbbbd4bc05feec1b03a490b
1,618
cpp
C++
Engine/lib/sdl/src/video/winrt/SDL_winrtopengles.cpp
John3/crabmusket_Torque3D
d84bd0fce2837ffac69d9fc9aadcdf5ee2c98b5c
[ "Unlicense" ]
77
2015-09-09T00:00:15.000Z
2021-08-28T04:37:35.000Z
Engine/lib/sdl/src/video/winrt/SDL_winrtopengles.cpp
John3/crabmusket_Torque3D
d84bd0fce2837ffac69d9fc9aadcdf5ee2c98b5c
[ "Unlicense" ]
10
2015-01-20T23:14:46.000Z
2019-04-05T22:04:15.000Z
Engine/lib/sdl/src/video/winrt/SDL_winrtopengles.cpp
John3/crabmusket_Torque3D
d84bd0fce2837ffac69d9fc9aadcdf5ee2c98b5c
[ "Unlicense" ]
53
2015-12-14T08:33:27.000Z
2021-12-28T04:51:43.000Z
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" // TODO: WinRT, make this file compile via C code #if SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL /* EGL implementation of SDL OpenGL support */ #include "SDL_winrtvideo_cpp.h" extern "C" { #include "SDL_winrtopengles.h" } #define EGL_D3D11_ONLY_DISPLAY_ANGLE ((NativeDisplayType) -3) extern "C" int WINRT_GLES_LoadLibrary(_THIS, const char *path) { return SDL_EGL_LoadLibrary(_this, path, EGL_D3D11_ONLY_DISPLAY_ANGLE); } extern "C" { SDL_EGL_CreateContext_impl(WINRT) SDL_EGL_SwapWindow_impl(WINRT) SDL_EGL_MakeCurrent_impl(WINRT) } #endif /* SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL */ /* vi: set ts=4 sw=4 expandtab: */
31.72549
76
0.765142
John3
6f406536ff342b5b4f54733cbd9cf6e0a69a38e3
2,671
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_multicore/python/focal/window4total.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_multicore/python/focal/window4total.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_multicore/python/focal/window4total.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#include "pcraster_multicore/python/focal/window4total.h" // PCRaster #include "calc_spatial.h" // Field wrapper #include "pcraster_multicore/wrapper/datatype_customization_points/multicore_spatial.h" #include "pcraster_multicore/wrapper/datatype_traits/multicore_spatial.h" #include "pcraster_multicore/wrapper/argument_customization_points/multicore_spatial.h" #include "pcraster_multicore/wrapper/argument_traits/multicore_spatial.h" #include "pcraster_multicore/python/execution_policy.h" #include "pcraster_multicore/python/local/utils.h" // Fern #include "fern/algorithm/convolution/neighborhood/square.h" #include "fern/algorithm/convolution/neighborhood/square_traits.h" #include "fern/algorithm/convolution/convolve.h" #include "fern/algorithm/convolution/policies.h" #include "fern/core/data_customization_point.h" namespace fa = fern::algorithm; namespace pcraster_multicore { namespace python { namespace detail { template< typename InputNoDataPolicy, typename OutputNoDataPolicy, typename ExecutionPolicy, typename Value, typename Result > void w4t( InputNoDataPolicy const& input_no_data_policy, OutputNoDataPolicy& output_no_data_policy, ExecutionPolicy& execution_policy, Value const& value, Result& result){ fern::Square<bool, 1> window_kernel({ {false, true , false}, {true , false, true}, {false, true , false} }); fa::convolution::convolve< fa::convolve::SkipNoData, fa::convolve::DontDivideByWeights, fa::convolve::SkipOutOfImage, fa::convolve::ReplaceNoDataFocusElement, fa::convolve::OutOfRangePolicy>( input_no_data_policy, output_no_data_policy, execution_policy, value, window_kernel, result); } } //namespace detail calc::Field* window4total( calc::Field * field){ if(field->isSpatial() == false){ throw std::runtime_error("argument is non-spatial, only spatial is allowed\n"); } assert_equal_location_attributes(*field); assert_scalar_valuescale(*field, "argument"); const multicore_field::Spatial<REAL4> arg(field); calc::Spatial* field_result = new calc::Spatial(VS_S, calc::CRI_f, nr_cells()); multicore_field::Spatial<REAL4> result(field_result); fa::ExecutionPolicy epol = execution_policy(); using InputNoDataPolicy = fa::InputNoDataPolicies<SpatialDetectNoData<REAL4>>; InputNoDataPolicy input_no_data_policy{{arg}}; SpatialSetNoData<REAL4> output_no_data_policy(result); detail::w4t(input_no_data_policy, output_no_data_policy, epol, arg, result); return field_result; } } // namespace python } // namespace pcraster_multicore
26.979798
87
0.750281
quanpands
6f4079e4415ef8af8f2de5d02fccf8e96c58c68a
10,359
cpp
C++
Experimental/Samples/VR/src/Sample_VR.cpp
azhirnov/DE-Experimental
be0872e603ff0ea1a2aa2b4e579807f6931e65ff
[ "MIT" ]
1
2020-12-19T02:16:12.000Z
2020-12-19T02:16:12.000Z
Experimental/Samples/VR/src/Sample_VR.cpp
azhirnov/DE-Experimental
be0872e603ff0ea1a2aa2b4e579807f6931e65ff
[ "MIT" ]
null
null
null
Experimental/Samples/VR/src/Sample_VR.cpp
azhirnov/DE-Experimental
be0872e603ff0ea1a2aa2b4e579807f6931e65ff
[ "MIT" ]
null
null
null
#include <random> #include <thread> #include "Timer.hpp" #include "MapHelper.hpp" #include "Sample_VR.hpp" #include "TextureUtilities.h" #include "TexturedCube.hpp" #include "EngineFactoryVk.h" #include "OpenVRDevice.h" #include "VREmulator.h" namespace DEVR { using EHmdStatus = IVRDevice::EHmdStatus; void Sample_VR::CreateUniformBuffer() { BufferDesc CBDesc; CBDesc.Name = "VS constants CB"; CBDesc.uiSizeInBytes = sizeof(float4x4) * 2; CBDesc.Usage = USAGE_DYNAMIC; CBDesc.BindFlags = BIND_UNIFORM_BUFFER; CBDesc.CPUAccessFlags = CPU_ACCESS_WRITE; m_pDevice->CreateBuffer(CBDesc, nullptr, &m_VSConstants); } void Sample_VR::CreatePipelineState() { LayoutElement LayoutElems[] = { LayoutElement{0, 0, 3, VT_FLOAT32, False}, LayoutElement{1, 0, 2, VT_FLOAT32, False}, LayoutElement{2, 1, 4, VT_FLOAT32, False, INPUT_ELEMENT_FREQUENCY_PER_INSTANCE}, LayoutElement{3, 1, 4, VT_FLOAT32, False, INPUT_ELEMENT_FREQUENCY_PER_INSTANCE}, LayoutElement{4, 1, 4, VT_FLOAT32, False, INPUT_ELEMENT_FREQUENCY_PER_INSTANCE}, LayoutElement{5, 1, 4, VT_FLOAT32, False, INPUT_ELEMENT_FREQUENCY_PER_INSTANCE}}; RefCntAutoPtr<IShaderSourceInputStreamFactory> pShaderSourceFactory; m_pEngineFactory->CreateDefaultShaderSourceStreamFactory(nullptr, &pShaderSourceFactory); m_pPSO = TexturedCube::CreatePipelineState(m_pDevice, m_VRDevice->GetImageFormat(), m_DepthFormat, pShaderSourceFactory, "cube_inst.vsh", "cube_inst.psh", LayoutElems, _countof(LayoutElems)); m_pPSO->GetStaticVariableByName(SHADER_TYPE_VERTEX, "Constants")->Set(m_VSConstants); m_pPSO->CreateShaderResourceBinding(&m_SRB, true); } void Sample_VR::CreateInstanceBuffer() { BufferDesc InstBuffDesc; InstBuffDesc.Name = "Instance data buffer"; InstBuffDesc.Usage = USAGE_DEFAULT; InstBuffDesc.BindFlags = BIND_VERTEX_BUFFER; InstBuffDesc.uiSizeInBytes = sizeof(float4x4) * MaxInstances; m_pDevice->CreateBuffer(InstBuffDesc, nullptr, &m_InstanceBuffer); PopulateInstanceBuffer(); } void Sample_VR::PopulateInstanceBuffer() { std::vector<float4x4> InstanceData(m_GridSize * m_GridSize * m_GridSize); float fGridSize = static_cast<float>(m_GridSize); std::mt19937 gen; std::uniform_real_distribution<float> scale_distr(0.3f, 1.0f); std::uniform_real_distribution<float> offset_distr(-0.15f, +0.15f); std::uniform_real_distribution<float> rot_distr(-PI_F, +PI_F); float BaseScale = 0.6f / fGridSize; int instId = 0; for (int x = 0; x < m_GridSize; ++x) { for (int y = 0; y < m_GridSize; ++y) { for (int z = 0; z < m_GridSize; ++z) { float xOffset = 2.f * (x + 0.5f + offset_distr(gen)) / fGridSize - 1.f; float yOffset = 2.f * (y + 0.5f + offset_distr(gen)) / fGridSize - 1.f; float zOffset = 2.f * (z + 0.5f + offset_distr(gen)) / fGridSize - 1.f; float scale = BaseScale * scale_distr(gen); float4x4 rotation = float4x4::RotationX(rot_distr(gen)) * float4x4::RotationY(rot_distr(gen)) * float4x4::RotationZ(rot_distr(gen)); float4x4 matrix = rotation * float4x4::Scale(scale, scale, scale) * float4x4::Translation(xOffset, yOffset, zOffset); InstanceData[instId++] = matrix; } } } Uint32 DataSize = static_cast<Uint32>(sizeof(InstanceData[0]) * InstanceData.size()); m_pContext->UpdateBuffer(m_InstanceBuffer, 0, DataSize, InstanceData.data(), RESOURCE_STATE_TRANSITION_MODE_TRANSITION); } void Sample_VR::CreateRenderTargets() { TextureDesc desc; desc.Name = "Depth texture"; desc.Type = RESOURCE_DIM_TEX_2D; desc.Width = m_VRDevice->GetRenderTargetDimension().x; desc.Height = m_VRDevice->GetRenderTargetDimension().y; desc.MipLevels = 1; desc.BindFlags = BIND_DEPTH_STENCIL; desc.Format = m_DepthFormat; m_pDevice->CreateTexture(desc, nullptr, &m_DepthTexture); } void Sample_VR::Render() { ITexture* RenderTargets[2] = {}; ITextureView* RTViews[2] = {}; ITextureView* DSView = m_DepthTexture->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL); if (!m_VRDevice->GetRenderTargets(&RenderTargets[0], &RenderTargets[1])) return; for (uint i = 0; i < 2; ++i) { RTViews[i] = RenderTargets[i]->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); m_pContext->SetRenderTargets(1, &RTViews[i], DSView, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); const float ClearColor[] = {0.350f, 0.350f, 0.350f, 1.0f}; m_pContext->ClearRenderTarget(RTViews[i], ClearColor, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); m_pContext->ClearDepthStencil(DSView, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); { MapHelper<float4x4> CBConstants(m_pContext, m_VSConstants, MAP_WRITE, MAP_FLAG_DISCARD); CBConstants[0] = m_ViewProjMatrix[i].Transpose(); CBConstants[1] = m_RotationMatrix.Transpose(); } Uint32 offsets[] = {0, 0}; IBuffer* pBuffs[] = {m_CubeVertexBuffer, m_InstanceBuffer}; m_pContext->SetVertexBuffers(0, _countof(pBuffs), pBuffs, offsets, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET); m_pContext->SetIndexBuffer(m_CubeIndexBuffer, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); m_pContext->SetPipelineState(m_pPSO); m_pContext->CommitShaderResources(m_SRB, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); DrawIndexedAttribs DrawAttrs; DrawAttrs.IndexType = VT_UINT32; DrawAttrs.NumIndices = 36; DrawAttrs.NumInstances = m_GridSize * m_GridSize * m_GridSize; DrawAttrs.Flags = DRAW_FLAG_VERIFY_ALL; m_pContext->DrawIndexed(DrawAttrs); } } float4x4 Sample_VR::GetAdjustedProjectionMatrix(float FOV, float NearPlane, float FarPlane) const { uint2 Dim = m_VRDevice->GetRenderTargetDimension(); float AspectRatio = float(Dim.x) / Dim.y; float YScale = 1.f / std::tan(FOV / 2.f); float XScale = YScale / AspectRatio; float4x4 Proj; Proj._11 = XScale; Proj._22 = YScale; Proj.SetNearFarClipPlanes(NearPlane, FarPlane, m_pDevice->GetDeviceCaps().IsGLDevice()); return Proj; } void Sample_VR::Update(double CurrTime, double ElapsedTime) { auto& vrCamera = m_VRDevice->GetCamera(); float4x4 View = float4x4::Translation(vrCamera.position) * vrCamera.pose; //float4x4::RotationX(-0.6f) * float4x4::Translation(0.f, 0.f, 4.0f); float4x4 Proj = GetAdjustedProjectionMatrix(PI_F / 4.0f, 0.1f, 100.f); m_ViewProjMatrix[0] = View * vrCamera.left.view * vrCamera.left.proj; m_ViewProjMatrix[1] = View * vrCamera.right.view * vrCamera.right.proj; m_RotationMatrix = float4x4::RotationY(float(CurrTime) * 0.01f) * float4x4::RotationX(-float(CurrTime) * 0.025f); } bool Sample_VR::Initialize() { // engine initialization { m_VRDevice.reset(new VREmulatorVk{}); //m_VRDevice.reset(new OpenVRDeviceVk{}); //m_VRDevice.reset(new OpenXRDeviceVk{}); if (!m_VRDevice->Create()) return false; IVRDevice::Requirements Req; m_VRDevice->GetRequirements(Req); EngineVkCreateInfo CreateInfo; CreateInfo.EnableValidation = true; CreateInfo.NumDeferredContexts = 0; CreateInfo.AdapterId = Req.AdapterId; CreateInfo.InstanceExtensionCount = Uint32(Req.InstanceExtensions.size()); CreateInfo.ppInstanceExtensionNames = CreateInfo.InstanceExtensionCount ? Req.InstanceExtensions.data() : nullptr; CreateInfo.DeviceExtensionCount = Uint32(Req.DeviceExtensions.size()); CreateInfo.ppDeviceExtensionNames = CreateInfo.DeviceExtensionCount ? Req.DeviceExtensions.data() : nullptr; auto* Factory = GetEngineFactoryVk(); m_pEngineFactory = Factory; IRenderDevice* Device = nullptr; IDeviceContext* Context = nullptr; Factory->CreateDeviceAndContextsVk(CreateInfo, &Device, &Context); if (!Device) return false; m_pDevice = Device; m_pContext = Context; m_VRDevice->Initialize(Device, Context); m_VRDevice->SetupCamera(float2{0.1f, 100.f}); } CreateRenderTargets(); CreateUniformBuffer(); CreatePipelineState(); m_CubeVertexBuffer = TexturedCube::CreateVertexBuffer(m_pDevice); m_CubeIndexBuffer = TexturedCube::CreateIndexBuffer(m_pDevice); m_TextureSRV = TexturedCube::LoadTexture(m_pDevice, "DGLogo.png")->GetDefaultView(TEXTURE_VIEW_SHADER_RESOURCE); m_SRB->GetVariableByName(SHADER_TYPE_PIXEL, "g_Texture")->Set(m_TextureSRV); CreateInstanceBuffer(); return true; } void Sample_VR::Run() { if (!Initialize()) return; Diligent::Timer Timer; auto PrevTime = Timer.GetElapsedTime(); for (;;) { if (!m_VRDevice->BeginFrame()) break; EHmdStatus status = m_VRDevice->GetStatus(); auto CurrTime = Timer.GetElapsedTime(); auto ElapsedTime = CurrTime - PrevTime; PrevTime = CurrTime; switch (status) { case EHmdStatus::Active: case EHmdStatus::Mounted: Update(CurrTime, ElapsedTime); Render(); break; case EHmdStatus::Standby: std::this_thread::sleep_for(std::chrono::milliseconds{1}); break; case EHmdStatus::PowerOff: return; } m_VRDevice->EndFrame(); m_pDevice->ReleaseStaleResources(); } } } // namespace DEVR int main() { DEVR::Sample_VR sample; sample.Run(); return 0; }
36.094077
153
0.643209
azhirnov
6f42c54b47627b1736ae9f57b429f87311734095
1,204
cc
C++
components/autofill_assistant/browser/features.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill_assistant/browser/features.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/autofill_assistant/browser/features.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill_assistant/browser/features.h" #include "base/feature_list.h" namespace autofill_assistant { namespace features { const base::Feature kAutofillAssistant{"AutofillAssistant", base::FEATURE_ENABLED_BY_DEFAULT}; // Guard for the end condition when a non-renderer-initiated navigation occurs // while the AutofillAssistant is in RUNNING state. // TODO(b/159309621): Remove this if the end condition shows no unwanted side // effects. const base::Feature kAutofillAssistantBreakOnRunningNavigation{ "AutofillAssistantBreakOnRunningNavigation", base::FEATURE_ENABLED_BY_DEFAULT}; // Controls whether to enable Assistant Autofill in a normal Chrome tab. const base::Feature kAutofillAssistantChromeEntry{ "AutofillAssistantChromeEntry", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kAutofillAssistantDirectActions{ "AutofillAssistantDirectActions", base::FEATURE_ENABLED_BY_DEFAULT}; } // namespace features } // namespace autofill_assistant
37.625
78
0.77907
mghgroup
6f480fe7d809ba9a8af7a76b60e358c45a94ec6c
2,569
cc
C++
chrome/browser/sync/util/user_settings_posix.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/browser/sync/util/user_settings_posix.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/sync/util/user_settings_posix.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
// Copyright (c) 2010 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. // // Implement the storage of service tokens in memory. #include "chrome/browser/sync/util/user_settings.h" #include "base/logging.h" #include "chrome/browser/password_manager/encryptor.h" #include "chrome/common/sqlite_utils.h" namespace browser_sync { void UserSettings::SetAuthTokenForService( const std::string& email, const std::string& service_name, const std::string& long_lived_service_token) { VLOG(1) << "Saving auth token " << long_lived_service_token << " for " << email << "for service " << service_name; std::string encrypted_service_token; if (!Encryptor::EncryptString(long_lived_service_token, &encrypted_service_token)) { LOG(ERROR) << "Encrytion failed: " << long_lived_service_token; return; } ScopedDBHandle dbhandle(this); SQLStatement statement; statement.prepare(dbhandle.get(), "INSERT INTO cookies " "(email, service_name, service_token) " "values (?, ?, ?)"); statement.bind_string(0, email); statement.bind_string(1, service_name); statement.bind_blob(2, encrypted_service_token.data(), encrypted_service_token.size()); if (SQLITE_DONE != statement.step()) { LOG(FATAL) << sqlite3_errmsg(dbhandle.get()); } } bool UserSettings::GetLastUserAndServiceToken(const std::string& service_name, std::string* username, std::string* service_token) { ScopedDBHandle dbhandle(this); SQLStatement query; query.prepare(dbhandle.get(), "SELECT email, service_token FROM cookies" " WHERE service_name = ?"); query.bind_string(0, service_name.c_str()); if (SQLITE_ROW == query.step()) { std::string encrypted_service_token; query.column_blob_as_string(1, &encrypted_service_token); if (!Encryptor::DecryptString(encrypted_service_token, service_token)) { LOG(ERROR) << "Decryption failed: " << encrypted_service_token; return false; } *username = query.column_string(0); VLOG(1) << "Found service token for:" << *username << " @ " << service_name << " returning: " << *service_token; return true; } VLOG(1) << "Couldn't find service token for " << service_name; return false; } } // namespace browser_sync
34.253333
79
0.644609
SlimKatLegacy
6f4832a47b91566139d2569ab9e05e6c03acc272
2,083
cpp
C++
Top Interview Questions/130. Surrounded Regions/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Top Interview Questions/130. Surrounded Regions/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Top Interview Questions/130. Surrounded Regions/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 130. Surrounded Regions // // Created by 边俊林 on 2019/10/20. // Copyright © 2019 Minecode.Link. All rights reserved. // #include <map> #include <set> #include <queue> #include <string> #include <stack> #include <vector> #include <cstdio> #include <numeric> #include <cstdlib> #include <utility> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // class Solution { public: void solve(vector<vector<char>>& board) { int rows = board.size(), cols = rows ? board[0].size() : 0; vector<vector<bool>> vis (rows, vector<bool> (cols, false)); queue<pair<int, int>> q; for (int i = 0; i < cols; ++i) q.emplace(0, i); for (int i = 1; i < rows; ++i) q.emplace(i, cols-1); for (int i = cols-2; i >= 0; --i) q.emplace(rows-1, i); for (int i = rows-2; i > 0; --i) q.emplace(i, 0); int dir[5] = {0, 1, 0, -1, 0}; while (q.size()) { auto pir = q.front(); q.pop(); int row = pir.first, col = pir.second; if (vis[row][col] || board[row][col] == 'X') continue; vis[row][col] = true; for (int i = 0; i < 4; ++i) { int tor = row + dir[i]; int toc = col + dir[i+1]; if (tor>=0 && tor<rows && toc>=0 && toc<cols && !vis[tor][toc] && board[tor][toc] == 'O') q.emplace(tor, toc); } } for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (board[i][j] == 'O' && !vis[i][j]) board[i][j] = 'X'; } } } }; int main() { Solution sol = Solution(); vector<string> strs = { // "XXXX", "XOOX", "XXOX", "XOXX" // "O" "OXO", "XOX", "OXO" }; vector<vector<char>> mat; for (auto& str: strs) mat.push_back(vector<char>(str.begin(), str.end())); sol.solve(mat); cout << mat.size() << endl; return 0; }
26.367089
68
0.473836
Minecodecraft
6f4860860d3892964a0adf854adff6219f3b37ca
1,733
hpp
C++
bsengine/src/bstorm/mesh.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/mesh.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/mesh.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
#pragma once #include <bstorm/cache_store.hpp> #include <vector> #include <memory> #include <unordered_map> #include <d3dx9.h> namespace bstorm { struct MeshVertex { MeshVertex() : x(0), y(0), z(0), nx(0), ny(0), nz(0), u(0), v(0) {} MeshVertex(float x, float y, float z, float nx, float ny, float nz, float u, float v) : x(x), y(y), z(z), nx(nx), ny(ny), nz(nz), u(u), v(v) {} float x, y, z; float nx, ny, nz; float u, v; static constexpr DWORD Format = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1; }; class Texture; struct MeshMaterial { MeshMaterial(float r, float g, float b, float a, float dif, float amb, float emi, const std::shared_ptr<Texture>& texture) : col({ r, g, b, a }), dif(dif), amb(amb), emi(emi), texture(texture) { } struct { float r; float g; float b; float a; } col; float dif; float amb; float emi; std::vector<MeshVertex> vertices; std::shared_ptr<Texture> texture; }; class TextureStore; class FileLoader; class Mesh { public: Mesh(const std::wstring& path, const std::shared_ptr<TextureStore>& textureStore, const std::shared_ptr<FileLoader>& fileLoader); ~Mesh(); std::vector<MeshMaterial> materials; const std::wstring& GetPath() const { return path_; } private: std::wstring path_; }; class MeshStore { public: MeshStore(const std::shared_ptr<TextureStore>& textureStore, const std::shared_ptr<FileLoader>& fileLoader); const std::shared_ptr<Mesh>& Load(const std::wstring& path); void RemoveUnusedMesh(); private: std::shared_ptr<TextureStore> textureStore_; std::shared_ptr<FileLoader> fileLoader_; CacheStore<std::wstring, Mesh> cacheStore_; }; }
25.865672
147
0.651471
At-sushi
6f4b2016ad7ae6eb186aaa70fa1f31b8e9db2bb9
582
cpp
C++
src/resources/pattern_store.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/resources/pattern_store.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/resources/pattern_store.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
/* * TS Elements * Copyright 2015-2018 M. Newhouse * Released under the MIT license. */ #include "pattern_store.hpp" #include "pattern.hpp" namespace ts { namespace resources { Pattern& PatternStore::load_from_file(const std::string& file_name) { auto it = loaded_patterns_.find(file_name); if (it != loaded_patterns_.end()) { return it->second; } auto pattern = load_pattern(file_name); auto result = loaded_patterns_.insert(std::make_pair(file_name, std::move(pattern))); return result.first->second; } } }
20.068966
91
0.654639
mnewhouse
6f4c3ad56bda5cc867130af27b5df9949f2f502e
25,884
cpp
C++
amara/amara_uiBox.cpp
BigBossErndog/Amara-RPG
0a95a35fcddd69775a7ca7b34f3f23be9eb77178
[ "MIT" ]
null
null
null
amara/amara_uiBox.cpp
BigBossErndog/Amara-RPG
0a95a35fcddd69775a7ca7b34f3f23be9eb77178
[ "MIT" ]
null
null
null
amara/amara_uiBox.cpp
BigBossErndog/Amara-RPG
0a95a35fcddd69775a7ca7b34f3f23be9eb77178
[ "MIT" ]
null
null
null
#pragma once #ifndef AMARA_UIBOX #define AMARA_UIBOX #include "amara.h" namespace Amara { class UIBox: public Amara::Actor { public: SDL_Renderer* gRenderer = nullptr; SDL_Texture* canvas = nullptr; Amara::ImageTexture* texture = nullptr; std::string textureKey; SDL_Rect viewport; SDL_Rect srcRect; SDL_FRect destRect; SDL_FPoint origin; bool pixelLocked = false; SDL_BlendMode blendMode = SDL_BLENDMODE_BLEND; float recWidth = -1; float recHeight = -1; int width = 0; int height = 0; int minWidth = 0; int minHeight = 0; int openWidth = 0; int openHeight = 0; bool lockOpen = false; int openSpeedX = 0; int openSpeedY = 0; int closeSpeedX = 0; int closeSpeedY = 0; int boxTextureWidth = 0; int boxTextureHeight = 0; int imageWidth = 0; int imageHeight = 0; int partitionTop = 0; int partitionBottom = 0; int partitionLeft = 0; int partitionRight = 0; int frame = 0; float originX = 0; float originY = 0; Amara::Alignment boxHorizontalAlignment = ALIGN_CENTER; Amara::Alignment boxVerticalAlignment = ALIGN_CENTER; Amara::StateManager* copySm = nullptr; Amara::StateManager mySm; bool keepOpen = false; Entity* content = nullptr; UIBox() {} UIBox(Amara::StateManager* gsm) { copyStateManager(gsm); setVisible(false); } UIBox(float gx, float gy, int gw, int gh, std::string gTextureKey): UIBox() { x = gx; y = gy; width = gw; height = gh; openWidth = width; openHeight = height; textureKey = gTextureKey; } UIBox(int gw, int gh, std::string gTextureKey): UIBox(0, 0, gw, gh, gTextureKey) {} virtual void init(Amara::GameProperties* gameProperties, Amara::Scene* givenScene, Amara::Entity* givenParent) { properties = gameProperties; load = properties->loader; gRenderer = properties->gRenderer; if (!textureKey.empty()) { setTexture(textureKey); } setSize(width, height); Amara::Actor::init(gameProperties, givenScene, givenParent); entityType = "uiBox"; } virtual void configure(nlohmann::json config) { Amara::Actor::configure(config); if (config.find("width") != config.end()) { width = config["width"]; openWidth = width; } if (config.find("height") != config.end()) { height = config["height"]; openHeight = height; } if (config.find("xFromRight") != config.end()) { int xFromRight = config["xFromRight"]; x = scene->mainCamera->width - width - xFromRight; } if (config.find("yFromBottom") != config.end()) { int yFromBottom = config["yFromBottom"]; y = scene->mainCamera->height - height - yFromBottom; } if (config.find("relativeXFromRight") != config.end()) { float relativeX = config["relativeXFromRight"]; x = scene->mainCamera->width - scene->mainCamera->width*relativeX - width; } if (config.find("relativeYFromBottom") != config.end()) { float relativeY = config["relativeYFromBottom"]; y = scene->mainCamera->height - scene->mainCamera->height*relativeY - height; } if (config.find("relativeXFromCenter") != config.end()) { float relativeX = config["relativeXFromCenter"]; x = scene->mainCamera->width/2.0 + scene->mainCamera->width*relativeX/2.0 - width/2.0; } if (config.find("relativeYFromCenter") != config.end()) { float relativeY = config["relativeYFromCenter"]; y = scene->mainCamera->height/2.0 + scene->mainCamera->height*relativeY/2.0 - height/2.0; } if (config.find("minWidth") != config.end()) { minWidth = config["minWidth"]; } if (config.find("minHeight") != config.end()) { minHeight = config["minHeight"]; } if (config.find("texture") != config.end()) { setTexture(config["texture"]); } if (config.find("openSpeedX") != config.end()) { openSpeedX = config["openSpeedX"]; } if (config.find("openSpeedY") != config.end()) { openSpeedY = config["openSpeedY"]; } if (config.find("closeSpeedX") != config.end()) { closeSpeedX = config["closeSpeedX"]; } if (config.find("closeSpeedY") != config.end()) { closeSpeedY = config["closeSpeedY"]; } if (config.find("openCloseSpeedX") != config.end()) { openSpeedX = config["openCloseSpeedX"]; closeSpeedX = config["openCloseSpeedX"]; } if (config.find("openCloseSpeedY") != config.end()) { openSpeedY = config["openCloseSpeedY"]; closeSpeedY = config["openCloseSpeedY"]; } if (config.find("openCloseSpeed") != config.end()) { setOpenCloseSpeed(config["openCloseSpeed"], config["openCloseSpeed"]); } if (config.find("fixedWithinBounds") != config.end() && config["fixedWithinBounds"]) { if (x < 0) x = 0; if (y < 0) y = 0; if (x + width > scene->mainCamera->width) { x = scene->mainCamera->width - width; } if (y + height > scene->mainCamera->height) { y = scene->mainCamera->height - height; } } if (config.find("partitionTop") != config.end()) { partitionTop = config["partitionTop"]; } if (config.find("partitionBottom") != config.end()) { partitionBottom = config["partitionBottom"]; } if (config.find("partitionLeft") != config.end()) { partitionLeft = config["partitionLeft"]; } if (config.find("partitionRight") != config.end()) { partitionRight = config["partitionRight"]; } if (config.find("boxHorizontalAlignment") != config.end()) { boxHorizontalAlignment = config["boxHorizontalAlignment"]; } if (config.find("boxVerticalAlignment") != config.end()) { boxVerticalAlignment = config["boxVerticalAlignment"]; } setOpenSpeed(openSpeedX, openSpeedY); setCloseSpeed(closeSpeedX, closeSpeedY); } virtual void drawBoxPart(int part) { bool skipDrawing = false; int partX = 0, partY = 0, partWidth = 0, partHeight = 0; float horizontalAlignmentFactor = 0.5; float verticalAlignmentFactor = 0.5; switch (boxHorizontalAlignment) { case ALIGN_LEFT: horizontalAlignmentFactor = 0; break; case ALIGN_RIGHT: horizontalAlignmentFactor = 1; break; } switch(boxVerticalAlignment) { case ALIGN_TOP: verticalAlignmentFactor = 0; break; case ALIGN_BOTTOM: verticalAlignmentFactor = 1; break; } switch (part % 3) { case 0: partX = 0; partWidth = partitionLeft; destRect.x = (width - openWidth)*horizontalAlignmentFactor; destRect.w = partWidth; break; case 1: partX = partitionLeft; partWidth = boxTextureWidth - partitionLeft - partitionRight; destRect.x = (width - openWidth)*horizontalAlignmentFactor + partitionLeft; destRect.w = openWidth - partitionLeft - partitionRight; break; case 2: partX = boxTextureWidth - partitionRight; partWidth = partitionRight; destRect.x = (width - openWidth)*horizontalAlignmentFactor + openWidth - partitionRight; destRect.w = partWidth; break; } switch ((int)floor(part/(float)3)) { case 0: partY = 0; partHeight = partitionTop; destRect.y = (height - openHeight)*verticalAlignmentFactor; destRect.h = partHeight; break; case 1: partY = partitionTop; partHeight = boxTextureHeight - partitionTop - partitionBottom; destRect.y = (height - openHeight)*verticalAlignmentFactor + partitionTop; destRect.h = openHeight - partitionTop - partitionBottom; break; case 2: partY = boxTextureHeight - partitionBottom; partHeight = partitionBottom; destRect.y = (height - openHeight)*verticalAlignmentFactor + openHeight - partitionBottom; destRect.h = partHeight; break; } if (destRect.w <= 0) skipDrawing = true; if (destRect.h <= 0) skipDrawing = true; if (!skipDrawing) { if (texture != nullptr) { SDL_Texture* tx = (SDL_Texture*)texture->asset; switch (texture->type) { case IMAGE: frame = 0; srcRect.x = partX; srcRect.y = partY; srcRect.w = partWidth; srcRect.h = partHeight; break; case SPRITESHEET: Amara::Spritesheet* spr = (Amara::Spritesheet*)texture; int maxFrame = ((texture->width / spr->frameWidth) * (texture->height / spr->frameHeight)); frame = frame % maxFrame; srcRect.x = (frame % (texture->width / spr->frameWidth)) * spr->frameWidth + partX; srcRect.y = floor(frame / (texture->width / spr->frameWidth)) * spr->frameHeight + partY; srcRect.w = partWidth; srcRect.h = partHeight; break; } SDL_RenderCopyF( gRenderer, (SDL_Texture*)(texture->asset), &srcRect, &destRect ); } } } virtual void draw(int vx, int vy, int vw, int vh) override { if (!isVisible) return; if (width < minWidth) width = minWidth; if (height < minHeight) height = minHeight; if (recWidth != width || recHeight != height) { recWidth = width; recHeight = height; if (openWidth > width) openWidth = width; if (openHeight > height) openHeight = height; createNewCanvasTexture(); } if (lockOpen) { openWidth = width; openHeight = height; } SDL_Texture* recTarget = SDL_GetRenderTarget(properties->gRenderer); SDL_SetRenderTarget(properties->gRenderer, canvas); SDL_SetTextureBlendMode(canvas, SDL_BLENDMODE_BLEND); SDL_SetTextureAlphaMod(canvas, 255); SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 0); SDL_RenderClear(gRenderer); SDL_RenderSetViewport(properties->gRenderer, NULL); for (int i = 0; i < 9; i++) { drawBoxPart(i); } SDL_SetRenderTarget(properties->gRenderer, recTarget); bool skipDrawing = false; if (alpha < 0) alpha = 0; if (alpha > 1) alpha = 1; viewport.x = vx; viewport.y = vy; viewport.w = vw; viewport.h = vh; SDL_RenderSetViewport(properties->gRenderer, &viewport); float nzoomX = 1 + (properties->zoomX-1)*zoomFactorX*properties->zoomFactorX; float nzoomY = 1 + (properties->zoomY-1)*zoomFactorY*properties->zoomFactorY; destRect.x = ((x*scaleX - properties->scrollX*scrollFactorX + properties->offsetX - (originX * width * scaleX)) * nzoomX); destRect.y = ((y*scaleY - properties->scrollY*scrollFactorY + properties->offsetY - (originY * height * scaleY)) * nzoomY); destRect.w = ((width * scaleX) * nzoomX); destRect.h = ((height * scaleY) * nzoomY); if (pixelLocked) { destRect.x = floor(destRect.x); destRect.y = floor(destRect.y); destRect.w = ceil(destRect.w); destRect.h = ceil(destRect.h); } origin.x = destRect.w * originX; origin.y = destRect.h * originY; int hx, hy, hw, hh = 0; hw = destRect.w; hh = destRect.h; if (destRect.x + destRect.w <= 0) skipDrawing = true; if (destRect.y + destRect.h <= 0) skipDrawing = true; if (destRect.x >= vw) skipDrawing = true; if (destRect.y >= vh) skipDrawing = true; if (destRect.w <= 0) skipDrawing = true; if (destRect.h <= 0) skipDrawing = true; if (!skipDrawing) { if (destRect.x >= 0) { hx = destRect.x + vx; } else { hw -= -(destRect.x); hx = vx; } if (destRect.y >= 0) { hy = destRect.y + vy; } else { hh -= -(destRect.y); hy = vy; } if (hx + hw > vx + vw) hw = ((vx + vw) - hx); if (hy + hh > vy + vh) hh = ((vy + vh) - hy); checkForHover(hx, hy, hw, hh); if (canvas != nullptr) { SDL_SetTextureBlendMode(canvas, blendMode); SDL_SetTextureAlphaMod(canvas, alpha * properties->alpha * 255); SDL_RenderCopyExF( properties->gRenderer, canvas, NULL, &destRect, angle + properties->angle, &origin, SDL_FLIP_NONE ); } } if (openWidth == width && openHeight == height) { Amara::Entity::draw(vx, vy, vw, vh); } } void createNewCanvasTexture() { if (canvas != nullptr) { SDL_DestroyTexture(canvas); } canvas = SDL_CreateTexture( properties->gRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, floor(width), floor(height) ); } bool setTexture(std::string gTextureKey) { if (texture) removeTexture(); if (load == nullptr || properties == nullptr) { textureKey = gTextureKey; return true; } texture = (Amara::ImageTexture*)(load->get(gTextureKey)); if (texture != nullptr) { textureKey = texture->key; if (texture->type == SPRITESHEET) { boxTextureWidth = ((Amara::Spritesheet*)texture)->frameWidth; boxTextureHeight = ((Amara::Spritesheet*)texture)->frameHeight; } else { boxTextureWidth = texture->width; boxTextureHeight = texture->height; } imageWidth = boxTextureWidth; imageHeight = boxTextureHeight; partitionLeft = imageWidth/3.0; partitionRight = imageWidth/3.0; partitionTop = imageHeight/3.0; partitionBottom = imageHeight/3.0; return true; } else { std::cout << "Texture with key: \"" << gTextureKey << "\" was not found." << std::endl; } return false; } bool removeTexture() { textureKey.clear(); if (texture && texture->temp) delete texture; texture = nullptr; } void setSize(int nw, int nh) { width = nw; height = nh; } void setOpenSize(int nw, int nh) { openWidth = nw; openHeight = nh; if (openWidth > width) openWidth = width; if (openHeight > height) openHeight = height; if (openWidth < minWidth) openWidth = minWidth; if (openHeight < minHeight) openHeight = minHeight; } void changeOpenSize(int gx, int gy) { setOpenSize(openWidth + gx, openHeight + gy); } void setOrigin(float gx, float gy) { originX = gx; originY = gy; } void setOrigin(float gi) { setOrigin(gi, gi); } void setOriginPosition(float gx, float gy) { originX = gx/width; originY = gy/height; } void setOriginPosition(float g) { setOriginPosition(g, g); } void copyStateManager(Amara::StateManager* gsm) { copySm = gsm; } void copyStateManager(Amara::StateManager& gsm) { copySm = &gsm; } Amara::StateManager& checkSm() { if (copySm != nullptr) { return *copySm; } else { return mySm; } } virtual bool show() { Amara::StateManager& sm = checkSm(); if (sm.once()) { setVisible(true); return true; } return false; } virtual bool hide() { Amara::StateManager& sm = checkSm(); if (sm.once()) { setVisible(false); return true; } return false; } virtual void onOpen() {} virtual void onClose() {} virtual bool open() { Amara::StateManager& sm = checkSm(); bool toReturn = false; if (sm.once()) { if (!keepOpen) { resetOpenSize(); } } if (show()) { toReturn = true; } if (sm.evt()) { bool complete = true; if (openSpeedX > 0) { openWidth += openSpeedX; if (openWidth >= width) { openWidth = width; } else { complete = false; } } if (openSpeedY > 0) { openHeight += openSpeedY; if (openHeight >= height) { openHeight = height; } else { complete = false; } } if (complete) { keepOpen = true; sm.nextEvt(); } toReturn = true; } if (sm.once()) { if (content) content->setVisible(true); onOpen(); toReturn = true; } return toReturn; } virtual bool close() { Amara::StateManager& sm = checkSm(); bool toReturn = false; if (sm.once()) { if (content) content->setVisible(false); onClose(); toReturn = true; } if (sm.evt()) { bool complete = true; if (closeSpeedX > 0) { openWidth -= closeSpeedX; if (openWidth <= minWidth) { openWidth = minWidth; } else { complete = false; } } if (closeSpeedY > 0) { openHeight -= closeSpeedY; if (openHeight <= minHeight) { openHeight = minHeight; } else { complete = false; } } if (complete) { keepOpen = false; sm.nextEvt(); } toReturn = true; } if (hide()) { toReturn = true; } return toReturn; } void setOpenSpeed(int gx, int gy) { openSpeedX = gx; openSpeedY = gy; if (openSpeedX < 0) openSpeedX = 0; if (openSpeedY < 0) openSpeedY = 0; resetOpenSize(); lockOpen = false; } void setOpenSpeed(int gy) { setOpenSpeed(0, gy); } void setOpenSpeed() { setOpenSpeed(0); } void setCloseSpeed(int gx, int gy) { closeSpeedX = gx; closeSpeedY = gy; if (closeSpeedX < 0) closeSpeedX = 0; if (closeSpeedY < 0) closeSpeedY = 0; if (openWidth < minWidth) openWidth = minWidth; if (openHeight < minHeight) openHeight = minHeight; lockOpen = false; } void setCloseSpeed(int gy) { setCloseSpeed(0, gy); } void setCloseSpeed() { setCloseSpeed(0); } void setOpenCloseSpeed(int gx, int gy) { setOpenSpeed(gx, gy); setCloseSpeed(gx, gy); } void setOpenCloseSpeed(int gy) { setOpenCloseSpeed(0, gy); } void setOpenCloseSpeed() { setOpenCloseSpeed(0); } void resetOpenSize() { if (openSpeedX > 0) setOpenSize(0, openHeight); if (openSpeedY > 0) setOpenSize(openWidth, 0); } ~UIBox() { SDL_DestroyTexture(canvas); } }; class UIBox_Open: public Script { public: UIBox* box; UIBoxOpen() {} void prepare() { box = (UIBox*)parent; box->copyStateManager(this); } void script() { start(); box->open(); finishEvt(); } }; class UIBox_Close: public Script { public: UIBox* box; UIBoxOpen() {} void prepare() { box = (UIBox*)parent; box->copyStateManager(this); } void script() { start(); box->close(); finishEvt(); } }; } #endif
35.264305
139
0.42478
BigBossErndog
6f4d3fc0b0beb8d9cdded7f3b25a283b0cc65d00
5,923
cpp
C++
tests/knnshow.cpp
HIPERT-SRL/libnabo
b3864c8ecab86932e27bd4d463977bfa4e3dc584
[ "BSD-3-Clause" ]
null
null
null
tests/knnshow.cpp
HIPERT-SRL/libnabo
b3864c8ecab86932e27bd4d463977bfa4e3dc584
[ "BSD-3-Clause" ]
null
null
null
tests/knnshow.cpp
HIPERT-SRL/libnabo
b3864c8ecab86932e27bd4d463977bfa4e3dc584
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010--2011, Stephane Magnenat, ASL, ETHZ, Switzerland You can contact the author at <stephane at magnenat dot net> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ETH-ASL 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 "nabo/nabo.h" #include <iostream> #include <fstream> #include <stdexcept> using namespace std; using namespace Nabo; template<typename T> typename NearestNeighbourSearch<T>::Matrix load(const char *fileName) { typedef typename NearestNeighbourSearch<T>::Matrix Matrix; ifstream ifs(fileName); if (!ifs.good()) throw runtime_error(string("Cannot open file ") + fileName); vector<T> data; int dim(0); bool firstLine(true); while (!ifs.eof()) { char line[1024]; ifs.getline(line, sizeof(line)); line[sizeof(line)-1] = 0; char *token = strtok(line, " \t,;"); while (token) { if (firstLine) ++dim; data.push_back(atof(token)); //cout << atof(token) << " "; token = strtok(NULL, " \t,;"); // FIXME: non reentrant, use strtok_r } firstLine = false; } return Matrix::Map(&data[0], dim, data.size() / dim); } template<typename T> void dumpCoordinateForSVG(const typename NearestNeighbourSearch<T>::Vector coord, const float zoom = 1, const float ptSize = 1, const char* style = "stroke=\"black\" fill=\"red\"") { if (coord.size() == 2) cout << "<circle cx=\"" << zoom*coord(0) << "\" cy=\"" << zoom*coord(1) << "\" r=\"" << ptSize << "\" stroke-width=\"" << 0.2 * ptSize << "\" " << style << "/>" << endl; else assert(false); } int main(int argc, char* argv[]) { typedef Nabo::NearestNeighbourSearch<float>::Matrix Matrix; typedef Nabo::NearestNeighbourSearch<float>::Vector Vector; typedef Nabo::NearestNeighbourSearch<float>::Index Index; typedef Nabo::NearestNeighbourSearch<float>::Indexes Indexes; typedef Nabo::BruteForceSearch<float> BFSF; typedef Nabo::KDTree<float> KDTF; if (argc != 2) { cerr << "Usage " << argv[0] << " DATA" << endl; return 1; } Matrix d(load<float>(argv[1])); BFSF bfs(d); KDTF kdt(d); const Index K(10); // uncomment to compare KDTree with brute force search if (K >= d.size()) return 2; const int itCount(100); for (int i = 0; i < itCount; ++i) { //Vector q(bfs.minBound.size()); //for (int i = 0; i < q.size(); ++i) // q(i) = bfs.minBound(i) + float(rand()) * (bfs.maxBound(i) - bfs.minBound(i)) / float(RAND_MAX); Vector q(d.col(rand() % d.cols())); q.cwise() += 0.01; //cerr << "bfs:\n"; Indexes indexes_bf(bfs.knn(q, K, false)); //cerr << "kdt:\n"; Indexes indexes_kdtree(kdt.knn(q, K, false)); //cout << indexes_bf.size() << " " << indexes_kdtree.size() << " " << K << endl; if (ndexes_bf.size() != indexes_kdtree.size()) return 2; assert(indexes_bf.size() == indexes_kdtree.size()); assert(indexes_bf.size() == K); //cerr << "\nquery:\n" << q << "\n\n"; for (size_t j = 0; j < K; ++j) { Vector pbf(d.col(indexes_bf[j])); Vector pkdtree(d.col(indexes_kdtree[j])); //cerr << "index " << j << ": " << indexes_bf[j] << ", " << indexes_kdtree[j] << "\n"; //cerr << "point " << j << ": " << "\nbf:\n" << pbf << "\nkdtree:\n" << pkdtree << "\n\n"; assert(indexes_bf[j] == indexes_kdtree[j]); assert(dist2(pbf, pkdtree) < numeric_limits<float>::epsilon()); } } cerr << "stats kdtree: " << kdt.getStatistics().totalVisitCount << " on " << itCount * d.cols() << " (" << double(100 * kdt.getStatistics().totalVisitCount) / double(itCount * d.cols()) << " %" << ")" << endl; /* // uncomment to randomly get a point and find its minimum cout << "<?xml version=\"1.0\" standalone=\"no\"?>" << endl; cout << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" << endl; cout << "<svg width=\"100%\" height=\"100%\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">" << endl; srand(time(0)); for (int i = 0; i < d.cols(); ++i) dumpCoordinateForSVG<float>(d.col(i), 100, 1); Vector q(bfs.minBound.size()); for (int i = 0; i < q.size(); ++i) q(i) = bfs.minBound(i) + float(rand()) * (bfs.maxBound(i) - bfs.minBound(i)) / float(RAND_MAX); Indexes indexes_bf(bfs.knn(q, K, false)); for (size_t i = 0; i < K; ++i) dumpCoordinateForSVG<float>(d.col(indexes_bf[i]), 100, 1, "stroke=\"black\" fill=\"green\""); dumpCoordinateForSVG<float>(q, 100, 1, "stroke=\"black\" fill=\"blue\""); cout << "</svg>" << endl; */ //cout << "Average KDTree visit count: " << double(totKDTreeVisitCount) * 100. / double(itCount * d.cols()) << " %" << endl; return 0; }
35.467066
180
0.650346
HIPERT-SRL
6f4fe5bc42841fbf76bea2508a67be5874d8abff
836
cpp
C++
application/main.cpp
Italo1994/SimuladorMips
075bfd9e1bc6e47f8c37f14208afe450bfad46b1
[ "MIT" ]
null
null
null
application/main.cpp
Italo1994/SimuladorMips
075bfd9e1bc6e47f8c37f14208afe450bfad46b1
[ "MIT" ]
null
null
null
application/main.cpp
Italo1994/SimuladorMips
075bfd9e1bc6e47f8c37f14208afe450bfad46b1
[ "MIT" ]
null
null
null
#include "conjuntoInstrucoes.h" #include "operador.h" #include "registrador.h" #include "tokenizacao.h" #include "pipeline.h" #include "dependencias.h" //#include "tela.h" #include <iostream> #include <string> #include <vector> using namespace std; int main() { //Simulador simulador; //simulador.criarInstrucoes(); //mostrarNaTela(9); //Registrador registrador[32]; //Operador operador[7]; vector<vector<string> > matrizInstrucoes; //criarRegistradores(registrador); //mostrarRegistradores(registrador); //criarOperadores(operador); //mostrarOperadores(operador); cout << endl; inicializarInstrucoes(&matrizInstrucoes, 3); //mostrarInstrucoes(matrizInstrucoes); //pipeline(2, matrizInstrucoes, 1); verificarDependencias(matrizInstrucoes, 3); //verificarDependencias(matrizInstrucoes, 2); return 0; }
17.061224
46
0.741627
Italo1994
6f568b8959b2d624e7df9210b2fa793e83de6fd0
11,250
hpp
C++
public/anton/algorithm.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
null
null
null
public/anton/algorithm.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
null
null
null
public/anton/algorithm.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
1
2020-12-15T13:51:38.000Z
2020-12-15T13:51:38.000Z
#pragma once #include <anton/algorithm/sort.hpp> #include <anton/array.hpp> #include <anton/iterators.hpp> #include <anton/math/math.hpp> #include <anton/memory.hpp> #include <anton/pair.hpp> #include <anton/swap.hpp> namespace anton { // fill_with_consecutive // Fills range [first, last[ with consecutive values starting at value. // template<typename Forward_Iterator, typename T> void fill_with_consecutive(Forward_Iterator first, Forward_Iterator last, T value) { for(; first != last; ++first, ++value) { *first = value; } } // find // Linearily searches the range [first, last[. // // Returns: The iterator to the first element in the range [first, last[ that satisfies // the condition *iterator == value or last if no such iterator is found. // // Complexity: At most 'last - first' comparisons. // template<typename Input_Iterator, typename T> [[nodiscard]] Input_Iterator find(Input_Iterator first, Input_Iterator last, T const& value) { while(first != last && *first != value) { ++first; } return first; } // find_if // Linearily searches the range [first, last[. // // Returns: The iterator to the first element in the range [first, last[ that satisfies // the condition predicate(*iterator) == true or last if no such iterator is found. // // Complexity: At most 'last - first' applications of the predicate. // template<typename Input_Iterator, typename Predicate> [[nodiscard]] Input_Iterator find_if(Input_Iterator first, Input_Iterator last, Predicate predicate) { while(first != last && !predicate(*first)) { ++first; } return first; } template<typename Input_Iterator, typename Predicate> [[nodiscard]] bool any_of(Input_Iterator first, Input_Iterator last, Predicate predicate) { for(; first != last; ++first) { if(predicate(*first)) { return true; } } return false; } // rotate_left // Performs left rotation on the range by swapping elements so that middle becomes the first element. // [first, last[ must be a valid range, middle must be within [first, last[. // // This function works on forward iterators meaning it supports lists, however you can get much better // performance by using splice operations instead (O(1) instead of O(n)). // // Returns: Position of the first element after rotate. // // Complexity: At most last - first swaps. // template<typename Forward_Iterator> Forward_Iterator rotate_left(Forward_Iterator first, Forward_Iterator middle, Forward_Iterator last) { using anton::swap; Forward_Iterator i = middle; while(true) { swap(*first, *i); ++first; ++i; if(i == last) { break; } if(first == middle) { middle = i; } } Forward_Iterator r = first; if(first != middle) { i = middle; while(true) { swap(*first, *i); ++first; ++i; if(i == last) { if(first == middle) { break; } i = middle; } else if(first == middle) { middle = i; } } } return r; } // unique // Eliminates all except the first element from every consecutive group of equivalent elements from // the range [first, last[ and returns a past-the-end iterator for the new logical end of the range. // template<typename Forward_Iterator, typename Predicate> Forward_Iterator unique(Forward_Iterator first, Forward_Iterator last, Predicate predicate) { if(first == last) { return last; } // Find first group that consists of > 2 duplicates. Forward_Iterator next = first; ++next; while(next != last && !predicate(*first, *next)) { ++first; ++next; } if(next != last) { for(; next != last; ++next) { if(!predicate(*first, *next)) { ++first; *first = ANTON_MOV(*next); } } return ++first; } else { return last; } } // unique // Eliminates all except the first element from every consecutive group of equivalent elements from // the range [first, last[ and returns a past-the-end iterator for the new logical end of the range. // template<typename Forward_Iterator> Forward_Iterator unique(Forward_Iterator first, Forward_Iterator last) { using value_type = typename Iterator_Traits<Forward_Iterator>::value_type; return unique(first, last, [](value_type const& lhs, value_type const& rhs) { return lhs == rhs; }); } // set_difference // Copies elements from [first1, last1[ that are not present in [first2, last2[ to // the destination range starting at dest. // // Requires: // Both input ranges must be sorted and neither must overlap with destination range. // (*first1 < *first2) and (*first2 < *first1) must be valid expressions. // // Returns: The end of the destination range. // // Complexity: TODO // template<typename Input_Iterator1, typename Input_Iterator2, typename Output_Iterator> Output_Iterator set_difference(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Input_Iterator2 last2, Output_Iterator dest) { while(first1 != last1 && first2 != last2) { if(*first1 < *first2) { *dest = *first1; ++dest; ++first1; } else if(*first2 < *first1) { ++first2; } else { ++first1; ++first2; } } for(; first1 != last1; ++first1, ++dest) { *dest = *first1; } return dest; } // set_difference overload with custom comparison predicate which enforces strict ordering (<). // template<typename Input_Iterator1, typename Input_Iterator2, typename Output_Iterator, typename Compare> Output_Iterator set_difference(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Input_Iterator2 last2, Output_Iterator dest, Compare compare) { while(first1 != last1 && first2 != last2) { if(compare(*first1, *first2)) { *dest = *first1; ++dest; ++first1; } else if(compare(*first2, *first1)) { ++first2; } else { ++first1; ++first2; } } for(; first1 != last1; ++first1, ++dest) { *dest = *first1; } return dest; } // mismatch // Finds the first mismatching pair of elements in the two ranges // defined by [first1, last1[ and [first2, first2 + (last1 - first1)[. // The elements are compared using operator==. // // Parameters: // first1, last1 - first range of elements. // first2, last2 - seconds range of elements. // p - predicate that returns true when the elements should be treated as equal. // The signature should be equivalent to bool(Type1 const&, Type2 const&) // // Returns: // Pair of iterators to the first elements that are not equal. // If no mismatches are found, one or both iterators are the end iterators. // template<typename Input_Iterator1, typename Input_Iterator2> Pair<Input_Iterator1, Input_Iterator2> mismatch(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2) { while(first1 != last1 && *first1 == *first2) { ++first1; ++first2; } return {first1, first2}; } // mismatch // Finds the first mismatching pair of elements in the two ranges // defined by [first1, last1[ and [first2, first2 + (last1 - first1)[. // The elements are compared using the predicate p. // // Parameters: // first1, last1 - first range of elements. // first2, last2 - seconds range of elements. // p - predicate that returns true when the elements should be treated as equal. // The signature should be equivalent to bool(Type1 const&, Type2 const&) // // Returns: // Pair of iterators to the first elements that are not equal. // If no mismatches are found, one or both iterators are the end iterators. // template<typename Input_Iterator1, typename Input_Iterator2, typename Predicate> Pair<Input_Iterator1, Input_Iterator2> mismatch(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Predicate p) { while(first1 != last1 && p(*first1, *first2)) { ++first1; ++first2; } return {first1, first2}; } // mismatch // Finds the first mismatching pair of elements in the two ranges defined by [first1, last1[ and [first2, last2[. // The elements are compared using operator==. // // Parameters: // first1, last1 - first range of elements. // first2, last2 - seconds range of elements. // // Returns: // Pair of iterators to the first elements that are not equal. // If no mismatches are found, one or both iterators are the end iterators. // template<typename Input_Iterator1, typename Input_Iterator2> Pair<Input_Iterator1, Input_Iterator2> mismatch(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Input_Iterator2 last2) { while(first1 != last1 && first2 != last2 && *first1 == *first2) { ++first1; ++first2; } return {first1, first2}; } // mismatch // Finds the first mismatching pair of elements in the two ranges defined by [first1, last1[ and [first2, last2[. // The elements are compared using the predicate p. // // Parameters: // first1, last1 - first range of elements. // first2, last2 - seconds range of elements. // p - predicate that returns true when the elements should be treated as equal. // The signature should be equivalent to bool(Type1 const&, Type2 const&) // // Returns: // Pair of iterators to the first elements that are not equal. // If no mismatches are found, one or both iterators are the end iterators. // template<typename Input_Iterator1, typename Input_Iterator2, typename Predicate> Pair<Input_Iterator1, Input_Iterator2> mismatch(Input_Iterator1 first1, Input_Iterator1 last1, Input_Iterator2 first2, Input_Iterator2 last2, Predicate p) { while(first1 != last1 && first2 != last2 && p(*first1, *first2)) { ++first1; ++first2; } return {first1, first2}; } } // namespace anton
36.407767
160
0.594133
kociap