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
72c1e2a0e1b07c400d95eb0841381aae9b6d107c
4,264
hpp
C++
librt/include/material.hpp
julitopower/RayTracingWeekend
0b9035f596fe33b39eb8a476a729a01dfecd2a1e
[ "MIT" ]
1
2018-12-22T00:12:10.000Z
2018-12-22T00:12:10.000Z
librt/include/material.hpp
julitopower/RayTracingWeekend
0b9035f596fe33b39eb8a476a729a01dfecd2a1e
[ "MIT" ]
null
null
null
librt/include/material.hpp
julitopower/RayTracingWeekend
0b9035f596fe33b39eb8a476a729a01dfecd2a1e
[ "MIT" ]
1
2019-04-09T12:51:49.000Z
2019-04-09T12:51:49.000Z
#ifndef MATERIAL_HPP #define MATERIAL_HPP #include <map> #include <memory> #include <string> #include <vector.hpp> #include <texture.hpp> namespace rt { class Hit; class Ray; /*! * \brief Abstract representation of a material that can be associated with * a object. Material is also used to decorate a Hit. */ class Material { public: /*! * \brief Scatter an incoming Ray using Hit information, and attenuation vector * * \param ray The incoming Ray * \param hit Information about the intersection between the Ray and a Hitable * \param attenuation Vector representing the attenuation factor to be applied to each color * \param scattered Output parameter. Ray generated by the scatter calculation * \return */ virtual bool scatter(const Ray& ray, const Hit& hit, Vector3f& attenuation, Ray& scattered) const = 0; virtual Vector3f emmitted() const { return {0,0,0}; } virtual ~Material(){}; }; class Light : public Material { public: Light(const Vector3f& color) : color_{color} {} bool scatter(const Ray& ray, const Hit& rec, Vector3f& attenuation, Ray& scattered) const final override { return false; } Vector3f emmitted() const final override { return color_; } private: Vector3f color_; }; /*! * \brief A non reflecting material */ class Lambertian : public Material { public: /*! * \brief Construct a new Lambertian material with the given attenuation vector */ explicit Lambertian(Texture* a) : albedo_{a} {} /* * Generate a scattered Ray in a random direction. Given an intersection point a * nd a normal with unit length, the scattered ray is calculated by moving the * intersection point in the direction of the normal, for the length of the * normal, and then moving it along a unit vector in a random direction. */ bool scatter(const Ray& ray, const Hit& rec, Vector3f& attenuation, Ray& scattered) const final override; private: Texture* albedo_; }; class Metal : public Material { public: explicit Metal(const Vector3f& a) : albedo_{a}{} bool scatter(const Ray& ray, const Hit& rec, Vector3f& attenuation, Ray& scattered) const final override; private: Vector3f albedo_; }; /*! * \brief A non reflecting material */ class Dielectric : public Material { public: /*! * \brief Construct a new Lambertian material with the given attenuation vector */ explicit Dielectric(float ri) : ref_idx_{ri} {} /* * Generate a scattered Ray in a random direction. Given an intersection point a * nd a normal with unit length, the scattered ray is calculated by moving the * intersection point in the direction of the normal, for the length of the * normal, and then moving it along a unit vector in a random direction. */ bool scatter(const Ray& ray, const Hit& rec, Vector3f& attenuation, Ray& scattered) const final override; private: float ref_idx_; }; class MaterialRegistry { public: MaterialRegistry() = default; void register_lambertian(const std::string& name, Texture* attenuation); void register_metal(const std::string& name, const Vector3f& attenuation); void register_dielectric(const std::string& name, float ref_idx); void register_light(const std::string& name, const Vector3f& color); Material* get(const std::string& name); Material* generate_lambertial(rt::TextureRegistry& textures) { random_.push_back(std::make_unique<Lambertian>(textures.random_color())); return random_.back().get(); } Material* generate_metal() { auto dis = std::uniform_real_distribution<float>{0.0, 1.0}; std::random_device device; random_.push_back( std::make_unique<Metal>(rt::Vector3f{0.5f * (1 + dis(device)), 0.5f * (1 + dis(device)), 0.5f * dis(device)})); return random_.back().get(); } Material* generate_dielectric() { random_.push_back(std::make_unique<Dielectric>(1.5)); return random_.back().get(); } private: std::map<std::string, std::unique_ptr<Material>> registry_; std::vector<std::unique_ptr<Material>> random_; }; } // namespace rt #endif // MATERIAL_HPP
25.842424
94
0.681989
julitopower
72c2f39b0ea0c6fdb9d72585fcaf9b3bc39297e7
1,171
cpp
C++
Interceptor/FunctionDepth.cpp
19317362/Interceptor
a64e8283454cd70b6e16161c322dc4d85663caa9
[ "MIT" ]
20
2016-04-14T18:29:46.000Z
2022-02-17T18:00:29.000Z
Interceptor/FunctionDepth.cpp
19317362/Interceptor
a64e8283454cd70b6e16161c322dc4d85663caa9
[ "MIT" ]
null
null
null
Interceptor/FunctionDepth.cpp
19317362/Interceptor
a64e8283454cd70b6e16161c322dc4d85663caa9
[ "MIT" ]
1
2018-11-01T01:43:49.000Z
2018-11-01T01:43:49.000Z
#include "FunctionDepth.h" #include <thread> using namespace Interceptor; std::size_t FuntionDepth::operator++() { auto id = std::this_thread::get_id(); UniqueGuard guard(m_mutex); auto iter = m_function_depth.find(id); if (iter != m_function_depth.end()) { (++iter->second); return iter->second; } m_function_depth[id] = 1; return 1; } std::size_t FuntionDepth::operator--() { auto id = std::this_thread::get_id(); UniqueGuard guard(m_mutex); auto iter = m_function_depth.find(id); if (iter != m_function_depth.end()) { (--iter->second); return iter->second; } return 0; } std::size_t FuntionDepth::load(const std::thread::id &_id)const { UniqueGuard guard(m_mutex); auto iter = m_function_depth.find(_id); if (iter != m_function_depth.end()) { return (iter->second); } return 0; } std::size_t FuntionDepth::load()const { auto id = std::this_thread::get_id(); UniqueGuard guard(m_mutex); auto iter = m_function_depth.find(id); if (iter != m_function_depth.end()) { return (iter->second); } return 0; } FuntionDepth::~FuntionDepth() { UniqueGuard guard(m_mutex); }
20.54386
66
0.653288
19317362
72c5793c91c9598f1df5c9fe7dd46f1ddd55ed61
2,339
cc
C++
src/cc/libclient/utils.cc
chanwit/qfs
dc6ba65f42ba55ed7d47e8a0cbf025096304f5d1
[ "Apache-2.0" ]
null
null
null
src/cc/libclient/utils.cc
chanwit/qfs
dc6ba65f42ba55ed7d47e8a0cbf025096304f5d1
[ "Apache-2.0" ]
null
null
null
src/cc/libclient/utils.cc
chanwit/qfs
dc6ba65f42ba55ed7d47e8a0cbf025096304f5d1
[ "Apache-2.0" ]
null
null
null
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2006/08/31 // Author: Sriram Rao // Mike Ovsiannikov // // Copyright 2008-2012 Quantcast Corp. // Copyright 2006-2008 Kosmix Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // \brief Miscellaneous utility functions. // //---------------------------------------------------------------------------- #include "utils.h" #include "common/RequestParser.h" #include <sys/time.h> #include <sys/types.h> #include <sys/select.h> #include <unistd.h> namespace KFS { namespace client { void Sleep(int secs) { if (secs <= 0) { return; } struct timeval end; gettimeofday(&end, 0); end.tv_sec += secs; struct timeval tm; tm.tv_sec = secs; tm.tv_usec = 0; for(; ;) { if (select(0, 0, 0, 0, &tm) == 0) { break; } gettimeofday(&tm, 0); if (tm.tv_sec + secs + 1 < end.tv_sec || // backward clock jump end.tv_sec < tm.tv_sec || (end.tv_sec == tm.tv_sec && end.tv_usec <= tm.tv_usec + 10000)) { break; } if (end.tv_usec < tm.tv_usec) { tm.tv_sec = end.tv_sec - tm.tv_sec - 1; tm.tv_usec = 1000000 - tm.tv_usec + end.tv_usec; } else { tm.tv_sec = end.tv_sec - tm.tv_sec; tm.tv_usec = end.tv_usec - tm.tv_usec; } } } void GetTimeval(const char* s, struct timeval& tv) { const char* p = s; const char* const e = p + (p ? strlen(s) : 0); if (! p || ! DecIntParser::Parse(p, e - p, tv.tv_sec) || ! DecIntParser::Parse(p, e - p, tv.tv_usec)) { tv.tv_sec = 0; tv.tv_usec = 0; } } } }
25.988889
78
0.54254
chanwit
72c8b0e1c3c67a575cea76d95ca253c44ac1feeb
392
hpp
C++
include/cgl/map.hpp
sdragonx/cgl
d8d45d3a3930bc8f3d0851371760742fda4733b8
[ "MIT" ]
1
2020-12-30T06:35:47.000Z
2020-12-30T06:35:47.000Z
include/cgl/map.hpp
sdragonx/cgl
d8d45d3a3930bc8f3d0851371760742fda4733b8
[ "MIT" ]
null
null
null
include/cgl/map.hpp
sdragonx/cgl
d8d45d3a3930bc8f3d0851371760742fda4733b8
[ "MIT" ]
null
null
null
/* Copyright (c) 2005-2020 sdragonx (mail:sdragonx@foxmail.com) map.hpp 2018-10-20 08:57:26 */ #ifndef MAP_HPP_20181020085726 #define MAP_HPP_20181020085726 #include <cgl/std/map/cmap.hpp> #include <cgl/std/map/dual_map.hpp> #include <cgl/std/map/idmap.hpp> #include <cgl/std/map/hashmap.hpp> namespace cgl{ }//end namespace cgl #endif //MAP_HPP_20181020085726
17.818182
62
0.709184
sdragonx
72d034f5d0523280715e05e1f3aeedad78e97678
1,972
cpp
C++
src/catamorph/interpreters/variable_ordering.cpp
geisserf/lemon-dd
e7518886ce7dc5960f16d799c8ff6450ea67e7ae
[ "BSL-1.0" ]
2
2018-10-26T11:21:13.000Z
2020-06-04T11:31:03.000Z
src/catamorph/interpreters/variable_ordering.cpp
geisserf/lemon-dd
e7518886ce7dc5960f16d799c8ff6450ea67e7ae
[ "BSL-1.0" ]
10
2018-11-28T08:55:51.000Z
2018-12-04T09:15:17.000Z
src/catamorph/interpreters/variable_ordering.cpp
geisserf/lemon-dd
e7518886ce7dc5960f16d799c8ff6450ea67e7ae
[ "BSL-1.0" ]
null
null
null
#include "variable_ordering.h" #include "../../parser.h" #include "dependencies.h" #include <iomanip> #include <iostream> #include <stack> ASTNode::ASTNode() : value("{}"), topo_order(-1), variable(false) {} ASTNode::ASTNode(double value) : value(std::to_string(value)), topo_order(0), variable(false) {} ASTNode::ASTNode(const std::string &value) : value(value), topo_order(0), variable(true) {} ASTNode::ASTNode(const std::string &value, const std::vector<ASTNode> &children) : value(value), variable(false) { // Children are sorted according to their topo order this->children = children; std::sort(this->children.begin(), this->children.end(), [](const ASTNode &x, const ASTNode &y) { return x.get_topo_order() < y.get_topo_order(); }); // Last child has highest topo value if (this->children.empty()) { topo_order = 0; } else { topo_order = this->children[children.size() - 1].get_topo_order() + 1; } } Ordering VariableOrdering::get_fan_in_ordering(const Expression &expr) { size_t num_supp_vars = Dependency::dependencies(expr).size(); auto node = create_ast(expr); Ordering var_order; std::stack<ASTNode> Q; std::vector<ASTNode> children; Q.push(node); while (!Q.empty()) { ASTNode cur = Q.top(); Q.pop(); if (var_order.size() == num_supp_vars) return var_order; // Is variable root node and not already contained in var_order if (cur.is_variable() && std::find(var_order.begin(), var_order.end(), cur.get_value()) == var_order.end()) { var_order.push_back(cur.get_value()); } children = cur.get_children(); // Children are already sorted by their topo order => push on stack for (size_t i = 0; i < children.size(); ++i) { Q.push(children[i]); } } return var_order; }
29.432836
80
0.60497
geisserf
72db594e5f5b029db43a3c22f46144f096f92012
2,749
cxx
C++
Readers/DXFReader/vtkDXFBlock.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
4
2016-01-21T21:45:43.000Z
2021-07-31T19:24:09.000Z
Readers/DXFReader/vtkDXFBlock.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
null
null
null
Readers/DXFReader/vtkDXFBlock.cxx
ObjectivitySRC/PVGPlugins
5e24150262af751159d719cc810620d1770f2872
[ "BSD-2-Clause" ]
6
2015-08-31T06:21:03.000Z
2021-07-31T19:24:10.000Z
// By: Eric Daoust && Matthew Livingstone #include "vtkDXFBlock.h" #include <vtksys/ios/sstream> #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkCollection.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" vtkCxxRevisionMacro(vtkDXFBlock, "$Revision: 1 $"); vtkStandardNewMacro(vtkDXFBlock); vtkDXFBlock::vtkDXFBlock() { this->blockScale = new double[3]; this->blockScale[0] = this->blockScale[1] = this->blockScale[2] = 1.0; this->blockTransform = new double[3]; this->blockTransform[0] = this->blockTransform[1] = this->blockTransform[2] = 0.0; this->parentLayer = ""; this->drawBlock = false; this->blockPropertyValue = 0; } vtkDXFBlock::~vtkDXFBlock() { if ( this->blockScale ) { delete[] this->blockScale; } if ( this->blockTransform ) { delete[] this->blockTransform; } } void vtkDXFBlock::PrintSelf(ostream& os, vtkIndent indent) { //TODO: complete this method this->Superclass::PrintSelf(os,indent); } void vtkDXFBlock::CopyFrom(vtkDXFBlock* block) { this->name = block->getName(); // Point/Cell Data this->pointPoints->DeepCopy(block->getPointPoints()); this->pointCells->DeepCopy(block->getPointCells()); this->linePoints->DeepCopy(block->getLinePoints()); this->lineCells->DeepCopy(block->getLineCells()); this->polyLinePoints->DeepCopy(block->getPolyLinePoints()); this->polyLineCells->DeepCopy(block->getPolyLineCells()); this->lwPolyLinePoints->DeepCopy(block->getLWPolyLinePoints()); this->lwPolyLineCells->DeepCopy(block->getLWPolyLineCells()); this->surfPoints->DeepCopy(block->getSurfPoints()); this->surfCells->DeepCopy(block->getSurfCells()); this->solidPoints->DeepCopy(block->getSolidPoints()); this->solidCells->DeepCopy(block->getSolidCells()); this->arcPoints->DeepCopy(block->getArcPoints()); this->arcCells->DeepCopy(block->getArcCells()); for(int textItem = 0; textItem < block->getText()->GetNumberOfItems(); textItem++) { this->textList->AddItem(vtkPolyData::SafeDownCast(block->getText()->GetItemAsObject(textItem))); } for(int circleItem = 0; circleItem < block->getCircles()->GetNumberOfItems(); circleItem++) { this->circleList->AddItem(vtkPolyData::SafeDownCast(block->getCircles()->GetItemAsObject(circleItem))); } // Properties this->pointProps->DeepCopy(block->getPointProps()); this->lineProps->DeepCopy(block->getLineProps()); this->polyLineProps->DeepCopy(block->getPolyLineProps()); this->lwPolyLineProps->DeepCopy(block->getLWPolyLineProps()); this->surfProps->DeepCopy(block->getSurfProps()); this->solidProps->DeepCopy(block->getSolidProps()); this->arcProps->DeepCopy(block->getArcProps()); this->circleProps->DeepCopy( block->getCircleProps() ); this->textProps->DeepCopy(block->getTextProps()); }
31.965116
105
0.734085
ObjectivitySRC
72e0f706f4400101306f7b0a889f95cec8db7696
4,905
hpp
C++
libraries/ThreadAPI/include/thread/Thread.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
7
2020-12-15T14:27:02.000Z
2022-03-23T12:00:13.000Z
libraries/ThreadAPI/include/thread/Thread.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
null
null
null
libraries/ThreadAPI/include/thread/Thread.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
1
2021-01-06T14:51:51.000Z
2021-01-06T14:51:51.000Z
// Copyright 2011-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #ifndef THREADAPI_THREAD_THREAD_HPP #define THREADAPI_THREAD_THREAD_HPP #include <pthread.h> #include <csignal> #include "Sched.hpp" #include "chrono/ClockTime.hpp" namespace thread { class Thread : public api::ExecutionContext { public: enum class DetachState { joinable = PTHREAD_CREATE_JOINABLE, detached = PTHREAD_CREATE_DETACHED }; using Policy = Sched::Policy; enum class IsInherit { no = PTHREAD_EXPLICIT_SCHED, yes = PTHREAD_INHERIT_SCHED }; enum class ContentionScope { system = PTHREAD_SCOPE_SYSTEM, process = PTHREAD_SCOPE_PROCESS }; using Scope = ContentionScope; typedef void *(*function_t)(void *); class Attributes : public api::ExecutionContext { public: Attributes(); ~Attributes(); Attributes &set_stack_size(size_t value); API_NO_DISCARD int get_stack_size() const; Attributes &set_detach_state(DetachState value); Attributes& set_joinable(){ return set_detach_state(DetachState::joinable); } Attributes& set_detached(){ return set_detach_state(DetachState::detached); } API_NO_DISCARD DetachState get_detach_state() const; Attributes &set_inherit_sched(IsInherit value); API_NO_DISCARD IsInherit get_inherit_sched() const; Attributes &set_scope(ContentionScope value); API_NO_DISCARD ContentionScope get_scope() const; Attributes &set_sched_policy(Sched::Policy value); Attributes &set_sched_priority(int priority); API_NO_DISCARD Sched::Policy get_sched_policy() const; API_NO_DISCARD int get_sched_priority() const; private: friend class Thread; pthread_attr_t m_pthread_attr{}; }; class Construct { API_ACCESS_FUNDAMENTAL(Construct, function_t, function, nullptr); API_ACCESS_FUNDAMENTAL(Construct, void *, argument, nullptr); }; Thread() = default; // don't allow making copies Thread(const Thread &thread) = delete; Thread &operator=(const Thread &thread) = delete; // allow moving threads Thread &operator=(Thread &&a) noexcept { swap(std::move(a)); return *this; } Thread(Thread &&a) noexcept { swap(std::move(a)); } Thread &&move() { return std::move(*this); } explicit Thread(const Construct &options); Thread(const Attributes &attributes, const Construct &options); Thread(const Attributes &attributes, void * argument, function_t thread_function){ construct(attributes, Construct().set_argument(argument).set_function(thread_function)); } Thread(void * argument, function_t thread_function){ construct(Attributes(), Construct().set_argument(argument).set_function(thread_function)); } ~Thread(); /*! \details Gets the ID of the thread. */ API_NO_DISCARD pthread_t id() const { return m_id; } /*! \details Returns true if the thread has a valid id. * * If create() has not been called, this will return false. * If there was an error creating the thread, this will * also return false; * */ API_NO_DISCARD bool is_valid() const; enum class CancelType { deferred = PTHREAD_CANCEL_DEFERRED, asynchronous = PTHREAD_CANCEL_ASYNCHRONOUS }; static CancelType set_cancel_type(CancelType cancel_type); enum class CancelState { enable = PTHREAD_CANCEL_ENABLE, disable = PTHREAD_CANCEL_DISABLE }; Thread &set_sched_parameters(Sched::Policy policy, int priority); API_NO_DISCARD Sched::Policy get_sched_policy() const; API_NO_DISCARD int get_sched_priority() const; static CancelState set_cancel_state(CancelState cancel_state); const Thread &cancel() const; Thread &cancel() { return API_CONST_CAST_SELF(Thread, cancel); } API_NO_DISCARD bool is_running() const; API_NO_DISCARD static pthread_t self() { return pthread_self(); } const Thread &kill(int signal_number) const { API_RETURN_VALUE_IF_ERROR(*this); API_SYSTEM_CALL("", pthread_kill(id(), signal_number)); return *this; } Thread &join(void **value = nullptr); API_NO_DISCARD bool is_joinable() const { return m_state == State::joinable; } //API_NO_DISCARD const api::Error *execution_context_error() const { // return m_execution_context_error; //} private: enum class State { null = 0, completed, error, joinable, detached }; const api::Error *m_execution_context_error = nullptr; volatile State m_state = State::null; pthread_t m_id = #if defined __link {}; #else 0; #endif void swap(Thread &&a) { std::swap(m_id, a.m_id); std::swap(m_state, a.m_state); std::swap(m_execution_context_error, a.m_execution_context_error); } void construct(const Attributes & attributes, const Construct & options); static void *handle_thread(void *args); int get_sched_parameters(int &policy, int &priority) const; }; } // namespace thread #endif /* THREADAPI_THREAD_THREAD_HPP */
27.711864
94
0.723547
StratifyLabs
72e25f61669c4b09244d38b5f4db1c64e5481d38
6,226
cc
C++
chrome/updater/win/setup/uninstall.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/updater/win/setup/uninstall.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/updater/win/setup/uninstall.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 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 "chrome/updater/win/setup/uninstall.h" #include <shlobj.h> #include <windows.h> #include <memory> #include <string> #include <vector> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/cxx17_backports.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/process/launch.h" #include "base/process/process.h" #include "base/strings/stringprintf.h" #include "base/win/scoped_com_initializer.h" #include "chrome/installer/util/install_service_work_item.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/work_item_list.h" #include "chrome/updater/app/server/win/updater_idl.h" #include "chrome/updater/app/server/win/updater_internal_idl.h" #include "chrome/updater/app/server/win/updater_legacy_idl.h" #include "chrome/updater/constants.h" #include "chrome/updater/updater_scope.h" #include "chrome/updater/util.h" #include "chrome/updater/win/setup/setup_util.h" #include "chrome/updater/win/task_scheduler.h" #include "chrome/updater/win/win_constants.h" #include "chrome/updater/win/win_util.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace updater { namespace { void DeleteComServer(UpdaterScope scope, HKEY root, bool uninstall_all) { for (const CLSID& clsid : JoinVectors( GetSideBySideServers(scope), uninstall_all ? GetActiveServers(scope) : std::vector<CLSID>())) { InstallUtil::DeleteRegistryKey(root, GetComServerClsidRegistryPath(clsid), WorkItem::kWow64Default); } } void DeleteComService(bool uninstall_all) { DCHECK(::IsUserAnAdmin()); for (const GUID& appid : JoinVectors(GetSideBySideServers(UpdaterScope::kSystem), uninstall_all ? GetActiveServers(UpdaterScope::kSystem) : std::vector<CLSID>())) { InstallUtil::DeleteRegistryKey(HKEY_LOCAL_MACHINE, GetComServerAppidRegistryPath(appid), WorkItem::kWow64Default); } for (const bool is_internal_service : {true, false}) { if (!uninstall_all && !is_internal_service) continue; const std::wstring service_name = GetServiceName(is_internal_service); if (!installer::InstallServiceWorkItem::DeleteService( service_name.c_str(), UPDATER_KEY, {}, {})) { LOG(WARNING) << "DeleteService [" << service_name << "] failed."; } } } void DeleteComInterfaces(HKEY root, bool uninstall_all) { for (const IID& iid : JoinVectors( GetSideBySideInterfaces(), uninstall_all ? GetActiveInterfaces() : std::vector<IID>())) { for (const auto& reg_path : {GetComIidRegistryPath(iid), GetComTypeLibRegistryPath(iid)}) { InstallUtil::DeleteRegistryKey(root, reg_path, WorkItem::kWow64Default); } } } int RunUninstallScript(UpdaterScope scope, bool uninstall_all) { const absl::optional<base::FilePath> versioned_dir = GetVersionedDirectory(scope); if (!versioned_dir) { LOG(ERROR) << "GetVersionedDirectory failed."; return -1; } const absl::optional<base::FilePath> base_dir = GetBaseDirectory(scope); if (scope == UpdaterScope::kSystem && !base_dir) { LOG(ERROR) << "GetBaseDirectory failed."; return -1; } wchar_t cmd_path[MAX_PATH] = {0}; DWORD size = ExpandEnvironmentStrings(L"%SystemRoot%\\System32\\cmd.exe", cmd_path, base::size(cmd_path)); if (!size || size >= MAX_PATH) return -1; const base::FilePath script_path = versioned_dir->AppendASCII(kUninstallScript); std::wstring cmdline = cmd_path; base::StringAppendF( &cmdline, L" /Q /C \"\"%ls\" --dir=\"%ls\"\"", script_path.value().c_str(), (uninstall_all ? base_dir : versioned_dir)->value().c_str()); base::LaunchOptions options; options.start_hidden = true; VLOG(1) << "Running " << cmdline; base::Process process = base::LaunchProcess(cmdline, options); if (!process.IsValid()) { LOG(ERROR) << "Failed to create process " << cmdline; return -1; } return 0; } // Reverses the changes made by setup. This is a best effort uninstall: // 1. Deletes the scheduled task. // 2. Deletes the Clients and ClientState keys. // 3. Runs the uninstall script in the install directory of the updater. // The execution of this function and the script race each other but the script // loops and waits in between iterations trying to delete the install directory. // If `uninstall_all` is set to `true`, the function uninstalls both the // internal as well as the active updater. If `uninstall_all` is set to `false`, // the function uninstalls only the internal updater. int UninstallImpl(UpdaterScope scope, bool uninstall_all) { VLOG(1) << __func__ << ", scope: " << scope; DCHECK(scope == UpdaterScope::kUser || ::IsUserAnAdmin()); HKEY key = scope == UpdaterScope::kSystem ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; auto scoped_com_initializer = std::make_unique<base::win::ScopedCOMInitializer>( base::win::ScopedCOMInitializer::kMTA); updater::UnregisterWakeTask(scope); if (uninstall_all) { std::unique_ptr<WorkItemList> uninstall_list( WorkItem::CreateWorkItemList()); uninstall_list->AddDeleteRegKeyWorkItem(key, UPDATER_KEY, Wow6432(0)); if (!uninstall_list->Do()) { LOG(ERROR) << "Failed to delete the registry keys."; uninstall_list->Rollback(); return -1; } } DeleteComInterfaces(key, uninstall_all); if (scope == UpdaterScope::kSystem) DeleteComService(uninstall_all); DeleteComServer(scope, key, uninstall_all); return RunUninstallScript(scope, uninstall_all); } } // namespace int Uninstall(UpdaterScope scope) { return UninstallImpl(scope, true); } // Uninstalls this version of the updater, without uninstalling any other // versions. This version is assumed to not be the active version. int UninstallCandidate(UpdaterScope scope) { return UninstallImpl(scope, false); } } // namespace updater
35.175141
80
0.697719
zealoussnow
72e4297f16e57a0fae35a24e615b439cc5da2a63
98,512
cpp
C++
src/gausskernel/cbb/workload/dywlm_client.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
1
2020-06-30T15:00:50.000Z
2020-06-30T15:00:50.000Z
src/gausskernel/cbb/workload/dywlm_client.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
src/gausskernel/cbb/workload/dywlm_client.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * dywlm_client.cpp * functions for workload management * * IDENTIFICATION * src/gausskernel/cbb/workload/dywlm_client.cpp * ------------------------------------------------------------------------- */ #include "postgres.h" #include "knl/knl_variable.h" #include "gssignal/gs_signal.h" #include "libpq/libpq.h" #include "libpq/pqformat.h" #include "tcop/tcopprot.h" #include "miscadmin.h" #include "pgstat.h" #include "pgxc/pgxc.h" #include "pgxc/pgxcnode.h" #include "pgxc/poolmgr.h" #include "utils/atomic.h" #include "utils/lsyscache.h" #include "utils/memprot.h" #include "utils/tqual.h" #include "workload/memctl.h" #include "workload/workload.h" #define CPU_UTIL_THRESHOLD 95 #define IO_UTIL_THRESHOLD 90 THR_LOCAL bool WLMProcessExiting = false; THR_LOCAL ServerDynamicManager* g_srvmgr = NULL; extern unsigned char is_transcation_start(const char* str); THR_LOCAL int reserved_in_central_waiting = 0; static THR_LOCAL bool acce_not_enough_resource = false; /* * @Description: register query dynamic information to hash table * @IN void * @Return: dynamic info node * @See also: */ DynamicInfoNode* dywlm_info_register(const DynamicMessageInfo* reginfo) { ClientDynamicManager* g_climgr = t_thrd.wlm_cxt.thread_climgr; USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_EXCLUSIVE); /* too many dynamic info now, ignore this time. */ if (hash_get_num_entries(g_climgr->dynamic_info_hashtbl) > g_climgr->max_info_count) { return NULL; } if (g_climgr->max_support_statements > 0 && hash_get_num_entries(g_climgr->dynamic_info_hashtbl) >= g_climgr->max_support_statements) { return NULL; } DynamicInfoNode* info = (DynamicInfoNode*)hash_search(g_climgr->dynamic_info_hashtbl, &reginfo->qid, HASH_ENTER_NULL, NULL); /* init dynamic node info */ if (info != NULL) { info->qid = reginfo->qid; info->memsize = reginfo->memsize; info->max_memsize = reginfo->max_memsize; info->min_memsize = reginfo->min_memsize; info->actpts = reginfo->actpts; info->max_actpts = reginfo->max_actpts; info->min_actpts = reginfo->min_actpts; info->maxpts = reginfo->maxpts; info->priority = reginfo->priority; info->is_dirty = false; info->wakeup = false; info->condition = (pthread_cond_t)PTHREAD_COND_INITIALIZER; (void)pthread_mutex_init(&info->mutex, NULL); errno_t errval = strncpy_s(info->rpname, sizeof(info->rpname), reginfo->rpname, sizeof(info->rpname) - 1); securec_check_errval(errval, , LOG); errval = strncpy_s(info->ngroup, sizeof(info->ngroup), reginfo->groupname, sizeof(info->ngroup) - 1); securec_check_errval(errval, , LOG); ereport(DEBUG1, (errmsg("register dynamic info into dynamic_info_hashtbl, qid:[%u, %lu, %ld]", info->qid.procId, info->qid.queryId, info->qid.stamp))); info->threadid = t_thrd.proc_cxt.MyProcPid; } return info; } /* * @Description: unregister query dynamic information from hash table * @IN void * @Return: void * @See also: */ void dywlm_info_unregister(void) { DynamicInfoNode* info = NULL; USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_EXCLUSIVE); info = (DynamicInfoNode*)hash_search( t_thrd.wlm_cxt.thread_climgr->dynamic_info_hashtbl, &u_sess->wlm_cxt->wlm_params.qid, HASH_FIND, NULL); if (info != NULL) { ereport(DEBUG1, (errmsg("unregister dynamic info from dynamic_info_hashtbl, qid:[%u, %lu, %ld]", info->qid.procId, info->qid.queryId, info->qid.stamp))); (void)pthread_mutex_destroy(&info->mutex); (void)hash_search( t_thrd.wlm_cxt.thread_climgr->dynamic_info_hashtbl, &u_sess->wlm_cxt->wlm_params.qid, HASH_REMOVE, NULL); } } /* * @Description: parallel control ready for client * @IN sqltext: sql text * @Return: void * @See also: */ void dywlm_parallel_ready(const char* sqltext) { errno_t errval = memset_s( &t_thrd.wlm_cxt.parctl_state, sizeof(t_thrd.wlm_cxt.parctl_state), 0, sizeof(t_thrd.wlm_cxt.parctl_state)); securec_check_errval(errval, , LOG); /* we always handle exception. */ u_sess->wlm_cxt->parctl_state_control = 1; t_thrd.wlm_cxt.parctl_state.except = 1; t_thrd.wlm_cxt.parctl_state.simple = 1; t_thrd.wlm_cxt.parctl_state.special = WLMIsSpecialQuery(sqltext) ? 1 : 0; /* Is the query in a transaction block now? */ t_thrd.wlm_cxt.parctl_state.transact = IsTransactionBlock() ? 1 : 0; t_thrd.wlm_cxt.parctl_state.transact_begin = 0; t_thrd.wlm_cxt.parctl_state.subquery = 0; /* * If we are in a transaction block, we will make it * has reserved global and resource pool active statements, * so that we can release active statements while transaction * block is end. */ if (t_thrd.wlm_cxt.parctl_state.transact && !t_thrd.wlm_cxt.parctl_state.transact_begin && u_sess->wlm_cxt->is_reserved_in_transaction) { t_thrd.wlm_cxt.parctl_state.reserve = 1; } if (IsAbortedTransactionBlockState()) { return; } /* set current user info */ WLMSetUserInfo(); /* * If the user is super user or it's a special * query it will not do the global parallel control. */ if (t_thrd.wlm_cxt.parctl_state.special == 0 && !u_sess->wlm_cxt->wlm_params.rpdata.superuser) { t_thrd.wlm_cxt.parctl_state.enqueue = 1; } /* set wlm stat info */ WLMSetStatInfo(sqltext); /* set wlm debug info */ u_sess->wlm_cxt->wlm_debug_info.climgr = &t_thrd.wlm_cxt.thread_node_group->climgr; u_sess->wlm_cxt->wlm_debug_info.srvmgr = &t_thrd.wlm_cxt.thread_node_group->srvmgr; u_sess->wlm_cxt->wlm_debug_info.pstate = &t_thrd.wlm_cxt.parctl_state; } /* * @Description: parse message from server for client * @IN input_message: message from the server * @OUT info: message detail info * @Return: void * @See also: */ void dywlm_client_parse_message(StringInfo input_message, DynamicMessageInfo* info) { /* query is finished, maybe we need wake up next query in pending mode */ info->qid.procId = (Oid)pq_getmsgint(input_message, 4); info->qid.queryId = (uint64)pq_getmsgint64(input_message); info->qid.stamp = (TimestampTz)pq_getmsgint64(input_message); info->qtype = (ParctlType)pq_getmsgint(input_message, 4); info->etype = (EnqueueType)pq_getmsgint(input_message, 4); info->memsize = pq_getmsgint(input_message, 4); info->actpts = pq_getmsgint(input_message, 4); errno_t errval = strncpy_s(info->nodename, sizeof(info->nodename), pq_getmsgstring(input_message), sizeof(info->nodename) - 1); securec_check_errval(errval, , LOG); errval = strncpy_s( info->groupname, sizeof(info->groupname), pq_getmsgstring(input_message), sizeof(info->groupname) - 1); securec_check_errval(errval, , LOG); pq_getmsgend(input_message); } /* * @Description: reply message to server from client * @IN errcode: error code * @IN mtype: message head character * @Return: void * @See also: */ void dywlm_client_reply(int errcode) { StringInfoData retbuf; pq_beginmessage(&retbuf, 'w'); pq_sendint(&retbuf, errcode, 4); pq_endmessage(&retbuf); pq_flush(); } /* * @Description: reply workload records on the client * @IN void * @Return: void * @See also: */ void dywlm_client_reply_records(ClientDynamicManager* climgr) { int count = 0; StringInfoData retbuf; if (g_instance.wlm_cxt->dynamic_workload_inited) { USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); DynamicInfoNode* info = NULL; HASH_SEQ_STATUS hash_seq; hash_seq_init(&hash_seq, climgr->dynamic_info_hashtbl); while ((info = (DynamicInfoNode*)hash_seq_search(&hash_seq)) != NULL) { /* * we can only judge whether the job is queued by whether the job * wakes up or not. If we are queuing, we can only think of queuing * in the global queue. */ ParctlType qtype = info->wakeup ? PARCTL_ACTIVE : PARCTL_GLOBAL; pq_beginmessage(&retbuf, 'r'); pq_sendint(&retbuf, (int)info->qid.procId, sizeof(int)); pq_sendint64(&retbuf, (uint64)info->qid.queryId); pq_sendint64(&retbuf, (int64)info->qid.stamp); pq_sendint(&retbuf, info->memsize, sizeof(int)); pq_sendint(&retbuf, info->max_memsize, sizeof(int)); pq_sendint(&retbuf, info->min_memsize, sizeof(int)); pq_sendint(&retbuf, info->actpts, sizeof(int)); pq_sendint(&retbuf, info->max_actpts, sizeof(int)); pq_sendint(&retbuf, info->min_actpts, sizeof(int)); pq_sendint(&retbuf, info->maxpts, sizeof(int)); pq_sendint(&retbuf, info->priority, sizeof(int)); pq_sendint(&retbuf, (int)qtype, sizeof(int)); pq_sendstring(&retbuf, info->rpname); pq_sendstring(&retbuf, g_instance.attr.attr_common.PGXCNodeName); pq_sendstring(&retbuf, info->ngroup); pq_endmessage(&retbuf); ereport(DEBUG1, (errmsg("CLIENT REPLY RECORDS qid [%u, %lu, %ld], qtype: %d", info->qid.procId, info->qid.queryId, info->qid.stamp, qtype))); ++count; } } /* completed tag */ pq_beginmessage(&retbuf, 'f'); pq_sendint(&retbuf, count, 4); pq_endmessage(&retbuf); pq_flush(); } /* * @Description: forward the message received from the server * @IN msginfo: message detail info * @Return: void * @See also: */ int dywlm_client_post(ClientDynamicManager* climgr, const DynamicMessageInfo* msginfo) { /* Make sure qid is valid */ if (IsQidInvalid(&msginfo->qid) || !g_instance.wlm_cxt->dynamic_workload_inited) { return DYWLM_SEND_OK; } Assert( !StringIsValid(msginfo->nodename) || strcmp(msginfo->nodename, g_instance.attr.attr_common.PGXCNodeName) == 0); USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); /* search query dynamic info in the hash table */ DynamicInfoNode* info = (DynamicInfoNode*)hash_search(climgr->dynamic_info_hashtbl, &msginfo->qid, HASH_FIND, NULL); if (info == NULL) { return DYWLM_NO_RECORD; } /* if server concurrency control has error, the corresponding thread will be cancel off */ if (msginfo->etype == ENQUEUE_ERROR) { (void)gs_signal_send(info->threadid, SIGINT); return 0; } RELEASE_AUTO_LWLOCK(); /* client may receive wake up message twice due to network * avoid wake up dirty stmt */ if (info->wakeup || info->is_dirty) { return DYWLM_SEND_OK; } WLMContextLock mtx_lock(&info->mutex, false); mtx_lock.Lock(); /* wake up the corresponding thread and update the current information */ info->memsize = msginfo->memsize; info->actpts = msginfo->actpts; mtx_lock.ConditionWakeUp(&info->condition); info->wakeup = true; mtx_lock.UnLock(); return DYWLM_SEND_OK; } /* * @Description: get node index * @IN nodename: node name * @Return: index, if not found ,return -1 * @See also: */ int dywlm_get_node_idx(const char* nodename) { return PgxcGetNodeIndex(nodename); } /* * @Description: directly use the interface of server on client * @IN msginfo: message detail info * @Return: enqueue type * @See also: */ EnqueueType dywlm_client_handle_for_server(ClientDynamicManager* climgr, DynamicMessageInfo* msginfo) { int count = 0; ServerDynamicManager* srvmgr = (ServerDynamicManager*)climgr->srvmgr; while (srvmgr->recover || (!COMP_ACC_CLUSTER && srvmgr->freesize_update == 0)) { pg_usleep(USECS_PER_SEC); ++count; /* wait for 5 seconds */ if (count >= 5) { return ENQUEUE_RECOVERY; } } switch (msginfo->qtype) { case PARCTL_RESERVE: case PARCTL_TRANSACT: return dywlm_server_reserve(srvmgr, msginfo); /* reserve memory */ case PARCTL_RELEASE: return dywlm_server_release(srvmgr, msginfo); /* release memory */ case PARCTL_CANCEL: return dywlm_server_cancel(srvmgr, msginfo); /* cancel request */ case PARCTL_CLEAN: return dywlm_server_clean_internal(srvmgr, msginfo->nodename); /* clean for recovery */ case PARCTL_MVNODE: return dywlm_server_move_node_to_list(srvmgr, msginfo); /* move node */ case PARCTL_JPQUEUE: return dywlm_server_jump_queue(srvmgr, msginfo); /* jump priority */ default: break; } return ENQUEUE_UNKNOWN; } /* * @Description: update memory usage while query can not be satisfied * @IN msginfo: message detail info * @Return: void * @See also: */ void dywlm_client_update_mem(ClientDynamicManager* climgr, DynamicMessageInfo* msginfo) { USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); DynamicInfoNode* info = (DynamicInfoNode*)hash_search(climgr->dynamic_info_hashtbl, &msginfo->qid, HASH_FIND, NULL); if (info != NULL) { /* update the information judged from server. */ info->memsize = msginfo->memsize; info->actpts = msginfo->actpts; } } /* @Description: get the connection to server and send message * @IN pgxc_handles: handle of connection * @IN ccn_handle: handle of connection to server * @IN retry_count: retry count * @OUT nodeidx: node index * @OUT msginfo: message detail info * @Return: true success; false failed * @See also: */ bool dywlm_client_connect( PGXCNodeAllHandles** pgxc_handles, PGXCNodeHandle** ccn_handle, int* nodeidx, DynamicMessageInfo* msginfo) { List* coordlist = NIL; MemoryContext curr_mcxt = CurrentMemoryContext; PoolAgent* agent = NULL; *ccn_handle = NULL; *pgxc_handles = NULL; /* search central node index */ *nodeidx = PgxcGetCentralNodeIndex(); /* create connection to the central node */ if (*nodeidx >= 0) { /* I am central node now, handle the message as server directly */ if (PgxcIsCentralCoordinator(g_instance.attr.attr_common.PGXCNodeName)) { msginfo->isserver = true; return true; } if (coordlist == NIL) { USE_MEMORY_CONTEXT(g_instance.wlm_cxt->workload_manager_mcxt); coordlist = lappend_int(coordlist, *nodeidx); } Assert(list_length(coordlist) == 1); PG_TRY(); { *pgxc_handles = get_handles(NULL, coordlist, true); agent = get_poolagent(); } PG_CATCH(); { *pgxc_handles = NULL; FlushErrorState(); } PG_END_TRY(); if (*pgxc_handles == NULL) { MemoryContextSwitchTo(curr_mcxt); list_free_ext(coordlist); pg_usleep(3 * USECS_PER_SEC); return false; } *ccn_handle = (*pgxc_handles)->coord_handles[0]; } if (agent == NULL || agent->coord_connections[*nodeidx] == NULL) { return false; } if (*ccn_handle) { /* send message to the central node to reserve or release memory */ if (pgxc_node_dywlm_send_params(*ccn_handle, msginfo) != 0) { list_free_ext(coordlist); release_pgxc_handles(*pgxc_handles); ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("[DYWLM] Failed to send dynamic workload params to CCN!"))); } list_free_ext(coordlist); return true; } list_free_ext(coordlist); release_pgxc_handles(*pgxc_handles); *pgxc_handles = NULL; return false; } /* * @Description: send message to server from the client * @IN msginfo: message detail info * @Return: enqueue type * @See also: */ EnqueueType dywlm_client_send(ClientDynamicManager* climgr, DynamicMessageInfo* msginfo) { PGXCNodeHandle* ccn_handle = NULL; PGXCNodeAllHandles* pgxc_handles = NULL; EnqueueType etype = ENQUEUE_CONNERR; int nodeidx = 0; struct timeval timeout = {300, 0}; ereport(DEBUG2, (errmsg("client send qid[%u, %lu, %ld], queue_type: %d", msginfo->qid.procId, msginfo->qid.queryId, msginfo->qid.stamp, msginfo->qtype))); if (!dywlm_client_connect(&pgxc_handles, &ccn_handle, &nodeidx, msginfo)) { release_pgxc_handles(pgxc_handles); return etype; } /* The application node is the server itself, then directly use the interface on the server */ if (msginfo->isserver) { return dywlm_client_handle_for_server(climgr, msginfo); } /* release message do not need reply */ if (msginfo->qtype == PARCTL_RELEASE) { release_pgxc_handles(pgxc_handles); return ENQUEUE_NONE; } while (true) { bool hasError = false; bool isFinished = false; if (!pgxc_node_receive(1, &ccn_handle, &timeout)) { char* msg = NULL; int len; char msg_type; msg_type = get_message(ccn_handle, &len, &msg); switch (msg_type) { case 'w': { DynamicMessageInfo info; errno_t errval = memset_s(&info, sizeof(info), 0, sizeof(info)); securec_check_errval(errval, , LOG); info.qtype = msginfo->qtype; StringInfoData input_msg; initStringInfo(&input_msg); appendBinaryStringInfo(&input_msg, msg, len); /* parse message string info */ dywlm_client_parse_message(&input_msg, &info); etype = info.etype; ereport(DEBUG3, (errmsg("ID[%u,%lu,%ld] -----dywlm_client_Send-----[current:%d, max:%d, min:%d, qtype:%d, " "etype:%d]", info.qid.procId, info.qid.queryId, info.qid.stamp, info.memsize, msginfo->max_memsize, msginfo->min_memsize, info.qtype, info.etype))); /* * If query is in a transaction or reserved from server, and the memory request * is not satisfied, update the request memory. */ if (((info.memsize != msginfo->memsize) || (info.actpts != msginfo->actpts)) && ((msginfo->qtype == PARCTL_TRANSACT) || (msginfo->qtype == PARCTL_RESERVE))) { dywlm_client_update_mem(climgr, &info); } isFinished = true; break; } case 'E': hasError = true; break; case 'Z': if (hasError) { isFinished = true; ereport(LOG, (errmsg("receive message error, " "error occurred on central node, %s", ccn_handle->error == NULL ? "receive data failed" : ccn_handle->error))); release_pgxc_handles(pgxc_handles); pgxc_handles = NULL; } break; default: break; } if (isFinished) { break; } } else { release_pgxc_handles(pgxc_handles); ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("[DYWLM] Failed to receive queue info from CCN, error info: %s", ccn_handle->error == NULL ? "receive data failed" : ccn_handle->error))); } } ccn_handle->state = DN_CONNECTION_STATE_IDLE; release_pgxc_handles(pgxc_handles); return etype; } /* * @Description: client get memory size * @IN void * @Return: memory size to use * @See also: */ int64 dywlm_client_get_memory(void) { if (!IS_PGXC_DATANODE || !g_instance.wlm_cxt->dynamic_workload_inited) { return 0L; } uint64 totalMemSize = (uint64)maxChunksPerProcess << (chunkSizeInBits - BITS_IN_MB); uint64 usedMemSize = (uint64)processMemInChunks << (chunkSizeInBits - BITS_IN_MB); int64 freeSize = totalMemSize - usedMemSize; int64 extsize = 0L; int active_count = g_instance.wlm_cxt->stat_manager.comp_count; if (usedMemSize >= totalMemSize * DYWLM_HIGH_QUOTA / FULL_PERCENT) { ereport(DEBUG1, (errmsg("used size %lu exceeds 90%% total size %lu, get size %ld", usedMemSize * KBYTES, totalMemSize * KBYTES, extsize))); return extsize; } if (active_count == 0) { extsize = freeSize * KBYTES * DYWLM_MEDIUM_QUOTA / FULL_PERCENT; ereport(DEBUG1, (errmsg("no acitve count, get size %ld", extsize))); return extsize; } if (active_count > 6) { if (usedMemSize >= totalMemSize * 70 / FULL_PERCENT) { ereport(DEBUG1, (errmsg("active count is %d, used size %lu exceeds 70%% total size %lu, get size %ld", active_count, usedMemSize * KBYTES, totalMemSize * KBYTES, extsize))); return extsize; } active_count = 6; } extsize = freeSize * KBYTES * (DYWLM_MEDIUM_QUOTA - 10 * (active_count - 1)) / FULL_PERCENT; ereport(DEBUG1, (errmsg("active count is %d, get size %ld is %d%% of free size %ld ", active_count, extsize, DYWLM_MEDIUM_QUOTA - 10 * (active_count - 1), freeSize * KBYTES))); return extsize; } /* * @Description: client set resource pool used memory size * @IN size: memory size to use * @Return: void * @See also: */ void dywlm_client_set_respool_memory(int size, WLMStatusTag status) { if (!(IS_PGXC_COORDINATOR || IS_SINGLE_NODE) || !g_instance.wlm_cxt->dynamic_workload_inited) { return; } if (!OidIsValid(u_sess->wlm_cxt->wlm_params.rpdata.rpoid) || u_sess->wlm_cxt->wlm_params.rpdata.rpoid == DEFAULT_POOL_OID || size == 0) { return; } ereport(DEBUG1, (errmsg("set resource pool memory: %d", size))); if (u_sess->wlm_cxt->wlm_params.rp == NULL) { if (status == WLM_STATUS_RELEASE) { return; } USE_AUTO_LWLOCK(ResourcePoolHashLock, LW_SHARED); /* get used memory size of resource pool */ u_sess->wlm_cxt->wlm_params.rp = GetRespoolFromHTab(u_sess->wlm_cxt->wlm_params.rpdata.rpoid, true); if (u_sess->wlm_cxt->wlm_params.rp == NULL) { ereport(WARNING, (errmsg("cannot get resource pool %u", u_sess->wlm_cxt->wlm_params.rpdata.rpoid))); return; } } gs_atomic_add_32(&((ResourcePool*)u_sess->wlm_cxt->wlm_params.rp)->memsize, size); /* calculate the total amount of memory requests used by the current node */ gs_atomic_add_32(&t_thrd.wlm_cxt.thread_climgr->usedsize, size); } /* * @Description: client get max memory size from resource pool * @IN void * @Return: max memory size to use * @See also: */ int64 dywlm_client_get_max_memory_internal(bool* use_tenant) { #define RESPOOL_MIN_SIZE (2 * 1024 * 1024) // 2GB /* no memory limit or not coordinator, nothing to do */ if (!(IS_PGXC_COORDINATOR || IS_SINGLE_NODE)) { return 0L; } int multiple = 1; if (g_instance.wlm_cxt->dynamic_workload_inited) { /* We allow at least two queries concurrently */ multiple = t_thrd.wlm_cxt.thread_climgr->active_statements > 1 ? 2 : 1; /* the default resource pool uses the global maximum memory */ if (!OidIsValid(u_sess->wlm_cxt->wlm_params.rpdata.rpoid) || u_sess->wlm_cxt->wlm_params.rpdata.rpoid == DEFAULT_POOL_OID) { return (int64)t_thrd.wlm_cxt.thread_srvmgr->totalsize * DYWLM_HIGH_QUOTA * KBYTES / FULL_PERCENT / multiple; } if (u_sess->wlm_cxt->wlm_params.rpdata.mem_size > RESPOOL_MIN_SIZE && u_sess->wlm_cxt->wlm_params.rpdata.max_pts > FULL_PERCENT) { return (int64)u_sess->wlm_cxt->wlm_params.rpdata.mem_size * DYWLM_HIGH_QUOTA / FULL_PERCENT / multiple; } else { return (int64)u_sess->wlm_cxt->wlm_params.rpdata.mem_size * DYWLM_HIGH_QUOTA / FULL_PERCENT; } } else { if (u_sess->wlm_cxt->wlm_params.rpdata.rpoid != DEFAULT_POOL_OID) { *use_tenant = true; if (u_sess->wlm_cxt->wlm_params.rpdata.mem_size > RESPOOL_MIN_SIZE && u_sess->wlm_cxt->wlm_params.rpdata.max_pts > FULL_PERCENT) { return (int64)u_sess->wlm_cxt->wlm_params.rpdata.mem_size * DYWLM_HIGH_QUOTA / FULL_PERCENT / multiple; } else { return (int64)u_sess->wlm_cxt->wlm_params.rpdata.mem_size * DYWLM_HIGH_QUOTA / FULL_PERCENT; } } } return 0; } /* * @Description: client get max memory size from resource pool * @IN void * @Return: max memory size to use * @See also: */ int64 dywlm_client_get_max_memory(bool* use_tenant) { /* no memory limit or not coordinator, nothing to do */ t_thrd.wlm_cxt.collect_info->max_mem = dywlm_client_get_max_memory_internal(use_tenant); return t_thrd.wlm_cxt.collect_info->max_mem; } /* * @Description: client get free memory size from resource pool * @IN void * @Return: free memory size to use * @See also: */ int64 dywlm_client_get_free_memory_internal(void) { /* no memory limit or not coordinator, nothing to do */ if (!(IS_PGXC_COORDINATOR || IS_SINGLE_NODE) || !g_instance.wlm_cxt->dynamic_workload_inited) { return 0L; } /* the default resource pool uses the global free memory */ if (!OidIsValid(u_sess->wlm_cxt->wlm_params.rpdata.rpoid) || u_sess->wlm_cxt->wlm_params.rpdata.rpoid == DEFAULT_POOL_OID) { /* only one active statements, use max memory */ if (t_thrd.wlm_cxt.thread_climgr->active_statements == 1) { return (int64)t_thrd.wlm_cxt.thread_srvmgr->totalsize * DYWLM_HIGH_QUOTA * KBYTES / FULL_PERCENT; } else { return (int64)t_thrd.wlm_cxt.thread_climgr->freesize * DYWLM_HIGH_QUOTA * KBYTES / FULL_PERCENT; } } USE_AUTO_LWLOCK(ResourcePoolHashLock, LW_SHARED); /* get used memory size of resource pool */ ResourcePool* rp = GetRespoolFromHTab(u_sess->wlm_cxt->wlm_params.rpdata.rpoid, true); if (rp == NULL) { ereport(WARNING, (errmsg("cannot get resource pool %u", u_sess->wlm_cxt->wlm_params.rpdata.rpoid))); return 0L; } if (rp->memsize <= 0) { rp->memsize = 0; } int64 max_size = (int64)u_sess->wlm_cxt->wlm_params.rpdata.mem_size * DYWLM_HIGH_QUOTA / FULL_PERCENT; int64 real_used_size = (int64)(t_thrd.wlm_cxt.thread_srvmgr->totalsize - t_thrd.wlm_cxt.thread_climgr->freesize) * KBYTES; int64 used_size = (int64)t_thrd.wlm_cxt.thread_climgr->usedsize * KBYTES; /* only one active statements, use max memory */ if (t_thrd.wlm_cxt.thread_climgr->active_statements == 1) { return max_size; } if (used_size < real_used_size) { max_size -= real_used_size - used_size; if (max_size <= 0) { max_size = 0; } } return (int64)rp->memsize * KBYTES > max_size ? 0L : (max_size - (int64)rp->memsize * KBYTES); } /* * @Description: client get free memory size from resource pool * @IN void * @Return: free memory size to use * @See also: */ int64 dywlm_client_get_free_memory(void) { t_thrd.wlm_cxt.collect_info->avail_mem = dywlm_client_get_free_memory_internal(); return t_thrd.wlm_cxt.collect_info->avail_mem; } /* * @Description: client get max and free memory size from resource pool or GUC variable * @OUT total_mem: max mem info * @OUT free_mem: free mem info * @OUT use_tenant: if tenant is used * @Return: void * @See also: */ void dywlm_client_get_memory_info(int* total_mem, int* free_mem, bool* use_tenant) { int query_mem = ASSIGNED_QUERY_MEM(u_sess->attr.attr_sql.statement_mem, u_sess->attr.attr_sql.statement_max_mem); int max_mem = (int)dywlm_client_get_max_memory(use_tenant); int available_mem = 0; if (g_instance.wlm_cxt->dynamic_workload_inited && g_instance.wlm_cxt->dynamic_memory_collected && max_mem == 0) { (elog(LOG, "[DYWLM] System max process memory unexpected to be 0.")); } /* We use query_mem first if set */ if (query_mem != 0) { /* query_mem set can't exceeds system max mem */ if (max_mem != 0) { max_mem = Min(query_mem, max_mem); } else { max_mem = query_mem; } available_mem = (u_sess->attr.attr_memory.work_mem >= STATEMENT_MIN_MEM * 1024 ? u_sess->attr.attr_memory.work_mem : max_mem); available_mem = Min(available_mem, max_mem); /* We use dynamic workload if query_mem is not set */ } else if (max_mem != 0) { int dywlm_mem = (int)dywlm_client_get_free_memory(); max_mem = ASSIGNED_QUERY_MEM(max_mem, u_sess->attr.attr_sql.statement_max_mem); if (*use_tenant) { available_mem = u_sess->attr.attr_memory.work_mem; } else { available_mem = Min(Max(dywlm_mem, STATEMENT_MIN_MEM * 1024), max_mem); } } *total_mem = max_mem; *free_mem = available_mem; /* before dynamic memory collected,set free memory STATEMENT_MIN_MEM */ if (g_instance.wlm_cxt->dynamic_workload_inited && !g_instance.wlm_cxt->dynamic_memory_collected) { *total_mem = STATEMENT_MIN_MEM * 1024; *free_mem = STATEMENT_MIN_MEM * 1024; ereport(DEBUG3, (errmsg("[DYWLM] Memory info has not been collected,use STATEMENT_MIN_MEM for query"))); } } /* * @Description: initalize message detail info * @IN msginfo: message detail info * @IN qtype: parctl type * @Return: message detail info * @See also: */ DynamicMessageInfo* dywlm_client_initmsg(ClientDynamicManager* climgr, DynamicMessageInfo* msginfo, ParctlType qtype) { errno_t errval = memset_s(msginfo, sizeof(DynamicMessageInfo), 0, sizeof(DynamicMessageInfo)); securec_check_errval(errval, , LOG); msginfo->qid = u_sess->wlm_cxt->wlm_params.qid; msginfo->maxpts = u_sess->wlm_cxt->wlm_params.rpdata.max_pts; msginfo->priority = t_thrd.wlm_cxt.qnode.priority; /* different qtype, so that the message has different function */ msginfo->qtype = qtype; msginfo->etype = ENQUEUE_NONE; msginfo->isserver = is_pgxc_central_nodename(g_instance.attr.attr_common.PGXCNodeName); /* Am I CCN? */ errval = strncpy_s(msginfo->rpname, sizeof(msginfo->rpname), u_sess->wlm_cxt->wlm_params.rpdata.rpname, sizeof(msginfo->rpname) - 1); securec_check_errval(errval, , LOG); errval = strncpy_s(msginfo->nodename, sizeof(msginfo->nodename), g_instance.attr.attr_common.PGXCNodeName, sizeof(msginfo->nodename) - 1); securec_check_errval(errval, , LOG); errval = strncpy_s(msginfo->groupname, sizeof(msginfo->groupname), u_sess->wlm_cxt->wlm_params.ngroup, sizeof(msginfo->groupname) - 1); securec_check_errval(errval, , LOG); msginfo->actpts = u_sess->wlm_cxt->wlm_params.rpdata.act_pts; msginfo->memsize = u_sess->wlm_cxt->wlm_params.memsize; msginfo->subquery = (t_thrd.wlm_cxt.parctl_state.subquery == 1) ? true : false; /* reserve info */ if (qtype == PARCTL_RESERVE || qtype == PARCTL_TRANSACT) { msginfo->max_actpts = u_sess->wlm_cxt->wlm_params.rpdata.max_act_pts; msginfo->min_actpts = u_sess->wlm_cxt->wlm_params.rpdata.min_act_pts; msginfo->max_memsize = u_sess->wlm_cxt->wlm_params.max_memsize; msginfo->min_memsize = u_sess->wlm_cxt->wlm_params.min_memsize; ereport(DEBUG3, (errmsg("----DYWLM---- dywlm_client_initmsg FULLinfo [min_mem: %d, min_act: %d, max_mem:%d, max_act:%d]", msginfo->min_memsize, msginfo->min_actpts, msginfo->max_memsize, msginfo->max_actpts))); /* release resource should get the resource used from records hash table */ } else if (qtype == PARCTL_RELEASE) { USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); DynamicInfoNode* info = (DynamicInfoNode*)hash_search(climgr->dynamic_info_hashtbl, &msginfo->qid, HASH_FIND, NULL); /* get message info from register hash table */ if (info != NULL) { msginfo->actpts = info->actpts; msginfo->max_actpts = info->max_actpts; msginfo->min_actpts = info->min_actpts; // Acceleration cluster if (COMP_ACC_CLUSTER) { msginfo->memsize = 0; } else { // customer cluster msginfo->memsize = info->memsize; } msginfo->max_memsize = info->max_memsize; msginfo->min_memsize = info->min_memsize; } } return msginfo; } /* * @Description: clean handler for the client * @IN ptr: parctl state pointer * @Return: void * @See also: */ void dywlm_client_clean(void* ptr) { if (ptr == NULL) { return; } ParctlState* state = (ParctlState*)ptr; /* it's released, nothing to do */ if (state->rp_release || t_thrd.proc_cxt.proc_exit_inprogress) { return; } /* record the wait count in central queue */ if (t_thrd.wlm_cxt.parctl_state.reserve && !t_thrd.wlm_cxt.parctl_state.transact) { USE_CONTEXT_LOCK(&t_thrd.wlm_cxt.thread_climgr->statement_list_mutex); if (t_thrd.wlm_cxt.thread_climgr->central_waiting_count) { t_thrd.wlm_cxt.thread_climgr->central_waiting_count--; reserved_in_central_waiting--; } } DynamicMessageInfo msginfo; /* init message info to send to server, it's will release resource on the server */ (void)dywlm_client_initmsg(t_thrd.wlm_cxt.thread_climgr, &msginfo, PARCTL_CANCEL); (void)dywlm_client_send(t_thrd.wlm_cxt.thread_climgr, &msginfo); pgstat_report_waiting_on_resource(STATE_NO_ENQUEUE); dywlm_info_unregister(); state->central_waiting = 0; /* handle exception */ if (state->except) { WLMResetStatInfo4Exception(); state->except = 0; } state->rp_release = 1; } /* * @Description: wait for reserving resource on the server * @IN msginfo: message detail info * @Return: 1 - global reserved * 0 - global reserved failed * @See also: */ int dywlm_client_wait(DynamicMessageInfo* msginfo) { ClientDynamicManager* g_climgr = t_thrd.wlm_cxt.thread_climgr; /* no memory to reserve, nothing to do */ if (!COMP_ACC_CLUSTER && msginfo->memsize <= 0) { ereport(DEBUG1, (errmsg("query[%u:%lu:%ld] request memory is less than 0", msginfo->qid.procId, msginfo->qid.queryId, msginfo->qid.stamp))); return 0; } int count = 0; bool timeout = false; /* register the info node in the hash table */ DynamicInfoNode* info = dywlm_info_register(msginfo); if (info == NULL) { ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory of current node, please check statement count"))); } /* * While the current node is in recovery state, query operation * cannot be performed, the reason is, node maybe still has the * residual enqueue information of the last process, we must take * these information clearing off, Otherwise, the resource information * leakage will occur on the server. * If current node do not finish recovery after 5 seconds, the * query can run anyway. */ while (g_climgr->recover) { pg_usleep(USECS_PER_SEC); count++; if (count > 5) { info->wakeup = true; return 0; } } EnqueueType etype = dywlm_client_send(g_climgr, msginfo); /* If current CN is CCN, the information passes without using hashtable. * Structure msginfo has changed as a parameter. * So we need to update client hashtable according to msginfo. */ if (!msginfo->isserver) { USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); DynamicInfoNode* crtinfo = (DynamicInfoNode*)hash_search(g_climgr->dynamic_info_hashtbl, &msginfo->qid, HASH_FIND, NULL); if (crtinfo != NULL) { msginfo->memsize = crtinfo->memsize; msginfo->actpts = crtinfo->actpts; } /* If current CN is not CCN, the changes have been written into hashtable on bosth side, * Structure msginfo should be updated according to the client-side hash table. */ } else { USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); DynamicInfoNode* crtinfo = (DynamicInfoNode*)hash_search(g_climgr->dynamic_info_hashtbl, &msginfo->qid, HASH_FIND, NULL); if (crtinfo != NULL) { crtinfo->memsize = msginfo->memsize; crtinfo->actpts = msginfo->actpts; } } switch (etype) { case ENQUEUE_CONNERR: /* failed to connect to central node, query will run */ ereport(LOG, (errmsg("failed to connect to central node"))); return 0; case ENQUEUE_ERROR: ereport(ERROR, (errcode(ERRCODE_SYSTEM_ERROR), errmsg("failed to enqueue in central node"))); break; case ENQUEUE_NORESPOOL: ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("resource pool: %s does not exist", msginfo->rpname))); break; case ENQUEUE_MEMERR: ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory of central node"))); break; case ENQUEUE_GROUPERR: ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("group name %s does not exist on central node", msginfo->groupname))); break; case ENQUEUE_RECOVERY: /* central node is in recovery state, query will run */ ereport(LOG, (errmsg("central node is recovering"))); return 0; case ENQUEUE_NONE: /* cluster has enough memory, need not enqueue on server. */ info->wakeup = true; return 1; case ENQUEUE_UNKNOWN: ereport(WARNING, (errmsg("parctl type %d is not valid for server handler", msginfo->qtype))); return 0; default: break; } /* query which used planA in logical-cluster should not be blocked */ if (u_sess->wlm_cxt->wlm_params.use_planA) { msginfo->qtype = PARCTL_RELEASE; msginfo->isserver = is_pgxc_central_nodename(g_instance.attr.attr_common.PGXCNodeName); etype = dywlm_client_send(g_climgr, msginfo); ereport(DEBUG3, (errmsg("force run qid [%u, %lu, %ld] since it uses plan A, etype: %d", msginfo->qid.procId, msginfo->qid.queryId, msginfo->qid.stamp, etype))); t_thrd.wlm_cxt.parctl_state.enqueue = 0; t_thrd.wlm_cxt.parctl_state.rp_release = 1; msginfo->memsize = msginfo->min_memsize; msginfo->actpts = msginfo->min_actpts; return 0; } pgstat_report_waiting_on_resource(STATE_ACTIVE_STATEMENTS); reserved_in_central_waiting = 0; /* record the wait count in central queue */ if (t_thrd.wlm_cxt.parctl_state.reserve && !t_thrd.wlm_cxt.parctl_state.transact && !t_thrd.wlm_cxt.parctl_state.subquery) { WLMContextLock list_lock(&g_climgr->statement_list_mutex); list_lock.Lock(); g_climgr->central_waiting_count++; reserved_in_central_waiting++; ereport(DEBUG3, (errmsg("---OVERRUN dywlm_client_wait() reserve --- " "active_statements: %d, central_waiting_count: %d, max_active_statements: %d.\n", g_climgr->active_statements, g_climgr->central_waiting_count, g_climgr->max_active_statements))); /* * It will wake up a statement if there are * statements waiting in the statements waiting * list due to the number of active statements * is less than max_active_statements. */ if (list_length(g_climgr->statements_waiting_list) > 0 && g_climgr->max_support_statements > 0 && g_climgr->current_support_statements < g_climgr->max_support_statements) { DynamicInfoNode* dyinfo = (DynamicInfoNode*)linitial(g_climgr->statements_waiting_list); if (dyinfo != NULL) { list_lock.ConditionWakeUp(&dyinfo->condition); } } list_lock.UnLock(); } WLMContextLock mtx_lock(&info->mutex, false); mtx_lock.Lock(); mtx_lock.set(dywlm_client_clean, &t_thrd.wlm_cxt.parctl_state); t_thrd.wlm_cxt.parctl_state.central_waiting = 1; /* report workload status */ pgstat_report_statement_wlm_status(); while (!info->wakeup && !timeout) { bool ImmediateInterruptOK_Old = t_thrd.int_cxt.ImmediateInterruptOK; PG_TRY(); { /* check for pending interrupts before waiting. */ CHECK_FOR_INTERRUPTS(); t_thrd.int_cxt.ImmediateInterruptOK = true; /* wait for the condition and timeout is set by user */ if (u_sess->attr.attr_resource.transaction_pending_time <= 0) { Assert(&info->condition != NULL); mtx_lock.ConditionTimedWait(&info->condition, SECS_PER_MINUTE); } else { int sec_timeout; if (COMP_ACC_CLUSTER) { sec_timeout = SECS_PER_MINUTE / 3; /* 20s is enough */ } else { sec_timeout = u_sess->attr.attr_resource.transaction_pending_time; } Assert(&info->condition != NULL); mtx_lock.ConditionTimedWait(&info->condition, sec_timeout); if ((t_thrd.wlm_cxt.parctl_state.transact || t_thrd.wlm_cxt.parctl_state.subquery || COMP_ACC_CLUSTER) && !info->wakeup) { /* wait timeout, transaction block will not continue to wait avoiding deadlock. */ timeout = true; } } t_thrd.int_cxt.ImmediateInterruptOK = ImmediateInterruptOK_Old; } PG_CATCH(); { t_thrd.int_cxt.ImmediateInterruptOK = ImmediateInterruptOK_Old; /* UnLock the waiting mutex. */ mtx_lock.UnLock(); PG_RE_THROW(); } PG_END_TRY(); } mtx_lock.reset(); mtx_lock.UnLock(); /* We should refresh from hashtable to get the current information when a query be waked up. */ WLMAutoLWLock htab_lock(WorkloadStatHashLock, LW_SHARED); htab_lock.AutoLWLockAcquire(); DynamicInfoNode* wkupinfo = (DynamicInfoNode*)hash_search(g_climgr->dynamic_info_hashtbl, &msginfo->qid, HASH_FIND, NULL); if (wkupinfo != NULL) { msginfo->memsize = wkupinfo->memsize; msginfo->actpts = wkupinfo->actpts; } htab_lock.AutoLWLockRelease(); t_thrd.wlm_cxt.parctl_state.central_waiting = 0; /* record the wait count in central queue */ if (t_thrd.wlm_cxt.parctl_state.reserve && !t_thrd.wlm_cxt.parctl_state.transact && !t_thrd.wlm_cxt.parctl_state.subquery) { USE_CONTEXT_LOCK(&g_climgr->statement_list_mutex); if (g_climgr->central_waiting_count) { g_climgr->central_waiting_count--; reserved_in_central_waiting--; ereport(DEBUG3, (errmsg("---OVERRUN dywlm_client_wait() release --- " "active_statements: %d, central_waiting_count: %d, max_active_statements: %d.\n", g_climgr->active_statements, g_climgr->central_waiting_count, g_climgr->max_active_statements))); } } pgstat_report_waiting_on_resource(STATE_NO_ENQUEUE); pgstat_report_statement_wlm_status(); if ((t_thrd.wlm_cxt.parctl_state.transact || t_thrd.wlm_cxt.parctl_state.subquery || COMP_ACC_CLUSTER) && !info->wakeup) { msginfo->qtype = PARCTL_RELEASE; msginfo->isserver = is_pgxc_central_nodename(g_instance.attr.attr_common.PGXCNodeName); etype = dywlm_client_send(g_climgr, msginfo); ereport(DEBUG2, (errmsg("send qid [%u, %lu, %ld] to release transaction block, etype: %d", msginfo->qid.procId, msginfo->qid.queryId, msginfo->qid.stamp, etype))); t_thrd.wlm_cxt.parctl_state.enqueue = 0; t_thrd.wlm_cxt.parctl_state.rp_release = 1; u_sess->wlm_cxt->forced_running = true; if (COMP_ACC_CLUSTER) { acce_not_enough_resource = true; } return 0; } return 1; } /* * @Description: remove the node from waiting list * @IN ptr: the node will be removed * @Return: void * @See also: */ void dywlm_client_max_clean(void* ptr) { Assert(ptr != NULL); Assert(t_thrd.wlm_cxt.thread_climgr != NULL); t_thrd.wlm_cxt.thread_climgr->statements_waiting_list = list_delete_ptr(t_thrd.wlm_cxt.thread_climgr->statements_waiting_list, ptr); pfree(ptr); t_thrd.wlm_cxt.parctl_state.preglobal_waiting = 0; return; } /* * @Description: if resource is limited * @IN: void * @Return: bool * @See also: dywlm_client_max_reserve */ bool dywlm_is_resource_limited(void) { ClientDynamicManager* g_climgr = t_thrd.wlm_cxt.thread_climgr; ereport(DEBUG3, (errmsg("---OVERRUN dywlm_is_resource_limited()--- " "active_statements: %d, central_waiting_count: %d, max_active_statements: %d.\n", g_climgr->active_statements, g_climgr->central_waiting_count, g_climgr->max_active_statements))); if ((g_climgr->active_statements >= g_climgr->max_active_statements && g_climgr->active_statements >= g_climgr->central_waiting_count && (g_climgr->active_statements - g_climgr->central_waiting_count) >= g_climgr->max_active_statements) || (u_sess->wlm_cxt->query_count_record == false && g_climgr->max_support_statements > 0 && g_climgr->current_support_statements >= g_climgr->max_support_statements)) { /* example: WLMmonitorDeviceStat.maxCpuUtil >= CPU_UTIL_THRESHOLD || * WLMmonitorDeviceStat.maxIOUtil >= IO_UTIL_THRESHOLD */ return true; } return false; } /* * @Description: CN reserve max resource * @IN: void * @Return: void * @See alsO: */ void dywlm_client_max_reserve(void) { ClientDynamicManager* g_climgr = t_thrd.wlm_cxt.thread_climgr; Assert(g_climgr != NULL); if (!t_thrd.wlm_cxt.parctl_state.enqueue) { return; } if (IsTransactionBlock()) { if (!u_sess->wlm_cxt->is_reserved_in_transaction) { u_sess->wlm_cxt->is_reserved_in_transaction = true; t_thrd.wlm_cxt.parctl_state.reserve = 1; } return; } /* while max_active_statements less than 0, do not control */ if (g_climgr->max_active_statements <= 0) { return; } WLMContextLock list_lock(&g_climgr->statement_list_mutex); list_lock.Lock(); if (u_sess->wlm_cxt->reserved_in_active_statements > 0) { ereport(LOG, (errmsg("When new query is arriving, thread is reserved %d statement and " "the reserved debug query is %s.", u_sess->wlm_cxt->reserved_in_active_statements, u_sess->wlm_cxt->reserved_debug_query))); g_climgr->active_statements = (g_climgr->active_statements > u_sess->wlm_cxt->reserved_in_active_statements) ? (g_climgr->active_statements - u_sess->wlm_cxt->reserved_in_active_statements) : 0; u_sess->wlm_cxt->reserved_in_active_statements = 0; } /* Check if the central waiting count is changed */ if (reserved_in_central_waiting > 0) { ereport(LOG, (errmsg("When new query is waiting in central, thread is reserved %d statement and " "the reserved debug query is %s.", reserved_in_central_waiting, u_sess->wlm_cxt->reserved_debug_query))); g_climgr->central_waiting_count = (g_climgr->central_waiting_count > reserved_in_central_waiting) ? (g_climgr->central_waiting_count - reserved_in_central_waiting) : 0; reserved_in_central_waiting = 0; } if (g_climgr->max_statements > 0 && (list_length(g_climgr->statements_waiting_list) >= g_climgr->max_statements)) { list_lock.UnLock(); ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("the counts of waiting statements have reached the limitation."))); } /* * statement will insert waiting list when active statements up * to max_active_statements. And if cpu or io utility is up to * threshold, statement will insert waiting list too. */ if (dywlm_is_resource_limited()) { pgstat_report_waiting_on_resource(STATE_ACTIVE_STATEMENTS); MemoryContext oldContext = MemoryContextSwitchTo(g_instance.wlm_cxt->workload_manager_mcxt); DynamicInfoNode* info = (DynamicInfoNode*)palloc0_noexcept(sizeof(DynamicInfoNode)); if (info == NULL) { list_lock.UnLock(); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory of current memory."))); } info->condition = (pthread_cond_t)PTHREAD_COND_INITIALIZER; g_climgr->statements_waiting_list = lappend(g_climgr->statements_waiting_list, info); (void)MemoryContextSwitchTo(oldContext); list_lock.set(dywlm_client_max_clean, info); t_thrd.wlm_cxt.parctl_state.preglobal_waiting = 1; pgstat_report_statement_wlm_status(); do { bool ImmediateInterruptOK_Old = t_thrd.int_cxt.ImmediateInterruptOK; PG_TRY(); { CHECK_FOR_INTERRUPTS(); t_thrd.int_cxt.ImmediateInterruptOK = true; list_lock.ConditionWait(&info->condition); t_thrd.int_cxt.ImmediateInterruptOK = ImmediateInterruptOK_Old; } PG_CATCH(); { t_thrd.int_cxt.ImmediateInterruptOK = ImmediateInterruptOK_Old; /* we must make sure we have the lock now */ if (!list_lock.IsOwner()) { list_lock.Lock(true); } /* clean the info in the list */ list_lock.UnLock(); PG_RE_THROW(); } PG_END_TRY(); } while (dywlm_is_resource_limited()); list_lock.clean(); t_thrd.wlm_cxt.parctl_state.preglobal_waiting = 0; } g_climgr->active_statements++; u_sess->wlm_cxt->reserved_in_active_statements++; ereport(DEBUG3, (errmsg("---OVERRUN dywlm_client_max_reserve() --- " "active_statements: %d, central_waiting_count: %d, max_active_statements: %d.\n", g_climgr->active_statements, g_climgr->central_waiting_count, g_climgr->max_active_statements))); if (u_sess->wlm_cxt->query_count_record == false) { u_sess->wlm_cxt->query_count_record = true; g_climgr->current_support_statements++; } /* reserved the string for later checking */ if (t_thrd.postgres_cxt.debug_query_string) { int rcs = snprintf_truncated_s(u_sess->wlm_cxt->reserved_debug_query, sizeof(u_sess->wlm_cxt->reserved_debug_query), "%s", t_thrd.postgres_cxt.debug_query_string); securec_check_ss(rcs, "\0", "\0"); } u_sess->wlm_cxt->wlm_debug_info.active_statement = g_climgr->active_statements; pgstat_report_waiting_on_resource(STATE_NO_ENQUEUE); t_thrd.wlm_cxt.parctl_state.reserve = 1; pgstat_report_statement_wlm_status(); list_lock.UnLock(); } void dywlm_client_release_statement() { if ((IS_PGXC_COORDINATOR || IS_SINGLE_NODE) && t_thrd.wlm_cxt.collect_info->sdetail.statement) { pfree_ext( t_thrd.wlm_cxt.collect_info->sdetail.statement); } return; } bool dywlm_is_local_node() { if ((IS_PGXC_COORDINATOR && !IsConnFromCoord()) || IS_SINGLE_NODE) { return true; } return false; } /* * @Description: CN release resource when statements finish * @IN: state: parallel control state * @Return: void * @See also: */ void dywlm_client_max_release(ParctlState* state) { ClientDynamicManager* g_climgr = t_thrd.wlm_cxt.thread_climgr; /* handle exception */ if (state->except) { WLMResetStatInfo4Exception(); state->except = 0; } if (state->release || !state->reserve) { dywlm_client_release_statement(); return; } if (dywlm_is_local_node() && (u_sess->wlm_cxt->parctl_state_exit || !IsTransactionBlock())) { Assert(g_climgr != NULL); WLMContextLock list_lock(&g_climgr->statement_list_mutex); list_lock.Lock(); /* * It will wake up a statement if there are * statements waiting in the statements waiting * list due to the number of active statements * is more than max_active_statements. */ if (list_length(g_climgr->statements_waiting_list) > 0 && g_climgr->max_support_statements > 0 && g_climgr->current_support_statements < g_climgr->max_support_statements) { /* && WLMmonitorDeviceStat.maxCpuUtil < CPU_UTIL_THRESHOLD && WLMmonitorDeviceStat.maxIOUtil < IO_UTIL_THRESHOLD */ DynamicInfoNode* info = (DynamicInfoNode*)linitial(g_climgr->statements_waiting_list); if (info != NULL) { list_lock.ConditionWakeUp(&info->condition); } } if (g_climgr->active_statements > 0) { g_climgr->active_statements--; u_sess->wlm_cxt->reserved_in_active_statements--; ereport(DEBUG3, (errmsg("---OVERRUN dywlm_client_max_release() --- " "active_statements: %d, central_waiting_count: %d, max_active_statements: %d.\n", g_climgr->active_statements, g_climgr->central_waiting_count, g_climgr->max_active_statements))); } state->release = 1; if (u_sess->wlm_cxt->is_reserved_in_transaction) { u_sess->wlm_cxt->is_reserved_in_transaction = false; } list_lock.UnLock(); if (u_sess->wlm_cxt->parctl_state_exit == 0) { pgstat_report_statement_wlm_status(); } } dywlm_client_release_statement(); } /* clean the active statements counts when thread is exiting */ void dywlm_client_proc_release(void) { ClientDynamicManager* g_climgr = t_thrd.wlm_cxt.thread_climgr; WLMContextLock list_lock(&g_climgr->statement_list_mutex); list_lock.Lock(); if (u_sess->wlm_cxt->query_count_record) { u_sess->wlm_cxt->query_count_record = false; g_climgr->current_support_statements--; /* try to wake if it is suspend by max support statements */ if (g_climgr->max_support_statements > 0 && (g_climgr->max_support_statements - g_climgr->current_support_statements == 1) && list_length(g_climgr->statements_waiting_list) > 0) { DynamicInfoNode* info = (DynamicInfoNode*)linitial(g_climgr->statements_waiting_list); if (info != NULL) { list_lock.ConditionWakeUp(&info->condition); } } } if (u_sess->wlm_cxt->reserved_in_active_statements > 0) { ereport(LOG, (errmsg("When thread is exited, thread is reserved %d global statement and " "the reserved debug query is %s.", u_sess->wlm_cxt->reserved_in_active_statements, u_sess->wlm_cxt->reserved_debug_query))); g_climgr->active_statements = (g_climgr->active_statements > u_sess->wlm_cxt->reserved_in_active_statements) ? (g_climgr->active_statements - u_sess->wlm_cxt->reserved_in_active_statements) : 0; u_sess->wlm_cxt->reserved_in_active_statements = 0; } if (reserved_in_central_waiting > 0) { ereport(LOG, (errmsg("When new query is exited and waiting in central, thread is reserved %d statement and " "the reserved debug query is %s.", reserved_in_central_waiting, u_sess->wlm_cxt->reserved_debug_query))); g_climgr->central_waiting_count = (g_climgr->central_waiting_count > reserved_in_central_waiting) ? (g_climgr->central_waiting_count - reserved_in_central_waiting) : 0; reserved_in_central_waiting = 0; } list_lock.UnLock(); } /* * @Description: update max_active_statements for one node group * @IN climgr: the information of one node group * @IN active_statements: new value of max_active_statements * @Return: void * @See also: */ void dywlm_update_max_statements_internal(ClientDynamicManager* climgr, int active_statements) { WLMContextLock list_lock(&climgr->statement_list_mutex); list_lock.Lock(); int old_active_statements = climgr->max_active_statements; int num_wake_up = active_statements - old_active_statements; climgr->max_active_statements = active_statements; climgr->max_statements = t_thrd.utils_cxt.gs_mp_inited ? (MAX_PARCTL_MEMORY * DYWLM_HIGH_QUOTA / FULL_PERCENT - active_statements * g_instance.wlm_cxt->parctl_process_memory) / PARCTL_MEMORY_UNIT : 0; /* If the new value of max_active_statements is larger than previous, * and there are statements waiting in waiting list, try to wake it up, * until active statements is up to new max_active_statements. */ while (num_wake_up-- > 0 && list_length(climgr->statements_waiting_list)) { DynamicInfoNode* info = (DynamicInfoNode*)linitial(climgr->statements_waiting_list); if (info != NULL) { list_lock.ConditionWakeUp(&info->condition); } } list_lock.UnLock(); } /* * @Description: update max_active_statements * @IN active_statements: new value of max_active_statements * @Return: void * @See also: */ void dywlm_update_max_statements(int active_statements) { ClientDynamicManager* climgr = &g_instance.wlm_cxt->MyDefaultNodeGroup.climgr; if (AmPostmasterProcess()) { dywlm_update_max_statements_internal(climgr, active_statements); } else if (AmWLMWorkerProcess()) { USE_AUTO_LWLOCK(WorkloadNodeGroupLock, LW_SHARED); WLMNodeGroupInfo* hdata = NULL; HASH_SEQ_STATUS hash_seq; hash_seq_init(&hash_seq, g_instance.wlm_cxt->stat_manager.node_group_hashtbl); while ((hdata = (WLMNodeGroupInfo*)hash_seq_search(&hash_seq)) != NULL) { if (!hdata->used) { continue; } climgr = &hdata->climgr; dywlm_update_max_statements_internal(climgr, active_statements); } } } /* * @Description: client reserve resource * @IN void * @Return: 1 - global reserved * 0 - global reserved failed * @See also: */ void dywlm_client_reserve(QueryDesc* queryDesc, bool isQueryDesc) { /* need not do enqueue */ if (!t_thrd.wlm_cxt.parctl_state.enqueue || t_thrd.wlm_cxt.parctl_state.simple || !IsQueuedSubquery()) { return; } WLMGeneralParam* g_wlm_params = &u_sess->wlm_cxt->wlm_params; if (g_wlm_params->rpdata.max_pts > 0 && g_wlm_params->rpdata.mem_size > 0) { Assert((g_wlm_params->memsize * KBYTES) <= g_wlm_params->rpdata.mem_size && (g_wlm_params->max_memsize * KBYTES) <= g_wlm_params->rpdata.mem_size && g_wlm_params->memsize <= g_wlm_params->max_memsize && (g_wlm_params->min_memsize * KBYTES) <= g_wlm_params->rpdata.mem_size && g_wlm_params->rpdata.act_pts <= g_wlm_params->rpdata.max_pts && g_wlm_params->rpdata.max_act_pts <= g_wlm_params->rpdata.max_pts && g_wlm_params->rpdata.min_act_pts <= g_wlm_params->rpdata.max_pts); } DynamicMessageInfo msginfo; ClientDynamicManager* g_climgr = t_thrd.wlm_cxt.thread_climgr; if (t_thrd.wlm_cxt.parctl_state.transact) { (void)dywlm_client_initmsg(g_climgr, &msginfo, PARCTL_TRANSACT); } else { (void)dywlm_client_initmsg(g_climgr, &msginfo, PARCTL_RESERVE); } if (IsQidInvalid(&msginfo.qid)) { return; } int ret = dywlm_client_wait(&msginfo); ereport(DEBUG3, (errmsg("ID[%u,%lu,%ld] -----DYWLM_client_reserve-----" "Memsize[current:%d, max:%d, min:%d]", msginfo.qid.procId, msginfo.qid.queryId, msginfo.qid.stamp, msginfo.memsize, msginfo.max_memsize, msginfo.min_memsize))); /* If return value does not match with the optimizer, we should report the current value. */ if (msginfo.memsize > msginfo.max_memsize || msginfo.memsize < msginfo.min_memsize) { ereport(LOG, (errmsg("WARNING: ID[%u,%lu,%ld] return value not match in dywlm_client_reserve," "Memsize[current:%d, max:%d, min:%d]", msginfo.qid.procId, msginfo.qid.queryId, msginfo.qid.stamp, msginfo.memsize, msginfo.max_memsize, msginfo.min_memsize))); } g_wlm_params->memsize = msginfo.memsize; g_wlm_params->rpdata.act_pts = msginfo.actpts; if (ret == 0) { dywlm_info_unregister(); } else { t_thrd.wlm_cxt.parctl_state.rp_reserve = 1; USE_CONTEXT_LOCK(&g_climgr->statement_list_mutex); g_climgr->running_count++; } /* Now the estimated memsize has been determined, the plan should be generated * For CalculateQueryMemMain() called by dywlm, we excute all 3 phases. */ bool use_tenant = (g_wlm_params->rpdata.rpoid != DEFAULT_POOL_OID); if (queryDesc && (WLMGetQueryMem(queryDesc, isQueryDesc) > MEM_THRESHOLD * 1024)) { g_wlm_params->memsize = Max(Min(g_wlm_params->max_memsize, g_wlm_params->memsize), g_wlm_params->min_memsize); if (g_wlm_params->memsize != g_wlm_params->max_memsize) { if (isQueryDesc && queryDesc->plannedstmt != NULL) { queryDesc->plannedstmt->assigned_query_mem[1] = g_wlm_params->memsize * 1024; } else { ((UtilityDesc*)queryDesc)->assigned_mem = g_wlm_params->memsize * 1024; } } ereport(DEBUG3, (errmsg("REGENERATE PLAN[%d,%d,%d]", g_wlm_params->memsize, g_wlm_params->max_memsize, g_wlm_params->min_memsize))); if (isQueryDesc != false && queryDesc != NULL && queryDesc->plannedstmt) { CalculateQueryMemMain(queryDesc->plannedstmt, use_tenant, true); t_thrd.shemem_ptr_cxt.mySessionMemoryEntry->estimate_memory = (unsigned int)WLMGetQueryMem(queryDesc, isQueryDesc) >> BITS_IN_KB; } } } /* * @Description: client release resource * @IN state: parctl state * @Return: void * @See also: */ void dywlm_client_release(ParctlState* state) { /* If it has been released, ignore this time. */ if (state == NULL || state->rp_release) { return; } ClientDynamicManager* g_climgr = t_thrd.wlm_cxt.thread_climgr; /* * It will release active statement if it has done * dynamic workload parallel control. */ if (state->enqueue && state->rp_reserve && ((IS_PGXC_COORDINATOR && !IsConnFromCoord()) || IS_SINGLE_NODE)) { dywlm_info_unregister(); if (!state->errjmp) { DynamicMessageInfo msginfo; (void)dywlm_client_initmsg(g_climgr, &msginfo, PARCTL_RELEASE); EnqueueType etype = dywlm_client_send(g_climgr, &msginfo); ereport(DEBUG2, (errmsg("send qid [%u, %lu, %ld] to release, etype: %d", msginfo.qid.procId, msginfo.qid.queryId, msginfo.qid.stamp, etype))); } state->rp_release = 1; // remove the counting when query is terminated if (g_climgr->running_count > 0) { USE_CONTEXT_LOCK(&g_climgr->statement_list_mutex); g_climgr->running_count--; } } /* handle exception */ if (state->except) { WLMResetStatInfo4Exception(); state->except = 0; } } /* * @Description: client reserve message from the server * @IN msg: message string info * @Return: void * @See also: */ void dywlm_client_receive(StringInfo msg) { int retcode = 0; DynamicMessageInfo recvinfo; errno_t errval = memset_s(&recvinfo, sizeof(recvinfo), 0, sizeof(recvinfo)); securec_check_errval(errval, , LOG); /* parse message to message detail info */ dywlm_client_parse_message(msg, &recvinfo); /* get the client manager based on node group name */ WLMNodeGroupInfo* ng = WLMGetNodeGroupFromHTAB(recvinfo.groupname); if (NULL == ng) { ereport(LOG, (errmsg("failed to get the nodegroup %s from htab.", recvinfo.groupname))); dywlm_client_reply(DYWLM_NO_NGROUP); return; } if (recvinfo.qtype == PARCTL_SYNC) { /* reply all workload records to server */ dywlm_client_reply_records(&ng->climgr); return; } else { if (strcmp(recvinfo.nodename, g_instance.attr.attr_common.PGXCNodeName) != 0) { ereport(LOG, (errmsg("node name %s received is not matched current node %s", recvinfo.nodename, g_instance.attr.attr_common.PGXCNodeName))); dywlm_client_reply(DYWLM_SEND_FAILED); return; } /* wake up the query to execute on the client */ retcode = dywlm_client_post(&ng->climgr, &recvinfo); } ereport(DEBUG2, (errmsg("reply retcode: %d", retcode))); /* reply 'w' message to server */ dywlm_client_reply(retcode); } /* * @Description: find statement by ThreadId * @IN tid: the ThreadId of statement * @Return: info node in the hash * @See also: */ DynamicInfoNode* dywlm_client_search_node(ClientDynamicManager* climgr, ThreadId tid) { DynamicInfoNode* node = NULL; HASH_SEQ_STATUS hstat; /* search the statment hash table to find statement */ hash_seq_init(&hstat, climgr->dynamic_info_hashtbl); USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); /* search hash to find thread id */ while ((node = (DynamicInfoNode*)hash_seq_search(&hstat)) != NULL) { if (node->threadid == tid) { hash_seq_term(&hstat); break; } } return node; } /* * @Description: client handle move node to list * @IN ng: the node group info * qid: the qid of statement will be moved * cgroup: new cgroup * @Return: * @See also: */ void dywlm_client_move_node_to_list(void* ng, uint64 tid, const char* cgroup) { DynamicMessageInfo msginfo; WLMNodeGroupInfo* tmpng = (WLMNodeGroupInfo*)ng; errno_t errval = memset_s(&msginfo, sizeof(DynamicMessageInfo), 0, sizeof(DynamicMessageInfo)); securec_check_errval(errval, , LOG); DynamicInfoNode* node = dywlm_client_search_node(&tmpng->climgr, tid); /* cannot find the statement in the hash */ if (node == NULL) { ereport(LOG, (errmsg("statement %lu is not in waiting list", tid))); return; } msginfo.qid = node->qid; msginfo.priority = gscgroup_get_percent(tmpng, cgroup); msginfo.qtype = PARCTL_MVNODE; errval = strncpy_s(msginfo.groupname, sizeof(msginfo.groupname), node->ngroup, sizeof(msginfo.groupname) - 1); securec_check_errval(errval, , LOG); EnqueueType etype = dywlm_client_send(&tmpng->climgr, &msginfo); /* send message info the server */ if (etype == ENQUEUE_RECOVERY) { ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("Central node is recovering now, please retry later."))); } if (etype == ENQUEUE_GROUPERR) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Central Node cannot get node group %s", msginfo.groupname))); } return; } /* * @Description: client handle jump priority * @IN qid: the qid of statement will jump to highest priority * @Return: * @See also: */ int dywlm_client_jump_queue(ClientDynamicManager* climgr, ThreadId tid) { if (!superuser()) { ereport(NOTICE, (errmsg("Only super user can change the queue."))); return 0; } DynamicMessageInfo msginfo; errno_t errval = memset_s(&msginfo, sizeof(DynamicMessageInfo), 0, sizeof(DynamicMessageInfo)); securec_check_errval(errval, , LOG); DynamicInfoNode* node = dywlm_client_search_node(climgr, tid); /* cannot find the statement in the hash */ if (node == NULL) { ereport(LOG, (errmsg("statement %lu in not in waiting list", tid))); return -1; } msginfo.qid = node->qid; msginfo.qtype = PARCTL_JPQUEUE; errval = strncpy_s(msginfo.groupname, sizeof(msginfo.groupname), node->ngroup, sizeof(msginfo.groupname) - 1); securec_check_errval(errval, , LOG); EnqueueType etype = dywlm_client_send(climgr, &msginfo); /* send message to server */ if (etype == ENQUEUE_RECOVERY) { ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("Central node is recovering now, please retry later."))); } if (etype == ENQUEUE_GROUPERR) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Central node cannot get node group %s", msginfo.groupname))); } return 0; } /* * @Description: recover client enqueue list * @IN void * @Return: void * @See also: */ void dywlm_client_recover(ClientDynamicManager* climgr) { if (climgr->recover) { return; } ereport(LOG, (errmsg("client recover start"))); climgr->recover = true; /* restore the records */ DynamicMessageInfo msginfo; (void)dywlm_client_initmsg(climgr, &msginfo, PARCTL_CLEAN); if (dywlm_client_send(climgr, &msginfo) == ENQUEUE_ERROR) { climgr->recover = false; ereport(ERROR, (errcode(ERRCODE_SYSTEM_ERROR), errmsg("client recover failed"))); } ereport(LOG, (errmsg("client recover end"))); climgr->recover = false; } /* * @Description: get client physical info * @OUT total_mem: total physical memory size * @OUT free_mem: free physical memory size * @return: 0 success -1 failed * @See also: */ int dywlm_client_physical_info(int* total_mem, int* free_mem) { FILE* fp = NULL; char buf[KBYTES]; const char* file = "/proc/meminfo"; /* open system file to read memory infomation */ if ((fp = fopen(file, "rb")) == NULL) { return -1; } int count = 0; /* read each line */ while (NULL != fgets(buf, KBYTES, fp)) { /* read total memory */ if (strstr(buf, "MemTotal") != NULL) { char* p = strchr(buf, ':'); if (p == NULL) { fclose(fp); return -1; } *total_mem = (int)strtol(p + 1, NULL, 10) / KBYTES; ++count; } else if (strstr(buf, "MemFree") != NULL) { /* read free memory */ char* p = strchr(buf, ':'); if (p == NULL) { fclose(fp); return -1; } *free_mem = (int)strtol(p + 1, NULL, 10) / KBYTES; ++count; } /* total memory and free memory get OK, finish reading */ if (count == 2) { break; } } fclose(fp); return count - 2; } /* * @Description: get all records from server node * @OUT num: number of the records * @Return: records list * @See also: */ DynamicWorkloadRecord* dywlm_client_get_records(ClientDynamicManager* climgr, int* num) { DynamicWorkloadRecord* records = NULL; PGXCNodeHandle* ccn_handle = NULL; PGXCNodeAllHandles* pgxc_handles = NULL; ServerDynamicManager* srvmgr = (ServerDynamicManager*)climgr->srvmgr; DynamicMessageInfo sendinfo; errno_t errval = memset_s(&sendinfo, sizeof(sendinfo), 0, sizeof(sendinfo)); securec_check_errval(errval, , LOG); sendinfo.qtype = PARCTL_SYNC; errval = strncpy_s(sendinfo.nodename, sizeof(sendinfo.nodename), g_instance.attr.attr_common.PGXCNodeName, sizeof(sendinfo.nodename) - 1); securec_check_errval(errval, , LOG); errval = strncpy_s(sendinfo.groupname, sizeof(sendinfo.groupname), srvmgr->group_name, sizeof(sendinfo.groupname) - 1); securec_check_errval(errval, , LOG); struct timeval timeout = {300, 0}; int codeidx = 0; /* connect to server with message info */ if (!dywlm_client_connect(&pgxc_handles, &ccn_handle, &codeidx, &sendinfo)) { release_pgxc_handles(pgxc_handles); ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("[DYWLM] Failed to send dynamic workload params to CCN!"))); } /* current node is server, get records directly */ if (sendinfo.isserver) { return dywlm_server_get_records(srvmgr, sendinfo.nodename, num); } int retcode = 0; int offset = 0; bool hasError = false; bool isFinished = false; /* receive message */ while (!pgxc_node_receive(1, &ccn_handle, &timeout)) { char* msg = NULL; int len; char msg_type; msg_type = get_message(ccn_handle, &len, &msg); switch (msg_type) { case '\0': /* message is not completed */ case 'E': /* message is error */ hasError = true; break; case 'n': /* the number of records */ { errno_t errval = memcpy_s(&retcode, sizeof(int), msg, 4); securec_check_errval(errval, , LOG); retcode = (int)ntohl(retcode); if (retcode != 0) { records = (DynamicWorkloadRecord*)palloc0_noexcept(retcode * sizeof(DynamicWorkloadRecord)); if (records == NULL) { ccn_handle->state = DN_CONNECTION_STATE_IDLE; release_pgxc_handles(pgxc_handles); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory of current node."))); } } break; } case 'r': /* get workload record */ { /* in a while loop, first it will be case n, and then it will enter case r, so the records will not be null */ Assert(records); DynamicWorkloadRecord* record = records + offset; StringInfoData input_msg; initStringInfo(&input_msg); appendBinaryStringInfo(&input_msg, msg, len); /* parse message to get record */ record->qid.procId = (Oid)pq_getmsgint(&input_msg, 4); record->qid.queryId = (uint64)pq_getmsgint64(&input_msg); record->qid.stamp = (TimestampTz)pq_getmsgint64(&input_msg); record->memsize = pq_getmsgint(&input_msg, 4); record->max_memsize = pq_getmsgint(&input_msg, 4); record->min_memsize = pq_getmsgint(&input_msg, 4); record->actpts = pq_getmsgint(&input_msg, 4); record->max_actpts = pq_getmsgint(&input_msg, 4); record->min_actpts = pq_getmsgint(&input_msg, 4); record->maxpts = pq_getmsgint(&input_msg, 4); record->priority = pq_getmsgint(&input_msg, 4); record->qtype = (ParctlType)pq_getmsgint(&input_msg, 4); errno_t errval = strncpy_s( record->rpname, sizeof(record->rpname), pq_getmsgstring(&input_msg), sizeof(record->rpname) - 1); securec_check_errval(errval, , LOG); errval = strncpy_s( record->nodename, sizeof(record->rpname), pq_getmsgstring(&input_msg), sizeof(record->rpname) - 1); securec_check_errval(errval, , LOG); errval = strncpy_s(record->groupname, sizeof(record->groupname), pq_getmsgstring(&input_msg), sizeof(record->groupname) - 1); securec_check_errval(errval, , LOG); pq_getmsgend(&input_msg); pfree(input_msg.data); ++offset; break; } case 'f': /* message is completed */ { errno_t errval = memcpy_s(num, sizeof(int), msg, 4); securec_check_errval(errval, , LOG); *num = (int)ntohl(*num); ereport(DEBUG2, (errmsg("finish receive record count: %d", *num))); if (retcode != *num) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("dynamic workload record number is not correct!"))); } isFinished = true; break; } case 'Z': if (hasError) { isFinished = true; } break; case 'A': /* NotificationResponse */ case 'S': /* SetCommandComplete */ { /* * Ignore these to prevent multiple messages, one from * each node. Coordinator will send on for DDL anyway */ break; } default: break; } /* error occurred or receive finished, stop looping */ if (isFinished) { break; } } ccn_handle->state = DN_CONNECTION_STATE_IDLE; release_pgxc_handles(pgxc_handles); return records; } bool dywlm_is_server_or_single_node() { if (PgxcIsCentralCoordinator(g_instance.attr.attr_common.PGXCNodeName) || IS_SINGLE_NODE) { return true; } return false; } /* * @Description: handle of getting all records * @IN num: entry count of the hash table * @Return: records list * @See also: */ DynamicWorkloadRecord* dywlm_get_records(int* num) { *num = 0; if (!g_instance.wlm_cxt->dynamic_workload_inited) { return NULL; } int count = 100; // default count int tmpnum = 0; errno_t rc = 0; bool flag = false; DynamicWorkloadRecord* tmprecord = NULL; DynamicWorkloadRecord* array = (DynamicWorkloadRecord*)palloc0(count * sizeof(DynamicWorkloadRecord)); /* check whether current node is server */ if (dywlm_is_server_or_single_node()) { tmprecord = dywlm_server_get_records( &g_instance.wlm_cxt->MyDefaultNodeGroup.srvmgr, g_instance.attr.attr_common.PGXCNodeName, num); } else { tmprecord = dywlm_client_get_records(&g_instance.wlm_cxt->MyDefaultNodeGroup.climgr, num); } if (*num > 0 && tmprecord != NULL) { while (*num >= count) { count *= 2; flag = true; } if (flag) { array = (DynamicWorkloadRecord*)repalloc(array, count * sizeof(DynamicWorkloadRecord)); } rc = memcpy_s(array, count * sizeof(DynamicWorkloadRecord), tmprecord, *num * sizeof(DynamicWorkloadRecord)); securec_check(rc, "\0", "\0"); } if (tmprecord != NULL) { pfree_ext(tmprecord); } USE_AUTO_LWLOCK(WorkloadNodeGroupLock, LW_SHARED); WLMNodeGroupInfo* hdata = NULL; HASH_SEQ_STATUS hash_seq; hash_seq_init(&hash_seq, g_instance.wlm_cxt->stat_manager.node_group_hashtbl); while ((hdata = (WLMNodeGroupInfo*)hash_seq_search(&hash_seq)) != NULL) { /* skip unused node group and elastic group */ if (!hdata->used || pg_strcasecmp(VNG_OPTION_ELASTIC_GROUP, hdata->group_name) == 0) { continue; } /* check whether current node is server */ if (dywlm_is_server_or_single_node()) { tmprecord = dywlm_server_get_records(&hdata->srvmgr, g_instance.attr.attr_common.PGXCNodeName, &tmpnum); } else { tmprecord = dywlm_client_get_records(&hdata->climgr, &tmpnum); } if (tmpnum > 0 && tmprecord != NULL) { while ((*num + tmpnum) >= count) { count *= 2; flag = true; } if (flag) { array = (DynamicWorkloadRecord*)repalloc(array, count * sizeof(DynamicWorkloadRecord)); } rc = memcpy_s(array + *num * sizeof(DynamicWorkloadRecord), (count - *num) * sizeof(DynamicWorkloadRecord), tmprecord, tmpnum * sizeof(DynamicWorkloadRecord)); securec_check(rc, "\0", "\0"); *num += tmpnum; } if (tmprecord != NULL) { pfree_ext(tmprecord); } } return array; } /* * @Description: client dynamic workload manager * @IN void * @Return: void * @See also: */ void dywlm_client_manager(QueryDesc* queryDesc, bool isQueryDesc) { bool force_control = false; u_sess->wlm_cxt->forced_running = false; if (t_thrd.wlm_cxt.parctl_state.subquery == 1) { t_thrd.wlm_cxt.parctl_state.rp_reserve = 0; t_thrd.wlm_cxt.parctl_state.rp_release = 0; t_thrd.wlm_cxt.parctl_state.release = 0; WLMSetCollectInfoStatus(WLM_STATUS_PENDING); } if (t_thrd.wlm_cxt.collect_info->status == WLM_STATUS_RUNNING) { return; } if (u_sess->wlm_cxt->is_active_statements_reset) { t_thrd.wlm_cxt.parctl_state.rp_reserve = 0; t_thrd.wlm_cxt.parctl_state.rp_release = 0; t_thrd.wlm_cxt.parctl_state.release = 0; WLMSetCollectInfoStatus(WLM_STATUS_PENDING); } WLMGeneralParam* g_wlm_params = &u_sess->wlm_cxt->wlm_params; /* get the user info */ if (u_sess->attr.attr_resource.enable_force_memory_control && OidIsValid(g_wlm_params->rpdata.rpoid) && (g_wlm_params->rpdata.rpoid != DEFAULT_POOL_OID) && (g_wlm_params->rpdata.mem_size > SIMPLE_THRESHOLD)) { UserData* userdata = GetUserDataFromHTab(GetUserId(), false); int memsize = (unsigned int)g_wlm_params->rpdata.mem_size >> BITS_IN_KB; if (userdata && (userdata->memsize > memsize)) { ereport(LOG, (errmsg("user used memory is %d MB, resource pool memory is %d MB. " "So to control the simple query now.", userdata->memsize, memsize))); force_control = true; } } t_thrd.wlm_cxt.parctl_state.simple = WLMIsSimpleQuery(queryDesc, force_control, isQueryDesc) ? 1 : 0; /* update transact state for begin...end query */ t_thrd.wlm_cxt.parctl_state.transact = IsTransactionBlock() ? 1 : 0; t_thrd.wlm_cxt.parctl_state.except = 1; t_thrd.wlm_cxt.parctl_state.enqueue = (IsQueuedSubquery() && t_thrd.wlm_cxt.parctl_state.special == 0 && !g_wlm_params->rpdata.superuser) ? 1 : t_thrd.wlm_cxt.parctl_state.enqueue; if (IS_PGXC_COORDINATOR && !IsConnFromCoord()) { g_wlm_params->qid.procId = u_sess->pgxc_cxt.PGXCNodeId; } if (g_instance.wlm_cxt->gscgroup_init_done && !IsAbortedTransactionBlockState()) { WLMSwitchCGroup(); } if (COMP_ACC_CLUSTER && WLMGetInComputePool(queryDesc, isQueryDesc)) { t_thrd.wlm_cxt.parctl_state.simple = 0; t_thrd.wlm_cxt.parctl_state.enqueue = 1; u_sess->wlm_cxt->parctl_state_control = 1; if (IS_PGXC_COORDINATOR) { WLMSetCollectInfoStatus(WLM_STATUS_PENDING); } } if (IS_PGXC_DATANODE) { WLMSetCollectInfoStatus(WLM_STATUS_PENDING); } /* "in_compute_pool == true" means we are in the compute pool. */ if (IS_PGXC_COORDINATOR && ((COMP_ACC_CLUSTER && WLMGetInComputePool(queryDesc, isQueryDesc)) || (!COMP_ACC_CLUSTER && !IsConnFromCoord()))) { if (g_instance.wlm_cxt->dynamic_workload_inited && (t_thrd.wlm_cxt.parctl_state.simple == 0)) { WLMHandleDywlmSimpleExcept(false); dywlm_client_reserve(queryDesc, isQueryDesc); } else { WLMParctlReserve(PARCTL_RESPOOL); } } if (acce_not_enough_resource) { acce_not_enough_resource = false; WLMSetCollectInfoStatus(WLM_STATUS_ABORT); ereport( ERROR, (errcode(ERRCODE_INSUFFICIENT_RESOURCES), errmsg("Can NOT get enough resource for this request."))); } WLMSetCollectInfoStatus(WLM_STATUS_RUNNING); } /* * @Description: client dynamic workload init all fields * @IN void * @Return: void * @See also: */ void dywlm_client_init(WLMNodeGroupInfo* info) { ClientDynamicManager* climgr = &info->climgr; HASHCTL hash_ctl; /* memory size we will use */ const int size = 1; /* MB */ errno_t errval = memset_s(&hash_ctl, sizeof(hash_ctl), 0, sizeof(hash_ctl)); securec_check_errval(errval, , LOG); hash_ctl.keysize = sizeof(Qid); hash_ctl.hcxt = g_instance.wlm_cxt->workload_manager_mcxt; /* use workload manager memory context */ hash_ctl.entrysize = sizeof(DynamicInfoNode); hash_ctl.hash = WLMHashCode; hash_ctl.match = WLMHashMatch; hash_ctl.alloc = WLMAlloc0NoExcept4Hash; hash_ctl.dealloc = pfree; climgr->dynamic_info_hashtbl = hash_create("dywlm register hash table", WORKLOAD_STAT_HASH_SIZE, &hash_ctl, HASH_ELEM | HASH_SHRCTX | HASH_FUNCTION | HASH_COMPARE | HASH_ALLOC | HASH_DEALLOC); climgr->active_statements = 0; climgr->max_info_count = size * MBYTES / sizeof(DynamicInfoNode); climgr->max_active_statements = u_sess->attr.attr_resource.max_active_statements; climgr->max_support_statements = t_thrd.utils_cxt.gs_mp_inited ? (MAX_PARCTL_MEMORY * PARCTL_ACTIVE_PERCENT) / (FULL_PERCENT * g_instance.wlm_cxt->parctl_process_memory) : 0; climgr->max_statements = t_thrd.utils_cxt.gs_mp_inited ? (MAX_PARCTL_MEMORY * DYWLM_HIGH_QUOTA / FULL_PERCENT - climgr->max_active_statements * g_instance.wlm_cxt->parctl_process_memory) / PARCTL_MEMORY_UNIT : 0; climgr->current_support_statements = 0; climgr->central_waiting_count = 0; climgr->usedsize = 0; climgr->cluster = -1; // unused climgr->freesize = 0; climgr->recover = false; climgr->group_name = info->group_name; climgr->srvmgr = (void*)(&info->srvmgr); climgr->statements_waiting_list = NULL; (void)pthread_mutex_init(&climgr->statement_list_mutex, NULL); } /* * @Description: client dynamic verfify resgister info * @IN void * @Return: void * @See also: */ void dywlm_client_verify_register_internal(ClientDynamicManager* climgr, int num_backends) { USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); int i = 0; int count = hash_get_num_entries(climgr->dynamic_info_hashtbl); ereport(DEBUG3, (errmsg("WLMmonitorMain: dywlm_client_verify_register_internal: " "length of climgr->dynamic_info_hashtbl: %d from NG: %s", count, climgr->group_name))); if (count == 0) { return; } DynamicInfoNode* nodes = (DynamicInfoNode*)palloc0(count * sizeof(DynamicInfoNode)); DynamicInfoNode* info = NULL; HASH_SEQ_STATUS hash_seq; hash_seq_init(&hash_seq, climgr->dynamic_info_hashtbl); while ((info = (DynamicInfoNode*)hash_seq_search(&hash_seq)) != NULL) { nodes[i++] = *info; } count = i; RELEASE_AUTO_LWLOCK(); for (i = 0; i < count; ++i) { int j = 0; if (nodes[i].threadid > 0) { for (j = 0; j < num_backends; ++j) { PgBackendStatus* beentry = pgstat_fetch_stat_beentry(j + 1); /* * If the backend thread is valid and the state * is not idle or undefined, we treat it as a active thread. */ if (beentry != NULL && beentry->st_sessionid == nodes[i].qid.queryId && beentry->st_block_start_time == nodes[i].qid.stamp) { break; } } } if (nodes[i].threadid == 0 || j >= num_backends) { USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_EXCLUSIVE); ereport(DEBUG1, (errmsg("VERIFY: remove job info from client record, qid:[%u, %lu, %ld]", nodes[i].qid.procId, nodes[i].qid.queryId, nodes[i].qid.stamp))); hash_search(climgr->dynamic_info_hashtbl, &nodes[i].qid, HASH_REMOVE, NULL); } } pfree(nodes); } /* * @Description: client dynamic verfify resgister info * @IN void * @Return: void * @See also: */ void dywlm_client_verify_register(void) { int num_backends = pgstat_get_backend_entries(); dywlm_client_verify_register_internal(&g_instance.wlm_cxt->MyDefaultNodeGroup.climgr, num_backends); USE_AUTO_LWLOCK(WorkloadNodeGroupLock, LW_SHARED); WLMNodeGroupInfo* hdata = NULL; HASH_SEQ_STATUS hash_seq; hash_seq_init(&hash_seq, g_instance.wlm_cxt->stat_manager.node_group_hashtbl); while ((hdata = (WLMNodeGroupInfo*)hash_seq_search(&hash_seq)) != NULL) { /* skip unused node group and elastic group */ if (!hdata->used || pg_strcasecmp(VNG_OPTION_ELASTIC_GROUP, hdata->group_name) == 0) { continue; } dywlm_client_verify_register_internal(&hdata->climgr, num_backends); } pgstat_reset_current_status(); } /* * @Description: get cpu count * @IN void * @Return: min cpu count * @See also: */ int dywlm_get_cpu_count(void) { USE_AUTO_LWLOCK(WorkloadIOUtilLock, LW_SHARED); return g_instance.wlm_cxt->io_context.WLMmonitorDeviceStat.cpu_count; } /* * @Description: get cpu util * @IN void * @Return: max cpu count * @See also: */ int dywlm_get_cpu_util(void) { USE_AUTO_LWLOCK(WorkloadIOUtilLock, LW_SHARED); return (int)g_instance.wlm_cxt->io_context.WLMmonitorDeviceStat.cpu_util; } /* * @Description: get active statement count of complicated query * @IN void * @Return: active statement count * @See also: */ int dywlm_get_active_statement_count(void) { return t_thrd.wlm_cxt.thread_climgr->running_count; } /* * @Description: display the climgr structure for one node group * @IN void * @Return: Void * @See also: */ void dywlm_client_display_climgr_info_internal(ClientDynamicManager* climgr, StringInfo strinfo) { WLMContextLock list_lock(&climgr->statement_list_mutex); list_lock.Lock(); /* print client dynamic workload state debug info */ appendStringInfo(strinfo, _("active_statements[%d], central_waiting_count[%d], max_active_statements[%d], running_count[%d], " "max_info_count[%d], max_support_statements[%d], current_support_statements[%d], max_statements[%d], " "freesize of DN [%d], usedsize in respool [%d], in recover state[%d], group_name[%s].\n"), climgr->active_statements, climgr->central_waiting_count, climgr->max_active_statements, climgr->running_count, climgr->max_info_count, climgr->max_support_statements, climgr->current_support_statements, climgr->max_statements, climgr->freesize, climgr->usedsize, climgr->recover, climgr->group_name); DynamicInfoNode* info = NULL; int i = 0; foreach_cell(cell, climgr->statements_waiting_list) { info = (DynamicInfoNode*)lfirst(cell); if (info != NULL) { appendStringInfo(strinfo, _("Waiting Global number[%d]: qid.procId[%u], qid.queryId[%lu], qid.stamp[%ld], threadid[%lu], " "memsize[%d], max_memsize[%d], min_memsize[%d], priority[%d], " "actpts[%d], max_actpts[%d], min_actpts[%d], maxpts[%d], rpname[%s], ngroup[%s]\n"), i++, info->qid.procId, info->qid.queryId, info->qid.stamp, info->threadid, info->memsize, info->max_memsize, info->min_memsize, info->priority, info->actpts, info->max_actpts, info->min_actpts, info->maxpts, info->rpname, info->ngroup); } } list_lock.UnLock(); USE_AUTO_LWLOCK(WorkloadStatHashLock, LW_SHARED); int waitcnt = 0; int runcnt = 0; HASH_SEQ_STATUS hash_seq; hash_seq_init(&hash_seq, climgr->dynamic_info_hashtbl); /* scan all records from the client cache for current node */ while ((info = (DynamicInfoNode*)hash_seq_search(&hash_seq)) != NULL) { if (info->wakeup) { appendStringInfo(strinfo, _("Running number[%d]: qid.procId[%u], qid.queryId[%lu], qid.stamp[%ld], threadid[%lu], " "memsize[%d], max_memsize[%d], min_memsize[%d], priority[%d], is_dirty[%d], " "actpts[%d], max_actpts[%d], min_actpts[%d], maxpts[%d], rpname[%s], ngroup[%s]\n"), runcnt++, info->qid.procId, info->qid.queryId, info->qid.stamp, info->threadid, info->memsize, info->max_memsize, info->min_memsize, info->priority, info->is_dirty, info->actpts, info->max_actpts, info->min_actpts, info->maxpts, info->rpname, info->ngroup); } else { appendStringInfo(strinfo, _("Waiting Central number[%d]: qid.procId[%u], qid.queryId[%lu], qid.stamp[%ld], threadid[%lu], " "memsize[%d], max_memsize[%d], min_memsize[%d], priority[%d], is_dirty[%d], " "actpts[%d], max_actpts[%d], min_actpts[%d], maxpts[%d], rpname[%s], ngroup[%s]\n"), waitcnt++, info->qid.procId, info->qid.queryId, info->qid.stamp, info->threadid, info->memsize, info->max_memsize, info->min_memsize, info->priority, info->is_dirty, info->actpts, info->max_actpts, info->min_actpts, info->maxpts, info->rpname, info->ngroup); } } } /* * @Description: display the climgr structure for all node groups * @IN void * @Return: Void * @See also: */ void dywlm_client_display_climgr_info(StringInfo strinfo) { appendStringInfo( strinfo, _("NodeGroup [%s] dynamic client info:\n"), g_instance.wlm_cxt->MyDefaultNodeGroup.group_name); dywlm_client_display_climgr_info_internal(&g_instance.wlm_cxt->MyDefaultNodeGroup.climgr, strinfo); USE_AUTO_LWLOCK(WorkloadNodeGroupLock, LW_SHARED); WLMNodeGroupInfo* hdata = NULL; HASH_SEQ_STATUS hash_seq; hash_seq_init(&hash_seq, g_instance.wlm_cxt->stat_manager.node_group_hashtbl); while ((hdata = (WLMNodeGroupInfo*)hash_seq_search(&hash_seq)) != NULL) { /* skip unused node group and elastic group */ if (!hdata->used || pg_strcasecmp(VNG_OPTION_ELASTIC_GROUP, hdata->group_name) == 0) { continue; } appendStringInfo(strinfo, _("NodeGroup [%s] dynamic client info:\n"), hdata->group_name); dywlm_client_display_climgr_info_internal(&hdata->climgr, strinfo); } }
33.113277
126
0.617671
wotchin
72e664d59e9416fe65c76d37c3f3c0acf8e3d9c9
925
cpp
C++
arc058_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
arc058_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
arc058_b/Main.cpp
s-shirayama/AtCoder
8bb777af516a6a24ce88a5b9f2c22bf4fc7cd3c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define REP(i, n, s) for (int i = (s); i < (n); i++) using namespace std; typedef long long int LL; typedef long double LD; const int MOD = 1e9 + 7; const int MAXN = 1e5 * 2; int nPn[MAXN]; int _pow(int a, int k) { int res = 1; while (k) { // k%1 == 1 if (k & 1) res = LL(res) * a % MOD; a = LL(a) * a % MOD; // k /= 2; k >>= 1; } return res; } int nCr(int n, int r) { // /= A -> *= A^M-2 return LL(nPn[n]) * _pow(LL(nPn[n-r]) * nPn[r] % MOD, MOD - 2) % MOD; } int calc(int h1, int w1, int h2, int w2) { return nCr((h2 - h1) + (w2 - w1), (h2 - h1)); } int main() { int H, W, A, B; scanf("%d %d %d %d", &H, &W, &A, &B); nPn[0] = 1; REP(i, MAXN+1, 1) nPn[i] = LL(i) * nPn[i-1] % MOD; int h = H - A, w = B + 1; int res = 0; while (h >= 1 && w <= W) { res = (LL(res) + LL(calc(1, 1, h, w)) * calc(h, w, H, W)) % MOD; h--, w++; } printf("%d\n", res); return 0; }
18.877551
70
0.473514
s-shirayama
72e6ac7c3343ed61d78d3d0aed0ebeb440d1e052
475
cpp
C++
object oriented programming/modifystring.cpp
ayaankhan98/C-Progamming_basics
0aba46dfe91986e30151bed54eaa7f66d0486c5e
[ "MIT" ]
null
null
null
object oriented programming/modifystring.cpp
ayaankhan98/C-Progamming_basics
0aba46dfe91986e30151bed54eaa7f66d0486c5e
[ "MIT" ]
null
null
null
object oriented programming/modifystring.cpp
ayaankhan98/C-Progamming_basics
0aba46dfe91986e30151bed54eaa7f66d0486c5e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string s1("Quick! Send for count Graystone"); string s2("Lord"); string s3("Don't "); s1.erase(0,7); s1.replace(9,5,s2); s1.replace(0,1,"S"); s1.insert(0,s3); s1.erase(s1.size()-1,1); s1.append(3,'!'); int x = s1.find(' '); while(x<s1.size()) { s1.replace(x,1,"/"); x = s1.find(' '); } cout<<"s1 : "<<s1<<endl; return 0; }
16.964286
49
0.501053
ayaankhan98
72e90d8b8b5de0630ade54589234bb59d05d640e
1,335
cc
C++
src/web_server/capabilities/contest_entry_token.cc
varqox/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
12
2017-11-05T21:02:58.000Z
2022-03-28T23:11:51.000Z
src/web_server/capabilities/contest_entry_token.cc
varqox/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
11
2017-01-05T18:11:41.000Z
2019-11-01T12:40:55.000Z
src/web_server/capabilities/contest_entry_token.cc
krzyk240/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
6
2016-12-25T11:22:34.000Z
2020-10-20T16:03:51.000Z
#include "src/web_server/capabilities/contest_entry_token.hh" #include "sim/contest_users/contest_user.hh" #include "sim/users/user.hh" #include "src/web_server/capabilities/contest.hh" #include "src/web_server/web_worker/context.hh" #include <cstdlib> using sim::contest_users::ContestUser; using sim::users::User; namespace web_server::capabilities { ContestEntryToken contest_entry_token_for( ContestEntryTokenKind token_kind, const decltype(web_worker::Context::session)& session, const Contest& caps_contest, std::optional<decltype(sim::contest_users::ContestUser::mode)> contest_user_mode) noexcept { bool is_admin = session and session->user_type == User::Type::ADMIN; bool is_contest_moderator = caps_contest.node.view and (is_admin or is_one_of(contest_user_mode, ContestUser::Mode::OWNER, ContestUser::Mode::MODERATOR)); switch (token_kind) { case ContestEntryTokenKind::NORMAL: case ContestEntryTokenKind::SHORT: return ContestEntryToken{ .view = is_contest_moderator, .create = is_contest_moderator, .regen = is_contest_moderator, .delete_ = is_contest_moderator, .use = true, .view_contest_name = true, }; } std::abort(); } } // namespace web_server::capabilities
34.230769
95
0.708614
varqox
6391c59ab61ba16f17bc4320343b19c4cb044181
1,084
cpp
C++
Sources/Particles/Particles.cpp
0xflotus/Acid
cf680a13c3894822920737dcf1b7d17aef74a474
[ "MIT" ]
1
2021-08-11T14:50:00.000Z
2021-08-11T14:50:00.000Z
Sources/Particles/Particles.cpp
sum01/Acid
d921472e062fc26b87c0163918aab553ac20739a
[ "MIT" ]
null
null
null
Sources/Particles/Particles.cpp
sum01/Acid
d921472e062fc26b87c0163918aab553ac20739a
[ "MIT" ]
null
null
null
#include "Particles.hpp" #include "Scenes/Scenes.hpp" namespace acid { const float Particles::MAX_ELAPSED_TIME = 5.0f; Particles::Particles() : m_particles(std::map<std::shared_ptr<ParticleType>, std::vector<Particle>>()) { } void Particles::Update() { if (Scenes::Get()->IsPaused()) { return; } for (auto it = m_particles.begin(); it != m_particles.end(); ++it) { for (auto it1 = (*it).second.begin(); it1 != (*it).second.end();) { (*it1).Update(); if (!(*it1).IsAlive()) { it1 = (*it).second.erase(it1); continue; } ++it1; } std::sort((*it).second.begin(), (*it).second.end()); (*it).first->Update((*it).second); } } void Particles::AddParticle(const Particle &particle) { auto it = m_particles.find(particle.GetParticleType()); if (it == m_particles.end()) { m_particles.emplace(particle.GetParticleType(), std::vector<Particle>()); it = m_particles.find(particle.GetParticleType()); } (*it).second.emplace_back(particle); } void Particles::Clear() { m_particles.clear(); } }
18.372881
79
0.611624
0xflotus
6393debf02672a7ecfceb92fc78d0d84d766458d
3,388
hpp
C++
includes/nt/directories/dir_relocs.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
140
2020-01-16T19:04:33.000Z
2022-03-10T02:54:01.000Z
includes/nt/directories/dir_relocs.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
4
2021-02-28T12:02:46.000Z
2022-02-14T01:41:57.000Z
includes/nt/directories/dir_relocs.hpp
archercreat/linux-pe
902f744424b70979d401a9274afd579bceea104a
[ "BSD-3-Clause" ]
38
2020-01-16T01:48:08.000Z
2022-03-12T16:52:20.000Z
// Copyright (c) 2020 Can Boluk // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #pragma once #include "../../img_common.hpp" #include "../data_directories.hpp" #pragma pack(push, WIN_STRUCT_PACKING) namespace win { enum reloc_type_id : uint16_t { rel_based_absolute = 0, rel_based_high = 1, rel_based_low = 2, rel_based_high_low = 3, rel_based_high_adj = 4, rel_based_ia64_imm64 = 9, rel_based_dir64 = 10, }; struct reloc_entry_t { uint16_t offset : 12; reloc_type_id type : 4; }; static_assert( sizeof( reloc_entry_t ) == 2, "Enum bitfield is not supported." ); struct reloc_block_t { uint32_t base_rva; uint32_t size_block; reloc_entry_t entries[ VAR_LEN ]; inline reloc_block_t* next() { return ( reloc_block_t* ) ( ( char* ) this + this->size_block ); } inline const reloc_block_t* next() const { return const_cast< reloc_block_t* >( this )->next(); } inline size_t num_entries() const { return ( reloc_entry_t* ) next() - &entries[ 0 ]; } inline reloc_entry_t* begin() { return &entries[ 0 ]; } inline const reloc_entry_t* begin() const { return &entries[ 0 ]; } inline reloc_entry_t* end() { return ( reloc_entry_t* ) next(); } inline const reloc_entry_t* end() const { return ( const reloc_entry_t* ) next(); } }; struct reloc_directory_t { reloc_block_t first_block; }; template<bool x64> struct directory_type<directory_id::directory_entry_basereloc, x64, void> { using type = reloc_directory_t; }; }; #pragma pack(pop)
44.578947
133
0.64876
archercreat
63945dfd7cbd7ec71bf405d89c81af3192f1e088
9,273
cpp
C++
src/RTCCertificate.cpp
paullouisageneau/librtcdcpp
62695f7fc11b3401e2f8266abeaa556c05536373
[ "BSD-3-Clause" ]
5
2018-01-16T17:02:20.000Z
2020-05-14T11:33:47.000Z
src/RTCCertificate.cpp
paullouisageneau/librtcdcpp
62695f7fc11b3401e2f8266abeaa556c05536373
[ "BSD-3-Clause" ]
null
null
null
src/RTCCertificate.cpp
paullouisageneau/librtcdcpp
62695f7fc11b3401e2f8266abeaa556c05536373
[ "BSD-3-Clause" ]
2
2019-08-14T12:04:05.000Z
2020-03-23T07:11:04.000Z
/** * Copyright (c) 2017, Andrew Gault, Nick Chadwick and Guillaume Egles. * 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 THE COPYRIGHT HOLDERS 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. */ /** * Simple wrapper around GnuTLS or OpenSSL Certs. */ #include "rtcdcpp/RTCCertificate.hpp" #include <cassert> #include <ctime> #ifdef USE_GNUTLS #include <gnutls/crypto.h> namespace rtcdcpp { using namespace std; static void check_gnutls(int ret, const std::string &message = "GnuTLS error") { if(ret != GNUTLS_E_SUCCESS) throw std::runtime_error(message + ": " + gnutls_strerror(ret)); } static gnutls_certificate_credentials_t *create_creds() { auto pcreds = new gnutls_certificate_credentials_t; check_gnutls(gnutls_certificate_allocate_credentials(pcreds)); return pcreds; } static void delete_creds(gnutls_certificate_credentials_t *pcreds) { gnutls_certificate_free_credentials(*pcreds); delete pcreds; } RTCCertificate RTCCertificate::GenerateCertificate(std::string common_name, int days) { gnutls_x509_crt_t crt; gnutls_x509_privkey_t privkey; check_gnutls(gnutls_x509_crt_init(&crt)); check_gnutls(gnutls_x509_privkey_init(&privkey)); try { const unsigned int bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_HIGH); check_gnutls(gnutls_x509_privkey_generate(privkey, GNUTLS_PK_RSA, bits, 0), "Unable to generate key pair"); gnutls_x509_crt_set_activation_time(crt, std::time(NULL) - 3600); gnutls_x509_crt_set_expiration_time(crt, std::time(NULL) + days*24*3600); gnutls_x509_crt_set_version(crt, 1); gnutls_x509_crt_set_key(crt, privkey); gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0, common_name.data(), common_name.size()); const size_t serialSize = 16; char serial[serialSize]; gnutls_rnd(GNUTLS_RND_NONCE, serial, serialSize); gnutls_x509_crt_set_serial(crt, serial, serialSize); check_gnutls(gnutls_x509_crt_sign2(crt, crt, privkey, GNUTLS_DIG_SHA256, 0), "Unable to auto-sign certificate"); return RTCCertificate(crt, privkey); } catch(...) { gnutls_x509_crt_deinit(crt); gnutls_x509_privkey_deinit(privkey); throw; } } std::string RTCCertificate::GenerateFingerprint(gnutls_x509_crt_t crt) { const size_t bufSize = 32; unsigned char buf[bufSize]; size_t len = bufSize; check_gnutls(gnutls_x509_crt_get_fingerprint(crt, GNUTLS_DIG_SHA256, buf, &len), "X509 fingerprint error"); int offset = 0; char fp[SHA256_FINGERPRINT_SIZE]; std::memset(fp, 0, SHA256_FINGERPRINT_SIZE); for (unsigned int i = 0; i < len; ++i) { snprintf(fp + offset, 4, "%02X:", buf[i]); offset += 3; } fp[offset - 1] = '\0'; return std::string(fp); } RTCCertificate::RTCCertificate(std::string crt_pem, std::string key_pem) : creds_(create_creds(), delete_creds) { gnutls_datum_t crt_datum; crt_datum.data = (unsigned char*)crt_pem.data(); crt_datum.size = crt_pem.size(); gnutls_datum_t key_datum; key_datum.data = (unsigned char*)key_pem.data(); key_datum.size = key_pem.size(); check_gnutls(gnutls_certificate_set_x509_key_mem(*creds_, &crt_datum, &key_datum, GNUTLS_X509_FMT_PEM), "Unable to import PEM"); gnutls_x509_crt_t *crt_list = NULL; unsigned int crt_list_size = 0; check_gnutls(gnutls_certificate_get_x509_crt(*creds_, 0, &crt_list, &crt_list_size)); assert(crt_list_size == 1); try { fingerprint_ = GenerateFingerprint(crt_list[0]); } catch(...) { gnutls_x509_crt_deinit(crt_list[0]); gnutls_free(crt_list); throw; } gnutls_x509_crt_deinit(crt_list[0]); gnutls_free(crt_list); } RTCCertificate::RTCCertificate(gnutls_x509_crt_t crt, gnutls_x509_privkey_t privkey) : creds_(create_creds(), delete_creds), fingerprint_(GenerateFingerprint(crt)) { check_gnutls(gnutls_certificate_set_x509_key(*creds_, &crt, 1, privkey), "Unable to set certificate and key pair in credentials"); gnutls_x509_crt_deinit(crt); gnutls_x509_privkey_deinit(privkey); } } #else #include <openssl/pem.h> namespace rtcdcpp { using namespace std; static std::shared_ptr<X509> GenerateX509(std::shared_ptr<EVP_PKEY> evp_pkey, const std::string &common_name, int days) { std::shared_ptr<X509> null_result; std::shared_ptr<X509> x509(X509_new(), X509_free); std::shared_ptr<BIGNUM> serial_number(BN_new(), BN_free); std::shared_ptr<X509_NAME> name(X509_NAME_new(), X509_NAME_free); if (!x509 || !serial_number || !name) { return null_result; } if (!X509_set_pubkey(x509.get(), evp_pkey.get())) { return null_result; } if (!BN_pseudo_rand(serial_number.get(), 64, 0, 0)) { return null_result; } ASN1_INTEGER *asn1_serial_number = X509_get_serialNumber(x509.get()); if (!asn1_serial_number) { return null_result; } if (!BN_to_ASN1_INTEGER(serial_number.get(), asn1_serial_number)) { return null_result; } if (!X509_set_version(x509.get(), 0L)) { return null_result; } if (!X509_NAME_add_entry_by_NID(name.get(), NID_commonName, MBSTRING_UTF8, (unsigned char *)common_name.c_str(), -1, -1, 0)) { return null_result; } if (!X509_set_subject_name(x509.get(), name.get()) || !X509_set_issuer_name(x509.get(), name.get())) { return null_result; } if (!X509_gmtime_adj(X509_get_notBefore(x509.get()), 0) || !X509_gmtime_adj(X509_get_notAfter(x509.get()), days * 24 * 3600)) { return null_result; } if (!X509_sign(x509.get(), evp_pkey.get(), EVP_sha1())) { return null_result; } return x509; } RTCCertificate RTCCertificate::GenerateCertificate(std::string common_name, int days) { std::shared_ptr<EVP_PKEY> pkey(EVP_PKEY_new(), EVP_PKEY_free); RSA *rsa = RSA_new(); std::shared_ptr<BIGNUM> exponent(BN_new(), BN_free); if (!pkey || !rsa || !exponent) { throw std::runtime_error("GenerateCertificate: !pkey || !rsa || !exponent"); } if (!BN_set_word(exponent.get(), 0x10001) || !RSA_generate_key_ex(rsa, 2048, exponent.get(), NULL) || !EVP_PKEY_assign_RSA(pkey.get(), rsa)) { throw std::runtime_error("GenerateCertificate: Error generating key"); } auto cert = GenerateX509(pkey, common_name, days); if (!cert) { throw std::runtime_error("GenerateCertificate: Error in GenerateX509"); } return RTCCertificate(cert, pkey); } std::string RTCCertificate::GenerateFingerprint(X509 *x509) { unsigned int len; unsigned char buf[EVP_MAX_MD_SIZE] = {0}; if (!X509_digest(x509, EVP_sha256(), buf, &len)) { throw std::runtime_error("GenerateFingerprint(): X509_digest error"); } if (len != 32) { throw std::runtime_error("GenerateFingerprint(): unexpected fingerprint size"); } int offset = 0; char fp[SHA256_FINGERPRINT_SIZE]; memset(fp, 0, SHA256_FINGERPRINT_SIZE); for (unsigned int i = 0; i < len; ++i) { snprintf(fp + offset, 4, "%02X:", buf[i]); offset += 3; } fp[offset - 1] = '\0'; return std::string(fp); } RTCCertificate::RTCCertificate(std::string crt_pem, std::string key_pem) { /* x509 */ BIO *bio = BIO_new(BIO_s_mem()); BIO_write(bio, crt_pem.c_str(), (int)crt_pem.length()); x509_ = std::shared_ptr<X509>(PEM_read_bio_X509(bio, nullptr, 0, 0), X509_free); BIO_free(bio); if (!x509_) { throw std::invalid_argument("Could not read certificate PEM"); } /* evp_pkey */ bio = BIO_new(BIO_s_mem()); BIO_write(bio, key_pem.c_str(), (int)key_pem.length()); evp_pkey_ = std::shared_ptr<EVP_PKEY>(PEM_read_bio_PrivateKey(bio, nullptr, 0, 0), EVP_PKEY_free); BIO_free(bio); if (!evp_pkey_) { throw std::invalid_argument("Could not read key PEM"); } fingerprint_ = GenerateFingerprint(x509_.get()); } RTCCertificate::RTCCertificate(std::shared_ptr<X509> x509, std::shared_ptr<EVP_PKEY> evp_pkey) : x509_(x509), evp_pkey_(evp_pkey), fingerprint_(GenerateFingerprint(x509_.get())) {} } #endif
33.476534
144
0.725116
paullouisageneau
639854d7b48cc15d2b9d44282e84ec6ac63bbf07
3,923
cpp
C++
project2D/Asteroid.cpp
CEbbinghaus/Asteroids
8bcac70c25602ef3fcf5edd699a0b630b2f8d40a
[ "MIT" ]
null
null
null
project2D/Asteroid.cpp
CEbbinghaus/Asteroids
8bcac70c25602ef3fcf5edd699a0b630b2f8d40a
[ "MIT" ]
null
null
null
project2D/Asteroid.cpp
CEbbinghaus/Asteroids
8bcac70c25602ef3fcf5edd699a0b630b2f8d40a
[ "MIT" ]
null
null
null
#include "Asteroid.h" #include "Asteroids.h" void Asteroid::update(float deltaTime){ //transform.Position += velocity * (speed * deltaTime); if (transform.Position.x < 0)transform.Position.x = Master::application->GetWindowWidth(); if (transform.Position.x > Master::application->GetWindowWidth())transform.Position.x = 0; if (transform.Position.y < 0)transform.Position.y = Master::application->GetWindowHeight(); if (transform.Position.y > Master::application->GetWindowHeight())transform.Position.y = 0; /*if (transform.Position.x + radius < 0)transform.Position.x = Master::application->GetWindowWidth() + radius; if (transform.Position.x - radius > Master::application->GetWindowWidth())transform.Position.x = -radius; if (transform.Position.y + radius < 0)transform.Position.y = Master::application->GetWindowHeight() + radius; if (transform.Position.y - radius > Master::application->GetWindowHeight())transform.Position.y = -radius; */ transform.Rotation += rotationVelocity * deltaTime; } void Asteroid::draw(aie::Renderer2D& renderer){ if(!points.length)return; float radOffset = (M_PI * 2) / (float)points.length; float lastRadius = points[points.length - 1]; for(auto [PRadius, Index] : points){ Vector3 prev = Vector3(radius * *PRadius * sinf(Index * radOffset), radius * *PRadius * cosf(Index * radOffset), 1.0f); --Index; Vector3 next = Vector3(radius * lastRadius * sinf(Index * radOffset), radius * lastRadius * cosf(Index * radOffset), 1.0f); prev = transform.GetGlobalTransform() * prev; next = transform.GetGlobalTransform() * next; renderer.DrawLine(prev.x, prev.y, next.x, next.y); //float xPos = transform.globalTransform.Pos.x + radius * *PRadius * sinf(Index * radOffset); //float yPos = transform.globalTransform.Pos.y + radius * *PRadius * cosf(Index * radOffset); //float PxPos = transform.globalTransform.Pos.x + radius * lastRadius * sinf(--Index * radOffset); //float PyPos = transform.globalTransform.Pos.y + radius * lastRadius * cosf(Index * radOffset); //renderer.DrawLine(PxPos, PyPos, xPos, yPos); lastRadius = *PRadius; } } void Asteroid::OnCollision(GameObject& other){ if (other.id == (char)Object::bullet) { int amount = 0; switch (size){ case 3: amount = Random.get<int>(2, 5); break; case 2: amount = Random.get<int>(0, 2); break; } float RadianOffset = Random.get<float>(0, M_PI * 2); float RadianAmount = (M_PI * 2) / amount; for (int i = 0; i < amount; ++i) { float finalRotation = RadianOffset + RadianAmount * i; Vector2 direction = Vector2(sinf(finalRotation), cosf(finalRotation)); Vector2 currentPosition = *(Vector2*)(&(transform.GetGlobalTransform().Pos)); Asteroid* a = new Asteroid(size - 1, direction, currentPosition + direction * Random.get<float>(radius / 2, radius)); Asteroids::instance->activeAsteroids.push(a); } Asteroids::instance->score += (100 * size); Asteroids::instance->activeAsteroids.remove(this); Master::DeleteObject(this); } } Asteroid::Asteroid(int a_size, Vector2 dir, Vector2 pos) : GameObject({new CircleCollider(*this, Vector2(1.0f, 1.0f), 10), new Rigidbody(*this, dir)}){ rotationVelocity = Random.get<float>(0.0f, 0.3f); id = (char)Object::asteroid; CircleCollider* c = GetComponent<CircleCollider>(); if(c) c->layerMask = Layer::default | Layer::one; size = a_size; speed = ((4 - size) * Asteroids::instance->level + 1) * 20; GetComponent<Rigidbody>()->velocity = speed * dir; float min = (float)size * 40.0f; GetComponent<CircleCollider>()->radius = radius = Random.get<float>(min, min * 1.3); // velocity = dir; transform.Position = pos; int minP = 3 * size; int maxP = 4 * size; int amount = Random.get<int>(minP, maxP); for(int i = 0; i < amount; i++){ points.push(Random.get<float>(0.3f, 1.0f)); } } Asteroid::~Asteroid(){ //Asteroids::instance->activeAsteroids.remove(this); }
37.361905
151
0.691053
CEbbinghaus
639f6b0646b7ec1e43748ed81bf38ff250644cf8
30,697
cpp
C++
src/mascgl-3/draw_basics.cpp
jmlien/lightbender
510f1971614930e2d75911d23a97b1ba77426074
[ "MIT" ]
null
null
null
src/mascgl-3/draw_basics.cpp
jmlien/lightbender
510f1971614930e2d75911d23a97b1ba77426074
[ "MIT" ]
null
null
null
src/mascgl-3/draw_basics.cpp
jmlien/lightbender
510f1971614930e2d75911d23a97b1ba77426074
[ "MIT" ]
1
2021-04-18T20:58:52.000Z
2021-04-18T20:58:52.000Z
#include "draw_basics.h" #define DEBUG 0 Camera camera; Shader shader; //----------------------------------------------------------------------------- // // GL/GUI initialization and setup // //----------------------------------------------------------------------------- GLFWwindow* initGLcontext(mascgl_workspace& workspace, string title, GLFWerrorfun errfun, GLFWkeyfun keyfun, GLFWmousebuttonfun mousefun, GLFWcursorposfun cursorfun) { glfwSetErrorCallback(errfun);// error_callback); // Initialise GLFW if (!glfwInit()) { cerr << "! Error: Failed to initialize GLFW" << endl; return NULL; } glfwWindowHint(GLFW_SAMPLES, 4); #ifdef _WIN32 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #else glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // // Open a window and create its OpenGL context // title += ": "; title += workspace.env_filename; GLFWwindow* window = glfwCreateWindow(workspace.image_w, workspace.image_h, title.c_str(), NULL, NULL); if (window == NULL){ cerr << "! Error: Failed to open a GLFW window" << endl; glfwTerminate(); return NULL; } glfwMakeContextCurrent(window); // // Initialize GLEW // glewExperimental = true; // Needed for core profile #if ( (defined(__MACH__)) && (defined(__APPLE__)) ) //nothing glewInit(); #else if (glewInit() != GLEW_OK) { cerr << "! Error: Failed to initialize GLEW" << endl; return NULL; } #endif // // set call back functions... // glfwSetKeyCallback(window, keyfun); glfwSetMouseButtonCallback(window, mousefun); glfwSetCursorPosCallback(window, cursorfun); //set camera position camera.setCameraPosX((float)workspace.COM[0]); camera.setCameraPosY((float)workspace.COM[1]); camera.setCameraPosZ(workspace.R*2.1f); camera.init(window); //tell workspace to create basic textures... workspace.createDefaultTextures(); //load textures from files for (list<object3D*>::iterator i = workspace.models.begin(); i != workspace.models.end(); i++) { object3D * obj = *i; //load textures if (!obj->color_texture_filename.empty()) { obj->color_texture = new Texture(); if (obj->color_texture->loadTexture(obj->color_texture_filename.c_str()) == false) { cerr << "! Error: Failed to load texture:" << obj->color_texture_filename << endl; return nullptr; } } if (!obj->normalmap_texture_filename.empty()) { obj->normalmap_texture = new Texture(); if (obj->normalmap_texture->loadTexture(obj->normalmap_texture_filename.c_str()) == false) { cerr << "! Error: Failed to load texture:" << obj->normalmap_texture_filename << endl; return nullptr; } } }//end for i return window; } void setupLight(mascgl_workspace& workspace, Shader& shader) { //Let's have light! for (list<light*>::iterator i = workspace.lights.begin(); i != workspace.lights.end(); i++) { light* li = *i; float pos[] = { (float)li->pos[0], (float)li->pos[1], (float)li->pos[2], 1.0f }; float diffuse[] = { (float)li->mat_color[0], (float)li->mat_color[1], (float)li->mat_color[2], 1.0f }; float specular[] = { (float)li->mat_specular[0], (float)li->mat_specular[1], (float)li->mat_specular[2], 1.0f }; float ambient[] = { (float)li->ambient[0], (float)li->ambient[1], (float)li->ambient[2], 1.0f }; glUniform3fv(shader.value("light.pos"), 1, pos); glUniform4fv(shader.value("light.diffuse"), 1, diffuse); glUniform4fv(shader.value("light.specular"), 1, specular); glUniform4fv(shader.value("light.ambient"), 1, ambient); glUniform1f(shader.value("light.att_const"), (float)li->att_const); glUniform1f(shader.value("light.att_linear"), (float)li->att_linear); //only the first light will be used... break; } //-------------------------------------------------- } void setupGLflags() { // transparent glShadeModel(GL_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); //glEnable(GL_NORMALIZE); glClearColor(1.0, 1.0, 1.0, 1.0); glEnable(GL_CULL_FACE); } //----------------------------------------------------------------------------- // // functions for rendering depth map // //----------------------------------------------------------------------------- //create view/projection matrix from the given light void createVPfromLight(mascgl_workspace& workspace, light * mylight, glm::mat4& depthProjectionMatrix, glm::mat4& depthViewMatrix) { //setup model, view, projection matrix for light space const Point3d& lp = mylight->pos; //light position const Point3d& lookat = mylight->lookat; //look at position float dist = Vector3d(lp - lookat).norm(); float dim = workspace.R; //mathtool::Point3d lp = mylight->pos; //light position //const mathtool::Point3d& lookat = mylight->lookat; //look at position //Vector3d viewdir = (mylight->pos - lookat).normalize()*workspace.R; //lp = lookat + viewdir; //float dist = viewdir.norm(); //float dim = workspace.R; if (mylight->type == light::SPOT_LIGHT) depthProjectionMatrix = glm::perspective(45.0, 1.0, mylight->znear, mylight->zfar); if (mylight->type == light::POINT_LIGHT) depthProjectionMatrix = glm::perspective(45.0, 1.0, mylight->znear, mylight->zfar); else depthProjectionMatrix = glm::ortho<float>(-dim, dim, -dim, dim, 0, dist + dim * 2); depthViewMatrix = glm::lookAt(toglm(lp), toglm(lookat), glm::vec3(0, 1, 0)); } //create view/projection matrix from the given light void createVPfromLight(mascgl_workspace& workspace, light * mylight, glm::mat4& depthVP) { glm::mat4 depthProjectionMatrix, depthViewMatrix; createVPfromLight(workspace, mylight, depthProjectionMatrix, depthViewMatrix); depthVP = depthProjectionMatrix * depthViewMatrix; } GLuint renderDepth(mascgl_workspace& workspace, glm::mat4& depthVP, vector<M_buffers>& buffers) { // --------------------------------------------- // Render to Texture // --------------------------------------------- // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); // Depth texture. Slower than a depth buffer, but you can sample it later in your shader //this is for depth GLuint depthTexture = 0; glGenTextures(1, &depthTexture); glBindTexture(GL_TEXTURE_2D, depthTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, workspace.image_w, workspace.image_h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); //for depth { glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); // No color output in the bound framebuffer, only depth. glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } // Always check that our framebuffer is ok if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { cerr << "! Error: glCheckFramebufferStatus failed" << endl; exit(-1); } //------------------------------------------------ //depth shader Shader depth_shader; depth_shader.init("shaders/renderDepth.vert", "shaders/renderDepth.frag"); depth_shader.addvarible("depthMVP"); //------------------------------------------------ //------------------------------------------------------------------------------------- // Render to our framebuffer //------------------------------------------------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0, 0, workspace.image_w, workspace.image_h); // Render on the whole framebuffer, complete from the lower left corner to the upper right // We don't use bias in the shader, but instead we draw back faces, // which are already separated from the front faces by a small distance // (if your geometry is made this way) glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // Cull back-facing triangles -> draw only front-facing triangles //------------------------------------------------------------------------------------- // // // render depth... // // // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); depth_shader.bind(); // //draw meshes // for (vector<M_buffers>::iterator i = buffers.begin(); i != buffers.end(); i++) { if (i->m == NULL) continue; //bind texture here... model & M = *(i->m); //compute depthMVP from depthVP glm::mat4 depthMVP = depthVP*toglm(M.getCurrentTransform()); // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(depth_shader.value("depthMVP"), 1, GL_FALSE, &depthMVP[0][0]); // // 1st attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, i->vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, i->trielementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode M.t_size * 3, // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); glDisableVertexAttribArray(0); } //TODO: we should draw spheres here as well... // depth_shader.unbind(); //SAVED IMAGE TO FILE //this is for depth #if DEBUG { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); float * img = new float[workspace.image_w*workspace.image_h]; glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, img); char id[1024]; sprintf(id, "%0d", (int)time(NULL)); string filename = "depth_"; filename = filename + id + ".ppm"; save2file(filename.c_str(), workspace.image_w, workspace.image_h, img); delete[] img; } #endif //DEBUG //reset back... glDeleteFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, workspace.image_w, workspace.image_h); return depthTexture; } GLuint renderDepth(mascgl_workspace& workspace, glm::mat4& depthVP, M_buffers& buffer) { if (buffer.m == NULL) return -1; // --------------------------------------------- // Render to Texture // --------------------------------------------- // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); // Depth texture. Slower than a depth buffer, but you can sample it later in your shader //this is for depth GLuint depthTexture = 0; glGenTextures(1, &depthTexture); glBindTexture(GL_TEXTURE_2D, depthTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, workspace.image_w, workspace.image_h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); //for depth { glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0); // No color output in the bound framebuffer, only depth. glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); } // Always check that our framebuffer is ok if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { cerr << "! Error: glCheckFramebufferStatus failed" << endl; exit(-1); } //------------------------------------------------ //depth shader Shader depth_shader; depth_shader.init("shaders/renderDepth.vert", "shaders/renderDepth.frag"); depth_shader.addvarible("depthMVP"); //------------------------------------------------ //------------------------------------------------------------------------------------- // Render to our framebuffer //------------------------------------------------------------------------------------- glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0, 0, workspace.image_w, workspace.image_h); // Render on the whole framebuffer, complete from the lower left corner to the upper right // We don't use bias in the shader, but instead we draw back faces, // which are already separated from the front faces by a small distance // (if your geometry is made this way) glEnable(GL_CULL_FACE); glCullFace(GL_BACK); // Cull back-facing triangles -> draw only front-facing triangles //------------------------------------------------------------------------------------- // // // render depth... // // // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); depth_shader.bind(); // //draw meshes // //bind texture here... model & M = *(buffer.m); //compute depthMVP from depthVP glm::mat4 depthMVP = depthVP*toglm(M.getCurrentTransform()); // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(depth_shader.value("depthMVP"), 1, GL_FALSE, &depthMVP[0][0]); // // 1st attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, buffer.vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.trielementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode M.t_size * 3, // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); glDisableVertexAttribArray(0); //TODO: we should draw spheres here as well... // depth_shader.unbind(); //SAVED IMAGE TO FILE //this is for depth #if DEBUG { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); float * img = new float[workspace.image_w*workspace.image_h]; glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT, img); char id[1024]; sprintf(id, "%0d", (int)time(NULL)); string filename = "depth_"; filename = filename + id + ".ppm"; save2file(filename.c_str(), workspace.image_w, workspace.image_h, img); filename = filename + id + ".dds"; int save_result = SOIL_save_image(filename.c_str(), SOIL_SAVE_TYPE_DDS, workspace.image_w, workspace.image_h, 3, img); delete[] img; } #endif //reset back... glDeleteFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, workspace.image_w, workspace.image_h); return depthTexture; } GLuint renderShadow(mascgl_workspace& workspace, glm::mat4& depthVP, GLuint depthTexture, vector<M_buffers>& buffers) { // //prepare framebuffer for shadow rendering... // --------------------------------------------- // Render to Texture // --------------------------------------------- // The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. // GLuint FramebufferName = 0; glGenFramebuffers(1, &FramebufferName); glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); // shadow texture. // this is for color GLuint colorTexture; glGenTextures(1, &colorTexture); glBindTexture(GL_TEXTURE_2D, colorTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, workspace.image_w, workspace.image_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); //for color glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorTexture, 0); // Set the list of draw buffers. GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers // The depth buffer (this block of code is necessary...) GLuint depthrenderbuffer; glGenRenderbuffers(1, &depthrenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, workspace.image_w, workspace.image_h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer); // Always check that our framebuffer is ok if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { cerr << "! Error: glCheckFramebufferStatus failed" << endl; exit(-1); } //bind this frame buffer glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName); glViewport(0, 0, workspace.image_w, workspace.image_h); //------------------------------------------------ //load shadow only shader Shader shadow_shader; shadow_shader.init("shaders/pointlight_shadow_only.vert", "shaders/pointlight_shadow_only.frag"); //get uniform variables shadow_shader.addvarible("MVP"); shadow_shader.addvarible("V"); shadow_shader.addvarible("M"); shadow_shader.addvarible("MV3x3"); shadow_shader.addvarible("DepthBiasMVP"); shadow_shader.addvarible("shadowMap"); //------------------------------------------------ //draw shadow //----------------------------------------------------------------------- // // draw to FramebufferName... // setup model, view, projection matrix // //----------------------------------------------------------------------- // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadow_shader.bind(); //let's look at the scene from the light (but near the bbox) light * mylight = workspace.lights.front(); mathtool::Point3d lp = mylight->pos; //light position const mathtool::Point3d& lookat = mylight->lookat; //look at position Vector3d viewdir = (mylight->pos - lookat).normalize()*workspace.R; lp = lookat + viewdir; float dist = viewdir.norm(); float dim = workspace.R; glm::mat4 ProjectionMatrix = glm::ortho<float>(-dim, dim, -dim, dim, 0, dist + workspace.R * 2); glm::mat4 ViewMatrix = glm::lookAt(toglm(lp), toglm(lookat), glm::vec3(0, 1, 0)); //glm::mat4 ProjectionMatrix, ViewMatrix; //createVPfromLight(mylight, ProjectionMatrix, ViewMatrix); //bind shadow texture... glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depthTexture); glUniform1i(shadow_shader.value("shadowMap"), 0); //here we draw walls only bool wallonly = true; bool texture = false; drawMesh(workspace, shadow_shader, ProjectionMatrix, ViewMatrix, depthVP, buffers, wallonly, texture); //done.... shadow_shader.unbind(); //unbind this frame buffer glDeleteFramebuffers(1, &FramebufferName); glDeleteRenderbuffers(1, &depthrenderbuffer); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, workspace.image_w, workspace.image_h); return colorTexture; } //----------------------------------------------------------------------------- // // Load and render individual model and shpere // //----------------------------------------------------------------------------- //load the given model M into GL buffers M_buffers loadModelBuffers(model& M) { M_buffers buffers; buffers.m = &M; //get positions of each vertex { std::vector<glm::vec3> indexed_vertices; indexed_vertices.reserve(M.v_size); for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec3 pos = toglm(v.p); indexed_vertices.push_back(pos); } glGenBuffers(1, &buffers.vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.vertexbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW); } //get normals of each vertex { std::vector<glm::vec3> indexed_normals; indexed_normals.reserve(M.v_size); for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec3 normal = toglm(v.n); indexed_normals.push_back(normal); } glGenBuffers(1, &buffers.normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.normalbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW); } //get tangent of each vertex { std::vector<glm::vec3> tangents; tangents.reserve(M.v_size); for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec3 tangent = toglm(v.t); tangents.push_back(tangent); } glGenBuffers(1, &buffers.tangentbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.tangentbuffer); glBufferData(GL_ARRAY_BUFFER, tangents.size() * sizeof(glm::vec3), &tangents[0], GL_STATIC_DRAW); } //get bitangent of each vertex { std::vector<glm::vec3> bitangents; bitangents.reserve(M.v_size); for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec3 bitangent = toglm(v.b); bitangents.push_back(bitangent); } glGenBuffers(1, &buffers.bitangentbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.bitangentbuffer); glBufferData(GL_ARRAY_BUFFER, bitangents.size() * sizeof(glm::vec3), &bitangents[0], GL_STATIC_DRAW); } //get UV of each vertex { std::vector<glm::vec2> UVs; for (unsigned int i = 0; i < M.v_size; i++) { vertex& v = M.vertices[i]; glm::vec2 uv(v.uv[0], v.uv[1]); UVs.push_back(uv); } glGenBuffers(1, &buffers.uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, buffers.uvbuffer); glBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs[0], GL_STATIC_DRAW); } // // find indices for each triangle vertex // { //std::vector<uint> indices; std::vector<unsigned int> indices; int vindex = 0; for (unsigned int i = 0; i < M.t_size; i++) { triangle & tri = M.tris[i]; for (short d = 0; d < 3; d++) { indices.push_back((unsigned int)tri.v[d]); } }//end for i // Generate a buffer for the indices as well glGenBuffers(1, &buffers.trielementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers.trielementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); } return buffers; } void drawMesh(mascgl_workspace& workspace, M_buffers& buffer, Shader& shader, glm::mat4& projection, glm::mat4& view, glm::mat4& depthVP, bool wall_only, bool show_texture) { if (buffer.m == NULL) return; unsigned int texture_location = shader.value("color_texture"); if (texture_location != UINT_MAX) { glActiveTexture(GL_TEXTURE1); glUniform1i(texture_location, 1); } //draw meshes //bind texture here... model & M = *(buffer.m); //setup transforms glm::mat4 ModelMatrix = toglm(M.getCurrentTransform()); glm::mat4 ModelViewMatrix = view * ModelMatrix; glm::mat3 ModelView3x3Matrix = glm::mat3(ModelViewMatrix); glm::mat4 MVP = projection * view * ModelMatrix; glm::mat4 depthMVP = depthVP * ModelMatrix; //matrix to map points into light space // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(shader.value("MVP"), 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(shader.value("M"), 1, GL_FALSE, &ModelMatrix[0][0]); glUniformMatrix4fv(shader.value("V"), 1, GL_FALSE, &view[0][0]); glUniformMatrix3fv(shader.value("MV3x3"), 1, GL_FALSE, &ModelView3x3Matrix[0][0]); glUniformMatrix4fv(shader.value("DepthBiasMVP"), 1, GL_FALSE, &depthMVP[0][0]); // if (show_texture && texture_location != UINT_MAX) { if (M.color_texture != NULL) { //M.color_texture->bind(shader.id(), "color_texture", GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, M.color_texture->getTextureID()); } else { //workspace.texture_white.bind(shader.id(), "color_texture", GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, workspace.texture_white.getTextureID()); } } //check if matrial is defined.... if (shader.value("material.diffuse") != UINT_MAX) { float diffuse[] = { (float)M.mat_color[0], (float)M.mat_color[1], (float)M.mat_color[2], 1.0f }; float specular[] = { (float)M.mat_specular[0], (float)M.mat_specular[1], (float)M.mat_specular[2], 1.0f }; float emission[] = { (float)M.mat_emission[0], (float)M.mat_emission[1], (float)M.mat_emission[2], 1.0f }; glUniform4fv(shader.value("material.diffuse"), 1, diffuse); glUniform4fv(shader.value("material.specular"), 1, specular); glUniform4fv(shader.value("material.emission"), 1, emission); glUniform1f(shader.value("material.shininess"), M.mat_shininess); } shader.validateProgram(); // // 1st attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, buffer.vertexbuffer); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, buffer.uvbuffer); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, buffer.normalbuffer); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 4th attribute buffer : tangents glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, buffer.tangentbuffer); glVertexAttribPointer( 3, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 5th attribute buffer : bitangents glEnableVertexAttribArray(4); glBindBuffer(GL_ARRAY_BUFFER, buffer.bitangentbuffer); glVertexAttribPointer( 4, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer.trielementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode M.t_size * 3, // count GL_UNSIGNED_INT, // type (void*)0 // element array buffer offset ); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); glDisableVertexAttribArray(4); } void drawMesh(mascgl_workspace& workspace, Shader& shader, glm::mat4& projection, glm::mat4& view, glm::mat4& depthVP, vector<M_buffers>& buffers, bool wall_only, bool show_texture) { unsigned int texture_location = shader.value("color_texture"); if (texture_location != UINT_MAX) { glActiveTexture(GL_TEXTURE1); glUniform1i(texture_location, 1); } //draw meshes for (vector<M_buffers>::iterator i = buffers.begin(); i != buffers.end(); i++) { if (wall_only && workspace.is_wall(i->m) == false) continue; //not a wall and only wall should be rendered... //if (shadow_caster_only && i->m->cast_shadow == false && workspace.is_wall(i->m) == false) continue;//this model does not cast shadow, so ignore drawMesh(workspace, *i, shader, projection, view, depthVP, wall_only, show_texture); } } //----------------------------------------------------------------------------- // // Save texture or image to file // //----------------------------------------------------------------------------- //save rendered image to file void save2file(const std::string& filename, int w, int h, unsigned char * img) { FILE *f = fopen(filename.c_str(), "w"); // Write image to PPM file. fprintf(f, "P3\n%d %d\n%d\n", w, h, 255); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int id = ((h - i - 1)*w + j) * 3; fprintf(f, "%d %d %d ", (int)img[id], (int)img[id + 1], (int)img[id + 2]); } } fclose(f); } //save depth image to file void save2file(const std::string& filename, int w, int h, float * img) { FILE *f = fopen(filename.c_str(), "w"); // Write image to PPM file. fprintf(f, "P3\n%d %d\n%d\n", w, h, 255); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int id = ((h - i - 1)*w + j); int depth = toInt(img[id]); fprintf(f, "%d %d %d ", depth, depth, depth); } } fclose(f); }
32.177149
182
0.624621
jmlien
63a2a4517d80c7765a41af3fe48edacb34392515
1,187
hpp
C++
University - Team Projects/Robotic Football/third-party & webots installer/webots 6.2.1 controllers/nao_soccer_player_blue/InfoMessage.hpp
mpuheim/Various
b96caabde036530329f0ebbe2e3f176dfe691d1c
[ "RSA-MD" ]
null
null
null
University - Team Projects/Robotic Football/third-party & webots installer/webots 6.2.1 controllers/nao_soccer_player_blue/InfoMessage.hpp
mpuheim/Various
b96caabde036530329f0ebbe2e3f176dfe691d1c
[ "RSA-MD" ]
null
null
null
University - Team Projects/Robotic Football/third-party & webots installer/webots 6.2.1 controllers/nao_soccer_player_blue/InfoMessage.hpp
mpuheim/Various
b96caabde036530329f0ebbe2e3f176dfe691d1c
[ "RSA-MD" ]
null
null
null
#ifndef INFO_MESSAGE_HPP #define INFO_MESSAGE_HPP //----------------------------------------------------------------------------- // File: InfoMessage class (to be used in a C++ Webots controllers) // Description: Example of data packet that can be sent between robots // to support e.g. ball and teammates localization, etc. // Project: Robotstadium, the online robot soccer competition // Author: Yvan Bourquin - www.cyberbotics.com // Date: May 4, 2008 // Changes: //----------------------------------------------------------------------------- // You should change the magic keyword in order to identify your own info messages // this is necessary, in order to avoid spam messages ... #define INFO_MESSAGE_STRUCT_HEADER "YourMagicKeywordHere" struct InfoMessage { // header to identify the structure (not null-termination) char header[sizeof(INFO_MESSAGE_STRUCT_HEADER) - 1]; int playerID; // 0: goalkeeper, 1: field player 1, etc. double distanceToBall; // my rough guess ... // and anything else you want: // double myLocation[2]; // double ballLocation[2]; // bool fallen; // etc. }; #endif
37.09375
82
0.594777
mpuheim
63a2e5ed6733881055afc287426dc15e9cf4cdbf
6,842
cxx
C++
Modules/ThirdParty/VNL/src/vxl/core/vnl/tests/test_hungarian_algorithm.cxx
eile/ITK
2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1
[ "Apache-2.0" ]
4
2015-05-22T03:47:43.000Z
2016-06-16T20:57:21.000Z
Modules/ThirdParty/VNL/src/vxl/core/vnl/tests/test_hungarian_algorithm.cxx
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
null
null
null
Modules/ThirdParty/VNL/src/vxl/core/vnl/tests/test_hungarian_algorithm.cxx
GEHC-Surgery/ITK
f5df62749e56c9036e5888cfed904032ba5fdfb7
[ "Apache-2.0" ]
9
2016-06-23T16:03:12.000Z
2022-03-31T09:25:08.000Z
#include <vnl/vnl_hungarian_algorithm.h> #include <testlib/testlib_test.h> #include <vcl_iostream.h> #include <vcl_limits.h> #include <vcl_algorithm.h> #include <vnl/vnl_matrix.h> #include <vnl/vnl_random.h> static vnl_random randgen; static void check_solution( vcl_vector<unsigned> const& assign, unsigned const* solution, unsigned const N ) { TEST( " assignment vector size", assign.size(), N ); bool okay = true; vcl_cout << " assignment:\n"; for ( unsigned i = 0; i < N; ++i ) { if ( assign[i] != unsigned(-1) || solution[i] != unsigned(-1) ) { vcl_cout << " " << i << " -> " << assign[i] << " (expected " << solution[i] << ")\n"; if ( assign[i] != solution[i] ) { vcl_cout << " (mismatch)\n"; okay = false; } } } TEST( " assignment result", okay, true ); } static vcl_vector<unsigned> make_up_solution( unsigned const M, unsigned const N ) { // True solution vcl_vector<unsigned> true_assn( M ); for ( unsigned i = 0; i < M; ++i ) { bool okay; do { true_assn[i] = randgen.lrand32( N ); okay = true; for ( unsigned j = 0; j < i; ++j ) { if ( true_assn[j] == true_assn[i] ) { okay = false; break; } } } while ( ! okay ); } return true_assn; } static void test_skewed_problem( unsigned const M, unsigned const N ) { vcl_cout << "Creating " << M << 'x' << N << " matrix" << vcl_endl; vnl_matrix<double> cost( M, N ); double low = vcl_min(M,N) + 5.0; for ( unsigned i = 0; i < M; ++i ) { for ( unsigned j = 0; j < N; ++j ) { cost(i,j) = randgen.drand32( low, 100000.0 ); } } vcl_vector<unsigned> true_assn; if ( M < N ) { true_assn = make_up_solution( M, N ); for ( unsigned i = 0; i < M; ++i ) { cost(i, true_assn[i]) = i; } } else { vcl_vector<unsigned> transposed_assn = make_up_solution( N, M ); true_assn.resize( M, unsigned(-1) ); for ( unsigned j = 0; j < N; ++j ) { true_assn[ transposed_assn[j] ] = j; cost(transposed_assn[j],j) = j; } } vcl_cout << "Costs computed for " << M << 'x' << N << " matrix" << vcl_endl; vcl_vector<unsigned> assn = vnl_hungarian_algorithm( cost ); check_solution( assn, &true_assn[0], M ); } static void run_test( vnl_matrix<double> const& cost, unsigned solution[] ) { { vcl_cout << "Test " << cost.rows() << 'x' << cost.cols() << " matrix" << vcl_endl; vcl_vector<unsigned> assign = vnl_hungarian_algorithm( cost ); check_solution( assign, solution, cost.rows() ); } { vcl_cout << "Test transposed problem" << vcl_endl; vnl_matrix<double> costT = cost.transpose(); vcl_vector<unsigned> assign = vnl_hungarian_algorithm( costT ); vcl_vector<unsigned> solutionT( costT.rows(), unsigned(-1) ); for ( unsigned i = 0; i < cost.rows(); ++i ) { if ( solution[i] != unsigned(-1) ) { solutionT[ solution[i] ] = i; } } check_solution( assign, &solutionT[0], costT.rows() ); } } static void test_hungarian_algorithm( int, char*[] ) { { double cost_val[3][3] = { { 1, 2, 3 }, { 2, 4, 6 }, { 3, 6, 9 } }; vnl_matrix<double> cost( &cost_val[0][0], 3, 3 ); vcl_vector<unsigned> assign = vnl_hungarian_algorithm( cost ); TEST( "Test 3x3 cost matrix" , assign.size()==3 && assign[0]==2 && assign[1]==1 && assign[2]==0, true); } { double cost_val[4][4] = { { 2.0, 1.0, 5.0, 3.0 }, { 0.5, 6.0, 3.0, 0.5 }, { 5.0, 2.0, 1.0, 6.0 }, { 7.0, 1.0, 3.0, 0.1 } }; vnl_matrix<double> cost( &cost_val[0][0], 4, 4 ); vcl_vector<unsigned> assign = vnl_hungarian_algorithm( cost ); TEST( "Test 4x4 cost matrix" , assign.size()==4 && assign[0]==1 && assign[1]==0 && assign[2]==2 && assign[3]==3, true); } { double cost_val[3][4] = { { 2.0, 1.0, 5.0, 3.0 }, { 0.5, 6.0, 3.0, 0.5 }, { 7.0, 1.0, 3.0, 0.1 } }; vnl_matrix<double> cost( &cost_val[0][0], 3, 4 ); unsigned solution[] = { 1, 0, 3 }; run_test( cost, solution ); } { // test where the greedy solution is not the optimal vcl_cout << "\n\nTest when greedy != optimal\n"; double cost_val[3][4] = { { 2.0, 1.0, 5.0, 3.0 }, { 0.5, 0.2, 3.0, 0.5 }, { 7.0, 1.0, 3.0, 0.1 } }; vnl_matrix<double> cost( &cost_val[0][0], 3, 4 ); unsigned solution[] = { 1, 0, 3 }; run_test( cost, solution ); } { // a white box test where the row-by-row minimum is not the // solution vcl_cout << "\n\nTest when row-by-row min != optimal\n"; double cost_val[3][4] = { { 2.0, 1.0, 5.0, 3.0 }, { 0.5, 6.0, 3.0, 0.5 }, { 0.1, 1.0, 3.0, 0.2 } }; vnl_matrix<double> cost( &cost_val[0][0], 3, 4 ); unsigned solution[] = { 1, 3, 0 }; run_test( cost, solution ); } { double cost_val[5][3] = { { 2.0, 0.5, 7.0 }, { 1.1, 6.0, 1.0 }, { 1.0, 2.0, 1.0 }, { 5.0, 3.0, 3.0 }, { 3.0, 0.5, 0.1 } }; vnl_matrix<double> cost( &cost_val[0][0], 5, 3 ); unsigned solution[] = { 1, unsigned(-1), 0, unsigned(-1), 2 }; run_test( cost, solution ); } double Inf = vcl_numeric_limits<double>::infinity(); { vcl_cout << "\n\nTest with Inf\n"; double cost_val[5][3] = { { 2.0, 0.5, 7.0 }, { 1.1, 6.0, 1.0 }, { 1.0, 2.0, 1.0 }, { Inf, 3.0, 3.0 }, { 3.0, 0.5, 0.1 } }; vnl_matrix<double> cost( &cost_val[0][0], 5, 3 ); unsigned solution[] = { 1, unsigned(-1), 0, unsigned(-1), 2 }; run_test( cost, solution ); } { vcl_cout << "\n\nTest with Inf, greedy not optimal\n"; double cost_val[5][3] = { { 2.0, 0.5, 7.0 }, { 1.1, 6.0, 1.0 }, { 1.0, 2.0, 1.0 }, { Inf, 3.0, 3.0 }, { 3.0, 0.5, 0.1 } }; vnl_matrix<double> cost( &cost_val[0][0], 5, 3 ); unsigned solution[] = { 1, unsigned(-1), 0, unsigned(-1), 2 }; run_test( cost, solution ); } // Verify that an O(mn) problem with m<<n does not explode into a // O(n^2) problem. { vcl_cout << "\n\nTest that O(N) is doesn't become O(N^2)\n"; // MN ~= 800 KB, N^2 ~= 20 GB test_skewed_problem( 2, 50000 ); test_skewed_problem( 50000, 2 ); } } TESTMAIN_ARGS( test_hungarian_algorithm )
30.140969
78
0.489769
eile
63a33cdfce5815ae624ad6c75e3e6fcfd6355de9
5,549
cc
C++
src/cxx/testbed/testbed.cc
emily33901/Argon
3c06ee562027540702114d0efacb6b12c767a921
[ "MIT" ]
19
2018-11-22T23:02:22.000Z
2022-02-13T22:26:19.000Z
src/cxx/testbed/testbed.cc
josh33901/Argon
3c06ee562027540702114d0efacb6b12c767a921
[ "MIT" ]
2
2019-03-20T11:42:27.000Z
2020-07-16T12:43:04.000Z
src/cxx/testbed/testbed.cc
josh33901/Argon
3c06ee562027540702114d0efacb6b12c767a921
[ "MIT" ]
1
2019-09-09T10:48:12.000Z
2019-09-09T10:48:12.000Z
#include "testbed.hh" #ifdef _MSC_VER const char *steam_path = "steamclient.dll"; #else const char *steam_path = "./libsteamclient.so"; #endif #define check_null(var) \ if (!var) { \ printf(#var " is null!\n"); \ return false; \ } bool load_steam_dll() { #ifdef _MSC_VER auto handle = LoadLibrary(steam_path); if (handle == nullptr) { printf("Unable to load steam from steam_path\n"); return false; } steam::create_interface = (CreateInterfaceFn)GetProcAddress(handle, "CreateInterface"); steam::get_next_callback = (GetCallbackFn)GetProcAddress(handle, "Steam_BGetCallback"); steam::free_last_callback = (FreeCallbackFn)GetProcAddress(handle, "Steam_FreeLastCallback"); #else auto handle = dlopen(steam_path, RTLD_NOW); if (handle == nullptr) { char *error = dlerror(); printf("Unable to load steam from steam_path\n"); printf("Error: %s\n", error); return false; } steam::create_interface = (CreateInterfaceFn)dlsym(handle, "CreateInterface"); steam::get_next_callback = (GetCallbackFn)dlsym(handle, "Steam_BGetCallback"); steam::free_last_callback = (FreeCallbackFn)dlsym(handle, "Steam_FreeLastCallback"); #endif check_null(steam::create_interface); check_null(steam::get_next_callback); check_null(steam::free_last_callback); return true; } bool get_steam_interfaces() { steam::engine = (IClientEngine005 *)steam::create_interface("CLIENTENGINE_INTERFACE_VERSION005"); steam::client = (ISteamClient017 *)steam::create_interface("SteamClient017"); check_null(steam::client); check_null(steam::engine); steam::pipe_handle = 0; steam::user_handle = 0; steam::user_handle = steam::engine->CreateLocalUser(&steam::pipe_handle, k_EAccountTypeIndividual); check_null(steam::pipe_handle); check_null(steam::user_handle); if (!steam::engine->IsValidHSteamUserPipe(steam::pipe_handle, steam::user_handle)) { printf("'valid' (non zero) user and pipe handle are not valid!\nThis is probably a bug.\n"); return false; } steam::user = (IClientUser001 *)steam::engine->GetIClientUser( steam::user_handle, steam::pipe_handle, "CLIENTUSER_INTERFACE_VERSION001"); steam::client_friends = (IClientFriends001 *)steam::engine->GetIClientFriends( steam::user_handle, steam::pipe_handle, "CLIENTFRIENDS_INTERFACE_VERSION001"); steam::steam_friends = (ISteamFriends015 *)steam::client->GetISteamFriends( steam::user_handle, steam::pipe_handle, "SteamFriends015"); check_null(steam::user); check_null(steam::steam_friends); check_null(steam::client_friends); return true; } #undef check_null bool run_tests() { // We need a way of checking the output of a test // To see whether it succeeded or failed printf("\n\nMapped Tests!\n\n"); // Use GetISteamUtils as it gets with pipe but no user auto mapped_test = (IMappedTest001 *)steam::client->GetISteamUtils(steam::pipe_handle, "MappedTest001"); int a = 3; int b = 3; int c = 10; auto res = mapped_test->PointerTest(&a, &b, &c); if (a == 4 && b == 5 && c == 6 && res == 15) { printf("PointerTest succeeded\n"); } else { printf("PointerTest failed\n"); printf("Expected 4, 5, 6, 15\n" "Got %d, %d, %d, %d\n", a, b, c, res); } char buffer[1024]; memset(buffer, 0, sizeof(buffer)); strcpy(buffer, "OverrideMe"); int bytes_wrote = mapped_test->BufferTest(buffer, 1024); if (bytes_wrote == 13 && strcmp(buffer, "OverrideMe") == 0) { printf("BufferTest succeeded\n"); } else { printf("BufferTest failed\n"); printf("Expected '13 characters', 13\n" "Got '%s', %d\n", buffer, bytes_wrote); } MappedTestStruct s; memset(&s, 0x11, sizeof(MappedTestStruct)); mapped_test->TestStruct(&s, sizeof(MappedTestStruct)); printf("StructTest: Testing struct alignment in buffers\n"); printf("%hhx %x %x %hhx %llx\n", s.a, s.b, s.c, s.d, s.e); printf("\n\nMapped tests finished\n\n"); return true; } void login_to_steam() { char username[128]; char password[128]; printf("Enter your username: "); scanf("%128s", username); printf("Enter your password: "); scanf("%128s", password); steam::user->LogOnWithPassword(username, password); } #include "listener.hh" int main(int argc, const char **argv) { if (!load_steam_dll()) { printf("Unable to load the steam dll from %s\n", steam_path); return 1; } if (!get_steam_interfaces()) { printf("Unable to get steam interfaces\n"); return 1; } ListenerRegister::register_all(); login_to_steam(); while (true) { steam::process_callbacks(); sleep(1); } getc(stdin); return 0; } // #pragma pack(push, 4) // struct packing_helper { // uint8 byte_a; // uint16 align_16; // uint8 byte_b; // uint32 align_32; // uint8 byte_c; // uint64 align_64; // }; // enum class packing_test { // a = offsetof(packing_helper, align_16) - offsetof(packing_helper, byte_a), // b = offsetof(packing_helper, align_32) - offsetof(packing_helper, byte_b), // c = offsetof(packing_helper, align_64) - offsetof(packing_helper, byte_c), // }; // #pragma pack(pop)
27.470297
108
0.633628
emily33901
63a5586719e42571233ea047d1fd02428db1a4b7
314
cpp
C++
DSAA2/TestStackAr.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
5
2017-03-30T23:23:08.000Z
2020-11-08T00:34:46.000Z
DSAA2/TestStackAr.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
null
null
null
DSAA2/TestStackAr.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
1
2019-04-12T13:17:31.000Z
2019-04-12T13:17:31.000Z
#include <iostream.h> #include "StackAr.h" int main( ) { Stack<int> s; for( int i = 0; i < 10; i++ ) s.push( i ); while( !s.isEmpty( ) ) cout << s.topAndPop( ) << endl; return 0; }
19.625
47
0.328025
crosslife
63a8693bdd8f506c846a79bdf7dcbe1c097fe50b
8,914
cpp
C++
planb_hw/src/hardware_node.cpp
liunx/planb_ros2
a9417a9699626f007752a3706d2b26c364075a92
[ "Apache-2.0" ]
null
null
null
planb_hw/src/hardware_node.cpp
liunx/planb_ros2
a9417a9699626f007752a3706d2b26c364075a92
[ "Apache-2.0" ]
null
null
null
planb_hw/src/hardware_node.cpp
liunx/planb_ros2
a9417a9699626f007752a3706d2b26c364075a92
[ "Apache-2.0" ]
null
null
null
#include <thread> #include <mraa.hpp> #include "planb_hw/hardware_node.hpp" #include "planb_common/common.hpp" using namespace std::chrono_literals; using std::placeholders::_1; HardwareNode::HardwareNode(const rclcpp::NodeOptions &options) : Node("hardware", options), status_("OFF") { std::string dev_path = this->declare_parameter("dev_path", "/dev/ttyS5"); int baud = this->declare_parameter("baud", 115200); serial_init(dev_path, baud); pub_status_ = this->create_publisher<std_msgs::msg::String>("/planb/hardware/status", 1); sub_cmd_ = this->create_subscription<planb_interfaces::msg::Cmd>( "/planb/hardware/cmd", 1, std::bind(&HardwareNode::cmd_callback, this, _1)); sub_robot_ = this->create_subscription<planb_interfaces::msg::Robot>( "/planb/hardware/robot", 1, std::bind(&HardwareNode::robot_callback, this, _1)); } HardwareNode::~HardwareNode() { uint8_t cmd[16] = {0xFF, 0xFF, 0xF0, 0xF0}; uart_->write((char *)cmd, 16); uart_->close(); } void HardwareNode::serial_init(std::string &dev_path, const int baud) { uart_ = std::make_shared<mraa::Uart>(dev_path); if (uart_->setBaudRate(baud) != mraa::SUCCESS) { RCLCPP_ERROR(this->get_logger(), "Error setting parity on UART"); return; } if (uart_->setMode(8, mraa::UART_PARITY_NONE, 1) != mraa::SUCCESS) { RCLCPP_ERROR(this->get_logger(), "Error setting parity on UART"); return; } if (uart_->setFlowcontrol(false, false) != mraa::SUCCESS) { RCLCPP_ERROR(this->get_logger(), "Error setting flow control UART"); return; } uint8_t cmd[16] = {0xFF, 0xFF, 0xF1, 0xF1}; uart_->write((char *)cmd, 16); } void HardwareNode::publish_status(const std::string &status) { std_msgs::msg::String msg; msg.data = status; status_ = status; pub_status_->publish(std::move(msg)); } void HardwareNode::turn_on() { publish_status("ON"); } void HardwareNode::turn_off() { publish_status("OFF"); } void HardwareNode::cmd_callback(const planb_interfaces::msg::Cmd &msg) { switch (msg.cmd) { case planb::CMD_TURN_ON: turn_on(); break; case planb::CMD_TURN_OFF: turn_off(); break; default: break; } } void HardwareNode::normal_mode(const planb_interfaces::msg::Robot &msg) { // servos uint8_t angle = (uint8_t)(90 + msg.servo.angle); if (msg.servo.left_front > 0) control_data_[0] = angle; if (msg.servo.left_tail > 0) control_data_[1] = angle; if (msg.servo.right_front > 0) control_data_[2] = angle; if (msg.servo.right_tail > 0) control_data_[3] = angle; // motors uint8_t motors[6] = { msg.motor.left_front, msg.motor.left_middle, msg.motor.left_tail, msg.motor.right_front, msg.motor.right_middle, msg.motor.right_tail}; uint8_t accel = (uint8_t)abs(msg.motor.accel); for (int i = 0; i < 6; i++) { if (motors[i] <= 0) continue; if (msg.motor.accel < 0) { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = accel; } else if (msg.motor.accel > 0) { control_data_[4 + 2 * i] = accel; control_data_[4 + 2 * i + 1] = 0; } else { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = 0; } } tx_data(); } void HardwareNode::accel_circle(const int accel) { // motors uint8_t _accel = (uint8_t)abs(accel); for (int i = 0; i < 3; i++) { if (accel < 0) { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = _accel; } else if (accel > 0) { control_data_[4 + 2 * i] = _accel; control_data_[4 + 2 * i + 1] = 0; } else { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = 0; } } for (int i = 3; i < 6; i++) { if (accel < 0) { control_data_[4 + 2 * i] = _accel; control_data_[4 + 2 * i + 1] = 0; } else if (accel > 0) { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = _accel; } else { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = 0; } } } void HardwareNode::circle_mode(const planb_interfaces::msg::Robot &msg) { // servos uint8_t angle = (uint8_t)std::round(std::atan(d1 / d2) * 180 / PI); control_data_[0] = 90 + angle; control_data_[1] = 90 - angle; control_data_[2] = 90 - angle; control_data_[3] = 90 + angle; // motors if (msg.motor.accel > 0) accel_circle(100); else if (msg.motor.accel < 0) accel_circle(-100); tx_data(); std::this_thread::sleep_for(30ms); accel_circle(msg.motor.accel); tx_data(); } void HardwareNode::accel_arckerman(const int accel) { // motors uint8_t _accel = (uint8_t)abs(accel); std::vector<uint8_t> accels; if (accel < 0) accels = calc_accel((float)angle_, _accel, true); else accels = calc_accel((float)angle_, _accel, false); for (int i = 0; i < 6; i++) { if (accel < 0) { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = accels[i]; } else if (accel > 0) { control_data_[4 + 2 * i] = accels[i]; control_data_[4 + 2 * i + 1] = 0; } else { control_data_[4 + 2 * i] = 0; control_data_[4 + 2 * i + 1] = 0; } } } void HardwareNode::arckerman_mode(const planb_interfaces::msg::Robot &msg) { // servos std::vector<uint8_t> angles; uint8_t angle = (uint8_t)abs(msg.servo.angle); if (msg.servo.angle < 0) angles = calc_angles(angle, true); else angles = calc_angles(angle, false); control_data_[0] = angles[0]; control_data_[1] = angles[1]; control_data_[2] = angles[2]; control_data_[3] = angles[3]; // motors if (msg.motor.accel > 0) accel_arckerman(100); else if (msg.motor.accel < 0) accel_arckerman(-100); tx_data(); std::this_thread::sleep_for(30ms); accel_arckerman(msg.motor.accel); tx_data(); } void HardwareNode::robot_callback(const planb_interfaces::msg::Robot &msg) { if (msg.mode == 0) { normal_mode(msg); } else if (msg.mode == 1) { circle_mode(msg); } else if (msg.mode == 2) { arckerman_mode(msg); } else { RCLCPP_INFO(this->get_logger(), "Uknown mode: %d!", msg.mode); } } std::vector<uint8_t> HardwareNode::calc_angles(float angle, bool direct_left) { if (angle == 0.0) return {90, 90, 90, 90}; float radius = std::round(d1 + d3 / std::tan(angle * PI / 180)); std::vector<uint8_t> angles; float a1 = std::round(std::atan(d3 / (d1 + radius)) * 180 / PI); float a2 = std::round(std::atan(d2 / (d1 + radius)) * 180 / PI); float a3 = std::round(std::atan(d3 / (radius - d1)) * 180 / PI); float a4 = std::round(std::atan(d2 / (radius - d1)) * 180 / PI); if (direct_left) return {(uint8_t)(90.0 - a1), (uint8_t)(90.0 + a2), (uint8_t)(90.0 - a3), (uint8_t)(90.0 + a4)}; else return {(uint8_t)(90.0 + a1), (uint8_t)(90.0 - a2), (uint8_t)(90.0 + a3), (uint8_t)(90.0 - a4)}; } std::vector<uint8_t> HardwareNode::calc_accel(float angle, uint8_t accel, bool direct_left) { if (angle == 0.0) return {accel, accel, accel, accel, accel, accel}; float radius = std::round(d1 + d3 / std::tan(angle * PI / 180)); std::vector<uint8_t> accels; uint8_t v1 = std::round(accel * std::sqrt(std::pow(d3, 2.0) + std::pow(d1 + radius, 2.0)) / (radius + d4)); uint8_t v2 = accel; uint8_t v3 = std::round(accel * std::sqrt(std::pow(d2, 2.0) + std::pow(d1 + radius, 2.0)) / (radius + d4)); uint8_t v4 = std::round(accel * std::sqrt(std::pow(d3, 2.0) + std::pow(radius - d1, 2.0)) / (radius + d4)); uint8_t v5 = std::round(accel * (radius - d4) / (radius + d4)); uint8_t v6 = std::round(accel * std::sqrt(std::pow(d2, 2.0) + std::pow(radius - d1, 2.0)) / (radius + d4)); if (direct_left) accels = {v4, v5, v6, v1, v2, v3}; else accels = {v1, v2, v3, v4, v5, v6}; float _max = *std::max_element(accels.begin(), accels.end()); if (_max > 100.0) { float rate = 100.0 / _max; for (int i = 0; i < 6; i++) { accels[i] = std::round(accels[i] * rate); } } return accels; } void HardwareNode::tx_data() { uart_->write((char *)control_data_, 16); }
26.688623
111
0.549697
liunx
63aa566999727b89505e2fb7aa8885bb737cb75f
581
cc
C++
tests/application/test_bitmap_application.cc
wujiazheng2020/simple_stl
f04ccd049a92e463bde4c34fed67679fb5822eb9
[ "MIT" ]
6
2021-08-31T04:44:50.000Z
2022-03-10T15:15:29.000Z
tests/application/test_bitmap_application.cc
wujiazheng2020/simple_stl
f04ccd049a92e463bde4c34fed67679fb5822eb9
[ "MIT" ]
null
null
null
tests/application/test_bitmap_application.cc
wujiazheng2020/simple_stl
f04ccd049a92e463bde4c34fed67679fb5822eb9
[ "MIT" ]
null
null
null
/* * Copyright 2021 Jiazheng Wu * * FileName: test_bitmap_algorithm.cc * * Author: Jiazheng Wu * Email: wujiazheng2020@gmail.com * Licensed under the MIT License */ #include <glog/logging.h> #include <gtest/gtest.h> #include <vector> #include "simple_stl/application/bitmap_application/calculate_prime.h" static const std::vector<int> prime_vec = sstl::CalculatePrimeBelowN<10000>(); TEST(BIT_MAP, BitMapBasic) { for (uint i = 1; i < prime_vec.size(); ++i) { std::cout << prime_vec[i] << " "; if (i % 15 == 0) { std::cout << std::endl; } } }
20.034483
70
0.652324
wujiazheng2020
63af9a26133a8a77a2a5f5b3af040bd8c56ba66f
621
cpp
C++
src/common/factorial.cpp
ull-esit-sistemas-operativos/ssoo-ejemplos
f59d606f45fd3cc05b605472db0dd90d3f209b71
[ "CC0-1.0" ]
1
2021-12-29T12:44:43.000Z
2021-12-29T12:44:43.000Z
src/common/factorial.cpp
ull-esit-sistemas-operativos/ssoo-ejemplos
f59d606f45fd3cc05b605472db0dd90d3f209b71
[ "CC0-1.0" ]
null
null
null
src/common/factorial.cpp
ull-esit-sistemas-operativos/ssoo-ejemplos
f59d606f45fd3cc05b605472db0dd90d3f209b71
[ "CC0-1.0" ]
null
null
null
// factorial.cpp - Funciones comunes a los ejemplos del factorial. // #include <iostream> #include "factorial.hpp" int get_user_input() { std::cout << "[PADRE] Introduzca un número: "; std::cout.flush(); int number; std::cin >> number; return number; } int calculate_factorial(int number) { std::cout << "[HIJO] Calculando..."; std::cout.flush(); int factorial = 1; for ( int i = 2; i <= number; i++ ) { factorial = factorial * i; std::cout << '.'; std::cout.flush(); } std::cout << '\n'; std::cout.flush(); return factorial; }
16.783784
66
0.553945
ull-esit-sistemas-operativos
63afc7a75dea3a330af51fc7926b3a22e2060645
15,712
cc
C++
mysql_sys/my_error.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
mysql_sys/my_error.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
mysql_sys/my_error.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
/* Copyright (c) 2000, 2017, Oracle 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.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. Without limiting anything contained in the foregoing, this file, which is part of C Driver for MySQL (Connector/C), is also subject to the Universal FOSS Exception, version 1.0, a copy of which can be found at http://oss.oracle.com/licenses/universal-foss-exception. 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, version 2.0, 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 mysys/my_error.cc */ #include <errno.h> #include <stdarg.h> #ifdef __linux__ #include <features.h> #endif #include <stdio.h> #include <string.h> #include <sys/types.h> #include "m_ctype.h" #include "m_string.h" #include "my_base.h" #include "my_dbug.h" #include "my_inttypes.h" #include "my_loglevel.h" #include "my_sys.h" #include "mysql/service_mysql_alloc.h" #include "my_handler_errors.h" #include "mysys_priv.h" #include "mysys_err.h" #include "mysql_strings/mb_wc.h" /* Max length of a error message. Should be kept in sync with MYSQL_ERRMSG_SIZE. */ #define ERRMSGSIZE (512) /* Define some external variables for error handling */ /* WARNING! my_error family functions have to be used according following rules: - if message has no parameters, use my_message(ER_CODE, ER(ER_CODE), MYF(N)) - if message has parameters and is registered: my_error(ER_CODE, MYF(N), ...) - for free-form messages use my_printf_error(ER_CODE, format, MYF(N), ...) These three send their messages using error_handler_hook, which normally means we'll send them to the client if we have one, or to error-log / stderr otherwise. */ /* Message texts are registered into a linked list of 'my_err_head' structs. Each struct contains (1.) a pointer to a function that returns C character strings with '\0' termination (2.) the error number for the first message in the array (array index 0) (3.) the error number for the last message in the array (array index (last - first)). The function may return NULL pointers and pointers to empty strings. Both kinds will be translated to "Unknown error %d.", if my_error() is called with a respective error number. The list of header structs is sorted in increasing order of error numbers. Negative error numbers are allowed. Overlap of error numbers is not allowed. Not registered error numbers will be translated to "Unknown error %d.". */ static struct my_err_head { struct my_err_head *meh_next; /* chain link */ const char *(*get_errmsg)(int); /* returns error message format */ int meh_first; /* error number matching array slot 0 */ int meh_last; /* error number matching last slot */ } my_errmsgs_globerrs = {NULL, get_global_errmsg, EE_ERROR_FIRST, EE_ERROR_LAST}; static struct my_err_head *my_errmsgs_list = &my_errmsgs_globerrs; /** Get a string describing a system or handler error. thread-safe. @param buf a buffer in which to return the error message @param len the size of the aforementioned buffer @param nr the error number @retval buf always buf. for signature compatibility with strerror(3). */ char *my_strerror(char *buf, size_t len, int nr) { char *msg = NULL; buf[0] = '\0'; /* failsafe */ /* These (handler-) error messages are shared by perror, as required by the principle of least surprise. */ if ((nr >= HA_ERR_FIRST) && (nr <= HA_ERR_LAST)) msg = (char *)handler_error_messages[nr - HA_ERR_FIRST]; if (msg != NULL) strmake(buf, msg, len - 1); else { /* On Windows, do things the Windows way. On a system that supports both the GNU and the XSI variant, use whichever was configured (GNU); if this choice is not advertised, use the default (POSIX/XSI). Testing for __GNUC__ is not sufficient to determine whether this choice exists. */ #if defined(_WIN32) strerror_s(buf, len, nr); if (thr_winerr() != 0) { /* If error code is EINVAL, and Windows Error code has been set, we append the Windows error code to the message. */ if (nr == EINVAL) { char tmp_buff[256]; snprintf(tmp_buff, sizeof(tmp_buff), " [OS Error Code : 0x%x]", thr_winerr()); strcat_s(buf, len, tmp_buff); } set_thr_winerr(0); } #elif ((defined _POSIX_C_SOURCE && (_POSIX_C_SOURCE >= 200112L)) || \ (defined _XOPEN_SOURCE && (_XOPEN_SOURCE >= 600))) && \ !defined _GNU_SOURCE strerror_r(nr, buf, len); /* I can build with or without GNU */ #elif defined(__GLIBC__) && defined(_GNU_SOURCE) char *r = strerror_r(nr, buf, len); if (r != buf) /* Want to help, GNU? */ strmake(buf, r, len - 1); /* Then don't. */ #else strerror_r(nr, buf, len); #endif } /* strerror() return values are implementation-dependent, so let's be pragmatic. */ if (!buf[0] || !strcmp(buf, "No error information")) strmake(buf, "Unknown error", len - 1); return buf; } /** @brief Get an error format string from one of the my_error_register()ed sets @note NULL values are possible even within a registered range. @param nr Errno @retval NULL if no message is registered for this error number @retval str C-string */ const char *my_get_err_msg(int nr) { const char *format; struct my_err_head *meh_p; /* Search for the range this error is in. */ for (meh_p = my_errmsgs_list; meh_p; meh_p = meh_p->meh_next) if (nr <= meh_p->meh_last) break; /* If we found the range this error number is in, get the format string. If the string is empty, or a NULL pointer, or if we're out of return, we return NULL. */ if (!(format = (meh_p && (nr >= meh_p->meh_first)) ? meh_p->get_errmsg(nr) : NULL) || !*format) return NULL; return format; } /** Fill in and print a previously registered error message. @note Goes through the (sole) function registered in error_handler_hook @param nr error number @param MyFlags Flags @param ... variable list matching that error format string */ void my_error(int nr, myf MyFlags, ...) { const char *format; char ebuff[ERRMSGSIZE]; DBUG_ENTER("my_error"); DBUG_PRINT("my", ("nr: %d MyFlags: %d errno: %d", nr, MyFlags, errno)); if (!(format = my_get_err_msg(nr))) (void)snprintf(ebuff, sizeof(ebuff), "Unknown error %d", nr); else { va_list args; va_start(args, MyFlags); (void)vsnprintf(ebuff, sizeof(ebuff), format, args); va_end(args); } /* Since this function is an error function, it will frequently be given values that are too long (and thus truncated on byte boundaries, not code point or grapheme boundaries), values that are binary, etc.. Go through and replace every malformed UTF-8 byte with a question mark, so that the result is safe to send to the client and makes sense to read for the user. */ for (char *ptr = ebuff, *end = ebuff + strlen(ebuff); ptr != end;) { my_wc_t ignored; int len = my_mb_wc_utf8mb4(&ignored, pointer_cast<const uchar *>(ptr), pointer_cast<const uchar *>(end)); if (len > 0) { ptr += len; } else { *ptr++ = '?'; } } (*error_handler_hook)(nr, ebuff, MyFlags); DBUG_VOID_RETURN; } /** Print an error message. @note Goes through the (sole) function registered in error_handler_hook @param error error number @param format format string @param MyFlags Flags @param ... variable list matching that error format string */ void my_printf_error(uint error, const char *format, myf MyFlags, ...) { va_list args; char ebuff[ERRMSGSIZE]; DBUG_ENTER("my_printf_error"); DBUG_PRINT("my", ("nr: %d MyFlags: %d errno: %d Format: %s", error, MyFlags, errno, format)); va_start(args, MyFlags); (void)vsnprintf(ebuff, sizeof(ebuff), format, args); va_end(args); (*error_handler_hook)(error, ebuff, MyFlags); DBUG_VOID_RETURN; } /** Print an error message. @note Goes through the (sole) function registered in error_handler_hook @param error error number @param format format string @param MyFlags Flags @param ap variable list matching that error format string */ void my_printv_error(uint error, const char *format, myf MyFlags, va_list ap) { char ebuff[ERRMSGSIZE]; DBUG_ENTER("my_printv_error"); DBUG_PRINT("my", ("nr: %d MyFlags: %d errno: %d format: %s", error, MyFlags, errno, format)); (void)vsnprintf(ebuff, sizeof(ebuff), format, ap); (*error_handler_hook)(error, ebuff, MyFlags); DBUG_VOID_RETURN; } /** Print an error message. @note Goes through the (sole) function registered in error_handler_hook @param error error number @param str error message @param MyFlags Flags */ void my_message(uint error, const char *str, myf MyFlags) { (*error_handler_hook)(error, str, MyFlags); } /** Register error messages for use with my_error(). The function is expected to return addresses to NUL-terminated C character strings. NULL pointers and empty strings ("") are allowed. These will be mapped to "Unknown error" when my_error() is called with a matching error number. This function registers the error numbers 'first' to 'last'. No overlapping with previously registered error numbers is allowed. @param get_errmsg function that returns error messages @param first error number of first message in the array @param last error number of last message in the array @retval 0 OK @retval != 0 Error */ int my_error_register(const char *(*get_errmsg)(int), int first, int last) { struct my_err_head *meh_p; struct my_err_head **search_meh_pp; /* Allocate a new header structure. */ if (!(meh_p = (struct my_err_head *)my_malloc( key_memory_my_err_head, sizeof(struct my_err_head), MYF(MY_WME)))) return 1; meh_p->get_errmsg = get_errmsg; meh_p->meh_first = first; meh_p->meh_last = last; /* Search for the right position in the list. */ for (search_meh_pp = &my_errmsgs_list; *search_meh_pp; search_meh_pp = &(*search_meh_pp)->meh_next) { if ((*search_meh_pp)->meh_last > first) break; } /* Error numbers must be unique. No overlapping is allowed. */ if (*search_meh_pp && ((*search_meh_pp)->meh_first <= last)) { my_free(meh_p); return 1; } /* Insert header into the chain. */ meh_p->meh_next = *search_meh_pp; *search_meh_pp = meh_p; return 0; } /** Unregister formerly registered error messages. This function unregisters the error numbers 'first' to 'last'. These must have been previously registered by my_error_register(). 'first' and 'last' must exactly match the registration. If a matching registration is present, the header is removed from the list. @param first error number of first message @param last error number of last message @retval true Error, no such number range registered. @retval false OK */ bool my_error_unregister(int first, int last) { struct my_err_head *meh_p; struct my_err_head **search_meh_pp; /* Search for the registration in the list. */ for (search_meh_pp = &my_errmsgs_list; *search_meh_pp; search_meh_pp = &(*search_meh_pp)->meh_next) { if (((*search_meh_pp)->meh_first == first) && ((*search_meh_pp)->meh_last == last)) break; } if (!*search_meh_pp) return true; /* Remove header from the chain. */ meh_p = *search_meh_pp; *search_meh_pp = meh_p->meh_next; /* Free the header. */ my_free(meh_p); return false; } /** Unregister all formerly registered error messages. This function unregisters all error numbers that previously have been previously registered by my_error_register(). All headers are removed from the list; the messages themselves are not released here as they may be static. */ void my_error_unregister_all(void) { struct my_err_head *cursor, *saved_next; for (cursor = my_errmsgs_globerrs.meh_next; cursor != NULL; cursor = saved_next) { /* We need this ptr, but we're about to free its container, so save it. */ saved_next = cursor->meh_next; my_free(cursor); } my_errmsgs_globerrs.meh_next = NULL; /* Freed in first iteration above. */ my_errmsgs_list = &my_errmsgs_globerrs; } /** Issue a message locally (i.e. on the same host the program is running on, don't transmit to a client). This is the default value for local_message_hook, and therefore the default printer for my_message_local(). mysys users should not call this directly, but go through my_message_local() instead. This printer prepends an Error/Warning/Note label to the string, then prints it to stderr using my_message_stderr(). Since my_message_stderr() appends a '\n', the format string should not end in a newline. @param ll log level: (ERROR|WARNING|INFORMATION)_LEVEL the printer may use these to filter for verbosity @param format a format string a la printf. Should not end in '\n' @param args parameters to go with that format string */ void my_message_local_stderr(enum loglevel ll, const char *format, va_list args) { char buff[1024]; size_t len; DBUG_ENTER("my_message_local_stderr"); len = snprintf( buff, sizeof(buff), "[%s] ", (ll == ERROR_LEVEL ? "ERROR" : ll == WARNING_LEVEL ? "Warning" : "Note")); vsnprintf(buff + len, sizeof(buff) - len, format, args); my_message_stderr(0, buff, MYF(0)); DBUG_VOID_RETURN; } /** Issue a message locally (i.e. on the same host the program is running on, don't transmit to a client). This goes through local_message_hook, i.e. by default, it calls my_message_local_stderr() which prepends an Error/Warning/Note label to the string, then prints it to stderr using my_message_stderr(). More advanced programs can use their own printers; mysqld for instance uses its own error log facilities which prepend an ISO 8601 / RFC 3339 compliant timestamp etc. @param ll log level: (ERROR|WARNING|INFORMATION)_LEVEL the printer may use these to filter for verbosity @param format a format string a la printf. Should not end in '\n'. @param ... parameters to go with that format string */ void my_message_local(enum loglevel ll, const char *format, ...) { va_list args; DBUG_ENTER("local_print_error"); va_start(args, format); (*local_message_hook)(ll, format, args); va_end(args); DBUG_VOID_RETURN; }
32.196721
80
0.683745
realnickel
63b2ddb8a74191cec522650e83d3e3d027aaed9d
6,463
cpp
C++
Web/src/HttpHandler/HttpHeader.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Web/src/HttpHandler/HttpHeader.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Web/src/HttpHandler/HttpHeader.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (C) 2004-2011 by Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of version 2.1 of the GNU Lesser // General Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // #include "HttpHandler.h" ////////////////////////////////////////////////////////////////// /// <summary> /// Constructor. Initialize string property collection. /// </summary> MgHttpHeader::MgHttpHeader() { // Nothing here yet } /// <summary> /// Adds the header name and value to the collection. /// header name - case-insensitive /// header value - case-insensitive /// </summary> /// <param name="name">Input /// Name of the header /// Two header can have same name. /// </param> /// <param name="value">Input /// Value corresponding to the header. /// NULL value and empty string is NOT allowed. /// </param> /// <returns> /// TRUE - Header name is successfully added. /// FALSE - Header could not be added. /// Possible cause - header value is NULL. /// </returns> bool MgHttpHeader::AddHeader(CREFSTRING name, CREFSTRING value) { if (value.length()!=0 && !m_headerCollection.Contains(name)) { m_headerCollection.Add(name, value); return true; } return false; } /// <summary> /// Removes the header name and value from the collection. /// header name - case-insensitive /// </summary> /// <param name="name">Input /// Name of the header to be removed. /// </param> /// <returns> /// TRUE - header name is successfully removed. /// FALSE - header name could not be removed. /// Possible cause is header name does not exist. /// </returns> bool MgHttpHeader::RemoveHeader(CREFSTRING name) { if (m_headerCollection.Contains(name)) { m_headerCollection.Remove(name); return true; } return false; } /// <summary> /// Retrieve the value for the specified header. /// header name - case-insensitive /// </summary> /// <param name="name">Input /// Name of the header for which value to be retrieved. /// </param> /// <returns> /// Value for the specified header or empty string if header does not exist. /// </returns> STRING MgHttpHeader::GetHeaderValue(CREFSTRING name) { if (m_headerCollection.Contains(name)) { return m_headerCollection.GetValue(name); } return L""; } /// <summary> /// Update the value for the specified header. /// header name - case-insensitive /// header value - case-insensitive /// </summary> /// <param name="name">Input /// Name of the header to be updated. /// </param> /// <param name="value">Input /// Value corresponding to the header. /// NULL value and empty string is NOT allowed. /// </param> /// <returns> /// TRUE - header is successfully updated. /// FALSE - header could not be updated. /// Possible cause is header does not exist or value is NULL. /// </returns> bool MgHttpHeader::SetHeaderValue(CREFSTRING name, CREFSTRING value) { if (m_headerCollection.Contains(name)) { m_headerCollection.SetValue(name, value); return true; } return false; } /// <summary> /// Returns the value of the specified header as a long value that represents a Date object. /// Use this method with headers that contain dates, such as If-Modified-Since. /// The date is returned as the number of milliseconds since January 1, 1970 GMT. /// </summary> /// <param name="name">Input /// Name of the header (case insensitive). /// </param> /// <returns> /// long - The date is returned as the number of milliseconds since January 1, 1970 GMT /// S_MISSING_HEADER - request did not have a header of the specified name /// S_CANNOT_CONVERT - header can't be converted to a date /// </returns> long MgHttpHeader::GetDateHeader(CREFSTRING name) { // TODO: Figure out which Date manipulation functions to use if (m_headerCollection.Contains(name)) { return 1; } else return 2; } /// <summary> /// Returns the value of the specified request header as an int. /// </summary> /// <param name="name">Input /// Name of the header (case-insensitive). /// </param> /// <returns> /// INT32 - An integer value /// S_MISSING_HEADER - request did not have a header of the specified name /// S_CANNOT_CONVERT - header can't be converted to an integer. /// </returns> INT32 MgHttpHeader::GetIntHeader(CREFSTRING name) { if (m_headerCollection.Contains(name)) { string headerIntString = MgUtil::WideCharToMultiByte(m_headerCollection.GetValue(name)); const char* headerIntCString = headerIntString.c_str(); // Check for non-digits in string for (unsigned int i=0; i < strlen(headerIntCString); i++) if (!isdigit(headerIntCString[i])) return S_CANNOT_CONVERT; return atoi(headerIntCString); } else return S_MISSING_HEADER; } /// <summary> /// Retrieve the list of all headers. /// </summary> /// <returns> /// A string collection containing names of all headers. /// </returns> MgStringCollection* MgHttpHeader::GetHeaderNames() { Ptr<MgStringCollection> mgsCollection; mgsCollection = new MgStringCollection(); for (int i = 0; i < m_headerCollection.GetCount(); i++) { mgsCollection->Add(m_headerCollection.GetName(i)); } return SAFE_ADDREF((MgStringCollection*)mgsCollection); } /// <summary> /// Retrieve the list of all possible values for a header. /// </summary> /// <returns> /// A string collection containing possible values of a header. /// </returns> MgStringCollection* MgHttpHeader::GetHeaders(CREFSTRING name) { MG_UNUSED_ARG(name); // TODO: Return proper string collection here Ptr<MgStringCollection> mgsCollection; mgsCollection = new MgStringCollection(); return SAFE_ADDREF((MgStringCollection*)mgsCollection); } void MgHttpHeader::Dispose() { delete this; } INT32 MgHttpHeader::GetClassId() { return m_cls_id; } MgHttpHeader::~MgHttpHeader() { }
28.1
96
0.674455
achilex
63b37238c7561064e42e89fb02b622a4a442839d
344
cpp
C++
Array Ques Missing Value.cpp
priyamittal15/Leetcode_Solutions
21cb9c09e053425dba66acd62240399b1a35fba0
[ "Apache-2.0" ]
1
2022-01-28T08:07:32.000Z
2022-01-28T08:07:32.000Z
Array Ques Missing Value.cpp
priyamittal15/Leetcode_Solutions
21cb9c09e053425dba66acd62240399b1a35fba0
[ "Apache-2.0" ]
null
null
null
Array Ques Missing Value.cpp
priyamittal15/Leetcode_Solutions
21cb9c09e053425dba66acd62240399b1a35fba0
[ "Apache-2.0" ]
1
2022-03-16T14:46:09.000Z
2022-03-16T14:46:09.000Z
#include<iostream> using namespace std; int main(void){ int arr[]={0,-9,1,3,-4,5}; int n=6; int res[n]; for(int i=0;i<n;i++){ if(arr[i]>=0){ res[i]=arr[i]; } else{ } } for(int i=0;i<n;i++){ cout<<res[i]; } for(int i=0;i<n;i++){ if(res[i+1]-res[i]==2){ cout<<i; } } }
11.096774
28
0.418605
priyamittal15
63b3c2a04fa9aeed198000f8618eff88bc84b5d6
3,974
cxx
C++
tests/mlio-test/test_recordio_protobuf_reader.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
null
null
null
tests/mlio-test/test_recordio_protobuf_reader.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
2
2020-04-08T01:37:44.000Z
2020-04-14T20:14:07.000Z
tests/mlio-test/test_recordio_protobuf_reader.cxx
rizwangilani/ml-io
d9572227281168139c4e99d79a6d2ebc83323a61
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <mlio.h> namespace mlio { class test_recordio_protobuf_reader : public ::testing::Test { protected: test_recordio_protobuf_reader() = default; ~test_recordio_protobuf_reader() override; protected: std::string const resources_path_ = "../resources/recordio/"; std::string const complete_records_path_ = resources_path_ + "complete_records.pr"; std::string const split_records_path_ = resources_path_ + "split_records.pr"; std::string const corrupt_split_records_path_ = resources_path_ + "corrupted_split_records.pr"; }; test_recordio_protobuf_reader::~test_recordio_protobuf_reader() = default; TEST_F(test_recordio_protobuf_reader, test_complete_records_path) { mlio::data_reader_params prm{}; prm.dataset.emplace_back( mlio::make_intrusive<mlio::file>(complete_records_path_)); prm.batch_size = 1; auto reader = mlio::make_intrusive<mlio::recordio_protobuf_reader>(prm); for (int i = 0; i < 2; i++) { mlio::intrusive_ptr<mlio::example> exm; while ((exm = reader->read_example()) != nullptr) { } reader->reset(); } EXPECT_TRUE(true); } TEST_F(test_recordio_protobuf_reader, test_split_records_path) { mlio::initialize(); mlio::data_reader_params prm{}; prm.dataset.emplace_back( mlio::make_intrusive<mlio::file>(split_records_path_)); prm.batch_size = 1; auto reader = mlio::make_intrusive<mlio::recordio_protobuf_reader>(prm); for (int i = 0; i < 2; i++) { mlio::intrusive_ptr<mlio::example> exm; while ((exm = reader->read_example()) != nullptr) { } reader->reset(); } EXPECT_TRUE(true); } TEST_F(test_recordio_protobuf_reader, test_corrupt_split_records_patH) { mlio::initialize(); // Check that the third record is corrupt. mlio::data_reader_params prm{}; prm.dataset.emplace_back( mlio::make_intrusive<mlio::file>(corrupt_split_records_path_)); prm.batch_size = 10; prm.num_prefetched_batches = 1; std::string error_substring = "The record 13 in the data store"; auto reader = mlio::make_intrusive<mlio::recordio_protobuf_reader>(prm); mlio::intrusive_ptr<mlio::example> exm; // Try to read batch, should fail due to corrupt record try { exm = reader->read_example(); FAIL() << "Expected corrupt error exception on 3rd record."; } catch (data_reader_error const &corrupt_record_err) { EXPECT_TRUE( std::string(corrupt_record_err.what()).find(error_substring) != std::string::npos) << "Error thrown:" + std::string(corrupt_record_err.what()); } catch (...) { FAIL() << "Expected corrupt error exception, not a different error."; } // Try to read batch, should fail again try { exm = reader->read_example(); FAIL() << "Expected corrupt error exception on 3rd record."; } catch (data_reader_error const &corrupt_record_err) { EXPECT_TRUE( std::string(corrupt_record_err.what()).find(error_substring) != std::string::npos) << "Error thrown:" + std::string(corrupt_record_err.what()); } catch (...) { FAIL() << "Expected corrupt error exception, not a different error."; } // Reset reader, expecting same results. reader->reset(); // Try to read batch, should fail again try { exm = reader->read_example(); FAIL() << "Expected corrupt error exception on 3rd record."; } catch (data_reader_error const &corrupt_record_err) { EXPECT_TRUE( std::string(corrupt_record_err.what()).find(error_substring) != std::string::npos) << "Error thrown:" + std::string(corrupt_record_err.what()); } catch (...) { FAIL() << "Expected corrupt error exception, not a different error."; } } } // namespace mlio
31.539683
77
0.648968
rizwangilani
63b55ef9ccd3d06015dda8bc64ec37466375fc61
10,669
cpp
C++
src/device_info_win32.cpp
semenovf/pfs-multimedia
78e2ea9dfe89d2f84d583f768ca35f183773d859
[ "MIT" ]
null
null
null
src/device_info_win32.cpp
semenovf/pfs-multimedia
78e2ea9dfe89d2f84d583f768ca35f183773d859
[ "MIT" ]
null
null
null
src/device_info_win32.cpp
semenovf/pfs-multimedia
78e2ea9dfe89d2f84d583f768ca35f183773d859
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2021 Vladislav Trifochkin // // This file is part of [multimedia-lib](https://github.com/semenovf/multimedia-lib) library. // // Changelog: // 2021.08.07 Initial version. //////////////////////////////////////////////////////////////////////////////// #include "pfs/multimedia/audio.hpp" #include <mmdeviceapi.h> #include <strmif.h> // ICreateDevEnum #include <functiondiscoverykeys_devpkey.h> // PROPERTYKEY #include <vector> #include <cwchar> namespace pfs { namespace multimedia { namespace audio { // Avoid warning: // warning C4996: 'wcsrtombs': This function or variable may be unsafe. // Consider using wcsrtombs_s instead. To disable // deprecation, use _CRT_SECURE_NO_WARNINGS. See online // help for details. #pragma warning(disable: 4996) static std::string convert_wide (LPCWSTR wstr) { std::mbstate_t state = std::mbstate_t(); std::size_t len = 1 + std::wcsrtombs(nullptr, & wstr, 0, & state); std::string result(len, '\x0'); std::wcsrtombs(& result[0], & wstr, len, & state); return result; } class IMMDeviceEnumerator_initializer { HRESULT hrCoInit {S_FALSE}; IMMDeviceEnumerator ** ppEnumerator {nullptr}; private: void finalize () { if (ppEnumerator && *ppEnumerator) { (*ppEnumerator)->Release(); *ppEnumerator = nullptr; ppEnumerator = nullptr; } if (SUCCEEDED(hrCoInit)) { CoUninitialize(); hrCoInit = S_FALSE; } } public: IMMDeviceEnumerator_initializer (IMMDeviceEnumerator ** pp) : ppEnumerator(pp) { if (pp) { bool success {false}; // Mandatory call to call CoCreateInstance() later hrCoInit = CoInitialize(nullptr); if (SUCCEEDED(hrCoInit)) { // https://docs.microsoft.com/en-gb/windows/win32/coreaudio/mmdevice-api const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); auto hr = CoCreateInstance(CLSID_MMDeviceEnumerator , nullptr , CLSCTX_ALL // CLSCTX_INPROC_SERVER , IID_IMMDeviceEnumerator , reinterpret_cast<void **>(ppEnumerator)); if (SUCCEEDED(hr)) { success = true; } else { // Possible errors: // REGDB_E_CLASSNOTREG - A specified class is not registered in the // registration database. Also can indicate that the type of server // you requested in the CLSCTX enumeration is not registered or the // values for the server types in the registry are corrupt. // E_NOINTERFACE - The specified class does not implement the requested // interface, or the controlling IUnknown does not expose the // requested interface. // There might be error handling here ; } } if (!success) finalize(); } } ~IMMDeviceEnumerator_initializer () { finalize(); } }; class IMMDeviceCollection_initializer { IMMDeviceCollection ** ppEndpoints {nullptr}; private: void finalize () { if (ppEndpoints && *ppEndpoints) { (*ppEndpoints)->Release(); *ppEndpoints = nullptr; ppEndpoints = nullptr; } } public: IMMDeviceCollection_initializer (IMMDeviceCollection ** pp , IMMDeviceEnumerator * pEnumerator , device_mode mode) : ppEndpoints(pp) { if (pEnumerator && pp) { bool success {false}; EDataFlow data_flow = (mode == device_mode::output) ? eRender : eCapture; // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdeviceenumerator-enumaudioendpoints auto hr = pEnumerator->EnumAudioEndpoints(data_flow , DEVICE_STATE_ACTIVE , ppEndpoints); if (SUCCEEDED(hr)) { success = true; } else { // There might be error handling here // NOTE! But there is no apparent reason for the error. ; } if (!success) finalize(); } } ~IMMDeviceCollection_initializer () { finalize(); } }; class IMMDevice_guard { IMMDevice ** ppDevice {nullptr}; public: IMMDevice_guard (IMMDevice ** pp) : ppDevice(pp) {} ~IMMDevice_guard () { if (ppDevice && *ppDevice) { (*ppDevice)->Release(); *ppDevice = nullptr; ppDevice = nullptr; } } }; static bool device_info_helper (IMMDevice * pEndpoint, device_info & di) { bool result = false; if (pEndpoint) { IPropertyStore * pProps = nullptr; // Get the endpoint ID string. // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-getid LPWSTR pwszID = nullptr; auto hr = pEndpoint->GetId(& pwszID); if (SUCCEEDED(hr)) { hr = pEndpoint->OpenPropertyStore(STGM_READ, & pProps); if (SUCCEEDED(hr)) { PROPVARIANT varName; // Initialize container for property value. PropVariantInit(& varName); // Get the endpoint's friendly-name property. hr = pProps->GetValue(PKEY_Device_FriendlyName, & varName); if (SUCCEEDED(hr)) { di.name = convert_wide(pwszID); di.readable_name = convert_wide(varName.pwszVal); PropVariantClear(& varName); result = true; } else { // pProps->GetValue() // There might be error handling here ; } if (pProps) { pProps->Release(); pProps = nullptr; } } else { // pEndpoint->OpenPropertyStore() // There might be error handling here // NOTE! But there is no apparent reason for the error. ; } } else { // pEndpoint->GetId() // There might be error handling here ; } if (pwszID) { CoTaskMemFree(pwszID); pwszID = nullptr; } } else { // There might be error handling here // E_INVALIDARG - Parameter 'device_index' is not a valid device number. ; } if (pEndpoint) { pEndpoint->Release(); pEndpoint = nullptr; } return result; } // Default source/input device static device_info default_device_helper (device_mode mode) { device_info result; IMMDeviceEnumerator * pEnumerator = nullptr; IMMDeviceEnumerator_initializer enumerator_initializer {& pEnumerator}; if (pEnumerator) { IMMDevice * pEndpoint = nullptr; EDataFlow data_flow = (mode == device_mode::output) ? eRender : eCapture; // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdeviceenumerator-getdefaultaudioendpoint auto hr = pEnumerator->GetDefaultAudioEndpoint(data_flow, eConsole, & pEndpoint); IMMDevice_guard endpoint_guard {& pEndpoint}; if (SUCCEEDED(hr) && pEndpoint) { if (!device_info_helper(pEndpoint, result)) { result = device_info{}; } } } return result; } // Default source/input device PFS_MULTIMEDIA_DLL_API device_info default_input_device () { return default_device_helper(device_mode::input); } // Default sink/ouput device PFS_MULTIMEDIA_DLL_API device_info default_output_device () { return default_device_helper(device_mode::output); } // https://docs.microsoft.com/en-us/windows/win32/coreaudio/device-properties PFS_MULTIMEDIA_DLL_API std::vector<device_info> fetch_devices (device_mode mode) { std::vector<device_info> result; IMMDeviceEnumerator * pEnumerator = nullptr; IMMDeviceEnumerator_initializer enumerator_initializer {& pEnumerator}; if (pEnumerator) { IMMDeviceCollection * pEndpoints = nullptr; IMMDeviceCollection_initializer endpoints_initializer {& pEndpoints, pEnumerator, mode}; if (pEndpoints) { // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevicecollection-getcount UINT count = 0; auto hr = pEndpoints->GetCount(& count); if (SUCCEEDED(hr)) { for (UINT device_index = 0; device_index < count; device_index++) { IMMDevice * pEndpoint = nullptr; // https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevicecollection-item hr = pEndpoints->Item(static_cast<UINT>(device_index), & pEndpoint); IMMDevice_guard endpoint_guard {& pEndpoint}; if (SUCCEEDED(hr) && pEndpoint) { device_info di; if (device_info_helper(pEndpoint, di)) { result.push_back(std::move(di)); } } else { // There might be error handling here // E_INVALIDARG - Parameter 'device_index' is not a valid device number. ; } } } else { // pEndpoints->GetCount() // There might be error handling here // NOTE! But there is no apparent reason for the error. ; } } } return result; } }}} // namespace pfs::multimedia::audio
32.330303
133
0.532571
semenovf
63bdedb8292f7432bfe611622e112d983f72d16b
107
hpp
C++
non-stiff/problem-3-conservation-vs-dissipation/include/macro/sides.hpp
ooreilly/sbp
47bf92f3ba3a6146250331a8c657948475f72e7c
[ "MIT" ]
3
2021-09-03T08:55:53.000Z
2021-11-11T02:51:03.000Z
non-stiff/problem-3-conservation-vs-dissipation/include/macro/sides.hpp
ooreilly/sbp
47bf92f3ba3a6146250331a8c657948475f72e7c
[ "MIT" ]
null
null
null
non-stiff/problem-3-conservation-vs-dissipation/include/macro/sides.hpp
ooreilly/sbp
47bf92f3ba3a6146250331a8c657948475f72e7c
[ "MIT" ]
4
2017-05-13T08:27:21.000Z
2021-10-05T08:22:55.000Z
#pragma once #define LEFT 0 #define RIGHT 1 #define BOTTOM 2 #define TOP 3 #define FRONT 4 #define BACK 5
11.888889
16
0.738318
ooreilly
63be27dd8421f94288ac74948f854c7984304875
2,048
cpp
C++
src/Particle/ParticleModule/ModuleSizeOverLifetime.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/Particle/ParticleModule/ModuleSizeOverLifetime.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/Particle/ParticleModule/ModuleSizeOverLifetime.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
#include "ModuleSizeOverLifetime.hpp" #include <iostream> #include "Cl/ClProgram.hpp" #include "OpenCGL_Tools.hpp" #include "Cl/ClKernel.hpp" #include "Particle/PaticleEmitter/AParticleEmitter.hpp" ModuleSizeOverLifetime::ModuleSizeOverLifetime(AParticleEmitter &emitter) : AParticleModule(emitter), gpuBufferModuleParam_(ClContext::Get().context, CL_MEM_READ_WRITE, sizeof(ModuleParamSizeOverLifetime)) { ClProgram::Get().addProgram(pathKernel_ / "Size.cl"); cpuBufferModuleParam_.size.rangeMin = 0.0f; cpuBufferModuleParam_.size.rangeMax = 10.0f; kernelUpdate_.setKernel(emitter_, "sizeUpdate"); kernelUpdate_.setArgsGPUBuffers(eParticleBuffer::kData); } void ModuleSizeOverLifetime::init() { if (debug_) printf("%s\n", __FUNCTION_NAME__); queue_.getQueue().enqueueWriteBuffer(gpuBufferModuleParam_, CL_TRUE, 0, sizeof(ModuleParamSizeOverLifetime), &cpuBufferModuleParam_); } void ModuleSizeOverLifetime::update(float deltaTime) { if (!isActive_) return; if (debug_) printf("%s\n", __FUNCTION_NAME__); queue_.getQueue().enqueueWriteBuffer(gpuBufferModuleParam_, CL_TRUE, 0, sizeof(ModuleParamSizeOverLifetime), &cpuBufferModuleParam_); kernelUpdate_.beginAndSetUpdatedArgs(gpuBufferModuleParam_); OpenCGL::RunKernelWithMem(queue_.getQueue(), kernelUpdate_, emitter_.getParticleOCGL_BufferData().mem, cl::NullRange, cl::NDRange(nbParticleMax_)); } void ModuleSizeOverLifetime::reload() { if (debug_) printf("%s\n", __FUNCTION_NAME__); gpuBufferModuleParam_ = cl::Buffer(ClContext::Get().context, CL_MEM_READ_WRITE, sizeof(ModuleParamSizeOverLifetime)); init(); } float &ModuleSizeOverLifetime::getSizeMin() { return cpuBufferModuleParam_.size.rangeMin; } float &ModuleSizeOverLifetime::getSizeMax() { return cpuBufferModuleParam_.size.rangeMax; } void ModuleSizeOverLifetime::setSizeMin(float min) { cpuBufferModuleParam_.size.rangeMin = min; } void ModuleSizeOverLifetime::setSizeMax(float max) { cpuBufferModuleParam_.size.rangeMax = max; }
34.133333
151
0.773926
Jino42
63bf359fb22d9e50326c8fc5e0c033aa560ea18d
6,368
cpp
C++
src/getting_started/07_transforms.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/getting_started/07_transforms.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/getting_started/07_transforms.cpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <stb_image.h> #include "../gl/shader.h" #include "../utils/log.h" #include "../gl/gl_utils.h" namespace getting_started { namespace transforms { float vertices[] = { // ---- 位置 ---- ---- 颜色 ---- - 纹理坐标 - 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, // 右上 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // 右下 -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, // 左下 -0.5f, 0.5f, 0.0f, 0.0f, 1.0f // 左上 }; unsigned short indices[] = { 0, 1, 3, // 第一个三角形 1, 2, 3}; // 第二个三角形 int main() { LOG_I(__FILENAME__); glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #if defined(__APPLE__) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); #endif GLFWwindow *window = glfwCreateWindow(800, 600, __FILENAME__, nullptr, nullptr); if (window == nullptr) { LOG_E("Failed to create GLFW window"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { LOG_E("Failed to initialize GLAD loader"); glfwTerminate(); return -1; } else { printGLInfo(); } glViewport(0, 0, 800, 600); glfwSetFramebufferSizeCallback(window, [](GLFWwindow *, int w, int h) { glViewport(0, 0, w, h); }); unsigned int VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); unsigned int EBO; glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); unsigned int VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (void *)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (void *)(sizeof(float) * 3)); glEnableVertexAttribArray(1); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); unsigned int containerTex; glGenTextures(1, &containerTex); glBindTexture(GL_TEXTURE_2D, containerTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); int width, height, channels; unsigned char *data = stbi_load("assets/container.jpg", &width, &height, &channels, 0); if (data == nullptr) { LOG_E("Failed to load image: %s", "assets/container.jpg"); glfwTerminate(); return -1; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(data); unsigned int faceTex; glGenTextures(1, &faceTex); glBindTexture(GL_TEXTURE_2D, faceTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); data = stbi_load("assets/awesomeface.png", &width, &height, &channels, 0); if (data == nullptr) { LOG_E("Failed to load image: %s", "assets/awesomeface.png"); glfwTerminate(); return -1; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(data); data = nullptr; auto shader = new Shader("shaders/getting_started/07/shader.vs", "shaders/getting_started/07/shader.fs"); while (!glfwWindowShouldClose(window)) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { LOG_I("Escape pressed, exiting."); glfwSetWindowShouldClose(window, GLFW_TRUE); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); if (!shader->Use()) { break; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, containerTex); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, faceTex); shader->SetInt("texture0", 0); shader->SetInt("texture1", 1); glm::mat4 trans = glm::mat4(1.0f); trans = glm::translate(trans, glm::vec3(0.5f, -0.5f, 0.0f)); trans = glm::rotate(trans, static_cast<float>(glfwGetTime()), glm::vec3(0.0f, 0.0f, 1.0f)); shader->SetMatrix4("uTransform", glm::value_ptr(trans)); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void *)0); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } } // namespace transforms } // namespace getting_started
39.308642
117
0.555905
clsrfish
63c3614f5ef54ef59eaf1be343dc61c0cee399b4
4,443
cpp
C++
openMP/Kruskal.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-2-1
a7ce190e778d7173399b4719a1d1d53d718004ac
[ "MIT" ]
null
null
null
openMP/Kruskal.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-2-1
a7ce190e778d7173399b4719a1d1d53d718004ac
[ "MIT" ]
null
null
null
openMP/Kruskal.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-2-1
a7ce190e778d7173399b4719a1d1d53d718004ac
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> #include <set> #include <chrono> #include <queue> #include <omp.h> #include <algorithm> using namespace std; typedef pair<int, int> parN; #define INF 1000 int node_number, edge_number = 0; class DisjSet { int *rank, *parent, n; public: /* Constructor * @param n: tamaño del grafo */ DisjSet(int n) { rank = new int[n]; parent = new int[n]; this->n = n; makeSet(); } /* Método que regresa el tamaño del grafo */ int size() { return n; } /* Crea un set para cada nodo */ void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } /* Encuentra el set de un nodo dado * @param x: nodo a buscar */ int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } /* Fusiona dos sets a uno solo * @param x: un nodo a fusionar * @param y: otro nodo a fusionar */ void Union(int x, int y) { int xset = find(x); int yset = find(y); if (xset == yset) return; if (rank[xset] < rank[yset]) { parent[xset] = yset; } else if (rank[xset] > rank[yset]) { parent[yset] = xset; } else { parent[yset] = xset; rank[xset] = rank[xset] + 1; } n -= 1; } /* Determina si dos nodos están dentro del mismo set * @param a: un nodo a comparar * @param b: otro nodo a comparar */ bool connected(int a, int b) { return find(a) == find(b); } }; /* Función auxiliar al método sort() para realizar * de manera ascendente conforme al peso*/ bool asc_peso(const pair<parN, int> &a, const pair<parN, int> &b) { int num_grande = 1000; if (a.second == b.second) { return (a.first.first * num_grande + a.first.second < b.first.first * num_grande + b.first.second); } return ((a.second < b.second)); } /* Función principal que ejecuta algoritmo de Kruskal * @param nodes: grupo de nodos sobre el cual se ejecutan comandos * @param edges: grupo de aristas sobre el cual se ejecutan comandos */ void KruskalUtil(set<int> nodes, vector< pair<parN, int> > edges) { vector< pair<parN, int> > mst; sort(edges.begin(), edges.end(), asc_peso); // for (int i = 0; i < edges.size(); ++i) // { // printf("De: %d, a: %d, con peso: %d\n", edges[i].first.first, edges[i].first.second, edges[i].second); // } int nodos[node_number]; for (int i = 0; i < node_number; ++i) { nodos[i] = i+1; } DisjSet disj_set(node_number); int cont = 0, num_aristas = edge_number; auto start = chrono::high_resolution_clock::now(); #pragma omp parallel num_threads(4) { while ((num_aristas > 0) && (disj_set.size() > 1)) { if (!disj_set.connected(edges[cont].first.first, edges[cont].first.second)) { mst.push_back(edges[cont]); disj_set.Union(edges[cont].first.first, edges[cont].first.second); num_aristas--; printf("De: %d, a: %d, con peso: %d\n", edges[cont].first.first, edges[cont].first.second, edges[cont].second); } cont++; } } auto stop = chrono::high_resolution_clock::now(); // Aqui se guarda el tiempo en ese momento auto duration = chrono::duration_cast<chrono::microseconds>(stop - start); printf("Kruskal tardó %ld microsegundos\n", duration.count()); } int main(int argc, char const *argv[]) { vector< pair<parN, int> > edges; set<int> nodes; node_number = 14; edge_number = 18; for (int i = 0; i < node_number; ++i) { nodes.insert(i+1); } /* El orden es {{origen, destino}, peso} */ /* Para obtener origen sería "edges[i].first.first" */ /* Para obtener destino sería "edges[i].first.second" */ /* Para obtener peso sería "edges[i].second" */ edges.push_back({{3, 2}, 1}); edges.push_back({{3, 7}, 2}); edges.push_back({{2, 8}, 8}); edges.push_back({{2, 1}, 6}); edges.push_back({{7, 6}, 4}); edges.push_back({{7, 8}, 3}); edges.push_back({{7, 14}, 2}); edges.push_back({{8, 10}, 6}); edges.push_back({{8, 6}, 2}); edges.push_back({{1, 4}, 7}); edges.push_back({{1, 5}, 9}); edges.push_back({{6, 9}, 9}); edges.push_back({{14, 10}, 4}); edges.push_back({{10, 12}, 7}); edges.push_back({{10, 11}, 8}); edges.push_back({{5, 11}, 9}); edges.push_back({{9, 8}, 9}); edges.push_back({{11, 13}, 2}); KruskalUtil(nodes, edges); return 0; }
22.784615
124
0.582489
tec-csf
63c3e66e04f59a207876ca145eb9e52ca7e2cd66
5,725
cpp
C++
ddraw/IDirectDrawClipper.cpp
SamSoneyC/dxwrapper
12bad2da2d453239119039c4ebb76665e09cffcd
[ "Zlib" ]
null
null
null
ddraw/IDirectDrawClipper.cpp
SamSoneyC/dxwrapper
12bad2da2d453239119039c4ebb76665e09cffcd
[ "Zlib" ]
null
null
null
ddraw/IDirectDrawClipper.cpp
SamSoneyC/dxwrapper
12bad2da2d453239119039c4ebb76665e09cffcd
[ "Zlib" ]
null
null
null
/** * Copyright (C) 2020 Elisha Riedlinger * * 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. * * Code taken from: https://github.com/strangebytes/diablo-ddrawwrapper */ #include "ddraw.h" HRESULT m_IDirectDrawClipper::QueryInterface(REFIID riid, LPVOID FAR * ppvObj) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (ppvObj && riid == IID_GetRealInterface) { *ppvObj = ProxyInterface; return DD_OK; } if (ppvObj && riid == IID_GetInterfaceX) { *ppvObj = this; return DD_OK; } if (!ProxyInterface) { if ((riid == IID_IDirectDrawClipper || riid == IID_IUnknown) && ppvObj) { AddRef(); *ppvObj = this; return DD_OK; } } return ProxyQueryInterface(ProxyInterface, riid, ppvObj, WrapperID, this); } ULONG m_IDirectDrawClipper::AddRef() { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { return InterlockedIncrement(&RefCount); } return ProxyInterface->AddRef(); } ULONG m_IDirectDrawClipper::Release() { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; ULONG ref; if (!ProxyInterface) { ref = InterlockedDecrement(&RefCount); } else { ref = ProxyInterface->Release(); } if (ref == 0) { delete this; } return ref; } HRESULT m_IDirectDrawClipper::GetClipList(LPRECT lpRect, LPRGNDATA lpClipList, LPDWORD lpdwSize) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { // When lpClipList is NULL, the variable at lpdwSize receives the required size of the buffer, in bytes. if (!lpClipList) { if (lpdwSize) { *lpdwSize = sizeof(RGNDATA); return DD_OK; } return DDERR_INVALIDPARAMS; } if (IsClipListSet) { // ToDo: add support for lpRect // A pointer to a RECT structure that GetClipList uses to clip the clip list. Set this parameter to NULL to retrieve the entire clip list. // ToDo: fix sizeof(RGNDATA) to be the atual size of the data if (lpdwSize && *lpdwSize <= sizeof(RGNDATA)) { IsClipListChangedFlag = false; // Just set this to false for now memcpy(lpClipList, &ClipList, *lpdwSize); return DD_OK; } else if (lpdwSize && *lpdwSize >= sizeof(RGNDATA)) { return DDERR_REGIONTOOSMALL; } } else { return DDERR_NOCLIPLIST; } return DDERR_GENERIC; } return ProxyInterface->GetClipList(lpRect, lpClipList, lpdwSize); } HRESULT m_IDirectDrawClipper::GetHWnd(HWND FAR * lphWnd) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { if (!lphWnd) { return DDERR_INVALIDPARAMS; } if (!cliphWnd) { return DDERR_GENERIC; } *lphWnd = cliphWnd; return DD_OK; } return ProxyInterface->GetHWnd(lphWnd); } HRESULT m_IDirectDrawClipper::Initialize(LPDIRECTDRAW lpDD, DWORD dwFlags) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { return DD_OK; } if (lpDD) { lpDD->QueryInterface(IID_GetRealInterface, (LPVOID*)&lpDD); } return ProxyInterface->Initialize(lpDD, dwFlags); } HRESULT m_IDirectDrawClipper::IsClipListChanged(BOOL FAR * lpbChanged) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { if (!lpbChanged) { return DDERR_INVALIDPARAMS; } // ToDo: Fix this to get real status of ClipList // lpbChanged is TRUE if the clip list has changed, and FALSE otherwise. if (IsClipListChangedFlag) { *lpbChanged = TRUE; } else { *lpbChanged = FALSE; } return DD_OK; } return ProxyInterface->IsClipListChanged(lpbChanged); } HRESULT m_IDirectDrawClipper::SetClipList(LPRGNDATA lpClipList, DWORD dwFlags) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { // You cannot set the clip list if a window handle is already associated with the DirectDrawClipper object. if (cliphWnd) { return DDERR_CLIPPERISUSINGHWND; } // **NOTE: If you call IDirectDrawSurface7::BltFast on a surface with an attached clipper, it returns DDERR_UNSUPPORTED. if (!lpClipList) { // Delete associated clip list if it exists IsClipListSet = false; } else { // Set clip list to lpClipList IsClipListSet = true; IsClipListChangedFlag = true; // ToDo: Fix this to get correct size of ClipList memcpy(&ClipList, lpClipList, sizeof(RGNDATA)); } return DD_OK; } return ProxyInterface->SetClipList(lpClipList, dwFlags); } HRESULT m_IDirectDrawClipper::SetHWnd(DWORD dwFlags, HWND hWnd) { Logging::LogDebug() << __FUNCTION__ << " (" << this << ")"; if (!ProxyInterface) { cliphWnd = hWnd; // Load clip list from window return DD_OK; } return ProxyInterface->SetHWnd(dwFlags, hWnd); } /************************/ /*** Helper functions ***/ /************************/ void m_IDirectDrawClipper::InitClipper() { // To add later } void m_IDirectDrawClipper::ReleaseClipper() { // To add later }
21.934866
141
0.676856
SamSoneyC
63cefda5d102285b3898bed6274add241a813239
7,775
cpp
C++
tests/TestCircularBuffer.cpp
sarahkw/swgetf0
b3cae9290ed90063c98a9e770482de2c5944ec0e
[ "Apache-2.0" ]
5
2017-01-01T19:36:10.000Z
2019-11-07T03:40:32.000Z
tests/TestCircularBuffer.cpp
hobakurafuto/swgetf0
b3cae9290ed90063c98a9e770482de2c5944ec0e
[ "Apache-2.0" ]
null
null
null
tests/TestCircularBuffer.cpp
hobakurafuto/swgetf0
b3cae9290ed90063c98a9e770482de2c5944ec0e
[ "Apache-2.0" ]
1
2018-06-04T02:27:14.000Z
2018-06-04T02:27:14.000Z
/* Copyright 2014 Sarah Wong 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 "gtest/gtest.h" #include "gmock/gmock.h" #include "../CircularBuffer.h" using namespace testing; namespace { class TestCircularBuffer : public ::testing::Test { protected: TestCircularBuffer() : m_cb3(3), m_cb0(0) {} void SetUp() override {} void TearDown() override {} CircularBuffer<int> m_cb3; CircularBuffer<int> m_cb0; }; } TEST_F(TestCircularBuffer, ReadEmptyBuffer) { ASSERT_TRUE(m_cb3.begin() == m_cb3.end()); ASSERT_EQ(m_cb3.size(), 0); } TEST_F(TestCircularBuffer, ReadWithoutLoop) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); ASSERT_THAT(m_cb3, ElementsAre(1, 2, 3)); ASSERT_EQ(m_cb3.size(), 3); } TEST_F(TestCircularBuffer, ReadLoop) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); ASSERT_THAT(m_cb3, ElementsAre(3, 4, 5)); ASSERT_EQ(m_cb3.size(), 3); } TEST_F(TestCircularBuffer, ReadLoopTwiceWithIteratorWrite) { const int values[] = {1, 2, 3, 4, 5, 6, 7}; for (auto value : values) { m_cb3.push_back(value); } ASSERT_THAT(m_cb3, ElementsAre(5, 6, 7)); ASSERT_EQ(m_cb3.size(), 3); } TEST_F(TestCircularBuffer, ZeroWorkingSet) { ASSERT_TRUE(m_cb0.begin() == m_cb0.end()); m_cb0.push_back(0); ASSERT_TRUE(m_cb0.begin() == m_cb0.end()); } TEST_F(TestCircularBuffer, ExpandBlank) { m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre()); } TEST_F(TestCircularBuffer, ExpandNotFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre(1, 2)); } TEST_F(TestCircularBuffer, ExpandFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre(0, 0, 0, 1, 2, 3)); } TEST_F(TestCircularBuffer, ExpandOverflow1) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre(0, 0, 0, 2, 3, 4)); } TEST_F(TestCircularBuffer, ExpandOverflow2) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); m_cb3.push_back(6); m_cb3.resize(6); ASSERT_THAT(m_cb3, ElementsAre(0, 0, 0, 4, 5, 6)); // Make sure it still works afterwards m_cb3.push_back(7); m_cb3.push_back(8); m_cb3.push_back(9); ASSERT_THAT(m_cb3, ElementsAre(4, 5, 6, 7, 8, 9)); m_cb3.push_back(10); ASSERT_THAT(m_cb3, ElementsAre(5, 6, 7, 8, 9, 10)); } TEST_F(TestCircularBuffer, ShrinkAllEmpty) { m_cb3.resize(0); ASSERT_THAT(m_cb3, ElementsAre()); ASSERT_EQ(m_cb3.size(), 0); // Use after m_cb3.push_back(0); ASSERT_THAT(m_cb3, ElementsAre()); ASSERT_EQ(m_cb3.size(), 0); } TEST_F(TestCircularBuffer, ShrinkAllFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.resize(0); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); m_cb3.push_back(3); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); } TEST_F(TestCircularBuffer, ShrinkAllOverflow) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.resize(0); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); m_cb3.push_back(3); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); } TEST_F(TestCircularBuffer, ShrinkAllPartial) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(0); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); m_cb3.push_back(3); ASSERT_EQ(m_cb3.size(), 0); ASSERT_THAT(m_cb3, ElementsAre()); } TEST_F(TestCircularBuffer, ShrinkPartialEmpty) { m_cb3.resize(1); ASSERT_THAT(m_cb3, ElementsAre()); ASSERT_EQ(m_cb3.size(), 0); // Use after m_cb3.push_back(0); ASSERT_THAT(m_cb3, ElementsAre(0)); ASSERT_EQ(m_cb3.size(), 1); } TEST_F(TestCircularBuffer, ShrinkPartialNotFullNoLoss) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(2); ASSERT_THAT(m_cb3, ElementsAre(1, 2)); ASSERT_EQ(m_cb3.size(), 2); // Use after m_cb3.push_back(3); ASSERT_THAT(m_cb3, ElementsAre(2, 3)); ASSERT_EQ(m_cb3.size(), 2); m_cb3.push_back(4); ASSERT_THAT(m_cb3, ElementsAre(3, 4)); ASSERT_EQ(m_cb3.size(), 2); } TEST_F(TestCircularBuffer, ShrinkPartialNotFullWithLoss) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(1); ASSERT_THAT(m_cb3, ElementsAre(2)); ASSERT_EQ(m_cb3.size(), 1); // Use after m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); ASSERT_THAT(m_cb3, ElementsAre(5)); ASSERT_EQ(m_cb3.size(), 1); m_cb3.push_back(6); m_cb3.push_back(7); ASSERT_THAT(m_cb3, ElementsAre(7)); ASSERT_EQ(m_cb3.size(), 1); } TEST_F(TestCircularBuffer, ShrinkPartialFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.resize(1); ASSERT_THAT(m_cb3, ElementsAre(3)); ASSERT_EQ(m_cb3.size(), 1); // Use after m_cb3.push_back(4); m_cb3.push_back(5); ASSERT_THAT(m_cb3, ElementsAre(5)); ASSERT_EQ(m_cb3.size(), 1); } TEST_F(TestCircularBuffer, ShrinkPartialOverflow) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.resize(2); ASSERT_EQ(m_cb3.size(), 2); ASSERT_THAT(m_cb3, ElementsAre(3, 4)); m_cb3.push_back(5); ASSERT_EQ(m_cb3.size(), 2); ASSERT_THAT(m_cb3, ElementsAre(4, 5)); m_cb3.push_back(6); ASSERT_EQ(m_cb3.size(), 2); ASSERT_THAT(m_cb3, ElementsAre(5, 6)); } TEST_F(TestCircularBuffer, ShrinkPartialOverflow2) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); m_cb3.resize(1); ASSERT_EQ(m_cb3.size(), 1); ASSERT_THAT(m_cb3, ElementsAre(5)); m_cb3.push_back(7); ASSERT_EQ(m_cb3.size(), 1); ASSERT_THAT(m_cb3, ElementsAre(7)); m_cb3.push_back(8); ASSERT_EQ(m_cb3.size(), 1); ASSERT_THAT(m_cb3, ElementsAre(8)); } TEST_F(TestCircularBuffer, ShrinkExpandFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.resize(1); m_cb3.resize(2); ASSERT_THAT(m_cb3, ElementsAre(0, 3)); ASSERT_EQ(m_cb3.size(), 2); } TEST_F(TestCircularBuffer, ShrinkExpandFullWrap) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.push_back(3); m_cb3.push_back(4); m_cb3.push_back(5); m_cb3.resize(1); m_cb3.resize(3); ASSERT_EQ(m_cb3.size(), 3); ASSERT_THAT(m_cb3, ElementsAre(0, 0, 5)); } TEST_F(TestCircularBuffer, ShrinkExpandNotFull) { m_cb3.push_back(1); m_cb3.resize(2); m_cb3.resize(3); ASSERT_THAT(m_cb3, ElementsAre(1)); ASSERT_EQ(m_cb3.size(), 1); } TEST_F(TestCircularBuffer, ShrinkExpandNotFullBecomeFull) { m_cb3.push_back(1); m_cb3.push_back(2); m_cb3.resize(2); ASSERT_EQ(m_cb3.size(), 2); m_cb3.resize(3); ASSERT_EQ(m_cb3.size(), 3); ASSERT_THAT(m_cb3, ElementsAre(0, 1, 2)); } TEST_F(TestCircularBuffer, ExpandZeroSize) { m_cb0.push_back(1); m_cb0.resize(3); ASSERT_THAT(m_cb0, ElementsAre(0, 0, 0)); ASSERT_EQ(m_cb0.size(), 3); // Still works? m_cb0.push_back(2); ASSERT_THAT(m_cb0, ElementsAre(0, 0, 2)); ASSERT_EQ(m_cb0.size(), 3); m_cb0.push_back(3); m_cb0.push_back(4); m_cb0.push_back(5); ASSERT_THAT(m_cb0, ElementsAre(3, 4, 5)); ASSERT_EQ(m_cb0.size(), 3); }
20.900538
74
0.696206
sarahkw
63cff69a8ca44a68d1fbd5e7db83195bf6335ee8
128,979
hpp
C++
test/TestChemicalChaste.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
test/TestChemicalChaste.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
test/TestChemicalChaste.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
#ifndef TESTCHEMICALCHASTE_HPP_ #define TESTCHEMICALCHASTE_HPP_ // chaste includes #include <cxxtest/TestSuite.h> #include "UblasIncludes.hpp" #include "AbstractCellBasedTestSuite.hpp" #include "CheckpointArchiveTypes.hpp" #include "PetscSetupAndFinalize.hpp" #include "SmartPointers.hpp" // general includes #include <iostream> #include <fstream> #include <string> #include <vector> #include <tuple> #include <cmath> // chemical includes #include "AbstractChemical.hpp" #include "AbstractDiffusiveChemical.hpp" #include "AbstractChemistry.hpp" #include "AbstractDiffusiveChemistry.hpp" // reaction-diffusion includes #include "AbstractReaction.hpp" #include "AbstractReversibleReaction.hpp" #include "AbstractReactionSystem.hpp" #include "MassActionReaction.hpp" #include "AbstractReactionSystemFromFile.hpp" #include "ReactionTypeDatabase.hpp" // chaste PdeOde includes #include "HoneycombMeshGenerator.hpp" #include "EulerIvpOdeSolver.hpp" #include "LinearParabolicPdeSystemWithCoupledOdeSystemSolver.hpp" #include "BoundaryConditionsContainer.hpp" #include "ConstBoundaryCondition.hpp" #include "OutputFileHandler.hpp" #include "RandomNumberGenerator.hpp" #include "TrianglesMeshReader.hpp" // custom pdeOde includes #include "PdeSchnackenbergCoupledPdeOdeSystem.hpp" #include "OdeSchnackenbergCoupledPdeOdeSystem.hpp" #include "PdeConsumerProducer.hpp" #include "OdeConsumerProducer.hpp" #include "AbstractChemicalOdeSystem.hpp" #include "AbstractChemicalOdeForCoupledPdeSystem.hpp" // CHASTE Spheroid includes #include "SimpleOxygenBasedCellCycleModel.hpp" #include "WildTypeCellMutationState.hpp" #include "StemCellProliferativeType.hpp" #include "CellwiseSourceEllipticPde.hpp" #include "ConstBoundaryCondition.hpp" #include "EllipticGrowingDomainPdeModifier.hpp" #include "OffLatticeSimulation.hpp" #include "GeneralisedLinearSpringForce.hpp" #include "SchnackenbergCoupledPdeSystem.hpp" class TestChemicalChaste : public AbstractCellBasedTestSuite { public: void TestChemicalClass() { std::cout<<"-----------------------------"<<std::endl; std::cout<<"Chemical"<<std::endl; AbstractChemical *p_chemical = new AbstractChemical("A"); AbstractDiffusiveChemical *p_chemical_diffusive = new AbstractDiffusiveChemical("B"); p_chemical_diffusive -> AddDiffusiveDomain("test",1.0); std::cout<<"Name: "<<p_chemical ->GetChemicalName() <<std::endl; std::cout<<"Type: "<<p_chemical ->GetChemicalType() <<std::endl; std::cout<<"Name: "<<p_chemical_diffusive ->GetChemicalName() <<std::endl; std::cout<<"Type: "<<p_chemical_diffusive ->GetChemicalType() <<std::endl; std::cout<<"Diffusivity: "<<p_chemical_diffusive ->GetDiffusiveDomainVector()[0] <<std::endl; // vectorise the pointers std::cout<<"Chemical vector"<<std::endl; std::vector<AbstractChemical*> p_chemicalVector; // implicit upcasting p_chemicalVector.push_back(p_chemical); p_chemicalVector.push_back(p_chemical_diffusive); std::cout<<p_chemicalVector[0] -> GetChemicalType() <<std::endl; std::cout<<p_chemicalVector[1] -> GetChemicalType() <<std::endl; // get the diffusive value for [1] std::cout<<"dynamic casting"<<std::endl; AbstractDiffusiveChemical *p_chemical_diffusive_2 = dynamic_cast<AbstractDiffusiveChemical*>(p_chemicalVector[1]); std::cout<<p_chemical_diffusive_2 -> GetChemicalDiffusivityVector()[0] <<std::endl; } void TestChemistryClass() { std::cout<<"-----------------------------"<<std::endl; std::cout<<"Abstract chemistry"<<std::endl; unsigned Number_of_species =2; std::vector<std::string> ChemicalNames = {"U", "V"}; std::vector<double> DiffusionRates = {1.0, 2.0}; std::vector<bool> IsDiffusing = {true, true}; std::vector<std::string> DiffusionDomains = {"Bulk", "Bulk"}; AbstractChemistry* p_chemistry = new AbstractChemistry(); for(unsigned species=0; species<Number_of_species; species++) { AbstractChemical *p_chemical = new AbstractChemical(ChemicalNames[species]); p_chemistry -> AddChemical(p_chemical); } std::vector<std::string> ChemNames = p_chemistry -> GetChemicalNames(); std::cout<<"Chemical names: "<<std::endl; for(unsigned i=0; i<Number_of_species; i++) { std::cout<<ChemNames[i]<<std::endl; } std::cout<<"Abstract diffusive chemistry"<<std::endl; std::vector<std::string> ChemicalNamesDiffusive = {"Ud", "Vd"}; AbstractDiffusiveChemistry* p_diffusive_chemistry = new AbstractDiffusiveChemistry(); for(unsigned species=0; species<Number_of_species; species++) { AbstractDiffusiveChemical *p_chemical = new AbstractDiffusiveChemical(ChemicalNamesDiffusive[species]); p_chemical -> AddDiffusiveDomain(DiffusionDomains[species],DiffusionRates[species]); p_diffusive_chemistry -> AddChemical(p_chemical); } std::cout<<"Chemical diffusivities: "<<std::endl; for(unsigned i=0; i<Number_of_species; i++) { std::cout<<p_diffusive_chemistry -> GetChemicalNamesByIndex(i)<<std::endl; std::cout<<p_diffusive_chemistry -> GetDiffusivityVectorByIndex(i)[0]<<std::endl; } std::cout<<"Add chemistries"<<std::endl; // upcast AbstractDiffusiveChemistry to AbstractChemistry // maybe need to template this function? currently add to the highest class to avoid object splicing AbstractChemistry *p_newChemistry = dynamic_cast<AbstractChemistry*>(p_diffusive_chemistry); p_chemistry -> AddChemistry(p_newChemistry); std::vector<std::string> ChemistryNames = p_chemistry -> GetChemicalNames(); for(unsigned i=0; i<Number_of_species; i++) { std::cout<<ChemistryNames[i]<<std::endl; } std::cout<<"Add diffusive chemistries"<<std::endl; // upcast AbstractDiffusiveChemistry to AbstractChemistry // maybe need to template this function? currently add to the highest class to avoid object splicing AbstractDiffusiveChemistry *p_newDiffusiveChemistry = new AbstractDiffusiveChemistry(); std::vector<std::string> NewChemicalNamesDiffusive = {"Ud", "Y"}; std::vector<double> NewDiffusionRates = {3,4}; for(unsigned species=0; species<Number_of_species; species++) { AbstractDiffusiveChemical *p_chemical = new AbstractDiffusiveChemical(NewChemicalNamesDiffusive[species]); p_chemical -> AddDiffusiveDomain(DiffusionDomains[species],NewDiffusionRates[species]); p_newDiffusiveChemistry -> AddChemical(p_chemical); //shouldn't add the first species Ud as is a duplicate of name and domain } p_diffusive_chemistry -> AddChemistry(p_newDiffusiveChemistry); std::cout<<"Number of chemicals: "<<p_diffusive_chemistry ->GetNumberChemicals()<<std::endl; std::cout<<"Number of diffusive chemicals: "<<p_diffusive_chemistry ->GetNumberDiffusiveChemicals()<<std::endl; for(unsigned i=0; i<4; i++) { std::cout<<p_diffusive_chemistry -> GetChemicalNamesByIndex(i)<<std::endl; std::cout<<p_diffusive_chemistry -> GetDiffusivityValueByChemicalName(p_diffusive_chemistry -> GetChemicalNamesByIndex(i))<<std::endl; } } void TestReactionClass() { std::cout<<"-----------------------------"<<std::endl; std::cout<<"Chemical information"<<std::endl; unsigned Number_of_species =2; std::vector<std::string> ChemicalNames = {"U", "V"}; std::vector<double> DiffusionRates = {1.0, 2.0}; std::vector<bool> IsDiffusing = {true, true}; std::vector<std::string> DiffusionDomains = {"Bulk", "Bulk"}; std::cout<<"Form chemical vector"<<std::endl; std::vector<AbstractChemical*> p_chemicalVector; for(unsigned species=0; species<Number_of_species; species++) { if(IsDiffusing[species]) { // use the diffusive chemical root AbstractDiffusiveChemical *p_chemical = new AbstractDiffusiveChemical(ChemicalNames[species]); p_chemical -> AddDiffusiveDomain(DiffusionDomains[species],DiffusionRates[species]); p_chemicalVector.push_back(p_chemical); }else{ // use the non-diffusive chemical root AbstractChemical *p_chemical = new AbstractChemical(ChemicalNames[species]); p_chemicalVector.push_back(p_chemical); } } // check iterating through the chemical vector works, need dynamic casting of the iterator for (std::vector<AbstractChemical*>::iterator chem_iter = p_chemicalVector.begin(); chem_iter != p_chemicalVector.end(); ++chem_iter) { std::string ChemicalName = "NA"; double Diffusivity = 0.0; std::string Domain = "None"; AbstractChemical *p_2 = dynamic_cast<AbstractChemical*>(*chem_iter); if( p_2 -> GetChemicalType() == "AbstractDiffusiveChemical") { AbstractDiffusiveChemical *p_chemical = dynamic_cast<AbstractDiffusiveChemical*>(*chem_iter); ChemicalName = p_chemical -> GetChemicalName(); Diffusivity = p_chemical -> GetChemicalDiffusivityVector()[0]; Domain = p_chemical -> GetDiffusiveDomainVector()[0]; } std::cout<<"Name: "<<ChemicalName<<std::endl; std::cout<<"Diffusivity: "<<Diffusivity<<std::endl; std::cout<<"Domain: "<<Domain<<std::endl; delete p_2; } std::cout<<"Schnackenberg Chemistry"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add U to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 0.2; double reaction_3_rate = 0.3; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); // concentration vector std::vector<double> concentration_vector= {1.0,1.0}; std::vector<double> change_concentration_vector= {0.0,0.0}; std::cout<<"Starting conditions"<<std::endl; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r1: 2U + V -> 3U forwardRate = "<<reaction_1_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_1 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); //concentration_vector[0] = concentration_vector[0] + change_concentration_vector[0]; //concentration_vector[1] = concentration_vector[1] + change_concentration_vector[1]; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r2: 0 <-> U forwardRate = "<<reaction_2_forward_rate<<" reverseRate = "<<reaction_2_reverse_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_2 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); //concentration_vector[0] = concentration_vector[0] + change_concentration_vector[0]; //concentration_vector[1] = concentration_vector[1] + change_concentration_vector[1]; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r3: 0 -> V forwardRate = "<<reaction_3_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_3 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); //concentration_vector[0] = concentration_vector[0] + change_concentration_vector[0]; //concentration_vector[1] = concentration_vector[1] + change_concentration_vector[1]; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; // form reaction system std::cout<<"Form reaction system: "<<std::endl; concentration_vector= {1.0,1.0}; change_concentration_vector= {0.0,0.0}; std::vector<AbstractReaction*> p_reaction_vector_1; p_reaction_vector_1.push_back(p_reaction_1); AbstractReactionSystem* p_reaction_system_1 = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector_1); p_reaction_system_1 -> ReactSystem(concentration_vector,change_concentration_vector); std::cout<<"============================"<<std::endl; std::cout<<"r1: 2U + V -> 3U forwardRate = "<<reaction_1_rate<<std::endl; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; // form mixed reaction system (AbstractReaction, AbstractReversibleReaction, AbstractReaction) concentration_vector= {1.0,1.0}; change_concentration_vector= {0.0,0.0}; std::vector<AbstractReaction*> p_reaction_vector_2; p_reaction_vector_2.push_back(p_reaction_1); p_reaction_vector_2.push_back(p_reaction_2); p_reaction_vector_2.push_back(p_reaction_3); AbstractReactionSystem* p_reaction_system_2 = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector_2); p_reaction_system_2 -> ReactSystem(concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; for(unsigned i=0; i<p_reaction_system_2 -> GetNumberOfReactions(); i++) { std::cout<<"Reaction type: "<<i<<" "<< p_reaction_system_2 -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; } } void TestMassActionReactionClass() { std::cout<<"-----------------------------"<<std::endl; AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add U to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 0.2; double reaction_3_rate = 0.3; MassActionReaction* p_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); // concentration vector std::vector<double> concentration_vector= {1.0,1.0}; std::vector<double> change_concentration_vector= {0.0,0.0}; std::cout<<"Mass action kinetics"<<std::endl; std::cout<<"Starting conditions"<<std::endl; std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r1: 2U + V -> 3U forwardRate = "<<reaction_1_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_1 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r2: 0 <-> U forwardRate = "<<reaction_2_forward_rate<<" reverseRate = "<<reaction_2_reverse_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_2 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; std::cout<<"============================"<<std::endl; std::cout<<"r3: 0 -> V forwardRate = "<<reaction_3_rate<<std::endl; change_concentration_vector= {0.0,0.0}; p_reaction_3 -> React(p_system_chemistry,concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; // form mixed mass action reaction system std::cout<<"============================"<<std::endl; std::cout<<"Form mass action reaction sysstem"<<std::endl; std::cout<<"============================"<<std::endl; concentration_vector= {1.0,1.0}; change_concentration_vector= {0.0,0.0}; std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_reaction_1); p_mass_action_reaction_vector.push_back(p_reaction_2); p_mass_action_reaction_vector.push_back(p_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); p_mass_action_reaction_system -> ReactSystem(concentration_vector,change_concentration_vector); std::cout<<"Concentration (U,V): "<<concentration_vector[0]<<" "<<concentration_vector[1]<<std::endl; std::cout<<"Concentration change (U,V): "<<change_concentration_vector[0]<<" "<<change_concentration_vector[1]<<std::endl; for(unsigned i=0; i<p_mass_action_reaction_system -> GetNumberOfReactions(); i++) { std::cout<<"Reaction type: "<<i<<" "<< p_mass_action_reaction_system -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; } } void TestSpatialPdeOdeSolver() { /* std::cout<<"SchnackenbergCoupledPdeOdeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {2.0, 0.75}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, false); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(1e-4, 1e-2); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional if(i==22 || i==77) { odeSystem.push_back(new OdeSchnackenbergCoupledPdeOdeSystem(0.1, 0.2, 0.3, 0.1)); }else if(i==27 || i==72) { odeSystem.push_back(new OdeSchnackenbergCoupledPdeOdeSystem(0.1, 0.2, 0.3, 0.1)); }else{ odeSystem.push_back(new OdeSchnackenbergCoupledPdeOdeSystem(0.1, 0.2, 0.3, 0.1)); } } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc, odeSystem, p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestVectorisedSchnackenbergOutput_correct_ks"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); */ } void TestSpatialConsumerProducerSolver() { /* std::cout<<"ConsumerProducer"<<std::endl; // reaction system involving two species, A and B // 0 -> A rateConstant = k1 // B -> 0 rateConstant = k2 // A <-> B rateConstantForward = k3 rateConstantReverse = k_3 // A diffuses at rate Da // B diffuses at rate Db // nodal ode of the form: OdeConsumerProducer(k1, k2, k3, k4) // with nodes 22, 27, 72, 77 selected forming corners of a square domain offset from the boundary double Da = 1e-1; double Db = 5e-2; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {0, 0}; std::vector<double> bcValues = {0, 0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, false); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = initValues[pdeDim] ;//fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); // pde system std::cout<<"Pde"<<std::endl; PdeConsumerProducer<elementDim, spaceDim, probDim> pde(Da, Db); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional if(i==22) { odeSystem.push_back(new OdeConsumerProducer(1, 0, 0, 0)); }else if(i==77) { odeSystem.push_back(new OdeConsumerProducer(0, 1, 0, 0)); }else{ odeSystem.push_back(new OdeConsumerProducer(0, 0, 0.1, 0)); } } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc, odeSystem, p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestConsumerProducerOutput_1"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); */ } void TestChemicalOde() { /* std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add U to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 2; double reaction_3_rate = 0.3; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); MassActionReaction* p_Mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_Mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_Mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); AbstractChemicalOdeSystem chemicalOde(p_mass_action_reaction_system); EulerIvpOdeSolver euler_solver; std::vector<double> initial_condition = {1.0, 1.0}; OdeSolution solutions = euler_solver.Solve(&chemicalOde, initial_condition, 0, 1, 0.01, 0.1); for (unsigned i=0; i<solutions.rGetTimes().size(); i++) { std::cout << solutions.rGetTimes()[i] << " " << solutions.rGetSolutions()[i][0] << " " << solutions.rGetSolutions()[i][1]<< "\n"; } */ } void TestChemicalOdePde() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 1.0; double reaction_2_forward_rate = 0.5; double reaction_2_reverse_rate = 2.2; double reaction_3_rate = 1.5; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestReactionSystemFromFile() { /* std::cout<<"Reaction system from file"<<std::endl; std::cout<<"-----------------------------"<<std::endl; AbstractReaction* p_reaction = new AbstractReaction(); std::cout<<"Before cast reaction type: "<<p_reaction -> GetReactionType()<<std::endl; ReactionTablet(p_reaction,"MassActionReaction"); std::cout<<"After cast reaction type: "<<p_reaction -> GetReactionType()<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::string reactionFilename = "/home/chaste/projects/ChemicalChaste/src/Data/SchnackenbergReactionFile.txt"; //std::string reactionFilename = "/home/chaste/projects/ChemicalChaste/src/Data/SchnackenbergReactionFileMixed.txt"; AbstractReactionSystemFromFile* p_file_reaction_system = new AbstractReactionSystemFromFile(reactionFilename); std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add U to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 0.2; double reaction_3_rate = 0.3; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); MassActionReaction* p_Mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_Mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_Mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_Mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); std::cout<<"--------------------------------------"<<std::endl; std::cout<<"Test the reaction systems for equality"<<std::endl; std::cout<<"--------------------------------------"<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"System from file"<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Read out reaction details: "<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Number of reactions: "<<p_file_reaction_system -> GetNumberOfReactions()<<std::endl; for(unsigned i=0; i<p_file_reaction_system -> GetNumberOfReactions(); i++) { std::cout<<"Reaction: "<<i<<" "<< p_file_reaction_system -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; std::cout<<"Reaction: "<<i<<" "<< dynamic_cast<MassActionReaction*>(p_file_reaction_system -> GetReactionByIndex(i)) -> GetForwardReactionRateConstant()<<std::endl; std::cout<<"Reaction: "<<i<<" "<< dynamic_cast<MassActionReaction*>(p_file_reaction_system -> GetReactionByIndex(i)) -> GetReverseReactionRateConstant()<<std::endl; } std::vector<std::string> chemNames = p_file_reaction_system-> GetSystemChemistry() -> GetChemicalNames(); std::cout<<"System chemical names:"<<std::endl; for(unsigned i=0; i<chemNames.size();i++) { std::cout<<chemNames[i]<<std::endl; } for(unsigned i=0; i<p_file_reaction_system-> GetNumberOfReactions(); i++ ) { AbstractReaction* p_reaction = p_file_reaction_system-> GetReactionByIndex(i); std::cout<<"Reaction type: "<<p_reaction ->GetReactionType()<<std::endl; for(unsigned j=0; j<p_reaction -> GetNumberOfSubstrates(); j++) { std::cout<<"Substrate: "<<p_reaction -> GetSubstratesByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichSubstratesByIndex(j)<<std::endl; } for(unsigned j=0; j<p_reaction -> GetNumberOfProducts(); j++) { std::cout<<"Product: "<<p_reaction -> GetProductsByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichProductsByIndex(j)<<std::endl; } } std::cout<<"-----------------------------"<<std::endl; std::cout<<"Hard coded system"<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Read out reaction details: "<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Number of reactions: "<<p_mass_action_reaction_system -> GetNumberOfReactions()<<std::endl; for(unsigned i=0; i<p_mass_action_reaction_system -> GetNumberOfReactions(); i++) { std::cout<<"Reaction: "<<i<<" "<< p_mass_action_reaction_system -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; std::cout<<"Reaction: "<<i<<" "<< dynamic_cast<MassActionReaction*>(p_mass_action_reaction_system -> GetReactionByIndex(i)) -> GetForwardReactionRateConstant()<<std::endl; std::cout<<"Reaction: "<<i<<" "<< dynamic_cast<MassActionReaction*>(p_mass_action_reaction_system -> GetReactionByIndex(i)) -> GetReverseReactionRateConstant()<<std::endl; } std::vector<std::string> chemNames_hard_coded = p_mass_action_reaction_system-> GetSystemChemistry() -> GetChemicalNames(); std::cout<<"System chemical names:"<<std::endl; for(unsigned i=0; i<chemNames_hard_coded.size();i++) { std::cout<<chemNames_hard_coded[i]<<std::endl; } for(unsigned i=0; i<p_mass_action_reaction_system-> GetNumberOfReactions(); i++ ) { AbstractReaction* p_reaction = p_mass_action_reaction_system-> GetReactionByIndex(i); std::cout<<"Reaction type: "<<p_reaction ->GetReactionType()<<std::endl; for(unsigned j=0; j<p_reaction -> GetNumberOfSubstrates(); j++) { std::cout<<"Substrate: "<<p_reaction -> GetSubstratesByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichSubstratesByIndex(j)<<std::endl; } for(unsigned j=0; j<p_reaction -> GetNumberOfProducts(); j++) { std::cout<<"Product: "<<p_reaction -> GetProductsByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichProductsByIndex(j)<<std::endl; } } std::cout<<"-----------------------------"<<std::endl; std::cout<<"Run the reaction ODE system "<<std::endl; std::cout<<"-----------------------------"<<std::endl; AbstractChemicalOdeSystem chemicalOde(p_mass_action_reaction_system); EulerIvpOdeSolver euler_solver; std::vector<double> initial_condition = {1.0, 1.0}; OdeSolution solutions = euler_solver.Solve(&chemicalOde, initial_condition, 0, 1, 0.1, 0.1); for (unsigned i=0; i<solutions.rGetTimes().size(); i++) { std::cout << solutions.rGetTimes()[i] << " " << solutions.rGetSolutions()[i][0] << " " << solutions.rGetSolutions()[i][1]<< "\n"; } std::cout<<"-----------------------------"<<std::endl; std::cout<<"Run the file reaction system "<<std::endl; std::cout<<"-----------------------------"<<std::endl; // implicit upcast AbstractReactionSystemFromFile to AbstractReactionSystem AbstractChemicalOdeSystem chemical_ode_file(p_file_reaction_system); std::vector<double> initial_condition_file = {1.0, 1.0}; EulerIvpOdeSolver euler_solver_file; OdeSolution solutions_file = euler_solver_file.Solve(&chemical_ode_file, initial_condition_file, 0, 1, 0.1, 0.1); for (unsigned i=0; i<solutions_file.rGetTimes().size(); i++) { std::cout << solutions_file.rGetTimes()[i] << " " << solutions_file.rGetSolutions()[i][0] << " " << solutions_file.rGetSolutions()[i][1]<< "\n"; } */ } void TestPdeFromFile() { /* std::cout<<"ConsumerProducerFromFile"<<std::endl; // reaction system involving two species, A and B // 0 -> A rateConstant = k1 // B -> 0 rateConstant = k2 // A <-> B rateConstantForward = k3 rateConstantReverse = k_3 // A diffuses at rate Da // B diffuses at rate Db // nodal ode of the form: OdeConsumerProducer(k1, k2, k3, k4) // with nodes 22, 27, 72, 77 selected forming corners of a square domain offset from the boundary double Da = 1e-1; double Db = 5e-2; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {0, 0}; std::vector<double> bcValues = {0, 0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, false); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = initValues[pdeDim] ;//fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); // pde system std::cout<<"Pde"<<std::endl; PdeConsumerProducer<elementDim, spaceDim, probDim> pde(Da, Db); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional if(i==22) { odeSystem.push_back(new OdeConsumerProducer(1, 0, 0, 0)); }else if(i==77) { odeSystem.push_back(new OdeConsumerProducer(0, 1, 0, 0)); }else{ odeSystem.push_back(new OdeConsumerProducer(0, 0, 0.1, 0)); } } // 0 -> A rateConstant = k1 // B -> 0 rateConstant = k2 // A <-> B rateConstantForward = k3 rateConstantReverse = k_3 // A diffuses at rate Da // B diffuses at rate Db std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc, odeSystem, p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestConsumerProducerOutputFromFile"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); */ } void TestCHASTESpheroidTutorial() { /* EXIT_IF_PARALLEL; HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<2,2>* p_mesh = generator.GetMesh(); std::vector<CellPtr> cells; MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(StemCellProliferativeType, p_stem_type); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { SimpleOxygenBasedCellCycleModel* p_model = new SimpleOxygenBasedCellCycleModel; p_model->SetDimension(2); CellPtr p_cell(new Cell(p_state, p_model)); p_cell->SetCellProliferativeType(p_stem_type); p_model->SetStemCellG1Duration(8.0); p_model->SetTransitCellG1Duration(8.0); double birth_time = - RandomNumberGenerator::Instance()->ranf() * ( p_model->GetStemCellG1Duration() + p_model->GetSG2MDuration() ); p_cell->SetBirthTime(birth_time); cells.push_back(p_cell); } MeshBasedCellPopulation<2> cell_population(*p_mesh, cells); MAKE_PTR_ARGS(CellwiseSourceEllipticPde<2>, p_pde, (cell_population, -0.03)); MAKE_PTR_ARGS(ConstBoundaryCondition<2>, p_bc, (1.0)); bool is_neumann_bc = false; MAKE_PTR_ARGS(EllipticGrowingDomainPdeModifier<2>, p_pde_modifier, (p_pde, p_bc, is_neumann_bc)); p_pde_modifier->SetDependentVariableName("oxygen"); OffLatticeSimulation<2> simulator(cell_population); simulator.AddSimulationModifier(p_pde_modifier); simulator.SetOutputDirectory("SpheroidTutorial"); simulator.SetEndTime(1.0); MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); p_linear_force->SetCutOffLength(3); simulator.AddForce(p_linear_force); simulator.Solve(); */ } void TestChemicalSpheroid() { /* std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {2.0, 0.75}; // mesh HoneycombMeshGenerator generator(100, 100, 0); MutableMesh<2,2>* p_mesh = generator.GetMesh(); SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.1, 0.2, 0.3, 0.1); BoundaryConditionsContainer<2,2,2> bcc; ConstBoundaryCondition<2>* p_bc_for_u = new ConstBoundaryCondition<2>(2.0); ConstBoundaryCondition<2>* p_bc_for_v = new ConstBoundaryCondition<2>(0.75); for (TetrahedralMesh<2,2>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, p_bc_for_u, 0); bcc.AddDirichletBoundaryCondition(*node_iter, p_bc_for_v, 1); } LinearParabolicPdeSystemWithCoupledOdeSystemSolver<2,2,2> solver(p_mesh, &pde, &bcc); double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestSchnackenbergSystemOnHoneycombMesh"); std::vector<double> init_conds(2*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { init_conds[2*i] = fabs(2.0 + RandomNumberGenerator::Instance()->ranf()); init_conds[2*i + 1] = fabs(0.75 + RandomNumberGenerator::Instance()->ranf()); } Vec initial_condition = PetscTools::CreateVec(init_conds); solver.SetInitialCondition(initial_condition); solver.SolveAndWriteResultsToFile(); PetscTools::Destroy(initial_condition); */ } void TestChemicalSpheroidPAPER() { std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {2.0, 0.75}; // mesh HoneycombMeshGenerator generator(3, 3, 0); MutableMesh<2,2>* p_mesh = generator.GetMesh(); SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); BoundaryConditionsContainer<2,2,2> bcc; ConstBoundaryCondition<2>* p_bc_for_u = new ConstBoundaryCondition<2>(2.0); ConstBoundaryCondition<2>* p_bc_for_v = new ConstBoundaryCondition<2>(0.75); for (TetrahedralMesh<2,2>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, p_bc_for_u, 0); bcc.AddDirichletBoundaryCondition(*node_iter, p_bc_for_v, 1); } LinearParabolicPdeSystemWithCoupledOdeSystemSolver<2,2,2> solver(p_mesh, &pde, &bcc); double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestSchnackenbergSystemOnHoneycombMesh_paper_test"); std::vector<double> init_conds(2*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { init_conds[2*i] = fabs(2.0 + RandomNumberGenerator::Instance()->ranf()); init_conds[2*i + 1] = fabs(0.75 + RandomNumberGenerator::Instance()->ranf()); } Vec initial_condition = PetscTools::CreateVec(init_conds); solver.SetInitialCondition(initial_condition); solver.SolveAndWriteResultsToFile(); PetscTools::Destroy(initial_condition); } void TestSpectatorDependentReactionClass() { /* std::cout<<"--------------------------------------"<<std::endl; std::cout<<"Test Spectator dependent reaction class"<<std::endl; std::cout<<"--------------------------------------"<<std::endl; std::string reactionFilename = "/home/chaste/projects/ChemicalChaste/src/Data/SpectatorReactionFile.txt"; AbstractReactionSystemFromFile* p_file_reaction_system = new AbstractReactionSystemFromFile(reactionFilename); std::cout<<"-----------------------------"<<std::endl; std::cout<<"System from file"<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Read out reaction details: "<<std::endl; std::cout<<"-----------------------------"<<std::endl; std::cout<<"Number of reactions: "<<p_file_reaction_system -> GetNumberOfReactions()<<std::endl; for(unsigned i=0; i<p_file_reaction_system -> GetNumberOfReactions(); i++) { std::cout<<"Reaction: "<<i<<" "<< p_file_reaction_system -> GetReactionByIndex(i) -> GetReactionType()<<std::endl; std::cout<<"Number of spectators: "<<i<<" "<< dynamic_cast<SpectatorDependentReaction*>(p_file_reaction_system -> GetReactionByIndex(i)) -> GetNumberOfSpectators()<<std::endl; } std::vector<std::string> chemNames = p_file_reaction_system-> GetSystemChemistry() -> GetChemicalNames(); std::cout<<"System chemical names:"<<std::endl; for(unsigned i=0; i<chemNames.size();i++) { std::cout<<chemNames[i]<<std::endl; } for(unsigned i=0; i<p_file_reaction_system-> GetNumberOfReactions(); i++ ) { AbstractReaction* p_reaction = p_file_reaction_system-> GetReactionByIndex(i); std::cout<<"Reaction type: "<<p_reaction ->GetReactionType()<<std::endl; for(unsigned j=0; j<p_reaction -> GetNumberOfSubstrates(); j++) { std::cout<<"Substrate: "<<p_reaction -> GetSubstratesByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichSubstratesByIndex(j)<<std::endl; } for(unsigned j=0; j<p_reaction -> GetNumberOfProducts(); j++) { std::cout<<"Product: "<<p_reaction -> GetProductsByIndex(j) -> GetChemicalName()<<" Stoich: "<<p_reaction ->GetStoichProductsByIndex(j)<<std::endl; } } std::cout<<"-----------------------------"<<std::endl; std::cout<<"Run the file reaction system "<<std::endl; std::cout<<"-----------------------------"<<std::endl; // implicit upcast AbstractReactionSystemFromFile to AbstractReactionSystem AbstractChemicalOdeSystem chemical_ode_file(p_file_reaction_system); // read in the order Alpha, Beta, A, B, C // order speceis occurance in reaction system, then order of spectator species when duplicates removed std::vector<double> initial_condition = {1.0, 1.0,1.0,1.0,0.0}; // initial_condition = {1.0, 1.0,1.0,1.0,0.0}, in order Alpha, Beta, A, B, C // C set to 0.0 makes reaction 1 have zero rate, reaction 0 occurs at coanstant rate, while reaction 2 has variable rate EulerIvpOdeSolver euler_solver_file; OdeSolution solutions_file = euler_solver_file.Solve(&chemical_ode_file, initial_condition, 0, 1, 0.1, 0.1); for (unsigned i=0; i<solutions_file.rGetTimes().size(); i++) { std::cout << "Time: "<<solutions_file.rGetTimes()[i] << " " << solutions_file.rGetSolutions()[i][0] << " " << solutions_file.rGetSolutions()[i][1]<< " " << solutions_file.rGetSolutions()[i][2]<< "\n"; } */ } void TestChemicalOdePdeConvergence() { /* std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 1.0; double reaction_2_forward_rate = 0.5; double reaction_2_reverse_rate = 2.2; double reaction_3_rate = 1.5; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); double t_end = 10; std::cout<<"Solver 1"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver1(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties solver1.SetTimes(0, t_end); solver1.SetTimeStep(1e-1); solver1.SetSamplingTimeStep(1e-1); solver1.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-1"); solver1.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver1.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 2"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver2(p_mesh, &pde, &bcc,odeSystem,p_solver); solver2.SetTimes(0, t_end); solver2.SetTimeStep(1e-2); solver2.SetSamplingTimeStep(1e-2); solver2.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-2"); solver2.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver2.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 3"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver3(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties solver3.SetTimes(0, t_end); solver3.SetTimeStep(1e-3); solver3.SetSamplingTimeStep(1e-3); solver3.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-3"); solver3.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver3.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 4"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver4(p_mesh, &pde, &bcc,odeSystem,p_solver); solver4.SetTimes(0, t_end); solver4.SetTimeStep(1e-4); solver4.SetSamplingTimeStep(1e-4); solver4.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-4"); solver4.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver4.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 5"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver5(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties solver5.SetTimes(0, t_end); solver5.SetTimeStep(1e-5); solver5.SetSamplingTimeStep(1e-5); solver5.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-5"); solver5.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver5.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; std::cout<<"Solver 6"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver6(p_mesh, &pde, &bcc,odeSystem,p_solver); solver6.SetTimes(0, t_end); solver6.SetTimeStep(1e-6); solver6.SetSamplingTimeStep(1e-6); solver6.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_1e-6"); solver6.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver6.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); */ } void TestChemicalOdePdeParameters() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.1; double reaction_2_forward_rate = 0.1; double reaction_2_reverse_rate = 0.2; double reaction_3_rate = 0.3; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_params1"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestChemicalOdePdeParameters2() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.2; double reaction_2_forward_rate = 0.2; double reaction_2_reverse_rate = 0.4; double reaction_3_rate = 0.6; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_params2"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestChemicalOdePdeParameters3() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.3; double reaction_2_forward_rate = 0.3; double reaction_2_reverse_rate = 0.6; double reaction_3_rate = 0.9; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-4, 1e-2 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_params3"); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestChemicalOdePdeDiffusion4() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.3; double reaction_2_forward_rate = 0.3; double reaction_2_reverse_rate = 0.6; double reaction_3_rate = 0.9; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-3, 1e-1 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_diffusion1e-31e-1 "); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } void TestChemicalOdePdeDiffusion3() { std::cout<<"Mass action kinetics of Schnackenberg using the AbstractChemicalOdeSystem Class"<<std::endl; std::cout<<"-----------------------------"<<std::endl; // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 AbstractChemistry* p_system_chemistry = new AbstractChemistry(); std::vector<AbstractChemical*> p_substrates_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_substrates_3 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_1 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_2 = std::vector<AbstractChemical*>(); std::vector<AbstractChemical*> p_products_3 = std::vector<AbstractChemical*>(); std::vector<unsigned> stoich_substrates_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_1 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_2 = std::vector<unsigned>(); std::vector<unsigned> stoich_substrates_3 = std::vector<unsigned>(); std::vector<unsigned> stoich_products_3 = std::vector<unsigned>(); AbstractChemical *p_chemical_U = new AbstractChemical("U"); p_system_chemistry -> AddChemical(p_chemical_U); // add U to reactions p_substrates_1.push_back(p_chemical_U); stoich_substrates_1.push_back(2); p_products_1.push_back(p_chemical_U); stoich_products_1.push_back(3); p_products_2.push_back(p_chemical_U); stoich_products_2.push_back(1); AbstractChemical *p_chemical_V = new AbstractChemical("V"); p_system_chemistry -> AddChemical(p_chemical_V); // add V to reactions p_substrates_1.push_back(p_chemical_V); stoich_substrates_1.push_back(1); p_products_3.push_back(p_chemical_V); stoich_products_3.push_back(1); // r1: 2U + V -> 3U forwardRate = 0.1 // r2: 0 <-> U forwardRate = 0.1 reverseRate = 0.2 // r3: 0 -> V forwardRate = 0.3 double reaction_1_rate = 0.3; double reaction_2_forward_rate = 0.3; double reaction_2_reverse_rate = 0.6; double reaction_3_rate = 0.9; AbstractReaction* p_reaction_1 = new AbstractReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,reaction_1_rate); AbstractReversibleReaction* p_reaction_2 = new AbstractReversibleReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,reaction_2_forward_rate, reaction_2_reverse_rate); AbstractReaction* p_reaction_3 = new AbstractReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,reaction_3_rate); std::vector<AbstractReaction*> p_reaction_vector; p_reaction_vector.push_back(p_reaction_1); p_reaction_vector.push_back(p_reaction_2); p_reaction_vector.push_back(p_reaction_3); //AbstractReactionSystem* p_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_reaction_vector); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); MassActionReaction* p_mass_action_reaction_1 = new MassActionReaction(p_substrates_1, p_products_1, stoich_substrates_1, stoich_products_1,false,false,reaction_1_rate); MassActionReaction* p_mass_action_reaction_2 = new MassActionReaction(p_substrates_2, p_products_2, stoich_substrates_2, stoich_products_2,false, true, reaction_2_forward_rate, reaction_2_reverse_rate); MassActionReaction* p_mass_action_reaction_3 = new MassActionReaction(p_substrates_3, p_products_3, stoich_substrates_3, stoich_products_3,false, false,reaction_3_rate); std::vector<AbstractReaction*> p_mass_action_reaction_vector; p_mass_action_reaction_vector.push_back(p_mass_action_reaction_1); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_2); p_mass_action_reaction_vector.push_back(p_mass_action_reaction_3); AbstractReactionSystem* p_mass_action_reaction_system = new AbstractReactionSystem(p_system_chemistry, p_mass_action_reaction_vector); // form ode system std::cout<<"SchnackenbergCoupledPdeOdeSystem -As AbstractChemicalODeSystem"<<std::endl; // system properties const unsigned probDim =2; const unsigned spaceDim=2; const unsigned elementDim=2; std::vector<double> initValues = {2.0, 0.75}; std::vector<double> bcValues = {0.0, 0.0}; // mesh HoneycombMeshGenerator generator(10, 10, 0); MutableMesh<elementDim,spaceDim>* p_mesh = generator.GetMesh(); // Process Boundary Conditions std::cout<<"Process Boundary Conditions"<<std::endl; BoundaryConditionsContainer<elementDim,spaceDim,probDim> bcc; std::vector<bool> areNeumannBoundaryConditions(probDim, true); std::vector<ConstBoundaryCondition<spaceDim>*> vectorConstBCs; for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++){ vectorConstBCs.push_back(new ConstBoundaryCondition<spaceDim>(bcValues[pdeDim])); } for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { if(areNeumannBoundaryConditions[pdeDim]==false) { for (TetrahedralMesh<elementDim,spaceDim>::BoundaryNodeIterator node_iter = p_mesh->GetBoundaryNodeIteratorBegin(); node_iter != p_mesh->GetBoundaryNodeIteratorEnd(); ++node_iter) { bcc.AddDirichletBoundaryCondition(*node_iter, vectorConstBCs[pdeDim], pdeDim); } }else{ for (TetrahedralMesh<elementDim,spaceDim>::BoundaryElementIterator boundary_iter = p_mesh->GetBoundaryElementIteratorBegin(); boundary_iter != p_mesh->GetBoundaryElementIteratorEnd(); boundary_iter++) { bcc.AddNeumannBoundaryCondition(*boundary_iter, vectorConstBCs[pdeDim], pdeDim); } } } std::cout<<"Initial conditions"<<std::endl; // initial conditions std::vector<double> init_conds(probDim*p_mesh->GetNumNodes()); for (unsigned i=0; i<p_mesh->GetNumNodes(); i++) { // set as being a random perturbation about the boundary values for(unsigned pdeDim=0; pdeDim<probDim; pdeDim++) { // serialised for nodes init_conds[probDim*i + pdeDim] = fabs(initValues[pdeDim] + RandomNumberGenerator::Instance()->ranf()); } } // PETSc Vec std::cout<<"PETSc Vec"<<std::endl; Vec initial_condition = PetscTools::CreateVec(init_conds); //SchnackenbergCoupledPdeSystem<2> pde(1e-4, 1e-2, 0.5, 2.2, 1.5, 1); // coupled ode system std::cout<<"Ode loop"<<std::endl; std::vector<AbstractOdeSystemForCoupledPdeSystem*> odeSystem; for (unsigned i=0; i<p_mesh->GetNumNodes(); i++){ // number of ode system objects must match the number of nodes, i.e the individual odes may be multi-dimensional odeSystem.push_back(new AbstractChemicalOdeForCoupledPdeSystem(p_mass_action_reaction_system)); } std::cout<<"Number odesAtNodes: "<<p_mesh->GetNumNodes()<<std::endl; // pde system std::cout<<"Pde"<<std::endl; PdeSchnackenbergCoupledPdeOdeSystem<elementDim, spaceDim, probDim> pde(odeSystem[0],1e-2, 1 ); // used the explicitly defined EulerIvpOdeSolver rather than the default defined BackwardEuler method //EulerIvpOdeSolver euler_solver; boost::shared_ptr<EulerIvpOdeSolver> p_solver(new EulerIvpOdeSolver); std::cout<<"Solver"<<std::endl; // solver LinearParabolicPdeSystemWithCoupledOdeSystemSolver<elementDim,spaceDim,probDim> solver(p_mesh, &pde, &bcc,odeSystem,p_solver); // solver properties double t_end = 10; solver.SetTimes(0, t_end); solver.SetTimeStep(1e-2); solver.SetSamplingTimeStep(1e-2); solver.SetOutputDirectory("TestAbstractChemicalOdeOutput_groupMeeting_diffusion1e-21e-0 "); solver.SetInitialCondition(initial_condition); // solve std::cout<<"Solve"<<std::endl; //solver.SolveAndWriteResultsToFile(); solver.SolveAndWriteResultsToFile(); std::cout<<"Clean"<<std::endl; // clean PetscTools::Destroy(initial_condition); } }; #endif
48.37922
212
0.656184
OSS-Lab
63d2dbb37e19b9e98ee0d5ce0dc7cc453047432c
432
cpp
C++
src/3rdPartyLib/EASTL.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
2
2020-02-03T04:58:17.000Z
2021-03-13T06:03:52.000Z
src/3rdPartyLib/EASTL.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
null
null
null
src/3rdPartyLib/EASTL.cpp
SapphireEngine/Engine
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
[ "MIT" ]
null
null
null
#include "define.h" #include <EASTL/EAStdC/EAMemory.cpp> #include <EASTL/EAStdC/EASprintf.cpp> #include <EASTL/MemoryTracking.cpp> #include <EASTL/allocator_forge.cpp> #include <EASTL/assert.cpp> #include <EASTL/fixed_pool.cpp> #include <EASTL/hashtable.cpp> #include <EASTL/intrusive_list.cpp> #include <EASTL/numeric_limits.cpp> #include <EASTL/red_black_tree.cpp> #include <EASTL/string.cpp> #include <EASTL/thread_support.cpp>
28.8
37
0.784722
SapphireEngine
63d4d437895d91607a767b9af49b58f1abe98e8a
15,529
cpp
C++
src/FeatureMatcher.cpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
src/FeatureMatcher.cpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
src/FeatureMatcher.cpp
charlie-lee/slam_demo
0bb6cc6d20c6a728eea502a61456f83881144e59
[ "MIT" ]
null
null
null
/** * @file FeatureMatcher.cpp * @brief Implementation of feature matcher class in SLAM system. * @author Charlie Li * @date 2019.10.22 */ #include "FeatureMatcher.hpp" #include <map> #include <memory> #include <vector> #include <opencv2/core.hpp> #include <opencv2/features2d.hpp> #include "Config.hpp" #include "FrameBase.hpp" #include "MapPoint.hpp" #include "Utility.hpp" namespace SLAM_demo { using cv::Mat; using std::make_shared; using std::map; using std::shared_ptr; using std::vector; FeatureMatcher::FeatureMatcher(float thDistMatchMax, bool bUseLoweRatioTest, float thRatioTest, float thAngMatchMax, int thDistDescMax) : mThDistMatchMax(thDistMatchMax), mbUseLoweRatioTest(bUseLoweRatioTest), mThRatioTest(thRatioTest), mThAngMatchMax(thAngMatchMax), mThDistDescMax(thDistDescMax) { // initialize feature matcher if (mbUseLoweRatioTest) { // FLANN-based matcher & use Lowe's ratio test //mpFeatMatcher = make_shared<cv::FlannBasedMatcher>( // cv::makePtr<cv::flann::LshIndexParams>(12, 20, 2)); mpFeatMatcher = cv::BFMatcher::create(cv::NORM_HAMMING, false); } else { // use symmetric test mpFeatMatcher = cv::BFMatcher::create(cv::NORM_HAMMING, true); } } std::vector<cv::DMatch> FeatureMatcher::match2Dto2D( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1) const { unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; vector<vector<cv::DMatch>> vvMatches21; mpFeatMatcher->knnMatch(pF2->descriptors(), // query pF1->descriptors(), // train vvMatches21, nBestMatches); // number of best matches return filterMatchResult(vvMatches21, pF2, pF1); } std::vector<cv::DMatch> FeatureMatcher::match2Dto2DCustom( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1) const { vector<cv::DMatch> vMatches21; vector<cv::KeyPoint> vKpts2 = pF2->keypoints(); vMatches21.reserve(vKpts2.size()); // traverse each keypoint in frame 2 for its match in frame 1 for (unsigned i = 0; i < vKpts2.size(); ++i) { const cv::KeyPoint& kpt2 = vKpts2[i]; float angle = kpt2.angle; Mat desc2 = pF2->descriptor(i); vector<int> vKptIndices = pF1->featuresInRange( Mat(kpt2.pt), angle, mThDistMatchMax, mThAngMatchMax); // traverse each keypoint index and get best match int nBestIdx1 = -1; // for frame 1 int nBestDist = 256; int nBestDist2nd = 256; for (const int& kptIdx : vKptIndices) { Mat desc1 = pF1->descriptor(kptIdx); int nDist = hammingDistance(desc2, desc1); if (nDist < nBestDist) { nBestDist2nd = nBestDist; nBestDist = nDist; nBestIdx1 = kptIdx; } } if (nBestIdx1 < 0 || nBestDist > mThDistDescMax) { continue; } // Lowe's ratio test if (static_cast<float>(nBestDist) >= mThRatioTest * nBestDist2nd) { continue; } // construct cv::DMatch object cv::DMatch match21(i, nBestIdx1, static_cast<float>(nBestDist)); vMatches21.push_back(match21); } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::match2Dto3D( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1, bool bBindMPts) const { unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; // get matching mask map<int, shared_ptr<MapPoint>> mpMPts1 = pF1->getMPtsMap(); //const vector<cv::KeyPoint>& vKpts1 = pF1->keypoints(); //const vector<cv::KeyPoint>& vKpts2 = pF2->keypoints(); //vector<int> vIdxKpts1; //vIdxKpts1.reserve(mpMPts1.size()); //for (const auto& pair : mpMPts1) { // vIdxKpts1.push_back(pair.first); //} //Mat mask = getMatchMask2Dto3D(vIdxKpts1, vKpts2.size(), vKpts1.size()); vector<bool> vbMPtsValid(pF1->keypoints().size(), false); for (const auto& pair : mpMPts1) { vbMPtsValid[pair.first] = true; } // feature matching with mask (partial query set and full train set) vector<vector<cv::DMatch>> vvMatches21; mpFeatMatcher->knnMatch(pF2->descriptors(), // query pF1->descriptors(), // train vvMatches21, nBestMatches, //mask, true); // mask is not functioning!!! cv::noArray(), false); vector<cv::DMatch> vMatches21 = filterMatchResult(vvMatches21, pF2, pF1, vbMPtsValid); // update map point data on current frame (pF2) if (bBindMPts) { for (const auto& match21 : vMatches21) { shared_ptr<MapPoint> pMPt = pF1->mappoint(match21.trainIdx); pF2->bindMPt(pMPt, match21.queryIdx); } } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::match2Dto3D( const std::shared_ptr<FrameBase>& pF2, const std::vector<std::shared_ptr<MapPoint>>& vpMPts, bool bBindMPts) const { unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; // get all descriptors Mat descXws; for (const auto& pMPt : vpMPts) { descXws.push_back(pMPt->descriptor()); } if (descXws.empty()) { return vector<cv::DMatch>(); } // feature matching with mask (partial query set and full train set) vector<vector<cv::DMatch>> vvMatches21; mpFeatMatcher->knnMatch(pF2->descriptors(), // query descXws, // train vvMatches21, nBestMatches); vector<cv::DMatch> vMatches21 = filterMatchResult(vvMatches21, pF2, vpMPts); // update map point data on current frame (pF2) if (bBindMPts) { for (const auto& match21 : vMatches21) { shared_ptr<MapPoint> pMPt = vpMPts[match21.trainIdx]; pF2->bindMPt(pMPt, match21.queryIdx); } } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::match2Dto3DCustom( const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1, bool bBindMPts) const { vector<cv::DMatch> vMatches21; map<int, shared_ptr<MapPoint>> mpMPts1 = pF1->getMPtsMap(); vMatches21.reserve(mpMPts1.size()); // traverse each 3D point for its 2D match for (const auto& pair : mpMPts1) { const shared_ptr<MapPoint>& pMPt = pair.second; Mat x = pF2->coordWorld2Img(pMPt->X3D()); // skip out-of-border reprojected points if (!Utility::is2DPtInBorder(x)) { continue; } float angle = pMPt->angle(); Mat desc1 = pMPt->descriptor(); vector<int> vKptIndices = pF2->featuresInRange( x, angle, mThDistMatchMax, mThAngMatchMax); // traverse each keypoint index and get best match int nBestIdx2 = -1; // for frame 2 int nBestDist = 256; int nBestDist2nd = 256; for (const int& kptIdx : vKptIndices) { Mat desc2 = pF2->descriptor(kptIdx); int nDist = hammingDistance(desc2, desc1); if (nDist < nBestDist) { nBestDist2nd = nBestDist; nBestDist = nDist; nBestIdx2 = kptIdx; } } if (nBestIdx2 < 0 || nBestDist > mThDistDescMax) { continue; } // Lowe's ratio test if (static_cast<float>(nBestDist) >= mThRatioTest * nBestDist2nd) { continue; } // construct cv::DMatch object int nIdx1 = pair.first; // frame 1 cv::DMatch match21(nBestIdx2, nIdx1, static_cast<float>(nBestDist)); vMatches21.push_back(match21); } // update map point data on current frame (pF2) if (bBindMPts) { for (const auto& match21 : vMatches21) { shared_ptr<MapPoint> pMPt = pF1->mappoint(match21.trainIdx); pF2->bindMPt(pMPt, match21.queryIdx); } } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::match2Dto3DCustom( const std::shared_ptr<FrameBase>& pF2, const std::vector<std::shared_ptr<MapPoint>>& vpMPts, bool bBindMPts) const { vector<cv::DMatch> vMatches21; int nMPts = vpMPts.size(); vMatches21.reserve(nMPts); // traverse each 3D point for its 2D match for (int i = 0; i < nMPts; ++i) { const auto& pMPt = vpMPts[i]; Mat x = pF2->coordWorld2Img(pMPt->X3D()); // skip out-of-border reprojected points if (!Utility::is2DPtInBorder(x)) { continue; } float angle = pMPt->angle(); Mat desc1 = pMPt->descriptor(); vector<int> vKptIndices = pF2->featuresInRange( x, angle, mThDistMatchMax, mThAngMatchMax); // traverse each keypoint index and get best match int nBestIdx2 = -1; // for frame 2 int nBestDist = 256; int nBestDist2nd = 256; for (const int& kptIdx : vKptIndices) { Mat desc2 = pF2->descriptor(kptIdx); int nDist = hammingDistance(desc2, desc1); if (nDist < nBestDist) { nBestDist2nd = nBestDist; nBestDist = nDist; nBestIdx2 = kptIdx; } } if (nBestIdx2 < 0 || nBestDist > mThDistDescMax) { continue; } // Lowe's ratio test if (static_cast<float>(nBestDist) >= mThRatioTest * nBestDist2nd) { continue; } // construct cv::DMatch object int nIdx1 = i; // frame 1 cv::DMatch match21(nBestIdx2, nIdx1, static_cast<float>(nBestDist)); vMatches21.push_back(match21); } // update map point data on current frame (pF2) if (bBindMPts) { for (const auto& match21 : vMatches21) { shared_ptr<MapPoint> pMPt = vpMPts[match21.trainIdx]; pF2->bindMPt(pMPt, match21.queryIdx); } } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::filterMatchResult( const std::vector<std::vector<cv::DMatch>>& vvMatches21, const std::shared_ptr<FrameBase>& pF2, const std::shared_ptr<FrameBase>& pF1, const std::vector<bool>& vbMask1) const { vector<cv::DMatch> vMatches21; vMatches21.reserve(vvMatches21.size()); unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; const vector<cv::KeyPoint>& vKpts1 = pF1->keypoints(); const vector<cv::KeyPoint>& vKpts2 = pF2->keypoints(); bool b2Dto2DCase = vbMask1.empty() ? true : false; for (unsigned i = 0; i < vvMatches21.size(); ++i) { // skip invalid matching result if (vvMatches21[i].size() != nBestMatches) { continue; } // skip null map point if (!b2Dto2DCase && !vbMask1[vvMatches21[i][0].trainIdx]) { continue; } // Lowe's ratio test if (nBestMatches == 2 && vvMatches21[i][0].distance >= mThRatioTest * vvMatches21[i][1].distance) { continue; } // filter out-of-border matches const cv::Point2f& pt1 = vKpts1[vvMatches21[i][0].trainIdx].pt; const cv::Point2f& pt2 = vKpts2[vvMatches21[i][0].queryIdx].pt; if (!Utility::is2DPtInBorder(Mat(pt1)) && !Utility::is2DPtInBorder(Mat(pt2))) { continue; } // filter matches whose dist between (reprojected) 2D point in view 1 // and 2D point in view 2 is larger than a threshold Mat x1; if (b2Dto2DCase) { x1 = Mat(pt1); } else { const shared_ptr<MapPoint> pMPt = pF1->mappoint(vvMatches21[i][0].trainIdx); assert(pMPt); x1 = pF1->coordWorld2Img(pMPt->X3D()); } Mat x2 = Mat(pt2); Mat xDiff = x1 - x2; float xDistSq = xDiff.dot(xDiff); if (xDistSq > mThDistMatchMax * mThDistMatchMax) { continue; } vMatches21.push_back(vvMatches21[i][0]); } return vMatches21; } std::vector<cv::DMatch> FeatureMatcher::filterMatchResult( const std::vector<std::vector<cv::DMatch>>& vvMatches21, const std::shared_ptr<FrameBase>& pF2, const std::vector<std::shared_ptr<MapPoint>>& vpMPts) const { vector<cv::DMatch> vMatches21; vMatches21.reserve(vvMatches21.size()); unsigned nBestMatches = mbUseLoweRatioTest ? 2 : 1; const vector<cv::KeyPoint>& vKpts2 = pF2->keypoints(); for (unsigned i = 0; i < vvMatches21.size(); ++i) { // skip invalid matching result if (vvMatches21[i].size() != nBestMatches) { continue; } // Lowe's ratio test if (nBestMatches == 2 && vvMatches21[i][0].distance >= mThRatioTest * vvMatches21[i][1].distance) { continue; } // filter out-of-border matches const shared_ptr<MapPoint>& pMPt = vpMPts[vvMatches21[i][0].trainIdx]; Mat x1 = pF2->coordWorld2Img(pMPt->X3D()); const cv::Point2f& pt1 = cv::Point2f(x1.at<float>(0), x1.at<float>(1)); const cv::Point2f& pt2 = vKpts2[vvMatches21[i][0].queryIdx].pt; if (!Utility::is2DPtInBorder(Mat(pt1)) && !Utility::is2DPtInBorder(Mat(pt2))) { continue; } // filter matches whose dist between (reprojected) 2D point in view 1 // and 2D point in view 2 is larger than a threshold Mat x2 = Mat(pt2); Mat xDiff = x1 - x2; float xDistSq = xDiff.dot(xDiff); if (xDistSq > mThDistMatchMax * mThDistMatchMax) { continue; } vMatches21.push_back(vvMatches21[i][0]); } return vMatches21; } cv::Mat FeatureMatcher::getMatchMask2Dto3D(const std::vector<int>& vIdxKpts1, int nKpts2, int nKpts1) const { Mat mask; // {row = vIdxKpts1.size(), col = nNumKpts2, type = CV_8UC1} int idx = 0; int nMPts = vIdxKpts1.size(); for (int i = 0; i < nKpts1; ++i) { bool bAllowMatching = false; if (idx == nMPts) { // last kpt index traversed bAllowMatching = false; } else { if (i < vIdxKpts1[idx]) { // less than nearest kpt index bAllowMatching = false; } else { // kpt index with map point bound bAllowMatching = true; } } // add one row to the transpose of mask if (bAllowMatching) { mask.push_back(Mat::ones(1, nKpts2, CV_8UC1)); ++idx; } else { mask.push_back(Mat::zeros(1, nKpts2, CV_8UC1)); } } mask = mask.t(); assert(mask.rows == nKpts2 && mask.cols == nKpts1); return mask; } int FeatureMatcher::hammingDistance(const cv::Mat& a, const cv::Mat& b) const { // Bit set count operation from const int* pa = a.ptr<int32_t>(); const int* pb = b.ptr<int32_t>(); int nDist = 0; for(int i = 0; i < 8; i++, pa++, pb++) { unsigned int v = *pa ^ *pb; v = v - ((v >> 1) & 0x55555555); v = (v & 0x33333333) + ((v >> 2) & 0x33333333); nDist += (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; } return nDist; } } // namespace SLAM_demo
36.198135
79
0.58072
charlie-lee
63d9e63f08e9c4646f09ee657912820fa850eec5
2,542
hpp
C++
Project/Folie/Ball.hpp
mikymaione/Folie
a5e2ea35f792036da7f2988adeace7f4b361c0f7
[ "MIT" ]
1
2019-08-29T09:00:16.000Z
2019-08-29T09:00:16.000Z
Project/Folie/Ball.hpp
mikymaione/Folie
a5e2ea35f792036da7f2988adeace7f4b361c0f7
[ "MIT" ]
null
null
null
Project/Folie/Ball.hpp
mikymaione/Folie
a5e2ea35f792036da7f2988adeace7f4b361c0f7
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2019 Michele Maione Permission is hereby granted, free of charge, toE any person obtaining a copy of this software and associated documentation files (the "Software"), toE deal in the Software without restriction, including without limitation the rights toE use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and toE permit persons toE whom the Software is furnished toE do so, subject toE the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "GB.hpp" #include "Unity/MonoBehaviourEX.hpp" #using <UnityEngine.PhysicsModule.dll> as_friend namespace Folie { ref class CoroutineQueue; // cross reference ref class Player; // cross reference public ref class Ball sealed :Unity::MonoBehaviourEX { private: CoroutineQueue ^waiter; UnityEngine::Rigidbody ^rigidBody; UnityEngine::Transform ^inHand; bool hitted, hitting, ground; internal: Player ^lastPlayerTouch; Enums::eArea targetArea; UnityEngine::Vector2 destination2D, target2D; UnityEngine::Vector3 destination3D; internal: Enums::eField getActualField(); void attachToHand(String ^player_name); bool ballInHand(); bool ballIsFlying(); bool started() override; Enums::eArea getTargetArea(); private: void Start(); void Update(); void OnCollisionEnter(UnityEngine::Collision collision); void addForce(Player ^playerTouch, Enums::eField field, UnityEngine::Vector2 coordinate2D, float angle_Deg); void setHitting(bool hitting_); void ballOnTheFloor(); public: Ball(); void serve(Player ^playerTouch, Enums::eField field, UnityEngine::Vector2 coordinate2D); void hit(Player ^playerTouch, Enums::eField field, Enums::ePosition position, float angle_Deg); void hit(Player ^playerTouch, Enums::eField field, Enums::eArea area, float angle_Deg); void hit(Player ^playerTouch, Enums::eField field, UnityEngine::Vector2 coordinate2D, float angle_Deg); }; }
34.821918
566
0.773013
mikymaione
63ded9f813358a38390085d3bf10a969e57df1e6
10,700
cpp
C++
code_reading/oceanbase-master/src/sql/resolver/ob_stmt.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/resolver/ob_stmt.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/resolver/ob_stmt.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_RESV #include "sql/resolver/ob_stmt.h" #include "sql/resolver/dml/ob_select_stmt.h" #include "sql/resolver/ob_stmt_resolver.h" //#include "sql/resolver/ob_schema_checker.h" #include "share/schema/ob_table_schema.h" #include "share/inner_table/ob_inner_table_schema.h" #include "sql/resolver/expr/ob_raw_expr_util.h" #include "sql/session/ob_sql_session_info.h" #include "share/schema/ob_column_schema.h" #include "sql/ob_sql_context.h" #include "common/ob_field.h" #include "sql/parser/ob_parser.h" #include "common/sql_mode/ob_sql_mode.h" namespace oceanbase { using namespace common; using namespace share::schema; namespace sql { // query_ctx_ no deep_copy // child_stmts_ no deep_copy // parent_stmt no deep_copy // synonym_is_store no deep_copy int ObStmt::assign(const ObStmt& other) { int ret = OB_SUCCESS; if (OB_FAIL(synonym_id_store_.assign(other.synonym_id_store_))) { LOG_WARN("failed to assign synonym id store", K(ret)); } else { stmt_type_ = other.stmt_type_; literal_stmt_type_ = other.literal_stmt_type_; sql_stmt_ = other.sql_stmt_; query_ctx_ = other.query_ctx_; tz_info_ = other.tz_info_; stmt_id_ = other.stmt_id_; } return ret; } int ObStmt::deep_copy(const ObStmt& other) { int ret = OB_SUCCESS; if (OB_FAIL(assign(other))) { LOG_WARN("failed to deep copy stmt", K(ret)); } else { /*do nothing*/ } return ret; } int ObStmt::check_table_id_exists(uint64_t table_id, bool& is_exist) { int ret = OB_SUCCESS; is_exist = false; if (OB_HASH_EXIST == (ret = get_query_ctx()->table_ids_.exist_refactored(table_id))) { ret = OB_SUCCESS; is_exist = true; } else if (OB_HASH_NOT_EXIST == ret) { if (OB_FAIL(get_query_ctx()->table_ids_.set_refactored(table_id))) { SQL_RESV_LOG(WARN, "insert table_id to set failed", K(table_id), K(ret)); } } else { SQL_RESV_LOG(WARN, "check table_id in table_ids set failed", K(table_id)); } return ret; } ObIArray<ObRawExpr*>& ObStmt::get_exec_param_ref_exprs() { return query_ctx_->exec_param_ref_exprs_; } ObIArray<ObRawExpr*>& ObStmt::get_exec_param_ref_exprs() const { return query_ctx_->exec_param_ref_exprs_; } bool ObStmt::get_fetch_cur_time() const { return query_ctx_->fetch_cur_time_; } int64_t ObStmt::get_pre_param_size() const { return query_ctx_->question_marks_count_; } void ObStmt::increase_question_marks_count() { ++query_ctx_->question_marks_count_; } int64_t ObStmt::get_question_marks_count() const { return query_ctx_->question_marks_count_; } int ObStmt::add_calculable_item(const ObHiddenColumnItem& calcuable_item) { increase_question_marks_count(); return query_ctx_->calculable_items_.push_back(calcuable_item); } const ObIArray<ObHiddenColumnItem>& ObStmt::get_calculable_exprs() const { return query_ctx_->calculable_items_; } common::ObIArray<ObHiddenColumnItem>& ObStmt::get_calculable_exprs() { return query_ctx_->calculable_items_; } void ObStmt::set_stmt_id() { if (NULL == query_ctx_) { stmt_id_ = 0; } else { stmt_id_ = query_ctx_->get_new_stmt_id(); } } int ObStmt::get_stmt_name_by_id(int64_t stmt_id, ObString& stmt_name) const { int ret = OB_SUCCESS; if (OB_ISNULL(query_ctx_)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("query_ctx_ is NULL", K(ret)); } else if (OB_FAIL(query_ctx_->get_stmt_name_by_id(stmt_id, stmt_name))) { LOG_WARN("fail to get stmt name by id", K(ret), K(stmt_id)); } else { /*do nothing*/ } return ret; } int ObStmt::get_first_stmt(common::ObString& first_stmt) { int ret = OB_SUCCESS; ObArenaAllocator allocator(ObModIds::OB_SQL_PARSER); ObSEArray<ObString, 1> queries; ObMPParseStat parse_stat; ObParser parser(allocator, DEFAULT_OCEANBASE_MODE); if (OB_FAIL(parser.split_multiple_stmt(get_sql_stmt(), queries, parse_stat, true /* return the first stmt */))) { ret = OB_ERR_UNEXPECTED; LOG_WARN("Get first statement from multiple statements failed", K(ret)); } else if (0 == queries.count()) { ret = OB_ERR_UNEXPECTED; LOG_WARN("Get non-statement from multiple statements", K(ret)); } else { first_stmt = queries.at(0); } return ret; } int ObStmt::get_stmt_org_name_by_id(int64_t stmt_id, common::ObString& org_name) const { int ret = OB_SUCCESS; if (OB_ISNULL(query_ctx_)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("query_ctx_ is NULL", K(ret)); } else if (OB_FAIL(query_ctx_->get_stmt_org_name_by_id(stmt_id, org_name))) { LOG_WARN("fail to get stmt name by id", K(ret), K(stmt_id)); } else { /*do nothing*/ } return ret; } int ObStmt::get_stmt_name(ObString& stmt_name) const { return get_stmt_name_by_id(stmt_id_, stmt_name); } int ObStmt::get_stmt_org_name(common::ObString& org_name) const { return get_stmt_org_name_by_id(stmt_id_, org_name); } int ObStmt::distribute_hint_in_query_ctx(common::ObIAllocator* allocator) { int ret = OB_SUCCESS; if (OB_ISNULL(query_ctx_)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("Query ctx is NULL", K(ret)); } else if (OB_FAIL(query_ctx_->generate_stmt_name(allocator))) { LOG_WARN("Failed to generate stmt name", K(ret)); } else if (OB_FAIL(query_ctx_->distribute_hint_to_stmt())) { LOG_WARN("Failed to distribute hint to stmt", K(ret)); } else { } return ret; } ObStmt::~ObStmt() {} int ObStmt::check_synonym_id_exist(uint64_t synonym_id, bool& is_exist) { int ret = OB_SUCCESS; is_exist = false; for (int64_t i = 0; OB_SUCC(ret) && !is_exist && i < synonym_id_store_.count(); ++i) { if (synonym_id == synonym_id_store_.at(i)) { is_exist = true; } } return ret; } int ObStmt::add_synonym_ids(const ObIArray<uint64_t>& synonym_ids, bool error_with_exist) { int ret = OB_SUCCESS; bool is_exist = false; for (int64_t i = 0; OB_SUCC(ret) && i < synonym_ids.count(); ++i) { uint64_t cur_synonym_id = synonym_ids.at(i); if (OB_FAIL(check_synonym_id_exist(cur_synonym_id, is_exist))) { LOG_WARN("fail to check synoym id exist", K(cur_synonym_id), K(ret)); } else if (is_exist) { if (error_with_exist) { ret = OB_ERR_LOOP_OF_SYNONYM; LOG_WARN("looping chain of synonyms", K(cur_synonym_id), K(ret)); } } else if (OB_FAIL(synonym_id_store_.push_back(cur_synonym_id))) { LOG_WARN("fail to add synonym id", K(cur_synonym_id), K(ret)); } } return ret; } int ObStmt::add_global_dependency_table(const ObSchemaObjVersion& dependency_table) { int ret = OB_SUCCESS; if (OB_ISNULL(get_query_ctx())) { ret = OB_NOT_INIT; LOG_WARN("query_ctx is null"); } else { bool is_found = false; for (int64_t i = 0; OB_SUCC(ret) && !is_found && i < get_query_ctx()->global_dependency_tables_.count(); ++i) { const ObSchemaObjVersion& obj_version = get_query_ctx()->global_dependency_tables_.at(i); // the operation in plan cache is different for explicit and implicit dbname, // so we need make a judgment here. if (obj_version.get_object_id() == dependency_table.get_object_id() && obj_version.object_type_ == dependency_table.object_type_ && obj_version.is_db_explicit() == dependency_table.is_db_explicit()) { is_found = true; } } if (OB_SUCC(ret) && !is_found) { ret = get_query_ctx()->global_dependency_tables_.push_back(dependency_table); } } return ret; } int ObStmt::add_table_stat_version(const ObOptTableStatVersion& table_stat_version) { int ret = OB_SUCCESS; if (OB_ISNULL(get_query_ctx())) { ret = OB_NOT_INIT; LOG_WARN("query_ctx is null"); } else { bool is_found = false; for (int64_t i = 0; OB_SUCC(ret) && !is_found && i < get_query_ctx()->table_stat_versions_.count(); ++i) { const ObOptTableStatVersion& stat_version = get_query_ctx()->table_stat_versions_.at(i); if (stat_version.key_.table_id_ == table_stat_version.key_.table_id_) { is_found = true; } } if (OB_SUCC(ret) && !is_found) { ret = get_query_ctx()->table_stat_versions_.push_back(table_stat_version); } } return ret; } const ObIArray<ObSchemaObjVersion>* ObStmt::get_global_dependency_table() const { const ObIArray<ObSchemaObjVersion>* ret = NULL; if (query_ctx_ != NULL) { ret = &(query_ctx_->global_dependency_tables_); } return ret; } ObIArray<share::schema::ObSchemaObjVersion>* ObStmt::get_global_dependency_table() { ObIArray<ObSchemaObjVersion>* ret = NULL; if (query_ctx_ != NULL) { ret = &(query_ctx_->global_dependency_tables_); } return ret; } const ObIArray<ObOptTableStatVersion>* ObStmt::get_table_stat_versions() const { const ObIArray<ObOptTableStatVersion>* ret = NULL; if (query_ctx_ != NULL) { ret = &(query_ctx_->table_stat_versions_); } return ret; } void ObStmtFactory::destory() { DLIST_FOREACH_NORET(node, stmt_store_.get_obj_list()) { if (node != NULL && node->get_obj() != NULL) { node->get_obj()->~ObStmt(); } } stmt_store_.destory(); if (query_ctx_ != NULL) { query_ctx_->~ObQueryCtx(); query_ctx_ = NULL; } } ObQueryCtx* ObStmtFactory::get_query_ctx() { void* ptr = NULL; if (NULL == query_ctx_) { if ((ptr = allocator_.alloc(sizeof(ObQueryCtx))) != NULL) { query_ctx_ = new (ptr) ObQueryCtx(); } else { LOG_WARN("create query ctx failed", "query_ctx size", sizeof(ObQueryCtx)); } } return query_ctx_; } template <> int ObStmtFactory::create_stmt<ObSelectStmt>(ObSelectStmt*& stmt) { int ret = common::OB_SUCCESS; void* ptr = NULL; if (free_list_.get_obj_list().is_empty()) { ptr = allocator_.alloc(sizeof(ObSelectStmt)); } else { stmt = free_list_.get_obj_list().remove_first()->get_obj(); stmt->~ObSelectStmt(); ptr = stmt; } stmt = NULL; if (OB_UNLIKELY(NULL == ptr)) { ret = common::OB_ALLOCATE_MEMORY_FAILED; SQL_RESV_LOG(ERROR, "no more memory to stmt"); } else { stmt = new (ptr) ObSelectStmt(); if (OB_FAIL(stmt_store_.store_obj(stmt))) { SQL_RESV_LOG(WARN, "store stmt failed", K(ret)); stmt->~ObSelectStmt(); stmt = NULL; } } return ret; } } // namespace sql } // namespace oceanbase
28.918919
115
0.701682
wangcy6
63e18aab313c11a3524d142c4f0b1cbba7d1e49e
3,390
cpp
C++
CppP4rhSln/10/querymain.cpp
blacop/CppPR
a76574ee83000d898d989aab96eac4ac746244fa
[ "MIT" ]
1
2017-04-01T06:57:30.000Z
2017-04-01T06:57:30.000Z
gnu_files/10/querymain.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
gnu_files/10/querymain.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
1
2022-01-25T15:51:34.000Z
2022-01-25T15:51:34.000Z
/* * This file contains code from "C++ Primer, Fourth Edition", by Stanley B. * Lippman, Jose Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2005 by Objectwrite, Inc., Jose Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Contracts Department * 75 Arlington Street, Suite 300 * Boston, MA 02216 * Fax: (617) 848-7047 */ #include "TextQuery.h" #include <string> #include <vector> #include <map> #include <set> #include <iostream> #include <fstream> #include <cctype> #include <cstring> #include <cstdlib> using std::set; using std::string; using std::map; using std::vector; using std::cerr; using std::cout; using std::cin; using std::ifstream; using std::endl; string make_plural(size_t, const string&, const string&); ifstream& open_file(ifstream&, const string&); void print_results(const set<TextQuery::line_no>& locs, const string& sought, const TextQuery &file) { // if the word was found, then print count and all occurrences typedef set<TextQuery::line_no> line_nums; line_nums::size_type size = locs.size(); cout << "\n" << sought << " occurs " << size << " " << make_plural(size, "time", "s") << endl; // print each line in which the word appeared line_nums::const_iterator it = locs.begin(); for ( ; it != locs.end(); ++it) { cout << "\t(line " // don't confound user with text lines starting at 0 << (*it) + 1 << ") " << file.text_line(*it) << endl; } } // program takes single argument specifying the file to query int main(int argc, char **argv) { // open the file from which user will query words ifstream infile; if (argc < 2 || !open_file(infile, argv[1])) { cerr << "No input file!" << endl; return EXIT_FAILURE; } TextQuery tq; tq.read_file(infile); // builds query map // iterate with the user: prompt for a word to find and print results // loop indefinitely; the loop exit is inside the while while (true) { cout << "enter word to look for, or q to quit: "; string s; cin >> s; // stop if hit eof on input or a 'q' is entered if (!cin || s == "q") break; // get the set of line numbers on which this word appears set<TextQuery::line_no> locs = tq.run_query(s); // print count and all occurrences, if any print_results(locs, s, tq); } return 0; }
32.596154
79
0.657227
blacop
63e683b557c248cfb2e27d91b3cd4c6d3dfa8157
179
cxx
C++
ports/x11-wm/bbpager/dragonfly/patch-src_main.cxx
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
31
2015-02-06T17:06:37.000Z
2022-03-08T19:53:28.000Z
ports/x11-wm/bbpager/dragonfly/patch-src_main.cxx
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
236
2015-06-29T19:51:17.000Z
2021-12-16T22:46:38.000Z
ports/x11-wm/bbpager/dragonfly/patch-src_main.cxx
liweitianux/DeltaPorts
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
[ "BSD-2-Clause-FreeBSD" ]
52
2015-02-06T17:05:36.000Z
2021-10-21T12:13:06.000Z
--- src/main.cxx.orig 2005-10-30 12:58:37.000000000 +0200 +++ src/main.cxx @@ -25,6 +25,7 @@ #include <stdio.h> #include <string> +#include <cstring> #include <iostream>
16.272727
57
0.625698
liweitianux
63eb04c50b7f543a79bdb64d952e565b78c27ac7
3,032
cpp
C++
Gems/LyShine/Code/Editor/HierarchyHeader.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Gems/LyShine/Code/Editor/HierarchyHeader.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/LyShine/Code/Editor/HierarchyHeader.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "UiCanvasEditor_precompiled.h" #include "EditorCommon.h" #define UICANVASEDITOR_HIERARCHY_HEADER_ICON_EYE ":/Icons/Eye.svg" #define UICANVASEDITOR_HIERARCHY_HEADER_ICON_PADLOCK ":/Icons/Padlock.svg" HierarchyHeader::HierarchyHeader(HierarchyWidget* parent) : QHeaderView(Qt::Horizontal, parent) , m_hierarchy(parent) , m_visibleIcon(UICANVASEDITOR_HIERARCHY_HEADER_ICON_EYE) , m_selectableIcon(UICANVASEDITOR_HIERARCHY_HEADER_ICON_PADLOCK) { setMouseTracking(true); setSectionsMovable(false); setStretchLastSection(false); QObject::connect(this, &QHeaderView::sectionClicked, this, [parent](int logicalIndex) { if (logicalIndex == kHierarchyColumnName) { // Nothing to do. return; } HierarchyItemRawPtrList items = SelectionHelpers::GetSelectedHierarchyItems(parent, parent->selectedItems()); if (items.empty()) { // If nothing is selected, then act on all existing items. HierarchyHelpers::AppendAllChildrenToEndOfList(parent->invisibleRootItem(), items); if (items.empty()) { // Nothing to do. return; } } if (logicalIndex == kHierarchyColumnIsVisible) { CommandHierarchyItemToggleIsVisible::Push(parent->GetEditorWindow()->GetActiveStack(), parent, items); } else if (logicalIndex == kHierarchyColumnIsSelectable) { CommandHierarchyItemToggleIsSelectable::Push(parent->GetEditorWindow()->GetActiveStack(), parent, items); } else { // This should NEVER happen. AZ_Assert(0, "Unxpected value for logicalIndex"); } }); } QSize HierarchyHeader::sizeHint() const { // This controls the height of the header. return QSize(UICANVASEDITOR_HIERARCHY_HEADER_ICON_SIZE, UICANVASEDITOR_HIERARCHY_HEADER_ICON_SIZE); } void HierarchyHeader::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const { if (logicalIndex == kHierarchyColumnIsVisible) { m_visibleIcon.paint(painter, rect); } else if (logicalIndex == kHierarchyColumnIsSelectable) { m_selectableIcon.paint(painter, rect); } // IMPORTANT: We DON'T want to call QHeaderView::paintSection() here. // Otherwise it will draw over our icons. } void HierarchyHeader::enterEvent(QEvent* ev) { m_hierarchy->ClearItemBeingHovered(); QHeaderView::enterEvent(ev); } #include <moc_HierarchyHeader.cpp>
31.257732
158
0.62533
aaarsene
63eb7f8c7b92d5f5920e96694250197b72c0a9c1
4,333
cpp
C++
remodet_repository_wdh_part/src/caffe/pose/pose_image_loader.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/src/caffe/pose/pose_image_loader.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/src/caffe/pose/pose_image_loader.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
#include "caffe/tracker/bounding_box.hpp" #include "caffe/pose/pose_image_loader.hpp" namespace caffe { using std::vector; using std::string; template <typename Dtype> void PoseImageLoader<Dtype>::LoadImage(const int image_num, cv::Mat* image) { const MetaData<Dtype>& annotation = annotations_[image_num]; const string& image_file = annotation.img_path; *image = cv::imread(image_file.c_str()); if (!image->data) { LOG(FATAL) << "Could not open or find image: " << image_file; return; } } template <typename Dtype> void PoseImageLoader<Dtype>::LoadAnnotation(const int image_num, cv::Mat* image, MetaData<Dtype>* meta) { const MetaData<Dtype>& annotation = annotations_[image_num]; const string& image_file = annotation.img_path; *image = cv::imread(image_file.c_str()); if (!image->data) { LOG(FATAL) << "Could not open or find image: " << image_file; return; } *meta = annotation; } template <typename Dtype> void PoseImageLoader<Dtype>::ShowImages() { for (int i = 0; i < annotations_.size(); ++i) { cv::Mat image; LoadImage(i, &image); cv::namedWindow("Imageshow", cv::WINDOW_AUTOSIZE); cv::imshow("Imageshow", image); cv::waitKey(0); } } template <typename Dtype> void PoseImageLoader<Dtype>::ShowAnnotations(const bool show_bbox) { for (int i = 0; i < annotations_.size(); ++i) { cv::Mat image; drawAnnotations(i, show_bbox, &image); cv::namedWindow("ImageShow", cv::WINDOW_AUTOSIZE); cv::imshow("ImageShow", image); cv::waitKey(0); } } template <typename Dtype> void PoseImageLoader<Dtype>::ShowAnnotationsRand(const bool show_bbox) { while (true) { const int image_num = rand() % annotations_.size(); cv::Mat image; drawAnnotations(image_num, show_bbox, &image); cv::namedWindow("ImageShow", cv::WINDOW_AUTOSIZE); cv::imshow("ImageShow", image); cv::waitKey(0); } } template <typename Dtype> void PoseImageLoader<Dtype>::Saving(const std::string& output_folder, const bool show_bbox) { for (int i = 0; i < annotations_.size(); ++i) { cv::Mat image; drawAnnotations(i, show_bbox, &image); // save int delim_pos = annotations_[i].img_path.find_last_of("/"); const string& file_name = annotations_[i].img_path.substr(delim_pos+1, annotations_[i].img_path.length()); const string& output_file = output_folder + "/" + file_name; LOG(INFO) << "saving image: " << file_name; imwrite(output_file, image); } } template <typename Dtype> void PoseImageLoader<Dtype>::merge_from(const PoseImageLoader<Dtype>* dst) { const std::vector<MetaData<Dtype> >& dst_annos = dst->get_annotations(); if (dst_annos.size() == 0) return; for (int i = 0; i < dst_annos.size(); ++i) { annotations_.push_back(dst_annos[i]); } LOG(INFO) << "Add " << dst_annos.size() << " Images."; } template <typename Dtype> void PoseImageLoader<Dtype>::drawAnnotations(const int image_num, const bool show_bbox, cv::Mat* dst_image) { cv::Mat image; MetaData<Dtype> meta; LoadAnnotation(image_num, &image, &meta); *dst_image = image.clone(); // 绘制 if (show_bbox) { // 绿色box drawbox(meta, dst_image); } // 红色关节点 drawkps(meta, dst_image); } template <typename Dtype> void PoseImageLoader<Dtype>::drawbox(const MetaData<Dtype>& meta, cv::Mat* image_out) { // bbox const BoundingBox<Dtype>& bbox = meta.bbox; bbox.Draw(0,255,0,image_out); // bbox of others for (int i = 0; i < meta.bbox_others.size(); ++i) { const BoundingBox<Dtype>& bbox_op = meta.bbox_others[i]; bbox_op.Draw(0,255,0,image_out); } } template <typename Dtype> void PoseImageLoader<Dtype>::drawkps(const MetaData<Dtype>& meta, cv::Mat* image_out) { const int num_kps = meta.joint_self.joints.size(); // draw self for(int i = 0; i < num_kps; i++) { if(meta.joint_self.isVisible[i] <= 1) circle(*image_out, meta.joint_self.joints[i], 5, CV_RGB(255,0,0), -1); } // joints of others for(int p = 0; p < meta.numOtherPeople; p++) { for(int i = 0; i < num_kps; i++) { if(meta.joint_others[p].isVisible[i] <= 1) circle(*image_out, meta.joint_others[p].joints[i], 5, CV_RGB(255,0,0), -1); } } } INSTANTIATE_CLASS(PoseImageLoader); }
31.172662
110
0.654512
UrwLee
63ef71aa6b436663e44687075426f3f3804724b4
3,567
cc
C++
Ohm/Netvars.cc
ramadan8/Ohm
fe9dbbdc40dc4c85a2cb2d033627673cd72ade39
[ "MIT" ]
1
2021-07-28T11:30:14.000Z
2021-07-28T11:30:14.000Z
Ohm/Netvars.cc
ramadan8/Ohm
fe9dbbdc40dc4c85a2cb2d033627673cd72ade39
[ "MIT" ]
1
2021-07-26T01:36:58.000Z
2021-07-27T14:45:21.000Z
Ohm/Netvars.cc
ramadan8/Ohm
fe9dbbdc40dc4c85a2cb2d033627673cd72ade39
[ "MIT" ]
1
2021-09-11T07:43:53.000Z
2021-09-11T07:43:53.000Z
#include <Windows.h> #include "./Netvars.h" #include "./Interfaces/Interfaces.h" #include "./SDK/Interfaces/IBaseClientDLL.h" intptr_t GetOffset(RecvTable* table, const char* tableName, const char* netvarName) { for (int i = 0; i < table->m_nProps; i++) { RecvProp prop = table->m_pProps[i]; if (!_stricmp(prop.m_pVarName, netvarName)) return prop.m_Offset; if (prop.m_pDataTable) { intptr_t offset = GetOffset(prop.m_pDataTable, tableName, netvarName); if (offset) return offset + prop.m_Offset; } } return 0; } intptr_t GetNetvarOffset(const char* tableName, const char* netvarName, IClientClass* clientClass) { IClientClass* currentNode = clientClass; for (auto currentNode = clientClass; currentNode; currentNode = currentNode->m_pNext) if (!_stricmp(tableName, currentNode->m_pRecvTable->m_pNetTableName)) return GetOffset(currentNode->m_pRecvTable, tableName, netvarName); return 0; } bool ClassIdentifiers::Initialize() { IClientClass* clientClass = interfaces->BaseClient->GetAllClasses(); IClientClass* currentNode = clientClass; int probableValidCount = 0; for (auto currentNode = clientClass; currentNode; currentNode = currentNode->m_pNext) { if (currentNode->m_ClassID > 0) ++probableValidCount; classIdentifiers[currentNode->m_pNetworkName] = currentNode->m_ClassID; } if (probableValidCount < 1) return false; CBaseAnimating = classIdentifiers["CBaseAnimating"]; CChicken = classIdentifiers["CChicken"]; CC4 = classIdentifiers["CC4"]; CCSPlayer = classIdentifiers["CCSPlayer"]; CPlantedC4 = classIdentifiers["CPlantedC4"]; FogController = classIdentifiers["FogController"]; return true; } Netvars::Netvars() { classIdentifiers = ClassIdentifiers(); clientClass = interfaces->BaseClient->GetAllClasses(); // DT_BaseCombatCharacter m_flNextAttack = GetNetvarOffset("DT_BaseCombatCharacter", "m_flNextAttack", clientClass); // DT_BaseCombatWeapon m_flNextPrimaryAttack = GetNetvarOffset("DT_BaseCombatWeapon", "m_flNextPrimaryAttack", clientClass); m_iClip = GetNetvarOffset("DT_BaseCombatWeapon", "m_iClip1", clientClass); // DT_BaseEntity m_hOwnerEntity = GetNetvarOffset("DT_BaseEntity", "m_hOwnerEntity", clientClass); m_rgflCoordinateFrame = GetNetvarOffset("DT_BaseEntity", "m_CollisionGroup", clientClass) - 0x30; // DT_BasePlayer m_Collision = GetNetvarOffset("DT_BasePlayer", "m_Collision", clientClass); m_fFlags = GetNetvarOffset("DT_BasePlayer", "m_fFlags", clientClass); m_iHealth = GetNetvarOffset("DT_BasePlayer", "m_iHealth", clientClass); m_iTeamNum = GetNetvarOffset("DT_BasePlayer", "m_iTeamNum", clientClass); m_nTickBase = GetNetvarOffset("DT_BasePlayer", "m_nTickBase", clientClass); m_vecOrigin = GetNetvarOffset("DT_BasePlayer", "m_vecOrigin", clientClass); // DT_CSPlayer m_ArmorValue = GetNetvarOffset("DT_CSPlayer", "m_ArmorValue", clientClass); m_bGunGameImmunity = GetNetvarOffset("DT_CSPlayer", "m_bGunGameImmunity", clientClass); m_bIsDefusing = GetNetvarOffset("DT_CSPlayer", "m_bIsDefusing", clientClass); m_bIsScoped = GetNetvarOffset("DT_CSPlayer", "m_bIsScoped", clientClass); m_flFlashMaxAlpha = GetNetvarOffset("DT_CSPlayer", "m_flFlashMaxAlpha", clientClass) - 8; m_lifeState = GetNetvarOffset("DT_CSPlayer", "m_lifeState", clientClass); // DT_DynamicProp m_bShouldGlow = GetNetvarOffset("DT_DynamicProp", "m_bShouldGlow", clientClass); // DT_PlantedC4 m_flC4Blow = GetNetvarOffset("DT_PlantedC4", "m_flC4Blow", clientClass); m_flTimerLength = GetNetvarOffset("DT_PlantedC4", "m_flTimerLength", clientClass); }
36.030303
102
0.769835
ramadan8
63f48dea33919d387ab94bf672a7cde06421b297
848
cxx
C++
PWG/HMTF/AliEventClassifierMPI.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWG/HMTF/AliEventClassifierMPI.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWG/HMTF/AliEventClassifierMPI.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
#include <vector> #include <iostream> #include "AliLog.h" #include "AliMCEvent.h" #include "AliStack.h" #include "AliGenPythiaEventHeader.h" #include "AliEventClassifierMPI.h" #include "AliIsPi0PhysicalPrimary.h" using namespace std; ClassImp(AliEventClassifierMPI) AliEventClassifierMPI::AliEventClassifierMPI(const char* name, const char* title, TList *taskOutputList) : AliEventClassifierBase(name, title, taskOutputList) { fExpectedMinValue = 0; fExpectedMaxValue = 250; } void AliEventClassifierMPI::CalculateClassifierValue(AliMCEvent *event, AliStack *stack) { fClassifierValue = 0.0; // If it is not a pythia header, this should fail AliGenPythiaEventHeader* header = dynamic_cast<AliGenPythiaEventHeader*>(event->GenEventHeader()); if(!header) { return; } else fClassifierValue = header->GetNMPI(); }
25.69697
100
0.760613
maroozm
63f6fa2c9f29c616e55147f84b272e01aedd2d6c
607
cpp
C++
DemoLib2/net/netmessages/NetSetPauseMessage.cpp
PazerOP/DemoLib2
7377f87654ce9bf6487d6b7ce7050cec8e76894e
[ "MIT" ]
14
2018-07-02T19:09:18.000Z
2022-01-12T12:35:43.000Z
DemoLib2/net/netmessages/NetSetPauseMessage.cpp
PazerOP/DemoLib2
7377f87654ce9bf6487d6b7ce7050cec8e76894e
[ "MIT" ]
1
2018-12-27T20:22:06.000Z
2020-01-04T03:27:31.000Z
DemoLib2/net/netmessages/NetSetPauseMessage.cpp
PazerOP/DemoLib2
7377f87654ce9bf6487d6b7ce7050cec8e76894e
[ "MIT" ]
1
2021-05-17T01:03:38.000Z
2021-05-17T01:03:38.000Z
#include "NetSetPauseMessage.hpp" #include "BitIO/BitIOReader.hpp" #include "BitIO/BitIOWriter.hpp" #include "net/worldstate/WorldState.hpp" void NetSetPauseMessage::GetDescription(std::ostream& description) const { description << "svc_SetPause: " << (m_Paused ? "paused" : "unpaused"); } void NetSetPauseMessage::ApplyWorldState(WorldState& world) const { world.m_Paused = m_Paused; } void NetSetPauseMessage::ReadElementInternal(BitIOReader& reader) { m_Paused = reader.ReadBit("is paused?"); } void NetSetPauseMessage::WriteElementInternal(BitIOWriter& writer) const { writer.Write(m_Paused); }
23.346154
72
0.771005
PazerOP
63fdac942da04b00c862c9de13d84239334be3d7
1,446
cpp
C++
avs_dx/DxVisuals/Threads/RenderThreadImpl.cpp
Const-me/vis_avs_dx
da1fd9f4323d7891dea233147e6ae16790ad9ada
[ "MIT" ]
33
2019-01-28T03:32:17.000Z
2022-02-12T18:17:26.000Z
avs_dx/DxVisuals/Threads/RenderThreadImpl.cpp
visbot/vis_avs_dx
03e55f8932a97ad845ff223d3602ff2300c3d1d4
[ "MIT" ]
2
2019-11-18T17:54:58.000Z
2020-07-21T18:11:21.000Z
avs_dx/DxVisuals/Threads/RenderThreadImpl.cpp
Const-me/vis_avs_dx
da1fd9f4323d7891dea233147e6ae16790ad9ada
[ "MIT" ]
5
2019-02-16T23:00:11.000Z
2022-03-27T15:22:10.000Z
#include "stdafx.h" #include "RenderThreadImpl.h" #include "AvsThreads.h" #include "effects.h" #include "Resources/staticResources.h" #include "Effects/Video/MF/mfStatic.h" #include "Render/Profiler.h" #include <Interop/deviceCreation.h> #include "Transition.h" RenderThreadImpl::RenderThreadImpl( winampVisModule * pModule ) : RenderThread( pModule ) { } RenderThreadImpl::~RenderThreadImpl() { logShutdown( "~RenderThreadImpl #1" ); // This will call the GUI thread to destroy rendering and profiler windows, so we can cleanup D3D device and associated resources. // Some resources, notably the video engine, have thread affinity, they must be released before MfShutdown() and CoUninitialize() calls. // Besides, we want to be sure the GUI thread will no longer present these frames, doing that after resources are released would prolly crash Winamp. RenderWindow::instance().shutdown(); logShutdown( "~RenderThreadImpl, #2" ); destroyAllEffects(); destroyTransitionInstance(); StaticResources::destroy(); mfShutdown(); gpuProfiler().shutdown(); destroyDevice(); comUninitialize(); logShutdown( "~RenderThreadImpl #3" ); } HRESULT RenderThreadImpl::initialize() { return RenderThread::startup(); } CSize getRenderSize(); HRESULT RenderThreadImpl::run() { while( !shouldQuit() ) { RenderThread::renderFrame(); const float fps = m_fps.update(); RenderThread::updateStats( getRenderSize(), fps ); } return S_OK; }
27.807692
150
0.750346
Const-me
63ff97d65ed29764176ac3d1376b2812f72af305
8,453
cpp
C++
Source/Lutefisk3D/Scene/ObjectAnimation.cpp
Lutefisk3D/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
2
2018-04-14T19:05:23.000Z
2020-05-10T22:42:12.000Z
Source/Lutefisk3D/Scene/ObjectAnimation.cpp
Lutefisk3D/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
4
2015-06-19T22:32:07.000Z
2017-04-05T06:01:50.000Z
Source/Lutefisk3D/Scene/ObjectAnimation.cpp
nemerle/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
1
2015-12-27T15:36:10.000Z
2015-12-27T15:36:10.000Z
// // Copyright (c) 2008-2017 the Urho3D project. // // 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 "ObjectAnimation.h" #include "Lutefisk3D/Core/Context.h" #include "SceneEvents.h" #include "ValueAnimation.h" #include "ValueAnimationInfo.h" #include "Lutefisk3D/Resource/XMLFile.h" #include "Lutefisk3D/Resource/JSONFile.h" namespace Urho3D { //instantiate the template template class LUTEFISK3D_EXPORT SharedPtr<ObjectAnimation>; const char* wrapModeNames[] = { "Loop", "Once", "Clamp", nullptr }; ObjectAnimation::ObjectAnimation(Context* context) : Resource(context) { } /// Register object factory. void ObjectAnimation::RegisterObject(Context* context) { context->RegisterFactory<ObjectAnimation>(); } /// Load resource from stream. May be called from a worker thread. Return true if successful. bool ObjectAnimation::BeginLoad(Deserializer& source) { XMLFile xmlFile(context_); if (!xmlFile.Load(source)) return false; return LoadXML(xmlFile.GetRoot()); } /// Save resource. Return true if successful. bool ObjectAnimation::Save(Serializer& dest) const { XMLFile xmlFile(context_); XMLElement rootElem = xmlFile.CreateRoot("objectanimation"); if (!SaveXML(rootElem)) return false; return xmlFile.Save(dest); } /// Load from XML data. Return true if successful. bool ObjectAnimation::LoadXML(const XMLElement& source) { attributeAnimationInfos_.clear(); XMLElement animElem; animElem = source.GetChild("attributeanimation"); while (animElem) { QString name = animElem.GetAttribute("name"); SharedPtr<ValueAnimation> animation(new ValueAnimation(context_)); if (!animation->LoadXML(animElem)) return false; QString wrapModeString = animElem.GetAttribute("wrapmode"); WrapMode wrapMode = WM_LOOP; for (int i = 0; i <= WM_CLAMP; ++i) { if (wrapModeString == wrapModeNames[i]) { wrapMode = (WrapMode)i; break; } } float speed = animElem.GetFloat("speed"); AddAttributeAnimation(name, animation, wrapMode, speed); animElem = animElem.GetNext("attributeanimation"); } return true; } /// Save as XML data. Return true if successful. bool ObjectAnimation::SaveXML(XMLElement& dest) const { for (auto elem=attributeAnimationInfos_.begin(),fin=attributeAnimationInfos_.end(); elem != fin; ++elem) { XMLElement animElem = dest.CreateChild("attributeanimation"); animElem.SetAttribute("name", MAP_KEY(elem)); const ValueAnimationInfo* info = MAP_VALUE(elem); if (!info->GetAnimation()->SaveXML(animElem)) return false; animElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]); animElem.SetFloat("speed", info->GetSpeed()); } return true; } /// Load from JSON data. Return true if successful. bool ObjectAnimation::LoadJSON(const JSONValue& source) { attributeAnimationInfos_.clear(); JSONValue attributeAnimationsValue = source.Get("attributeanimations"); if (attributeAnimationsValue.IsNull()) return true; if (!attributeAnimationsValue.IsObject()) return true; const JSONObject& attributeAnimationsObject = attributeAnimationsValue.GetObject(); for (const auto & ob : attributeAnimationsObject) { QString name = ELEMENT_KEY(ob); JSONValue value = ELEMENT_VALUE(ob); SharedPtr<ValueAnimation> animation(new ValueAnimation(context_)); if (!animation->LoadJSON(value)) return false; QString wrapModeString = value.Get("wrapmode").GetString(); WrapMode wrapMode = WM_LOOP; for (int i = 0; i <= WM_CLAMP; ++i) { if (wrapModeString == wrapModeNames[i]) { wrapMode = (WrapMode)i; break; } } float speed = value.Get("speed").GetFloat(); AddAttributeAnimation(name, animation, wrapMode, speed); } return true; } /// Save as JSON data. Return true if successful. bool ObjectAnimation::SaveJSON(JSONValue& dest) const { JSONValue attributeAnimationsValue; for (auto &elem : attributeAnimationInfos_) { JSONValue animValue; animValue.Set("name", ELEMENT_KEY(elem)); const ValueAnimationInfo* info = ELEMENT_VALUE(elem); if (!info->GetAnimation()->SaveJSON(animValue)) return false; animValue.Set("wrapmode", wrapModeNames[info->GetWrapMode()]); animValue.Set("speed", (float) info->GetSpeed()); attributeAnimationsValue.Set(ELEMENT_KEY(elem), animValue); } dest.Set("attributeanimations", attributeAnimationsValue); return true; } /// Add attribute animation, attribute name can in following format: "attribute" or "#0/#1/attribute" or ""#0/#1/@component#1/attribute. void ObjectAnimation::AddAttributeAnimation(const QString& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed) { if (attributeAnimation == nullptr) return; attributeAnimation->SetOwner(this); attributeAnimationInfos_[name] = new ValueAnimationInfo(attributeAnimation, wrapMode, speed); attributeAnimationAdded(this,name); } /// Remove attribute animation, attribute name can in following format: "attribute" or "#0/#1/attribute" or ""#0/#1/@component#1/attribute. void ObjectAnimation::RemoveAttributeAnimation(const QString& name) { HashMap<QString, SharedPtr<ValueAnimationInfo> >::iterator i = attributeAnimationInfos_.find(name); if (i != attributeAnimationInfos_.end()) { attributeAnimationRemoved(this,name); MAP_VALUE(i)->GetAnimation()->SetOwner(nullptr); attributeAnimationInfos_.erase(i); } } /// Remove attribute animation. void ObjectAnimation::RemoveAttributeAnimation(ValueAnimation* attributeAnimation) { if (attributeAnimation == nullptr) return; for (auto i = attributeAnimationInfos_.begin(); i != attributeAnimationInfos_.end(); ++i) { if (MAP_VALUE(i)->GetAnimation() == attributeAnimation) { attributeAnimationRemoved(this,MAP_KEY(i)); attributeAnimation->SetOwner(nullptr); attributeAnimationInfos_.erase(i); return; } } } /// Return attribute animation by name. ValueAnimation* ObjectAnimation::GetAttributeAnimation(const QString& name) const { ValueAnimationInfo* info = GetAttributeAnimationInfo(name); return info != nullptr ? info->GetAnimation() : nullptr; } /// Return attribute animation wrap mode by name. WrapMode ObjectAnimation::GetAttributeAnimationWrapMode(const QString& name) const { ValueAnimationInfo* info = GetAttributeAnimationInfo(name); return info != nullptr ? info->GetWrapMode() : WM_LOOP; } /// Return attribute animation speed by name. float ObjectAnimation::GetAttributeAnimationSpeed(const QString& name) const { ValueAnimationInfo* info = GetAttributeAnimationInfo(name); return info != nullptr ? info->GetSpeed() : 1.0f; } /// Return attribute animation info by name. ValueAnimationInfo* ObjectAnimation::GetAttributeAnimationInfo(const QString& name) const { auto i = attributeAnimationInfos_.find(name); if (i != attributeAnimationInfos_.end()) return MAP_VALUE(i); return nullptr; } }
33.543651
139
0.694428
Lutefisk3D
1201d06b481652931f5eaf2080b47e5a67662579
1,121
cpp
C++
codeforces/CF681/B_Saving_the_City.cpp
anandj123/gcpdemo
96ef4c64047b16f397369c71ace74daa7d43acec
[ "MIT" ]
null
null
null
codeforces/CF681/B_Saving_the_City.cpp
anandj123/gcpdemo
96ef4c64047b16f397369c71ace74daa7d43acec
[ "MIT" ]
null
null
null
codeforces/CF681/B_Saving_the_City.cpp
anandj123/gcpdemo
96ef4c64047b16f397369c71ace74daa7d43acec
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<vector> #include<algorithm> #include<cmath> #include<numeric> using namespace std; #define debug(x) cerr << #x << " : " << x << "\n" #define REP(i,a,b) for(int i=a; i<b;++i) #define endl "\n" typedef vector<int> vi; typedef vector< vector<int> > vvi; int INF = 1e9; void calculate(int a, int b, string s) { int len = s.length(); vector<int> dp1(len,0); vector<int> dp2(len,0); // debug(s); // debug(len); int first = a; REP(i,0,len){ //debug(dp1[i-1]); //debug(dp2[i-1]); if(s[i] == '1') { dp1[i] = min((i>0?dp1[i-1]:0) + a, (i>0?dp1[i-1]:0) + (i>0?dp2[i-1]:0)+first); dp2[i] = 0; first = 0; } else { dp1[i] = (i>0?dp1[i-1]:0); dp2[i] = (i>0?dp2[i-1]:0)+ b; } // debug(dp1[i]); // debug(dp2[i]); // debug(i); } cout << dp1[len-1] << endl; } int main() { int T; cin >> T; while(T-- > 0){ int a, b; string s; cin >> a >> b >> s; calculate(a,b,s); } }
20.381818
90
0.447814
anandj123
120399d65cfd059b7bfc2de6649deb58867c33f7
822
cpp
C++
src/libs/qlib/qdmbuffer.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdmbuffer.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdmbuffer.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * QDMBuffer - definition/implementation * NOTES: * - Tiny wrapper around DMbuffer concept * (C) 28-02-99 MarketGraph/RVG */ #include <qlib/dmbuffer.h> //#include <dmedia/dm_buffer.h> #include <dmedia/dm_params.h> #include <qlib/debug.h> DEBUG_ENABLE #define DMCHK(s,e)\ if((e)!=DM_SUCCESS)QShowDMErrors(s) //if((s)!=DM_SUCCESS)qerr("DM failure: %s",e) /** HELP **/ QDMBuffer::QDMBuffer(DMbuffer buf) { dmbuffer=buf; } QDMBuffer::~QDMBuffer() { } bool QDMBuffer::Attach() { QASSERT_F(dmbuffer); #ifndef WIN32 dmBufferAttach(dmbuffer); #endif return TRUE; } bool QDMBuffer::Free() { QASSERT_F(dmbuffer); #ifndef WIN32 dmBufferFree(dmbuffer); #endif return TRUE; } int QDMBuffer::GetSize() { QASSERT_0(dmbuffer); #ifdef WIN32 return 0; #else return dmBufferGetSize(dmbuffer); #endif }
14.678571
47
0.694647
3dhater
120569b970efd97f4310316d282266bc0dda77d1
22,816
cpp
C++
mp/src/game/server/coven_apc.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
mp/src/game/server/coven_apc.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
mp/src/game/server/coven_apc.cpp
rendenba/source-sdk-2013
4a0314391b01a2450788e0d4ee0926a05f3af8b0
[ "Unlicense" ]
null
null
null
#include "cbase.h" #include "vphysics/constraints.h" #include "coven_apc.h" #include "hl2mp_gamerules.h" #include "covenlib.h" extern ConVar coven_debug_visual; extern ConVar sv_coven_refuel_distance; Vector CCoven_APC::wheelOffset[] = { Vector(80, -50, -32), Vector(-72, -50, -32), Vector(80, 50, -32), Vector(-72, 50, -32) }; QAngle CCoven_APC::wheelOrientation[] = { QAngle(0, -90, 0), QAngle(0, -90, 0), QAngle(0, 90, 0), QAngle(0, 90, 0) }; int CCoven_APC::wheelDirection[] = { -1, -1, 1, 1 }; float CCoven_APC::m_flWheelDiameter = 64.6f; float CCoven_APC::m_flWheelRadius = CCoven_APC::m_flWheelDiameter / 2.0f; float CCoven_APC::m_flWheelBase = (CCoven_APC::wheelOffset[0] - CCoven_APC::wheelOffset[1]).Length2D(); float CCoven_APC::m_flWheelTrack = (CCoven_APC::wheelOffset[0] - CCoven_APC::wheelOffset[2]).Length2D(); LINK_ENTITY_TO_CLASS(coven_prop_physics, CCoven_APCProp); CCoven_APCProp::CCoven_APCProp() { m_pParent = NULL; } void CCoven_APCProp::Use(CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value) { if (m_pParent) { if (pActivator->IsPlayer()) { CHL2MP_Player *pHL2Player = ToHL2MPPlayer(pActivator); if (pHL2Player->HasStatus(COVEN_STATUS_HAS_GAS)) { if (pHL2Player->IsPerformingDeferredAction()) pHL2Player->CancelDeferredAction(); CovenItemInfo_t *info = GetCovenItemData(COVEN_ITEM_GASOLINE); pHL2Player->QueueDeferredAction(COVEN_ACTION_REFUEL, (info->iFlags & ITEM_FLAG_MOVEMENT_CANCEL) > 0, info->flUseTime, true, this, sv_coven_refuel_distance.GetFloat()); pHL2Player->EmitSound(info->aSounds[COVEN_SND_START]); } else pHL2Player->EmitSound("HL2Player.UseDeny"); } } } int CCoven_APCProp::ObjectCaps(void) { if (m_pParent) return BaseClass::ObjectCaps() | FCAP_IMPULSE_USE; return 0; } LINK_ENTITY_TO_CLASS(coven_apc, CCoven_APC); CCoven_APC::CCoven_APC() { Q_memset(m_pWheels, NULL, sizeof(m_pWheels)); m_pBody = NULL; m_bPlayingSound = m_bRunning = m_bPlayingSiren = false; m_angTurningAngle.Init(); m_flTurningAngle = 0.0f; m_iGoalNode = -1; m_iGoalCheckpoint = -1; m_flMaxSpeed = 0.0f; m_iFuel = m_iFuelUpAmount = 0; m_vecFrontAxelPosition.Init(); m_flSoundSwitch = m_flSoundSirenSwitch = 0.0f; m_hLeftLampGlow = NULL; m_hRightLampGlow = NULL; } void CCoven_APC::Precache(void) { PrecacheModel("models/props_junk/rock001a.mdl"); PrecacheModel(COVEN_APC_GLOW_SPRITE); PrecacheScriptSound("ATV_engine_start"); PrecacheScriptSound("ATV_engine_stop"); PrecacheScriptSound("ATV_engine_idle"); PrecacheScriptSound("TimerLow"); BaseClass::Precache(); } void CCoven_APC::Spawn(void) { Precache(); SetModel("models/props_junk/rock001a.mdl"); AddEffects(EF_NODRAW); SetSolid(SOLID_VPHYSICS); AddSolidFlags(FSOLID_NOT_SOLID); SetAbsOrigin(GetAbsOrigin() + Vector(0, 0, CCoven_APC::m_flWheelDiameter)); BaseClass::Spawn(); m_iHealth = 100; m_iFuel = 0; for (int i = 0; i < 4; i++) { m_pWheels[i] = CCoven_APCPart::CreateAPCPart(this, "models/props_vehicles/apc_tire001.mdl", CCoven_APC::wheelOffset[i], CCoven_APC::wheelOrientation[i], CCoven_APC::m_flWheelRadius, COLLISION_GROUP_VEHICLE_WHEEL); m_pWheels[i]->Spawn(); m_pWheels[i]->AttachPhysics(); m_pWheels[i]->MoveToCorrectLocation(); } m_pBody = CCoven_APCPart::CreateAPCPart(this, "models/props_vehicles/apc001.mdl", Vector(0, 0, 0), QAngle(0, -90, 0), CCoven_APC::m_flWheelRadius + 32, COLLISION_GROUP_VEHICLE, true); m_pBody->Spawn(); m_pBody->AttachPhysics(); m_pBody->MoveToCorrectLocation(); m_flSpeed = 0.0f; Activate(); SetThink(&CCoven_APC::MakeSolid); SetNextThink(gpGlobals->curtime + 0.1f); ToggleLights(false); ResetLocation(); MoveForward(); } void CCoven_APC::UpdateLightPosition(void) { Vector forward(0, 0, 0), right(0, 0, 0), up(0, 0, 0); QAngle angles = m_pBody->GetAbsAngles(); float roll = -angles.z; angles.z = -angles.x; angles.x = roll; angles -= m_pBody->GetOffsetAngle(); AngleVectors(angles, &forward, &right, &up); float size = random->RandomFloat(1.5f, 2.0f); int bright = size * 127; m_hLeftLampGlow->SetAbsOrigin(GetAbsOrigin() + 143.0f * forward + 42.0f * right + 21.0f * up); m_hLeftLampGlow->SetBrightness(bright, 0.1f); m_hLeftLampGlow->SetScale(size, 0.1f); m_hRightLampGlow->SetAbsOrigin(GetAbsOrigin() + 143.0f * forward - 42.0f * right + 21.0f * up); m_hRightLampGlow->SetScale(size, 0.1f); m_hRightLampGlow->SetBrightness(bright, 0.1f); } void CCoven_APC::ToggleLights(bool bToggle) { if (m_hLeftLampGlow == NULL) { m_hLeftLampGlow = CSprite::SpriteCreate(COVEN_APC_GLOW_SPRITE, GetLocalOrigin(), false); if (m_hLeftLampGlow) { m_hLeftLampGlow->SetTransparency(kRenderWorldGlow, 255, 255, 255, 128, kRenderFxNoDissipation); m_hLeftLampGlow->SetBrightness(0); } } if (m_hRightLampGlow == NULL) { m_hRightLampGlow = CSprite::SpriteCreate(COVEN_APC_GLOW_SPRITE, GetLocalOrigin(), false); if (m_hRightLampGlow) { m_hRightLampGlow->SetTransparency(kRenderWorldGlow, 255, 255, 255, 128, kRenderFxNoDissipation); m_hRightLampGlow->SetBrightness(0); } } if (bToggle) { m_hLeftLampGlow->SetColor(255, 255, 255); m_hRightLampGlow->SetColor(255, 255, 255); m_hLeftLampGlow->SetBrightness(180, 0.1f); m_hRightLampGlow->SetBrightness(180, 0.1f); m_hLeftLampGlow->SetScale(0.8f, 0.1f); m_hRightLampGlow->SetScale(0.8f, 0.1f); } else { m_hLeftLampGlow->SetColor(255, 255, 255); m_hRightLampGlow->SetColor(255, 255, 255); m_hLeftLampGlow->SetScale(0.1f, 0.1f); m_hRightLampGlow->SetScale(0.1f, 0.1f); m_hLeftLampGlow->SetBrightness(0, 0.1f); m_hRightLampGlow->SetBrightness(0, 0.1f); } } void CCoven_APC::MakeSolid(void) { for (int i = 0; i < 4; i++) { m_pWheels[i]->MakeSolid(); } m_pBody->MakeSolid(); SetThink(NULL); } void CCoven_APC::APCThink(void) { if (HasValidGoal() && HasReachedCurrentGoal()) { //Msg("Reached node: %d\n", m_iGoalNode); if (m_iGoalNode == m_iGoalCheckpoint) HL2MPRules()->ReachedCheckpoint(m_iGoalCheckpoint); m_iGoalNode++; if (m_iGoalNode >= HL2MPRules()->hAPCNet.Count()) { SetThink(NULL); return; } } if (m_iFuel > 0) { if (m_flSpeed < m_flMaxSpeed) m_flSpeed += m_flMaxSpeed / 6.0f; } SetNextThink(gpGlobals->curtime + 0.1f); if (HasValidGoal()) { if (coven_debug_visual.GetBool()) NDebugOverlay::Cross3D(HL2MPRules()->hAPCNet[m_iGoalNode]->location, -Vector(12, 12, 12), Vector(12, 12, 12), 0, 255, 0, false, 0.5f); Vector directionDifference = HL2MPRules()->hAPCNet[m_iGoalNode]->location - GetAbsOrigin(); QAngle ang(0, 0, 0), curAngles = GetAbsAngles(); VectorAngles(directionDifference, ang); float dir = AngleNormalize(curAngles.y - ang.y); if (dir < -1.0f) TurnLeft(dir); else if (dir > 1.0f) TurnRight(dir); else m_flTurningAngle = 0.0f; //Msg("%f %f - %f %f - %f - %f %f - %d\n", curAngles.y, ang.y, m_angTurningAngle.y, m_flTurningAngle, dir, m_flSpeed, m_flMaxSpeed, m_iFuel); } //Msg("%f %f - %f %f - %d\n", m_angTurningAngle.y, m_flTurningAngle, m_flSpeed, m_flMaxSpeed, m_iFuel); MoveForward(); if (m_bPlayingSiren && gpGlobals->curtime > m_flSoundSirenSwitch) { #ifdef WIN32 m_flSoundSirenSwitch = gpGlobals->curtime + GetSoundDuration("TimerLow", NULL); #else m_flSoundSirenSwitch = gpGlobals->curtime + 3.687438f; #endif StopSound("TimerLow"); EmitSound("TimerLow"); } if (m_bPlayingSound && gpGlobals->curtime > m_flSoundSwitch) { #ifdef WIN32 m_flSoundSwitch = gpGlobals->curtime + GetSoundDuration("ATV_engine_idle", NULL); #else m_flSoundSwitch = gpGlobals->curtime + 4.316735f; #endif StopSound("ATV_engine_start"); StopSound("ATV_engine_idle"); EmitSound("ATV_engine_idle"); } if (m_iFuel == 0) { if (m_bPlayingSound) { StopSound("ATV_engine_start"); StopSound("ATV_engine_idle"); EmitSound("ATV_engine_stop"); m_bPlayingSound = m_bRunning = false; ToggleLights(false); } if (m_flSpeed > 0.0f) m_flSpeed -= m_flMaxSpeed / 14.0f; else { m_flSpeed = 0.0f; SetThink(NULL); } } else m_iFuel--; } void CCoven_APC::UpdateOnRemove(void) { if (m_hLeftLampGlow != NULL) { UTIL_Remove(m_hLeftLampGlow); m_hLeftLampGlow = NULL; } if (m_hRightLampGlow != NULL) { UTIL_Remove(m_hRightLampGlow); m_hRightLampGlow = NULL; } BaseClass::UpdateOnRemove(); } bool CCoven_APC::HasValidGoal(void) { return m_iGoalNode < HL2MPRules()->hAPCNet.Count() && m_iGoalNode >= 0; } bool CCoven_APC::HasReachedCurrentGoal(void) { return (GetAbsOrigin() - HL2MPRules()->hAPCNet[m_iGoalNode]->location).Length2D() < 24.0f; } void CCoven_APC::SetGoal(int iGoalNode) { m_iGoalNode = iGoalNode; } void CCoven_APC::SetCheckpoint(int iGoalCheckpoint) { m_iGoalCheckpoint = iGoalCheckpoint; } void CCoven_APC::SetMaxSpeed(float flMaxSpeed) { m_flMaxSpeed = flMaxSpeed; } void CCoven_APC::SetFuelUp(int iFuelUp) { m_iFuelUpAmount = iFuelUp; } void CCoven_APC::StartSiren(void) { if (!m_bPlayingSiren) { m_bPlayingSiren = true; EmitSound("TimerLow"); #ifdef WIN32 m_flSoundSirenSwitch = gpGlobals->curtime + GetSoundDuration("TimerLow", NULL); #else m_flSoundSirenSwitch = gpGlobals->curtime + 3.687438f; #endif } } void CCoven_APC::StopSiren(void) { if (m_bPlayingSiren) { m_bPlayingSiren = false; StopSound("TimerLow"); m_flSoundSirenSwitch = 0.0f; } } const Vector &CCoven_APC::GetFrontAxelPosition(void) { if (gpGlobals->tickcount != m_vecTick) { m_vecTick = gpGlobals->tickcount; Vector forward(0, 0, 0); AngleVectors(GetAbsAngles(), &forward); m_vecFrontAxelPosition = GetAbsOrigin() + forward * CCoven_APC::wheelOffset[FRONT_PASSENGER].x; } return m_vecFrontAxelPosition; } //flMagnitude is negative void CCoven_APC::TurnLeft(float flMagnitude) { if (m_angTurningAngle.y > -COVEN_APC_MAX_TURNING_VALUE && m_angTurningAngle.y > flMagnitude) { if (m_angTurningAngle.y < -1.0f || m_angTurningAngle.y > 0.0f) m_flTurningAngle = max(m_flTurningAngle - 1.0f, -COVEN_APC_MAX_TURN_ACCEL); else m_flTurningAngle = -1.0f; m_angTurningAngle.y += m_flTurningAngle; } else m_flTurningAngle = 0.0f; } //flMagnitude is positive void CCoven_APC::TurnRight(float flMagnitude) { if (m_angTurningAngle.y < COVEN_APC_MAX_TURNING_VALUE && m_angTurningAngle.y < flMagnitude) { if (m_angTurningAngle.y > 1.0f || m_angTurningAngle.y < 0.0f) m_flTurningAngle = min(m_flTurningAngle + 1.0f, COVEN_APC_MAX_TURN_ACCEL); else m_flTurningAngle = 1.0f; m_angTurningAngle.y += m_flTurningAngle; } else m_flTurningAngle = 0.0f; } void CCoven_APC::MoveForward(void) { WheelLocation_t lowestWheel = FRONT_PASSENGER; WheelLocation_t highestWheel = FRONT_PASSENGER; Vector vecFloorPosition[4]; Vector vecDesiredPosition[5]; QAngle angDesiredAngles[5]; if (m_angTurningAngle.y == 0.0f) { Vector forward; AngleVectors(GetAbsAngles(), &forward); for (int i = 0; i < 4; i++) { vecDesiredPosition[i] = m_pWheels[i]->GetAbsOrigin() + forward * m_flSpeed; float roll = GetAbsAngles().z; angDesiredAngles[i] = m_pWheels[i]->GetAbsAngles(); angDesiredAngles[i].x = 0; angDesiredAngles[i] += QAngle(roll * CCoven_APC::wheelDirection[i], 0, WheelDegreesTraveled(m_flSpeed) * CCoven_APC::wheelDirection[i]); } angDesiredAngles[4] = GetAbsAngles(); vecDesiredPosition[4] = GetAbsOrigin() + forward * m_flSpeed; } else { float alpha = m_angTurningAngle.y; //Right turn WheelLocation_t steeringWheel = FRONT_PASSENGER; float direction = 1.0f; //Left turn if (alpha < 0.0f) { direction = -1.0f; steeringWheel = FRONT_DRIVER; } //float r = CCoven_APC::m_flWheelBase / tan(M_PI * alpha / 180.0f); //rear wheel radius float R = CCoven_APC::m_flWheelBase / sin(M_PI * alpha / 180.0f); //front wheel radius float beata = -m_flSpeed / R; //radians QAngle angleToCenter = m_pWheels[steeringWheel]->GetAbsAngles(); angleToCenter.x = angleToCenter.z = 0; Vector dirToCenter(0, 0, 0); AngleVectors(angleToCenter, &dirToCenter); Vector O = m_pWheels[steeringWheel]->GetAbsOrigin() - CCoven_APC::wheelDirection[steeringWheel] * R * dirToCenter; //Msg("%f %f %f %f\n", beata, R, (m_pWheels[0]->GetAbsOrigin() - m_pWheels[2]->GetAbsOrigin()).Length2D(), m_pWheels[0]->GetAbsAngles().y - m_pWheels[2]->GetAbsAngles().y); for (int i = 0; i < 4; i++) { vecDesiredPosition[i] = m_pWheels[i]->GetAbsOrigin(); VectorRotate2DPoint(m_pWheels[i]->GetAbsOrigin(), O, beata, &vecDesiredPosition[i], true); QAngle oldAng = m_pWheels[i]->GetAbsAngles(); Vector newDir; newDir = direction * CCoven_APC::wheelDirection[i] * (vecDesiredPosition[i] - O); angDesiredAngles[i].Init(); VectorAngles(newDir, angDesiredAngles[i]); float roll = GetAbsAngles().z; //float pitch = GetAbsAngles().x; angDesiredAngles[i].z = oldAng.z; if (i == steeringWheel) angDesiredAngles[i].y -= m_flTurningAngle; angDesiredAngles[i] += QAngle(roll * CCoven_APC::wheelDirection[i], 0, WheelDegreesTraveled(m_flSpeed) * CCoven_APC::wheelDirection[i]); } if (coven_debug_visual.GetBool()) NDebugOverlay::Cross3D(O, -Vector(12, 12, 12), Vector(12, 12, 12), 0, 0, 255, true, 1.0f); Vector dir(0, 0, 0), newDir(0, 0, 0); VectorRotate2DPoint(m_pBody->GetAbsOrigin(), O, beata, &vecDesiredPosition[4], true); AngleVectors(GetAbsAngles(), &dir); VectorRotate2D(dir, beata, &newDir, true); VectorAngles(newDir, angDesiredAngles[4]); angDesiredAngles[4].x = AngleNormalize(angDesiredAngles[4].x); angDesiredAngles[4].y = AngleNormalize(angDesiredAngles[4].y); //Msg("DEBUG: %f %f %f\n", dir.z, newDir.z, beata); } for (int i = 0; i < 4; i++) { trace_t tr; //BB: TODO: we need to trace a hull here! UTIL_TraceLine(vecDesiredPosition[i], vecDesiredPosition[i] + Vector(0, 0, -500), MASK_ALL, m_pWheels[i]->GetProp(), COLLISION_GROUP_WEAPON, &tr); if (tr.DidHit()) vecFloorPosition[i] = tr.endpos; else vecFloorPosition[i].Init(); if (vecFloorPosition[i].z < vecFloorPosition[lowestWheel].z) lowestWheel = (WheelLocation_t)i; if (vecFloorPosition[i].z > vecFloorPosition[highestWheel].z) highestWheel = (WheelLocation_t)i; } if (lowestWheel != highestWheel) { //Pitch = highest point of highest direction - lowest point of other direction float highest = vecDesiredPosition[highestWheel].z; float lowestP = vecDesiredPosition[CCoven_APC::AdjacentWheel(highestWheel)].z; float pitchRadians = atan((highest - lowestP) / CCoven_APC::m_flWheelBase); if (highestWheel == FRONT_DRIVER || highestWheel == FRONT_PASSENGER) pitchRadians = -pitchRadians; //Roll = highest point of highest side - lowest point of other side. float lowestR = vecDesiredPosition[CCoven_APC::OppositeWheel(highestWheel)].z; float rollRadians = atan((highest - lowestR) / CCoven_APC::m_flWheelTrack); if (highestWheel >= FRONT_DRIVER) rollRadians = -rollRadians; angDesiredAngles[4].x = AngleNormalize(pitchRadians * 180.0f / M_PI); angDesiredAngles[4].z = AngleNormalize(rollRadians * 180.0f / M_PI); WheelLocation_t oppositeWheel = CCoven_APC::AdjacentWheel(CCoven_APC::OppositeWheel(highestWheel)); vecDesiredPosition[oppositeWheel].z = vecDesiredPosition[highestWheel].z - lowestP - lowestR; //NDebugOverlay::Cross3D(vecDesiredPosition[highestWheel], -Vector(12, 12, 12), Vector(12, 12, 12), 255, 0, 0, false, 0.5f); //NDebugOverlay::Cross3D(vecDesiredPosition[lowestWheel], -Vector(12, 12, 12), Vector(12, 12, 12), 0, 255, 0, false, 0.5f); } //Msg("APC Pitch: %f\n", angDesiredAngles[4].x); for (int i = 0; i < 4; i++) { vecDesiredPosition[i].z = vecFloorPosition[i].z + m_pWheels[i]->RestHeight(); m_pWheels[i]->MoveTo(&vecDesiredPosition[i], &angDesiredAngles[i]); } float midZ = vecDesiredPosition[lowestWheel].z + (vecDesiredPosition[highestWheel].z - vecDesiredPosition[lowestWheel].z) / 2.0f + CCoven_APC::m_flWheelRadius; vecDesiredPosition[4].z = midZ; SetAbsAngles(angDesiredAngles[4]); SetAbsOrigin(vecDesiredPosition[4]); float roll = -angDesiredAngles[4].z; angDesiredAngles[4].z = -angDesiredAngles[4].x + random->RandomFloat(-0.5f, 0.5f); angDesiredAngles[4].x = roll + random->RandomFloat(-0.5f, 0.5f); angDesiredAngles[4] += m_pBody->GetOffsetAngle(); m_pBody->MoveTo(&vecDesiredPosition[4], &angDesiredAngles[4]); //Msg("Body Pitch: %f\n", angDesiredAngles[4].x); if (m_bRunning) UpdateLightPosition(); } bool CCoven_APC::IsRunning(void) { return m_bRunning || m_flSpeed > 0.0f; } void CCoven_APC::ResetLocation(void) { for (int i = 0; i < 4; i++) { QAngle ang = GetAbsAngles(); float roll = ang.z; //float pitch = ang.x; ang.x = ang.z = 0; if (i == FRONT_DRIVER || i == FRONT_PASSENGER) ang += m_angTurningAngle; ang += m_pWheels[i]->GetOffsetAngle() + QAngle(roll * CCoven_APC::wheelDirection[i], 0, m_pWheels[i]->GetAbsAngles().z + WheelDegreesTraveled(m_flSpeed) * CCoven_APC::wheelDirection[i]); Vector vec = GetAbsOrigin() + CCoven_APC::wheelOffset[i]; Vector rotated = vec; VectorRotate2DPoint(vec, GetAbsOrigin(), GetAbsAngles().y, &rotated); m_pWheels[i]->MoveTo(&rotated, &ang); } Vector bodyLocation = GetAbsOrigin(); QAngle bodyAngles = GetAbsAngles() + QAngle(0, -90, 0); m_pBody->MoveTo(&bodyLocation, &bodyAngles); } void CCoven_APC::StartUp(void) { if (!m_bRunning) { if (!m_bPlayingSound) { m_bPlayingSound = true; EmitSound("ATV_engine_start"); //BB: GetSoundDuration does not appear to work for Linux SRCDS! Linux will need a hardcoded timestamp! FIX THIS THROUGHOUT THIS FILE! #ifdef WIN32 m_flSoundSwitch = gpGlobals->curtime + GetSoundDuration("ATV_engine_Start", NULL); #else m_flSoundSwitch = gpGlobals->curtime + 6.151132f; #endif SetThink(&CCoven_APC::APCThink); SetNextThink(gpGlobals->curtime + 0.2f); } m_bRunning = true; ToggleLights(true); } m_iFuel += m_iFuelUpAmount; } int CCoven_APC::CurrentGoal(void) { return m_iGoalNode; } int CCoven_APC::CurrentCheckpoint(void) { return m_iGoalCheckpoint; } WheelLocation_t CCoven_APC::OppositeWheel(WheelLocation_t wheel) { if (wheel > REAR_PASSENGER) return (WheelLocation_t)(wheel - 2); return (WheelLocation_t)(wheel + 2); } WheelLocation_t CCoven_APC::AdjacentWheel(WheelLocation_t wheel) { if (wheel == FRONT_PASSENGER) return REAR_PASSENGER; if (wheel == REAR_PASSENGER) return FRONT_PASSENGER; if (wheel == FRONT_DRIVER) return REAR_DRIVER; return FRONT_DRIVER; } LINK_ENTITY_TO_CLASS(coven_apc_part, CCoven_APCPart); CCoven_APCPart::CCoven_APCPart() { m_pConstraint = NULL; m_hAPC = NULL; m_vecOffset.Init(); m_angOffset.Init(); m_flRestHeight = 0.0f; } CCoven_APCPart::~CCoven_APCPart() { if (m_pConstraint) { physenv->DestroyConstraint(m_pConstraint); m_pConstraint = NULL; } } CCoven_APCPart *CCoven_APCPart::CreateAPCPart(CCoven_APC *pParentAPC, char *szModelName, const Vector &vecOffset, const QAngle &angOffset, float flRestHeight, Collision_Group_t collisionGroup, bool bMakeUsable) { CCoven_APCPart *pPart = (CCoven_APCPart *)CBaseEntity::Create("coven_apc_part", pParentAPC->GetAbsOrigin(), pParentAPC->GetAbsAngles()); if (!pPart) return NULL; pPart->m_hAPC = pParentAPC; pPart->m_vecOffset = vecOffset; pPart->m_angOffset = angOffset; pPart->m_flRestHeight = flRestHeight; pPart->m_pPart = dynamic_cast< CCoven_APCProp * >(CreateEntityByName("coven_prop_physics")); if (pPart->m_pPart) { Vector location = pParentAPC->GetAbsOrigin(); QAngle orientation = pParentAPC->GetAbsAngles(); char buf[512]; // Pass in standard key values Q_snprintf(buf, sizeof(buf), "%.10f %.10f %.10f", location.x, location.y, location.z); pPart->m_pPart->KeyValue("origin", buf); Q_snprintf(buf, sizeof(buf), "%.10f %.10f %.10f", orientation.x, orientation.y, orientation.z); pPart->m_pPart->KeyValue("angles", buf); pPart->m_pPart->KeyValue("model", szModelName); pPart->m_pPart->KeyValue("fademindist", "-1"); pPart->m_pPart->KeyValue("fademaxdist", "0"); pPart->m_pPart->KeyValue("fadescale", "1"); pPart->m_pPart->KeyValue("inertiaScale", "1.0"); pPart->m_pPart->KeyValue("physdamagescale", "0.1"); pPart->m_pPart->Precache(); pPart->m_pPart->SetCollisionGroup(collisionGroup); pPart->m_pPart->Spawn(); pPart->m_pPart->Activate(); pPart->m_pPart->AddSolidFlags(FSOLID_NOT_SOLID); } if (bMakeUsable) pPart->m_pPart->m_pParent = pPart; pPart->AddSolidFlags(FSOLID_NOT_SOLID); // Disable movement on the root, we'll move this thing manually. pPart->VPhysicsInitShadow(false, false); pPart->SetMoveType(MOVETYPE_NONE); return pPart; } void CCoven_APCPart::MakeSolid(void) { m_pPart->RemoveSolidFlags(FSOLID_NOT_SOLID); } Vector CCoven_APCPart::GetOffsetPosition(void) { Vector offset = m_vecOffset; if (m_vecOffset != vec3_origin) { float sine = 0.0f; float cosine = 0.0f; SinCos(m_hAPC->GetAbsAngles().y / 180.0f * M_PI, &sine, &cosine); offset.x = cosine * m_vecOffset.x - sine * m_vecOffset.y; offset.y = sine * m_vecOffset.x + cosine * m_vecOffset.y; } return offset; } QAngle CCoven_APCPart::GetOffsetAngle(void) { return m_angOffset; } float CCoven_APCPart::RestHeight(void) { return m_flRestHeight; } void CCoven_APCPart::MoveTo(const Vector *vec, const QAngle *ang) { if (vec != NULL) SetAbsOrigin(*vec); if (ang != NULL) SetAbsAngles(*ang); if (vec != NULL || ang != NULL) UpdatePhysicsShadowToCurrentPosition(0.1f); } void CCoven_APCPart::UpdatePosition(void) { if (m_hAPC != NULL) { SetAbsOrigin(m_hAPC->GetAbsOrigin() + GetOffsetPosition()); UpdatePhysicsShadowToCurrentPosition(0.1f); } } void CCoven_APCPart::Spawn(void) { Precache(); SetModel("models/props_junk/rock001a.mdl"); AddEffects(EF_NODRAW); SetSolid(SOLID_VPHYSICS); AddSolidFlags(FSOLID_NOT_SOLID); BaseClass::Spawn(); } void CCoven_APCPart::Precache(void) { PrecacheModel("models/props_junk/rock001a.mdl"); BaseClass::Precache(); } void CCoven_APCPart::DropToFloor(void) { trace_t tr; UTIL_TraceLine(GetAbsOrigin(), GetAbsOrigin() + Vector(0, 0, -500), MASK_ALL, m_pPart, COLLISION_GROUP_PLAYER, &tr); if (tr.DidHit()) { SetAbsOrigin(tr.endpos + Vector(0, 0, m_flRestHeight)); } } void CCoven_APCPart::MoveToCorrectLocation(void) { if (m_hAPC != NULL) { Vector location = m_hAPC->GetAbsOrigin() + GetOffsetPosition(); QAngle angles = m_hAPC->GetAbsAngles() + m_angOffset; Teleport(&location, &angles, NULL); UpdatePhysicsShadowToCurrentPosition(0); } } void CCoven_APCPart::AttachPhysics(void) { if (!m_pConstraint) { IPhysicsObject *pPartPhys = m_pPart->VPhysicsGetObject(); IPhysicsObject *pShadowPhys = VPhysicsGetObject(); constraint_fixedparams_t fixed; fixed.Defaults(); fixed.InitWithCurrentObjectState(pShadowPhys, pPartPhys); fixed.constraint.Defaults(); m_pConstraint = physenv->CreateFixedConstraint(pShadowPhys, pPartPhys, NULL, fixed); } }
28.627353
215
0.720678
rendenba
1205ece7c57ad787c5c14ffb91a7cecf8190cb6f
2,612
hpp
C++
include/Nazara/Graphics/UberShader.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Graphics/UberShader.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Graphics/UberShader.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_GRAPHICS_UBERSHADER_HPP #define NAZARA_GRAPHICS_UBERSHADER_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Algorithm.hpp> #include <Nazara/Core/Bitset.hpp> #include <Nazara/Core/Signal.hpp> #include <Nazara/Graphics/Config.hpp> #include <Nazara/Renderer/RenderPipeline.hpp> #include <Nazara/Shader/ShaderModuleResolver.hpp> #include <Nazara/Shader/Ast/Module.hpp> #include <unordered_map> namespace Nz { class ShaderModule; class NAZARA_GRAPHICS_API UberShader { public: struct Config; struct Option; using ConfigCallback = std::function<void(Config& config, const std::vector<RenderPipelineInfo::VertexBufferData>& vertexBuffers)>; UberShader(ShaderStageTypeFlags shaderStages, std::string moduleName); UberShader(ShaderStageTypeFlags shaderStages, ShaderModuleResolver& moduleResolver, std::string moduleName); UberShader(ShaderStageTypeFlags shaderStages, ShaderAst::ModulePtr shaderModule); ~UberShader() = default; inline ShaderStageTypeFlags GetSupportedStages() const; const std::shared_ptr<ShaderModule>& Get(const Config& config); inline bool HasOption(const std::string& optionName, Pointer<const Option>* option = nullptr) const; inline void UpdateConfig(Config& config, const std::vector<RenderPipelineInfo::VertexBufferData>& vertexBuffers); inline void UpdateConfigCallback(ConfigCallback callback); struct Config { std::unordered_map<UInt32, ShaderAst::ConstantValue> optionValues; }; struct ConfigEqual { inline bool operator()(const Config& lhs, const Config& rhs) const; }; struct ConfigHasher { inline std::size_t operator()(const Config& config) const; }; struct Option { UInt32 hash; }; NazaraSignal(OnShaderUpdated, UberShader* /*uberShader*/); private: ShaderAst::ModulePtr Validate(const ShaderAst::Module& module, std::unordered_map<std::string, Option>* options); NazaraSlot(ShaderModuleResolver, OnModuleUpdated, m_onShaderModuleUpdated); std::unordered_map<Config, std::shared_ptr<ShaderModule>, ConfigHasher, ConfigEqual> m_combinations; std::unordered_map<std::string, Option> m_optionIndexByName; ShaderAst::ModulePtr m_shaderModule; ConfigCallback m_configCallback; ShaderStageTypeFlags m_shaderStages; }; } #include <Nazara/Graphics/UberShader.inl> #endif // NAZARA_GRAPHICS_UBERSHADER_HPP
31.46988
134
0.769525
jayrulez
1209463f60ad0473a1d6a2ec3e539fa200001bd5
876
cpp
C++
dos/dos_memmgr_test.cpp
wwiv/door86c
bfdc6408bf632da74a1e58d97da3257d715f3f6e
[ "Apache-2.0" ]
1
2021-11-04T03:13:25.000Z
2021-11-04T03:13:25.000Z
dos/dos_memmgr_test.cpp
wwiv/door86c
bfdc6408bf632da74a1e58d97da3257d715f3f6e
[ "Apache-2.0" ]
null
null
null
dos/dos_memmgr_test.cpp
wwiv/door86c
bfdc6408bf632da74a1e58d97da3257d715f3f6e
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include "cpu/memory.h" #include "dos/dos.h" #include <cstdlib> #include <cstdint> #include <iostream> using namespace door86::cpu; using namespace door86::dos; class DosMemMgrTest : public testing::Test { public: DosMemMgrTest() : mm(&m, 0x1000, 0x7000) {} Memory m{1 << 20}; DosMemoryManager mm; }; TEST_F(DosMemMgrTest, Smoke) { ASSERT_EQ(1, mm.blocks().size()); const auto o = mm.allocate(0x2000); ASSERT_TRUE(o.has_value()); ASSERT_EQ(0x1000, o.value()); const auto o2 = mm.allocate(0x5001); ASSERT_FALSE(o2.has_value()); } TEST_F(DosMemMgrTest, Tail) { mm.strategy(DosMemoryManager::fit_strategy_t::last); ASSERT_EQ(1, mm.blocks().size()); const auto o = mm.allocate(0x2000); ASSERT_TRUE(o.has_value()); ASSERT_EQ(0x5000, o.value()); const auto o2 = mm.allocate(0x5001); ASSERT_FALSE(o2.has_value()); }
21.365854
54
0.691781
wwiv
120eda04e422f7779e3386c663df16e8326e5f43
5,843
cpp
C++
third_party/SimpleBluez/examples/pair/pair.cpp
Andrey1994/brainflow
6b776859fba6a629b1acd471ae5d1320bffe9ca5
[ "MIT" ]
53
2018-12-11T13:35:47.000Z
2020-04-21T00:08:13.000Z
third_party/SimpleBluez/examples/pair/pair.cpp
Andrey1994/brainflow
6b776859fba6a629b1acd471ae5d1320bffe9ca5
[ "MIT" ]
14
2019-06-12T05:22:27.000Z
2020-04-20T19:14:44.000Z
examples/pair/pair.cpp
OpenBluetoothToolbox/SimpleBluez
aece6ec75732b216f0f68144f4fe42c6190d0a65
[ "MIT" ]
9
2019-04-13T19:03:16.000Z
2020-04-07T16:42:20.000Z
#include <simplebluez/Bluez.h> #include <simplebluez/Exceptions.h> #include <atomic> #include <chrono> #include <cstdlib> #include <iomanip> #include <iostream> #include <thread> SimpleBluez::Bluez bluez; std::atomic_bool async_thread_active = true; void async_thread_function() { while (async_thread_active) { bluez.run_async(); std::this_thread::sleep_for(std::chrono::microseconds(100)); } } void millisecond_delay(int ms) { for (int i = 0; i < ms; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } std::vector<std::shared_ptr<SimpleBluez::Device>> peripherals; int main(int argc, char* argv[]) { int selection = -1; bluez.init(); std::thread* async_thread = new std::thread(async_thread_function); auto agent = bluez.get_agent(); agent->set_capabilities(SimpleBluez::Agent::Capabilities::KeyboardDisplay); // Configure all callback handlers for the agent, as part of this example. agent->set_on_request_pin_code([&]() { std::cout << "Agent::RequestPinCode" << std::endl; return "123456"; }); agent->set_on_display_pin_code([&](const std::string& pin_code) { std::cout << "Agent::DisplayPinCode: " << pin_code << std::endl; return true; }); agent->set_on_request_passkey([&]() { std::cout << "Agent::RequestPasskey" << std::endl; return 123456; }); agent->set_on_display_passkey([&](uint32_t passkey, uint16_t entered) { std::cout << "Agent::DisplayPasskey: " << passkey << " (" << entered << " entered)" << std::endl; }); agent->set_on_request_confirmation([&](uint32_t passkey) { std::cout << "Agent::RequestConfirmation: " << passkey << std::endl; return true; }); agent->set_on_request_authorization([&]() { std::cout << "Agent::RequestAuthorization" << std::endl; return true; }); agent->set_on_authorize_service([&](const std::string& uuid) { std::cout << "Agent::AuthorizeService: " << uuid << std::endl; return true; }); bluez.register_agent(); auto adapters = bluez.get_adapters(); std::cout << "Available adapters:" << std::endl; for (int i = 0; i < adapters.size(); i++) { std::cout << "[" << i << "] " << adapters[i]->identifier() << " [" << adapters[i]->address() << "]" << std::endl; } std::cout << "Please select an adapter to scan: "; std::cin >> selection; if (selection < 0 || selection >= adapters.size()) { std::cout << "Invalid selection" << std::endl; return 1; } auto adapter = adapters[selection]; std::cout << "Scanning " << adapter->identifier() << " [" << adapter->address() << "]" << std::endl; adapter->discovery_filter(SimpleBluez::Adapter::DiscoveryFilter::LE); adapter->set_on_device_updated([](std::shared_ptr<SimpleBluez::Device> device) { if (std::find(peripherals.begin(), peripherals.end(), device) == peripherals.end()) { std::cout << "Found device: " << device->name() << " [" << device->address() << "]" << std::endl; peripherals.push_back(device); } }); adapter->discovery_start(); millisecond_delay(3000); adapter->discovery_stop(); std::cout << "The following devices were found:" << std::endl; for (int i = 0; i < peripherals.size(); i++) { std::cout << "[" << i << "] " << peripherals[i]->name() << " [" << peripherals[i]->address() << "]" << std::endl; } std::cout << "Please select a device to pair to: "; std::cin >> selection; if (selection >= 0 && selection < peripherals.size()) { auto peripheral = peripherals[selection]; std::cout << "Pairing to " << peripheral->name() << " [" << peripheral->address() << "]" << std::endl; for (int attempt = 0; attempt < 3; attempt++) { try { peripheral->connect(); // At this point, the connection will be established, // but services might not be resolved yet for (int i = 0; i < 10; i++) { std::cout << "Waiting for services to resolve..." << std::endl; millisecond_delay(100); if (peripheral->services_resolved()) { break; } } if (peripheral->connected() && peripheral->services_resolved()) { break; } } catch (SimpleDBus::Exception::SendFailed& e) { millisecond_delay(100); } } if (!peripheral->connected() || !peripheral->services_resolved()) { std::cout << "Failed to connect to " << peripheral->name() << " [" << peripheral->address() << "]" << std::endl; return 1; } std::cout << "Successfully connected, listing services." << std::endl; for (auto service : peripheral->services()) { std::cout << "Service: " << service->uuid() << std::endl; for (auto characteristic : service->characteristics()) { std::cout << " Characteristic: " << characteristic->uuid() << std::endl; } } millisecond_delay(2000); peripheral->disconnect(); if (peripheral->paired()) { adapter->device_remove(peripheral->path()); } // Sleep for an additional second before returning. // If there are any unexpected events, this example will help debug them. millisecond_delay(1000); } async_thread_active = false; while (!async_thread->joinable()) { millisecond_delay(10); } async_thread->join(); delete async_thread; return 0; }
33.011299
110
0.556906
Andrey1994
1211f6335d41fc83efb6404e4b78a6d0da338d77
6,636
hpp
C++
c++17_features.hpp
ralphtandetzky/cpp_utils
3adfed125db6fccd7478385544b96ceecdf435e7
[ "MIT" ]
3
2018-01-04T18:07:32.000Z
2021-09-01T14:19:43.000Z
c++17_features.hpp
ralphtandetzky/cpp_utils
3adfed125db6fccd7478385544b96ceecdf435e7
[ "MIT" ]
null
null
null
c++17_features.hpp
ralphtandetzky/cpp_utils
3adfed125db6fccd7478385544b96ceecdf435e7
[ "MIT" ]
null
null
null
/** @file This file defines features available from C++17 onwards. * * The features are defined in the cu namespace instead of the std namespace. * When moving to C++17 just remove this header from the project, * in order to keep you project clean. This should require only a bit of * refactoring by replacing the respective @c cu:: by @c std::. * * @author Ralph Tandetzky */ #pragma once #include <cstddef> #include <type_traits> #include <utility> #ifdef __has_include // Check if __has_include is present # if __has_include(<optional>) // Check for a standard library # include <optional> # elif __has_include(<experimental/optional>) // Check for an experimental version # include <experimental/optional> # elif __has_include(<boost/optional.hpp>) // Try with an external library # include <boost/optional.hpp> # else // Not found at all # error "Missing <optional>" # endif #else # error "Compiler does not support __has_include" #endif namespace cu { //using std::experimental::optional; // #include <optional> // // std::optional<T> #if __has_include(<optional>) // Check for a standard library using std::optional; using std::nullopt; #elif __has_include(<experimental/optional>) // Check for an experimental version using std::experimental::optional; using std::experimental::nullopt; #elif __has_include(<boost/optional.hpp>) // Try with an external library using boost::optional; using boost::nullopt; #endif // #include <iterator> // // std::size() template <typename Container> constexpr auto size( const Container& container ) -> decltype(container.size()) { return container.size(); } template <typename T, std::size_t N> constexpr std::size_t size( const T (&)[N] ) noexcept { return N; } // #include <functional> // // std::invoke() namespace detail { template <typename T> struct is_reference_wrapper : std::false_type {}; template <typename U> struct is_reference_wrapper<std::reference_wrapper<U>> : std::true_type {}; template <typename Base, typename T, typename Derived, typename... Args> auto INVOKE(T Base::*pmf, Derived&& ref, Args&&... args) noexcept(noexcept((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))) -> typename std::enable_if<std::is_function<T>::value && std::is_base_of<Base, typename std::decay<Derived>::type>::value, decltype((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))>::type { return (std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...); } template <typename Base, typename T, typename RefWrap, typename... Args> auto INVOKE(T Base::*pmf, RefWrap&& ref, Args&&... args) noexcept(noexcept((ref.get().*pmf)(std::forward<Args>(args)...))) -> typename std::enable_if<std::is_function<T>::value && is_reference_wrapper<typename std::decay<RefWrap>::type>::value, decltype((ref.get().*pmf)(std::forward<Args>(args)...))>::type { return (ref.get().*pmf)(std::forward<Args>(args)...); } template <typename Base, typename T, typename Pointer, typename... Args> auto INVOKE(T Base::*pmf, Pointer&& ptr, Args&&... args) noexcept(noexcept(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))) -> typename std::enable_if<std::is_function<T>::value && !is_reference_wrapper<typename std::decay<Pointer>::type>::value && !std::is_base_of<Base, typename std::decay<Pointer>::type>::value, decltype(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))>::type { return ((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...); } template <typename Base, typename T, typename Derived> auto INVOKE(T Base::*pmd, Derived&& ref) noexcept(noexcept(std::forward<Derived>(ref).*pmd)) -> typename std::enable_if<!std::is_function<T>::value && std::is_base_of<Base, typename std::decay<Derived>::type>::value, decltype(std::forward<Derived>(ref).*pmd)>::type { return std::forward<Derived>(ref).*pmd; } template <typename Base, typename T, typename RefWrap> auto INVOKE(T Base::*pmd, RefWrap&& ref) noexcept(noexcept(ref.get().*pmd)) -> typename std::enable_if<!std::is_function<T>::value && is_reference_wrapper<typename std::decay<RefWrap>::type>::value, decltype(ref.get().*pmd)>::type { return ref.get().*pmd; } template <typename Base, typename T, typename Pointer> auto INVOKE(T Base::*pmd, Pointer&& ptr) noexcept(noexcept((*std::forward<Pointer>(ptr)).*pmd)) -> typename std::enable_if<!std::is_function<T>::value && !is_reference_wrapper<typename std::decay<Pointer>::type>::value && !std::is_base_of<Base, typename std::decay<Pointer>::type>::value, decltype((*std::forward<Pointer>(ptr)).*pmd)>::type { return (*std::forward<Pointer>(ptr)).*pmd; } template <typename F, typename... Args> auto INVOKE(F&& f, Args&&... args) noexcept(noexcept(std::forward<F>(f)(std::forward<Args>(args)...))) -> typename std::enable_if<!std::is_member_pointer<typename std::decay<F>::type>::value, decltype(std::forward<F>(f)(std::forward<Args>(args)...))>::type { return std::forward<F>(f)(std::forward<Args>(args)...); } } // namespace detail template< typename F, typename... ArgTypes > auto invoke(F&& f, ArgTypes&&... args) // exception specification for QoI noexcept(noexcept(detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...))) -> decltype(detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...)) { return detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...); } // #include <tuple> // // std::apply() #ifdef I #define CU_OLD_I_DEF I #undef I #endif namespace detail { template <typename F, typename Tuple, std::size_t... I> constexpr decltype(auto) apply_impl( F&& f, Tuple&& t, std::index_sequence<I...> ) { return cu::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...); } } // namespace detail #ifdef CU_OLD_I_DEF #define I CU_OLD_I_DEF #undef CU_OLD_I_DEF #endif template <typename F, typename Tuple> constexpr decltype(auto) apply(F&& f, Tuple&& t) { return detail::apply_impl(std::forward<F>(f), std::forward<Tuple>(t), std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>{}>{}); } } // namespace cu
35.111111
97
0.639693
ralphtandetzky
12127b43dcec8286e422ffa955176069b384e3b2
6,439
cpp
C++
Code/EnginePlugins/UltralightPlugin/Resources/Implementation/UltralightHTMLResource.cpp
asheraryam/ezEngine
bfe6d109b72d8fd6f13d043b11980796625c648e
[ "MIT" ]
null
null
null
Code/EnginePlugins/UltralightPlugin/Resources/Implementation/UltralightHTMLResource.cpp
asheraryam/ezEngine
bfe6d109b72d8fd6f13d043b11980796625c648e
[ "MIT" ]
null
null
null
Code/EnginePlugins/UltralightPlugin/Resources/Implementation/UltralightHTMLResource.cpp
asheraryam/ezEngine
bfe6d109b72d8fd6f13d043b11980796625c648e
[ "MIT" ]
null
null
null
#include <PCH.h> #include <Core/Assets/AssetFileHeader.h> #include <RendererFoundation/Device/Device.h> #include <RendererFoundation/Resources/Texture.h> #include <RendererCore/Textures/TextureUtils.h> #include <UltralightPlugin/Integration/GPUDriverEz.h> #include <UltralightPlugin/Integration/UltralightResourceManager.h> #include <UltralightPlugin/Resources/UltralightHTMLResource.h> #include <Ultralight/Ultralight.h> EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezUltralightHTMLResource, 1, ezRTTIDefaultAllocator<ezUltralightHTMLResource>) EZ_END_DYNAMIC_REFLECTED_TYPE; ezUltralightHTMLResource::ezUltralightHTMLResource() : ezTexture2DResource(DoUpdate::OnMainThread) { } ezUltralightHTMLResource::~ezUltralightHTMLResource() { ezUltralightResourceManager::GetInstance()->Unregister(this); } void ezUltralightHTMLResource::OnBeginLoading(ultralight::View* caller) {} void ezUltralightHTMLResource::OnFinishLoading(ultralight::View* caller) {} void ezUltralightHTMLResource::OnUpdateHistory(ultralight::View* caller) {} void ezUltralightHTMLResource::OnDOMReady(ultralight::View* caller) {} void ezUltralightHTMLResource::OnChangeTitle(ultralight::View* caller, const ultralight::String& title) {} void ezUltralightHTMLResource::OnChangeURL(ultralight::View* caller, const ultralight::String& url) {} void ezUltralightHTMLResource::OnChangeTooltip(ultralight::View* caller, const ultralight::String& tooltip) {} void ezUltralightHTMLResource::OnChangeCursor(ultralight::View* caller, ultralight::Cursor cursor) {} void ezUltralightHTMLResource::OnAddConsoleMessage(ultralight::View* caller, ultralight::MessageSource source, ultralight::MessageLevel level, const ultralight::String& message, uint32_t line_number, uint32_t column_number, const ultralight::String& source_id) { } ultralight::View* ezUltralightHTMLResource::GetView() { EZ_ASSERT_DEV(ezThreadUtils::IsMainThread(), "Ultralight operations need to happen on the mainthread"); return m_View.get(); } void ezUltralightHTMLResource::CreateView(ultralight::Renderer* pRenderer) { EZ_ASSERT_DEV(ezThreadUtils::IsMainThread(), "Ultralight operations need to happen on the mainthread"); m_View = pRenderer->CreateView(m_Descriptor.m_uiWidth, m_Descriptor.m_uiHeight, m_Descriptor.m_bTransparentBackground); m_View->set_load_listener(this); m_View->set_view_listener(this); if (!m_Descriptor.m_sHTMLContent.IsEmpty()) { m_View->LoadHTML(m_Descriptor.m_sHTMLContent.GetData()); } else if (!m_Descriptor.m_sHTMLFileName.IsEmpty()) { ezStringBuilder FileUrl("file:///", m_Descriptor.m_sHTMLFileName); m_View->LoadURL(FileUrl.GetData()); } auto renderTarget = m_View->render_target(); m_UVCoords = renderTarget.uv_coords; m_hGALTexture[m_uiLoadedTextures] = static_cast<ezUltralightGPUDriver*>(ultralight::Platform::instance().gpu_driver())->GetTextureHandleForTextureId(renderTarget.texture_id); } void ezUltralightHTMLResource::DestroyView() { EZ_ASSERT_DEV(ezThreadUtils::IsMainThread(), "Ultralight operations need to happen on the mainthread"); m_View = nullptr; } void ezUltralightHTMLResource::SetTextureHandle(ezGALTextureHandle hTextureHandle) { m_hGALTexture[0] = hTextureHandle; if (m_View) { m_UVCoords = m_View->render_target().uv_coords; } } EZ_RESOURCE_IMPLEMENT_COMMON_CODE(ezUltralightHTMLResource); EZ_RESOURCE_IMPLEMENT_CREATEABLE(ezUltralightHTMLResource, ezUltralightHTMLResourceDescriptor) { ezResourceLoadDesc ret; ret.m_uiQualityLevelsDiscardable = 0; ret.m_uiQualityLevelsLoadable = 0; ret.m_State = ezResourceState::Loaded; ezGALDevice* pDevice = ezGALDevice::GetDefaultDevice(); if (!ezUltralightResourceManager::GetInstance()->IsRegistered(this)) { ezUltralightResourceManager::GetInstance()->Register(this); } else { ezUltralightResourceManager::GetInstance()->UpdateResource(this); } m_uiLoadedTextures++; if (!m_hSamplerState.IsInvalidated()) { pDevice->DestroySamplerState(m_hSamplerState); } ezGALSamplerStateCreationDescription SamplerDesc; m_hSamplerState = pDevice->CreateSamplerState(SamplerDesc); EZ_ASSERT_DEV(!m_hSamplerState.IsInvalidated(), "Sampler state error"); m_Type = ezGALTextureType::Texture2D; m_Format = ezGALResourceFormat::BGRAUByteNormalized; m_uiWidth = descriptor.m_uiWidth; m_uiHeight = descriptor.m_uiHeight; m_Descriptor = std::move(descriptor); return ret; } ezResourceLoadDesc ezUltralightHTMLResource::UnloadData(Unload WhatToUnload) { ezResourceLoadDesc res; res.m_uiQualityLevelsDiscardable = 0; res.m_uiQualityLevelsLoadable = 1; res.m_State = ezResourceState::Unloaded; return res; } ezResourceLoadDesc ezUltralightHTMLResource::UpdateContent(ezStreamReader* Stream) { EZ_LOG_BLOCK("ezUltralightHTMLResource::UpdateContent", GetResourceDescription().GetData()); ezResourceLoadDesc res; res.m_uiQualityLevelsDiscardable = 0; res.m_uiQualityLevelsLoadable = 0; if (Stream == nullptr) { res.m_State = ezResourceState::LoadedResourceMissing; return res; } // skip the absolute file path data that the standard file reader writes into the stream { ezString sAbsFilePath; (*Stream) >> sAbsFilePath; } // skip the asset file header at the start of the file ezAssetFileHeader AssetHash; AssetHash.Read(*Stream); ezUltralightHTMLResourceDescriptor desc; desc.Load(*Stream); m_uiLoadedTextures = 0; CreateResource(std::move(desc)); res.m_State = ezResourceState::Loaded; return res; } void ezUltralightHTMLResource::UpdateMemoryUsage(MemoryUsage& out_NewMemoryUsage) { out_NewMemoryUsage.m_uiMemoryGPU = 0; out_NewMemoryUsage.m_uiMemoryCPU = 0; // TODO } void ezUltralightHTMLResourceDescriptor::Save(ezStreamWriter& stream) const { const ezUInt8 uiVersion = 1; stream << uiVersion; stream << m_sHTMLContent; stream << m_sHTMLFileName; stream << m_uiWidth; stream << m_uiHeight; stream << m_bTransparentBackground; } void ezUltralightHTMLResourceDescriptor::Load(ezStreamReader& stream) { ezUInt8 uiVersion = 0; stream >> uiVersion; EZ_ASSERT_DEV(uiVersion == 1, "Invalid ultralight HTML descriptor version {0}", uiVersion); stream >> m_sHTMLContent; stream >> m_sHTMLFileName; stream >> m_uiWidth; stream >> m_uiHeight; stream >> m_bTransparentBackground; } EZ_STATICLINK_FILE(UltralightPlugin, UltralightPlugin_Resources_UltralightHTMLResource);
28.617778
142
0.78537
asheraryam
1213c97231770ea12c77544d88451128874db7a0
2,274
hpp
C++
src/Include/process_result_facedetect.hpp
Xilinx/nlp-smartvision
e028b93b5fa964510dce1ddb9ae3dc28a15628d4
[ "Apache-2.0" ]
3
2021-05-20T13:49:07.000Z
2021-05-21T02:44:36.000Z
src/Include/process_result_facedetect.hpp
Xilinx/nlp-smartvision
e028b93b5fa964510dce1ddb9ae3dc28a15628d4
[ "Apache-2.0" ]
null
null
null
src/Include/process_result_facedetect.hpp
Xilinx/nlp-smartvision
e028b93b5fa964510dce1ddb9ae3dc28a15628d4
[ "Apache-2.0" ]
2
2021-05-21T10:59:13.000Z
2021-08-24T10:48:54.000Z
/* * Copyright 2021 Xilinx 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 <iostream> #include <opencv2/opencv.hpp> #include <string> #include <glog/logging.h> void process_result_facedetect(cv::Mat *m1, const vitis::ai::FaceDetectResult &result, bool is_jpeg, long int time, int thickness, bool left, bool right, int green, int blue, int red) { for (const auto &r : result.rects) { LOG_IF(INFO, is_jpeg) << " " << r.score << " " // << r.x << " " // << r.y << " " // << r.width << " " // << r.height; if (left==false && right==false){ cv::rectangle((*m1), cv::Rect{cv::Point(r.x * m1->cols, r.y * m1->rows), cv::Size{(int)(r.width * m1->cols), (int)(r.height * m1->rows)}}, cv::Scalar (blue,green,red), thickness); } else if((r.x + (r.width/2)) <= 0.5 and left==true){ cv::rectangle((*m1), cv::Rect{cv::Point(r.x * m1->cols, r.y * m1->rows), cv::Size{(int)(r.width * m1->cols), (int)(r.height * m1->rows)}}, cv::Scalar (blue,green,red), thickness); } else if((r.x + (r.width/2)) > 0.5 and right==true){ cv::rectangle((*m1), cv::Rect{cv::Point(r.x * m1->cols, r.y * m1->rows), cv::Size{(int)(r.width * m1->cols), (int)(r.height * m1->rows)}}, cv::Scalar (blue,green,red), thickness); } } return; }
39.206897
122
0.493404
Xilinx
1213e79b24fde59bab9ba2136fa2cd41bb928072
1,599
cpp
C++
sscanf/src/tests/test_group_specifiers.cpp
dzoj/ultra_balkan_alpha-master.github.io
f2c1835f2ad2a97436197956de62ef3a43ef7dff
[ "MIT" ]
null
null
null
sscanf/src/tests/test_group_specifiers.cpp
dzoj/ultra_balkan_alpha-master.github.io
f2c1835f2ad2a97436197956de62ef3a43ef7dff
[ "MIT" ]
null
null
null
sscanf/src/tests/test_group_specifiers.cpp
dzoj/ultra_balkan_alpha-master.github.io
f2c1835f2ad2a97436197956de62ef3a43ef7dff
[ "MIT" ]
null
null
null
#include "../specifiers/group_specifiers.h" TEST(AltGroup1, { AltGroup gg; return gg.ReadToken(S"(ii|dd)") == OK && *CUR == '\0'; }) TEST(AltGroup2, { AltGroup gg; gg.ReadToken(S"(ii|xh)");ss s; return dynamic_cast<ss &>(s << gg).str() == "(ii|xh)"; }) TEST(AltGroup4, { AltGroup gg; if (gg.ReadToken(S"(ii|dd|cc|xx)") != OK) return false; int i = 0; for (auto b = gg.Begin(), e = gg.End(); b != e; ++b) ++i; return i == 4 && gg.CountChildren() == 4; }) TEST(AltGroup5, { AltGroup gg; if (gg.ReadToken(S"(ii|dd|cc|xx|dd|dd|dd)") != OK) return false; int i = 0; for (auto b = gg.Begin(), e = gg.End(); b != e; ++b) { ++i; if ((*b)->CountChildren() != 2) return false; } return i == 7 && gg.CountChildren() == 7; }) TEST(AltGroup6, { AltGroup gg; if (gg.ReadToken(S"(ii)") != OK) return false; int i = 0; for (auto b = gg.Begin(), e = gg.End(); b != e; ++b) ++i; return i == 1 && gg.CountChildren() == 1; }) TEST(GlobGroup1, { AltGroup gg(false); return gg.ReadToken(S"ii|dd") == OK && *CUR == '\0'; }) TEST(GlobGroup2, { AltGroup gg(false); return gg.ReadToken(S"ii|") == ERROR_NO_CHILDREN; }) TEST(GlobGroup3, { AltGroup gg(false); return gg.ReadToken(S"|dd") == ERROR_NO_CHILDREN; }) TEST(GlobGroup6, { AltGroup gg(false); return gg.ReadToken(S"I(5)") == OK; }) TEST(GlobGroup7, { AltGroup gg(false); return gg.ReadToken(S"I(q)") == ERROR_NAN; }) TEST(GlobGroup4, { AltGroup gg(false); return gg.ReadToken(S"ii|D(5)|cc| H(11)n") == OK && *CUR == '\0'; }) TEST(GlobGroup5, { AltGroup gg(false); gg.ReadToken(S"ii|xh");ss s; return dynamic_cast<ss &>(s << gg).str() == "ii|xh"; })
79.95
164
0.600375
dzoj
12144c8bab5bae8239524d585bc9c5cc617608ab
639
cpp
C++
day26/day26.cpp
offonrynk/30_days_of_code
6b6e4ce05e07a3065fc9db2fff7dc62ac81a7289
[ "MIT" ]
null
null
null
day26/day26.cpp
offonrynk/30_days_of_code
6b6e4ce05e07a3065fc9db2fff7dc62ac81a7289
[ "MIT" ]
null
null
null
day26/day26.cpp
offonrynk/30_days_of_code
6b6e4ce05e07a3065fc9db2fff7dc62ac81a7289
[ "MIT" ]
null
null
null
#include <iostream> int main() { int day, month, year; std::cin >> day >> month >> year; int dayExpected, monthExpected, yearExpected; std::cin >> dayExpected >> monthExpected >> yearExpected; int fine = 0; if (year > yearExpected) { fine = 10000; } else if (year == yearExpected) { if (month > monthExpected) { fine = 500 * (month - monthExpected); } else if ((month == monthExpected) && (day > dayExpected)) { fine = 15 * (day - dayExpected); } else if ((month == monthExpected) && (day == dayExpected)) { fine = 0; } } std::cout << fine << std::endl; return 0; }
20.612903
64
0.56964
offonrynk
12151e08bf4ed73e3b693e21e4ca4b2a2d2fbce6
487
hpp
C++
src/constants.hpp
yhamdoud/engine
0e1e589be4eb3b50ac21f0d166a2c76f576fdeb7
[ "MIT" ]
4
2021-08-29T09:34:22.000Z
2022-01-27T00:24:52.000Z
src/constants.hpp
yhamdoud/engine
0e1e589be4eb3b50ac21f0d166a2c76f576fdeb7
[ "MIT" ]
null
null
null
src/constants.hpp
yhamdoud/engine
0e1e589be4eb3b50ac21f0d166a2c76f576fdeb7
[ "MIT" ]
null
null
null
#pragma once #include <filesystem> namespace engine { using uint = unsigned int; const uint invalid_texture_id = 0; const uint invalid_shader_id = 0; const uint default_frame_buffer_id = 0; const std::filesystem::path resources_path{"../resources"}; const std::filesystem::path textures_path{resources_path / "textures"}; const std::filesystem::path shaders_path{resources_path / "shaders"}; const std::filesystem::path models_path{resources_path / "models"}; } // namespace engine
25.631579
71
0.770021
yhamdoud
1217063959e302507e8e8889380d1a42b69592ab
1,845
cpp
C++
Codeforces/932F.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
UESTC/2394.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
UESTC/2394.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <bits/stdc++.h> #define MAXN 100005 using namespace std; const int Z=1e5; struct Line { long long k,b;int x; Line(){} Line(long long _,long long __,int ___): k(_),b(__),x(___){} long long getY(int x) { return k*x+b; } }tr[MAXN<<2]; int ls[MAXN<<2],rs[MAXN<<2],rt[MAXN],tot; int n,u,v,a[MAXN],b[MAXN],pool[MAXN],top; long long f[MAXN]; vector <int> g[MAXN]; inline int newnode() { if (top) return pool[top--]; return ++tot; } inline void delnode(int &x) { pool[++top]=x;ls[x]=rs[x]=0;tr[x]=Line(0,0,0);x=0; return ; } inline void insert(int &x,int l,int r,Line p) { if (!x){tr[x=newnode()]=p;return ;} if (p.getY(l)<=tr[x].getY(l)&&p.getY(r)<=tr[x].getY(r)) { tr[x]=p;return ; } if (p.getY(l)>=tr[x].getY(l)&&p.getY(r)>=tr[x].getY(r)) return ; int m=l+r>>1; if (p.getY(m)<tr[x].getY(m)) swap(p,tr[x]); insert(ls[x],l,m,p);insert(rs[x],m+1,r,p); return ; } inline int merge(int x,int y,int l,int r) { if (!x||!y) return x+y; int m=l+r>>1; ls[x]=merge(ls[x],ls[y],l,m); rs[x]=merge(rs[x],rs[y],m+1,r); insert(x,l,r,tr[y]);delnode(y); return x; } Line query(int u,int l,int r,int x) { if (l==r) return tr[u];int m=l+r>>1; Line k; if (x<=m) k=query(ls[u],l,m,x); else k=query(rs[u],m+1,r,x); return ((!k.x)||(k.getY(x)>tr[u].getY(x)))?tr[u]:k; } inline void TreeDP(int x,int fa) { for (auto v:g[x]) if (v!=fa) { TreeDP(v,x); rt[x]=merge(rt[x],rt[v],0,Z<<1); } int v=query(rt[x],0,Z<<1,a[x]+Z).x; f[x]=f[v]+1LL*b[v]*a[x]; insert(rt[x],0,Z<<1,Line(b[x],f[x]-1LL*b[x]*Z,x)); return ; } int main() { scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&a[i]); for (int i=1;i<=n;i++) scanf("%d",&b[i]); for (int i=1;i<n;i++) { scanf("%d %d",&u,&v); g[u].push_back(v);g[v].push_back(u); } TreeDP(1,-1); for (int i=1;i<=n;i++) printf("%lld%c",f[i],i==n?'\n':' '); return 0; }
19.421053
65
0.547425
HeRaNO
121b7e8b1b6fcbfc5a8b1f76d56796ba6082586e
5,295
cpp
C++
test/geometry/polygon.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
null
null
null
test/geometry/polygon.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
1
2019-08-24T17:31:50.000Z
2019-08-24T17:31:50.000Z
test/geometry/polygon.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <vector> #include "gtest/gtest.h" #include "geometry/polygon.hpp" #include "geometry/layout.hpp" using std::vector; using Eigen::Vector2d; using terrain::geometry::Polygon; using terrain::geometry::Layout; namespace terrain::geometry { TEST(PolygonTest, DefaultConfiguration) { const Polygon shape; const auto& points = shape.points; ASSERT_TRUE(points[0].isApprox(Vector2d(0,0))); ASSERT_TRUE(points[1].isApprox(Vector2d(1,0))); ASSERT_TRUE(points[2].isApprox(Vector2d(1,1))); ASSERT_TRUE(points[3].isApprox(Vector2d(0,1))); } TEST(PolygonTest, LoadList_5Point) { // Note: this polygen is configured as CW: // it will be enclosed, and reversed, internally Polygon shape( {{ 3, 4}, { 5,11}, {12, 8}, { 9, 5}, { 5, 6}}); // DEBUG // shape.write_yaml(std::cerr, " "); ASSERT_EQ( shape[0], Vector2d( 3, 4)); ASSERT_EQ( shape[1], Vector2d( 5, 6)); ASSERT_EQ( shape[2], Vector2d( 9, 5)); ASSERT_EQ( shape[3], Vector2d( 12, 8)); ASSERT_EQ( shape[4], Vector2d( 5, 11)); ASSERT_EQ( shape[5], Vector2d( 3, 4)); } TEST(PolygonTest, LoadList_DiamondRhombus) { Polygon shape({{1,0},{0,1},{-1,0},{0,-1}}); // // DEBUG // shape.write_yaml(std::cerr, " "); ASSERT_EQ( shape[0], Vector2d(1,0) ); ASSERT_EQ( shape[1], Vector2d(0,1) ); ASSERT_EQ( shape[2], Vector2d(-1,0) ); ASSERT_EQ( shape[3], Vector2d(0,-1) ); ASSERT_EQ( shape[4], Vector2d(1,0) ); } TEST(PolygonTest, MakeLayout) { Polygon bounds; Polygon shape( {{ 5, 6}, { 9, 5}, {12, 8}, { 5,11}, { 3, 4}, { 5, 6}} ); const double precision = 0.5; const Layout& layout = shape.make_layout(precision); // ====== ====== Preconditions ====== ====== EXPECT_DOUBLE_EQ(layout.get_precision(), 1.0); EXPECT_DOUBLE_EQ(layout.get_x(), 8); EXPECT_DOUBLE_EQ(layout.get_y(), 8); EXPECT_DOUBLE_EQ(layout.get_width(), 16); EXPECT_EQ(layout.get_dimension(), 16); EXPECT_EQ(layout.get_size(), 256); EXPECT_FALSE( layout.contains({ -1., -1.}) ); EXPECT_FALSE( layout.contains({ -2., -2.}) ); EXPECT_EQ( layout.rhash(0.1, 0.1), 0); EXPECT_EQ( layout.rhash(1.1, 0.1), 1); EXPECT_EQ( layout.rhash(0.1, 1.1), 16); EXPECT_EQ( layout.rhash(1.1, 1.1), 17); ASSERT_EQ( layout.rhash(2., 0.), 2); ASSERT_EQ( layout.rhash(3., 0.), 3); ASSERT_EQ( layout.rhash(2., 1.), 18); ASSERT_EQ( layout.rhash(3., 1.), 19); } // TEST(PolygonTest, InBoundingBoxByX) { // BoundaryPolygon bounds; // bounds.setParam("margin", "20."); // bounds.setParam("priority_function", "linear"); // bounds.setParam("points", "-200,-200: 200,-200: 200,200: -200,200"); // // ====== ====== Preconditions ====== ====== // ASSERT_DOUBLE_EQ(bounds.min.x, -200); // ASSERT_DOUBLE_EQ(bounds.max.x, 200); // ASSERT_DOUBLE_EQ(bounds.min.y, -200); // ASSERT_DOUBLE_EQ(bounds.max.y, 200); // ASSERT_DOUBLE_EQ(bounds.margin, 20); // ASSERT_DOUBLE_EQ(bounds.center[0], 0); // ASSERT_DOUBLE_EQ(bounds.center[1], 0); // ASSERT_TRUE(bounds.is_convex); // // ====== ====== Graphics Message Output ====== ====== // const string& poly2 = bounds.getBoundaryPolygonGraphics(true,"aqua"); // const string exp2("label=Boundary,active=true,pts={-200,-200:200,-200:200,200:-200,200:-200,-200},edge_color=aqua"); // ASSERT_EQ(poly2, exp2); // vector<TestPoint> test_cases; // test_cases.emplace_back( -205, 0, 1.00, 90); // test_cases.emplace_back( -201, 0, 1.00, 90); // test_cases.emplace_back( -200, 0, 1.00, 90); // test_cases.emplace_back( -199, 0, 0, 0); // test_cases.emplace_back( -190, 0, 0, 0); // test_cases.emplace_back( -181, 0, 0, 0); // test_cases.emplace_back( -180, 0, 0, 0); // test_cases.emplace_back( -179, 0, 0, 0); // test_cases.emplace_back( 0, 0, 0, 0); // test_cases.emplace_back( 179, 0, 0, 0); // test_cases.emplace_back( 180, 0, 0, 0); // test_cases.emplace_back( 181, 0, 0, 0); // test_cases.emplace_back( 190, 0, 0, 0); // test_cases.emplace_back( 199, 0, 0, 0); // test_cases.emplace_back( 200, 0, 1.00, 270); // test_cases.emplace_back( 201, 0, 1.00, 270); // // ===================================== // for( uint i=0; i < test_cases.size(); i++){ // const TestPoint& expect = test_cases[i]; // const PolarVector2D& actual = bounds.getHeadingDesiredBoundingBox(expect.x,expect.y); // ostringstream buf; // buf << "@@ x=" << expect.x << " y=" << expect.y; // buf << " => " << actual.magnitude << " \u2220 "<< actual.heading <<"\u00b0"; // const string& case_descriptor = buf.str(); // ASSERT_NEAR(actual.magnitude, expect.magnitude, 0.01) << case_descriptor; // ASSERT_NEAR(actual.heading, expect.heading, 0.1) << case_descriptor; // } // } }; // namespace terrain::geometry
33.942308
123
0.560151
teyrana
121cbbb6e03bb86fed80ba5a41b54a54985621eb
377
cpp
C++
1. Alokasi dan Representasi/14 Program Alokasi Dinamis/PTR4.cpp
zharmedia386/Data-Structures-and-Algorithms
316a7f4836cf77a4c150d4ee6a48b8d94db6518e
[ "MIT" ]
2
2021-06-21T16:33:26.000Z
2022-03-13T04:59:43.000Z
1. Alokasi dan Representasi/14 Program Alokasi Dinamis/PTR4.cpp
zharmedia386/Data-Structures-and-Algorithms
316a7f4836cf77a4c150d4ee6a48b8d94db6518e
[ "MIT" ]
null
null
null
1. Alokasi dan Representasi/14 Program Alokasi Dinamis/PTR4.cpp
zharmedia386/Data-Structures-and-Algorithms
316a7f4836cf77a4c150d4ee6a48b8d94db6518e
[ "MIT" ]
2
2021-06-21T16:33:34.000Z
2022-03-13T04:58:20.000Z
/*--------------------------- File Program : PTR4.cpp Contoh operasi pemakaian pointer Tujuan : Melakukan operasi pada nilai yang ditunjuk pada pointer ----------------------------*/ #include <stdio.h> int main() { int z, s, *pz, *ps; z = 20; s = 30; pz = &z; ps = &s; int result = *pz + *ps; printf("z = %d, s = %d, s + z = %d\n", z, s, result); return 0; }
18.85
64
0.488064
zharmedia386
121f75494aa80c0d1d59020bec36381801c4f013
1,724
hpp
C++
src/reference_counted_object.hpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
12
2015-03-04T15:07:00.000Z
2019-09-13T16:31:06.000Z
src/reference_counted_object.hpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
null
null
null
src/reference_counted_object.hpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
5
2017-04-22T08:16:48.000Z
2020-07-12T03:35:16.000Z
/* $Id: reference_counted_object.hpp 48153 2011-01-01 15:57:50Z mordante $ */ /* Copyright (C) 2008 - 2011 by David White <dave@whitevine.net> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ #ifndef REFERENCE_COUNTED_OBJECT_HPP_INCLUDED #define REFERENCE_COUNTED_OBJECT_HPP_INCLUDED #include "boost/intrusive_ptr.hpp" class reference_counted_object { public: reference_counted_object() : count_(0) {} reference_counted_object(const reference_counted_object& /*obj*/) : count_(0) {} reference_counted_object& operator=(const reference_counted_object& /*obj*/) { return *this; } virtual ~reference_counted_object() {} void add_ref() const { ++count_; } void dec_ref() const { if(--count_ == 0) { delete const_cast<reference_counted_object*>(this); } } int refcount() const { return count_; } protected: void turn_reference_counting_off() const { count_ = 1000000; } private: mutable int count_; }; inline void intrusive_ptr_add_ref(const reference_counted_object* obj) { obj->add_ref(); } inline void intrusive_ptr_release(const reference_counted_object* obj) { obj->dec_ref(); } typedef boost::intrusive_ptr<reference_counted_object> object_ptr; typedef boost::intrusive_ptr<const reference_counted_object> const_object_ptr; #endif
31.925926
100
0.739559
blackberry
121fa1ada6dee2ae4c3e5240a755cf55391194b2
27,969
cpp
C++
src/q3bsp/Q3BspMap.cpp
suijingfeng/bsp_vulkan
8f96b164b30d6860e2a2861e1809bf693f0c8de0
[ "MIT" ]
2
2021-07-29T19:56:03.000Z
2021-09-13T12:06:06.000Z
src/q3bsp/Q3BspMap.cpp
suijingfeng/bsp_vulkan
8f96b164b30d6860e2a2861e1809bf693f0c8de0
[ "MIT" ]
null
null
null
src/q3bsp/Q3BspMap.cpp
suijingfeng/bsp_vulkan
8f96b164b30d6860e2a2861e1809bf693f0c8de0
[ "MIT" ]
null
null
null
#include "Q3BspMap.hpp" #include "Q3BspPatch.hpp" #include "../renderer/TextureManager.hpp" #include "../renderer/vulkan/CmdBuffer.hpp" #include "../renderer/vulkan/Pipeline.hpp" #include "../Math.hpp" #include "../Utils.hpp" #include <algorithm> #include <sstream> extern RenderContext g_renderContext; const int Q3BspMap::s_tesselationLevel = 10; // level of curved surface tesselation const float Q3BspMap::s_worldScale = 64.f; // scale down factor for the map Q3BspMap::~Q3BspMap() { delete[] entities.ents; delete[] visData.vecs; for (auto &it : m_patches) delete it; // release all allocated Vulkan resources vkDeviceWaitIdle(g_renderContext.device.logical); vk::destroyPipeline(g_renderContext.device, m_facesPipeline); vk::destroyPipeline(g_renderContext.device, m_patchPipeline); for (auto &it : m_renderBuffers.m_faceBuffers) { vkDestroyDescriptorPool(g_renderContext.device.logical, it.second.descriptor.pool, nullptr); vk::freeBuffer(g_renderContext.device, it.second.vertexBuffer); vk::freeBuffer(g_renderContext.device, it.second.indexBuffer); } for (auto &it : m_renderBuffers.m_patchBuffers) { for (auto &it2 : it.second) { vkDestroyDescriptorPool(g_renderContext.device.logical, it2.descriptor.pool, nullptr); vk::freeBuffer(g_renderContext.device, it2.vertexBuffer); vk::freeBuffer(g_renderContext.device, it2.indexBuffer); } } for (size_t i = 0; i < lightMaps.size(); ++i) { vk::releaseTexture(g_renderContext.device, m_lightmapTextures[i]); } delete[] m_lightmapTextures; vk::freeBuffer(g_renderContext.device, m_renderBuffers.uniformBuffer); vk::releaseTexture(g_renderContext.device, m_whiteTex); vk::freeCommandBuffers(g_renderContext.device, m_commandPool, m_commandBuffers); vk::destroyRenderPass(g_renderContext.device, m_renderPass); vkDestroyCommandPool(g_renderContext.device.logical, m_commandPool, nullptr); vkDestroyDescriptorSetLayout(g_renderContext.device.logical, m_dsLayout, nullptr); } void Q3BspMap::Init() { // regular faces are simple triangle lists, patches are drawn as triangle strips, so we need extra pipeline m_facesPipeline.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; m_patchPipeline.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; VK_VERIFY(vk::createRenderPass(g_renderContext.device, g_renderContext.swapChain, &m_renderPass)); VK_VERIFY(vk::createCommandPool(g_renderContext.device, &m_commandPool)); // build the swap chain g_renderContext.RecreateSwapChain(m_commandPool, m_renderPass); // stub missing texture used if original Quake assets are missing m_missingTex = TextureManager::GetInstance()->LoadTexture("../../res/missing.png", m_commandPool); // load textures LoadTextures(); // load lightmaps LoadLightmaps(); // create renderable faces and patches m_renderLeaves.reserve(leaves.size()); for (const auto &l : leaves) { m_renderLeaves.push_back(Q3LeafRenderable()); m_renderLeaves.back().visCluster = l.cluster; m_renderLeaves.back().firstFace = l.leafFace; m_renderLeaves.back().numFaces = l.n_leafFaces; // create a bounding box m_renderLeaves.back().boundingBoxVertices[0] = Math::Vector3f((float)l.mins.x, (float)l.mins.y, (float)l.mins.z); m_renderLeaves.back().boundingBoxVertices[1] = Math::Vector3f((float)l.mins.x, (float)l.mins.y, (float)l.maxs.z); m_renderLeaves.back().boundingBoxVertices[2] = Math::Vector3f((float)l.mins.x, (float)l.maxs.y, (float)l.mins.z); m_renderLeaves.back().boundingBoxVertices[3] = Math::Vector3f((float)l.mins.x, (float)l.maxs.y, (float)l.maxs.z); m_renderLeaves.back().boundingBoxVertices[4] = Math::Vector3f((float)l.maxs.x, (float)l.mins.y, (float)l.mins.z); m_renderLeaves.back().boundingBoxVertices[5] = Math::Vector3f((float)l.maxs.x, (float)l.mins.y, (float)l.maxs.z); m_renderLeaves.back().boundingBoxVertices[6] = Math::Vector3f((float)l.maxs.x, (float)l.maxs.y, (float)l.mins.z); m_renderLeaves.back().boundingBoxVertices[7] = Math::Vector3f((float)l.maxs.x, (float)l.maxs.y, (float)l.maxs.z); for (int i = 0; i < 8; ++i) { m_renderLeaves.back().boundingBoxVertices[i].m_x /= Q3BspMap::s_worldScale; m_renderLeaves.back().boundingBoxVertices[i].m_y /= Q3BspMap::s_worldScale; m_renderLeaves.back().boundingBoxVertices[i].m_z /= Q3BspMap::s_worldScale; } } m_renderFaces.reserve(faces.size()); // create a common descriptor set layout and vertex buffer info m_vbInfo.bindingDescriptions.push_back(vk::getBindingDescription(sizeof(Q3BspVertexLump))); m_vbInfo.attributeDescriptions.push_back(vk::getAttributeDescription(inVertex, VK_FORMAT_R32G32B32_SFLOAT, 0)); m_vbInfo.attributeDescriptions.push_back(vk::getAttributeDescription(inTexCoord, VK_FORMAT_R32G32_SFLOAT, sizeof(vec3f))); m_vbInfo.attributeDescriptions.push_back(vk::getAttributeDescription(inTexCoordLightmap, VK_FORMAT_R32G32_SFLOAT, sizeof(vec3f) + sizeof(vec2f))); CreateDescriptorSetLayout(); // single shared uniform buffer VK_VERIFY(vk::createUniformBuffer(g_renderContext.device, sizeof(UniformBufferObject), &m_renderBuffers.uniformBuffer)); int faceArrayIdx = 0; int patchArrayIdx = 0; for (const auto &f : faces) { m_renderFaces.push_back(Q3FaceRenderable()); //is it a patch? if (f.type == FaceTypePatch) { m_renderFaces.back().index = patchArrayIdx; CreatePatch(f); // generate Vulkan buffers for current patch CreateBuffersForPatch(patchArrayIdx); ++patchArrayIdx; } else { m_renderFaces.back().index = faceArrayIdx; // generate Vulkan buffers for current face CreateBuffersForFace(f, faceArrayIdx); } ++faceArrayIdx; m_renderFaces.back().type = f.type; } m_mapStats.totalVertices = vertices.size(); m_mapStats.totalFaces = faces.size(); m_mapStats.totalPatches = patchArrayIdx; RebuildPipelines(); VK_VERIFY(vk::createCommandBuffers(g_renderContext.device, m_commandPool, m_commandBuffers, g_renderContext.frameBuffers.size())); // set the scale-down uniform m_ubo.worldScaleFactor = 1.f / Q3BspMap::s_worldScale; printf("Q3BspMap::Init()\n"); } void Q3BspMap::OnRender() { // update uniform buffers m_ubo.ModelViewProjectionMatrix = g_renderContext.ModelViewProjectionMatrix; m_frustum.UpdatePlanes(); void *data; vmaMapMemory(g_renderContext.device.allocator, m_renderBuffers.uniformBuffer.allocation, &data); memcpy(data, &m_ubo, sizeof(m_ubo)); vmaUnmapMemory(g_renderContext.device.allocator, m_renderBuffers.uniformBuffer.allocation); // record new set of command buffers including only visible faces and patches RecordCommandBuffers(); // render visible faces VK_VERIFY(g_renderContext.Submit(m_commandBuffers)); } void Q3BspMap::OnWindowChanged() { g_renderContext.RecreateSwapChain(m_commandPool, m_renderPass); RebuildPipelines(); } // determine if a bsp cluster is visible from a given camera cluster bool Q3BspMap::ClusterVisible(int cameraCluster, int testCluster) const { if (!visData.vecs || (cameraCluster < 0)) { return true; } int idx = (cameraCluster * visData.sz_vecs) + (testCluster >> 3); return (visData.vecs[idx] & (1 << (testCluster & 7))) != 0; } // determine which bsp leaf camera resides in int Q3BspMap::FindCameraLeaf(const Math::Vector3f &cameraPosition) const { int leafIndex = 0; while (leafIndex >= 0) { // children.x - front node; children.y - back node if (PointPlanePos(planes[nodes[leafIndex].plane].normal.x, planes[nodes[leafIndex].plane].normal.y, planes[nodes[leafIndex].plane].normal.z, planes[nodes[leafIndex].plane].dist, cameraPosition) == Math::PointInFrontOfPlane) { leafIndex = nodes[leafIndex].children.x; } else { leafIndex = nodes[leafIndex].children.y; } } return ~leafIndex; } //Calculate which faces to draw given a camera position & view frustum void Q3BspMap::CalculateVisibleFaces(const Math::Vector3f &cameraPosition) { m_visibleFaces.clear(); m_visiblePatches.clear(); //calculate the camera leaf int cameraLeaf = FindCameraLeaf(cameraPosition * Q3BspMap::s_worldScale); int cameraCluster = m_renderLeaves[cameraLeaf].visCluster; //loop through the leaves for (const auto &rl : m_renderLeaves) { //if the leaf is not in the PVS - skip it if (!HasRenderFlag(Q3RenderSkipPVS) && !ClusterVisible(cameraCluster, rl.visCluster)) continue; //if this leaf does not lie in the frustum - skip it if (!HasRenderFlag(Q3RenderSkipFC) && !m_frustum.BoxInFrustum(rl.boundingBoxVertices)) continue; //loop through faces in this leaf and them to visibility set for(int j = 0; j < rl.numFaces; ++j) { int idx = leafFaces[rl.firstFace + j].face; Q3FaceRenderable *face = &m_renderFaces[leafFaces[rl.firstFace + j].face]; if (HasRenderFlag(Q3RenderSkipMissingTex) && !m_textures[faces[idx].texture]) continue; if ((face->type == FaceTypePolygon || face->type == FaceTypeMesh) && std::find(m_visibleFaces.begin(), m_visibleFaces.end(), face) == m_visibleFaces.end()) { m_visibleFaces.push_back(face); } if (face->type == FaceTypePatch && std::find(m_visiblePatches.begin(), m_visiblePatches.end(), idx) == m_visiblePatches.end()) { m_visiblePatches.push_back(idx); } } } m_mapStats.visibleFaces = m_visibleFaces.size(); m_mapStats.visiblePatches = m_visiblePatches.size(); } void Q3BspMap::ToggleRenderFlag(int flag) { m_renderFlags ^= flag; bool set = HasRenderFlag(flag); switch (flag) { case Q3RenderShowWireframe: m_facesPipeline.mode = set ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; m_patchPipeline.mode = set ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; RebuildPipelines(); break; case Q3RenderShowLightmaps: m_ubo.renderLightmaps = set ? 1 : 0; break; case Q3RenderUseLightmaps: m_ubo.useLightmaps = set ? 1 : 0; break; case Q3RenderAlphaTest: m_ubo.useAlphaTest = set ? 1 : 0; break; default: break; } } void Q3BspMap::LoadTextures() { int numTextures = header.direntries[Textures].length / sizeof(Q3BspTextureLump); m_textures.resize(numTextures); // load the textures from file (determine wheter it's a jpg or tga) for (const auto &f : faces) { if (m_textures[f.texture]) continue; std::string nameJPG = textures[f.texture].name; nameJPG.append(".jpg"); m_textures[f.texture] = TextureManager::GetInstance()->LoadTexture(nameJPG.c_str(), m_commandPool); if (m_textures[f.texture] == nullptr) { std::string nameTGA = textures[f.texture].name; nameTGA.append(".tga"); m_textures[f.texture] = TextureManager::GetInstance()->LoadTexture(nameTGA.c_str(), m_commandPool); if (m_textures[f.texture] == nullptr) { std::stringstream sstream; sstream << "Missing texture: " << nameTGA.c_str() << "\n"; LOG_MESSAGE(sstream.str().c_str()); } } } printf("LoadTextures()\n"); } void Q3BspMap::LoadLightmaps() { m_lightmapTextures = new vk::Texture[lightMaps.size()]; // optional: change gamma settings of the lightmaps (make them brighter) SetLightmapGamma(2.5f); // few GPUs support true 24bit textures, so we need to convert lightmaps to 32bit for Vulkan to work unsigned char rgba_lmap[128 * 128 * 4]; for (size_t i = 0; i < lightMaps.size(); ++i) { memset(rgba_lmap, 255, 128 * 128 * 4); for (int j = 0, k = 0; k < 128 * 128 * 3; j += 4, k += 3) memcpy(rgba_lmap + j, lightMaps[i].map + k, 3); // Create texture from bsp lightmap data vk::createTexture(g_renderContext.device, m_commandPool, &m_lightmapTextures[i], rgba_lmap, 128, 128); } // Create white texture for if no lightmap specified unsigned char white[] = { 255, 255, 255, 255 }; vk::createTexture(g_renderContext.device, m_commandPool, &m_whiteTex, white, 1, 1); printf("LoadLightmaps()\n"); } // tweak lightmap gamma settings void Q3BspMap::SetLightmapGamma(float gamma) { for (size_t i = 0; i < lightMaps.size(); ++i) { for (int j = 0; j < 128 * 128; ++j) { float r, g, b; r = lightMaps[i].map[j * 3 + 0]; g = lightMaps[i].map[j * 3 + 1]; b = lightMaps[i].map[j * 3 + 2]; r *= gamma / 255.0f; g *= gamma / 255.0f; b *= gamma / 255.0f; float scale = 1.0f; float temp; if (r > 1.0f && (temp = (1.0f / r)) < scale) scale = temp; if (g > 1.0f && (temp = (1.0f / g)) < scale) scale = temp; if (b > 1.0f && (temp = (1.0f / b)) < scale) scale = temp; scale *= 255.0f; r *= scale; g *= scale; b *= scale; lightMaps[i].map[j * 3 + 0] = (unsigned char)r; lightMaps[i].map[j * 3 + 1] = (unsigned char)g; lightMaps[i].map[j * 3 + 2] = (unsigned char)b; } } } // create a Q3Bsp curved surface void Q3BspMap::CreatePatch(const Q3BspFaceLump &f) { Q3BspPatch *newPatch = new Q3BspPatch; newPatch->textureIdx = f.texture; newPatch->lightmapIdx = f.lm_index; newPatch->width = f.size.x; newPatch->height = f.size.y; int numPatchesWidth = (newPatch->width - 1) >> 1; int numPatchesHeight = (newPatch->height - 1) >> 1; newPatch->quadraticPatches.resize(numPatchesWidth*numPatchesHeight); // generate biquadratic patches (components that make the curved surface) for (int y = 0; y < numPatchesHeight; ++y) { for (int x = 0; x < numPatchesWidth; ++x) { for (int row = 0; row < 3; ++row) { for (int col = 0; col < 3; ++col) { int patchIdx = y * numPatchesWidth + x; int cpIdx = row * 3 + col; newPatch->quadraticPatches[patchIdx].controlPoints[cpIdx] = vertices[f.vertex + (y * 2 * newPatch->width + x * 2) + row * newPatch->width + col]; } } newPatch->quadraticPatches[y * numPatchesWidth + x].Tesselate(Q3BspMap::s_tesselationLevel); } } m_patches.push_back(newPatch); } void Q3BspMap::RecordCommandBuffers() { for (size_t i = 0; i < m_commandBuffers.size(); ++i) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; beginInfo.pInheritanceInfo = nullptr; VkResult result = vkBeginCommandBuffer(m_commandBuffers[i], &beginInfo); LOG_MESSAGE_ASSERT(result == VK_SUCCESS, "Could not begin command buffer: " << result); VkClearValue clearColors[2]; clearColors[0].color = { 0.f, 0.f, 0.f, 1.f }; clearColors[1].depthStencil = { 1.0f, 0 }; VkRenderPassBeginInfo renderBeginInfo = {}; renderBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderBeginInfo.renderPass = m_renderPass.renderPass; renderBeginInfo.framebuffer = g_renderContext.frameBuffers[i]; renderBeginInfo.renderArea.offset = { 0, 0 }; renderBeginInfo.renderArea.extent = g_renderContext.swapChain.extent; renderBeginInfo.clearValueCount = 2; renderBeginInfo.pClearValues = clearColors; vkCmdBeginRenderPass(m_commandBuffers[i], &renderBeginInfo, VK_SUBPASS_CONTENTS_INLINE); // queue standard faces vkCmdBindPipeline(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_facesPipeline.pipeline); for (auto &f : m_visibleFaces) { FaceBuffers &fb = m_renderBuffers.m_faceBuffers[f->index]; VkBuffer vertexBuffers[] = { fb.vertexBuffer.buffer }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(m_commandBuffers[i], 0, 1, vertexBuffers, offsets); // quake 3 bsp requires uint32 for index type - 16 is too small vkCmdBindIndexBuffer(m_commandBuffers[i], fb.indexBuffer.buffer, 0, VK_INDEX_TYPE_UINT32); vkCmdBindDescriptorSets(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_facesPipeline.layout, 0, 1, &fb.descriptor.set, 0, nullptr); vkCmdDrawIndexed(m_commandBuffers[i], fb.indexCount, 1, 0, 0, 0); } // queue patches vkCmdBindPipeline(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_patchPipeline.pipeline); for (auto &pi : m_visiblePatches) { for (auto &p : m_renderBuffers.m_patchBuffers[pi]) { VkBuffer vertexBuffers[] = { p.vertexBuffer.buffer }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(m_commandBuffers[i], 0, 1, vertexBuffers, offsets); // quake 3 bsp requires uint32 for index type - 16 is too small vkCmdBindIndexBuffer(m_commandBuffers[i], p.indexBuffer.buffer, 0, VK_INDEX_TYPE_UINT32); vkCmdBindDescriptorSets(m_commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_patchPipeline.layout, 0, 1, &p.descriptor.set, 0, nullptr); vkCmdDrawIndexed(m_commandBuffers[i], p.indexCount, 1, 0, 0, 0); } } vkCmdEndRenderPass(m_commandBuffers[i]); result = vkEndCommandBuffer(m_commandBuffers[i]); LOG_MESSAGE_ASSERT(result == VK_SUCCESS, "Error recording command buffer: " << result); } } void Q3BspMap::RebuildPipelines() { vkDeviceWaitIdle(g_renderContext.device.logical); vk::destroyPipeline(g_renderContext.device, m_facesPipeline); vk::destroyPipeline(g_renderContext.device, m_patchPipeline); // todo: pipeline derivatives https://github.com/SaschaWillems/Vulkan/blob/master/examples/pipelines/pipelines.cpp const char *shaders[] = { "../../res/Basic_vert.spv", "../../res/Basic_frag.spv" }; VK_VERIFY(vk::createPipeline(g_renderContext.device, g_renderContext.swapChain, m_renderPass, m_dsLayout, &m_vbInfo, &m_facesPipeline, shaders)); VK_VERIFY(vk::createPipeline(g_renderContext.device, g_renderContext.swapChain, m_renderPass, m_dsLayout, &m_vbInfo, &m_patchPipeline, shaders)); } void Q3BspMap::CreateBuffersForFace(const Q3BspFaceLump &face, int idx) { if (face.type == FaceTypeBillboard) return; auto &faceBuffer = m_renderBuffers.m_faceBuffers[idx]; faceBuffer.descriptor.setLayout = m_dsLayout; faceBuffer.vertexCount = face.n_vertexes; faceBuffer.indexCount = face.n_meshverts; // vertex buffer and index buffer with staging buffer vk::createVertexBuffer(g_renderContext.device, m_commandPool, &(vertices[face.vertex].position), sizeof(Q3BspVertexLump) * face.n_vertexes, &faceBuffer.vertexBuffer); vk::createIndexBuffer(g_renderContext.device, m_commandPool, &meshVertices[face.meshvert], sizeof(Q3BspMeshVertLump) * face.n_meshverts, &faceBuffer.indexBuffer); // check if both the texture and lightmap exist and if not - replace them with missing/white texture stubs const vk::Texture *colorTex = m_textures[faces[idx].texture] ? *m_textures[faces[idx].texture] : *m_missingTex; const vk::Texture &lmap = faces[idx].lm_index >= 0 ? m_lightmapTextures[faces[idx].lm_index] : m_whiteTex; const vk::Texture *textureSet[2] = { colorTex, &lmap }; CreateDescriptor(textureSet, &faceBuffer.descriptor); } void Q3BspMap::CreateBuffersForPatch(int idx) { int numPatches = m_patches[idx]->quadraticPatches.size(); for (int i = 0; i < numPatches; i++) { // shorthand references so the code is easier to read auto *patch = m_patches[idx]; auto &biquadPatch = patch->quadraticPatches[i]; auto &patchBuffer = m_renderBuffers.m_patchBuffers[idx]; int numVerts = biquadPatch.m_vertices.size(); int tessLevel = biquadPatch.m_tesselationLevel; for (int row = 0; row < tessLevel; ++row) { FaceBuffers pb; pb.descriptor.setLayout = m_dsLayout; pb.vertexCount = numVerts; pb.indexCount = 2 * (tessLevel + 1); // vertex buffer and index buffer with staging buffer vk::createVertexBuffer(g_renderContext.device, m_commandPool, &biquadPatch.m_vertices[0].position, sizeof(Q3BspVertexLump) * numVerts, &pb.vertexBuffer); vk::createIndexBuffer(g_renderContext.device, m_commandPool, &biquadPatch.m_indices[row * 2 * (tessLevel + 1)], sizeof(Q3BspMeshVertLump) * 2 * (tessLevel + 1), &pb.indexBuffer); // check if both the texture and lightmap exist and if not - replace them with missing/white texture stubs const vk::Texture *colorTex = m_textures[patch->textureIdx] ? *m_textures[patch->textureIdx] : *m_missingTex; const vk::Texture &lmap = patch->lightmapIdx >= 0 ? m_lightmapTextures[patch->lightmapIdx] : m_whiteTex; // create Vulkan descriptor const vk::Texture *textureSet[] = { colorTex, &lmap }; CreateDescriptor(textureSet, &pb.descriptor); patchBuffer.emplace_back(pb); } } } void Q3BspMap::CreateDescriptorSetLayout() { VkDescriptorSetLayoutBinding uboLayoutBinding = {}; uboLayoutBinding.binding = 0; uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uboLayoutBinding.descriptorCount = 1; uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; uboLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutBinding samplerLayoutBinding = {}; samplerLayoutBinding.binding = 1; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; samplerLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutBinding lightmapSamplerLayoutBinding = {}; lightmapSamplerLayoutBinding.binding = 2; lightmapSamplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; lightmapSamplerLayoutBinding.descriptorCount = 1; lightmapSamplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; lightmapSamplerLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutBinding bindings[] = { uboLayoutBinding, samplerLayoutBinding, lightmapSamplerLayoutBinding }; VkDescriptorSetLayoutCreateInfo layoutInfo = {}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 3; layoutInfo.pBindings = bindings; VK_VERIFY(vkCreateDescriptorSetLayout(g_renderContext.device.logical, &layoutInfo, nullptr, &m_dsLayout)); } void Q3BspMap::CreateDescriptor(const vk::Texture **textures, vk::Descriptor *descriptor) { // create descriptor pool VkDescriptorPoolSize poolSizes[3]; poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSizes[0].descriptorCount = 1; poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[1].descriptorCount = 1; poolSizes[2].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; poolSizes[2].descriptorCount = 1; VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 3; poolInfo.pPoolSizes = poolSizes; poolInfo.maxSets = 1; VK_VERIFY(vkCreateDescriptorPool(g_renderContext.device.logical, &poolInfo, nullptr, &descriptor->pool)); // create descriptor set VK_VERIFY(vk::createDescriptorSet(g_renderContext.device, descriptor)); VkDescriptorBufferInfo bufferInfo = {}; bufferInfo.offset = 0; bufferInfo.buffer = m_renderBuffers.uniformBuffer.buffer; bufferInfo.range = sizeof(UniformBufferObject); VkDescriptorImageInfo imageInfo = {}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = textures[0]->imageView; imageInfo.sampler = textures[0]->sampler; VkDescriptorImageInfo lightmapInfo = {}; lightmapInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; lightmapInfo.imageView = textures[1]->imageView; lightmapInfo.sampler = textures[1]->sampler; VkWriteDescriptorSet descriptorWrites[3]; descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[0].dstSet = descriptor->set; descriptorWrites[0].dstBinding = 0; descriptorWrites[0].dstArrayElement = 0; descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrites[0].descriptorCount = 1; descriptorWrites[0].pBufferInfo = &bufferInfo; descriptorWrites[0].pImageInfo = nullptr; descriptorWrites[0].pTexelBufferView = nullptr; descriptorWrites[0].pNext = nullptr; descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[1].dstSet = descriptor->set; descriptorWrites[1].dstBinding = 1; descriptorWrites[1].dstArrayElement = 0; descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrites[1].descriptorCount = 1; descriptorWrites[1].pBufferInfo = nullptr; descriptorWrites[1].pImageInfo = &imageInfo; descriptorWrites[1].pTexelBufferView = nullptr; descriptorWrites[1].pNext = nullptr; descriptorWrites[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrites[2].dstSet = descriptor->set; descriptorWrites[2].dstBinding = 2; descriptorWrites[2].dstArrayElement = 0; descriptorWrites[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrites[2].descriptorCount = 1; descriptorWrites[2].pBufferInfo = nullptr; descriptorWrites[2].pImageInfo = &lightmapInfo; descriptorWrites[2].pTexelBufferView = nullptr; descriptorWrites[2].pNext = nullptr; vkUpdateDescriptorSets(g_renderContext.device.logical, 3, descriptorWrites, 0, nullptr); }
41.252212
156
0.653152
suijingfeng
1220881c38060cb1b2a19c4c26f39604e2d1edab
2,854
cpp
C++
tests/serialization_ext_std_chrono.cpp
victorstewart/bitsery
db884a0656a3aabb87da1ae6edf12629507f76a7
[ "MIT" ]
722
2017-08-22T06:07:02.000Z
2022-03-30T03:29:20.000Z
tests/serialization_ext_std_chrono.cpp
victorstewart/bitsery
db884a0656a3aabb87da1ae6edf12629507f76a7
[ "MIT" ]
85
2017-10-19T07:23:29.000Z
2022-03-02T06:54:10.000Z
tests/serialization_ext_std_chrono.cpp
victorstewart/bitsery
db884a0656a3aabb87da1ae6edf12629507f76a7
[ "MIT" ]
69
2017-08-28T06:38:07.000Z
2022-03-13T03:12:02.000Z
//MIT License // //Copyright (c) 2019 Mindaugas Vinkelis // //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 <bitsery/ext/std_chrono.h> #include <gmock/gmock.h> #include "serialization_test_utils.h" using StdDuration = bitsery::ext::StdDuration; using StdTimePoint = bitsery::ext::StdTimePoint; using testing::Eq; TEST(SerializeExtensionStdChrono, IntegralDuration) { SerializationContext ctx1; using Hours = std::chrono::duration<int32_t, std::ratio<60>>; Hours data{43}; Hours res{}; ctx1.createSerializer().ext4b(data, StdDuration{}); ctx1.createDeserializer().ext4b(res, StdDuration{}); EXPECT_THAT(res, Eq(data)); } TEST(SerializeExtensionStdChrono, IntegralTimePoint) { SerializationContext ctx1; using Duration = std::chrono::duration<int64_t, std::milli>; using TP = std::chrono::time_point<std::chrono::system_clock, Duration>; TP data{Duration{243}}; TP res{}; ctx1.createSerializer().ext8b(data, StdTimePoint{}); ctx1.createDeserializer().ext8b(res, StdTimePoint{}); EXPECT_THAT(res, Eq(data)); } TEST(SerializeExtensionStdChrono, FloatDuration) { SerializationContext ctx1; using Hours = std::chrono::duration<float, std::ratio<60>>; Hours data{43.5f}; Hours res{}; ctx1.createSerializer().ext4b(data, StdDuration{}); ctx1.createDeserializer().ext4b(res, StdDuration{}); EXPECT_THAT(res, Eq(data)); } TEST(SerializeExtensionStdChrono, FloatTimePoint) { SerializationContext ctx1; using Duration = std::chrono::duration<double, std::milli>; using TP = std::chrono::time_point<std::chrono::system_clock, Duration>; TP data{Duration{243457.4}}; TP res{}; ctx1.createSerializer().ext8b(data, StdTimePoint{}); ctx1.createDeserializer().ext8b(res, StdTimePoint{}); EXPECT_THAT(res, Eq(data)); }
34.804878
80
0.734408
victorstewart
1220e5dc0ecb154d3c197288354a7640ae647746
4,554
cpp
C++
projects/InjectDLL/system/textures.cpp
LoadCake/OriWotwRandomizerClient
99812148b60aad77895bf4aa560128d0ff9b73eb
[ "MIT" ]
null
null
null
projects/InjectDLL/system/textures.cpp
LoadCake/OriWotwRandomizerClient
99812148b60aad77895bf4aa560128d0ff9b73eb
[ "MIT" ]
null
null
null
projects/InjectDLL/system/textures.cpp
LoadCake/OriWotwRandomizerClient
99812148b60aad77895bf4aa560128d0ff9b73eb
[ "MIT" ]
null
null
null
#include <system/textures.h> #include <Common/ext.h> #include <Il2CppModLoader/common.h> #include <Il2CppModLoader/il2cpp_helpers.h> #include <Il2CppModLoader/interception_macros.h> #include <utils\stb_image.h> #include <fstream> #include <string> #include <unordered_map> using namespace modloader; namespace textures { std::unordered_map<std::wstring, uint32_t> files; NAMED_IL2CPP_BINDING_OVERLOAD(UnityEngine, Texture2D, void, .ctor, ctor, (app::Texture2D* this_ptr, int width, int height, app::TextureFormat__Enum format, bool mip_chain, bool linear), (System:Int32, System:Int32, UnityEngine:TextureFormat, System:Boolean, System:Boolean)) IL2CPP_BINDING(UnityEngine, Texture2D, void, LoadRawTextureData, (app::Texture2D* this_ptr, void* data, int size)); IL2CPP_BINDING(UnityEngine, Texture2D, void, Apply, (app::Texture2D* this_ptr, bool update_mipmaps, bool no_longer_readable)); app::Texture2D* get_texture(std::wstring_view path) { try { auto separator = path.find(':', 0); if (separator == -1) { // Trace error return nullptr; } auto type = path.substr(0, separator); auto value = std::wstring(path.substr(separator + 1)); if (type == L"shard") { auto actual_value = static_cast<app::SpiritShardType__Enum>(std::stoi(value)); auto settings = il2cpp::get_class<app::SpiritShardSettings__Class>("", "SpiritShardSettings")->static_fields->Instance; auto item = il2cpp::invoke<app::SpiritShardIconsCollection_Icons__Boxed>(settings->fields.Icons, "GetValue", &actual_value); // TODO: add second selector. return item == nullptr ? nullptr : item->fields.InventoryIcon; } else if (type == L"ability") { auto actual_value = static_cast<app::AbilityType__Enum>(std::stoi(value)); auto settings = il2cpp::get_class<app::SpellSettings__Class>("", "SpellSettings")->static_fields->Instance; auto item = il2cpp::invoke<app::Texture2D>(settings->fields.CustomAbilityIcons, "GetValue", &actual_value); // TODO: add second selector. return item; } else if (type == L"spell") { auto actual_value = static_cast<app::EquipmentType__Enum>(std::stoi(value)); auto settings = il2cpp::get_class<app::SpellSettings__Class>("", "SpellSettings")->static_fields->Instance; auto item = il2cpp::invoke<app::SpellIconsCollection_Icons__Boxed>(settings->fields.Icons, "GetValue", &actual_value); // TODO: add second selector. return item == nullptr ? nullptr : item->fields.InventoryIcon; } else if (type == L"file") { auto it = files.find(value); if (it != files.end()) return reinterpret_cast<app::Texture2D*>(il2cpp::gchandle_target(it->second)); auto path = base_path + convert_wstring_to_string(value); replace_all(path, "/", "\\"); int x; int y; int n = 4; stbi_set_flip_vertically_on_load(true); unsigned char* data = stbi_load(path.c_str(), &x, &y, &n, STBI_rgb_alpha); if (data == nullptr) { modloader::warn("textures", format("failed to load texture %s (%s).", path.c_str(), stbi_failure_reason())); return nullptr; } auto texture = il2cpp::create_object<app::Texture2D>("UnityEngine", "Texture2D"); Texture2D::ctor(texture, x, y, app::TextureFormat__Enum_RGBA32, false, false); Texture2D::LoadRawTextureData(texture, data, x * y * n); Texture2D::Apply(texture, true, false); stbi_image_free(data); files[value] = il2cpp::gchandle_new(texture, false); return texture; } else { modloader::warn("textures", "unknown texture protocol used when loading texture."); return nullptr; } } catch (std::exception e) { modloader::warn("textures", format("Fatal error fetching texture (%s)", e.what())); return nullptr; } } }
43.371429
140
0.577514
LoadCake
12238f77a4457449517ef9c7dd13e7fa927f8434
47,151
hxx
C++
Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
2
2015-06-19T07:18:36.000Z
2019-04-18T07:28:23.000Z
Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
null
null
null
Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx
CapeDrew/DCMTK-ITK
440bf8ed100445396912cfd0aa72f36d4cdefe0c
[ "Apache-2.0" ]
2
2017-05-02T07:18:49.000Z
2020-04-30T01:37:35.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkMattesMutualInformationImageToImageMetric_hxx #define __itkMattesMutualInformationImageToImageMetric_hxx #include "itkMattesMutualInformationImageToImageMetric.h" #include "itkImageRandomConstIteratorWithIndex.h" #include "itkImageRegionIterator.h" #include "itkImageIterator.h" #include "vnl/vnl_math.h" #include "itkStatisticsImageFilter.h" #include "vnl/vnl_vector.h" #include "vnl/vnl_c_vector.h" namespace itk { /** * Constructor */ template <class TFixedImage, class TMovingImage> MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::MattesMutualInformationImageToImageMetric() : // Initialize memory m_FixedImageMarginalPDF(NULL), m_MovingImageMarginalPDF(NULL), m_PRatioArray(), m_MetricDerivative(0), m_ThreaderMetricDerivative(NULL), // Initialize PDFs to NULL m_JointPDF(NULL), m_JointPDFBufferSize(0), m_JointPDFDerivatives(NULL), m_JointPDFDerivativesBufferSize(0), m_NumberOfHistogramBins(50), m_MovingImageNormalizedMin(0.0), m_FixedImageNormalizedMin(0.0), m_MovingImageTrueMin(0.0), m_MovingImageTrueMax(0.0), m_FixedImageBinSize(0.0), m_MovingImageBinSize(0.0), m_CubicBSplineKernel(NULL), m_CubicBSplineDerivativeKernel(NULL), // For multi-threading the metric m_ThreaderFixedImageMarginalPDF(NULL), m_ThreaderJointPDF(NULL), m_ThreaderJointPDFDerivatives(NULL), m_ThreaderJointPDFStartBin(NULL), m_ThreaderJointPDFEndBin(NULL), m_ThreaderJointPDFSum(NULL), m_JointPDFSum(0.0), m_UseExplicitPDFDerivatives(true), m_ImplicitDerivativesSecondPass(false) { this->SetComputeGradient(false); // don't use the default gradient for now this->m_WithinThreadPreProcess = true; this->m_WithinThreadPostProcess = false; this->m_ComputeGradient = false; } template <class TFixedImage, class TMovingImage> MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::~MattesMutualInformationImageToImageMetric() { if( m_FixedImageMarginalPDF != NULL ) { delete[] m_FixedImageMarginalPDF; } m_FixedImageMarginalPDF = NULL; if( m_MovingImageMarginalPDF != NULL ) { delete[] m_MovingImageMarginalPDF; } m_MovingImageMarginalPDF = NULL; if( m_ThreaderJointPDF != NULL ) { delete[] m_ThreaderJointPDF; } m_ThreaderJointPDF = NULL; if( m_ThreaderJointPDFDerivatives != NULL ) { delete[] m_ThreaderJointPDFDerivatives; } m_ThreaderJointPDFDerivatives = NULL; if( m_ThreaderFixedImageMarginalPDF != NULL ) { delete[] m_ThreaderFixedImageMarginalPDF; } m_ThreaderFixedImageMarginalPDF = NULL; if( m_ThreaderJointPDFStartBin != NULL ) { delete[] m_ThreaderJointPDFStartBin; } m_ThreaderJointPDFStartBin = NULL; if( m_ThreaderJointPDFEndBin != NULL ) { delete[] m_ThreaderJointPDFEndBin; } m_ThreaderJointPDFEndBin = NULL; if( m_ThreaderJointPDFSum != NULL ) { delete[] m_ThreaderJointPDFSum; } m_ThreaderJointPDFSum = NULL; if( this->m_ThreaderMetricDerivative != NULL ) { delete[] this->m_ThreaderMetricDerivative; } this->m_ThreaderMetricDerivative = NULL; } /** * Print out internal information about this class */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "NumberOfHistogramBins: "; os << this->m_NumberOfHistogramBins << std::endl; // Debugging information os << indent << "FixedImageNormalizedMin: "; os << this->m_FixedImageNormalizedMin << std::endl; os << indent << "MovingImageNormalizedMin: "; os << this->m_MovingImageNormalizedMin << std::endl; os << indent << "MovingImageTrueMin: "; os << this->m_MovingImageTrueMin << std::endl; os << indent << "MovingImageTrueMax: "; os << this->m_MovingImageTrueMax << std::endl; os << indent << "FixedImageBinSize: "; os << this->m_FixedImageBinSize << std::endl; os << indent << "MovingImageBinSize: "; os << this->m_MovingImageBinSize << std::endl; os << indent << "UseExplicitPDFDerivatives: "; os << this->m_UseExplicitPDFDerivatives << std::endl; os << indent << "ImplicitDerivativesSecondPass: "; os << this->m_ImplicitDerivativesSecondPass << std::endl; if( this->m_JointPDF.IsNotNull() ) { os << indent << "JointPDF: "; os << this->m_JointPDF << std::endl; } if( this->m_JointPDFDerivatives.IsNotNull() ) { os << indent << "JointPDFDerivatives: "; os << this->m_JointPDFDerivatives; } } /** * Initialize */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::Initialize(void) throw ( ExceptionObject ) { this->Superclass::Initialize(); this->Superclass::MultiThreadingInitialize(); { /** * Compute the minimum and maximum within the specified mask * region for creating the size of the 2D joint histogram. * Areas outside the masked region should be ignored * in computing the range of intensity values. */ this->m_FixedImageTrueMin = vcl_numeric_limits<typename TFixedImage::PixelType>::max(); this->m_FixedImageTrueMax = vcl_numeric_limits<typename TFixedImage::PixelType>::min(); this->m_MovingImageTrueMin = vcl_numeric_limits<typename TMovingImage::PixelType>::max(); this->m_MovingImageTrueMax = vcl_numeric_limits<typename TMovingImage::PixelType>::min(); // We need to make robust measures only over the requested mask region itk::ImageRegionConstIteratorWithIndex<TFixedImage> fi(this->m_FixedImage, this->m_FixedImage->GetBufferedRegion() ); while( !fi.IsAtEnd() ) { typename TFixedImage::PointType fixedSpacePhysicalPoint; this->m_FixedImage->TransformIndexToPhysicalPoint(fi.GetIndex(), fixedSpacePhysicalPoint); if( this->m_FixedImageMask.IsNull() // A null mask implies entire space is to be used. || this->m_FixedImageMask->IsInside(fixedSpacePhysicalPoint) ) { const typename TFixedImage::PixelType currValue = fi.Get(); m_FixedImageTrueMin = (m_FixedImageTrueMin < currValue) ? m_FixedImageTrueMin : currValue; m_FixedImageTrueMax = (m_FixedImageTrueMax > currValue) ? m_FixedImageTrueMax : currValue; } ++fi; } { itk::ImageRegionConstIteratorWithIndex<TMovingImage> mi(this->m_MovingImage, this->m_MovingImage->GetBufferedRegion() ); while( !mi.IsAtEnd() ) { typename TMovingImage::PointType movingSpacePhysicalPoint; this->m_MovingImage->TransformIndexToPhysicalPoint(mi.GetIndex(), movingSpacePhysicalPoint); if( this->m_MovingImageMask.IsNull() // A null mask implies entire space is to be used. || this->m_MovingImageMask->IsInside(movingSpacePhysicalPoint) ) { const typename TMovingImage::PixelType currValue = mi.Get(); m_MovingImageTrueMin = (m_MovingImageTrueMin < currValue) ? m_MovingImageTrueMin : currValue; m_MovingImageTrueMax = (m_MovingImageTrueMax > currValue) ? m_MovingImageTrueMax : currValue; } ++mi; } } } itkDebugMacro(" FixedImageMin: " << m_FixedImageTrueMin << " FixedImageMax: " << m_FixedImageTrueMax << std::endl); itkDebugMacro(" MovingImageMin: " << m_MovingImageTrueMin << " MovingImageMax: " << m_MovingImageTrueMax << std::endl); /** * Compute binsize for the histograms. * * The binsize for the image intensities needs to be adjusted so that * we can avoid dealing with boundary conditions using the cubic * spline as the Parzen window. We do this by increasing the size * of the bins so that the joint histogram becomes "padded" at the * borders. Because we are changing the binsize, * we also need to shift the minimum by the padded amount in order to * avoid minimum values filling in our padded region. * * Note that there can still be non-zero bin values in the padded region, * it's just that these bins will never be a central bin for the Parzen * window. * */ const int padding = 2; // this will pad by 2 bins m_FixedImageBinSize = ( m_FixedImageTrueMax - m_FixedImageTrueMin ) / static_cast<double>( m_NumberOfHistogramBins - 2 * padding ); m_FixedImageNormalizedMin = m_FixedImageTrueMin / m_FixedImageBinSize - static_cast<double>( padding ); m_MovingImageBinSize = ( m_MovingImageTrueMax - m_MovingImageTrueMin ) / static_cast<double>( m_NumberOfHistogramBins - 2 * padding ); m_MovingImageNormalizedMin = m_MovingImageTrueMin / m_MovingImageBinSize - static_cast<double>( padding ); itkDebugMacro("FixedImageNormalizedMin: " << m_FixedImageNormalizedMin); itkDebugMacro("MovingImageNormalizedMin: " << m_MovingImageNormalizedMin); itkDebugMacro("FixedImageBinSize: " << m_FixedImageBinSize); itkDebugMacro("MovingImageBinSize; " << m_MovingImageBinSize); /** * Allocate memory for the marginal PDF and initialize values * to zero. The marginal PDFs are stored as std::vector. */ if( m_FixedImageMarginalPDF != NULL ) { delete[] m_FixedImageMarginalPDF; } m_FixedImageMarginalPDF = new PDFValueType[m_NumberOfHistogramBins]; if( m_MovingImageMarginalPDF != NULL ) { delete[] m_MovingImageMarginalPDF; } m_MovingImageMarginalPDF = new PDFValueType[m_NumberOfHistogramBins]; /** * Allocate memory for the joint PDF and joint PDF derivatives. * The joint PDF and joint PDF derivatives are store as itk::Image. */ m_JointPDF = JointPDFType::New(); // Instantiate a region, index, size JointPDFRegionType jointPDFRegion; JointPDFIndexType jointPDFIndex; JointPDFSizeType jointPDFSize; JointPDFDerivativesRegionType jointPDFDerivativesRegion; // // Now allocate memory according to the user-selected method. // if( this->m_UseExplicitPDFDerivatives ) { // Deallocate the memory that may have been allocated for // previous runs of the metric. // and by allocating very small the static ones this->m_PRatioArray.SetSize(1, 1); // Not needed if m_UseExplicitPDFDerivatives this->m_MetricDerivative = DerivativeType(1); // Not needed if m_UseExplicitPDFDerivatives this->m_JointPDFDerivatives = JointPDFDerivativesType::New(); JointPDFDerivativesIndexType jointPDFDerivativesIndex; JointPDFDerivativesSizeType jointPDFDerivativesSize; // For the derivatives of the joint PDF define a region starting from // {0,0,0} // with size {m_NumberOfParameters,m_NumberOfHistogramBins, // m_NumberOfHistogramBins}. The dimension represents transform parameters, // fixed image parzen window index and moving image parzen window index, // respectively. jointPDFDerivativesIndex.Fill(0); jointPDFDerivativesSize[0] = this->m_NumberOfParameters; jointPDFDerivativesSize[1] = this->m_NumberOfHistogramBins; jointPDFDerivativesSize[2] = this->m_NumberOfHistogramBins; jointPDFDerivativesRegion.SetIndex(jointPDFDerivativesIndex); jointPDFDerivativesRegion.SetSize(jointPDFDerivativesSize); // Set the regions and allocate m_JointPDFDerivatives->SetRegions(jointPDFDerivativesRegion); m_JointPDFDerivatives->Allocate(); m_JointPDFDerivativesBufferSize = jointPDFDerivativesSize[0] * jointPDFDerivativesSize[1] * jointPDFDerivativesSize[2] * sizeof( JointPDFDerivativesValueType ); } else { // Deallocate the memory that may have been allocated for // previous runs of the metric. this->m_JointPDFDerivatives = NULL; // Not needed if m_UseExplicitPDFDerivatives=false /** Allocate memory for helper array that will contain the pRatios * for each bin of the joint histogram. This is part of the effort * for flattening the computation of the PDF Jacobians. */ this->m_PRatioArray.SetSize(this->m_NumberOfHistogramBins, this->m_NumberOfHistogramBins); this->m_MetricDerivative = DerivativeType( this->GetNumberOfParameters() ); } // For the joint PDF define a region starting from {0,0} // with size {m_NumberOfHistogramBins, m_NumberOfHistogramBins}. // The dimension represents fixed image parzen window index // and moving image parzen window index, respectively. jointPDFIndex.Fill(0); jointPDFSize.Fill(m_NumberOfHistogramBins); jointPDFRegion.SetIndex(jointPDFIndex); jointPDFRegion.SetSize(jointPDFSize); // Set the regions and allocate m_JointPDF->SetRegions(jointPDFRegion); { // By setting these values, the joint histogram physical locations will correspond to intensity values. typename JointPDFType::PointType origin; origin[0] = this->m_FixedImageTrueMin; origin[1] = this->m_MovingImageTrueMin; m_JointPDF->SetOrigin(origin); typename JointPDFType::SpacingType spacing; spacing[0] = this->m_FixedImageBinSize; spacing[1] = this->m_MovingImageBinSize; m_JointPDF->SetSpacing(spacing); } m_JointPDF->Allocate(); m_JointPDFBufferSize = jointPDFSize[0] * jointPDFSize[1] * sizeof( PDFValueType ); /** * Setup the kernels used for the Parzen windows. */ m_CubicBSplineKernel = CubicBSplineFunctionType::New(); m_CubicBSplineDerivativeKernel = CubicBSplineDerivativeFunctionType::New(); /** * Pre-compute the fixed image parzen window index for * each point of the fixed image sample points list. */ this->ComputeFixedImageParzenWindowIndices(this->m_FixedImageSamples); if( m_ThreaderFixedImageMarginalPDF != NULL ) { delete[] m_ThreaderFixedImageMarginalPDF; } // Assumes number of threads doesn't change between calls to Initialize m_ThreaderFixedImageMarginalPDF = new PDFValueType[( this->m_NumberOfThreads - 1 ) * m_NumberOfHistogramBins]; if( m_ThreaderJointPDF != NULL ) { delete[] m_ThreaderJointPDF; } m_ThreaderJointPDF = new typename JointPDFType::Pointer[this->m_NumberOfThreads - 1]; if( m_ThreaderJointPDFStartBin != NULL ) { delete[] m_ThreaderJointPDFStartBin; } m_ThreaderJointPDFStartBin = new int[this->m_NumberOfThreads]; if( m_ThreaderJointPDFEndBin != NULL ) { delete[] m_ThreaderJointPDFEndBin; } m_ThreaderJointPDFEndBin = new int[this->m_NumberOfThreads]; if( m_ThreaderJointPDFSum != NULL ) { delete[] m_ThreaderJointPDFSum; } m_ThreaderJointPDFSum = new double[this->m_NumberOfThreads]; const int binRange = m_NumberOfHistogramBins / this->m_NumberOfThreads; for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { m_ThreaderJointPDF[threadID] = JointPDFType::New(); m_ThreaderJointPDF[threadID]->SetRegions(jointPDFRegion); m_ThreaderJointPDF[threadID]->Allocate(); m_ThreaderJointPDFStartBin[threadID] = threadID * binRange; m_ThreaderJointPDFEndBin[threadID] = ( threadID + 1 ) * binRange - 1; } m_ThreaderJointPDFStartBin[this->m_NumberOfThreads - 1] = ( this->m_NumberOfThreads - 1 ) * binRange; m_ThreaderJointPDFEndBin[this->m_NumberOfThreads - 1] = m_NumberOfHistogramBins - 1; // Release memory of arrays that may have been used for // previous executions of this metric with different settings // of the memory caching flags. if( m_ThreaderJointPDFDerivatives != NULL ) { delete[] m_ThreaderJointPDFDerivatives; } m_ThreaderJointPDFDerivatives = NULL; if( m_ThreaderMetricDerivative != NULL ) { delete[] m_ThreaderMetricDerivative; } m_ThreaderMetricDerivative = NULL; if( this->m_UseExplicitPDFDerivatives ) { m_ThreaderJointPDFDerivatives = new typename JointPDFDerivativesType::Pointer[this->m_NumberOfThreads - 1]; for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { m_ThreaderJointPDFDerivatives[threadID] = JointPDFDerivativesType::New(); m_ThreaderJointPDFDerivatives[threadID]->SetRegions( jointPDFDerivativesRegion); m_ThreaderJointPDFDerivatives[threadID]->Allocate(); } } else { m_ThreaderMetricDerivative = new DerivativeType[this->m_NumberOfThreads - 1]; for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { this->m_ThreaderMetricDerivative[threadID] = DerivativeType( this->GetNumberOfParameters() ); } } } /** * From the pre-computed samples, now * fill in the parzen window index locations */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::ComputeFixedImageParzenWindowIndices( FixedImageSampleContainer & samples) { const typename FixedImageSampleContainer::const_iterator end = samples.end(); for( typename FixedImageSampleContainer::iterator iter = samples.begin(); iter != end; ++iter ) { // Determine parzen window arguments (see eqn 6 of Mattes paper [2]). const double windowTerm = static_cast<double>( ( *iter ).value ) / m_FixedImageBinSize - m_FixedImageNormalizedMin; OffsetValueType pindex = static_cast<OffsetValueType>( windowTerm ); // Make sure the extreme values are in valid bins if( pindex < 2 ) { pindex = 2; } else { const OffsetValueType nindex = static_cast<OffsetValueType>( this->m_NumberOfHistogramBins ) - 3; if( pindex > nindex ) { pindex = nindex; } } ( *iter ).valueIndex = pindex; } } template <class TFixedImage, class TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueThreadPreProcess(ThreadIdType threadID, bool withinSampleThread) const { this->Superclass::GetValueThreadPreProcess(threadID, withinSampleThread); if( threadID > 0 ) { memset(m_ThreaderJointPDF[threadID - 1]->GetBufferPointer(), 0, m_JointPDFBufferSize); memset( &( m_ThreaderFixedImageMarginalPDF[( threadID - 1 ) * m_NumberOfHistogramBins] ), 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); } else { // zero-th thread uses the variables directly memset(m_JointPDF->GetBufferPointer(), 0, m_JointPDFBufferSize); memset( m_FixedImageMarginalPDF, 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); } } template <class TFixedImage, class TMovingImage> inline bool MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueThreadProcessSample(ThreadIdType threadID, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue) const { /** * Compute this sample's contribution to the marginal and * joint distributions. * */ if( movingImageValue < m_MovingImageTrueMin ) { return false; } else if( movingImageValue > m_MovingImageTrueMax ) { return false; } // Determine parzen window arguments (see eqn 6 of Mattes paper [2]). const double movingImageParzenWindowTerm = movingImageValue / m_MovingImageBinSize - m_MovingImageNormalizedMin; // Same as floor OffsetValueType movingImageParzenWindowIndex = static_cast<OffsetValueType>( movingImageParzenWindowTerm ); if( movingImageParzenWindowIndex < 2 ) { movingImageParzenWindowIndex = 2; } else { const OffsetValueType nindex = static_cast<OffsetValueType>( this->m_NumberOfHistogramBins ) - 3; if( movingImageParzenWindowIndex > nindex ) { movingImageParzenWindowIndex = nindex; } } const unsigned int fixedImageParzenWindowIndex = this->m_FixedImageSamples[fixedImageSample].valueIndex; if( threadID > 0 ) { m_ThreaderFixedImageMarginalPDF[( threadID - 1 ) * m_NumberOfHistogramBins + fixedImageParzenWindowIndex] += 1; } else { m_FixedImageMarginalPDF[fixedImageParzenWindowIndex] += 1; } // Pointer to affected bin to be updated JointPDFValueType *pdfPtr; if( threadID > 0 ) { pdfPtr = m_ThreaderJointPDF[threadID - 1]->GetBufferPointer() + ( fixedImageParzenWindowIndex * m_ThreaderJointPDF[threadID - 1] ->GetOffsetTable()[1] ); } else { pdfPtr = m_JointPDF->GetBufferPointer() + ( fixedImageParzenWindowIndex * m_JointPDF->GetOffsetTable()[1] ); } // Move the pointer to the first affected bin int pdfMovingIndex = static_cast<int>( movingImageParzenWindowIndex ) - 1; pdfPtr += pdfMovingIndex; const int pdfMovingIndexMax = static_cast<int>( movingImageParzenWindowIndex ) + 2; double movingImageParzenWindowArg = static_cast<double>( pdfMovingIndex ) - movingImageParzenWindowTerm; while( pdfMovingIndex <= pdfMovingIndexMax ) { *( pdfPtr++ ) += static_cast<PDFValueType>( m_CubicBSplineKernel ->Evaluate( movingImageParzenWindowArg) ); movingImageParzenWindowArg += 1; ++pdfMovingIndex; } return true; } template <class TFixedImage, class TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueThreadPostProcess( ThreadIdType threadID, bool itkNotUsed(withinSampleThread) ) const { const int maxI = m_NumberOfHistogramBins * ( m_ThreaderJointPDFEndBin[threadID] - m_ThreaderJointPDFStartBin[threadID] + 1 ); JointPDFValueType * const pdfPtrStart = m_JointPDF->GetBufferPointer() + ( m_ThreaderJointPDFStartBin[threadID] * m_JointPDF->GetOffsetTable()[1] ); const unsigned int tPdfPtrOffset = ( m_ThreaderJointPDFStartBin[threadID] * m_JointPDF->GetOffsetTable()[1] ); for( unsigned int t = 0; t < this->m_NumberOfThreads - 1; t++ ) { JointPDFValueType * pdfPtr = pdfPtrStart; JointPDFValueType const * tPdfPtr = m_ThreaderJointPDF[t]->GetBufferPointer() + tPdfPtrOffset; JointPDFValueType const * const tPdfPtrEnd = tPdfPtr + maxI; // for(i=0; i < maxI; i++) while( tPdfPtr < tPdfPtrEnd ) { *( pdfPtr++ ) += *( tPdfPtr++ ); } for( int i = m_ThreaderJointPDFStartBin[threadID]; i <= m_ThreaderJointPDFEndBin[threadID]; i++ ) { m_FixedImageMarginalPDF[i] += m_ThreaderFixedImageMarginalPDF[ ( t * m_NumberOfHistogramBins ) + i]; } } double jointPDFSum = 0.0; JointPDFValueType const * pdfPtr = pdfPtrStart; for( int i = 0; i < maxI; i++ ) { jointPDFSum += *( pdfPtr++ ); } if( threadID > 0 ) { m_ThreaderJointPDFSum[threadID - 1] = jointPDFSum; } else { m_JointPDFSum = jointPDFSum; } } template <class TFixedImage, class TMovingImage> typename MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::MeasureType MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValue(const ParametersType & parameters) const { // Set up the parameters in the transform this->m_Transform->SetParameters(parameters); this->m_Parameters = parameters; // MUST BE CALLED TO INITIATE PROCESSING this->GetValueMultiThreadedInitiate(); // MUST BE CALLED TO INITIATE PROCESSING this->GetValueMultiThreadedPostProcessInitiate(); for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { m_JointPDFSum += m_ThreaderJointPDFSum[threadID]; } if( m_JointPDFSum == 0.0 ) { itkExceptionMacro("Joint PDF summed to zero\n" << m_JointPDF ); } memset( m_MovingImageMarginalPDF, 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); const double nFactor = 1.0 / m_JointPDFSum; JointPDFValueType *pdfPtr = m_JointPDF->GetBufferPointer(); double fixedPDFSum = 0.0; for( unsigned int i = 0; i < m_NumberOfHistogramBins; i++ ) { fixedPDFSum += m_FixedImageMarginalPDF[i]; PDFValueType * movingMarginalPtr = m_MovingImageMarginalPDF; for( unsigned int j = 0; j < m_NumberOfHistogramBins; j++ ) { *( pdfPtr ) *= nFactor; *( movingMarginalPtr++ ) += *( pdfPtr++ ); } } if( this->m_NumberOfPixelsCounted < this->m_NumberOfFixedImageSamples / 16 ) { itkExceptionMacro("Too many samples map outside moving image buffer: " << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl); } // Normalize the fixed image marginal PDF if( fixedPDFSum == 0.0 ) { itkExceptionMacro("Fixed image marginal PDF summed to zero"); } for( unsigned int bin = 0; bin < m_NumberOfHistogramBins; bin++ ) { m_FixedImageMarginalPDF[bin] /= fixedPDFSum; } /** * Compute the metric by double summation over histogram. */ // Setup pointer to point to the first bin JointPDFValueType *jointPDFPtr = m_JointPDF->GetBufferPointer(); double sum = 0.0; for( unsigned int fixedIndex = 0; fixedIndex < m_NumberOfHistogramBins; ++fixedIndex ) { const double fixedImagePDFValue = m_FixedImageMarginalPDF[fixedIndex]; for( unsigned int movingIndex = 0; movingIndex < m_NumberOfHistogramBins; ++movingIndex, jointPDFPtr++ ) { const double movingImagePDFValue = m_MovingImageMarginalPDF[movingIndex]; const double jointPDFValue = *( jointPDFPtr ); // check for non-zero bin contribution if( jointPDFValue > 1e-16 && movingImagePDFValue > 1e-16 ) { const double pRatio = vcl_log(jointPDFValue / movingImagePDFValue); if( fixedImagePDFValue > 1e-16 ) { sum += jointPDFValue * ( pRatio - vcl_log(fixedImagePDFValue) ); } } // end if-block to check non-zero bin contribution } // end for-loop over moving index } // end for-loop over fixed index return static_cast<MeasureType>( -1.0 * sum ); } template <class TFixedImage, class TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueAndDerivativeThreadPreProcess( ThreadIdType threadID, bool itkNotUsed(withinSampleThread) ) const { if( threadID > 0 ) { memset(m_ThreaderJointPDF[threadID - 1]->GetBufferPointer(), 0, m_JointPDFBufferSize); memset( &( m_ThreaderFixedImageMarginalPDF[( threadID - 1 ) * m_NumberOfHistogramBins] ), 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); if( this->m_UseExplicitPDFDerivatives ) { memset(m_ThreaderJointPDFDerivatives[threadID - 1]->GetBufferPointer(), 0, m_JointPDFDerivativesBufferSize); } } else { memset(m_JointPDF->GetBufferPointer(), 0, m_JointPDFBufferSize); memset( m_FixedImageMarginalPDF, 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); if( this->m_UseExplicitPDFDerivatives ) { memset(m_JointPDFDerivatives->GetBufferPointer(), 0, m_JointPDFDerivativesBufferSize); } } } template <class TFixedImage, class TMovingImage> inline bool MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueAndDerivativeThreadProcessSample(ThreadIdType threadID, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue, const ImageDerivativesType & movingImageGradientValue) const { /** * Compute this sample's contribution to the marginal * and joint distributions. * */ if( movingImageValue < m_MovingImageTrueMin ) { return false; } else if( movingImageValue > m_MovingImageTrueMax ) { return false; } unsigned int fixedImageParzenWindowIndex = this->m_FixedImageSamples[fixedImageSample].valueIndex; // Determine parzen window arguments (see eqn 6 of Mattes paper [2]). double movingImageParzenWindowTerm = movingImageValue / m_MovingImageBinSize - m_MovingImageNormalizedMin; OffsetValueType movingImageParzenWindowIndex = static_cast<OffsetValueType>( movingImageParzenWindowTerm ); // Make sure the extreme values are in valid bins if( movingImageParzenWindowIndex < 2 ) { movingImageParzenWindowIndex = 2; } else { const OffsetValueType nindex = static_cast<OffsetValueType>( this->m_NumberOfHistogramBins ) - 3; if( movingImageParzenWindowIndex > nindex ) { movingImageParzenWindowIndex = nindex; } } // Since a zero-order BSpline (box car) kernel is used for // the fixed image marginal pdf, we need only increment the // fixedImageParzenWindowIndex by value of 1.0. if( threadID > 0 ) { ++m_ThreaderFixedImageMarginalPDF[( threadID - 1 ) * m_NumberOfHistogramBins + fixedImageParzenWindowIndex]; } else { ++m_FixedImageMarginalPDF[fixedImageParzenWindowIndex]; } /** * The region of support of the parzen window determines which bins * of the joint PDF are effected by the pair of image values. * Since we are using a cubic spline for the moving image parzen * window, four bins are effected. The fixed image parzen window is * a zero-order spline (box car) and thus effects only one bin. * * The PDF is arranged so that moving image bins corresponds to the * zero-th (column) dimension and the fixed image bins corresponds * to the first (row) dimension. * */ // Pointer to affected bin to be updated JointPDFValueType *pdfPtr; if( threadID > 0 ) { pdfPtr = m_ThreaderJointPDF[threadID - 1] ->GetBufferPointer() + ( fixedImageParzenWindowIndex * m_NumberOfHistogramBins ); } else { pdfPtr = m_JointPDF->GetBufferPointer() + ( fixedImageParzenWindowIndex * m_NumberOfHistogramBins ); } // Move the pointer to the fist affected bin int pdfMovingIndex = static_cast<int>( movingImageParzenWindowIndex ) - 1; pdfPtr += pdfMovingIndex; const int pdfMovingIndexMax = static_cast<int>( movingImageParzenWindowIndex ) + 2; double movingImageParzenWindowArg = static_cast<double>( pdfMovingIndex ) - static_cast<double>( movingImageParzenWindowTerm ); while( pdfMovingIndex <= pdfMovingIndexMax ) { *( pdfPtr++ ) += static_cast<PDFValueType>( m_CubicBSplineKernel ->Evaluate( movingImageParzenWindowArg) ); if( this->m_UseExplicitPDFDerivatives || this->m_ImplicitDerivativesSecondPass ) { // Compute the cubicBSplineDerivative for later repeated use. const double cubicBSplineDerivativeValue = m_CubicBSplineDerivativeKernel->Evaluate(movingImageParzenWindowArg); // Compute PDF derivative contribution. this->ComputePDFDerivatives(threadID, fixedImageSample, pdfMovingIndex, movingImageGradientValue, cubicBSplineDerivativeValue); } movingImageParzenWindowArg += 1; ++pdfMovingIndex; } return true; } template <class TFixedImage, class TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueAndDerivativeThreadPostProcess(ThreadIdType threadID, bool withinSampleThread) const { this->GetValueThreadPostProcess(threadID, withinSampleThread); if( this->m_UseExplicitPDFDerivatives ) { const unsigned int rowSize = this->m_NumberOfParameters * m_NumberOfHistogramBins; const unsigned int maxI = rowSize * ( m_ThreaderJointPDFEndBin[threadID] - m_ThreaderJointPDFStartBin[threadID] + 1 ); JointPDFDerivativesValueType *const pdfDPtrStart = m_JointPDFDerivatives->GetBufferPointer() + ( m_ThreaderJointPDFStartBin[threadID] * rowSize ); const unsigned int tPdfDPtrOffset = m_ThreaderJointPDFStartBin[threadID] * rowSize; for( unsigned int t = 0; t < this->m_NumberOfThreads - 1; t++ ) { JointPDFDerivativesValueType * pdfDPtr = pdfDPtrStart; JointPDFDerivativesValueType const *tPdfDPtr = m_ThreaderJointPDFDerivatives[t]->GetBufferPointer() + tPdfDPtrOffset; JointPDFDerivativesValueType const * const tPdfDPtrEnd = tPdfDPtr + maxI; // for(i = 0; i < maxI; i++) while( tPdfDPtr < tPdfDPtrEnd ) { *( pdfDPtr++ ) += *( tPdfDPtr++ ); } } const double nFactor = 1.0 / ( m_MovingImageBinSize * this->m_NumberOfPixelsCounted ); JointPDFDerivativesValueType * pdfDPtr = pdfDPtrStart; JointPDFDerivativesValueType const * const tPdfDPtrEnd = pdfDPtrStart + maxI; // for(int i = 0; i < maxI; i++) while( pdfDPtr < tPdfDPtrEnd ) { *( pdfDPtr++ ) *= nFactor; } } } /** * Get the both Value and Derivative Measure */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetValueAndDerivative(const ParametersType & parameters, MeasureType & value, DerivativeType & derivative) const { // Set output values to zero value = NumericTraits<MeasureType>::Zero; if( this->m_UseExplicitPDFDerivatives ) { // Set output values to zero if( derivative.GetSize() != this->m_NumberOfParameters ) { derivative = DerivativeType(this->m_NumberOfParameters); } memset( derivative.data_block(), 0, this->m_NumberOfParameters * sizeof( double ) ); } else { this->m_PRatioArray.Fill(0.0); this->m_MetricDerivative.Fill(NumericTraits<MeasureType>::Zero); for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { this->m_ThreaderMetricDerivative[threadID].Fill(NumericTraits<MeasureType>::Zero); } this->m_ImplicitDerivativesSecondPass = false; } // Set up the parameters in the transform this->m_Transform->SetParameters(parameters); this->m_Parameters = parameters; // MUST BE CALLED TO INITIATE PROCESSING ON SAMPLES this->GetValueAndDerivativeMultiThreadedInitiate(); // CALL IF DOING THREADED POST PROCESSING this->GetValueAndDerivativeMultiThreadedPostProcessInitiate(); for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads - 1; threadID++ ) { m_JointPDFSum += m_ThreaderJointPDFSum[threadID]; } if( m_JointPDFSum == 0.0 ) { itkExceptionMacro("Joint PDF summed to zero"); } memset( m_MovingImageMarginalPDF, 0, m_NumberOfHistogramBins * sizeof( PDFValueType ) ); double fixedPDFSum = 0.0; const double normalizationFactor = 1.0 / m_JointPDFSum; JointPDFValueType *pdfPtr = m_JointPDF->GetBufferPointer(); for( unsigned int i = 0; i < m_NumberOfHistogramBins; i++ ) { fixedPDFSum += m_FixedImageMarginalPDF[i]; PDFValueType * movingMarginalPtr = m_MovingImageMarginalPDF; for( unsigned int j = 0; j < m_NumberOfHistogramBins; j++ ) { *( pdfPtr ) *= normalizationFactor; *( movingMarginalPtr++ ) += *( pdfPtr++ ); } } if( this->m_NumberOfPixelsCounted < this->m_NumberOfFixedImageSamples / 16 ) { itkExceptionMacro("Too many samples map outside moving image buffer: " << this->m_NumberOfPixelsCounted << " / " << this->m_NumberOfFixedImageSamples << std::endl); } // Normalize the fixed image marginal PDF if( fixedPDFSum == 0.0 ) { itkExceptionMacro("Fixed image marginal PDF summed to zero"); } for( unsigned int bin = 0; bin < m_NumberOfHistogramBins; bin++ ) { m_FixedImageMarginalPDF[bin] /= fixedPDFSum; } /** * Compute the metric by double summation over histogram. */ // Setup pointer to point to the first bin JointPDFValueType *jointPDFPtr = m_JointPDF->GetBufferPointer(); // Initialize sum to zero double sum = 0.0; const double nFactor = 1.0 / ( m_MovingImageBinSize * this->m_NumberOfPixelsCounted ); for( unsigned int fixedIndex = 0; fixedIndex < m_NumberOfHistogramBins; ++fixedIndex ) { const double fixedImagePDFValue = m_FixedImageMarginalPDF[fixedIndex]; for( unsigned int movingIndex = 0; movingIndex < m_NumberOfHistogramBins; ++movingIndex, jointPDFPtr++ ) { const double movingImagePDFValue = m_MovingImageMarginalPDF[movingIndex]; const double jointPDFValue = *( jointPDFPtr ); // check for non-zero bin contribution if( jointPDFValue > 1e-16 && movingImagePDFValue > 1e-16 ) { const double pRatio = vcl_log(jointPDFValue / movingImagePDFValue); if( fixedImagePDFValue > 1e-16 ) { sum += jointPDFValue * ( pRatio - vcl_log(fixedImagePDFValue) ); } if( this->m_UseExplicitPDFDerivatives ) { // move joint pdf derivative pointer to the right position JointPDFValueType const * derivPtr = m_JointPDFDerivatives->GetBufferPointer() + ( fixedIndex * m_JointPDFDerivatives->GetOffsetTable()[2] ) + ( movingIndex * m_JointPDFDerivatives->GetOffsetTable()[1] ); for( unsigned int parameter = 0; parameter < this->m_NumberOfParameters; ++parameter, derivPtr++ ) { // Ref: eqn 23 of Thevenaz & Unser paper [3] derivative[parameter] -= ( *derivPtr ) * pRatio; } // end for-loop over parameters } else { this->m_PRatioArray[fixedIndex][movingIndex] = pRatio * nFactor; } } // end if-block to check non-zero bin contribution } // end for-loop over moving index } // end for-loop over fixed index if( !( this->m_UseExplicitPDFDerivatives ) ) { // Second pass: This one is done for accumulating the contributions // to the derivative array. // this->m_ImplicitDerivativesSecondPass = true; // // MUST BE CALLED TO INITIATE PROCESSING ON SAMPLES this->GetValueAndDerivativeMultiThreadedInitiate(); // CALL IF DOING THREADED POST PROCESSING this->GetValueAndDerivativeMultiThreadedPostProcessInitiate(); // Consolidate the contributions from each one of the threads to the total // derivative. for( unsigned int t = 0; t < this->m_NumberOfThreads - 1; t++ ) { DerivativeType const * const source = &( this->m_ThreaderMetricDerivative[t] ); for( unsigned int pp = 0; pp < this->m_NumberOfParameters; pp++ ) { this->m_MetricDerivative[pp] += ( *source )[pp]; } } derivative = this->m_MetricDerivative; } value = static_cast<MeasureType>( -1.0 * sum ); } /** * Get the match measure derivative */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::GetDerivative(const ParametersType & parameters, DerivativeType & derivative) const { MeasureType value; // call the combined version this->GetValueAndDerivative(parameters, value, derivative); } /** * Compute PDF derivatives contribution for each parameter */ template <class TFixedImage, class TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> ::ComputePDFDerivatives(ThreadIdType threadID, unsigned int sampleNumber, int pdfMovingIndex, const ImageDerivativesType & movingImageGradientValue, double cubicBSplineDerivativeValue) const { // Update bins in the PDF derivatives for the current intensity pair // Could pre-compute JointPDFDerivativesValueType *derivPtr; double precomputedWeight = 0.0; const int pdfFixedIndex = this->m_FixedImageSamples[sampleNumber].valueIndex; DerivativeType *derivativeHelperArray = NULL; if( this->m_UseExplicitPDFDerivatives ) { if( threadID > 0 ) { derivPtr = m_ThreaderJointPDFDerivatives[threadID - 1]->GetBufferPointer() + ( pdfFixedIndex * m_JointPDFDerivatives->GetOffsetTable()[2] ) + ( pdfMovingIndex * m_JointPDFDerivatives->GetOffsetTable()[1] ); } else { derivPtr = m_JointPDFDerivatives->GetBufferPointer() + ( pdfFixedIndex * m_JointPDFDerivatives->GetOffsetTable()[2] ) + ( pdfMovingIndex * m_JointPDFDerivatives->GetOffsetTable()[1] ); } } else { derivPtr = 0; // Recover the precomputed weight for this specific PDF bin precomputedWeight = this->m_PRatioArray[pdfFixedIndex][pdfMovingIndex]; if( threadID > 0 ) { derivativeHelperArray = &( this->m_ThreaderMetricDerivative[threadID - 1] ); } else { derivativeHelperArray = &( this->m_MetricDerivative ); } } if( !this->m_TransformIsBSpline ) { /** * Generic version which works for all transforms. */ // Compute the transform Jacobian. // Should pre-compute typedef typename TransformType::JacobianType JacobianType; // Need to use one of the threader transforms if we're // not in thread 0. // // Use a raw pointer here to avoid the overhead of smart pointers. // For instance, Register and UnRegister have mutex locks around // the reference counts. TransformType *transform; if( threadID > 0 ) { transform = this->m_ThreaderTransform[threadID - 1]; } else { transform = this->m_Transform; } JacobianType jacobian; transform->ComputeJacobianWithRespectToParameters( this->m_FixedImageSamples[sampleNumber].point, jacobian); for( unsigned int mu = 0; mu < this->m_NumberOfParameters; mu++ ) { double innerProduct = 0.0; for( unsigned int dim = 0; dim < Superclass::FixedImageDimension; dim++ ) { innerProduct += jacobian[dim][mu] * movingImageGradientValue[dim]; } const double derivativeContribution = innerProduct * cubicBSplineDerivativeValue; if( this->m_UseExplicitPDFDerivatives ) { *( derivPtr ) -= derivativeContribution; ++derivPtr; } else { ( *derivativeHelperArray )[mu] += precomputedWeight * derivativeContribution; } } } else { const WeightsValueType *weights = NULL; const IndexValueType * indices = NULL; BSplineTransformWeightsType * weightsHelper = NULL; BSplineTransformIndexArrayType *indicesHelper = NULL; if( this->m_UseCachingOfBSplineWeights ) { // // If the transform is of type BSplineTransform, we can obtain // a speed up by only processing the affected parameters. Note that // these pointers are just pointing to pre-allocated rows of the caching // arrays. There is therefore, no need to free this memory. // weights = this->m_BSplineTransformWeightsArray[sampleNumber]; indices = this->m_BSplineTransformIndicesArray[sampleNumber]; } else { if( threadID > 0 ) { weightsHelper = &( this->m_ThreaderBSplineTransformWeights[threadID - 1] ); indicesHelper = &( this->m_ThreaderBSplineTransformIndices[threadID - 1] ); } else { weightsHelper = &( this->m_BSplineTransformWeights ); indicesHelper = &( this->m_BSplineTransformIndices ); } /** Get Jacobian at a point. A very specialized function just for BSplines */ this->m_BSplineTransform->ComputeJacobianFromBSplineWeightsWithRespectToPosition( this->m_FixedImageSamples[sampleNumber].point, *weightsHelper, *indicesHelper); } for( unsigned int dim = 0; dim < Superclass::FixedImageDimension; dim++ ) { for( unsigned int mu = 0; mu < this->m_NumBSplineWeights; mu++ ) { /* The array weights contains the Jacobian values in a 1-D array * (because for each parameter the Jacobian is non-zero in only 1 of the * possible dimensions) which is multiplied by the moving image * gradient. */ double innerProduct; int parameterIndex; if( this->m_UseCachingOfBSplineWeights ) { innerProduct = movingImageGradientValue[dim] * weights[mu]; parameterIndex = indices[mu] + this->m_BSplineParametersOffset[dim]; } else { innerProduct = movingImageGradientValue[dim] * ( *weightsHelper )[mu]; parameterIndex = ( *indicesHelper )[mu] + this->m_BSplineParametersOffset[dim]; } const double derivativeContribution = innerProduct * cubicBSplineDerivativeValue; if( this->m_UseExplicitPDFDerivatives ) { JointPDFValueType * const ptr = derivPtr + parameterIndex; *( ptr ) -= derivativeContribution; } else { ( *derivativeHelperArray )[parameterIndex] += precomputedWeight * derivativeContribution; } } // end mu for loop } // end dim for loop } // end if-block transform is BSpline } } // end namespace itk #endif
34.216981
121
0.672775
CapeDrew
12247c340acb0ba8f2462878f262227e9a4abad3
5,427
cpp
C++
libraries/C6502Cpu/CVanguardGame.cpp
porchio/arduino-mega-ict
dcc4b37cdbae2966d5736589bea776bf286df9ee
[ "BSD-2-Clause" ]
19
2016-01-14T10:54:07.000Z
2021-06-29T17:47:54.000Z
libraries/C6502Cpu/CVanguardGame.cpp
LabRat3K/arduino-mega-ict
b5f46ee41fc088c4ef80e3dcfb045685e6b89e94
[ "BSD-2-Clause" ]
11
2016-01-20T23:30:34.000Z
2021-05-22T18:06:55.000Z
libraries/C6502Cpu/CVanguardGame.cpp
LabRat3K/arduino-mega-ict
b5f46ee41fc088c4ef80e3dcfb045685e6b89e94
[ "BSD-2-Clause" ]
16
2016-01-03T18:29:09.000Z
2021-08-18T14:09:36.000Z
// // Copyright (c) 2020, Paul R. Swan // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT 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. // #include "CVanguardGame.h" // 01 02 04 08 10 20 40 80 100 200 400 800 static const UINT16 s_romData2n_1[] = {0x6f,0xa9,0x9d,0x10,0x8e,0x8a,0x02,0x02,0xba,0x02,0x60,0xc9}; // 1 static const UINT16 s_romData2n_2[] = {0xc9,0x06,0x60,0x34,0x00,0x48,0x32,0x85,0x38,0x68,0x54,0xc9}; // 2 static const UINT16 s_romData2n_3[] = {0x29,0x03,0xbd,0x12,0x10,0x60,0xb0,0x90,0x51,0x51,0x51,0x4c}; // 3 static const UINT16 s_romData2n_4[] = {0x48,0x8a,0x98,0xb5,0xe6,0x50,0x20,0x68,0x5f,0xed,0x48,0x3b}; // 4 static const UINT16 s_romData2n_5[] = {0x7c,0xc2,0x86,0x02,0x62,0x08,0x0c,0x9e,0xf8,0x00,0x88,0x38}; // 5 static const UINT16 s_romData2n_6[] = {0x19,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x32}; // 6 static const UINT16 s_romData2n_7[] = {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0xd4}; // 7 static const UINT16 s_romData2n_8[] = {0x01,0xd1,0xd1,0xd1,0xd7,0xd2,0xc9,0x30,0xc4,0x01,0x20,0x14}; // 8 // // Centuri Set 1 // static const ROM_REGION s_romRegionCenturiSet1[] PROGMEM = { // {NO_BANK_SWITCH, 0x4000, 0x1000, s_romData2n_1, 0x6a29e354, " 1 "}, // 1 {NO_BANK_SWITCH, 0x5000, 0x1000, s_romData2n_2, 0x302bba54, " 2 "}, // 2 {NO_BANK_SWITCH, 0x6000, 0x1000, s_romData2n_3, 0x424755f6, " 3 "}, // 3 {NO_BANK_SWITCH, 0x7000, 0x1000, s_romData2n_4, 0x770f9714, " 4 "}, // 4CN {NO_BANK_SWITCH, 0x8000, 0x1000, s_romData2n_5, 0x3445cba6, " 5 "}, // 5C {NO_BANK_SWITCH, 0x9000, 0x1000, s_romData2n_6, 0x0d5b47d0, " 6 "}, // 6 {NO_BANK_SWITCH, 0xA000, 0x1000, s_romData2n_7, 0x8549b8f8, " 7 "}, // 7 {NO_BANK_SWITCH, 0xB000, 0x1000, s_romData2n_8, 0x4b825bc8, " 8 "}, // 8CS {NO_BANK_SWITCH, 0xF000, 0x1000, s_romData2n_5, 0x3445cba6, " 5 "}, // 5C, mirror {0} }; // end of list // // German Set 1 // static const ROM_REGION s_romRegionGermanSet1[] PROGMEM = { // {NO_BANK_SWITCH, 0x4000, 0x1000, s_romData2n_1, 0x6a29e354, " 1 "}, // 1 {NO_BANK_SWITCH, 0x5000, 0x1000, s_romData2n_2, 0x302bba54, " 2 "}, // 2 {NO_BANK_SWITCH, 0x6000, 0x1000, s_romData2n_3, 0x424755f6, " 3 "}, // 3 {NO_BANK_SWITCH, 0x7000, 0x1000, s_romData2n_4, 0x4a82306a, " 4 "}, // 4G {NO_BANK_SWITCH, 0x8000, 0x1000, s_romData2n_5, 0xfde157d0, " 5 "}, // 5 {NO_BANK_SWITCH, 0x9000, 0x1000, s_romData2n_6, 0x0d5b47d0, " 6 "}, // 6 {NO_BANK_SWITCH, 0xA000, 0x1000, s_romData2n_7, 0x8549b8f8, " 7 "}, // 7 {NO_BANK_SWITCH, 0xB000, 0x1000, s_romData2n_8, 0xabe5fa3f, " 8 "}, // 8S {NO_BANK_SWITCH, 0xF000, 0x1000, s_romData2n_5, 0xfde157d0, " 5 "}, // 5, mirror {0} }; // end of list IGame* CVanguardGame::createInstanceCenturiSet1( ) { return (new CVanguardGame(s_romRegionCenturiSet1)); } IGame* CVanguardGame::createInstanceGermanSet1( ) { return (new CVanguardGame(s_romRegionGermanSet1)); } CVanguardGame::CVanguardGame( const ROM_REGION *romRegion ) : CVanguardBaseGame( romRegion ) { }
60.3
141
0.563663
porchio
1224e1747e7a6831bef92ba65de97dbd347696c1
14,568
hpp
C++
include/cps/Socket.hpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
1
2015-09-22T10:32:36.000Z
2015-09-22T10:32:36.000Z
include/cps/Socket.hpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
null
null
null
include/cps/Socket.hpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
null
null
null
#ifndef CPS_SOCKET_HPP_ #define CPS_SOCKET_HPP_ #include <string> #include <vector> #include "Exception.hpp" #include "Utils.hpp" #include "boost/bind.hpp" #include "boost/lambda/lambda.hpp" namespace CPS { #ifndef USE_HEADER_ONLY_ASIO #include "boost/asio.hpp" using namespace boost; #else #define ASIO_DISABLE_THREADS // To disable linking errors #include "asio.hpp" #endif class AbstractSocket { public: AbstractSocket(asio::io_service &io_service) : io_service(io_service), deadline(io_service), connected(false) { connectTimeout = 5; sendTimeout = 30; recieveTimeout = 60; // No deadline is required until the first socket operation is started. We // set the deadline to positive infinity so that the actor takes no action // until a specific deadline is set. deadline.expires_at(boost::posix_time::pos_infin); // Start the persistent actor that checks for deadline expiry. check_deadline(); } virtual ~AbstractSocket() { } virtual void connect(const std::string &host, int port) = 0; virtual std::vector<unsigned char> send(const std::string &data) = 0; virtual std::vector<unsigned char> read() = 0; bool isConnected() { return connected; } void check_deadline() { // Check whether the deadline has passed. We compare the deadline against // the current time since a new asynchronous operation may have moved the // deadline before this actor had a chance to run. if (deadline.expires_at() <= asio::deadline_timer::traits_type::now()) { // The deadline has passed. The socket is closed so that any outstanding // asynchronous operations are cancelled. This allows the blocked // connect(), read_line() or write_line() functions to return. error = asio::error::timed_out; handle_timer_expiration(); // There is no longer an active deadline. The expire is set to positive // infinity so that the actor takes no action until a new deadline is set. deadline.expires_at(boost::posix_time::pos_infin); } // Put the actor back::asio to sleep. deadline.async_wait(boost::bind(&AbstractSocket::check_deadline, this)); } virtual void handle_timer_expiration() { // Nothing to do here.. Should be overloaded in child classes } int connectTimeout; int sendTimeout; int recieveTimeout; protected: asio::io_service &io_service; asio::deadline_timer deadline; #ifndef USE_HEADER_ONLY_ASIO boost::system::error_code error; #else asio::error_code error; #endif bool connected; }; class TcpSocket: public AbstractSocket { public: TcpSocket(asio::io_service &io_service) : AbstractSocket(io_service), socket(io_service) { } virtual ~TcpSocket() { socket.close(); connected = false; } virtual void connect(const std::string &host, int port) { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(connectTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; asio::ip::tcp::resolver resolver(io_service); asio::ip::tcp::resolver::query query(host, Utils::toString(port)); endpoint_iterator = resolver.resolve(query); // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. socket.async_connect(*endpoint_iterator, boost::lambda::var(error) = boost::lambda::_1); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); // Determine whether a connection was successfully established. The // deadline actor may have had a chance to run and close our socket, even // though the connect operation notionally succeeded. Therefore we must // check whether the socket is still open before deciding if we succeeded // or failed. if (error || !socket.is_open()) { throw CPS::Exception("Could not connect. " + error.message()); } connected = true; } virtual std::vector<unsigned char> send(const std::string &data) { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(sendTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. asio::async_write(socket, asio::buffer(data, data.size()), boost::lambda::var(error) = boost::lambda::_1); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open()) { throw CPS::Exception("Could not send message. " + error.message()); } return read(); } virtual std::vector<unsigned char> read() { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(recieveTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; std::vector<unsigned char> reply(8); size_t len = 0, content_len = 0; socket.async_read_some(asio::buffer(reply), (boost::lambda::var(error) = boost::lambda::_1, boost::lambda::var(len) = boost::lambda::_2)); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open() || len != 8 || !(reply[0] == 0x09 && reply[1] == 0x09 && reply[2] == 0x00 && reply[3] == 0x00)) { throw CPS::Exception("Invalid header received. " + error.message()); } content_len = (reply[4]) | (reply[5] << 8) | (reply[6] << 16) | (reply[7] << 24); // Read rest of message error = asio::error::would_block; reply.clear(); reply.resize(content_len); asio::async_read(socket, asio::buffer(reply), (boost::lambda::var(error) = boost::lambda::_1, boost::lambda::var(len) = boost::lambda::_2)); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open() || len != content_len) { throw CPS::Exception("Could not read message. " + error.message()); } return reply; } void handle_timer_expiration() { socket.close(); connected = false; } protected: asio::ip::tcp::socket socket; asio::ip::tcp::resolver::iterator endpoint_iterator; }; #ifdef BOOST_ASIO_HAS_LOCAL_SOCKETS class UnixSocket: public AbstractSocket { public: UnixSocket(asio::io_service &io_service) : AbstractSocket(io_service), socket(io_service) { } virtual ~UnixSocket() { socket.close(); } virtual void connect(const std::string &host, int port) { asio::local::stream_protocol::endpoint ep(host); // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(connectTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. socket.async_connect(ep, boost::lambda::var(error) = boost::lambda::_1); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); // Determine whether a connection was successfully established. The // deadline actor may have had a chance to run and close our socket, even // though the connect operation notionally succeeded. Therefore we must // check whether the socket is still open before deciding if we succeeded // or failed. if (error || !socket.is_open()) { throw CPS::Exception("Could not connect. " + error.message()); } connected = true; } virtual std::vector<unsigned char> send(const std::string &data) { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(sendTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; // Start the asynchronous operation itself. The boost::lambda function // object is used as a callback and will update the ec variable when the // operation completes. asio::async_write(socket, asio::buffer(data, data.size()), boost::lambda::var(error) = boost::lambda::_1); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open()) { throw CPS::Exception("Could not send message. " + error.message()); } return read(); } virtual std::vector<unsigned char> read() { // Set a deadline for the asynchronous operation. deadline.expires_from_now(boost::posix_time::seconds(recieveTimeout)); // Set up the variable that receives the result of the asynchronous // operation. The error code is set to would_block to signal that the // operation is incomplete. Asio guarantees that its asynchronous // operations will never fail with would_block, so any other value in // ec indicates completion. error = asio::error::would_block; std::vector<unsigned char> reply(8); size_t len = 0, content_len = 0; socket.async_read_some(asio::buffer(reply), (boost::lambda::var(error) = boost::lambda::_1, boost::lambda::var(len) = boost::lambda::_2)); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open() || len != 8 || !(reply[0] == 0x09 && reply[1] == 0x09 && reply[2] == 0x00 && reply[3] == 0x00)) { throw CPS::Exception("Invalid header received. " + error.message()); } content_len = (reply[4]) | (reply[5] << 8) | (reply[6] << 16) | (reply[7] << 24); // Read rest of message error = asio::error::would_block; reply.clear(); reply.resize(content_len); asio::async_read(socket, asio::buffer(reply), (boost::lambda::var(error) = boost::lambda::_1, boost::lambda::var(len) = boost::lambda::_2)); // Block until the asynchronous operation has completed. do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open() || len != content_len) { throw CPS::Exception("Could not read message. " + error.message()); } return reply; } void handle_timer_expiration() { socket.close(error); connected = false; } protected: asio::local::stream_protocol::socket socket; }; #endif class HttpSocket: public TcpSocket { public: HttpSocket(asio::io_service &io_service, const std::string &host, int port, const std::string &path) : TcpSocket(io_service) { this->host = host; this->port = port; this->path = path; } virtual ~HttpSocket() { } virtual void connect(const std::string &host, int port) { deadline.expires_from_now(boost::posix_time::seconds(connectTimeout)); error = asio::error::would_block; asio::ip::tcp::resolver resolver(io_service); asio::ip::tcp::resolver::query query(host, Utils::toString(port)); endpoint_iterator = resolver.resolve(query); socket.async_connect(*endpoint_iterator, boost::lambda::var(error) = boost::lambda::_1); do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open()) { throw CPS::Exception("Could not connect. " + error.message()); } connected = true; } virtual std::vector<unsigned char> send(const std::string &data) { deadline.expires_from_now(boost::posix_time::seconds(sendTimeout)); error = asio::error::would_block; // Create post headers std::string header = ""; header += "POST " + path + " HTTP/1.0\r\n"; header += "Host: " + host + ":" + Utils::toString(port) + "\r\n"; header += "Content-Length: " + Utils::toString(data.size()) + "\r\n"; header += "Connection: close\r\n"; header += "\r\n"; // Send headers asio::async_write(socket, asio::buffer(header, header.size()), boost::lambda::var(error) = boost::lambda::_1); // Send data asio::async_write(socket, asio::buffer(data, data.size()), boost::lambda::var(error) = boost::lambda::_1); do io_service.run_one(); while (error == asio::error::would_block); if (error || !socket.is_open()) { throw CPS::Exception("Could not send message. " + error.message()); } return this->read(); } virtual std::vector<unsigned char> read() { asio::streambuf response; #ifndef USE_HEADER_ONLY_ASIO boost::system::error_code err; #else asio::error_code err; #endif std::vector <unsigned char> reply; int read = 0; bool past_header = false; while ((read = asio::read(socket, response, asio::transfer_at_least(1), err)) != 0) { char cbuf[response.size() + 1]; int rc = response.sgetn(cbuf, sizeof(cbuf)); if (past_header == false) { char *data; if ((data = strstr(cbuf, "\r\n\r\n")) != NULL) { reply.insert(reply.end(), data + 4, cbuf + rc); past_header = true; } } else { reply.insert(reply.end(), cbuf, cbuf + rc); } } if (err != asio::error::eof) BOOST_THROW_EXCEPTION(Exception("Problem reading from socket")); return reply; } public: std::string host; int port; std::string path; protected: asio::ip::tcp::resolver::iterator endpoint_iterator; }; } #endif //#ifndef CPS_SOCKET_HPP_
34.521327
112
0.705656
clusterpoint
1225fb25b18b3ca12ea5812dbd8dc4b07db48775
4,923
cpp
C++
unittests/core/test_sstring_view_archive.cpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
unittests/core/test_sstring_view_archive.cpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
unittests/core/test_sstring_view_archive.cpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- unittests/core/test_sstring_view_archive.cpp -----------------------===// //* _ _ _ * //* ___ ___| |_ _ __(_)_ __ __ _ __ _(_) _____ __ * //* / __/ __| __| '__| | '_ \ / _` | \ \ / / |/ _ \ \ /\ / / * //* \__ \__ \ |_| | | | | | | (_| | \ V /| | __/\ V V / * //* |___/___/\__|_| |_|_| |_|\__, | \_/ |_|\___| \_/\_/ * //* |___/ * //* _ _ * //* __ _ _ __ ___| |__ (_)_ _____ * //* / _` | '__/ __| '_ \| \ \ / / _ \ * //* | (_| | | | (__| | | | |\ V / __/ * //* \__,_|_| \___|_| |_|_| \_/ \___| * //* * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "pstore/core/sstring_view_archive.hpp" #include <vector> #include <gmock/gmock.h> #include "pstore/core/transaction.hpp" #include "pstore/core/db_archive.hpp" #include "pstore/support/assert.hpp" #include "empty_store.hpp" namespace { using shared_sstring_view = pstore::sstring_view<std::shared_ptr<char const>>; class SStringViewArchive : public EmptyStore { public: SStringViewArchive () : db_{this->file ()} { db_.set_vacuum_mode (pstore::database::vacuum_mode::disabled); } protected: pstore::database db_; pstore::address current_pos (pstore::transaction_base & t) const; std::vector<char> as_vector (pstore::typed_address<char> first, pstore::typed_address<char> last) const; static shared_sstring_view make_shared_sstring_view (char const * s); }; shared_sstring_view SStringViewArchive::make_shared_sstring_view (char const * s) { auto const length = std::strlen (s); auto ptr = std::shared_ptr<char> (new char[length], [] (char * p) { delete[] p; }); std::copy (s, s + length, ptr.get ()); return {ptr, length}; } pstore::address SStringViewArchive::current_pos (pstore::transaction_base & t) const { return t.allocate (0U, 1U); // allocate 0 bytes to get the current EOF. } std::vector<char> SStringViewArchive::as_vector (pstore::typed_address<char> first, pstore::typed_address<char> last) const { PSTORE_ASSERT (last >= first); if (last < first) { return {}; } // Get the chars within the specified address range. std::size_t const num_chars = last.absolute () - first.absolute (); auto ptr = db_.getro (first, num_chars); // Convert them to a vector so that they're easy to compare. return {ptr.get (), ptr.get () + num_chars}; } } // namespace TEST_F (SStringViewArchive, Empty) { auto str = make_shared_sstring_view (""); // Append 'str'' to the store (we don't need to have committed the transaction to be able to // access its contents). mock_mutex mutex; auto transaction = begin (db_, std::unique_lock<mock_mutex>{mutex}); auto const first = pstore::typed_address<char> (this->current_pos (transaction)); pstore::serialize::write (pstore::serialize::archive::make_writer (transaction), str); auto const last = pstore::typed_address<char> (this->current_pos (transaction)); EXPECT_THAT (as_vector (first, last), ::testing::ElementsAre ('\x1', '\x0')); // Now try reading it back and compare to the original string. { using namespace pstore::serialize; shared_sstring_view const actual = read<shared_sstring_view> (archive::database_reader{db_, first.to_address ()}); EXPECT_EQ (actual, ""); } } TEST_F (SStringViewArchive, WriteHello) { auto str = make_shared_sstring_view ("hello"); mock_mutex mutex; auto transaction = begin (db_, std::unique_lock<mock_mutex>{mutex}); auto const first = pstore::typed_address<char> (this->current_pos (transaction)); { auto writer = pstore::serialize::archive::make_writer (transaction); pstore::serialize::write (writer, str); } auto const last = pstore::typed_address<char> (this->current_pos (transaction)); EXPECT_THAT (as_vector (first, last), ::testing::ElementsAre ('\xb', '\x0', 'h', 'e', 'l', 'l', 'o')); { auto reader = pstore::serialize::archive::database_reader{db_, first.to_address ()}; shared_sstring_view const actual = pstore::serialize::read<shared_sstring_view> (reader); EXPECT_EQ (actual, "hello"); } }
41.369748
97
0.566118
paulhuggett
1226c5c4d2478de9e19e9e3aaa71303d0ea0d6ed
917
cpp
C++
src/FalconEngine/Core/GameEngineProfiler.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
6
2017-04-17T12:34:57.000Z
2019-10-19T23:29:59.000Z
src/FalconEngine/Core/GameEngineProfiler.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
null
null
null
src/FalconEngine/Core/GameEngineProfiler.cpp
Lywx/FalconEngine
c4d1fed789218d1994908b8dbbcd6c01961f9ef2
[ "MIT" ]
2
2019-12-30T08:28:04.000Z
2020-08-05T09:58:53.000Z
#include <FalconEngine/Core/GameEngineProfiler.h> namespace FalconEngine { /************************************************************************/ /* Public Members */ /************************************************************************/ void GameEngineProfiler::Destroy() { } void GameEngineProfiler::Initialize() { } double GameEngineProfiler::GetLastFrameElapsedMillisecond() const { return mLastFrameElapsedMillisecond; } double GameEngineProfiler::GetLastFrameFps() const { return mLastFrameFps; } double GameEngineProfiler::GetLastFrameUpdateTotalCount() const { return mLastFrameUpdateTotalCount; } double GameEngineProfiler::GetLastUpdateElapsedMillisecond() const { return mLastUpdateElapsedMillisecond; } double GameEngineProfiler::GetLastRenderElapsedMillisecond() const { return mLastRenderElapsedMillisecond; } }
18.34
74
0.623773
Lywx
1229c7a143db8848bfec305d4389b32e1349b437
6,075
cpp
C++
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/BreathingCircuit/Simulator.cpp
raavilagoo/Test
e2de25cc4b6fcbffe3f98f4a7ce1644fa8b6bb16
[ "Apache-2.0" ]
null
null
null
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/BreathingCircuit/Simulator.cpp
raavilagoo/Test
e2de25cc4b6fcbffe3f98f4a7ce1644fa8b6bb16
[ "Apache-2.0" ]
null
null
null
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/BreathingCircuit/Simulator.cpp
raavilagoo/Test
e2de25cc4b6fcbffe3f98f4a7ce1644fa8b6bb16
[ "Apache-2.0" ]
null
null
null
/* * BreathingCircuit.tpp * * Created on: June 6, 2020 * Author: Ethan Li */ #include "Pufferfish/Driver/BreathingCircuit/Simulator.h" #include "Pufferfish/Util/Timeouts.h" namespace Pufferfish::Driver::BreathingCircuit { // Simulator void Simulator::input_clock(uint32_t current_time) { if (initial_time_ == 0) { initial_time_ = current_time; } if (update_needed()) { previous_time_ = current_time_; } current_time_ = current_time - initial_time_; } uint32_t Simulator::current_time() const { return current_time_; } void Simulator::transform_fio2(float params_fio2, float &sensor_meas_fio2) { sensor_meas_fio2 += (params_fio2 - sensor_meas_fio2) * fio2_responsiveness / sensor_update_interval; } bool Simulator::update_needed() const { return !Util::within_timeout(previous_time_, sensor_update_interval, current_time_); } // PC-AC Simulator void PCACSimulator::transform( const Parameters &parameters, const SensorVars & /*sensor_vars*/, SensorMeasurements &sensor_measurements, CycleMeasurements &cycle_measurements) { if (!update_needed()) { return; } if (!parameters.ventilating || parameters.mode != VentilationMode_pc_ac) { return; } // Timing sensor_measurements.time = current_time(); uint32_t cycle_period = minute_duration / parameters.rr; if (!Util::within_timeout(cycle_start_time_, cycle_period, current_time())) { init_cycle(cycle_period, parameters, sensor_measurements); transform_cycle_measurements(parameters, cycle_measurements); } if (Util::within_timeout(cycle_start_time_, insp_period_, current_time())) { transform_airway_inspiratory(parameters, sensor_measurements); } else { transform_airway_expiratory(parameters, sensor_measurements); } transform_fio2(parameters.fio2, sensor_measurements.fio2); } void PCACSimulator::init_cycle( uint32_t cycle_period, const Parameters &parameters, SensorMeasurements &sensor_measurements) { cycle_start_time_ = current_time(); sensor_measurements.flow = insp_init_flow_rate; sensor_measurements.volume = 0; insp_period_ = cycle_period / (1 + 1.0 / parameters.ie); sensor_measurements.cycle += 1; } void PCACSimulator::transform_cycle_measurements( const Parameters &parameters, CycleMeasurements &cycle_measurements) { cycle_measurements.time = current_time(); cycle_measurements.rr = parameters.rr; cycle_measurements.peep = parameters.peep; cycle_measurements.pip = parameters.pip; } void PCACSimulator::transform_airway_inspiratory( const Parameters &parameters, SensorMeasurements &sensor_measurements) { sensor_measurements.paw += (parameters.pip - sensor_measurements.paw) * insp_responsiveness / time_step(); sensor_measurements.flow *= (1 - insp_flow_responsiveness / time_step()); sensor_measurements.volume += static_cast<float>(sensor_measurements.flow / min_per_s * time_step()); } void PCACSimulator::transform_airway_expiratory( const Parameters &parameters, SensorMeasurements &sensor_measurements) { sensor_measurements.paw += (parameters.peep - sensor_measurements.paw) * exp_responsiveness / time_step(); if (sensor_measurements.flow >= 0) { sensor_measurements.flow = exp_init_flow_rate; } else { sensor_measurements.flow *= (1 - exp_flow_responsiveness / time_step()); } sensor_measurements.volume += sensor_measurements.flow / min_per_s * time_step(); } // HFNC Simulator void HFNCSimulator::transform( const Parameters &parameters, const SensorVars &sensor_vars, SensorMeasurements &sensor_measurements, // cycle_measurements is part of the Simulator interface // NOLINTNEXTLINE(misc-unused-parameters) CycleMeasurements & /*cycle_measurements*/) { if (!update_needed()) { return; } if (!parameters.ventilating || parameters.mode != VentilationMode_hfnc) { return; } // Timing sensor_measurements.time = current_time(); transform_flow(parameters.flow, sensor_measurements.flow); if (sensor_vars.po2 != 0) { // simulate FiO2 from pO2 if pO2 is available sensor_measurements.fio2 = sensor_vars.po2 * po2_fio2_conversion; } else if (std::abs(sensor_vars.flow_air + sensor_vars.flow_o2) >= 1) { // simulate FiO2 from relative flow rates if flow rates are available float flow_o2_ratio = sensor_vars.flow_o2 / (sensor_vars.flow_air + sensor_vars.flow_o2); float inferred_fio2 = fio2_min * (1 - flow_o2_ratio) + fio2_max * flow_o2_ratio; transform_fio2(inferred_fio2, sensor_measurements.fio2); } else { // simulate FiO2 from params transform_fio2(parameters.fio2, sensor_measurements.fio2); } transform_spo2(sensor_measurements.fio2, sensor_measurements.spo2); } void HFNCSimulator::init_cycle() { cycle_start_time_ = current_time(); } void HFNCSimulator::transform_flow(float params_flow, float &sens_meas_flow) { sens_meas_flow += (params_flow - sens_meas_flow) * flow_responsiveness / time_step(); } void HFNCSimulator::transform_spo2(float fio2, float &spo2) { spo2 += (spo2_fio2_scale * fio2 - spo2) * spo2_responsiveness / time_step(); if (spo2 < spo2_min) { spo2 = spo2_min; } if (spo2 > spo2_max) { spo2 = spo2_max; } } // Simulators void Simulators::transform( uint32_t current_time, const Parameters &parameters, const SensorVars &sensor_vars, SensorMeasurements &sensor_measurements, CycleMeasurements &cycle_measurements) { switch (parameters.mode) { case VentilationMode_pc_ac: active_simulator_ = &pc_ac_; break; case VentilationMode_hfnc: active_simulator_ = &hfnc_; break; default: active_simulator_ = nullptr; return; } input_clock(current_time); active_simulator_->transform(parameters, sensor_vars, sensor_measurements, cycle_measurements); } void Simulators::input_clock(uint32_t current_time) { if (active_simulator_ == nullptr) { return; } pc_ac_.input_clock(current_time); hfnc_.input_clock(current_time); } } // namespace Pufferfish::Driver::BreathingCircuit
31.314433
99
0.744856
raavilagoo
122ae8a4dbb851bd8b0686cc72850a236e1f754e
8,475
cpp
C++
common/events/src/events/zsysd.cpp
naazgull/zapata
e5734ff88a17b261a2f4547fa47f01dbb1a69d84
[ "Unlicense" ]
9
2016-08-10T16:51:23.000Z
2020-04-08T22:07:47.000Z
common/events/src/events/zsysd.cpp
naazgull/zapata
e5734ff88a17b261a2f4547fa47f01dbb1a69d84
[ "Unlicense" ]
78
2015-02-25T15:16:02.000Z
2021-10-31T15:58:15.000Z
common/events/src/events/zsysd.cpp
naazgull/zapata
e5734ff88a17b261a2f4547fa47f01dbb1a69d84
[ "Unlicense" ]
7
2015-01-13T14:39:21.000Z
2018-11-24T06:48:09.000Z
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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 <fstream> #include <iostream> #include <signal.h> #include <string> #include <unistd.h> #include <semaphore.h> #include <zapata/base.h> #include <zapata/events.h> #include <zapata/json.h> auto generate(zpt::json _to_add, zpt::json _global_conf) -> void { std::ifstream _ifs; _ifs.open( (std::string("/etc/zapata/backend-available/") + std::string(_to_add) + std::string(".conf")) .data()); if (_ifs.is_open()) { zpt::json _conf; _ifs >> _conf; _ifs.close(); _conf = _global_conf + _conf; zpt::conf::setup(_conf); _conf << "!warning" << "AUTOMATIC GENERATED FILE, do NOT edit by hand"; _conf << "$source" << _to_add; if (!_conf["boot"][0]["name"]->is_string()) { std::cout << "no bootable configuration found in /etc/zapata/backend-available/" << std::string(_to_add) << ".conf" << std::endl << std::flush; exit(-1); } std::ofstream _ofs; _ofs.open((std::string("/etc/zapata/backend-enabled/") + std::string(_conf["boot"][0]["name"]) + std::string(".conf")) .data(), std::ios::out | std::ios::trunc); _ofs << zpt::json::pretty(_conf) << std::flush; _ofs.close(); std::cout << "> wrote /etc/zapata/backend-enabled/" << std::string(_conf["boot"][0]["name"]) << ".conf" << std::endl << std::flush; std::string _sysd("[Unit]\n" "Description=${name}\n" "${dependencies}\n" "${requirements}\n" "\n" "[Service]\n" "LimitNOFILE=${fd_max}\n" "Type=notify\n" "TimeoutStartSec=0\n" "TimeoutStopSec=2\n" "Restart=${restart}\n" "RemainAfterExit=no\n" "WatchdogSec=${keep_alive}\n" "\n" "ExecStart=/usr/bin/zpt -c /etc/zapata/backend-enabled/${name}.conf\n" "\n" "[Install]\n" "WantedBy=multi-user.target\n"); std::string _after; std::string _requires; if (_conf["boot"][0]["depends"]->is_array()) { for (auto [_idx, _key, _dep] : _conf["boot"][0]["depends"]) { _after += std::string("After=") + std::string(_dep) + std::string(".service\n"); _requires += std::string("Requires=") + std::string(_dep) + std::string(".service\n"); } } zpt::replace(_sysd, "${dependencies}", _after); zpt::replace(_sysd, "${requirements}", _requires); zpt::replace(_sysd, "${name}", std::string(_conf["boot"][0]["name"])); if (_conf["boot"][0]["keep_alive"]->ok()) { zpt::replace(_sysd, "${keep_alive}", std::string(_conf["boot"][0]["keep_alive"])); } else { zpt::replace(_sysd, "${keep_alive}", "0"); } if (_conf["boot"][0]["fd_max"]->ok()) { zpt::replace(_sysd, "${fd_max}", std::string(_conf["boot"][0]["fd_max"])); } else { zpt::replace(_sysd, "${fd_max}", "0"); } if (_conf["boot"][0]["restart_policy"]->ok()) { zpt::replace(_sysd, "${restart}", std::string(_conf["boot"][0]["restart_policy"])); } else { zpt::replace(_sysd, "${restart}", "no"); } std::ofstream _sfs; _sfs.open((std::string("/lib/systemd/system/") + std::string(_conf["boot"][0]["name"]) + std::string(".service")) .data()); if (_sfs.is_open()) { _sfs << _sysd << std::endl << std::flush; _sfs.close(); std::cout << "> wrote /lib/systemd/system/" << std::string(_conf["boot"][0]["name"]) << ".service" << std::endl << std::flush; } else { std::cout << "couldn't write to /lib/systemd/system/" << std::string(_conf["boot"][0]["name"]) << ".service" << std::endl << std::flush; exit(-1); } } else { std::cout << "no such file named /etc/zapata/backend-available/" << std::string(_to_add) << ".conf" << std::endl << std::flush; exit(-1); } } int main(int argc, char* argv[]) { zpt::json _args = zpt::conf::getopt(argc, argv); if (_args["add"]) { zpt::json _global_conf; std::ifstream _zfs; _zfs.open((std::string("/etc/zapata/zapata.conf")).data()); if (_zfs.is_open()) { zpt::json _conf; _zfs >> _conf; _zfs.close(); } for (auto _to_add : _args["add"]->array()) { generate(_to_add, _global_conf); } } else if (_args["reconfigure"]) { zpt::json _global_conf; std::ifstream _zfs; _zfs.open((std::string("/etc/zapata/zapata.conf")).data()); if (_zfs.is_open()) { zpt::json _conf; _zfs >> _conf; _zfs.close(); } std::vector<std::string> _files; zpt::glob("/etc/zapata/backend-enabled/", _files, "(.*)\\.conf"); for (auto _file : _files) { std::ifstream _ifs; _ifs.open(_file.data()); if (_ifs.is_open()) { zpt::json _conf; _ifs >> _conf; _ifs.close(); generate(_conf["$source"], _global_conf); } else { std::cout << "no such file named " << _file << std::endl << std::flush; exit(-1); } } } else if (_args["remove"]) { for (auto _to_remove : _args["remove"]->array()) { std::ifstream _ifs; _ifs.open((std::string("/etc/zapata/backend-available/") + std::string(_to_remove) + std::string(".conf")) .data()); if (_ifs.is_open()) { zpt::json _conf; _ifs >> _conf; _ifs.close(); if (system((std::string("rm -rf /etc/zapata/backend-enabled/") + std::string(_conf["boot"][0]["name"]) + std::string(".conf")) .data())) {} std::cout << "> removing /etc/zapata/backend-enabled/" << std::string(_conf["boot"][0]["name"]) << ".conf" << std::endl << std::flush; if (system((std::string("rm -rf /lib/systemd/system/") + std::string(_conf["boot"][0]["name"]) + std::string(".service")) .data())) {} std::cout << "> removing /lib/systemd/system/" << std::string(_conf["boot"][0]["name"]) << ".service" << std::endl << std::flush; } } } return 0; }
38.004484
100
0.487198
naazgull
122b1f5dd7e100112c1df1920bb2392b584c44bc
8,793
cpp
C++
parameter_generator.cpp
alexrow/LEDAtools
f847707833650706519cc57f5956b8e1a17a157c
[ "Unlicense" ]
null
null
null
parameter_generator.cpp
alexrow/LEDAtools
f847707833650706519cc57f5956b8e1a17a157c
[ "Unlicense" ]
null
null
null
parameter_generator.cpp
alexrow/LEDAtools
f847707833650706519cc57f5956b8e1a17a157c
[ "Unlicense" ]
1
2021-03-12T09:12:30.000Z
2021-03-12T09:12:30.000Z
#include <NTL/ZZ.h> #include <cstdint> #include <cmath> #define NUM_BITS_REAL_MANTISSA 128 #define IGNORE_DECODING_COST 0 #define SKIP_BJMM 0 #define LOG_COST_CRITERION 1 #include "proper_primes.hpp" #include "binomials.hpp" #include "bit_error_probabilities.hpp" #include "partitions_permanents.hpp" #include "isd_cost_estimate.hpp" #include <cmath> uint32_t estimate_t_val(const uint32_t c_sec_level, const uint32_t q_sec_level, const uint32_t n_0, const uint32_t p){ double achieved_c_sec_level = c_sec_level; double achieved_q_sec_level = q_sec_level; uint32_t lo = 1, t, t_prec; uint32_t hi; hi = p < 4*c_sec_level ? p : 4*c_sec_level; t = lo; t_prec = lo; while (hi - lo > 1){ t_prec = t; t = (lo + hi)/2; std::cerr << "testing t " << t << std::endl; achieved_c_sec_level = c_isd_log_cost(n_0*p,((n_0-1)*p),t,p,0); achieved_q_sec_level = q_isd_log_cost(n_0*p,((n_0-1)*p),t,p,0); if ( (achieved_c_sec_level >= c_sec_level) && (achieved_q_sec_level >= q_sec_level) ){ hi = t; } else { lo = t; } } if( (achieved_c_sec_level >= c_sec_level) && (achieved_q_sec_level >= q_sec_level) ){ return t; } return t_prec; } int ComputeDvMPartition(const uint64_t d_v_prime, const uint64_t n_0, uint64_t mpartition[], uint64_t &d_v){ d_v = floor(sqrt(d_v_prime)); d_v = (d_v & 0x01) ? d_v : d_v + 1; uint64_t m = ceil( (double) d_v_prime / (double) d_v ); int partition_ok; partition_ok = FindmPartition(m,mpartition,n_0); while(!partition_ok && (d_v_prime/d_v) >= n_0){ d_v += 2; m = ceil( (double) d_v_prime / (double) d_v ); partition_ok = FindmPartition(m,mpartition,n_0); } return partition_ok; } uint64_t estimate_dv (const uint32_t c_sec_level, // expressed as const uint32_t q_sec_level, const uint32_t n_0, const uint32_t p, uint64_t mpartition[]){ double achieved_c_sec_level = 0.0; double achieved_q_sec_level = 0.0; double achieved_c_enum_sec_level = 0.0; double achieved_q_enum_sec_level = 0.0; NTL::ZZ keyspace; uint32_t lo = 1, d_v_prime, hi; uint64_t d_v,d_v_prec =0; int found_dv_mpartition = 0; // recalling that the weight of the sought codeword in a KRA is // d_c_prime = n_0 * d_v_prime, d_c_prime < p // d_v_prime should not be greater than p/n_0 hi = (p/n_0) < 4*c_sec_level ? (p/n_0) : 4*c_sec_level; d_v_prime = lo; d_v = (int) sqrt(lo); while (hi - lo > 1){ d_v_prec = d_v; d_v_prime = (lo + hi)/2; found_dv_mpartition = ComputeDvMPartition(d_v_prime,n_0,mpartition,d_v); if(found_dv_mpartition) { keyspace = 1; for(int i =0; i < (int)n_0; i++){ keyspace *= binomial_wrapper(p,mpartition[i]); } keyspace = NTL::power(keyspace,n_0); keyspace += NTL::power(binomial_wrapper(p,d_v),n_0); achieved_c_enum_sec_level = NTL::conv<double>(log2_RR(NTL::to_RR(keyspace))); achieved_q_enum_sec_level = achieved_c_enum_sec_level/2; if ((achieved_q_enum_sec_level >= q_sec_level) && (achieved_c_enum_sec_level >= c_sec_level) ){ /* last parameter indicates a KRA, reduce margin by p due to quasi cyclicity */ achieved_c_sec_level = c_isd_log_cost(n_0*p,p,n_0*d_v_prime,p,1); achieved_q_sec_level = q_isd_log_cost(n_0*p,p,n_0*d_v_prime,p,1); } } if ( (found_dv_mpartition) && (achieved_q_enum_sec_level >= q_sec_level) && (achieved_c_enum_sec_level >= c_sec_level) && (achieved_c_sec_level >= c_sec_level) && (achieved_q_sec_level >= q_sec_level) ){ hi = d_v_prime; } else { lo = d_v_prime; } } if ( (found_dv_mpartition) && (achieved_q_enum_sec_level >= q_sec_level) && (achieved_c_enum_sec_level >= c_sec_level) && (achieved_c_sec_level >= c_sec_level) && (achieved_q_sec_level >= q_sec_level) ){ return d_v; } return d_v_prec; } int main(int argc, char* argv[]){ if(argc != 6){ std::cout << "Code Parameter Computer for LEDA[kem|pkc]" << std::endl << " Usage " << argv[0] << " security_level_classic security_level_pq n_0 epsilon starting_prime_lb" << std::endl; return -1; } uint32_t c_sec_level = atoi(argv[1]); uint32_t q_sec_level = atoi(argv[2]); uint32_t n_0 = atoi(argv[3]); float epsilon = atof(argv[4]); uint32_t starting_prime_lower_bound = atoi(argv[5]); std::cerr << "Computing the parameter set for security level classic:2^" << c_sec_level << " post-q:2^" << q_sec_level << " n_0 " << n_0 << " epsilon " << epsilon << std::endl; uint64_t p, p_th, t, d_v_prime, d_v; uint64_t mpartition[n_0] = {0}; int current_prime_pos = 0; while (proper_primes[current_prime_pos] < starting_prime_lower_bound){ current_prime_pos++; } p_th = proper_primes[current_prime_pos]; InitBinomials(); NTL::RR::SetPrecision(NUM_BITS_REAL_MANTISSA); pi = NTL::ComputePi_RR(); /* since some values of p may yield no acceptable partitions for m, binary * search on p is not feasible. Fall back to fast increase of the value of * p exploiting the value of the p expected to be correcting the required t * errors */ std::cout << "finding parameters" << std::endl; do { /* estimate the current prime as the closest * to the previous p_th * (1+epsilon) */ uint32_t next_prime = ceil(p_th * (1.0+epsilon)); current_prime_pos = 0; while (proper_primes[current_prime_pos] < next_prime){ current_prime_pos++; } p = proper_primes[current_prime_pos]; std::cout << " -- testing p: " << p << std::endl; // Estimate number of errors to ward off ISD decoding t = estimate_t_val(c_sec_level,q_sec_level,n_0,p); std::cout << " -- found t: " << t << std::endl; /* Estimate H*Q density to avoid key recovery via ISD and enumeration * of H and Q */ d_v = estimate_dv(c_sec_level,q_sec_level,n_0,p,mpartition); std::cout << " -- found d_v: " << d_v << std::endl; // Estimate the bit flipping thresholds and correction capability d_v_prime=0; for(int i=0;i< (int)n_0;i++){ d_v_prime += mpartition[i]; } d_v_prime = d_v * d_v_prime; p_th=Findpth(n_0, d_v_prime, t); std::cout << " -- p should be at least " << (1.0+epsilon)* p_th << "to correct the errors" << std::endl; } while ((p <= (1.0+epsilon)* p_th) && (current_prime_pos < PRIMES_NO) ); std::cout << "refining parameters" << std::endl; uint64_t p_ok, t_ok, d_v_ok, mpartition_ok[n_0] = {0}; /* refinement step taking into account possible invalid m partitions */ do { p = proper_primes[current_prime_pos]; std::cout << " -- testing p: " << p << std::endl; // Estimate number of errors to ward off ISD decoding t = estimate_t_val(c_sec_level,q_sec_level,n_0,p); std::cout << " -- found t: " << t << std::endl; /* Estimate H*Q density to avoid key recovery via ISD and enumeration * of H and Q */ d_v = estimate_dv(c_sec_level,q_sec_level,n_0,p,mpartition); std::cout << " -- found d_v: " << d_v << std::endl; // Estimate the bit flipping thresholds and correction capability d_v_prime=0; for(int i=0;i< (int)n_0;i++){ d_v_prime += mpartition[i]; } d_v_prime = d_v * d_v_prime; p_th=Findpth(n_0, d_v_prime, t); std::cout << " -- the threshold value for p to be correcting errors is " << p_th << std::endl; if(p > (1.0+epsilon)* p_th ) { //store last valid parameter set std::cout << " -- p is at least " << (1.0+epsilon)*p_th << "; it corrects the errors" << std::endl; p_ok = p; t_ok = t; d_v_ok = d_v; for(unsigned i = 0; i < n_0 ; i++){ mpartition_ok[i] = mpartition[i]; } } current_prime_pos--; } while ((p > (1.0+epsilon)* p_th ) && (current_prime_pos > 0)); std::cout << "parameter set found: p:" << p_ok << " t: " << t_ok; std::cout << " d_v : " << d_v_ok << " mpartition: [ "; for (unsigned i = 0; i < n_0 ; i++ ){ std::cout << mpartition_ok[i] << " "; } std::cout << " ]" << std::endl; return 0; }
35.455645
116
0.589446
alexrow
122e5086319ce6bf859f46f5a1bc19bb9cdc8c8a
923
cpp
C++
src/terminal/render/Translate.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
src/terminal/render/Translate.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
src/terminal/render/Translate.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
#include "Translate.h" #include <glm/gtx/rotate_vector.hpp> #include "../Resources.h" #include "Model.h" #include "RModel.h" glm::mat4 etm::tsl::model(Resources *res, Model &m) { glm::mat4 model(1.0f); // Translate so that the x/y coords are in the middle // of the object, then convert to quads (OpenGL style). const float xPos = (m.x + m.width / 2) / res->getViewportWidth() * 2 - 1; const float yPos = ((m.y + m.height / 2) / res->getViewportHeight() * 2 - 1) * -1; model = glm::translate(model, glm::vec3(xPos, yPos, 0.0f)); // Convert width and height to OpenGL-readable clamped floats, 0-1 model = glm::scale(model, glm::vec3(m.width / res->getViewportWidth(), m.height / res->getViewportHeight(), 0.0f)); return model; } glm::mat4 etm::tsl::rModel(Resources *res, RModel &m) { return glm::rotate(model(res, m), glm::radians(m.rotation), glm::vec3(0.0f, 0.0f, 1.0f)); }
34.185185
119
0.641387
KeinR
122ed0e34c0bb22804e4541fc998efbf1fd47cd7
112
cpp
C++
language.cpp
MasterQ32/CodersNotepad
8248ce25bda3b9fb82d84ec682bc9c82ac4e868a
[ "MIT" ]
null
null
null
language.cpp
MasterQ32/CodersNotepad
8248ce25bda3b9fb82d84ec682bc9c82ac4e868a
[ "MIT" ]
null
null
null
language.cpp
MasterQ32/CodersNotepad
8248ce25bda3b9fb82d84ec682bc9c82ac4e868a
[ "MIT" ]
null
null
null
#include "language.h" Language::Language(QString id, QObject *parent) : QObject(parent), mId(id) { }
11.2
49
0.642857
MasterQ32
12321dfd81c2143f28ab45a2e45581e2ee362dd0
9,804
cpp
C++
unittest/benchmark/benchmark_knowhere_binary.cpp
ChunelFeng/knowhere
4c6ff55b5a23a9a38b12db40cbb5cd847cae1408
[ "Apache-2.0" ]
null
null
null
unittest/benchmark/benchmark_knowhere_binary.cpp
ChunelFeng/knowhere
4c6ff55b5a23a9a38b12db40cbb5cd847cae1408
[ "Apache-2.0" ]
null
null
null
unittest/benchmark/benchmark_knowhere_binary.cpp
ChunelFeng/knowhere
4c6ff55b5a23a9a38b12db40cbb5cd847cae1408
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019-2020 Zilliz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under the License. #include <gtest/gtest.h> #include <vector> #include "knowhere/index/IndexType.h" #include "knowhere/index/VecIndexFactory.h" #include "knowhere/index/vector_index/adapter/VectorAdapter.h" #include "unittest/benchmark/benchmark_sift.h" #include "unittest/utils.h" #define CALC_TIME_SPAN(X) \ double t_start = elapsed(); \ X; \ double t_diff = elapsed() - t_start; class Benchmark_knowhere_binary : public Benchmark_sift { public: void write_index(const std::string& filename, const knowhere::Config& conf) { binary_set_.clear(); FileIOWriter writer(filename); binary_set_ = index_->Serialize(conf); const auto& m = binary_set_.binary_map_; for (auto it = m.begin(); it != m.end(); ++it) { const std::string& name = it->first; size_t name_size = name.length(); const knowhere::BinaryPtr data = it->second; size_t data_size = data->size; writer(&name_size, sizeof(size_t)); writer(&data->size, sizeof(data->size)); writer((void*)name.c_str(), name_size); writer(data->data.get(), data->size); } } void read_index(const std::string& filename) { binary_set_.clear(); FileIOReader reader(filename); int64_t file_size = reader.size(); if (file_size < 0) { throw knowhere::KnowhereException(filename + " not exist"); } int64_t offset = 0; while (offset < file_size) { size_t name_size, data_size; reader(&name_size, sizeof(size_t)); offset += sizeof(size_t); reader(&data_size, sizeof(size_t)); offset += sizeof(size_t); std::string name; name.resize(name_size); reader(name.data(), name_size); offset += name_size; auto data = new uint8_t[data_size]; reader(data, data_size); offset += data_size; std::shared_ptr<uint8_t[]> data_ptr(data); binary_set_.Append(name, data_ptr, data_size); } } std::string get_index_name(const std::vector<int32_t>& params) { std::string params_str = ""; for (size_t i = 0; i < params.size(); i++) { params_str += "_" + std::to_string(params[i]); } return ann_test_name_ + "_" + std::string(index_type_) + params_str + ".index"; } void create_cpu_index(const std::string& index_file_name, const knowhere::Config& conf) { printf("[%.3f s] Creating CPU index \"%s\"\n", get_time_diff(), std::string(index_type_).c_str()); auto& factory = knowhere::VecIndexFactory::GetInstance(); index_ = factory.CreateVecIndex(index_type_); try { printf("[%.3f s] Reading index file: %s\n", get_time_diff(), index_file_name.c_str()); read_index(index_file_name); } catch (...) { printf("[%.3f s] Building all on %d vectors\n", get_time_diff(), nb_); knowhere::DatasetPtr ds_ptr = knowhere::GenDataset(nb_, dim_, xb_); index_->BuildAll(ds_ptr, conf); printf("[%.3f s] Writing index file: %s\n", get_time_diff(), index_file_name.c_str()); write_index(index_file_name, conf); } } void test_binary_idmap(const knowhere::Config& cfg) { auto conf = cfg; printf("\n[%0.3f s] %s | %s \n", get_time_diff(), ann_test_name_.c_str(), std::string(index_type_).c_str()); printf("================================================================================\n"); for (auto nq : NQs_) { knowhere::DatasetPtr ds_ptr = knowhere::GenDataset(nq, dim_, xq_); for (auto k : TOPKs_) { knowhere::SetMetaTopk(conf, k); CALC_TIME_SPAN(auto result = index_->Query(ds_ptr, conf, nullptr)); auto ids = knowhere::GetDatasetIDs(result); float recall = CalcRecall(ids, nq, k); printf(" nq = %4d, k = %4d, elapse = %.4fs, R@ = %.4f\n", nq, k, t_diff, recall); } } printf("================================================================================\n"); printf("[%.3f s] Test '%s/%s' done\n\n", get_time_diff(), ann_test_name_.c_str(), std::string(index_type_).c_str()); } void test_binary_ivf(const knowhere::Config& cfg) { auto conf = cfg; auto nlist = knowhere::GetIndexParamNlist(conf); printf("\n[%0.3f s] %s | %s | nlist=%ld\n", get_time_diff(), ann_test_name_.c_str(), std::string(index_type_).c_str(), nlist); printf("================================================================================\n"); for (auto nprobe : NPROBEs_) { knowhere::SetIndexParamNprobe(conf, nprobe); for (auto nq : NQs_) { knowhere::DatasetPtr ds_ptr = knowhere::GenDataset(nq, dim_, xq_); for (auto k : TOPKs_) { knowhere::SetMetaTopk(conf, k); CALC_TIME_SPAN(auto result = index_->Query(ds_ptr, conf, nullptr)); auto ids = knowhere::GetDatasetIDs(result); float recall = CalcRecall(ids, nq, k); printf(" nprobe = %4d, nq = %4d, k = %4d, elapse = %.4fs, R@ = %.4f\n", nprobe, nq, k, t_diff, recall); } } } printf("================================================================================\n"); printf("[%.3f s] Test '%s/%s' done\n\n", get_time_diff(), ann_test_name_.c_str(), std::string(index_type_).c_str()); } protected: void SetUp() override { T0_ = elapsed(); // set_ann_test_name("sift-128-euclidean"); set_ann_test_name("sift-4096-hamming"); parse_ann_test_name(); load_hdf5_data<true>(); assert(metric_str_ == METRIC_HAM_STR || metric_str_ == METRIC_JAC_STR || metric_str_ == METRIC_TAN_STR); metric_type_ = (metric_str_ == METRIC_HAM_STR) ? knowhere::metric::HAMMING : (metric_str_ == METRIC_JAC_STR) ? knowhere::metric::JACCARD : knowhere::metric::TANIMOTO; knowhere::SetMetaMetricType(cfg_, metric_type_); knowhere::KnowhereConfig::SetSimdType(knowhere::KnowhereConfig::SimdType::AUTO); } void TearDown() override { free_all(); } protected: knowhere::MetricType metric_type_; knowhere::BinarySet binary_set_; knowhere::IndexType index_type_; knowhere::VecIndexPtr index_ = nullptr; knowhere::Config cfg_; const std::vector<int32_t> NQs_ = {10000}; const std::vector<int32_t> TOPKs_ = {10}; // IVF index params const std::vector<int32_t> NLISTs_ = {1024}; const std::vector<int32_t> NPROBEs_ = {1, 2, 4, 8, 16, 32, 64, 128, 256}; }; // This testcase can be used to generate binary sift1m HDF5 file // Following these steps: // 1. set_ann_test_name("sift-128-euclidean") // 2. use load_hdf5_data<false>(); // 3. change metric type to expected value (hamming/jaccard/tanimoto) manually // 4. specify the hdf5 file name to generate // 5. run this testcase #if 0 TEST_F(Benchmark_knowhere_binary, TEST_CREATE_BINARY_HDF5) { index_type_ = knowhere::IndexEnum::INDEX_FAISS_BIN_IDMAP; knowhere::Config conf = cfg_; std::string index_file_name = get_index_name({}); // use sift1m data as binary data dim_ *= 32; metric_type_ = knowhere::metric::HAMMING; knowhere::SetMetaMetricType(conf, metric_type_); create_cpu_index(index_file_name, conf); index_->Load(binary_set_); knowhere::DatasetPtr ds_ptr = knowhere::GenDataset(nq_, dim_, xq_); knowhere::SetMetaTopk(conf, gt_k_); auto result = index_->Query(ds_ptr, conf, nullptr); auto gt_ids = knowhere::GetDatasetIDs(result); auto gt_dist = knowhere::GetDatasetDistance(result); auto gt_ids_int = new int32_t[gt_k_ * nq_]; for (int32_t i = 0; i < gt_k_ * nq_; i++) { gt_ids_int[i] = gt_ids[i]; } assert(dim_ == 4096); assert(nq_ == 10000); assert(gt_k_ == 100); hdf5_write<true>("sift-4096-hamming.hdf5", dim_/32, gt_k_, xb_, nb_, xq_, nq_, gt_ids_int, gt_dist); delete[] gt_ids_int; } #endif TEST_F(Benchmark_knowhere_binary, TEST_BINARY_IDMAP) { index_type_ = knowhere::IndexEnum::INDEX_FAISS_BIN_IDMAP; knowhere::Config conf = cfg_; std::string index_file_name = get_index_name({}); create_cpu_index(index_file_name, conf); index_->Load(binary_set_); test_binary_idmap(conf); } TEST_F(Benchmark_knowhere_binary, TEST_BINARY_IVFFLAT) { index_type_ = knowhere::IndexEnum::INDEX_FAISS_BIN_IVFFLAT; knowhere::Config conf = cfg_; for (auto nlist : NLISTs_) { std::string index_file_name = get_index_name({nlist}); knowhere::SetIndexParamNlist(conf, nlist); create_cpu_index(index_file_name, conf); index_->Load(binary_set_); test_binary_ivf(conf); } }
37.853282
116
0.586597
ChunelFeng
123358de8146823dfc763ad8df7083420de0c640
8,638
hpp
C++
OBJ_IO.hpp
James-Wickenden/computer-graphics
03a2661e4c9368773b21ea9e7b459f0bde7a649c
[ "MIT" ]
1
2020-07-15T13:14:57.000Z
2020-07-15T13:14:57.000Z
OBJ_IO.hpp
James-Wickenden/computer-graphics
03a2661e4c9368773b21ea9e7b459f0bde7a649c
[ "MIT" ]
null
null
null
OBJ_IO.hpp
James-Wickenden/computer-graphics
03a2661e4c9368773b21ea9e7b459f0bde7a649c
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <sstream> #include <vector> #include <unordered_map> #include <algorithm> #include <cmath> #include <tuple> #include <optional> #include "OBJ_Structure.hpp" #include "Texture.hpp" using namespace std; using namespace glm; class OBJ_IO { public: OBJ_IO () {} // For clarity: each ModelTriangle (a triangle in 3D space) may get their // "filling" from a TextureTriangle (a triangle in 2D space). tuple<vector<GObject>, optional<Texture>> loadOBJ(string filename) { optional<Texture> maybeTexture; OBJ_Structure structure = loadOBJpass1(filename); if (structure.textureFilename.empty()) maybeTexture = nullopt; else maybeTexture.emplace(Texture(structure.textureFilename)); //cout << structure << endl; return make_tuple(structure.toGObjects(), maybeTexture); } std::vector<GObject> scale_additive(std::vector<GObject> gobjects) { float currentMinComponent = std::numeric_limits<float>::infinity(); for (uint j=0; j<gobjects.size(); j++) { for (uint i=0; i<gobjects.at(j).faces.size(); i++) { for (int k=0; k<3; k++) { float smallest = minComponent(gobjects.at(j).faces.at(i).vertices[k]); if (smallest < currentMinComponent) currentMinComponent = smallest; } } } float addFactor = currentMinComponent < 0.0f ? abs(currentMinComponent) : 0.0f; for (uint j=0; j<gobjects.size(); j++) { //std::cout << "gobject " << gobjects.at(j).name << '\n'; for (uint i=0; i<gobjects.at(j).faces.size(); i++) { for (int k=0; k<3; k++) { glm::vec3 v = gobjects.at(j).faces.at(i).vertices[k]; v[0] += addFactor; v[1] += addFactor; v[2] += addFactor; gobjects.at(j).faces.at(i).vertices[k] = v; // std::cout << "NEW VERTEX: (" << v.x << ", " << v.y << ", " << v.z << ")\n"; } } } return gobjects; } std::vector<GObject> scale_multiplicative(int width, std::vector<GObject> gobjects) { float currentMaxComponent = -std::numeric_limits<float>::infinity(); for (uint j=0; j<gobjects.size(); j++) { for (uint i=0; i<gobjects.at(j).faces.size(); i++) { for (int k=0; k<3; k++) { float greatest = maxComponent(gobjects.at(j).faces.at(i).vertices[k]); if (greatest > currentMaxComponent) currentMaxComponent = greatest; } } } float multFactor = width / (currentMaxComponent); //std::cout << "MULTIPLICATIVE SCALE FACTOR: " << multFactor << '\n'; //std::cout << "ADDITIVE SCALE FACTOR: " << addFactor << '\n'; for (uint j=0; j<gobjects.size(); j++) { //std::cout << "gobject " << gobjects.at(j).name << '\n'; for (uint i=0; i<gobjects.at(j).faces.size(); i++) { for (int k=0; k<3; k++) { glm::vec3 v = gobjects.at(j).faces.at(i).vertices[k]; v[0] *= multFactor; v[1] *= multFactor; v[2] *= multFactor; gobjects.at(j).faces.at(i).vertices[k] = v; //std::cout << "NEW VERTEX: (" << v.x << ", " << v.y << ", " << v.z << ")\n"; } } } //std::cout << "finished scaling" << '\n'; return gobjects; } private: void skipToNextLine(ifstream& inFile) { inFile.ignore(numeric_limits<int>::max(), '\n'); } bool emptyOrCommentLine(string lineString) { return (lineString.empty() || lineString.front() == '#'); } faceData processFaceLine(istringstream& lineStream, OBJ_Structure structure) { string faceTerm; vec3_int vindices; vec3_int tindices; // vec3_int nindices; bool vts = true; faceData face; int i = 0; // Repeatedly get "v1/vt1/vn1" or similar, then parse /-delimited ints. // Ignore vector normals for now. while (lineStream >> faceTerm) { sscanf(faceTerm.c_str(), "%d/%d", &vindices[i], &tindices[i]); // nindices[i] if (structure.textureFilename.empty()) vts = false; i += 1; } // Don't forget to subtract one from all the indices, since OBJ files use // 1-based indices for (int i=0; i<(int)vindices.size(); i++) vindices[i] -= 1; if (vts) { for (int i=0; i<(int)tindices.size(); i++) tindices[i] -= 1; face = make_tuple(vindices, tindices, nullopt); } else { face = make_tuple(vindices, nullopt, nullopt); } return face; } // Don't bother having an MTL_Structure class, just use a tuple tuple<materialDict, string> loadMTL(string filename) { // Return values materialDict mtlDict; string textureFilename; // Temp vars string mtlName; float r, g, b; Colour colour; ifstream inFile; inFile.open(filename); if (inFile.fail()) { cout << "File not found." << endl; exit(1); } string lineString, linePrefix; while (getline(inFile, lineString)) { if (emptyOrCommentLine(lineString)) continue; istringstream lineStream(lineString); lineStream >> linePrefix; // use this as the conditional in an if stmt to detect failure if needed if (linePrefix == "map_Kd") { lineStream >> textureFilename; } else if (linePrefix == "newmtl") { lineStream >> mtlName; } // Assumes a "newmtl" line has come before, initialising mtlName else if (linePrefix == "Kd") { lineStream >> r >> g >> b; mtlDict.insert({mtlName, Colour(mtlName, round(255*r), round(255*g), round(255*b))}); } } inFile.close(); return make_tuple(mtlDict, textureFilename); } OBJ_Structure loadOBJpass1(string filename) { // Store all intermediate stuff in here. Use it to build a vector of // gobjects. OBJ_Structure structure; // Temp vars float a, b, c; vec3 vertex; vec2 textureVertex; faceData face; string currentObjName = "loose"; string currentObjMtlName; ifstream inFile; inFile.open(filename); if (inFile.fail()) { cout << "File not found." << endl; exit(1); } string lineString, linePrefix; while (getline(inFile, lineString)) { if (emptyOrCommentLine(lineString)) continue; istringstream lineStream(lineString); lineStream >> linePrefix; //cout << "linePrefix '" << linePrefix << "'" << endl; if (linePrefix == "mtllib") { // cout << "This should only appear once" << endl; lineStream >> structure.mtlLibFileName; // TODO: check which of these is empty, if any, and do sth appropriate tie(structure.mtlDict, structure.textureFilename) = loadMTL(structure.mtlLibFileName); } else if (linePrefix == "v") { lineStream >> a >> b >> c; vertex[0] = a; vertex[1] = b; vertex[2] = c; structure.allVertices.push_back(vertex); } else if (linePrefix == "vt") { lineStream >> a >> b; textureVertex[0] = a; textureVertex[1] = b; // Normalise texture vertices in case of erroneous .objs if (a > 1 || a < 0) { textureVertex[0] = abs(a); if (textureVertex[0] > 1) textureVertex[0] = 1 / textureVertex[0]; } if (b > 1 || b < 0) { textureVertex[1] = abs(b); if (textureVertex[1] > 1) textureVertex[1] = 1 / textureVertex[1]; } structure.allTextureVertices.push_back(textureVertex); } else if (linePrefix == "f") { face = processFaceLine(lineStream, structure); structure.faceDict.insert({currentObjName, face}); } else if (linePrefix == "o") { lineStream >> currentObjName; } // Assumes an "o" line has come before it, initialising currentObjName else if (linePrefix == "usemtl") { lineStream >> currentObjMtlName; structure.objMatNameDict.insert({currentObjName, currentObjMtlName}); } } inFile.close(); return structure; } float maxComponent(glm::vec3 v) { float greatest = std::max(std::max(v[0], v[1]), v[2]); return greatest; } // potentially most negative float minComponent(glm::vec3 v) { float smallest = std::min(std::min(v[0], v[1]), v[2]); return smallest; } };
33.48062
106
0.56263
James-Wickenden
1233d6e75cbe55afab5f5e68a38abc200ef11be0
2,291
cpp
C++
tests/test_framework.cpp
sagniknitr/EDGEMW
54638a6532f2593a0775740fcbfcf297291cbe70
[ "MIT" ]
1
2020-08-26T20:22:24.000Z
2020-08-26T20:22:24.000Z
tests/test_framework.cpp
sagniknitr/EDGEMW
54638a6532f2593a0775740fcbfcf297291cbe70
[ "MIT" ]
4
2021-09-20T00:33:33.000Z
2021-09-20T00:35:46.000Z
tests/test_framework.cpp
sagniknitr/EDGEMW
54638a6532f2593a0775740fcbfcf297291cbe70
[ "MIT" ]
1
2022-03-24T13:41:46.000Z
2022-03-24T13:41:46.000Z
#include <iostream> #include <string> #include <stdint.h> extern "C" { int prng_test(int argc, char **argv); int list_test(int argc, char **argv); int sysioctl_test(int argc, char **argv); int pthread_test(int argc, char **argv); //int crypto_test(int argc, char **argv); int sched_test(int argc, char **argv); int dlist_test(int argc, char **argv); int static_list_test(int argc, char **argv); int stack_test(int argc, char **argv); int queue_test(int argc, char **argv); int fifo_test(int argc, char **argv); //int ssl_test(int argc, char **argv); int hashtbl_test(int argc, char **argv); int rawsock_test(int argc, char **argv); } int evtloop_test(int argc, char **argv); int config_parser_test(int argc, char **argv); int fsAPI_test(int argc, char **argv); int tokparse_test(int argc, char **argv); int msg_queue_test(int argc, char **argv); int monitor_test(int argc, char **argv); static struct test_cases { std::string name; int (*executor)(int argc, char **argv); } test_case[] = { {"list_test", list_test}, {"evtloop_test", evtloop_test}, {"prng_test", prng_test}, {"fsapi_test", fsAPI_test}, {"tokparse_test", tokparse_test}, {"sysioctl_test", sysioctl_test}, {"pthread_test", pthread_test}, //{"crypto_test", crypto_test}, {"sched_test", sched_test}, {"config_parser_test", config_parser_test}, {"dlist_test", dlist_test}, {"static_list_test", static_list_test}, {"stack_test", stack_test}, {"queue_test", queue_test}, {"fifo_test", fifo_test}, //{"ssl_test", ssl_test}, {"hashtbl_test", hashtbl_test}, {"msg_queue_test", msg_queue_test}, {"monitor_test", monitor_test}, {"rawsock_test", rawsock_test}, }; int main(int argc, char **argv) { uint32_t i; for (i = 0; i < sizeof(test_case) / sizeof(test_case[0]); i ++) { std::string exec_name = std::string(argv[1]); if (exec_name == test_case[i].name) { test_case[i].executor(argc - 1, &argv[1]); break; } #if 0 if (test_case[i].executor(argc, argv)) { std::cerr << "test " << test_case[i].name << " failed" << std::endl; } else { std::cerr << "test " << test_case[i].name << " passed" << std::endl; } #endif } return 0; }
29.371795
80
0.633348
sagniknitr
72eb7c7fa4280678d2284acfe37f340c3ea6ec8d
9,522
cpp
C++
TAO/orbsvcs/examples/Notify/MC/monitor/monitor.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/orbsvcs/examples/Notify/MC/monitor/monitor.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/orbsvcs/examples/Notify/MC/monitor/monitor.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: monitor.cpp 90164 2010-05-18 21:47:55Z mitza $ #include "ace/Get_Opt.h" #include "ace/OS_NS_ctype.h" #include "orbsvcs/Notify/MonitorControl/NotificationServiceMCC.h" static const ACE_TCHAR* monitor_ior = 0; static const char* shutdown_cmd = "shutdown"; static const char* rm_consumer = "remove_consumer"; static const char* rm_supplier = "remove_supplier"; static const char* rm_consumeradmin = "remove_consumeradmin"; static const char* rm_supplieradmin = "remove_supplieradmin"; static int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT ("k:")); int c; while ((c = get_opts ()) != -1) { switch (c) { case 'k': monitor_ior = get_opts.opt_arg (); break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-k <ior> " "\n", argv [0]), -1); } } return 0; } extern "C" int sorter (const void* a, const void* b) { const char* left = *(reinterpret_cast<const char* const*> (a)); const char* right = *(reinterpret_cast<const char* const*> (b)); return ACE_OS::strcmp (left, right); } bool process_command (CosNotification::NotificationServiceMonitorControl_ptr nsm, char* buf, const char* command) { if (ACE_OS::strstr (buf, command) == buf) { const char* name = buf + ACE_OS::strlen (command); bool space = false; size_t i = 0; while (ACE_OS::ace_isspace (name[i])) { space = true; ++i; } if (space) { try { const char* start = name + i; if (ACE_OS::strcmp (command, shutdown_cmd) == 0) { nsm->shutdown_event_channel (start); } else if (ACE_OS::strcmp (command, rm_consumer) == 0) { nsm->remove_consumer (start); } else if (ACE_OS::strcmp (command, rm_supplier) == 0) { nsm->remove_supplier (start); } else if (ACE_OS::strcmp (command, rm_consumeradmin) == 0) { nsm->remove_consumeradmin (start); } else if (ACE_OS::strcmp (command, rm_supplieradmin) == 0) { nsm->remove_supplieradmin (start); } } catch (const CORBA::Exception& ex) { ACE_OS::strcat (buf, ": "); ex._tao_print_exception (buf); } return true; } } return false; } int ACE_TMAIN (int argc, ACE_TCHAR* argv[]) { int status = 0; try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); if (parse_args (argc, argv) != 0) { return 1; } CORBA::Object_var obj = orb->string_to_object ( ACE_TEXT_ALWAYS_CHAR (monitor_ior)); CosNotification::NotificationServiceMonitorControl_var nsm = CosNotification::NotificationServiceMonitorControl::_narrow (obj.in ()); if (CORBA::is_nil (nsm.in ())) { ACE_ERROR_RETURN ((LM_ERROR, "Unable to locate the " "Notification Service Monitor\n"), 1); } bool done = false; static const size_t lsize = 1024; char prev[lsize]; while (!done) { ACE_OS::printf ("NotifyService> "); ACE_OS::fflush (stdout); char line[lsize] = ""; char* rl = ACE_OS::fgets (line, lsize, stdin); if (rl != 0) { int len = static_cast<int> (ACE_OS::strlen (line)); for (int i = 0; i < len && ACE_OS::ace_isspace (rl[0]); ++i) { rl++; } for (int i = len - 1; i >= 0 && ACE_OS::ace_isspace (line[i]); --i) { line[i] = '\0'; } if (ACE_OS::strlen (rl) == 0 || ACE_OS::strcmp (rl, "!!") == 0) { ACE_OS::strcpy (line, prev); rl = line; } ACE_OS::strcpy (prev, line); } if (rl == 0) { done = true; ACE_DEBUG ((LM_DEBUG, "\n")); } else if (ACE_OS::strlen (rl) == 0) { } else if (ACE_OS::strcmp (rl, "quit") == 0) { done = true; } else if (ACE_OS::strcmp (rl, "help") == 0) { ACE_DEBUG ((LM_DEBUG, "names - Get a list of " "currently available statistic names.\n" "quit - Exit the monitor.\n" "remove_consumer - Remove a consumer " "with the given name.\n" "remove_supplier - Remove a supplier " "with the given name.\n" "remove_consumeradmin - Remove a consumer " "admin with the given name.\n" "remove_supplieradmin - Remove a supplier " "admin with the given name.\n" "shutdown - Shut down an " "event channel with the given name.\n" "<statistic name> - Return the " "information for the specified statistic.\n")); } else if (ACE_OS::strcmp (rl, "names") == 0) { try { Monitor::NameList_var names = nsm->get_statistic_names (); CORBA::ULong length = names->length (); ACE_DEBUG ((LM_DEBUG, "Statistic names\n")); // It's much easier to read once it's sorted const char** narray = 0; ACE_NEW_THROW_EX (narray, const char* [length], CORBA::NO_MEMORY ()); for (CORBA::ULong i = 0; i < length; ++i) { narray[i] = names[i].in (); } ACE_OS::qsort (narray, length, sizeof (const char*), sorter); for (CORBA::ULong i = 0; i < length; ++i) { ACE_DEBUG ((LM_DEBUG, " %s\n", narray[i])); } delete [] narray; } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("names: "); } } else { if (process_command (nsm.in (), rl, shutdown_cmd)) { continue; } else if (process_command (nsm.in (), rl, rm_consumer)) { continue; } else if (process_command (nsm.in (), rl, rm_supplier)) { continue; } else if (process_command (nsm.in (), rl, rm_consumeradmin)) { continue; } else if (process_command (nsm.in (), rl, rm_supplieradmin)) { continue; } try { Monitor::Data_var data = nsm->get_statistic (rl); ACE_DEBUG ((LM_DEBUG, "%s => ", rl)); if (data->data_union._d () == Monitor::DATA_NUMERIC) { ACE_DEBUG ((LM_DEBUG, "Last: %g Average: %g\n", data->data_union.num().dlist[0].value, data->data_union.num().average)); } else { Monitor::NameList list = data->data_union.list (); CORBA::ULong const length = list.length (); for (CORBA::ULong i = 0; i < length; ++i) { ACE_DEBUG ((LM_DEBUG, "%s ", list[i].in ())); } ACE_DEBUG ((LM_DEBUG, "\n")); } } catch (const CORBA::Exception& ex) { ACE_OS::strcat (rl, ": "); ex._tao_print_exception (rl); } } } orb->destroy (); } catch (const CORBA::UserException& ex) { ex._tao_print_exception ("Notification Service Monitor: "); ++status; } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Notification Service Monitor: "); ++status; } catch (...) { ACE_ERROR ((LM_ERROR, "Notification Service Monitor: " "unexpected exception type\n")); status++; } return status; }
30.132911
81
0.413989
cflowe
72eb8e94d6b6de0cd52e42525121b40d4ab81ed0
7,197
cc
C++
tools/gn/setup.cc
MIPS/external-chromium_org
e31b3128a419654fd14003d6117caa8da32697e7
[ "BSD-3-Clause" ]
2
2017-03-21T23:19:25.000Z
2019-02-03T05:32:47.000Z
tools/gn/setup.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
tools/gn/setup.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tools/gn/setup.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "tools/gn/filesystem_utils.h" #include "tools/gn/input_file.h" #include "tools/gn/parse_tree.h" #include "tools/gn/parser.h" #include "tools/gn/source_dir.h" #include "tools/gn/source_file.h" #include "tools/gn/tokenizer.h" #include "tools/gn/value.h" extern const char kDotfile_Help[] = ".gn file\n" "\n" " When gn starts, it will search the current directory and parent\n" " directories for a file called \".gn\". This indicates the source root.\n" " You can override this detection by using the --root command-line\n" " argument\n" "\n" " The .gn file in the source root will be executed. The syntax is the\n" " same as a buildfile, but with very limited build setup-specific\n" " meaning.\n" "\n" "Variables:\n" " buildconfig [required]\n" " Label of the build config file. This file will be used to setup\n" " the build file execution environment for each toolchain.\n" "\n" " secondary_source [optional]\n" " Label of an alternate directory tree to find input files. When\n" " searching for a BUILD.gn file (or the build config file discussed\n" " above), the file fill first be looked for in the source root.\n" " If it's not found, the secondary source root will be checked\n" " (which would contain a parallel directory hierarchy).\n" "\n" " This behavior is intended to be used when BUILD.gn files can't be\n" " checked in to certain source directories for whaever reason.\n" "\n" " The secondary source root must be inside the main source tree.\n" "\n" "Example .gn file contents:\n" "\n" " buildconfig = \"//build/config/BUILDCONFIG.gn\"\n" "\n" " secondary_source = \"//build/config/temporary_buildfiles/\"\n"; namespace { // More logging. const char kSwitchVerbose[] = "v"; const char kSwitchRoot[] = "root"; const char kSecondarySource[] = "secondary"; const base::FilePath::CharType kGnFile[] = FILE_PATH_LITERAL(".gn"); base::FilePath FindDotFile(const base::FilePath& current_dir) { base::FilePath try_this_file = current_dir.Append(kGnFile); if (base::PathExists(try_this_file)) return try_this_file; base::FilePath with_no_slash = current_dir.StripTrailingSeparators(); base::FilePath up_one_dir = with_no_slash.DirName(); if (up_one_dir == current_dir) return base::FilePath(); // Got to the top. return FindDotFile(up_one_dir); } } // namespace Setup::Setup() : dotfile_toolchain_(Label()), dotfile_settings_(&dotfile_build_settings_, &dotfile_toolchain_, std::string()), dotfile_scope_(&dotfile_settings_) { } Setup::~Setup() { } bool Setup::DoSetup() { CommandLine* cmdline = CommandLine::ForCurrentProcess(); scheduler_.set_verbose_logging(cmdline->HasSwitch(kSwitchVerbose)); if (!FillSourceDir(*cmdline)) return false; if (!RunConfigFile()) return false; if (!FillOtherConfig(*cmdline)) return false; // FIXME(brettw) get python path! #if defined(OS_WIN) build_settings_.set_python_path( base::FilePath(FILE_PATH_LITERAL("cmd.exe /c python"))); #else build_settings_.set_python_path(base::FilePath(FILE_PATH_LITERAL("python"))); #endif build_settings_.SetBuildDir(SourceDir("//out/gn/")); return true; } bool Setup::Run() { // Load the root build file and start runnung. build_settings_.toolchain_manager().StartLoadingUnlocked( SourceFile("//BUILD.gn")); if (!scheduler_.Run()) return false; Err err = build_settings_.item_tree().CheckForBadItems(); if (err.has_error()) { err.PrintToStdout(); return false; } return true; } bool Setup::FillSourceDir(const CommandLine& cmdline) { // Find the .gn file. base::FilePath root_path; // Prefer the command line args to the config file. base::FilePath relative_root_path = cmdline.GetSwitchValuePath(kSwitchRoot); if (!relative_root_path.empty()) { root_path = base::MakeAbsoluteFilePath(relative_root_path); dotfile_name_ = root_path.Append(kGnFile); } else { base::FilePath cur_dir; file_util::GetCurrentDirectory(&cur_dir); dotfile_name_ = FindDotFile(cur_dir); if (dotfile_name_.empty()) { Err(Location(), "Can't find source root.", "I could not find a \".gn\" file in the current directory or any " "parent,\nand the --root command-line argument was not specified.") .PrintToStdout(); return false; } root_path = dotfile_name_.DirName(); } if (scheduler_.verbose_logging()) scheduler_.Log("Using source root", FilePathToUTF8(root_path)); build_settings_.set_root_path(root_path); return true; } bool Setup::RunConfigFile() { if (scheduler_.verbose_logging()) scheduler_.Log("Got dotfile", FilePathToUTF8(dotfile_name_)); dotfile_input_file_.reset(new InputFile(SourceFile("//.gn"))); if (!dotfile_input_file_->Load(dotfile_name_)) { Err(Location(), "Could not load dotfile.", "The file \"" + FilePathToUTF8(dotfile_name_) + "\" cound't be loaded") .PrintToStdout(); return false; } Err err; dotfile_tokens_ = Tokenizer::Tokenize(dotfile_input_file_.get(), &err); if (err.has_error()) { err.PrintToStdout(); return false; } dotfile_root_ = Parser::Parse(dotfile_tokens_, &err); if (err.has_error()) { err.PrintToStdout(); return false; } dotfile_root_->AsBlock()->ExecuteBlockInScope(&dotfile_scope_, &err); if (err.has_error()) { err.PrintToStdout(); return false; } return true; } bool Setup::FillOtherConfig(const CommandLine& cmdline) { Err err; // Secondary source path. SourceDir secondary_source; if (cmdline.HasSwitch(kSecondarySource)) { // Prefer the command line over the config file. secondary_source = SourceDir(cmdline.GetSwitchValueASCII(kSecondarySource)); } else { // Read from the config file if present. const Value* secondary_value = dotfile_scope_.GetValue("secondary_source", true); if (secondary_value) { if (!secondary_value->VerifyTypeIs(Value::STRING, &err)) { err.PrintToStdout(); return false; } build_settings_.SetSecondarySourcePath( SourceDir(secondary_value->string_value())); } } // Build config file. const Value* build_config_value = dotfile_scope_.GetValue("buildconfig", true); if (!build_config_value) { Err(Location(), "No build config file.", "Your .gn file (\"" + FilePathToUTF8(dotfile_name_) + "\")\n" "didn't specify a \"buildconfig\" value.").PrintToStdout(); return false; } else if (!build_config_value->VerifyTypeIs(Value::STRING, &err)) { err.PrintToStdout(); return false; } build_settings_.set_build_config_file( SourceFile(build_config_value->string_value())); return true; }
30.888412
80
0.680006
MIPS
72ef6173b28a1535cc00fc18f6393683ab11f2f5
10,181
cpp
C++
Components/Components/Logic/KalmanFilter6DOF.cpp
muellerlab/agri-fly
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
[ "BSD-2-Clause" ]
1
2022-03-09T21:31:49.000Z
2022-03-09T21:31:49.000Z
Components/Components/Logic/KalmanFilter6DOF.cpp
muellerlab/agri-fly
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
[ "BSD-2-Clause" ]
4
2022-02-11T18:24:49.000Z
2022-03-28T01:16:51.000Z
Components/Components/Logic/KalmanFilter6DOF.cpp
muellerlab/agri-fly
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
[ "BSD-2-Clause" ]
null
null
null
#include "KalmanFilter6DOF.hpp" #include <cerrno> using namespace Onboard; float const TIME_CONST_ATT_CORR = 4.0f; //[s] KalmanFilter6DOF::KalmanFilter6DOF(BaseTimer* const masterTimer) : _estimateTimer(masterTimer), _timerLastGoodMeasUpdate(masterTimer), _IMUInitialized(false), _UWBInitialized(false) { //TODO: Sensible numbers here! _initStdDevPos = 3.0f; //[m] _initStdDevVel = 3.0f; //[m/s] _initStdDevAtt_perpToGravity = 10.0f * float(M_PI) / 180.0f; //[rad] _initStdDevAtt_aboutGravity = 30.0f * float(M_PI) / 180.0f; //[rad] _measNoiseStdDevAccelerometer = 5; //[m/s**2] _measNoiseStdDevRateGyro = 0.1f; //[rad/s] _measNoiseStdDevRangeMeasurements = 0.14f; //[m] _outlierDetectionStatisticalDist = 3.0f; _numMeasRejected = 0; _numMeasRejectedSequentially = 0; _maxNumMeasRejectedSequentially = 5; // TODO: add a set function for this _numResets = 0; _lastCheckNumResets = 0; } void KalmanFilter6DOF::Reset() { _numResets++; _IMUInitialized = _UWBInitialized = false; _pos = Vec3f(0, 0, 0); _vel = Vec3f(0, 0, 0); _att = Rotationf::Identity(); _angVel = Vec3f(0, 0, 0); //Default initial covariance, should make a paramter (or something!) for (int i = 0; i < NUM_STATES; i++) { for (int j = 0; j < NUM_STATES; j++) { _cov(i, j) = 0; } } for (int i = 0; i < 3; i++) { _cov(I_POS + i, I_POS + i) = _initStdDevPos * _initStdDevPos; _cov(I_VEL + i, I_VEL + i) = _initStdDevVel * _initStdDevVel; } //TODO FIXME. This is a hack. We want to encode that we're less certain of orientation // about gravity than other two directions. Below is OK, because _att is identity, but // this isn't future-proof. Nicer would be a geometric construction, using current estimate // of gravity. _cov(I_ATT + 0, I_ATT + 0) = _initStdDevAtt_perpToGravity * _initStdDevAtt_perpToGravity; _cov(I_ATT + 1, I_ATT + 1) = _initStdDevAtt_perpToGravity * _initStdDevAtt_perpToGravity; _cov(I_ATT + 2, I_ATT + 2) = _initStdDevAtt_aboutGravity * _initStdDevAtt_aboutGravity; //estimate is valid *now*: _estimateTimer.Reset(); _timerLastGoodMeasUpdate.Reset(); _lastMeasUpdateAttCorrection = Vec3f(0, 0, 0); } void KalmanFilter6DOF::Predict(Vec3f const measGyro, Vec3f const measAcc) { if (!_IMUInitialized) { Reset(); _IMUInitialized = true; _estimateTimer.Reset(); /*Assume we're measuring gravity; construct a consistent initial attitude: * * TODO: note, this does not correctly initialise the attitude covariance * necessarily: we want large uncertainty about gravity */ errno = 0; Vec3f const expAccelerometer = _att.Inverse() * Vec3f(0, 0, 1); Vec3f const accUnitVec = measAcc.GetUnitVector(); float const cosAngleError = expAccelerometer.Dot(accUnitVec); Vec3f rotAx = (accUnitVec.Cross(expAccelerometer)); if (rotAx.GetNorm2() > 1e-6f) { rotAx = rotAx / rotAx.GetNorm2(); } else { rotAx = Vec3f(1, 0, 0); //somewhat arbitrary } float angle = acosf(cosAngleError); if (errno) { //acos failed: if (cosAngleError < 0) { angle = float(M_PI); } else { angle = 0; } } _att = _att * Rotationf::FromAxisAngle(rotAx, angle); return; } //time since last run: float const dt = _estimateTimer.GetSeconds<float>(); _estimateTimer.Reset(); if (!_UWBInitialized) { _angVel = measGyro; //do a low-pass ("complementary") estimate of attitude, using gyro & accelerometer Rotationf newAtt = _att * Rotationf::FromRotationVector(measGyro * dt); _att = newAtt; Vec3f const expAccelerometer = _att.Inverse() * Vec3f(0, 0, 1); Vec3f const accUnitVec = measAcc.GetUnitVector(); Vec3f rotAx = (accUnitVec.Cross(expAccelerometer)); if (rotAx.GetNorm2() > 1e-6f) { rotAx = rotAx / rotAx.GetNorm2(); } else { rotAx = Vec3f(1, 0, 0); //somewhat arbitrary } float const cosAngleError = expAccelerometer.Dot(accUnitVec); errno = 0; float angle = acosf(cosAngleError); if (errno) { //acos failed, or sqrtf: if (cosAngleError < 0) { angle = float(M_PI); } else { angle = 0; } } float const corrAngle = (dt / TIME_CONST_ATT_CORR) * angle; _att = _att * Rotationf::FromAxisAngle(rotAx, corrAngle); return; } //mean prediction: //we're assuming that dt**2 ~= 0 Vec3f const pos(_pos); Vec3f const vel(_vel); Rotationf const att(_att); // Vec3f const angVel(_angVel); Vec3f const acc = _att * measAcc + Vec3f(0, 0, -9.81f); _pos = pos + vel * dt; _vel = vel + acc * dt; _att = att * Rotationf::FromRotationVector(measGyro * dt); //NOTE: we're using the rate gyro to integrate, not old estimate _angVel = measGyro; float rotMat[9]; att.GetRotationMatrix(rotMat); SquareMatrix<float, NUM_STATES> f = ZeroMatrix<float, NUM_STATES, NUM_STATES>(); //del(d(pos))/del(pos) = I f(I_POS + 0, I_POS + 0) = 1; f(I_POS + 1, I_POS + 1) = 1; f(I_POS + 2, I_POS + 2) = 1; //del(d(pos))/del(vel) = I*dt f(I_POS + 0, I_VEL + 0) = dt; f(I_POS + 1, I_VEL + 1) = dt; f(I_POS + 2, I_VEL + 2) = dt; //del(d(vel))/del(vel) = I f(I_VEL + 0, I_VEL + 0) = 1; f(I_VEL + 1, I_VEL + 1) = 1; f(I_VEL + 2, I_VEL + 2) = 1; //del(d(vel))/del(att) //dt*(accMeas(1)*Rref(0, 2) - accMeas(2)*Rref(0, 1)) //dt*(accMeas(1)*Rref(1, 2) - accMeas(2)*Rref(1, 1)) //dt*(accMeas(1)*Rref(2, 2) - accMeas(2)*Rref(2, 1)) f(I_VEL + 0, I_ATT + 0) = dt * (+measAcc.y * rotMat[3 * 0 + 2] - measAcc.z * rotMat[3 * 0 + 1]); f(I_VEL + 1, I_ATT + 0) = dt * (+measAcc.y * rotMat[3 * 1 + 2] - measAcc.z * rotMat[3 * 1 + 1]); f(I_VEL + 2, I_ATT + 0) = dt * (+measAcc.y * rotMat[3 * 2 + 2] - measAcc.z * rotMat[3 * 2 + 1]); //dt*(-accMeas(0)*Rref(0, 2) + accMeas(2)*Rref(0, 0)) //dt*(-accMeas(0)*Rref(1, 2) + accMeas(2)*Rref(1, 0)) //dt*(-accMeas(0)*Rref(2, 2) + accMeas(2)*Rref(2, 0)) f(I_VEL + 0, I_ATT + 1) = dt * (-measAcc.x * rotMat[3 * 0 + 2] + measAcc.z * rotMat[3 * 0 + 0]); f(I_VEL + 1, I_ATT + 1) = dt * (-measAcc.x * rotMat[3 * 1 + 2] + measAcc.z * rotMat[3 * 1 + 0]); f(I_VEL + 2, I_ATT + 1) = dt * (-measAcc.x * rotMat[3 * 2 + 2] + measAcc.z * rotMat[3 * 2 + 0]); //dt*(accMeas(0)*Rref(0, 1) - accMeas(1)*Rref(0, 0)), //dt*(accMeas(0)*Rref(1, 1) - accMeas(1)*Rref(1, 0)), //dt*(accMeas(0)*Rref(2, 1) - accMeas(1)*Rref(2, 0)), f(I_VEL + 0, I_ATT + 2) = dt * (+measAcc.x * rotMat[3 * 0 + 1] - measAcc.y * rotMat[3 * 0 + 0]); f(I_VEL + 1, I_ATT + 2) = dt * (+measAcc.x * rotMat[3 * 1 + 1] - measAcc.y * rotMat[3 * 1 + 0]); f(I_VEL + 2, I_ATT + 2) = dt * (+measAcc.x * rotMat[3 * 2 + 1] - measAcc.y * rotMat[3 * 2 + 0]); //del(d(att))/del(att) f(I_ATT + 0, I_ATT + 0) = 1; f(I_ATT + 1, I_ATT + 0) = -(dt * measGyro.z + _lastMeasUpdateAttCorrection.z / 2.0f); f(I_ATT + 2, I_ATT + 0) = +(dt * measGyro.y + _lastMeasUpdateAttCorrection.y / 2.0f); f(I_ATT + 0, I_ATT + 1) = +(dt * measGyro.z + _lastMeasUpdateAttCorrection.z / 2.0f); f(I_ATT + 1, I_ATT + 1) = 1; f(I_ATT + 2, I_ATT + 1) = -(dt * measGyro.x + _lastMeasUpdateAttCorrection.x / 2.0f); f(I_ATT + 0, I_ATT + 2) = -(dt * measGyro.y + _lastMeasUpdateAttCorrection.y / 2.0f); f(I_ATT + 1, I_ATT + 2) = +(dt * measGyro.x + _lastMeasUpdateAttCorrection.x / 2.0f); f(I_ATT + 2, I_ATT + 2) = 1; _lastMeasUpdateAttCorrection = Vec3f(0, 0, 0); //Covariance prediction: _cov = f * _cov * f.transpose(); //add process noise: for (int i = 0; i < 3; i++) { _cov(I_VEL + i, I_VEL + i) += _measNoiseStdDevAccelerometer * _measNoiseStdDevAccelerometer * dt * dt; _cov(I_ATT + i, I_ATT + i) += _measNoiseStdDevRateGyro * _measNoiseStdDevRateGyro * dt * dt; } } void KalmanFilter6DOF::UpdateWithRangeMeasurement(Vec3f const targetPosition, float const range) { if (!_IMUInitialized) { return; } //Test for NaN in range: if (not (range == range)) { return; } _UWBInitialized = true; float const expectedRange = (_pos - targetPosition).GetNorm2(); Vec3f const targetDirection = (_pos - targetPosition) / expectedRange; //Measurement matrix: Matrix<float, 1, NUM_STATES> H; for (int i = 0; i < 3; i++) { H(0, I_POS + i) = targetDirection[i]; H(0, I_VEL + i) = 0; H(0, I_ATT + i) = 0; } //filter gain: float const innovationCov = (H * (_cov * H.transpose()))(0, 0) + _measNoiseStdDevRangeMeasurements * _measNoiseStdDevRangeMeasurements; //scalar measurement, so easy Matrix<float, NUM_STATES, 1> L = _cov * H.transpose() * (1 / innovationCov); //can now do a Mahalanobis outlier detection: float const measDistSqr = (range - expectedRange) * (range - expectedRange) / innovationCov; //scalar is easy if (measDistSqr > _outlierDetectionStatisticalDist * _outlierDetectionStatisticalDist) { //Reject this as an outlier _numMeasRejected++; _numMeasRejectedSequentially++; if (_numMeasRejectedSequentially >= _maxNumMeasRejectedSequentially) { //TODO: Is this the right action? Alternative is to force-accept the measurment. -- blame Saman. Reset(); } return; } _numMeasRejectedSequentially = 0; //state update: Matrix<float, NUM_STATES, 1> dx = L * (range - expectedRange); _pos = _pos + Vec3f(dx(I_POS + 0, 0), dx(I_POS + 1, 0), dx(I_POS + 2, 0)); _vel = _vel + Vec3f(dx(I_VEL + 0, 0), dx(I_VEL + 1, 0), dx(I_VEL + 2, 0)); _lastMeasUpdateAttCorrection = Vec3f(dx(I_ATT + 0, 0), dx(I_ATT + 1, 0), dx(I_ATT + 2, 0)); _att = _att * Rotationf::FromRotationVector(_lastMeasUpdateAttCorrection); //covariance update: _cov = (IdentityMatrix<float, NUM_STATES>() - L * H) * _cov; MakeCovarianceSymmetric(); _timerLastGoodMeasUpdate.Reset(); } void KalmanFilter6DOF::MakeCovarianceSymmetric() { for (int i = 0; i < NUM_STATES; i++) { for (int j = i + 1; j < NUM_STATES; j++) { _cov(i, j) = _cov(j, i); } } }
32.841935
126
0.615264
muellerlab
72f0219ecd22fe90ce62aaa8eee1e4dc6d0118a4
2,595
cc
C++
zircon/kernel/lib/code-patching/code-patching.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
zircon/kernel/lib/code-patching/code-patching.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
null
null
null
zircon/kernel/lib/code-patching/code-patching.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT #include <lib/arch/nop.h> #include <lib/code-patching/code-patching.h> #include <lib/fitx/result.h> #include <lib/zbitl/error-stdio.h> #include <ktl/move.h> #include <ktl/string_view.h> #include <ktl/enforce.h> namespace code_patching { fitx::result<Patcher::Error> Patcher::Init(Bootfs bootfs, ktl::string_view directory) { ZX_ASSERT(!directory.empty()); bootfs_ = ktl::move(bootfs); dir_ = directory; auto it = bootfs_.find({dir_, kPatchesBin}); if (auto result = bootfs_.take_error(); result.is_error()) { return result; } if (it == bootfs_.end()) { return fitx::error{Error{.reason = "failed to find patch directives"sv}}; } if (it->data.size() % sizeof(Directive) != 0) { fitx::error{Error{ .reason = "patch directive payload has bad size"sv, .filename = it->name, .entry_offset = it.dirent_offset(), }}; } patches_ = { reinterpret_cast<const Directive*>(it->data.data()), it->data.size() / sizeof(Directive), }; return fitx::ok(); } fitx::result<Patcher::Error> Patcher::PatchWithAlternative(ktl::span<ktl::byte> instructions, ktl::string_view alternative) { auto result = GetPatchAlternative(alternative); if (result.is_error()) { return result.take_error(); } Bytes bytes = ktl::move(result).value(); ZX_ASSERT_MSG( instructions.size() >= bytes.size(), "instruction range (%zu bytes) is too small for patch alternative \"%.*s\" (%zu bytes)", instructions.size(), static_cast<int>(alternative.size()), alternative.data(), bytes.size()); memcpy(instructions.data(), bytes.data(), bytes.size()); PrepareToSync(instructions); return fitx::ok(); } void Patcher::NopFill(ktl::span<ktl::byte> instructions) { arch::NopFill(instructions); PrepareToSync(instructions); } fitx::result<Patcher::Error, Patcher::Bytes> Patcher::GetPatchAlternative(ktl::string_view name) { auto it = bootfs_.find({dir_, kPatchAlternativeDir, name}); if (auto result = bootfs_.take_error(); result.is_error()) { return result.take_error(); } if (it == bootfs_.end()) { return fitx::error{Error{.reason = "failed to find patch alternative"sv}}; } return fitx::ok(it->data); } void PrintPatcherError(const Patcher::Error& error, FILE* f) { return zbitl::PrintBootfsError(error, f); } } // namespace code_patching
30.174419
99
0.66474
fabio-d
72f02ed9254a861eb20cee1c4e4735344a970481
7,164
cpp
C++
Code/Framework/AzCore/AzCore/Android/Utils.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Framework/AzCore/AzCore/Android/Utils.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzCore/AzCore/Android/Utils.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Android/Utils.h> #include <AzCore/Android/AndroidEnv.h> #include <AzCore/Android/APKFileHandler.h> #include <AzCore/Android/JNI/Object.h> #include <AzCore/Debug/Trace.h> #include <AzCore/Memory/OSAllocator.h> #include <AzCore/IO/Path/Path.h> namespace AZ { namespace Android { namespace Utils { namespace { //////////////////////////////////////////////////////////////// constexpr const char* GetApkAssetsPrefix() { return "/APK"; } } //////////////////////////////////////////////////////////////// jclass GetActivityClassRef() { return AndroidEnv::Get()->GetActivityClassRef(); } //////////////////////////////////////////////////////////////// jobject GetActivityRef() { return AndroidEnv::Get()->GetActivityRef(); } //////////////////////////////////////////////////////////////// AAssetManager* GetAssetManager() { return AndroidEnv::Get()->GetAssetManager(); } //////////////////////////////////////////////////////////////// AConfiguration* GetConfiguration() { return AndroidEnv::Get()->GetConfiguration(); } //////////////////////////////////////////////////////////////// void UpdateConfiguration() { return AndroidEnv::Get()->UpdateConfiguration(); } //////////////////////////////////////////////////////////////// const char* GetAppPrivateStoragePath() { return AndroidEnv::Get()->GetAppPrivateStoragePath(); } //////////////////////////////////////////////////////////////// const char* GetAppPublicStoragePath() { return AndroidEnv::Get()->GetAppPublicStoragePath(); } //////////////////////////////////////////////////////////////// const char* GetObbStoragePath() { return AndroidEnv::Get()->GetObbStoragePath(); } //////////////////////////////////////////////////////////////// const char* GetPackageName() { return AndroidEnv::Get()->GetPackageName(); } //////////////////////////////////////////////////////////////// int GetAppVersionCode() { return AndroidEnv::Get()->GetAppVersionCode(); } //////////////////////////////////////////////////////////////// const char* GetObbFileName(bool mainFile) { return AndroidEnv::Get()->GetObbFileName(mainFile); } //////////////////////////////////////////////////////////////// bool IsApkPath(const char* filePath) { return AZ::IO::PathView(filePath).IsRelativeTo(AZ::IO::PathView(GetApkAssetsPrefix())); } //////////////////////////////////////////////////////////////// AZ::IO::FixedMaxPath StripApkPrefix(const char* filePath) { constexpr AZ::IO::PathView apkPrefixView = GetApkAssetsPrefix(); return AZ::IO::PathView(filePath).LexicallyProximate(apkPrefixView); } //////////////////////////////////////////////////////////////// const char* FindAssetsDirectory() { #if defined(LY_NO_ASSETS) // The TestRunner app which runs unit tests does not have any assets. return GetAppPublicStoragePath(); #endif #if !defined(_RELEASE) // first check to see if they are in public storage (application specific) const char* publicAppStorage = GetAppPublicStoragePath(); OSString path = OSString::format("%s/engine.json", publicAppStorage); AZ_TracePrintf("Android::Utils", "Searching for %s\n", path.c_str()); FILE* f = fopen(path.c_str(), "r"); if (f != nullptr) { fclose(f); return publicAppStorage; } #endif // !defined(_RELEASE) // if they aren't in public storage, they are in private storage (APK) AAssetManager* mgr = GetAssetManager(); if (mgr) { AAsset* asset = AAssetManager_open(mgr, "engine.json", AASSET_MODE_UNKNOWN); if (asset) { AAsset_close(asset); return GetApkAssetsPrefix(); } } AZ_Assert(false, "Failed to locate the engine.json path"); return nullptr; } //////////////////////////////////////////////////////////////// void ShowSplashScreen() { JNI::Internal::Object<AZ::OSAllocator> activity(GetActivityClassRef(), GetActivityRef()); activity.RegisterMethod("ShowSplashScreen", "()V"); activity.InvokeVoidMethod("ShowSplashScreen"); } //////////////////////////////////////////////////////////////// void DismissSplashScreen() { JNI::Internal::Object<AZ::OSAllocator> activity(GetActivityClassRef(), GetActivityRef()); activity.RegisterMethod("DismissSplashScreen", "()V"); activity.InvokeVoidMethod("DismissSplashScreen"); } //////////////////////////////////////////////////////////////// ANativeWindow* GetWindow() { return AndroidEnv::Get()->GetWindow(); } //////////////////////////////////////////////////////////////// bool GetWindowSize(int& widthPixels, int& heightPixels) { ANativeWindow* window = GetWindow(); if (window) { widthPixels = ANativeWindow_getWidth(window); heightPixels = ANativeWindow_getHeight(window); // should an error occur from the above functions a negative value will be returned return (widthPixels > 0 && heightPixels > 0); } return false; } //////////////////////////////////////////////////////////////// void SetLoadFilesToMemory(const char* fileNames) { APKFileHandler::SetLoadFilesToMemory(fileNames); } } } }
36.365482
158
0.400195
aaarsene
72f505ad7263cbbb422071cf83d1160c3602ebe7
5,074
cpp
C++
Game/keyconfiglabel.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
1
2021-04-14T15:06:55.000Z
2021-04-14T15:06:55.000Z
Game/keyconfiglabel.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
7
2020-05-14T02:14:26.000Z
2020-05-22T04:57:47.000Z
Game/keyconfiglabel.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
null
null
null
// Copyright(c) 2018 Seth Ballantyne <seth.ballantyne@gmail.com> // // 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 "keyconfiglabel.h" #include "gameoptions.h" void KeyConfigLabel::HandleKey(unsigned char key) { if(!KeyInUse(key)) { UpdateConfig(key); changingKey = false; } else { // attempted to assign a key that's already in bound // to another option. Play a prompt indicating the error. ResourceManager::GetSoundBuffer("error3")->Play(); } } bool KeyConfigLabel::KeyInUse(unsigned char key) { array<SelectableControl ^, 1> ^controls = ParentContainer->GetControls(); for(int i = 0; i < controls->Length; i++) { if(controls[i]->GetType() == KeyConfigLabel::typeid && !ReferenceEquals(this, controls[i])) { KeyConfigLabel ^keyConfigLabel = dynamic_cast<KeyConfigLabel ^>(controls[i]); String ^keyText = Input::GetDIKAsString(key); // is the key in use? if(nullptr == keyText || keyConfigLabel->label->Text == keyText) { // if keyText evaluates to nullptr, the user has pressed a key that's not in the // lookup table used by GetDIKAsString() to retrieve the string representation of the key. // If it's not in the table, it's an invalid key for our purposes, so pretend // it's already in use; this'll force them to bind another key and play the error // sound effect. return true; } } } return false; } KeyConfigLabel::KeyConfigLabel(int x, int y, String ^font, int selectedIndex, String ^optionsKey, MenuItemContainer ^parentContainer) : ContainerControl(x, y, selectedIndex, parentContainer) { if(nullptr == optionsKey) { throw gcnew ArgumentNullException("optionsKey"); } else if(nullptr == font) { throw gcnew ArgumentNullException("font"); } else if(nullptr == parentContainer) { throw gcnew ArgumentNullException("parentContainer"); } if(String::Empty == optionsKey) { throw gcnew ArgumentException("optionsKey evaluates to String::Empty."); } else if(String::Empty == font) { throw gcnew ArgumentException("font evaluates to String::Empty."); } this->optionsKey = optionsKey; try { label = gcnew Label(x, y, font, nullptr); } catch(...) { throw; } } void KeyConfigLabel::ReceiveSceneArgs(array<Object ^, 1> ^sceneArgs) { if(firstRun) { firstRun = false; int keyValue = GameOptions::GetValue(optionsKey, -1); String ^caption = Input::GetDIKAsString(keyValue); if(nullptr == caption) { caption = "UNDEFINED"; LogManager::WriteLine(LogType::Debug, "Key assigned to {0} is an illegal value.", optionsKey); } label->Text = caption; } } void KeyConfigLabel::Update(Keys ^keyboardState, Mouse ^mouseState) { if(nullptr == keyboardState) { throw gcnew ArgumentNullException("keyboardState"); } else if(nullptr == mouseState) { throw gcnew ArgumentNullException("keyboardState"); } if(changingKey != true) { if(keyboardState->KeyPressed(DIK_RETURN)) { changingKey = true; label->Text = "PRESS A KEY"; } else if(keyboardState->KeyPressed(DIK_UP)) { ParentContainer->SelectPreviousControl(); } else if(keyboardState->KeyPressed(DIK_DOWN)) { ParentContainer->SelectNextControl(); } } else { if(mouseState->ButtonDown(0)) { HandleKey(0); } else if(mouseState->ButtonDown(1)) { HandleKey(1); } else { int pressedKey = keyboardState->PressedKey; // in the off chance that the user presses keys and mouse buttons(s) at the same time, // the keyboard takes precendence. if(pressedKey != -1) // -1 means a key hasn't been pressed. { HandleKey(pressedKey); } } } }
30.566265
133
0.645644
sethballantyne
72f5f37c1905bf7f237fd45aa63ef18e7bc77b41
11,687
cpp
C++
src/services/events/system.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
26
2018-03-19T15:59:46.000Z
2021-08-06T16:13:16.000Z
src/services/events/system.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
34
2018-01-21T17:43:29.000Z
2020-06-27T02:00:53.000Z
src/services/events/system.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
3
2019-12-08T22:26:35.000Z
2021-06-25T17:05:57.000Z
/* Copyright (c) 2017, Patrick Lafferty 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "system.h" #include "ipc.h" #include <services.h> #include <system_calls.h> #include <saturn/wait.h> #include <saturn/parsing.h> using namespace VirtualFileSystem; namespace Event { void Log::addEntry(std::string_view entry) { entries.push_back(std::string{entry}); } int EventSystem::getFunction(std::string_view name) { if (name.compare("subscribe") == 0) { return static_cast<int>(FunctionId::Subscribe); } return -1; } void EventSystem::readFunction(uint32_t requesterTaskId, uint32_t requestId, uint32_t functionId) { describeFunction(requesterTaskId, requestId, functionId); } void EventSystem::writeFunction(uint32_t requesterTaskId, uint32_t requestId, uint32_t functionId, Vostok::ArgBuffer& args) { auto type = args.readType(); if (type != Vostok::ArgTypes::Function) { Vostok::replyWriteSucceeded(requesterTaskId, requestId, false); return; } switch(functionId) { case static_cast<uint32_t>(FunctionId::Subscribe): { auto subscriberTaskId = args.read<uint32_t>(Vostok::ArgTypes::Uint32); if (!args.hasErrors()) { subscribe(requesterTaskId, requestId, subscriberTaskId); } else { Vostok::replyWriteSucceeded(requesterTaskId, requestId, false); } break; } default: { Vostok::replyWriteSucceeded(requesterTaskId, requestId, false); } } } void EventSystem::describeFunction(uint32_t requesterTaskId, uint32_t requestId, uint32_t functionId) { ReadResult result {}; result.requestId = requestId; result.success = true; Vostok::ArgBuffer args{result.buffer, sizeof(result.buffer)}; args.writeType(Vostok::ArgTypes::Function); switch(functionId) { case static_cast<uint32_t>(FunctionId::Subscribe): { args.writeType(Vostok::ArgTypes::Uint32); args.writeType(Vostok::ArgTypes::EndArg); break; } default: { result.success = false; } } result.recipientId = requesterTaskId; send(IPC::RecipientType::TaskId, &result); } void EventSystem::subscribe(uint32_t requesterTaskId, uint32_t requestId, uint32_t subscriberTaskId) { char path[256]; memset(path, '\0', 256); sprintf(path, "/applications/%d/receive", subscriberTaskId); auto result = openSynchronous(path); if (result.success) { subscribers.push_back(result.fileDescriptor); if (!receiveSignature) { auto readResult = readSynchronous(result.fileDescriptor, 0); receiveSignature = ReceiveSignature {{}, {nullptr, 0}}; auto& sig = receiveSignature.value(); sig.result = readResult; sig.args = Vostok::ArgBuffer{&sig.result.buffer[0], 256}; } } Vostok::replyWriteSucceeded(requesterTaskId, requestId, result.success); } void EventSystem::handleOpenRequest(OpenRequest& request) { OpenResult result; result.requestId = request.requestId; result.serviceType = Kernel::ServiceType::VFS; auto words = split({request.path, strlen(request.path)}, '/'); if (words.size() == 1) { if (words[0].compare("subscribe") == 0) { Vostok::FileDescriptor descriptor; descriptor.instance = this; descriptor.functionId = 0; descriptor.type = Vostok::DescriptorType::Function; auto id = nextDescriptorId++; openDescriptors.push_back(FileDescriptor{id, descriptor}); result.fileDescriptor = id; result.success = true; } else { auto it = std::find_if(begin(logs), end(logs), [&](const auto& log) { return words[0].compare(log->name) == 0; }); if (it != end(logs)) { FileDescriptor descriptor {nextDescriptorId++, it->get()}; openDescriptors.push_back(descriptor); result.fileDescriptor = descriptor.id; result.success = true; } } } send(IPC::RecipientType::ServiceName, &result); } void EventSystem::handleCreateRequest(CreateRequest& request) { auto words = split({request.path, strlen(request.path)}, '/'); CreateResult result; result.requestId = request.requestId; result.serviceType = Kernel::ServiceType::VFS; if (words.size() == 1) { auto it = std::find_if(begin(logs), end(logs), [&](const auto& log) { return words[0].compare(log->name) == 0; }); if (it == end(logs)) { logs.push_back(std::make_unique<Log>(words[0])); result.success = true; } } send(IPC::RecipientType::ServiceName, &result); } void EventSystem::handleReadRequest(ReadRequest& request) { auto it = std::find_if(begin(openDescriptors), end(openDescriptors), [&](const auto& descriptor) { return descriptor.id == request.fileDescriptor; }); if (it != end(openDescriptors)) { if (std::holds_alternative<Vostok::FileDescriptor>(it->object)) { auto& desc = std::get<Vostok::FileDescriptor>(it->object); desc.read(request.senderTaskId, request.requestId); } } } void EventSystem::handleWriteRequest(WriteRequest& request) { WriteResult result; result.requestId = request.requestId; result.serviceType = Kernel::ServiceType::VFS; result.recipientId = request.senderTaskId; auto it = std::find_if(begin(openDescriptors), end(openDescriptors), [&](auto& d) { return d.id == request.fileDescriptor; }); if (it != end(openDescriptors)) { result.success = true; if (std::holds_alternative<Log*>(it->object)) { auto log = std::get<Log*>(it->object); std::string_view view {reinterpret_cast<char*>(&request.buffer[0]), request.writeLength}; log->addEntry(view); if (!subscribers.empty()) { broadcastEvent(view); } forwardToSerialPort(request); } else if (std::holds_alternative<Vostok::FileDescriptor>(it->object)) { auto descriptor = std::get<Vostok::FileDescriptor>(it->object); Vostok::ArgBuffer args{request.buffer, sizeof(request.buffer)}; descriptor.write(request.senderTaskId, request.requestId, args); return; } } send(IPC::RecipientType::TaskId, &result); } void EventSystem::broadcastEvent(std::string_view event) { auto signature = receiveSignature.value(); signature.args.typedBuffer = signature.result.buffer; signature.args.readType(); signature.args.write(event.data(), Vostok::ArgTypes::Cstring); for (auto subscriber : subscribers) { write(subscriber, signature.result.buffer, sizeof(signature.result.buffer)); } } void EventSystem::forwardToSerialPort(WriteRequest& request) { request.fileDescriptor = serialFileDescriptor; request.serviceType = Kernel::ServiceType::VFS; send(IPC::RecipientType::ServiceName, &request); } void EventSystem::messageLoop() { auto openResult = openSynchronous("/serial/output"); serialFileDescriptor = openResult.fileDescriptor; while (true) { IPC::MaximumMessageBuffer buffer; receive(&buffer); switch (buffer.messageNamespace) { case IPC::MessageNamespace::VFS: { switch (static_cast<MessageId>(buffer.messageId)) { case MessageId::OpenRequest: { auto request = IPC::extractMessage<OpenRequest>(buffer); handleOpenRequest(request); break; } case MessageId::CreateRequest: { auto request = IPC::extractMessage<CreateRequest>(buffer); handleCreateRequest(request); break; } case MessageId::ReadRequest: { auto request = IPC::extractMessage<ReadRequest>(buffer); handleReadRequest(request); break; } case MessageId::WriteRequest: { auto request = IPC::extractMessage<WriteRequest>(buffer); handleWriteRequest(request); break; } case MessageId::WriteResult: { break; } default: break; } break; } default: break; } } } void service() { waitForServiceRegistered(Kernel::ServiceType::VFS); Saturn::Event::waitForMount("/serial"); MountRequest request; const char* path = "/events"; memcpy(request.path, path, strlen(path) + 1); request.serviceType = Kernel::ServiceType::VFS; request.cacheable = false; send(IPC::RecipientType::ServiceName, &request); auto system = new EventSystem(); system->messageLoop(); } }
36.867508
129
0.57534
patrick-lafferty
72fabfadf143f37ccb37fb1957981107315c2112
3,480
cpp
C++
src/plugins/azoth/plugins/vader/vader.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/azoth/plugins/vader/vader.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/azoth/plugins/vader/vader.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "vader.h" #include <QIcon> #include <QAction> #include <QUrl> #include <util/util.h> #include <util/xpc/util.h> #include <xmlsettingsdialog/xmlsettingsdialog.h> #include <interfaces/core/ientitymanager.h> #include <interfaces/azoth/iproxyobject.h> #include "mrimprotocol.h" #include "mrimbuddy.h" #include "vaderutil.h" #include "xmlsettingsmanager.h" namespace LC { namespace Azoth { namespace Vader { void Plugin::Init (ICoreProxy_ptr proxy) { Util::InstallTranslator ("azoth_vader"); XSD_ = std::make_shared<Util::XmlSettingsDialog> (); XSD_->RegisterObject (&XmlSettingsManager::Instance (), "azothvadersettings.xml"); CoreProxy_ = proxy; } void Plugin::SecondInit () { Proto_ = std::make_shared<MRIMProtocol> (AzothProxy_, CoreProxy_); emit gotNewProtocols ({ Proto_.get () }); } void Plugin::Release () { Proto_.reset (); } QByteArray Plugin::GetUniqueID () const { return "org.LeechCraft.Azoth.Vader"; } QString Plugin::GetName () const { return "Azoth Vader"; } QString Plugin::GetInfo () const { return tr ("Support for the Mail.ru Agent protocol."); } QIcon Plugin::GetIcon () const { static QIcon icon ("lcicons:/plugins/azoth/plugins/vader/resources/images/vader.svg"); return icon; } Util::XmlSettingsDialog_ptr Plugin::GetSettingsDialog () const { return XSD_; } QSet<QByteArray> Plugin::GetPluginClasses () const { QSet<QByteArray> classes; classes << "org.LeechCraft.Plugins.Azoth.Plugins.IProtocolPlugin"; return classes; } QObject* Plugin::GetQObject () { return this; } QList<QObject*> Plugin::GetProtocols () const { if (Proto_) return { Proto_.get () }; else return {}; } void Plugin::initPlugin (QObject *proxy) { AzothProxy_ = qobject_cast<IProxyObject*> (proxy); } void Plugin::hookEntryActionAreasRequested (LC::IHookProxy_ptr, QObject*, QObject*) { } void Plugin::hookEntryActionsRequested (LC::IHookProxy_ptr proxy, QObject *entry) { if (!qobject_cast<MRIMBuddy*> (entry)) return; if (!EntryServices_.contains (entry)) { auto list = VaderUtil::GetBuddyServices (this, SLOT (entryServiceRequested ())); for (const auto act : list) act->setProperty ("Azoth/Vader/Entry", QVariant::fromValue<QObject*> (entry)); EntryServices_ [entry] = list; } auto list = proxy->GetReturnValue ().toList (); for (const auto act : EntryServices_ [entry]) list += QVariant::fromValue<QObject*> (act); proxy->SetReturnValue (list); } void Plugin::entryServiceRequested () { const auto& url = sender ()->property ("URL").toString (); const auto buddyObj = sender ()->property ("Azoth/Vader/Entry").value<QObject*> (); const auto buddy = qobject_cast<MRIMBuddy*> (buddyObj); const auto& subst = VaderUtil::SubstituteNameDomain (url, buddy->GetHumanReadableID ()); const auto& e = Util::MakeEntity (QUrl (subst), {}, OnlyHandle | FromUserInitiated); CoreProxy_->GetEntityManager ()->HandleEntity (e); } } } } LC_EXPORT_PLUGIN (leechcraft_azoth_vader, LC::Azoth::Vader::Plugin);
24
88
0.670977
Maledictus
72fd44ad283abd8d85d93a4d070f7e9932fdb001
922
hpp
C++
Libraries/Libui/LayoutParams.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
21
2021-08-22T19:06:54.000Z
2022-03-31T12:44:30.000Z
Libraries/Libui/LayoutParams.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
1
2021-09-01T22:55:59.000Z
2021-09-08T20:52:09.000Z
Libraries/Libui/LayoutParams.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
null
null
null
#pragma once namespace UI { enum class LayoutParamsType { Default, MarginLayoutParams, LinearLayoutParams, }; struct LayoutParams { LayoutParams() = default; LayoutParams(LayoutParamsType type) : type(type) { } enum Size { WRAP_CONTENT = -2, MATCH_PARENT = -1, }; int width {}; int height {}; LayoutParamsType type {}; }; struct MarginLayoutParams : public LayoutParams { using LayoutParams::LayoutParams; MarginLayoutParams() : LayoutParams(LayoutParamsType::MarginLayoutParams) { } int left_margin {}; int top_margin {}; int right_margin {}; int bottom_margin {}; }; struct LinearLayoutParams : public MarginLayoutParams { using MarginLayoutParams::MarginLayoutParams; LinearLayoutParams() : MarginLayoutParams(LayoutParamsType::LinearLayoutParams) { } int weight {}; }; }
18.816327
66
0.64859
Plunkerusr
72fe365c0ac25e513416ba572994d39c7a0c54bf
545
cpp
C++
ICPC/Repechaje2021/base.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
ICPC/Repechaje2021/base.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
ICPC/Repechaje2021/base.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <stdio.h> #include <string> #include <vector> #include <map> #include <math.h> #include <numeric> #include <queue> #include <stack> #include <utility> #include <queue> #include <set> #include <iomanip> using namespace std; typedef int64_t ll; typedef pair<int,int> pii; #define loop(i,a,b) for(int i = a; i < b; ++i) const int maxN = 200005; int n; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); //if(fopen("case.txt", "r")) freopen("case.txt", "r", stdin); return 0; }
17.580645
65
0.658716
CaDe27
72fe5603bd613549421b714a7f45b5f916b921bd
132
cpp
C++
Numbers/Fibonacci_Recursive.cpp
PhilRybka/Algorithms
86a11777aa7fc19abee845f0c18893afbd491130
[ "MIT" ]
null
null
null
Numbers/Fibonacci_Recursive.cpp
PhilRybka/Algorithms
86a11777aa7fc19abee845f0c18893afbd491130
[ "MIT" ]
null
null
null
Numbers/Fibonacci_Recursive.cpp
PhilRybka/Algorithms
86a11777aa7fc19abee845f0c18893afbd491130
[ "MIT" ]
null
null
null
//Returns the n-th element of the Fibonacci sequence int fib(int n){ if(n==1||n==2) return 1; return fib(n-2)+fib(n-1); }
16.5
52
0.613636
PhilRybka
72ffb2d48de7d5b06f9e60c525b2c3c216c1aabf
3,828
cpp
C++
aligndiff/algorithms/lcslength_ondgreedy.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
14
2017-06-16T22:52:38.000Z
2022-02-14T04:11:06.000Z
aligndiff/algorithms/lcslength_ondgreedy.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:50:04.000Z
2019-04-01T09:53:17.000Z
aligndiff/algorithms/lcslength_ondgreedy.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:05:17.000Z
2018-09-18T01:28:42.000Z
// Copyright (c) 2017 mogemimi. Distributed under the MIT license. #include "aligndiff.h" #include <cassert> #include <cstdlib> namespace aligndiff { int computeLCSLength_ONDGreedyAlgorithm( const std::string& text1, const std::string& text2) { // NOTE: // This algorithm is based on Myers's An O((M+N)D) Greedy Algorithm in // "An O(ND)Difference Algorithm and Its Variations", // Algorithmica (1986), pages 251-266. if (text1.empty() || text2.empty()) { return 0; } const auto M = static_cast<int>(text1.size()); const auto N = static_cast<int>(text2.size()); const auto maxD = M + N; const auto offset = N; std::vector<int> vertices(M + N + 1); #if !defined(NDEBUG) // NOTE: // There is no need to initialize with the zero value for array elements, // but you have to assign the zero value to `vertices[1 + offset]`. std::fill(std::begin(vertices), std::end(vertices), -1); #endif vertices[1 + offset] = 0; std::vector<int> lcsLengths(M + N + 1); lcsLengths[1 + offset] = 0; for (int d = 0; d <= maxD; ++d) { const int startK = -std::min(d, (N * 2) - d); const int endK = std::min(d, (M * 2) - d); assert((-N <= startK) && (endK <= M)); assert(std::abs(startK % 2) == (d % 2)); assert(std::abs(endK % 2) == (d % 2)); assert((d > N) ? (startK == -(N * 2 - d)) : (startK == -d)); assert((d > M) ? (endK == (M * 2 - d)) : (endK == d)); for (int k = startK; k <= endK; k += 2) { assert((-N <= k) && (k <= M)); assert(std::abs(k % 2) == (d % 2)); const auto kOffset = k + offset; int x = 0; int lcsLength = 0; if (k == startK) { // NOTE: Move directly from vertex(x, y - 1) to vertex(x, y) x = vertices[kOffset + 1]; lcsLength = lcsLengths[kOffset + 1]; } else if (k == endK) { // NOTE: Move directly from vertex(x - 1, y) to vertex(x, y) x = vertices[kOffset - 1] + 1; lcsLength = lcsLengths[kOffset - 1]; } else if (vertices[kOffset - 1] < vertices[kOffset + 1]) { // NOTE: Move from vertex(k + 1) to vertex(k) // vertex(k + 1) is ahead of vertex(k - 1). assert(-N < k && k < M); assert((k != -d) && (k != -N)); assert((k != d) && (k != M)); x = vertices[kOffset + 1]; lcsLength = lcsLengths[kOffset + 1]; } else { // NOTE: Move from vertex(k - 1) to vertex(k) // vertex(k - 1) is ahead of vertex(k + 1). assert(-N < k && k < M); assert((k != -d) && (k != -N)); assert((k != d) && (k != M)); assert(vertices[kOffset - 1] >= vertices[kOffset + 1]); x = vertices[kOffset - 1] + 1; lcsLength = lcsLengths[kOffset - 1]; } // NOTE: `k` is defined from `x - y = k`. int y = x - k; assert(x >= 0 && y >= 0); #if !defined(NDEBUG) if (d == 0) { assert((x == 0) && (y == 0) && (k == 0)); } #endif while (x < M && y < N && text1[x] == text2[y]) { // NOTE: This loop finds a possibly empty sequence // of diagonal edges called a 'snake'. x += 1; y += 1; lcsLength += 1; } if (x >= M && y >= N) { return lcsLength; } vertices[kOffset] = x; lcsLengths[kOffset] = lcsLength; } } return 0; } } // namespace aligndiff
32.440678
77
0.449582
mogemimi
f4031124c33c5e509c18ccefb7d3aadddd44d520
237
hpp
C++
learnBoost/learnBoost/c++/bootregister.hpp
zhenyiyi/LearnDiary
7e88ced2c4294b5cfb7dd60c046fbc9510aab489
[ "MIT" ]
1
2019-03-18T06:58:36.000Z
2019-03-18T06:58:36.000Z
learnBoost/learnBoost/c++/bootregister.hpp
zhenyiyi/LearnDiary
7e88ced2c4294b5cfb7dd60c046fbc9510aab489
[ "MIT" ]
null
null
null
learnBoost/learnBoost/c++/bootregister.hpp
zhenyiyi/LearnDiary
7e88ced2c4294b5cfb7dd60c046fbc9510aab489
[ "MIT" ]
null
null
null
// // bootregister.hpp // learnBoost // // Created by fenglin on 2017/11/20. // Copyright © 2017年 fenglin. All rights reserved. // #ifndef bootregister_hpp #define bootregister_hpp #include <stdio.h> #endif /* bootregister_hpp */
15.8
51
0.704641
zhenyiyi
f40ad5b256b350cf7df9faaf45d8e5a0b7b3d58f
2,953
cpp
C++
src/sound/snth5.cpp
DavidLudwig/executor
eddb527850af639b3ffe314e05d92a083ba47af6
[ "MIT" ]
null
null
null
src/sound/snth5.cpp
DavidLudwig/executor
eddb527850af639b3ffe314e05d92a083ba47af6
[ "MIT" ]
null
null
null
src/sound/snth5.cpp
DavidLudwig/executor
eddb527850af639b3ffe314e05d92a083ba47af6
[ "MIT" ]
null
null
null
/* Copyright 1992 by Abacus Research and * Development, Inc. All rights reserved. */ #include <base/common.h> #include <SoundMgr.h> #include <sound/soundopts.h> using namespace Executor; /* * It's not really clear how an actual synthesizer is expected to work * with the Sound Manager's queues. In this implementation we start * the relavent command playing and see that the ROMLIB_soundcomplete() * function is called when we're done. */ BOOLEAN Executor::C_snth5(SndChannelPtr chanp, SndCommand *cmdp, ModifierStubPtr mp) { #if defined(MACOSX_) soundbuffer_t *bufp; BOOLEAN done; static BOOLEAN beenhere = 0; if(!beenhere) { /* ROMlib_soundreserve(); */ beenhere = 1; } done = true; switch(cmdp->cmd) { case initCmd: LM(SoundActive) = soundactive5; /* TODO */ break; case freeCmd: LM(SoundActive) = 0; done = false; /* TODO */ break; case quietCmd: /* TODO */ break; case flushCmd: /* TODO */ break; case waitCmd: /* TODO */ break; case pauseCmd: /* TODO */ break; case resumeCmd: /* TODO */ break; case callBackCmd: #if 0 printf("CB"); fflush(stdout); #endif chanp->callBack(chanp, cmdp); break; case syncCmd: /* TODO */ break; case availableCmd: done = false; /* TODO */ break; case bufferCmd: bufp = (soundbuffer_t *)cmdp->param2; #if 0 printf("offset = %d, nsamples = %d, rate = 0x%x\n", bufp->offset, bufp->nsamples, bufp->rate); printf("BU"); fflush(stdout); #endif ROMlib_outbuffer((char *)bufp->buf, bufp->nsamples, bufp->rate, chanp); done = false; break; case requestNextCmd: /* not needed */ case tickleCmd: /* not implemented */ case howOftenCmd: /* not implemented */ case wakeUpCmd: /* not implemented */ case noteCmd: /* not implemented */ case restCmd: /* not implemented */ case freqCmd: /* not implemented */ case ampCmd: /* not implemented */ case timbreCmd: /* not implemented */ case waveTableCmd: /* not implemented */ case phaseCmd: /* not implemented */ case soundCmd: /* not implemented */ case rateCmd: /* not implemented */ case emptyCmd: /* does nothing */ case nullCmd: /* does nothing */ case midiDataCmd: /* not implemented */ default: #if 1 printf("unexpected sound command %d\n", (LONGINT)cmdp->cmd); #endif break; } if(done) ROMlib_callcompletion(chanp); #endif return false; }
26.603604
75
0.532001
DavidLudwig
f40b63805681fc9df4ce28af6a437004b1ad064b
954
hpp
C++
include/sparsex/internals/CsxSpmv.hpp
Baltoli/sparsex
36145d9c47e40dbd7da71ba5a75b7644e2eda5d8
[ "BSD-3-Clause" ]
28
2015-02-03T13:19:01.000Z
2022-03-25T15:46:11.000Z
include/sparsex/internals/CsxSpmv.hpp
Baltoli/sparsex
36145d9c47e40dbd7da71ba5a75b7644e2eda5d8
[ "BSD-3-Clause" ]
2
2018-06-19T06:41:47.000Z
2019-05-10T09:51:17.000Z
include/sparsex/internals/CsxSpmv.hpp
Baltoli/sparsex
36145d9c47e40dbd7da71ba5a75b7644e2eda5d8
[ "BSD-3-Clause" ]
7
2015-01-15T16:06:59.000Z
2019-03-01T12:30:04.000Z
/* * Copyright (C) 2012-2014, Computing Systems Laboratory (CSLab), NTUA. * Copyright (C) 2012-2014, Athena Elafrou * All rights reserved. * * This file is distributed under the BSD License. See LICENSE.txt for details. */ /** * \file CsxSpmv.hpp * \brief Thread-level SpMV routines * * \author Computing Systems Laboratory (CSLab), NTUA * \date 2011&ndash;2014 * \copyright This file is distributed under the BSD License. See LICENSE.txt * for details. */ #ifndef SPARSEX_INTERNALS_CSX_SPMV_HPP #define SPARSEX_INTERNALS_CSX_SPMV_HPP #include <sparsex/internals/Barrier.hpp> #include <sparsex/internals/SpmMt.hpp> #include <sparsex/internals/SpmvMethod.hpp> #include <sparsex/internals/Vector.hpp> namespace sparsex { void do_mv_thread(void *args); void do_mv_sym_thread(void *args); void do_kernel_thread(void *params); void do_kernel_sym_thread(void *args); } // end of namespace sparsex #endif // SPARSEX_INTERNALS_CSX_SPMV_HPP
25.783784
79
0.75891
Baltoli
f410b8e813c94eed8a9a7c69426cadf6663b0f22
2,760
cpp
C++
src/mbgl/util/tile_cover.cpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
1
2015-07-01T21:59:13.000Z
2015-07-01T21:59:13.000Z
src/mbgl/util/tile_cover.cpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
null
null
null
src/mbgl/util/tile_cover.cpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
null
null
null
#include <mbgl/util/tile_cover.hpp> #include <mbgl/util/vec.hpp> #include <mbgl/util/box.hpp> namespace mbgl { // Taken from polymaps src/Layer.js // https://github.com/simplegeo/polymaps/blob/master/src/Layer.js#L333-L383 struct edge { double x0 = 0, y0 = 0; double x1 = 0, y1 = 0; double dx = 0, dy = 0; edge(vec2<double> a, vec2<double> b) { if (a.y > b.y) { std::swap(a, b); } x0 = a.x; y0 = a.y; x1 = b.x; y1 = b.y; dx = b.x - a.x; dy = b.y - a.y; } }; typedef const std::function<void(int32_t x0, int32_t x1, int32_t y)> ScanLine; // scan-line conversion static void scanSpans(edge e0, edge e1, int32_t ymin, int32_t ymax, ScanLine scanLine) { double y0 = std::fmax(ymin, std::floor(e1.y0)); double y1 = std::fmin(ymax, std::ceil(e1.y1)); // sort edges by x-coordinate if ((e0.x0 == e1.x0 && e0.y0 == e1.y0) ? (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) : (e0.x1 - e1.dy / e0.dy * e0.dx < e1.x0)) { std::swap(e0, e1); } // scan lines! double m0 = e0.dx / e0.dy; double m1 = e1.dx / e1.dy; double d0 = e0.dx > 0; // use y + 1 to compute x0 double d1 = e1.dx < 0; // use y + 1 to compute x1 for (int32_t y = y0; y < y1; y++) { double x0 = m0 * std::fmax(0, std::fmin(e0.dy, y + d0 - e0.y0)) + e0.x0; double x1 = m1 * std::fmax(0, std::fmin(e1.dy, y + d1 - e1.y0)) + e1.x0; scanLine(std::floor(x1), std::ceil(x0), y); } } // scan-line conversion static void scanTriangle(const mbgl::vec2<double> a, const mbgl::vec2<double> b, const mbgl::vec2<double> c, int32_t ymin, int32_t ymax, ScanLine& scanLine) { edge ab = edge(a, b); edge bc = edge(b, c); edge ca = edge(c, a); // sort edges by y-length if (ab.dy > bc.dy) { std::swap(ab, bc); } if (ab.dy > ca.dy) { std::swap(ab, ca); } if (bc.dy > ca.dy) { std::swap(bc, ca); } // scan span! scan span! if (ab.dy) scanSpans(ca, ab, ymin, ymax, scanLine); if (bc.dy) scanSpans(ca, bc, ymin, ymax, scanLine); } std::forward_list<TileID> tileCover(int8_t z, const mbgl::box &bounds, int8_t actualZ) { int32_t tiles = 1 << z; std::forward_list<mbgl::TileID> t; auto scanLine = [&](int32_t x0, int32_t x1, int32_t y) { int32_t x; if (y >= 0 && y <= tiles) { for (x = x0; x < x1; x++) { t.emplace_front(actualZ, x, y, z); } } }; // Divide the screen up in two triangles and scan each of them: // \---+ // | \ | // +---\. scanTriangle(bounds.tl, bounds.tr, bounds.br, 0, tiles, scanLine); scanTriangle(bounds.br, bounds.bl, bounds.tl, 0, tiles, scanLine); t.unique(); return t; } }
29.361702
158
0.546739
donpark
f411a425aa78cc87e1a5004a9440c1c257518beb
267
cpp
C++
Tools/CRCompilerAudio/SoundsHandler.cpp
duhone/HeadstoneHarry
961a314a0e69d67275253da802e41429cff80097
[ "MIT" ]
1
2020-02-06T16:11:02.000Z
2020-02-06T16:11:02.000Z
Tools/CRCompilerAudio/SoundsHandler.cpp
duhone/HeadstoneHarry
961a314a0e69d67275253da802e41429cff80097
[ "MIT" ]
null
null
null
Tools/CRCompilerAudio/SoundsHandler.cpp
duhone/HeadstoneHarry
961a314a0e69d67275253da802e41429cff80097
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "SoundsHandler.h" #include "SoundsCompiler.h" using namespace CR::Compiler; SoundsHandler::SoundsHandler(void) { } SoundsHandler::~SoundsHandler(void) { } INodeCompiler* SoundsHandler::StartElement() { return new SoundsCompiler(); }
14.052632
44
0.756554
duhone
f4121a8096dd1546344ae9e51201b37b92148ef1
5,841
cxx
C++
nn.cxx
pgomoluch/simple-nn
8075338939f1293824de67ce2c6a21b295d65e7e
[ "MIT" ]
null
null
null
nn.cxx
pgomoluch/simple-nn
8075338939f1293824de67ce2c6a21b295d65e7e
[ "MIT" ]
null
null
null
nn.cxx
pgomoluch/simple-nn
8075338939f1293824de67ce2c6a21b295d65e7e
[ "MIT" ]
null
null
null
#include "config.h" #include "network.h" #include "utils.h" #include <chrono> #include <cmath> #include <cstdlib> #include <fstream> #include <iostream> using namespace std; using namespace std::chrono; const char *learning_log_file = "learning_log.txt"; const char *features_train_file = "features_train.txt"; const char *features_test_file = "features_test.txt"; const char *labels_train_file = "labels_train.txt"; const char *labels_test_file = "labels_test.txt"; void test1(); void test5_learn_split(); void test6_learn_all(); void learn(const vector<vector<double> > &features, const vector<double> &labels, const Config &config); int main(int argc, const char *argv[]) { srand(time(NULL)); if (argc == 1) { test6_learn_all(); //test5_learn_split(); } else if (argc == 2) { Config config; config.load(argv[1]); vector<vector<double> > features; vector<double> labels; read_data(config.features_train.c_str(), config.labels_train.c_str(), features, labels); learn(features, labels, config); } else if (argc >= 5) // old command line interface, deprecated, use a configuration file instead { // nn <features file> <labels file> <iterations> [<first hidden layer size> [<second ...> ...]] const char *features_path = argv[1]; const char *labels_path = argv[2]; unsigned iters = atoi(argv[3]); vector<unsigned> architecture; for (int i = 4; i < argc; ++i) architecture.push_back(atoi(argv[i])); vector<vector<double> > features; vector<double> labels; read_data(features_path, labels_path, features, labels); Config config; config.iterations = iters; config.hidden_layers = architecture; config.learning_rate = 0.0000000001; learn(features, labels, config); } else { cout << "Usage: nn <configuration file>" << endl; } return 0; } void learn(const vector<vector<double> > &features, const vector<double> &labels, const Config &config) { vector<unsigned> architecture = config.hidden_layers; architecture.insert(architecture.begin(), features[0].size()); Network network(architecture); ofstream learning_log(learning_log_file); double initial_mae = network.mae(features, labels); double initial_mse = network.mse(features, labels); learning_log << 0 << " " << initial_mae << " " << initial_mse << endl; cout << "Initial MAE: " << initial_mae << endl; steady_clock::time_point t1 = steady_clock::now(); for (unsigned i = 0; i < config.iterations; ++i) { //network.train(features, labels, 100000, 0.0000000001); network.train(features, labels, 100000, config.learning_rate); double _mae = network.mae(features, labels); double _mse = network.mse(features, labels); cout << "Ep: " << i << " MAE: " << _mae << " MSE: " << _mse << endl; learning_log << i+1 << " " << _mae << " " << _mse << endl; if(i && (i % 10000 == 0)) { char filename[100]; sprintf(filename, "%s-b%d", config.network_file.c_str(), i); network.save(filename); } } steady_clock::time_point t2 = steady_clock::now(); auto duration = duration_cast<seconds>(t2 - t1).count(); cout << "Total training time: " << duration << "s." << endl; learning_log.close(); network.save(config.network_file.c_str()); Network network2(config.network_file.c_str()); double mse_result; high_resolution_clock::time_point et1 = high_resolution_clock::now(); mse_result = network2.mse(features, labels); high_resolution_clock::time_point et2 = high_resolution_clock::now(); duration = (duration_cast<milliseconds>(et2 - et1)).count(); cout << "MSE on loaded network: " << mse_result << ". Computed in " << duration << " ms." << endl; cout << "MAE on loaded network: " << network2.mae(features, labels) << endl; cout << "Total samples: " << labels.size() << endl; } void test1() { vector<vector<double> > features = {{0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 1.0}}; vector<double> labels = {0.3, 0.5, 0.2, 0.4}; Network network({2, 4}); cout << "Initial MAE:" << network.mae(features, labels) << endl; for (int j=0; j < 10; j++) { network.train(features, labels, 1000, 0.001); cout << "MAE: " << network.mae(features, labels) << " MSE: " << network.mse(features, labels) << endl; } } void test5_learn_split() { vector<vector<double> > features_train, features_test; vector<double> labels_train, labels_test; read_data(features_train_file, labels_train_file, features_train, labels_train); read_data(features_test_file, labels_test_file, features_test, labels_test); Config config; config.iterations = 100; config.hidden_layers = vector<unsigned>({5,3}); config.learning_rate = 0.00000001; learn(features_train, labels_train, config); Network network3(config.network_file.c_str()); cout << "MSE (test set): " << network3.mse(features_test, labels_test) << ".\n"; cout << "MAE (test set): " << network3.mae(features_test, labels_test) << ".\n"; } void test6_learn_all() { vector<vector<double> > features; vector<double> labels; // merge train and test read_data(features_train_file, labels_train_file, features, labels); read_data(features_test_file, labels_test_file, features, labels); Config config; config.iterations = 10000; config.hidden_layers = vector<unsigned>({7,3}); config.learning_rate = 0.00000001; learn(features, labels, config); }
33.1875
104
0.624551
pgomoluch
f41333fb4106c1084a7f323eeef63c8c53d549be
1,378
cpp
C++
share/fs/file.cpp
ShZh-Playground/tiny-FTP
89965f74a94cc05e956ad9115bc0ef7be70a57eb
[ "MIT" ]
null
null
null
share/fs/file.cpp
ShZh-Playground/tiny-FTP
89965f74a94cc05e956ad9115bc0ef7be70a57eb
[ "MIT" ]
null
null
null
share/fs/file.cpp
ShZh-Playground/tiny-FTP
89965f74a94cc05e956ad9115bc0ef7be70a57eb
[ "MIT" ]
null
null
null
#include <Windows.h> #include <iostream> #include <io.h> #include "file.h" using namespace FileSystem; bool File::IsDirectory(const string& path) { WIN32_FIND_DATAA find_file_data; FindFirstFileA(path.c_str(), &find_file_data); return find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; } bool File::IsFile(const string& path) { return !IsDirectory(path); } vector<string> File::GetPathInfoInDir(const string& dir_name) { if (IsDirectory(dir_name)) { vector<string> result; string match = dir_name + "\\*"; _finddata_t file_info; long long find_result = _findfirst(match.c_str(), &file_info); if (find_result == -1) { _findclose(find_result); return vector<string>(); } string file_name; do { if (file_info.attrib == _A_ARCH || (file_info.attrib == _A_SUBDIR && strcmp(file_info.name, ".") != 0 && strcmp(file_info.name, "..") != 0)) { file_name = dir_name + "\\" + file_info.name; result.push_back(file_name); } } while (_findnext(find_result, &file_info) == 0); _findclose(find_result); return result; } else { return vector<string>(); } } void File::CreateFolder(const string& folder_name) { const char* folder_name_c = folder_name.c_str(); if (GetFileAttributesA(folder_name_c) & FILE_ATTRIBUTE_DIRECTORY) { CreateDirectoryA(folder_name_c, NULL); } }
27.019608
69
0.679245
ShZh-Playground