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
7d8d4e079ea50b00869f110d8dab885e825acd21
2,787
cpp
C++
engine/gfx/gles2/src/gfx_gles2_shader.cpp
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
12
2017-02-25T17:14:15.000Z
2021-08-02T13:39:18.000Z
engine/gfx/gles2/src/gfx_gles2_shader.cpp
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
31
2017-02-23T06:59:44.000Z
2017-05-21T11:49:10.000Z
engine/gfx/gles2/src/gfx_gles2_shader.cpp
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
5
2017-05-02T05:34:53.000Z
2020-05-19T06:57:50.000Z
/* * Copyright (c) 2012-2018 Robin Degen * * 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 <aeon/gfx/gles2/gfx_gles2_shader.h> #include <glm/gtc/type_ptr.hpp> #include <aeon/gfx/gl_common/check_gl_error.h> namespace aeon { namespace gfx { namespace gles2 { gfx_gles2_shader::gfx_gles2_shader() : logger_(common::logger::get_singleton(), "Gfx::Gles2::Shader") , handle_(0) , projection_matrix_handle_(0) , model_matrix_handle_(0) , view_matrix_handle_(0) { } gfx_gles2_shader::~gfx_gles2_shader() { AEON_LOG_TRACE(logger_) << "Deleting Program (GL handle: " << handle_ << ")." << std::endl; glDeleteProgram(handle_); AEON_CHECK_GL_ERROR(); } void gfx_gles2_shader::bind() const { glUseProgram(handle_); AEON_CHECK_GL_ERROR(); } void gfx_gles2_shader::set_projection_matrix(const glm::mat4 &matrix) { glUniformMatrix4fv(projection_matrix_handle_, 1, GL_FALSE, glm::value_ptr(matrix)); AEON_CHECK_GL_ERROR(); } void gfx_gles2_shader::set_model_matrix(const glm::mat4 &matrix) { glUniformMatrix4fv(model_matrix_handle_, 1, GL_FALSE, glm::value_ptr(matrix)); AEON_CHECK_GL_ERROR(); } void gfx_gles2_shader::set_view_matrix(const glm::mat4 &matrix) { glUniformMatrix4fv(view_matrix_handle_, 1, GL_FALSE, glm::value_ptr(matrix)); AEON_CHECK_GL_ERROR(); } auto gfx_gles2_shader::get_sampler_handle_by_name(const std::string &name) const -> GLint { auto handle = glGetUniformLocation(handle_, name.c_str()); AEON_CHECK_GL_ERROR(); return handle; } void gfx_gles2_shader::bind_sampler(const GLint handle, const int bind_point) const { glUniform1i(handle, bind_point); AEON_CHECK_GL_ERROR(); } } // namespace gles2 } // namespace gfx } // namespace aeon
29.648936
95
0.743093
aeon-engine
7d8db40b57296ab0611ed65766375ef9d6539625
6,205
cc
C++
mindspore/ccsrc/plugin/device/cpu/kernel/eigen/eig_cpu_kernel.cc
httpsgithu/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
1
2022-02-23T09:13:43.000Z
2022-02-23T09:13:43.000Z
mindspore/ccsrc/plugin/device/cpu/kernel/eigen/eig_cpu_kernel.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/plugin/device/cpu/kernel/eigen/eig_cpu_kernel.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021-2022 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "plugin/device/cpu/kernel/eigen/eig_cpu_kernel.h" #include <algorithm> #include <type_traits> #include <utility> #include "plugin/device/cpu/kernel/eigen/eigen_common_utils.h" #include "utils/ms_utils.h" #include "Eigen/Eigenvalues" namespace mindspore { namespace kernel { namespace { constexpr size_t kInputsNum = 1; constexpr size_t kOutputsNumNV = 1; constexpr size_t kOutputsNumV = 2; } // namespace void EigCpuKernelMod::InitMatrixInfo(const std::vector<size_t> &shape) { if (shape.size() < kShape2dDims) { MS_LOG_EXCEPTION << "For '" << kernel_name_ << "', the rank of parameter 'a' must be at least 2, but got " << shape.size() << " dimensions."; } row_size_ = shape[shape.size() - kDim1]; col_size_ = shape[shape.size() - kDim2]; if (row_size_ != col_size_) { MS_LOG_EXCEPTION << "For '" << kernel_name_ << "', the shape of parameter 'a' must be a square matrix, but got last two dimensions is " << row_size_ << " and " << col_size_; } batch_size_ = 1; for (auto i : shape) { batch_size_ *= i; } batch_size_ /= (row_size_ * col_size_); } void EigCpuKernelMod::InitKernel(const CNodePtr &kernel_node) { kernel_name_ = common::AnfAlgo::GetCNodeName(kernel_node); // If compute_v_ is true, then: w, v = Eig(a) // If compute_v_ is false, then: w = Eig(a) if (common::AnfAlgo::HasNodeAttr(COMPUTE_V, kernel_node)) { compute_v_ = common::AnfAlgo::GetNodeAttr<bool>(kernel_node, COMPUTE_V); } size_t input_num = common::AnfAlgo::GetInputTensorNum(kernel_node); CHECK_KERNEL_INPUTS_NUM(input_num, kInputsNum, kernel_name_); size_t output_num = common::AnfAlgo::GetOutputTensorNum(kernel_node); auto expect_output_num = compute_v_ ? kOutputsNumV : kOutputsNumNV; CHECK_KERNEL_OUTPUTS_NUM(output_num, expect_output_num, kernel_name_); auto input_shape = common::AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, 0); InitMatrixInfo(input_shape); auto kernel_attr = GetKernelAttrFromNode(kernel_node); auto [is_match, index] = MatchKernelAttr(kernel_attr, GetOpSupport()); if (!is_match) { MS_LOG(EXCEPTION) << "Eig does not support this kernel data type: " << kernel_attr; } kernel_func_ = func_list_[index].second; } template <typename T, typename C> bool EigCpuKernelMod::LaunchKernel(const std::vector<AddressPtr> &inputs, const std::vector<AddressPtr> &, const std::vector<AddressPtr> &outputs) { auto input_addr = reinterpret_cast<T *>(inputs[0]->addr); auto output_w_addr = reinterpret_cast<C *>(outputs[0]->addr); auto output_v_addr = compute_v_ ? reinterpret_cast<C *>(outputs[1]->addr) : nullptr; for (size_t batch = 0; batch < batch_size_; ++batch) { T *a_addr = input_addr + batch * row_size_ * col_size_; C *w_addr = output_w_addr + batch * row_size_; Map<MatrixSquare<T>> a(a_addr, row_size_, col_size_); Map<MatrixSquare<C>> w(w_addr, row_size_, 1); auto eigen_option = compute_v_ ? Eigen::ComputeEigenvectors : Eigen::EigenvaluesOnly; Eigen::ComplexEigenSolver<MatrixSquare<T>> solver(a, eigen_option); w = solver.eigenvalues(); if (compute_v_) { C *v_addr = output_v_addr + batch * row_size_ * col_size_; Map<MatrixSquare<C>> v(v_addr, row_size_, col_size_); v = solver.eigenvectors(); } if (solver.info() != Eigen::Success) { MS_LOG_WARNING << "For '" << kernel_name_ << "', the computation was not successful. Eigen::ComplexEigenSolver returns 'NoConvergence'."; } } return true; } std::vector<std::pair<KernelAttr, EigCpuKernelMod::EigFunc>> EigCpuKernelMod::func_list_ = { // If compute_v is false. {KernelAttr().AddInputAttr(kNumberTypeFloat32).AddOutputAttr(kNumberTypeComplex64), &EigCpuKernelMod::LaunchKernel<float, float_complex>}, {KernelAttr().AddInputAttr(kNumberTypeFloat64).AddOutputAttr(kNumberTypeComplex128), &EigCpuKernelMod::LaunchKernel<double, double_complex>}, {KernelAttr().AddInputAttr(kNumberTypeComplex64).AddOutputAttr(kNumberTypeComplex64), &EigCpuKernelMod::LaunchKernel<float_complex, float_complex>}, {KernelAttr().AddInputAttr(kNumberTypeComplex128).AddOutputAttr(kNumberTypeComplex128), &EigCpuKernelMod::LaunchKernel<double_complex, double_complex>}, // If compute_v is true. {KernelAttr() .AddInputAttr(kNumberTypeFloat32) .AddOutputAttr(kNumberTypeComplex64) .AddOutputAttr(kNumberTypeComplex64), &EigCpuKernelMod::LaunchKernel<float, float_complex>}, {KernelAttr() .AddInputAttr(kNumberTypeFloat64) .AddOutputAttr(kNumberTypeComplex128) .AddOutputAttr(kNumberTypeComplex128), &EigCpuKernelMod::LaunchKernel<double, double_complex>}, {KernelAttr() .AddInputAttr(kNumberTypeComplex64) .AddOutputAttr(kNumberTypeComplex64) .AddOutputAttr(kNumberTypeComplex64), &EigCpuKernelMod::LaunchKernel<float_complex, float_complex>}, {KernelAttr() .AddInputAttr(kNumberTypeComplex128) .AddOutputAttr(kNumberTypeComplex128) .AddOutputAttr(kNumberTypeComplex128), &EigCpuKernelMod::LaunchKernel<double_complex, double_complex>}}; std::vector<KernelAttr> EigCpuKernelMod::GetOpSupport() { std::vector<KernelAttr> support_list; (void)std::transform(func_list_.begin(), func_list_.end(), std::back_inserter(support_list), [](const std::pair<KernelAttr, EigFunc> &pair) { return pair.first; }); return support_list; } MS_KERNEL_FACTORY_REG(NativeCpuKernelMod, Eig, EigCpuKernelMod); } // namespace kernel } // namespace mindspore
42.793103
116
0.720709
httpsgithu
7d9519c733e9832a84f01afa3237f1e607efdcf2
306
cpp
C++
libs/mxgui/_tools/qtsimulator/qtsimulator.cpp
skyward-er/skyward-boardcore
05b9fc2ef45d27487af57cc11ed8b85524451510
[ "MIT" ]
6
2022-01-06T14:20:45.000Z
2022-02-28T07:32:39.000Z
libs/mxgui/_tools/qtsimulator/qtsimulator.cpp
skyward-er/skyward-boardcore
05b9fc2ef45d27487af57cc11ed8b85524451510
[ "MIT" ]
null
null
null
libs/mxgui/_tools/qtsimulator/qtsimulator.cpp
skyward-er/skyward-boardcore
05b9fc2ef45d27487af57cc11ed8b85524451510
[ "MIT" ]
null
null
null
#include <QtGui/QApplication> #include <boost/filesystem.hpp> #include "window.h" using namespace boost::filesystem; int main(int argc, char *argv[]) { current_path(path(argv[0]).parent_path()); //chdir() to executable's path QApplication a(argc,argv); Window window; return a.exec(); }
20.4
77
0.69281
skyward-er
7d9be2c5607d56344fbce7a08e3a134e7f9b1a03
543
cpp
C++
Olympiad Solutions/URI/1234.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Olympiad Solutions/URI/1234.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Olympiad Solutions/URI/1234.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Ivan Carvalho // Solution to https://www.urionlinejudge.com.br/judge/problems/view/1234 #include <cstdio> #include <cstring> #include <cctype> #include <iostream> int main(){ char frase[50]; while(std::cin.getline(frase,50)){ int tamanho = strlen(frase),i,valido=1; for(i=0;i<tamanho;i++){ char davez = frase[i]; if (davez != ' '){ if (valido){ davez = toupper(davez); valido = 0; } else { davez = tolower(davez); valido = 1; } } printf("%c",davez); } printf("\n"); } return 0; }
18.724138
73
0.587477
Ashwanigupta9125
7d9ce29c24d2f57029956dc2dc705fa615ac628f
422
cpp
C++
C++Now 2017/Mocking Examples/runtime_rtti_name/f.cpp
dascandy/presentations
7a004ba5e485900a7c81e7a1116b098d24331075
[ "Apache-2.0" ]
2
2017-05-18T19:48:51.000Z
2017-11-10T16:11:43.000Z
C++Now 2017/Mocking Examples/runtime_rtti_name/f.cpp
dascandy/presentations
7a004ba5e485900a7c81e7a1116b098d24331075
[ "Apache-2.0" ]
null
null
null
C++Now 2017/Mocking Examples/runtime_rtti_name/f.cpp
dascandy/presentations
7a004ba5e485900a7c81e7a1116b098d24331075
[ "Apache-2.0" ]
null
null
null
#include <typeinfo> #include <cstdlib> #include <cstdio> #include <cstring> struct T { virtual ~T() {} }; struct rttiinfo { void* type; const char* name; void* base; }; T* f(const char* name) { static rttiinfo rti; void** vt = new void*[10]; static T object; memcpy(&rti, ((void***)&object)[0][-1], sizeof(rttiinfo)); *(void**)&object = &vt[1]; vt[0] = &rti; rti.name = name; return &object; }
15.62963
60
0.594787
dascandy
7d9dc8e3d47c49f5ce5db516be1ea23172d4c790
644
cpp
C++
OOP/Shapes.cpp
ApostolAndrew/OOP
aff106a8df8960108fa07ed0c36ed64dc8497a9f
[ "MIT" ]
null
null
null
OOP/Shapes.cpp
ApostolAndrew/OOP
aff106a8df8960108fa07ed0c36ed64dc8497a9f
[ "MIT" ]
null
null
null
OOP/Shapes.cpp
ApostolAndrew/OOP
aff106a8df8960108fa07ed0c36ed64dc8497a9f
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Shape { protected: float width, height; public: void set(float a, float b) { width = a; height = b; } }; class Rectangle : public Shape { public: float area() { return width * height; } }; class Triangle : public Shape { public: float area() { return (width * height / 2); } }; int main() { Triangle tri; Rectangle rec; float tarea, rarea; tri.set(5,10); rec.set(7,3); cout << tri.area() << endl; cout << rec.area() << endl; return 0; }
16.947368
40
0.493789
ApostolAndrew
7da1d757366a23377316e1c32feed2fc22302b8d
4,929
cpp
C++
src/util/tensor_distribution.cpp
mdschatz/rote
111e965c6365c605f9872ee8302b1170565a3002
[ "BSD-3-Clause" ]
null
null
null
src/util/tensor_distribution.cpp
mdschatz/rote
111e965c6365c605f9872ee8302b1170565a3002
[ "BSD-3-Clause" ]
null
null
null
src/util/tensor_distribution.cpp
mdschatz/rote
111e965c6365c605f9872ee8302b1170565a3002
[ "BSD-3-Clause" ]
2
2018-07-21T15:39:45.000Z
2021-02-09T20:34:50.000Z
#include "rote.hpp" namespace rote{ bool CheckOrder(const Unsigned& outOrder, const Unsigned& inOrder){ if(outOrder != inOrder){ LogicError("Invalid redistribution: Objects being redistributed must be of same order"); } return true; } bool CheckNonDistOutIsPrefix(const TensorDistribution& outDist, const TensorDistribution& inDist){ Unsigned nonDistMode = outDist.size() - 1; if(!(outDist[nonDistMode] <= inDist[nonDistMode])){ std::stringstream msg; msg << "Invalid redistribution\n" << outDist << " <-- " << inDist << std::endl << "Output Non-distributed mode distribution must be prefix" << std::endl; LogicError(msg.str()); } return true; } bool CheckNonDistInIsPrefix(const TensorDistribution& outDist, const TensorDistribution& inDist){ Unsigned nonDistMode = outDist.size() - 1; if(!(inDist[nonDistMode] <= outDist[nonDistMode])){ std::stringstream msg; msg << "Invalid redistribution\n" << outDist << " <-- " << inDist << std::endl << "Input Non-distributed mode distribution must be prefix" << std::endl; LogicError(msg.str()); } return true; } bool CheckSameNonDist(const TensorDistribution& outDist, const TensorDistribution& inDist){ Unsigned nonDistMode = outDist.size() - 1; if(!outDist[nonDistMode].SameModesAs(inDist[nonDistMode])){ std::stringstream msg; msg << "Invalid redistribution\n" << outDist << " <-- " << inDist << std::endl << "Output Non-distributed mode distribution must be same" << std::endl; LogicError(msg.str()); } return true; } bool CheckSameCommModes(const TensorDistribution& outDist, const TensorDistribution& inDist){ TensorDistribution commonPrefix = inDist.GetCommonPrefix(outDist); TensorDistribution remainderIn = inDist - commonPrefix; TensorDistribution remainderOut = outDist - commonPrefix; if(!remainderIn.UsedModes().SameModesAs(remainderOut.UsedModes())){ std::stringstream msg; msg << "Invalid redistribution\n" << outDist << " <-- " << inDist << std::endl << "Cannot determine modes communicated over" << std::endl; LogicError(msg.str()); } return true; } bool CheckPartition(const TensorDistribution& outDist, const TensorDistribution& inDist){ Unsigned i; Unsigned j = 0; Unsigned objOrder = outDist.size() - 1; ModeArray sourceModes; ModeArray sinkModes; for(i = 0; i < objOrder; i++){ if(inDist[i].size() != outDist[i].size()){ if(inDist[i] <= outDist[i]){ sinkModes.push_back(i); } else if(outDist[i] <= inDist[i]){ sourceModes.push_back(i); } }else if(inDist[i] != outDist[i]){ std::stringstream msg; msg << "Invalid redistribution\n" << outDist << " <-- " << inDist << std::endl << "Cannot form partition" << std::endl; LogicError(msg.str()); } } for(i = 0; i < sourceModes.size() && j < sinkModes.size(); i++){ if(sourceModes[i] == sinkModes[j]){ std::stringstream msg; msg << "Invalid redistribution\n" << outDist << " <-- " << inDist << std::endl << "Cannot form partition" << std::endl; LogicError(msg.str()); }else if(sourceModes[i] > sinkModes[j]){ i--; j++; }else if(sourceModes[i] < sinkModes[j]){ continue; } } return true; } bool CheckInIsPrefix(const TensorDistribution& outDist, const TensorDistribution& inDist){ Unsigned objOrder = outDist.size() - 1; for(Unsigned i = 0; i < objOrder; i++){ if(!(inDist[i] <= outDist[i])){ std::stringstream msg; msg << "Invalid redistribution:\n" << outDist << " <-- " << inDist << std::endl << "Input mode-" << i << " mode distribution must be prefix of output mode distribution" << std::endl; LogicError(msg.str()); } } return true; } bool CheckOutIsPrefix(const TensorDistribution& outDist, const TensorDistribution& inDist){ Unsigned objOrder = outDist.size() - 1; for(Unsigned i = 0; i < objOrder; i++){ if(!(outDist[i] <= inDist[i])){ std::stringstream msg; msg << "Invalid redistribution\n" << outDist << " <-- " << inDist << std::endl << "Output mode-" << i << " mode distribution must be prefix of input mode distribution" << std::endl; LogicError(msg.str()); } } return true; } bool CheckSameGridViewShape(const ObjShape& outShape, const ObjShape& inShape){ if(AnyElemwiseNotEqual(outShape, inShape)){ std::stringstream msg; msg << "Invalid redistribution: Mode distributions must correspond to equal logical grid dimensions" << std::endl; LogicError(msg.str()); } return true; } bool CheckIsValidPermutation(const Unsigned& order, const Permutation& perm){ return perm.size() == order; } }
27.082418
102
0.623656
mdschatz
7da344669f21c1cfdaecf5062fbb9717b6904967
1,960
cc
C++
test/testnewalloc.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
test/testnewalloc.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
test/testnewalloc.cc
dch0ph/libcmatrix
1f5fae7a398fe2c643252f93371b407dbfb70855
[ "MIT" ]
null
null
null
#include "cmatrix.h" #include <iostream> struct dodgy; std::ostream& operator<< (std::ostream&, const dodgy&); static int initcount=0; static int destroycount=0; static int copycount=0; //static int assigncount=0; struct dodgy { int val; explicit dodgy(int valv =1234) : val(valv) { std::cerr << "Make: " << valv << '\n'; initcount++; } dodgy(const dodgy& a) { val=a.val; std::cerr << "Copy: " << *this << '\n'; copycount++; } // dodgy& operator= (const dodgy& a) { // std::cerr << "Assigned: " << *this << '\n'; // assigncount++; // val=a.val; // return *this; // } ~dodgy() { //if (val!=1234) std::cerr << "Uninitialised dodgy: " << *this << '\n'; destroycount++; } }; std::ostream& operator<< (std::ostream& ostr, const dodgy& a) { return ostr << a.val; } using namespace libcmatrix; template<class T> bool stress(T& obj, int left) { typedef typename T::value_type Type; char junk[]="DEADBEEFDEADBEEFDE"; //mess up stack a bit try { T newlist(3,mxflag::normal); std::cout << newlist << '\n'; //newlist=dodgy(5); //std::cout << newlist << '\n'; newlist.create(4,Type(99)); newlist.push_back(Type(100)); std::cout << newlist << '\n'; //T newlist2(5,Type(3),mxflag::normal); //std::cout << newlist2 << '\n'; } catch (MatrixException& exc) { std::cerr << exc << '\n'; return false; } if (--left>0) stress(obj,--left); return true; } int main() { List<dodgy> dlist1; stress(dlist1,3); std::cout << "Created: " << initcount << '\n'; std::cout << "Copied: " << copycount << '\n'; std::cout << "Destroyed: " << destroycount << '\n'; // std::cout << "Assigned: " << copycount << '\n'; cmatrix b(4,4); Matrix<int> x(5,5); //this won't show up for (size_t j=4;j--;) { cmatrix a(3,3,4.0); std::cout << a << '\n'; matrix_traits<complex>::allocator::print(std::cout); } return 0; }
21.304348
61
0.557143
dch0ph
7da38eb297d73de555fa3171db7348109211039c
22,360
hpp
C++
include/flusspferd/class_description.hpp
Flusspferd/flusspferd
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
[ "MIT" ]
7
2015-06-08T09:59:36.000Z
2021-02-27T18:45:17.000Z
include/flusspferd/class_description.hpp
Flusspferd/flusspferd
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
[ "MIT" ]
null
null
null
include/flusspferd/class_description.hpp
Flusspferd/flusspferd
f2a070c4805e0bdbae4b5f528e94a9a36ceb80c5
[ "MIT" ]
3
2016-07-06T20:47:01.000Z
2021-06-30T19:09:47.000Z
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* The MIT License Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or http://flusspferd.org/contributors.txt) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FLUSSFPERD_CLASS_DESCRIPTION_HPP #define FLUSSFPERD_CLASS_DESCRIPTION_HPP #ifndef PREPROC_DEBUG #include "class.hpp" #include "native_object_base.hpp" #include "create/function.hpp" #endif #include "detail/limit.hpp" #include <boost/preprocessor.hpp> #ifndef IN_DOXYGEN /* 2-tuple seq */ #define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2(x, y) \ ((x, y)) \ FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS #define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS(x, y) \ ((x, y)) \ FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2 #define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS_ELIM #define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2_ELIM #define FLUSSPFERD_PP_GEN_TUPLE2SEQ(x) \ BOOST_PP_CAT(FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS x, _ELIM) /* 3-tuple seq */ #define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2(x, y, z) \ ((x, y, z)) \ FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS #define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS(x, y, z) \ ((x, y, z)) \ FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2 #define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS_ELIM #define FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS2_ELIM #define FLUSSPFERD_PP_GEN_TUPLE3SEQ(x) \ BOOST_PP_CAT(FLUSSPFERD_PP_GEN_TUPLE3SEQ_PROCESS x, _ELIM) /* -- */ #define FLUSSPFERD_CD_PARAM_FOLD(s, state, elem) \ BOOST_PP_ARRAY_REPLACE( \ state, \ BOOST_PP_EXPAND( \ BOOST_PP_CAT(FLUSSPFERD_CD_PARAM__, \ BOOST_PP_TUPLE_ELEM(2, 0, elem))), \ BOOST_PP_TUPLE_ELEM(2, 1, elem)) \ /* */ #define FLUSSPFERD_CD_PARAM_INITIAL \ (13, ( \ ~cpp_name~, /* name */ \ ::flusspferd::native_object_base, /* base class */ \ ~constructor_name~, /* constructor name */ \ 0, /* constructor arity */ \ true, /* constructible */ \ ~full_name~, /* full name */ \ (~, none, ~), /* methods */ \ (~, none, ~), /* constructor methods */ \ (~, none, ~), /* properties */ \ (~, none, ~), /* constructor properties */ \ false, /* custom enumerate */ \ 0, /* augment constructor (custom func.)*/\ 0 /* augment prototype (custom func.) */ \ )) \ /* */ #define FLUSSPFERD_CD_PARAM__cpp_name 0 #define FLUSSPFERD_CD_PARAM__base 1 #define FLUSSPFERD_CD_PARAM__constructor_name 2 #define FLUSSPFERD_CD_PARAM__constructor_arity 3 #define FLUSSPFERD_CD_PARAM__constructible 4 #define FLUSSPFERD_CD_PARAM__full_name 5 #define FLUSSPFERD_CD_PARAM__methods 6 #define FLUSSPFERD_CD_PARAM__constructor_methods 7 #define FLUSSPFERD_CD_PARAM__properties 8 #define FLUSSPFERD_CD_PARAM__constructor_properties 9 #define FLUSSPFERD_CD_PARAM__custom_enumerate 10 #define FLUSSPFERD_CD_PARAM__augment_constructor 11 #define FLUSSPFERD_CD_PARAM__augment_prototype 12 #define FLUSSPFERD_CD_PARAM(tuple_seq) \ BOOST_PP_SEQ_FOLD_LEFT( \ FLUSSPFERD_CD_PARAM_FOLD, \ FLUSSPFERD_CD_PARAM_INITIAL, \ FLUSSPFERD_PP_GEN_TUPLE2SEQ(tuple_seq) \ ) \ /* */ #define FLUSSPFERD_CLASS_DESCRIPTION_A(array) \ BOOST_PP_EXPAND(FLUSSPFERD_CLASS_DESCRIPTION_P BOOST_PP_ARRAY_DATA(array)) \ /* */ #define FLUSSPFERD_CLASS_DESCRIPTION_P( \ p_cpp_name, \ p_base, \ p_constructor_name, \ p_constructor_arity, \ p_constructible, \ p_full_name, \ p_methods, \ p_constructor_methods, \ p_properties, \ p_constructor_properties, \ p_custom_enumerate, \ p_augment_constructor, \ p_augment_prototype \ ) \ template<typename Class> \ class BOOST_PP_CAT(p_cpp_name, _base) : public p_base { \ public: \ typedef BOOST_PP_CAT(p_cpp_name, _base) base_type; \ struct class_info : ::flusspferd::class_info { \ typedef boost::mpl::bool_< (p_constructible) > constructible; \ static char const *constructor_name() { \ return (p_constructor_name); \ } \ typedef ::boost::mpl::size_t< (p_constructor_arity) > constructor_arity; \ static char const *full_name() { \ return (p_full_name); \ } \ static ::flusspferd::object create_prototype() { \ ::flusspferd::root_object obj(::flusspferd::create<flusspferd::object>( \ ::flusspferd::prototype< p_base >() \ )); \ FLUSSPFERD_CD_METHODS(p_methods) \ FLUSSPFERD_CD_PROPERTIES(p_properties) \ BOOST_PP_EXPR_IF( \ p_augment_prototype, \ Class :: augment_prototype(obj);) \ return obj; \ } \ static void augment_constructor(::flusspferd::object &obj) { \ (void)obj; \ FLUSSPFERD_CD_METHODS(p_constructor_methods) \ FLUSSPFERD_CD_PROPERTIES(p_constructor_properties) \ BOOST_PP_EXPR_IF( \ p_augment_constructor, \ Class :: augment_constructor(obj);) \ } \ typedef boost::mpl::bool_< (p_custom_enumerate) > custom_enumerate; \ }; \ BOOST_PP_REPEAT( \ BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT), \ FLUSSPFERD_CD_CTOR_FWD, \ (BOOST_PP_CAT(p_cpp_name, _base), p_base)) \ }; \ class p_cpp_name \ : \ public BOOST_PP_CAT(p_cpp_name, _base) < p_cpp_name > \ /* */ #define FLUSSPFERD_CD_CTOR_FWD(z, n, d) \ BOOST_PP_EXPR_IF(n, template<) \ BOOST_PP_ENUM_PARAMS(n, typename P) \ BOOST_PP_EXPR_IF(n, >) \ BOOST_PP_TUPLE_ELEM(2, 0, d) \ ( \ BOOST_PP_ENUM_BINARY_PARAMS(n, P, const &p) \ ) \ : \ BOOST_PP_TUPLE_ELEM(2, 1, d) \ ( \ BOOST_PP_ENUM_PARAMS(n, p) \ ) \ { } \ /* */ #define FLUSSPFERD_CD_METHODS(p_methods) \ BOOST_PP_SEQ_FOR_EACH( \ FLUSSPFERD_CD_METHOD, \ ~, \ FLUSSPFERD_PP_GEN_TUPLE3SEQ(p_methods)) \ /* */ #define FLUSSPFERD_CD_METHOD(r, d, p_method) \ BOOST_PP_CAT( \ FLUSSPFERD_CD_METHOD__, \ BOOST_PP_TUPLE_ELEM(3, 1, p_method) \ ) ( \ BOOST_PP_TUPLE_ELEM(3, 0, p_method), \ BOOST_PP_TUPLE_ELEM(3, 2, p_method) \ ) \ /* */ #define FLUSSPFERD_CD_METHOD__bind(p_method_name, p_bound) \ ::flusspferd::create< ::flusspferd::method>( \ ::flusspferd::param::_container = obj, \ ::flusspferd::param::_name = (p_method_name), \ ::flusspferd::param::_function = & Class :: p_bound); \ /* */ #define FLUSSPFERD_CD_METHOD__bind_static(p_method_name, p_bound) \ ::flusspferd::create< ::flusspferd::function>( \ ::flusspferd::param::_container = obj, \ ::flusspferd::param::_name = (p_method_name), \ ::flusspferd::param::_function = & Class :: p_bound); \ /* */ #define FLUSSPFERD_CD_METHOD__alias(p_method_name, p_alias) \ obj.define_property( \ (p_method_name), \ obj.get_property((p_alias)), \ ::flusspferd::dont_enumerate); \ /* */ #define FLUSSPFERD_CD_METHOD__function(p_method_name, p_expr) \ ::flusspferd::create< ::flusspferd::function>( \ ::flusspferd::param::_container = obj, \ ::flusspferd::param::_name = (p_method_name), \ ::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(2, 1, p_expr), \ ::flusspferd::param::_signature = \ ::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(2, 0, p_expr)>()); \ /* */ #define FLUSSPFERD_CD_METHOD__method(p_method_name, p_expr) \ ::flusspferd::create< ::flusspferd::method>( \ ::flusspferd::param::_container = obj, \ ::flusspferd::param::_name = (p_method_name), \ ::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(2, 1, p_expr), \ ::flusspferd::param::_signature = \ ::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(2, 0, p_expr)>()); \ /* */ #define FLUSSPFERD_CD_METHOD__none(p_method_name, p_param) \ /* */ #define FLUSSPFERD_CD_PROPERTIES(p_properties) \ BOOST_PP_SEQ_FOR_EACH( \ FLUSSPFERD_CD_PROPERTY, \ ~, \ FLUSSPFERD_PP_GEN_TUPLE3SEQ(p_properties)) \ /* */ #define FLUSSPFERD_CD_PROPERTY(r, d, p_property) \ BOOST_PP_CAT( \ FLUSSPFERD_CD_PROPERTY__, \ BOOST_PP_TUPLE_ELEM(3, 1, p_property) \ ) ( \ BOOST_PP_TUPLE_ELEM(3, 0, p_property), \ BOOST_PP_TUPLE_ELEM(3, 2, p_property) \ ) \ /* */ #define FLUSSPFERD_CD_PROPERTY__getter_setter(p_property_name, p_param) \ { \ flusspferd::root_object getter( \ ::flusspferd::create< ::flusspferd::method>( \ "$get_" p_property_name, \ & Class :: \ BOOST_PP_TUPLE_ELEM(2, 0, p_param) \ ) \ ); \ flusspferd::root_object setter( \ ::flusspferd::create< ::flusspferd::method>( \ "$set_" p_property_name, \ & Class :: \ BOOST_PP_TUPLE_ELEM(2, 1, p_param) \ ) \ ); \ obj.define_property( \ (p_property_name), \ ::flusspferd::property_attributes( \ ::flusspferd::permanent_shared_property, getter, setter)); \ } \ /* */ #define FLUSSPFERD_CD_PROPERTY__getter_setter_expression(p_property_name, p_expr) \ { \ ::flusspferd::root_object getter(::flusspferd::create< ::flusspferd::method>( \ ::flusspferd::param::_name = (p_property_name), \ ::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(4, 1, p_expr), \ ::flusspferd::param::_signature = \ ::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(4, 0, p_expr)>())); \ ::flusspferd::root_object setter(::flusspferd::create< ::flusspferd::method>( \ ::flusspferd::param::_name = (p_property_name), \ ::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(4, 3, p_expr), \ ::flusspferd::param::_signature = \ ::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(4, 2, p_expr)>())); \ obj.define_property( \ (p_property_name), \ ::flusspferd::property_attributes( \ ::flusspferd::permanent_shared_property, getter, setter)); \ } \ /* */ #define FLUSSPFERD_CD_PROPERTY__getter(p_property_name, p_param) \ { \ ::flusspferd::root_object getter( \ ::flusspferd::create< ::flusspferd::method>( \ "$get_" p_property_name, \ & Class :: p_param \ ) \ ); \ obj.define_property( \ (p_property_name), \ ::flusspferd::property_attributes( \ ::flusspferd::permanent_shared_property \ | ::flusspferd::read_only_property, \ getter \ ) \ ); \ } \ /* */ #define FLUSSPFERD_CD_PROPERTY__getter_expression(p_property_name, p_expr) \ { \ ::flusspferd::root_object getter(::flusspferd::create< ::flusspferd::method>( \ ::flusspferd::param::_name = (p_property_name), \ ::flusspferd::param::_function = BOOST_PP_TUPLE_ELEM(2, 1, p_expr), \ ::flusspferd::param::_signature = \ ::flusspferd::param::type<BOOST_PP_TUPLE_ELEM(2, 0, p_expr)>())); \ obj.define_property( \ (p_property_name), \ ::flusspferd::property_attributes( \ ::flusspferd::permanent_shared_property \ | ::flusspferd::read_only_property, \ getter \ ) \ ); \ } \ /* */ #define FLUSSPFERD_CD_PROPERTY__constant(p_property_name, p_param) \ obj.define_property( \ (p_property_name), \ ::flusspferd::value((p_param)), \ ::flusspferd::read_only_property | ::flusspferd::permanent_property); \ /* */ #define FLUSSPFERD_CD_PROPERTY__variable(p_property_name, p_param) \ obj.define_property( \ (p_property_name), \ ::flusspferd::value((p_param))); \ /* */ #define FLUSSPFERD_CD_PROPERTY__none(p_property_name, p_param) \ /* */ #define FLUSSPFERD_CLASS_DESCRIPTION(p_cpp_name, tuple_seq) \ FLUSSPFERD_CLASS_DESCRIPTION_A( \ FLUSSPFERD_CD_PARAM( \ tuple_seq \ (cpp_name, p_cpp_name) \ ) \ ) \ /* */ #else // IN_DOXYGEN /** * Generate a @ref flusspferd::load_class "loadable" class named @p cpp_name. * * Also generates a template class <code>cpp_name<em>_base</em>&lt;T&gt;</code>. * This class contains a typedef @c base_type to itself, and it is the direct * base class of @p cpp_name. This implies that inside @p cpp_name, the * identifier @p base_type can be used to reference the direct base class, * especially in constructors. * * The class @p base_type has forwarding constructors to its base class (by * default flusspferd::native_object_base), taking each parameter as a constant * reference to its type. These forwarding constructors can be used to * initialize the real (indirect) base class. * * Most importantly, @p base_type contains a class @c class_info, with all * elements set according to the named parameters. * * <dl><dt><b>Usage template:</b></dt><dd> * @code FLUSSPFERD_CLASS_DESCRIPTION( cpp_name, (parameter_name_1, parameter_value_1) (parameter_name_2, parameter_value_2) ... ) { CONTENTS }; * @endcode * </dd></dl> * * @param cpp_name The name of the generated class. * @param named_parameters A sequence of named parameters in the form * <code>(parameter1_name, parameter2_value) * (parameter2_name, parameter2_value) ...</code> * * <dl><dt><b>Named parameters:</b></dt> * <dd><dl> * <dt><em>base</em> (optional)</dt> * <dd><b>{Class}</b> The (indirect) base class. Must be derived from * flusspferd::native_object_base and contain a valid class_info. * The class' prototype will be used as the prototype of the generated * prototype (i.e., @c instanceof works). * <br>Default: flusspferd::native_object_base. * </dd> * <dt><em>constructor_name</em> (required)</dt> * <dd><b>{String}</b> The name of the constructor inside the container passed * to flusspferd::load_class.</dd> * <dt><em>constructor_arity</em> (optional)</dt> * <dd><b>{Integer}</b> The Javascript constructor's arity. * <br>Default: @c 0.</dd> * <dt><em>constructible</em> (optional)</dt> * <dd><b>{Boolean}</b> Whether the class is constructible from Javascript. * <br>Default: @c true.</dd> * <dt><em>full_name</em> (required)</dt> * <dd><b>{String}</b> The full, identifying name of the class, must be * system-unique.</dd> * <dt><em>methods</em> (optional)</dt> * <dd><b>[3-tuple Sequence]</b> Sequence of automatically generated Javascript * methods. Of the form <code>(method_name, type, parameter)...</code>, * where @c method_name is a string. * <br>Default: <code>(~, none, ~)</code></dd> * <dt><em>constructor_methods</em> (optional)</dt> * <dd><b>[3-tuple Sequence]</b> Sequence of automatically generated Javascript * methods <b>on the constructor</b>. Of the form <code>(method_name, type, * parameter)...</code>, * where @c method_name is a string. * <br>Default: <code>(~, none, ~)</code></dd> * <dt><em>properties</em> (optional)</dt> * <dd><b>[3-tuple Sequence]</b> Sequence of automatically generated Javascript * properties. Of the form <code>(property_name, type, parameter)...</code>, * where @c property_name is a string. * <br>Default: <code>(~, none, ~)</code></dd> * <dt><em>constructor_properties</em> (optional)</dt> * <dd><b>[3-tuple Sequence]</b> Sequence of automatically generated Javascript * properties <b>on the constructor</b>. Of the form <code>(property_name, * type, parameter)...</code>, * where @c property_name is a string. * <br>Default: <code>(~, none, ~)</code></dd> * <dt><em>custom_enumerate</em> (optional)</dt> * <dd><b>{Boolean}</b> Whether the class overrides the standard enumerate * hooks. (Enables class_info::custom_enumerate.) * <br>Default: @c true.</dd> * <dt><em>augment_constructor</em> (optional)</dt> * <dd><b>{0,1}</b> If set to 1, @p cpp_name::augment_constructor(ctor) will be * called with the constructor object as parameter when the Javascript * constructor is being generated by flusspferd::load_class (or more * specifically, @c base_type::class_info::augment_constructor). * <br>Default: 0</dd> * <dt><em>augment_prototype</em> (optional)</dt> * <dd><b>{0,1}</b> If set to 1, @p cpp_name::augment_prototype(ctor) will be * called with the prototype object as parameter when the Javascript * constructor is being generated by flusspferd::load_class (or more * specifically, @c base_type::class_info::create_prototype). * <br>Default: 0</dd> * </dl></dd></dl> * * <dl><dt><b>Method types:</b></dt> * <dd>The parameters @c methods and @c constructor_methods take sequences with elements of * the form <code>(method_name, <b>type</b>, parameter)</code>, where @c type is one of * the identifiers mentioned below. * <br><br> * <dl> * <dt><code>(?, <b>none</b>, ?)</code></dt> * <dd>Generates no method. Used as a dummy of the form <code>(~, none, ~)</code> * because empty sequences are not valid.</dd> * <dt><code>(name, <b>bind</b>, method)</code></dt> * <dd>Binds the method with name @p name to non-static method @c cpp_name::method.</dd> * <dt><code>(name, <b>bind_static</b>, method)</code></dt> * <dd>Binds the method with name @p name to the static method @c cpp_name::method.</dd> * <dt><code>(name, <b>alias</b>, alias_name)</code></dt> * <dd>Copies the method @p alias_name into a property with name @p name. The method * @p alias_name must be already defined @em above this method.</dd> * <dt><code>(name, <b>function</b>, (signature, expression))</code></dt> * <dd>Add a function expression (a functor or a Boost.Phoenix expression, * for example) with a given function signature. The class object will * @em not be passed. * @note Use (literally) @p Class instead of the class name in the * expression.</dd> * <dt><code>(name, <b>method</b>, (signature, expression))</code></dt> * <dd>Add a function expression (a functor or a Boost.Phoenix expression, * for example) with a given function signature. The class object * @em will be passed. * @note Use (literally) @p Class instead of the class name in the * expression!</dd> * </dl> * </dd></dl> * * <dl><dt><b>Property types:</b></dt> * <dd>The parameters @c properties and @c constructor_properties take sequences with elements * of the form <code>(property_name, <b>type</b>, parameter)</code>, where @c type is one * of the identifiers mentioned below. * <br><br> * <dl> * <dt><code>(?, <b>none</b>, ?)</code></dt> * <dd>Generates no property. Used as a dummy of the form <code>(~, none, ~)</code> * because empty sequences are not valid.</dd> * <dt><code>(name, <b>getter_setter</b>, (getter, setter))</code></dt> * <dd>Generates a property that is accessed through the accessors (non-static methods) * @p cpp_name::getter and @p cpp_name::setter.</dd> * <dt><code>(name, <b>getter</b>, getter)</code></dt> * <dd>Generates a @em constant property that is accessed through the non-static method * @p cpp_name::getter.</dd> * <dt><code>(name, <b>variable</b>, initial_value)</code></dt> * <dd>Generates a standard property with the initial value @p initial_value.</dd> * <dt><code>(name, <b>constant</b>, value)</code></dt> * <dd>Generates a constant property with the value @p value.</dd> * <dt><code>(name, <b>getter_expression</b>, (signature, expression))</code></dt> * <dd>Generates a @em constant property that is accessed through a getter * expression (a functor or a Boost.Phoenix expression, for example) * with a given function signature. The class object @em will be passed. * @note Use (literally) @p Class instead of the class name in the * expression!</dd> * <dt><code>(name, <b>getter_setter_expression</b>, (getter_signature, getter_expression, setter_signature, setter_expression))</code></dt> * <dd>Generates a property that is accessed through each a getter and * setter expression (a functor or a Boost.Phoenix expression, for example) * with a given function signature. The class object @em will be passed. * @note Use (literally) @p Class instead of the class name in the * expression!</dd> * </dl> * </dd></dl> * * <dl><dt><b>Example:</b></dt> * <dd> * @code FLUSSPFERD_CLASS_DESCRIPTION( my_class, (full_name, "MyModule.MyClass") (constructor_name, "MyClass") (methods, ("myMethod", bind, my_method) ("anotherName", alias, "myMethod")) (constructor_methods, ("constructorMethod", bind_static, constructor_method)) (constructor_properties, ("VERSION", constant, "1.0"))) { double my_method(double parameter) { return parameter * 2; } static double constructor_method(double parameter1, int parameter2) { return parameter1 + parameter1; } }; void some_function() { flusspferd::load_class<my_class>(); } @endcode * </dd></dl> * * @see flusspferd::load_class, flusspferd::class_info * * @ingroup classes */ #define FLUSSPFERD_CLASS_DESCRIPTION(cpp_name, named_parameters) ... #endif // IN_DOXYGEN #endif
38.222222
144
0.652326
Flusspferd
7da444fef18e499bc96280f8f86bf5c177b3b49b
831
cc
C++
src/Parser/AST/AtomExprNode.cc
stenbror/PythonCoreNative
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
[ "BSL-1.0" ]
2
2021-06-09T12:58:46.000Z
2021-06-09T21:06:43.000Z
src/Parser/AST/AtomExprNode.cc
JeffTheK/PythonCoreNative
a5b4c2a4092e39d9094042e88d272f01ae84993d
[ "BSL-1.0" ]
null
null
null
src/Parser/AST/AtomExprNode.cc
JeffTheK/PythonCoreNative
a5b4c2a4092e39d9094042e88d272f01ae84993d
[ "BSL-1.0" ]
1
2021-05-24T11:18:32.000Z
2021-05-24T11:18:32.000Z
#include <ast/AtomExprNode.h> using namespace PythonCoreNative::RunTime::Parser::AST; using namespace PythonCoreNative::RunTime::Parser; AtomExprNode::AtomExprNode( unsigned int start, unsigned int end, std::shared_ptr<Token> op1, std::shared_ptr<ExpressionNode> left, std::shared_ptr<std::vector<std::shared_ptr<ExpressionNode>>> right ) : ExpressionNode(start, end) { mOp1 = op1; mLeft = left; mRight = right; } std::shared_ptr<Token> AtomExprNode::GetOperator() { return mOp1; } std::shared_ptr<ExpressionNode> AtomExprNode::GetLeft() { return mLeft; } std::shared_ptr<std::vector<std::shared_ptr<ExpressionNode>>> AtomExprNode::GetRight() { return mRight; }
25.181818
95
0.613718
stenbror
7daa822af90d6f7d460cf32208aa31ca968062ed
1,070
cpp
C++
robot-car/sensors/UltrasonicSensor.cpp
TanayB11/intro-to-robotics
d1f3c936b80837de189461e492e5d3cae9c164bb
[ "MIT" ]
null
null
null
robot-car/sensors/UltrasonicSensor.cpp
TanayB11/intro-to-robotics
d1f3c936b80837de189461e492e5d3cae9c164bb
[ "MIT" ]
null
null
null
robot-car/sensors/UltrasonicSensor.cpp
TanayB11/intro-to-robotics
d1f3c936b80837de189461e492e5d3cae9c164bb
[ "MIT" ]
null
null
null
//Ultrasonic Ranger #define ECHO A4 #define TRIG A5 #include <Servo.h> Servo rangerServo; // function prototypes void allStop(); void forward(); void back(); void right(); void left(); int findRange(){ //Dist in cm int range; digitalWrite(TRIG,LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(20); digitalWrite(TRIG, LOW); range = pulseIn(ECHO,HIGH); //Pulse width measure in difference of microseconds range = range/58; return(range); delay(500); } void setup(){ Serial.begin(9600); for (int c=0;c<10;c++){ int servoR = 20; int servoL = 180; int servoC = 110; pinMode(ECHO,INPUT); pinMode(TRIG, OUTPUT); rangerServo.attach(3); rangerServo.write(servoL); delay(1000); Serial.println(findRange()); rangerServo.write(servoR); delay(1000); Serial.println(findRange()); rangerServo.write(servoC); delay(1000); Serial.println(findRange()); } } void loop(){ }
20.980392
83
0.598131
TanayB11
7dad0696f55a0708eae5ebfb16be66a70dfa2d75
5,203
cpp
C++
server/server_state_game.cpp
cschreib/cobalt
11184864008f411875a3321f3fb4493ebc9a79e2
[ "MIT" ]
9
2015-12-09T22:25:25.000Z
2022-01-12T23:50:56.000Z
server/server_state_game.cpp
cschreib/cobalt
11184864008f411875a3321f3fb4493ebc9a79e2
[ "MIT" ]
6
2019-12-28T21:18:16.000Z
2020-02-15T21:04:54.000Z
server/server_state_game.cpp
cschreib/cobalt
11184864008f411875a3321f3fb4493ebc9a79e2
[ "MIT" ]
null
null
null
#include "server_state_game.hpp" #include "server_state_idle.hpp" #include "server_instance.hpp" #include <filesystem.hpp> namespace server { namespace state { game::game(server::instance& serv) : base(serv, server::state_id::game, "game"), saving_(false) { // TODO: add all game components to this container save_chunks_.push_back(universe_.make_serializer()); } void game::register_callbacks() { pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::game_save>&& req) { try { save_to_directory(req.arg.save); req.answer(); } catch (request::server::game_save::failure& fail) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } req.fail(std::move(fail)); } catch (...) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } out_.error("unexpected exception in game::save_to_directory()"); throw; } }); pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::game_load>&& req) { try { load_from_directory(req.arg.save); req.answer(); } catch (request::server::game_load::failure& fail) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } req.fail(std::move(fail)); } catch (...) { // Clear load buffers for (auto& c : save_chunks_) { c.clear(); } out_.error("unexpected exception in game::load_from_directory()"); throw; } }); pool_ << net_.watch_request( [this](server::netcom::request_t<request::server::stop_and_idle>&& req) { serv_.set_state<server::state::idle>(); req.answer(); }); } void game::set_player_list(std::unique_ptr<server::player_list> plist) { plist_ = std::move(plist); } void game::save_to_directory(const std::string& dir) { using failure = request::server::game_save::failure; if (saving_) { throw failure{failure::reason::already_saving, ""}; } saving_ = true; // Block the game and bake all game data into serializable structures net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::gathering_game_data )); for (auto& c : save_chunks_) { c.save_data(); } // Save to disk in the background net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::saving_to_disk )); thread_ = std::thread([this, dir]() { for (auto& c : save_chunks_) { c.serialize(dir); } // Clear buffers for (auto& c : save_chunks_) { c.clear(); } net_.send_message(netcom::all_actor_id, make_packet<message::server::game_save_progress>( message::server::game_save_progress::step::game_saved )); saving_ = false; }); } void game::load_from_directory(const std::string& dir) { using failure = request::server::game_load::failure; // The whole game will be blocked during the operation. if (saving_) { throw failure{failure::reason::cannot_load_while_saving, ""}; } if (!file::exists(dir)) { throw failure{failure::reason::no_such_saved_game, ""}; } if (!is_saved_game_directory(dir)) { throw failure{failure::reason::invalid_saved_game, ""}; } // NOTE: One might need to clear the game state before std::uint16_t s = 0; std::uint16_t nchunk = save_chunks_.size(); for (auto& c : save_chunks_) { net_.send_message(netcom::all_actor_id, make_packet<message::server::game_load_progress>( nchunk, s, c.name() )); c.deserialize(dir); c.load_data_first_pass(); ++s; } net_.send_message(netcom::all_actor_id, make_packet<message::server::game_load_progress>( nchunk, nchunk, "loading_second_pass" )); // A two pass loading is needed for some components for (auto& c : save_chunks_) { c.load_data_second_pass(); } // Clear buffers for (auto& c : save_chunks_) { c.clear(); } } bool game::is_saved_game_directory(const std::string& dir) const { for (auto& c : save_chunks_) { if (!c.is_valid_directory(dir)) { return false; } } return true; } } }
30.605882
101
0.528733
cschreib
7daec3a428e9fe2617aa53a1049d7162812a67d4
5,784
cpp
C++
ugene/src/plugins/external_tool_support/src/cufflinks/CuffmergeWorker.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/plugins/external_tool_support/src/cufflinks/CuffmergeWorker.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/plugins/external_tool_support/src/cufflinks/CuffmergeWorker.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "CuffmergeWorker.h" #include <U2Core/L10n.h> #include <U2Designer/DelegateEditors.h> #include <U2Gui/DialogUtils.h> #include <U2Lang/ActorPrototypeRegistry.h> #include <U2Lang/BaseActorCategories.h> #include <U2Lang/BaseTypes.h> #include <U2Lang/WorkflowEnv.h> namespace U2 { namespace LocalWorkflow { /***************************** * CuffmergeWorkerFactory *****************************/ const QString CuffmergeWorkerFactory::ACTOR_ID("cuffmerge"); const QString REF_ANNOTATION("ref-annotation"); const QString REF_SEQ("ref-seq"); const QString CUFFCOMPARE_TOOL_PATH("cuffcompare-tool-path"); const QString EXT_TOOL_PATH("path"); const QString TMP_DIR_PATH("tmp-dir"); void CuffmergeWorkerFactory::init() { QList<PortDescriptor*> portDescriptors; QList<Attribute*> attributes; // Description of the element Descriptor cuffmergeDescriptor(ACTOR_ID, CuffmergeWorker::tr("Merge Assemblies with Cuffmerge"), CuffmergeWorker::tr("Cuffmerge merges together several assemblies." " It also handles running Cuffcompare for you, and automatically" " filters a number of transfrags that are probably artifacts." " If you have a reference file available, you can provide it" " to Cuffmerge in order to gracefully merge input (e.g. novel) isoforms and" " known isoforms and maximize overall assembly quality.")); // Define parameters of the element Descriptor refAnnotation(REF_ANNOTATION, CuffmergeWorker::tr("Reference annotation"), CuffmergeWorker::tr("Merge the input assemblies together with" " this reference annotation")); Descriptor refSeq(REF_SEQ, CuffmergeWorker::tr("Reference sequence"), CuffmergeWorker::tr("The genomic DNA sequences for the reference." " It is used to assist in classifying transfrags and excluding" " artifacts (e.g. repeats). For example, transcripts consisting" " mostly of lower-case bases are classified as repeats.")); Descriptor cuffcompareToolPath(CUFFCOMPARE_TOOL_PATH, CuffmergeWorker::tr("Cuffcompare tool path"), CuffmergeWorker::tr("The path to the Cuffcompare external tool in UGENE")); Descriptor extToolPath(EXT_TOOL_PATH, CuffmergeWorker::tr("Cuffmerge tool path"), CuffmergeWorker::tr("The path to the Cuffmerge external tool in UGENE")); Descriptor tmpDir(TMP_DIR_PATH, CuffmergeWorker::tr("Temporary directory"), CuffmergeWorker::tr("The directory for temporary files")); attributes << new Attribute(refAnnotation, BaseTypes::STRING_TYPE(), false, QVariant("")); attributes << new Attribute(refSeq, BaseTypes::STRING_TYPE(), false, QVariant("")); attributes << new Attribute(cuffcompareToolPath, BaseTypes::STRING_TYPE(), true, QVariant(L10N::defaultStr())); attributes << new Attribute(extToolPath, BaseTypes::STRING_TYPE(), true, QVariant(L10N::defaultStr())); attributes << new Attribute(tmpDir, BaseTypes::STRING_TYPE(), true, QVariant(L10N::defaultStr())); // Create the actor prototype ActorPrototype* proto = new IntegralBusActorPrototype(cuffmergeDescriptor, portDescriptors, attributes); // Values range of some parameters QMap<QString, PropertyDelegate*> delegates; delegates[REF_ANNOTATION] = new URLDelegate(DialogUtils::prepareDocumentsFileFilter(true), "", false); delegates[REF_SEQ] = new URLDelegate(DialogUtils::prepareDocumentsFileFilter(true), "", false); delegates[CUFFCOMPARE_TOOL_PATH] = new URLDelegate("", "executable", false); delegates[EXT_TOOL_PATH] = new URLDelegate("", "executable", false); delegates[TMP_DIR_PATH] = new URLDelegate("", "TmpDir", false, true); // Init and register the actor prototype proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new CuffmergePrompter()); WorkflowEnv::getProtoRegistry()->registerProto( BaseActorCategories::CATEGORY_RNA_SEQ(), proto); DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new CuffmergeWorkerFactory()); } /***************************** * CuffmergePrompter *****************************/ CuffmergePrompter::CuffmergePrompter(Actor* parent) : PrompterBase<CuffmergePrompter>(parent) { } QString CuffmergePrompter::composeRichDoc() { QString result = CuffmergeWorker::tr("Merges together supplied assemblies."); return result; } /***************************** * CuffmergeWorker *****************************/ CuffmergeWorker::CuffmergeWorker(Actor* actor) : BaseWorker(actor), input(NULL), output(NULL) { } void CuffmergeWorker::init() { } Task* CuffmergeWorker::tick() { return NULL; } void CuffmergeWorker::sl_taskFinished() { } void CuffmergeWorker::cleanup() { } } // namespace LocalWorkflow } // namespace U2
33.241379
115
0.703492
iganna
7daed8b0134aa1554ac7b67d778c39e89a446fe6
7,724
cpp
C++
Source/com/Communicator.cpp
goruklu/WPEFramework
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
[ "Apache-2.0" ]
null
null
null
Source/com/Communicator.cpp
goruklu/WPEFramework
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
[ "Apache-2.0" ]
null
null
null
Source/com/Communicator.cpp
goruklu/WPEFramework
99fc7dd0732dbdd9c332df7ceccb625436ab7a4e
[ "Apache-2.0" ]
null
null
null
#include "Communicator.h" namespace WPEFramework { namespace RPC { static Core::ProxyPoolType<RPC::AnnounceMessage> AnnounceMessageFactory(2); static void LoadProxyStubs(const string& pathName) { static std::list<Core::Library> processProxyStubs; Core::Directory index(pathName.c_str(), _T("*.so")); while (index.Next() == true) { // Check if this ProxySTub file is already loaded in this process space.. std::list<Core::Library>::const_iterator loop(processProxyStubs.begin()); while ((loop != processProxyStubs.end()) && (loop->Name() != index.Current())) { loop++; } if (loop == processProxyStubs.end()) { Core::Library library(index.Current().c_str()); if (library.IsLoaded() == true) { processProxyStubs.push_back(library); } } } } void* Communicator::RemoteProcess::Aquire(const uint32_t waitTime, const string& className, const uint32_t interfaceId, const uint32_t versionId) { void* result(nullptr); if (_channel.IsValid() == true) { Core::ProxyType<RPC::AnnounceMessage> message(AnnounceMessageFactory.Element()); message->Parameters().Set(className, interfaceId, versionId); uint32_t feedback = _channel->Invoke(message, waitTime); if (feedback == Core::ERROR_NONE) { void* implementation = message->Response().Implementation(); if (implementation != nullptr) { // From what is returned, we need to create a proxy ProxyStub::UnknownProxy* instance = RPC::Administrator::Instance().ProxyInstance(_channel, implementation, interfaceId, true, interfaceId, false); result = (instance != nullptr ? instance->QueryInterface(interfaceId) : nullptr); } } } return (result); } Communicator::Communicator(const Core::NodeId& node, Core::ProxyType<IHandler> handler, const string& proxyStubPath) : _processMap(*this) , _ipcServer(node, _processMap, handler, proxyStubPath) { if (proxyStubPath.empty() == false) { RPC::LoadProxyStubs(proxyStubPath); } // These are the elements we are expecting to receive over the IPC channels. _ipcServer.CreateFactory<AnnounceMessage>(1); _ipcServer.CreateFactory<InvokeMessage>(3); } /* virtual */ Communicator::~Communicator() { // Make sure any closed channel is cleared before we start validating the end result :-) _ipcServer.Cleanup(); // All process must be terminated if we end up here :-) ASSERT(_processMap.Size() == 0); // Close all communication paths... _ipcServer.Close(Core::infinite); _ipcServer.DestroyFactory<InvokeMessage>(); _ipcServer.DestroyFactory<AnnounceMessage>(); TRACE_L1("Clearing Communicator. Active Processes %d", _processMap.Size()); } void Communicator::RemoteProcess::Terminate() { ASSERT(_parent != nullptr); if (_parent != nullptr) { _parent->Destroy(Id()); } } CommunicatorClient::CommunicatorClient(const Core::NodeId& remoteNode, Core::ProxyType<IHandler> handler) : Core::IPCChannelClientType<Core::Void, false, true>(remoteNode, CommunicationBufferSize) , _announceMessage(Core::ProxyType<RPC::AnnounceMessage>::Create()) , _announceEvent(false, true) , _handler(handler) , _announcements(*this) { CreateFactory<RPC::AnnounceMessage>(1); CreateFactory<RPC::InvokeMessage>(2); Register(_handler->InvokeHandler()); Register(_handler->AnnounceHandler()); _handler->AnnounceHandler(&_announcements); // For now clients do not support announce messages from the server... // Register(_handler->AnnounceHandler()); } CommunicatorClient::~CommunicatorClient() { BaseClass::Close(Core::infinite); Unregister(_handler->AnnounceHandler()); Unregister(_handler->InvokeHandler()); _handler->AnnounceHandler(nullptr); DestroyFactory<RPC::InvokeMessage>(); DestroyFactory<RPC::AnnounceMessage>(); } uint32_t CommunicatorClient::Open(const uint32_t waitTime) { ASSERT(BaseClass::IsOpen() == false); _announceEvent.ResetEvent(); //do not set announce parameters, we do not know what side will offer the interface uint32_t result = BaseClass::Open(waitTime); if ((result == Core::ERROR_NONE) && (_announceEvent.Lock(waitTime) != Core::ERROR_NONE)) { result = Core::ERROR_OPENING_FAILED; } return (result); } uint32_t CommunicatorClient::Open(const uint32_t waitTime, const string& className, const uint32_t interfaceId, const uint32_t version) { ASSERT(BaseClass::IsOpen() == false); _announceEvent.ResetEvent(); _announceMessage->Parameters().Set(className, interfaceId, version); uint32_t result = BaseClass::Open(waitTime); if ((result == Core::ERROR_NONE) && (_announceEvent.Lock(waitTime) != Core::ERROR_NONE)) { result = Core::ERROR_OPENING_FAILED; } return (result); } uint32_t CommunicatorClient::Open(const uint32_t waitTime, const uint32_t interfaceId, void* implementation) { ASSERT(BaseClass::IsOpen() == false); _announceEvent.ResetEvent(); _announceMessage->Parameters().Set(interfaceId, implementation, Data::Init::REQUEST); uint32_t result = BaseClass::Open(waitTime); if ((result == Core::ERROR_NONE) && (_announceEvent.Lock(waitTime) != Core::ERROR_NONE)) { result = Core::ERROR_OPENING_FAILED; } return (result); } uint32_t CommunicatorClient::Close(const uint32_t waitTime) { return (BaseClass::Close(waitTime)); } /* virtual */ void CommunicatorClient::StateChange() { BaseClass::StateChange(); if (BaseClass::Source().IsOpen()) { TRACE_L1("Invoking the Announce message to the server. %d", __LINE__); uint32_t result = Invoke<RPC::AnnounceMessage>(_announceMessage, this); TRACE_L1("Todo Announce message handled. %d", __LINE__); if (result != Core::ERROR_NONE) { TRACE_L1("Error during invoke of AnnounceMessage: %d", result); } } else { TRACE_L1("Connection to the server is down (ticket has been raised: WPE-255)"); } } /* virtual */ void CommunicatorClient::Dispatch(Core::IIPC& element) { // Message delivered and responded on.... RPC::AnnounceMessage* announceMessage = static_cast<RPC::AnnounceMessage*>(&element); ASSERT(dynamic_cast<RPC::AnnounceMessage*>(&element) != nullptr); // Is result of an announce message, contains default trace categories in JSON format. string jsonDefaultCategories(announceMessage->Response().TraceCategories()); if (jsonDefaultCategories.empty() == false) { Trace::TraceUnit::Instance().SetDefaultCategoriesJson(jsonDefaultCategories); } string proxyStubPath(announceMessage->Response().ProxyStubPath()); if (proxyStubPath.empty() == false) { // Also load the ProxyStubs before we do anything else RPC::LoadProxyStubs(proxyStubPath); } // Set event so WaitForCompletion() can continue. _announceEvent.SetEvent(); } } }
35.431193
166
0.625971
goruklu
7db01b41db6a230d93d36370ee279da8d2d3771c
1,954
cc
C++
src/core/basetypes/MCLog.cc
zhanleewo/mailcore2
a6c2d0465b25351689a1b4761f191201275f2b52
[ "BSD-3-Clause" ]
null
null
null
src/core/basetypes/MCLog.cc
zhanleewo/mailcore2
a6c2d0465b25351689a1b4761f191201275f2b52
[ "BSD-3-Clause" ]
null
null
null
src/core/basetypes/MCLog.cc
zhanleewo/mailcore2
a6c2d0465b25351689a1b4761f191201275f2b52
[ "BSD-3-Clause" ]
null
null
null
#include "MCLog.h" #include <stdarg.h> #include <string.h> #include <stdio.h> #include <time.h> #include <sys/time.h> #include <pthread.h> #include <unistd.h> static pid_t sPid = -1; bool mailcore::logEnabled = false; __attribute__((constructor)) static void initialize() { sPid = getpid(); } static void logInternalv(FILE * file, const char * user, const char * filename, unsigned int line, int dumpStack, const char * format, va_list argp); void mailcore::logInternal(const char * user, const char * filename, unsigned int line, int dumpStack, const char * format, ...) { va_list argp; va_start(argp, format); logInternalv(stderr, user, filename, line, dumpStack, format, argp); va_end(argp); } static void logInternalv(FILE * file, const char * user, const char * filename, unsigned int line, int dumpStack, const char * format, va_list argp) { if (!mailcore::logEnabled) return; while (1) { const char * p = filename; p = strchr(filename, '/'); if (p == NULL) { break; } filename = p + 1; } struct timeval tv; struct tm tm_value; pthread_t thread_id = pthread_self(); gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm_value); fprintf(file, "%04u-%02u-%02u %02u:%02u:%02u.%03u ", tm_value.tm_year + 1900, tm_value.tm_mon + 1, tm_value.tm_mday, tm_value.tm_hour, tm_value.tm_min, tm_value.tm_sec, (int) (tv.tv_usec / 1000)); #ifdef __MACH__ if (pthread_main_np()) { #else if (0) { #endif fprintf(file, "[%i:main] %s:%i: ", sPid, filename, line); } else { unsigned long threadValue; #ifdef _MACH_PORT_T threadValue = pthread_mach_thread_np(thread_id); #else threadValue = (unsigned long) thread_id; #endif fprintf(file, "[%i:%lx] %s:%i: ", sPid, threadValue, filename, line); } vfprintf(file, format, argp); fprintf(file, "\n"); }
24.425
197
0.631013
zhanleewo
7db36b23be968d4b9e78291144751234d7bfb4e8
1,945
cc
C++
www/cliqz/patches/patch-mozilla-release_media_webrtc_trunk_webrtc_modules_video__capture_linux_device__info__linux.cc
fraggerfox/cliqz-pkgsrc
61233b17d4c5bc1edeb571ddbf00fb2308c10c5f
[ "BSD-2-Clause" ]
null
null
null
www/cliqz/patches/patch-mozilla-release_media_webrtc_trunk_webrtc_modules_video__capture_linux_device__info__linux.cc
fraggerfox/cliqz-pkgsrc
61233b17d4c5bc1edeb571ddbf00fb2308c10c5f
[ "BSD-2-Clause" ]
null
null
null
www/cliqz/patches/patch-mozilla-release_media_webrtc_trunk_webrtc_modules_video__capture_linux_device__info__linux.cc
fraggerfox/cliqz-pkgsrc
61233b17d4c5bc1edeb571ddbf00fb2308c10c5f
[ "BSD-2-Clause" ]
null
null
null
$NetBSD: patch-mozilla-release_media_webrtc_trunk_webrtc_modules_video__capture_linux_device__info__linux.cc,v 1.1 2020/07/24 07:29:32 fox Exp $ * Fix buiuld under NetBSD. NetBSD's sys/videoio.h does not have v4l2_capability.device_caps and video capture does not work for me anyway. Taken from www/firefox --- mozilla-release/media/webrtc/trunk/webrtc/modules/video_capture/linux/device_info_linux.cc.orig 2020-06-19 00:11:06.000000000 +0000 +++ mozilla-release/media/webrtc/trunk/webrtc/modules/video_capture/linux/device_info_linux.cc @@ -207,10 +207,12 @@ uint32_t DeviceInfoLinux::NumberOfDevice sprintf(device, "/dev/video%d", n); if ((fd = open(device, O_RDONLY)) != -1) { // query device capabilities and make sure this is a video capture device +#if !defined(__NetBSD__) if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0 || !(cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) { close(fd); continue; } +#endif close(fd); count++; @@ -241,10 +243,12 @@ int32_t DeviceInfoLinux::GetDeviceName(u sprintf(device, "/dev/video%d", device_index); if ((fd = open(device, O_RDONLY)) != -1) { // query device capabilities and make sure this is a video capture device +#if !defined(__NetBSD__) if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0 || !(cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) { close(fd); continue; } +#endif if (count == deviceNumber) { // Found the device found = true; @@ -328,9 +332,11 @@ int32_t DeviceInfoLinux::CreateCapabilit struct v4l2_capability cap; if (ioctl(fd, VIDIOC_QUERYCAP, &cap) == 0) { // skip devices without video capture capability +#if !defined(__NetBSD__) if (!(cap.device_caps & V4L2_CAP_VIDEO_CAPTURE)) { continue; } +#endif if (cap.bus_info[0] != 0) { if (strncmp((const char*)cap.bus_info, (const char*)deviceUniqueIdUTF8,
39.693878
144
0.66838
fraggerfox
7db8d980c2a3aaaf7ab23d1ce8b4f91c9ec67f33
3,101
cpp
C++
Sources/Elastos/LibCore/src/elastos/text/CDateFormatHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/src/elastos/text/CDateFormatHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/src/elastos/text/CDateFormatHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "CDateFormatHelper.h" #include "DateFormat.h" namespace Elastos { namespace Text { CAR_INTERFACE_IMPL(CDateFormatHelper, Singleton, IDateFormatHelper) CAR_SINGLETON_IMPL(CDateFormatHelper) ECode CDateFormatHelper::GetAvailableLocales( /* [out, callee] */ ArrayOf<ILocale*>** locales) { return DateFormat::GetAvailableLocales(locales); } ECode CDateFormatHelper::GetDateInstance( /* [out] */ IDateFormat** instance) { return DateFormat::GetDateInstance(instance); } ECode CDateFormatHelper::GetDateInstance( /* [in] */ Int32 style, /* [out] */ IDateFormat** instance) { return DateFormat::GetDateInstance(style,instance); } ECode CDateFormatHelper::GetDateInstance( /* [in] */ Int32 style, /* [in] */ ILocale* locale, /* [out] */ IDateFormat** instance) { return DateFormat::GetDateInstance(style,locale,instance); } ECode CDateFormatHelper::GetDateTimeInstance( /* [out] */ IDateFormat** instance) { return DateFormat::GetDateTimeInstance(instance); } ECode CDateFormatHelper::GetDateTimeInstance( /* [in] */ Int32 dateStyle, /* [in] */ Int32 timeStyle, /* [out] */ IDateFormat** instance) { return DateFormat::GetDateTimeInstance(dateStyle,timeStyle,instance); } ECode CDateFormatHelper::GetDateTimeInstance( /* [in] */ Int32 dateStyle, /* [in] */ Int32 timeStyle, /* [in] */ ILocale* locale, /* [out] */ IDateFormat** instance) { return DateFormat::GetDateTimeInstance(dateStyle,timeStyle,locale,instance); } ECode CDateFormatHelper::Set24HourTimePref( /* [in] */ Boolean bval) { return DateFormat::Set24HourTimePref(bval); } ECode CDateFormatHelper::GetInstance( /* [out] */ IDateFormat** instance) { return DateFormat::GetInstance(instance); } ECode CDateFormatHelper::GetTimeInstance( /* [out] */ IDateFormat** instance) { return DateFormat::GetTimeInstance(instance); } ECode CDateFormatHelper::GetTimeInstance( /* [in] */ Int32 style, /* [out] */ IDateFormat** instance) { return DateFormat::GetTimeInstance(style,instance); } ECode CDateFormatHelper::GetTimeInstance( /* [in] */ Int32 style, /* [in] */ ILocale* locale, /* [out] */ IDateFormat** instance) { return DateFormat::GetTimeInstance(style,locale,instance); } } // namespace Text } // namespace Elastos
27.6875
80
0.671719
jingcao80
7dbb3900d3bf652de4dde9567004d7685874909b
12,103
hpp
C++
search/flrtastar.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
28
2015-02-10T04:06:16.000Z
2022-03-11T11:51:38.000Z
search/flrtastar.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
3
2016-11-03T12:03:28.000Z
2020-07-13T17:35:40.000Z
search/flrtastar.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
9
2015-10-22T20:22:45.000Z
2020-06-30T20:11:31.000Z
// Copyright © 2013 the Search Authors under the MIT license. See AUTHORS for the list of authors. #pragma once #include "../search/search.hpp" #include "../utils/geom2d.hpp" #include "../utils/pool.hpp" #include <vector> template <class D> class Flrtastar2 : public SearchAlgorithm<D> { private: typedef typename D::PackedState PackedState; typedef typename D::Operators Operators; typedef typename D::State State; typedef typename D::Cost Cost; typedef typename D::Oper Oper; typedef typename D::Edge Edge; class Node; class Nodes; struct inedge { inedge(Node *n, double c) : node(n), incost(c) { } Node *node; double incost; }; struct outedge { outedge(Node *n, Oper o, Cost rc, Cost c) : node(n), op(o), revcost(rc == Cost(-1) ? geom2d::Infinity : rc), outcost(c == Cost(-1) ? geom2d::Infinity : c) { } Node *node; Oper op; double revcost; double outcost; }; class Node { public: static ClosedEntry<Node, D> &closedentry(Node *n) { return n->closedent; } static PackedState &key(Node *n) { return n->state; } PackedState state; double gglobal, h, hdef; bool dead; bool expd; // was this expanded before? bool goal; std::vector<outedge> succs; std::vector<inedge> preds; private: friend class Nodes; friend class Pool<Node>; Node() : gglobal(geom2d::Infinity), dead(false), expd(false) { } ClosedEntry<Node, D> closedent; }; class Nodes { public: Nodes(unsigned int sz) : tbl(sz) { pool = new Pool<Node>(); } ~Nodes() { delete pool; } void clear() { tbl.clear(); delete pool; pool = new Pool<Node>(); } Node *get(D &d, State &s) { Node *n = pool->construct(); d.pack(n->state, s); unsigned long hash = n->state.hash(&d); Node *found = tbl.find(n->state, hash); if (found) { pool->destruct(n); return found; } n->goal = d.isgoal(s); n->h = n->hdef = d.h(s); tbl.add(n, hash); return n; } private: ClosedList<Node, Node, D> tbl; Pool<Node> *pool; }; class AstarNode { public: AstarNode() : openind(-1), updated(false) { } class Nodes { public: static ClosedEntry<AstarNode, D> &closedentry(AstarNode *n) { return n->nodesent; } static PackedState &key(AstarNode *n) { return n->node->state; } }; class Closed { public: static ClosedEntry<AstarNode, D> &closedentry(AstarNode *n) { return n->closedent; } static PackedState &key(AstarNode *n) { return n->node->state; } }; class FSort { public: static void setind(AstarNode *n, int i) { n->openind = i; } static bool pred(AstarNode *a, AstarNode *b) { if (geom2d::doubleeq(a->f, b->f)) return a->glocal > b->glocal; return a->f < b->f; } }; class HSort { public: static void setind(AstarNode *n, int i) { n->openind = i; } static bool pred(AstarNode *a, AstarNode *b) { return a->node->h < b->node->h; } }; Node *node; AstarNode *parent; double glocal, f; Oper op; long openind; bool updated; private: ClosedEntry<AstarNode, D> closedent, nodesent; }; public: Flrtastar2(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), astarClosed(1), astarNodes(1), nodes(30000001), lookahead(0) { for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-lookahead") == 0) lookahead = strtoul(argv[++i], NULL, 10); } if (lookahead < 1) fatal("Must specify a lookahead ≥1 using -lookahead"); astarPool = new Pool<AstarNode>(); astarNodes.resize(lookahead*3); astarClosed.resize(lookahead*3); } ~Flrtastar2() { delete astarPool; } void reset() { SearchAlgorithm<D>::reset(); nodes.clear(); astarOpen.clear(); astarClosed.clear(); astarNodes.clear(); delete astarPool; astarPool = new Pool<AstarNode>(); } void search(D &d, State &s0) { this->start(); Node *cur = nodes.get(d, s0); cur->gglobal = 0; while (!cur->goal && !this->limit()) { AstarNode *goal = expandLss(d, cur); if (!goal && !this->limit()) { gCostLearning(d); hCostLearning(d); markDeadRedundant(d); } cur = move(cur, goal); times.push_back(walltime() - this->res.wallstart); } this->finish(); if (!cur->goal) { this->res.ops.clear(); return; } // Rebuild the path from the operators. nodes.clear(); this->res.path.push_back(s0); for (auto it = this->res.ops.begin(); it != this->res.ops.end(); it++) { State copy = this->res.path.back(); Edge e(d, copy, *it); this->res.path.push_back(e.state); } std::reverse(this->res.ops.begin(), this->res.ops.end()); std::reverse(this->res.path.begin(), this->res.path.end()); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); dfpair(out, "num steps", "%lu", (unsigned long) times.size()); assert (lengths.size() == times.size()); if (times.size() != 0) { double min = times.front(); double max = times.front(); for (unsigned int i = 1; i < times.size(); i++) { double dt = times[i] - times[i-1]; if (dt < min) min = dt; if (dt > max) max = dt; } dfpair(out, "first emit wall time", "%f", times.front()); dfpair(out, "min step wall time", "%f", min); dfpair(out, "max step wall time", "%f", max); dfpair(out, "mean step wall time", "%f", (times.back()-times.front())/times.size()); } if (lengths.size() != 0) { unsigned int min = lengths.front(); unsigned int max = lengths.front(); unsigned long sum = 0; for (auto l : lengths) { if (l < min) min = l; if (l > max) max = l; sum += l; } dfpair(out, "min step length", "%u", min); dfpair(out, "max step length", "%u", max); dfpair(out, "mean step length", "%g", sum / (double) lengths.size()); } } private: // ExpandLss returns the cheapest goal node if one was generated // and NULL otherwise. AstarNode *expandLss(D &d, Node *rootNode) { astarOpen.clear(); for (auto n : astarNodes) astarPool->destruct(n); astarNodes.clear(); astarClosed.clear(); AstarNode *a = astarPool->construct(); a->node = rootNode; a->parent = NULL; a->op = D::Nop; a->glocal = 0; a->f = rootNode->h; astarOpen.push(a); astarNodes.add(a); AstarNode *goal = NULL; for (unsigned int exp = 0; !astarOpen.empty() && exp < lookahead && !this->limit(); exp++) { AstarNode *s = *astarOpen.pop(); if (!astarClosed.find(s->node->state)) astarClosed.add(s); if (s->node->dead) continue; AstarNode *g = expandPropagate(d, s, true); if (g && (!goal || g->glocal < goal->glocal)) goal = g; if (s->node->goal) { astarOpen.push(s); goal = s; break; } } return goal; } // ExpandPropagate returns the cheapest goal node if one is generated // and NULL otherwise. AstarNode *expandPropagate(D &d, AstarNode *s, bool doExpand) { AstarNode *goal = NULL; if (this->limit()) return NULL; auto kids = expand(d, s->node); for (unsigned int i = 0; i < kids.size(); i++) { auto e = kids[i]; Node *k = e.node; AstarNode *kid = astarNodes.find(k->state); if (doExpand && astarNodes.find(s->node->state)) { if (!kid) { kid = astarPool->construct(); kid->node = k; kid->glocal = geom2d::Infinity; kid->openind = -1; astarNodes.add(kid); } if (kid->glocal > s->glocal + e.outcost) { if (kid->parent) // !NULL if a dup this->res.dups++; kid->parent = s; kid->glocal = s->glocal + e.outcost; kid->f = kid->glocal + kid->node->h; kid->op = e.op; astarOpen.pushupdate(kid, kid->openind); } } if (k->goal && kid && (!goal || kid->glocal < goal->glocal)) goal = kid; if (s->node->gglobal + e.outcost < k->gglobal) { bool wasDead = k->dead; k->dead = false; k->gglobal = s->node->gglobal + e.outcost; // k->h = k->hdef; bool onClosed = astarClosed.find(k->state); if (kid && onClosed && wasDead) expandPropagate(d, kid, true); else if (kid && (kid->openind >= 0 || onClosed)) expandPropagate(d, kid, false); } if (k->gglobal + e.revcost < s->node->gglobal && !k->dead) { s->node->gglobal = k->gglobal + e.revcost; // s->node->h = s->node->hdef; if (i > 0) i = -1; } } return goal; } void gCostLearning(D &d) { std::vector<AstarNode*> &o = astarOpen.data(); for (unsigned int i = 0; i < o.size(); i++) { if (!o[i]->node->dead) expandPropagate(d, o[i], false); } } void hCostLearning(D &d) { BinHeap<typename AstarNode::HSort, AstarNode*> open; open.append(astarOpen.data()); unsigned long left = astarClosed.getFill(); while (left > 0 && !open.empty()) { AstarNode *s = *open.pop(); if (astarClosed.find(s->node->state)) left--; for (auto e : s->node->preds) { Node *sprime = e.node; AstarNode *sp = astarClosed.find(sprime->state); if (!sp) continue; if (!sp->updated || sprime->h > e.incost + s->node->h) { sprime->h = e.incost + s->node->h; sp->updated = true; open.pushupdate(sp, sp->openind); } } } } void markDeadRedundant(D &d) { for (auto n : astarClosed) { assert(!n->node->goal); if (n->node->dead) // || n->node->goal) continue; n->node->dead = isDead(d, n->node) || isRedundant(d, n->node); } for (auto n : astarOpen.data()) { if (n->node->dead || n->node->goal) continue; assert (!std::isinf(n->node->gglobal)); n->node->dead = isDead(d, n->node) || isRedundant(d, n->node); } } bool isDead(D &d, Node *n) { for (auto succ : expand(d, n)) { if (succ.node->gglobal >= n->gglobal + succ.outcost) return false; } return true; } bool isRedundant(D &d, Node *n) { for (auto succ : expand(d, n)) { if (succ.node->dead) continue; // The distinct predecessor with minimum f was the earliest // to be expanded. Node *distinct = NULL; double bestc = geom2d::Infinity; for (auto pred : succ.node->preds) { if (pred.node->dead) continue; double c = pred.node->gglobal + pred.incost; if (!distinct || c < bestc) { distinct = pred.node; bestc = c; } assert (distinct == n || !std::isinf(succ.node->gglobal)); } if (distinct == n) return false; } return true; } Node *move(Node *cur, AstarNode *goal) { AstarNode *best = goal; if (!best) { for (auto n : astarOpen.data()) { if (n->node == cur || n->node->dead) continue; if (best == NULL || AstarNode::FSort::pred(n, best)) best = n; } } if (best) { assert (best->node != cur); std::vector<Oper> ops; for (AstarNode *p = best; p->node != cur; p = p->parent) { assert (p->parent != best); // no cycles ops.push_back(p->op); } this->res.ops.insert(this->res.ops.end(), ops.rbegin(), ops.rend()); lengths.push_back(ops.size()); return best->node; } outedge next = cur->succs[0]; for (unsigned int i = 1; i < cur->succs.size(); i++) { if (cur->succs[i].node->gglobal < next.node->gglobal) next = cur->succs[i]; } this->res.ops.push_back(next.op); lengths.push_back(1); return next.node; } // Expand returns the successor nodes of a state. std::vector<outedge> expand(D &d, Node *n) { assert(!n->dead); if (n->expd) return n->succs; State buf, &s = d.unpack(buf, n->state); this->res.expd++; Operators ops(d, s); for (unsigned int i = 0; i < ops.size(); i++) { this->res.gend++; Edge e(d, s, ops[i]); Node *k = nodes.get(d, e.state); if (std::isinf(k->gglobal)) k->gglobal = n->gglobal + e.cost; k->preds.emplace_back(n, e.cost); n->succs.emplace_back(k, ops[i], e.revcost, e.cost); } n->expd = true; return n->succs; } BinHeap<typename AstarNode::FSort, AstarNode*> astarOpen; ClosedList<typename AstarNode::Closed, AstarNode, D> astarClosed; ClosedList<typename AstarNode::Nodes, AstarNode, D> astarNodes; Pool<AstarNode> *astarPool; Nodes nodes; unsigned int lookahead; std::vector<double> times; std::vector<unsigned int> lengths; };
22.207339
98
0.590102
skiesel
7dbe445dba5f2fdc6d304dc5747b534460221d13
626
hpp
C++
src/shader.hpp
qkniep/Simetra
734292ff3d48afd83f811501d8da39f5bb0d3623
[ "MIT" ]
2
2021-01-07T15:30:36.000Z
2021-06-13T21:47:46.000Z
src/shader.hpp
qkniep/Simetra
734292ff3d48afd83f811501d8da39f5bb0d3623
[ "MIT" ]
null
null
null
src/shader.hpp
qkniep/Simetra
734292ff3d48afd83f811501d8da39f5bb0d3623
[ "MIT" ]
null
null
null
#ifndef SHADER_HPP #define SHADER_HPP #include <string> #include <GLFW/glfw3.h> class ShaderProgram { GLuint programID; public: bool load(const char* vertexFilePath, const char* fragmentFilePath); void use(); GLuint getProgramID(); private: static bool loadShaderFromFile(const GLuint shaderID, const char* filePath); static bool readShaderCodeFromFile(std::string& shaderCode, const char* filePath); static bool compileShader(const GLuint shaderID, const std::string& shaderCode); void linkProgram(const GLuint vertexShaderID, const GLuint fragmentShaderID); }; #endif // SHADER_HPP
24.076923
84
0.749201
qkniep
7dc0c97881c6a9cdcf7f9d5456557ea9e190341b
2,759
cpp
C++
Engine/Source/Runtime/Engine/Private/UserInterface/EngineFontServices.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Engine/Private/UserInterface/EngineFontServices.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Engine/Private/UserInterface/EngineFontServices.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "EnginePrivate.h" #include "EngineFontServices.h" #include "SlateBasics.h" #if !UE_SERVER #include "ISlateRHIRendererModule.h" #endif FEngineFontServices* FEngineFontServices::Instance = nullptr; FEngineFontServices::FEngineFontServices() { check(IsInGameThread()); #if !UE_SERVER if (!IsRunningDedicatedServer()) { RenderThreadFontAtlasFactory = FModuleManager::Get().GetModuleChecked<ISlateRHIRendererModule>("SlateRHIRenderer").CreateSlateFontAtlasFactory(); } #endif } FEngineFontServices::~FEngineFontServices() { check(IsInGameThread()); if(RenderThreadFontCache.IsValid()) { RenderThreadFontCache->ReleaseResources(); FlushRenderingCommands(); RenderThreadFontCache.Reset(); } } void FEngineFontServices::Create() { check(!Instance); Instance = new FEngineFontServices(); } void FEngineFontServices::Destroy() { check(Instance); delete Instance; Instance = nullptr; } bool FEngineFontServices::IsInitialized() { return Instance != nullptr; } FEngineFontServices& FEngineFontServices::Get() { check(Instance); return *Instance; } TSharedPtr<FSlateFontCache> FEngineFontServices::GetFontCache() { check(IsInGameThread() || IsInRenderingThread()); #if !UE_SERVER if(IsInGameThread()) { if(FSlateApplication::IsInitialized()) { return FSlateApplication::Get().GetRenderer()->GetFontCache(); } } else { ConditionalCreateRenderThreadFontCache(); return RenderThreadFontCache; } #endif return nullptr; } TSharedPtr<FSlateFontMeasure> FEngineFontServices::GetFontMeasure() { check(IsInGameThread() || IsInRenderingThread()); #if !UE_SERVER if(IsInGameThread()) { if(FSlateApplication::IsInitialized()) { FSlateApplication::Get().GetRenderer()->GetFontMeasureService(); } } else { ConditionalCreatRenderThreadFontMeasure(); return RenderThreadFontMeasure; } #endif return nullptr; } void FEngineFontServices::UpdateCache() { check(IsInGameThread() || IsInRenderingThread()); if(IsInGameThread()) { if(FSlateApplication::IsInitialized()) { FSlateApplication::Get().GetRenderer()->GetFontCache()->UpdateCache(); } } else { if(RenderThreadFontCache.IsValid()) { RenderThreadFontCache->UpdateCache(); } } } void FEngineFontServices::ConditionalCreateRenderThreadFontCache() { if(!RenderThreadFontCache.IsValid()) { RenderThreadFontCache = MakeShareable(new FSlateFontCache(RenderThreadFontAtlasFactory.ToSharedRef())); } } void FEngineFontServices::ConditionalCreatRenderThreadFontMeasure() { ConditionalCreateRenderThreadFontCache(); if(!RenderThreadFontMeasure.IsValid()) { RenderThreadFontMeasure = FSlateFontMeasure::Create(RenderThreadFontCache.ToSharedRef()); } }
19.429577
147
0.760783
PopCap
7dc183c37c84af1bbbe3a71a43284014cf3a4010
2,715
cpp
C++
main.cpp
nathan-osman/sudokubot
3088cae5ea88fa6c2e08853c712bab8f9e4d4752
[ "MIT" ]
null
null
null
main.cpp
nathan-osman/sudokubot
3088cae5ea88fa6c2e08853c712bab8f9e4d4752
[ "MIT" ]
null
null
null
main.cpp
nathan-osman/sudokubot
3088cae5ea88fa6c2e08853c712bab8f9e4d4752
[ "MIT" ]
null
null
null
/** * The MIT License (MIT) * * Copyright (c) 2015 Nathan Osman * * 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 <cstring> #include <iostream> #include "puzzle.h" int main(int argc, char **argv) { // Currently, input to the program is provided by way of a single command- // line argument containing the 81 digits for the puzzle in order from // left-to-right and then top-to-bottom // Ensure the correct input was provided if(argc != 2 || strlen(argv[1]) != 81) { std::cerr << "Error: argument be a list of 81 digits" << std::endl; return 1; } Puzzle puzzle; char *input = argv[1]; // Whenever a digit between 1 and 9 (inclusive) is specified, set the // corresponding square in the puzzle - everything else is unknown for(int i = 0; i < 81; ++i) { if(input[i] >= '1' && input[i] <= '9') { puzzle.set(i % 9, i / 9, input[i] - '0'); } } // Let the puzzle solver do all of the hard work bool solved = puzzle.solve(); // Indicate the status to the user std::cerr << std::endl << (solved ? "Puzzle was solved" : "Unable to solve puzzle") << std::endl << std::endl; // Display a grid of the solution (or the solver's attempt if unsolved) for(int y = 0; y < 9; ++y) { std::cout << "|"; for(int x = 0; x < 9; ++x) { int num = puzzle.get(x, y); std::cout << (num ? static_cast<char>(num + '0') : ' ') << '|'; } std::cout << std::endl; } std::cerr << std::endl; // Return 0 (success) only if the puzzle was solved return solved ? 0 : 1; }
35.25974
79
0.632044
nathan-osman
7dc2e2f3b3958394ab573ab39b079a6f0d422ff1
16,397
cc
C++
examples/tester/wampcc_tester.cc
vai-hhn/wampcc
ac206f60028406ea8af4c295e11cbc7de67cf2ad
[ "MIT" ]
70
2017-03-09T12:45:30.000Z
2021-12-31T20:34:40.000Z
examples/tester/wampcc_tester.cc
vai-hhn/wampcc
ac206f60028406ea8af4c295e11cbc7de67cf2ad
[ "MIT" ]
54
2017-04-15T23:02:08.000Z
2021-04-13T08:44:25.000Z
examples/tester/wampcc_tester.cc
vai-hhn/wampcc
ac206f60028406ea8af4c295e11cbc7de67cf2ad
[ "MIT" ]
30
2017-06-02T14:12:28.000Z
2021-12-06T07:28:48.000Z
/* * Copyright (c) 2017 Darren Smith * * wampcc is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #include "wampcc/wampcc.h" #include "wampcc/utils.h" #include <algorithm> #include <sstream> #include <getopt.h> /* for getopt_long; standard getopt is in unistd.h */ #define LOG(X) \ do { \ auto level = wampcc::logger::eInfo; \ if (logger.wants_level && logger.write && logger.wants_level(level)) { \ std::ostringstream __xx_oss; \ __xx_oss << X; \ logger.write(level, __xx_oss.str(), __FILE__, __LINE__); \ } \ } while (0) const std::string uri_double = "double"; enum class role { invalid = 0, router, callee, caller, publisher, subscriber }; wampcc::wamp_args const final_item {{"final"},{{"final",1}}}; struct user_options { enum class transport { rawsocket, websocket, } session_transport = transport::websocket; int serialisers = wampcc::all_serialisers; wampcc::user_optional<std::string> admin_port; wampcc::user_optional<std::string> port; wampcc::user_optional<int> count; role program_role = role::invalid; std::string realm = "default_realm"; bool debug = false; bool use_websocket = false; bool use_ssl = false; } uopts; wampcc::logger logger; class tester { private: std::unique_ptr<wampcc::kernel> m_kernel; std::shared_ptr<wampcc::wamp_router> m_router; std::shared_ptr<wampcc::wamp_router> m_admin; std::shared_ptr<wampcc::wamp_session> m_callee; std::shared_ptr<wampcc::wamp_session> m_subscriber; std::vector<wampcc::wamp_args> m_subscription_data; public: // control when main thread can exit std::promise<int> can_exit; void create_kernel() { auto loglevel = uopts.debug ? wampcc::logger::eDebug : wampcc::logger::eInfo; logger = wampcc::logger::stream(wampcc::logger::lockable_cout, wampcc::logger::levels_upto(loglevel)); m_kernel.reset(new wampcc::kernel({}, logger)); } void create_router() { m_router.reset(new wampcc::wamp_router(m_kernel.get())); logger.write(wampcc::logger::eInfo, "router listening on " + uopts.port.value(), __FILE__, __LINE__); m_router->listen(wampcc::auth_provider::no_auth_required(), std::atoi(uopts.port.value().c_str())); } std::shared_ptr<wampcc::wamp_session> connect_and_logon() { std::string host = "127.0.0.1"; std::unique_ptr<wampcc::tcp_socket> sock( new wampcc::tcp_socket(m_kernel.get())); auto fut = sock->connect(host, uopts.port.value()); if (fut.wait_for(std::chrono::milliseconds(250)) != std::future_status::ready) throw std::runtime_error("timeout during connect"); if (auto ec = fut.get()) throw std::runtime_error("connect failed: " + std::to_string(ec.os_value()) + ", " + ec.message()); auto on_session_state = [this](wampcc::wamp_session&, bool is_open) { if (!is_open) try { this->can_exit.set_value(0); } catch (...) { /* ignore promise already set error */ } }; std::shared_ptr<wampcc::wamp_session> session; switch (uopts.session_transport) { case user_options::transport::websocket: { wampcc::websocket_protocol::options proto_opts; proto_opts.serialisers = uopts.serialisers; session = wampcc::wamp_session::create<wampcc::websocket_protocol>( m_kernel.get(), std::move(sock), on_session_state, proto_opts); break; } case user_options::transport::rawsocket: { wampcc::rawsocket_protocol::options proto_opts; proto_opts.serialisers = uopts.serialisers; session = wampcc::wamp_session::create<wampcc::rawsocket_protocol>( m_kernel.get(), std::move(sock), on_session_state, proto_opts); break; } } wampcc::client_credentials credentials; credentials.realm = uopts.realm; auto logon_fut = session->hello(credentials); if (logon_fut.wait_for(std::chrono::seconds(5)) != std::future_status::ready) throw std::runtime_error("time-out during wamp session logon"); if (!session->is_open()) throw std::runtime_error("wamp session logon failed"); return session; } void create_callee() { std::shared_ptr<wampcc::wamp_session> session = connect_and_logon(); wampcc::json_object options; std::promise<std::tuple<bool, std::string>> promise; auto on_result = [&](wampcc::wamp_session&, wampcc::registered_info info) { bool is_good = !info.was_error; std::string error_uri = info.error_uri; std::tuple<bool, std::string> result{is_good, error_uri}; promise.set_value(result); }; auto on_invoke = [](wampcc::wamp_session& ws, wampcc::invocation_info invoc) { for (auto& item : invoc.args.args_list) if (item.is_string()) item = item.as_string() + item.as_string(); ws.yield(invoc.request_id, std::move(invoc.args.args_list)); }; session->provide(uri_double, options, std::move(on_result), std::move(on_invoke)); auto fut = promise.get_future(); if (fut.wait_for(std::chrono::seconds(1)) != std::future_status::ready) throw std::runtime_error("timeout during rpc registration"); auto result = fut.get(); if (std::get<0>(result) == false) throw std::runtime_error("rpc registration failed: " + std::get<1>(result)); m_callee = std::move(session); } void create_caller() { if (!uopts.count) throw std::runtime_error("missing count"); std::shared_ptr<wampcc::wamp_session> session = connect_and_logon(); for (int i = 0; i < uopts.count.value(); i++) { std::promise<wampcc::result_info> promised_result; wampcc::wamp_args call_args; call_args.args_list = {"hello", "world", std::to_string(i)}; session->call(uri_double, {}, call_args, [&](wampcc::wamp_session&, wampcc::result_info r) { try { promised_result.set_value(r); } catch (...) { /* ignore promise already set error */ } }); auto fut = promised_result.get_future(); if (fut.wait_for(std::chrono::seconds(1)) != std::future_status::ready) throw std::runtime_error("timeout during call"); auto result = fut.get(); if (result.was_error) throw std::runtime_error("call error: " + result.error_uri); // expected value for (auto& item : call_args.args_list) if (item.is_string()) item = item.as_string() + item.as_string(); if (call_args != result.args) throw std::runtime_error("rpc result did not match expected"); } LOG("rpc result successful, closing session"); if (session->close().wait_for(std::chrono::seconds(1)) != std::future_status::ready) throw std::runtime_error("timeout during session close"); } void create_admin_port() { m_admin.reset(new wampcc::wamp_router(m_kernel.get())); logger.write(wampcc::logger::eInfo, "admin listening on " + uopts.admin_port.value(), __FILE__, __LINE__); std::future<wampcc::uverr> futerr = m_admin->listen(wampcc::auth_provider::no_auth_required(), std::atoi(uopts.admin_port.value().c_str())); if (futerr.wait_for(std::chrono::milliseconds(250)) != std::future_status::ready) throw std::runtime_error("timeout during listen(admin)"); if (auto ec = futerr.get()) throw std::runtime_error("listen failed: " + std::to_string(ec.os_value()) + ", " + ec.message()); m_admin->callable("default_realm", "stop", [this](wampcc::wamp_router&, wampcc::wamp_session&, wampcc::call_info) { this->can_exit.set_value(0); }); } std::vector<wampcc::wamp_args> data_set() const { std::vector<wampcc::wamp_args> retval; retval.reserve(uopts.count.value()+1); for (int i = 0; i < uopts.count.value(); i++) { wampcc::wamp_args args; args.args_list.push_back(wampcc::json_value::make_uint(i)); retval.push_back(std::move(args)); } retval.push_back(final_item); return retval; } void create_publisher() { if (!uopts.count) throw std::runtime_error("missing count"); { std::shared_ptr<wampcc::wamp_session> session = connect_and_logon(); std::string uri_numbers_topic = "numbers"; auto data_to_send = data_set(); for (auto& item : data_to_send) session->publish(uri_numbers_topic, {}, std::move(item)); } can_exit.set_value(0); } void create_subscriber() { if (!uopts.count) throw std::runtime_error("missing count"); auto data_execpt = data_set(); decltype(data_execpt) data_actual; std::shared_ptr<wampcc::wamp_session> session = connect_and_logon(); std::promise<wampcc::subscribed_info> promised_result; auto on_subscribed = [&](wampcc::wamp_session&, wampcc::subscribed_info r) { promised_result.set_value(std::move(r)); }; auto on_event = [this](wampcc::wamp_session&, wampcc::event_info info) { LOG("subscription event: " << info.args.args_list); bool is_final = info.args == final_item; m_subscription_data.push_back(std::move(info.args)); if (is_final) { auto expect = data_set(); if (m_subscription_data == expect) { LOG("received expected data set"); can_exit.set_value(0); } else { LOG("received unexpected data set"); can_exit.set_value(1); } } }; std::string uri_numbers_topic = "numbers"; wampcc::json_object options; wampcc::wamp_args args; session->subscribe(uri_numbers_topic, options, on_subscribed, on_event); auto fut = promised_result.get_future(); if (fut.wait_for(std::chrono::seconds(1)) != std::future_status::ready) throw std::runtime_error("timeout during subscribe"); auto subscribed_result = fut.get(); if (subscribed_result.was_error) throw std::runtime_error("subscribe error: " + subscribed_result.error_uri); m_subscriber = std::move(session); } }; void parse_proto(const char* src) { for (auto str : wampcc::tokenize(src, ',', false)) { if (str == "web") uopts.session_transport = user_options::transport::websocket; else if (str == "raw") uopts.session_transport = user_options::transport::rawsocket; else if (str == "ssl") uopts.use_ssl = true; else if (str == "json") uopts.serialisers = static_cast<int>(wampcc::serialiser_type::json); else if (str == "msgpack") uopts.serialisers = static_cast<int>(wampcc::serialiser_type::msgpack); else throw std::runtime_error("unknown proto flag"); } } #define HELPLN(X, S, T) std::cout << " " << X << S << T << std::endl void usage() { const char* sp1 = "\t"; const char* sp2 = "\t\t"; std::cout << "usage: wampcc_tester [OPTIONS]" << std::endl; std::cout << "Options:" << std::endl; HELPLN("--router", sp2, "router role"); HELPLN("--caller", sp2, "caller role"); HELPLN("--callee", sp2, "callee role"); HELPLN("--subscriber", sp2, "subscriber role"); HELPLN("--publisher", sp2, "publisher role"); HELPLN("-a, --admin_port=ARG", sp1, "specify admin port"); HELPLN("-p, --port", sp2, "wamp connection port"); HELPLN("-d, --debug", sp2, "increased logging"); HELPLN("-c, --count=N", sp2, "number of messages to-send / expect-receive"); HELPLN("--proto PROTO_OPTS", sp1, "comma separated list of options, default 'web,json'"); std::cout << std::endl << "Protocol options:" << std::endl << " web - select websocket protocol" << std::endl << " raw - select rawsocket protocol" << std::endl << " json - support only json serialiser" << std::endl << " msgpack - support only msgpack serialiser" << std::endl; exit(0); } static void process_options(int argc, char** argv) { /* struct option { const char *name; int has_arg; int *flag; int val; }; */ // these enums are used for options that don't have a short version enum { OPT_NO_URI_CHECK = 1, OPT_ARGLIST, OPT_ARGDICT, OPT_TIMEOUT, OPT_PROTO, OPT_ROUTER, OPT_CALLEE, OPT_CALLER, OPT_PUBLISHER, OPT_SUBSCRIBER }; // int digit_optind = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"router", no_argument, 0, OPT_ROUTER}, {"callee", no_argument, 0, OPT_CALLEE}, {"caller", no_argument, 0, OPT_CALLER}, {"publisher", no_argument, 0, OPT_PUBLISHER}, {"subscriber", no_argument, 0, OPT_SUBSCRIBER}, {"proto", required_argument, 0, OPT_PROTO}, {"admin_port", required_argument, 0, 'a'}, {"port", required_argument, 0, 'p'}, {"debug", no_argument, 0, 'd'}, {"count", required_argument, 0, 'c'}, {NULL, 0, NULL, 0}}; const char* optstr = "hp:a:dc:"; // short opt string ::opterr = 1; while (true) { /* "optind" is the index of the next element to be processed in argv. It is defined in the getopts header, and the system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector. */ // take a copy to remember value for after return from getopt_long() // int this_option_optind = ::optind ? ::optind : 1; int long_index = 0; int c = getopt_long(argc, argv, optstr, long_options, &long_index); if (c == -1) break; switch (c) { case OPT_PROTO: parse_proto(optarg); break; case OPT_ROUTER: uopts.program_role = role::router; break; case OPT_CALLER: uopts.program_role = role::caller; break; case OPT_PUBLISHER: uopts.program_role = role::publisher; break; case OPT_SUBSCRIBER: uopts.program_role = role::subscriber; break; case OPT_CALLEE: uopts.program_role = role::callee; break; case 'a': uopts.admin_port = optarg; break; case 'p': uopts.port = optarg; break; case 'd': uopts.debug = true; break; case 'h': usage(); break; case 'c': uopts.count = std::atoi(optarg); break; case '?': exit(1); // invalid option default: { std::cout << "unknown option: -" << char(c) << "\n"; exit(1); } } } // while if (uopts.program_role == role::invalid) throw std::runtime_error("missing role"); if (!uopts.port) throw std::runtime_error("missing port"); } int main_impl(int argc, char** argv) { process_options(argc, argv); tester impl; impl.create_kernel(); if (uopts.admin_port) impl.create_admin_port(); switch (uopts.program_role) { case role::invalid: throw std::runtime_error("role not specified"); break; case role::router: impl.create_router(); break; case role::callee: impl.create_callee(); break; case role::caller: impl.create_caller(); break; case role::publisher: impl.create_publisher(); break; case role::subscriber: impl.create_subscriber(); break; } /* Suspend main thread */ int result = impl.can_exit.get_future().get(); return result; } int main(int argc, char** argv) { try { return main_impl(argc, argv); } catch (std::exception& e) { std::cout << "error, " << e.what() << std::endl; return 1; } }
30.252768
98
0.598707
vai-hhn
7dc9018939e96b62f6b2f0ff121a5a036f7089ce
1,375
hpp
C++
include/euclidean2/object/water.hpp
Euclidean-Entertainment/Assignment_2
04a855f3cec41c9046340b3248d32e5acb94c221
[ "BSD-3-Clause" ]
1
2018-05-03T03:57:29.000Z
2018-05-03T03:57:29.000Z
include/euclidean2/object/water.hpp
Euclidean-Entertainment/Assignment_2
04a855f3cec41c9046340b3248d32e5acb94c221
[ "BSD-3-Clause" ]
1
2018-05-04T14:17:53.000Z
2018-05-04T14:17:53.000Z
include/euclidean2/object/water.hpp
Euclidean-Entertainment/Assignment_2
04a855f3cec41c9046340b3248d32e5acb94c221
[ "BSD-3-Clause" ]
2
2018-05-03T03:57:32.000Z
2018-05-20T12:01:55.000Z
/** * */ #ifndef _WATER_HPP_INCLUDED_ #define _WATER_HPP_INCLUDED_ #include "euclidean2/vertex.hpp" #include "euclidean2/system/material.hpp" #include "euclidean2/system/texture.hpp" #include <climits> #include <vector> static constexpr int MIN_TESSELATIONS = 16; static constexpr int MAX_TESSELATIONS = 512; struct water_t { int tesselations = MIN_TESSELATIONS; vertex3f_t verts[MAX_TESSELATIONS][MAX_TESSELATIONS]; material_t mat; }; struct ground_t { vertex3f_t verts[128][128]; // We don't need too many tesselations for the seafloor texture_t tex; material_t mat; }; /** * Generate our water using triangle strips */ void water_generate(water_t& water); /** * Actually draw the quad strip */ void water_draw(water_t& water, bool drawNorms); /** * Animate our water */ void water_animate(water_t& water, float t, int numWaves); /** * Draw the seafloor */ void water_drawGround(ground_t& ground); /** * */ static inline void water_increaseTesselations(water_t& water) { if(water.tesselations < MAX_TESSELATIONS) { water.tesselations *= 2; water_generate(water); } } /** * */ static inline void water_decreaseTesselations(water_t& water) { if(water.tesselations > MIN_TESSELATIONS) { water.tesselations /= 2; water_generate(water); } } #endif
17.628205
88
0.688727
Euclidean-Entertainment
7dca48bbb88ede97a25fd4a70ba9b8ec9b17992b
1,284
cpp
C++
GeeksForGeeks/C Plus Plus/K_largest_elements.cpp
ankit-sr/Competitive-Programming
3397b313b80a32a47cfe224426a6e9c7cf05dec2
[ "MIT" ]
4
2021-06-19T14:15:34.000Z
2021-06-21T13:53:53.000Z
GeeksForGeeks/C Plus Plus/K_largest_elements.cpp
ankit-sr/Competitive-Programming
3397b313b80a32a47cfe224426a6e9c7cf05dec2
[ "MIT" ]
2
2021-07-02T12:41:06.000Z
2021-07-12T09:37:50.000Z
GeeksForGeeks/C Plus Plus/K_largest_elements.cpp
ankit-sr/Competitive-Programming
3397b313b80a32a47cfe224426a6e9c7cf05dec2
[ "MIT" ]
3
2021-06-19T15:19:20.000Z
2021-07-02T17:24:51.000Z
/* Problem Statement: ----------------- Given an array Arr of N positive integers, find K largest elements from the array. The output elements should be printed in decreasing order. Example 1: --------- Input: N = 5, K = 2 Arr[] = {12, 5, 787, 1, 23} Output: 787 23 Explanation: 1st largest element in the array is 787 and second largest is 23. Example 2: --------- Input: N = 7, K = 3 Arr[] = {1, 23, 12, 9, 30, 2, 50} Output: 50 30 23 Explanation: 3 Largest element in the array are 50, 30 and 23. Your Task: You don't need to read input or print anything. Your task is to complete the function kLargest() which takes the array of integers arr, n and k as parameters and returns an array of integers denoting the answer. The array should be in decreasing order. Expected Time Complexity: O(N) Expected Auxiliary Space: O(K*logK) */ // Link --> https://practice.geeksforgeeks.org/problems/k-largest-elements4206/1# // Code: class Solution{ public: vector <int> kLargest(int a[], int n, int k) { vector <int> answer; priority_queue <int> maxHeap; for(int i=0 ; i<n ; i++) maxHeap.push(a[i]); for(int i=0 ; i<k ; i++) { answer.push_back(maxHeap.top()); maxHeap.pop(); } return answer; } };
24.226415
148
0.639408
ankit-sr
7dcacce0b81670de55e2e6819af4998a256efbb5
5,646
cc
C++
typecd/usb_monitor.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
typecd/usb_monitor.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
typecd/usb_monitor.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2022 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "typecd/usb_monitor.h" #include <utility> #include <base/files/file_util.h> #include <base/logging.h> #include "base/strings/string_number_conversions.h" #include <base/strings/string_util.h> #include <re2/re2.h> namespace { constexpr char kInterfaceFilePathRegex[] = R"((\d+)-(\d+)(\.(\d+))*:(\d+)\.(\d+))"; constexpr char kTypecPortUeventRegex[] = R"(TYPEC_PORT=port(\d+))"; typecd::UsbSpeed ConvertToUsbSpeed(std::string speed) { if (speed == "1.5") return typecd::UsbSpeed::k1_5; else if (speed == "12") return typecd::UsbSpeed::k12; else if (speed == "480") return typecd::UsbSpeed::k480; else if (speed == "5000") return typecd::UsbSpeed::k5000; else if (speed == "10000") return typecd::UsbSpeed::k10000; else if (speed == "20000") return typecd::UsbSpeed::k20000; else return typecd::UsbSpeed::kOther; } typecd::UsbDeviceClass ConvertToUsbClass(std::string device_class) { if (device_class == "00") return typecd::UsbDeviceClass::kNone; else if (device_class == "09") return typecd::UsbDeviceClass::kHub; else return typecd::UsbDeviceClass::kOther; } // Convert version string parsed from USB device sysfs to UsbVersion enum to // store in UsbDevice. typecd::UsbVersion ConvertToUsbVersion(std::string version) { if (version == "1.00") return typecd::UsbVersion::k1_0; else if (version == "1.10") return typecd::UsbVersion::k1_1; else if (version == "2.00") return typecd::UsbVersion::k2_0; else if (version == "2.10") return typecd::UsbVersion::k2_1; else if (version == "3.00") return typecd::UsbVersion::k3_0; else if (version == "3.10") return typecd::UsbVersion::k3_1; else if (version == "3.20") return typecd::UsbVersion::k3_2; else return typecd::UsbVersion::kOther; } } // namespace namespace typecd { UsbMonitor::UsbMonitor() : metrics_(nullptr) {} void UsbMonitor::OnDeviceAddedOrRemoved(const base::FilePath& path, bool added) { auto key = path.BaseName().value(); if (RE2::FullMatch(key, kInterfaceFilePathRegex)) { return; } auto it = devices_.find(key); if (added) { if (it != devices_.end()) { LOG(WARNING) << "Attempting to add an already added usb device in " << path; return; } std::string busnum; std::string devnum; if (!base::ReadFileToString(path.Append("busnum"), &busnum)) { PLOG(ERROR) << "Failed to find busnum in " << path; return; } if (!base::ReadFileToString(path.Append("devnum"), &devnum)) { PLOG(ERROR) << "Failed to find devnum in " << path; return; } base::TrimWhitespaceASCII(busnum, base::TRIM_TRAILING, &busnum); base::TrimWhitespaceASCII(devnum, base::TRIM_TRAILING, &devnum); int busnum_int; int devnum_int; if (!base::StringToInt(busnum, &busnum_int) || !base::StringToInt(devnum, &devnum_int)) { PLOG(ERROR) << "Failed to parse integer value from busnum and devnum in " << path; return; } devices_.emplace(key, std::make_unique<UsbDevice>(busnum_int, devnum_int, key)); std::string typec_port_uevent; int typec_port_num; if (base::ReadFileToString(path.Append("port/connector/uevent"), &typec_port_uevent) && RE2::PartialMatch(typec_port_uevent, kTypecPortUeventRegex, &typec_port_num)) { GetDevice(key)->SetTypecPortNum(typec_port_num); } else { // Parent USB hub device's sysfs directory name. // e.g. Parent sysfs of 2-1.5.4 would be 2-1 auto parent_key = key.substr(0, key.find(".")); // If parent USB hub device is present and has a Type C port associated, // use the parent's Type C port number. if (GetDevice(parent_key) != nullptr) GetDevice(key)->SetTypecPortNum( GetDevice(parent_key)->GetTypecPortNum()); } std::string speed; if (base::ReadFileToString(path.Append("speed"), &speed)) { base::TrimWhitespaceASCII(speed, base::TRIM_TRAILING, &speed); GetDevice(key)->SetSpeed(ConvertToUsbSpeed(speed)); } std::string device_class; if (base::ReadFileToString(path.Append("bDeviceClass"), &device_class)) { base::TrimWhitespaceASCII(device_class, base::TRIM_TRAILING, &device_class); GetDevice(key)->SetDeviceClass(ConvertToUsbClass(device_class)); } std::string version; if (base::ReadFileToString(path.Append("version"), &version)) { base::TrimWhitespaceASCII(version, base::TRIM_ALL, &version); GetDevice(key)->SetVersion(ConvertToUsbVersion(version)); } ReportMetrics(path, key); } else { if (it == devices_.end()) { LOG(WARNING) << "Attempting to remove a non-existent usb device in " << path; return; } devices_.erase(key); } } UsbDevice* UsbMonitor::GetDevice(std::string key) { auto it = devices_.find(key); if (it == devices_.end()) return nullptr; return it->second.get(); } void UsbMonitor::ReportMetrics(const base::FilePath& path, std::string key) { if (!metrics_) return; UsbDevice* device = GetDevice(key); if (!device) { LOG(WARNING) << "Metrics reporting attempted for non-existent usb device in " << path; return; } device->ReportMetrics(metrics_); } } // namespace typecd
30.192513
79
0.638328
ascii33
7dd03b654fc86cb8bea767f9fe15e55ea5ead232
9,163
hxx
C++
main/extensions/source/bibliography/datman.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/extensions/source/bibliography/datman.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/extensions/source/bibliography/datman.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _BIB_DATMAN_HXX #define _BIB_DATMAN_HXX #include <com/sun/star/awt/XControlModel.hpp> #include <com/sun/star/form/XForm.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp> #include <com/sun/star/form/runtime/XFormController.hpp> #include <cppuhelper/compbase2.hxx> #include <cppuhelper/interfacecontainer.h> #include <com/sun/star/form/XLoadable.hpp> #include <comphelper/broadcasthelper.hxx> // #100312# -------------------- #include <com/sun/star/frame/XDispatchProviderInterceptor.hpp> #include <com/sun/star/frame/XDispatchProviderInterception.hpp> #include <cppuhelper/implbase1.hxx> class Window; //----------------------------------------------------------------------------- namespace bib { class BibView; // #100312# ----------- class BibBeamer; } class BibToolBar; struct BibDBDescriptor; // #100312# --------------------- class BibInterceptorHelper :public cppu::WeakImplHelper1< ::com::sun::star::frame::XDispatchProviderInterceptor > { private: ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xMasterDispatchProvider; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > xSlaveDispatchProvider; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xFormDispatch; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterception > xInterception; protected: ~BibInterceptorHelper( ); public: BibInterceptorHelper( ::bib::BibBeamer* pBibBeamer, ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch); void ReleaseInterceptor(); // XDispatchProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& aDescripts ) throw (::com::sun::star::uno::RuntimeException); // XDispatchProviderInterceptor virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewSlaveDispatchProvider ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& xNewMasterDispatchProvider ) throw (::com::sun::star::uno::RuntimeException); }; typedef cppu::WeakComponentImplHelper2 < ::com::sun::star::beans::XPropertyChangeListener , ::com::sun::star::form::XLoadable > BibDataManager_Base; class BibDataManager :public ::comphelper::OMutexAndBroadcastHelper ,public BibDataManager_Base { private: ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > m_xForm; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > m_xGridModel; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > m_xSourceProps; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer > m_xParser; ::com::sun::star::uno::Reference< ::com::sun::star::form::runtime::XFormController > m_xFormCtrl; // #100312# ------------------- ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > m_xFormDispatch; BibInterceptorHelper* m_pInterceptorHelper; ::rtl::OUString aActiveDataTable; ::rtl::OUString aDataSourceURL; ::rtl::OUString aQuoteChar; ::com::sun::star::uno::Any aUID; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > xBibCursor; ::cppu::OInterfaceContainerHelper m_aLoadListeners; ::bib::BibView* pBibView; BibToolBar* pToolbar; rtl::OUString sIdentifierMapping; protected: void InsertFields(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormComponent > & xGrid); void SetMeAsUidListener(); void RemoveMeAsUidListener(); void UpdateAddressbookCursor(::rtl::OUString aSourceName); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > updateGridModel(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > & xDbForm); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > createGridModel( const ::rtl::OUString& rName ); // XLoadable virtual void SAL_CALL load( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL unload( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL reload( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isLoaded( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeLoadListener( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XLoadListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL disposing(); public: BibDataManager(); ~BibDataManager(); virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException ); ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm > createDatabaseForm( BibDBDescriptor& aDesc); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > updateGridModel(); ::com::sun::star::uno::Sequence< ::rtl::OUString> getDataSources(); ::rtl::OUString getActiveDataSource() {return aDataSourceURL;} void setActiveDataSource(const ::rtl::OUString& rURL); ::rtl::OUString getActiveDataTable(); void setActiveDataTable(const ::rtl::OUString& rTable); void setFilter(const ::rtl::OUString& rQuery); ::rtl::OUString getFilter(); ::com::sun::star::uno::Sequence< ::rtl::OUString> getQueryFields(); ::rtl::OUString getQueryField(); void startQueryWith(const ::rtl::OUString& rQuery); const ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >& getParser() { return m_xParser; } const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& getForm() { return m_xForm; } ::rtl::OUString getControlName(sal_Int32 nFormatKey ); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > loadControlModel(const ::rtl::OUString& rName, sal_Bool bForceListBox = sal_False); void CreateMappingDialog(Window* pParent); ::rtl::OUString CreateDBChangeDialog(Window* pParent); void DispatchDBChangeDialog(); sal_Bool HasActiveConnection() const; void SetView( ::bib::BibView* pView ) { pBibView = pView; } void SetToolbar(BibToolBar* pSet); const rtl::OUString& GetIdentifierMapping(); void ResetIdentifierMapping() {sIdentifierMapping = rtl::OUString();} ::com::sun::star::uno::Reference< ::com::sun::star::form::runtime::XFormController > GetFormController(); // #100312# ---------- void RegisterInterceptor( ::bib::BibBeamer* pBibBeamer); sal_Bool HasActiveConnection(); }; #endif
46.75
291
0.666267
Grosskopf
7dd0ff3c07426231bb6aeb7e8dde943472e08431
2,549
cpp
C++
Engine/GameObject.cpp
rakocevicjovan/PCG_and_graphics
02c81d5b814f468f1397c6377438cb4a8810e0ac
[ "MIT" ]
null
null
null
Engine/GameObject.cpp
rakocevicjovan/PCG_and_graphics
02c81d5b814f468f1397c6377438cb4a8810e0ac
[ "MIT" ]
3
2021-05-09T20:19:23.000Z
2021-08-10T19:00:19.000Z
Engine/GameObject.cpp
rakocevicjovan/PCG_and_graphics
02c81d5b814f468f1397c6377438cb4a8810e0ac
[ "MIT" ]
null
null
null
#include "pch.h" #include "GameObject.h" #include "Renderer.h" Actor::Actor(Model* model, SMatrix& transform) : _steerComp(this), _transform(transform), _collider(Collider(BoundingVolumeType::BVT_SPHERE, this, true)) { _renderables.reserve(model->_meshes.size()); for (MeshNode& meshNode : model->_meshNodeTree) { // Work this out for (auto& meshInMeshNode : meshNode.meshes) { _renderables.emplace_back(model->_meshes[meshInMeshNode], meshNode.transform); } //_renderables.back()._localTransform = mesh._parentSpaceTransform; //_renderables.back()._transform = transform * mesh._parentSpaceTransform; //_renderables.back().mat = mesh._material.get(); _collider.addHull(new SphereHull(_renderables.back()._transform.Translation(), 1.f * transform._11)); //@TODO see what to do about this } } Actor::Actor(const Actor& other) : _steerComp(other._steerComp), _collider(Collider(other._collider.BVT, this, other._collider.dynamic)) { _transform = other._transform; for (Hull* sp : other._collider.getHulls()) _collider.addHull(new SphereHull(sp->getPosition(), sp->getExtent())); _renderables.reserve(other._renderables.size()); for (const Renderable& r : other._renderables) _renderables.push_back(r); } void Actor::patchMaterial(VertexShader* vs, PixelShader* ps) { for (Renderable& r : _renderables) { r.mat->setVS(vs); r.mat->setPS(ps); } } void Actor::propagate() { for (Renderable& r : _renderables) { r._transform = _transform * r._localTransform; } //@TODO consider changing to per-mesh collider... could be cleaner tbh _collider.updateHullPositions(); } void Actor::render(const Renderer& renderer) const { for (const Renderable& r : _renderables) renderer.render(r); } void Actor::addToRenderQueue(Renderer& renderer, const SVec3& camPos, const SVec3& viewForward) { for (Renderable& r : _renderables) { r.zDepth = (_transform.Translation() - camPos).Dot(viewForward); renderer.addToRenderQueue(r); } } void Actor::addRenderable(const Renderable& renderable, float r) { _renderables.push_back(renderable); _collider.addHull(new SphereHull(renderable._localTransform.Translation(), r)); } /* void Actor::copyShenanigans(const Actor& other) { _collider = other._collider; _collider.clearHullsNoDelete(); for (Hull* sp : other._collider.getHulls()) _collider.addHull(new SphereHull(sp->getPosition(), sp->getExtent())); renderables.reserve(other.renderables.size()); for (const Renderable& r : other.renderables) renderables.push_back(r); } */
23.601852
138
0.731267
rakocevicjovan
7dd1a7c1f1f9a42be384305132f18161f709a168
2,952
cpp
C++
Projects/Overloading/pr6-28.cpp
ToyVo/CSIIStout
c9b0f2adfa9eb60f078413c2a17f30b44d85059f
[ "MIT" ]
null
null
null
Projects/Overloading/pr6-28.cpp
ToyVo/CSIIStout
c9b0f2adfa9eb60f078413c2a17f30b44d85059f
[ "MIT" ]
null
null
null
Projects/Overloading/pr6-28.cpp
ToyVo/CSIIStout
c9b0f2adfa9eb60f078413c2a17f30b44d85059f
[ "MIT" ]
null
null
null
// This program demonstrates overloaded functions to calculate // the gross weekly pay of hourly-wage or salaried employees. #include <iostream> #include <iomanip> using namespace std; // Function prototypes char getChoice(); double calcWeeklyPay(int, double); double calcWeeklyPay(double); int main() { char selection; // Menu selection int worked; // Weekly hours worked double rate, // Hourly pay rate yearly; // Annual salary // Set numeric output formatting cout << fixed << showpoint << setprecision(2); // Display the menu and get a selection cout << "Do you want to calculate the weekly pay of\n"; cout << "(H) an hourly-wage employee, or \n"; cout << "(S) a salaried employee? "; selection = getChoice(); // Process the menu selection switch (selection) { // Hourly employee case 'H' : case 'h' : cout << "How many hours were worked? "; cin >> worked; cout << "What is the hourly pay rate? "; cin >> rate; cout << "The gross weekly pay is $"; cout << calcWeeklyPay(worked, rate) << endl; break; // Salaried employee case 'S' : case 's' : cout << "What is the annual salary? "; cin >> yearly; cout << "The gross weekly pay is $"; cout << calcWeeklyPay(yearly) << endl; } system("pause"); return 0; } /***************************************************** * getChoice * * Accepts and returns user's validated menu choice. * *****************************************************/ char getChoice() { char letter; // Holds user's letter choice // Get the user's choice cin >> letter; // Validate the choice while (letter != 'H' && letter != 'h' && letter != 'S' && letter != 's') { cout << "Enter H or S: "; cin >> letter; } // Return the choice return letter; } /************************************************************* * overloaded function calcWeeklyPay * * This function calculates and returns the gross weekly pay * * of an hourly-wage employee. Parameters hours and payRate * * hold the number of hours worked and the hourly pay rate. * *************************************************************/ double calcWeeklyPay(int hours, double payRate) { return hours * payRate; } /************************************************************* * overloaded function calcWeeklyPay * * This function calculates and returns the gross weekly pay * * of a salaried employee. The parameter annSalary holds the * * employee's annual salary. * *************************************************************/ double calcWeeklyPay(double annSalary) { return annSalary / 52.0; }
31.404255
63
0.505759
ToyVo
7dd74ce39de9bd43e27097a0fb3026a5959e01d7
2,768
hpp
C++
display/GUI.hpp
mbellier/FluidSolver
c75c95f1725a362703d500c0dd3443df7d710bc3
[ "Apache-2.0" ]
18
2015-01-08T00:48:40.000Z
2022-01-12T15:04:04.000Z
display/GUI.hpp
mbellier/FluidSolver
c75c95f1725a362703d500c0dd3443df7d710bc3
[ "Apache-2.0" ]
null
null
null
display/GUI.hpp
mbellier/FluidSolver
c75c95f1725a362703d500c0dd3443df7d710bc3
[ "Apache-2.0" ]
3
2015-11-20T02:35:16.000Z
2018-03-25T20:14:55.000Z
#ifndef GUI_H #define GUI_H #include <QtOpenGL> #include <QGLWidget> #include <QString> #include <QList> #include "Print.hpp" #include "Dialog.hpp" #include "../config.hpp" #include "../solver/FluidSolver2D.hpp" #include "../solver/FloatMatrix2D.hpp" #include "LeapMotion.h" /** * Class herited from myGLWidget corresponding * to the window where the fluid is displayed. */ class GUI : public QGLWidget { Q_OBJECT//Maccro used to define new SLOTS public: GUI(QWidget *parent, \ QString name, \ Print *p, \ Config &configurationDatas, bool drawVelocityField,\ bool enableMouseMove); ~GUI(); void initializeGL(); void resizeGL(int width, int height); void paintGL(); void keyPressEvent(QKeyEvent *keyEvent); void mousePressEvent(QMouseEvent *mouseEvent); void mouseReleaseEvent(QMouseEvent *mouseEvent); void mouseMoveEvent(QMouseEvent *mouseEvent); void wheelEvent(QWheelEvent *mouseEvent); void toggleFullWindow(); void calculateFPS(); void fillSquare(unsigned int sqrWidth, unsigned int sqrHeight, float value, FloatMatrix2D* matrix, bool prev = false); void addObstacle(float sqrWidth, float sqrHeight); void resizeMatrix(FloatMatrix2D &out, const FloatMatrix2D &in, int k); void addPrintMode(Print *p); FluidSolver *fluid; public slots: virtual void timeOutSlot(); void saveConfig(); void loadConfig(); void desPause(){_pause = false;}; private: QTimer *t_Timer; // used to refresh the window. bool _pause; // pause the simulation bool b_Fullscreen; // window fullscreen state bool _drawVelocityField; // toggle velocity field drawings float coef; // 'radius' of the cursor int mouseX; // horizontal position of the mouse int mouseY; // hertical position of the mouse int prevMouseX; // previous event horizontal position of the mouse int prevMouseY; // previous event vertical position of the mouse bool pressing; // is mouse left button pressed ? bool emptying; // is mouse right button pressed ? bool _enableMouseMove; // toggle mouse velocity modifications Config &configuration; bool waitingMousePress; // waiting for button pressed? int firstPosX; int firstPosY; Dialog *saveWin; Dialog *loadWin; // LeapMotion Leap::Controller leap; QList <Leap::Vector> fingers; // information displayed in the title float fps; unsigned int dispMouseX, dispMouseY; float dispDens, dispVelX, dispVelY; // Print modes QList <Print *> _printModes; unsigned int _currentPrintMode; // Average matrices FloatMatrix2D *M1; FloatMatrix2D *M2; // Reduction factor static const int k = 5; }; #endif // GUI_H
26.873786
120
0.696171
mbellier
7dd832787c050136d22b59a79eb1f95ac3791afa
618
cpp
C++
potd/potd-q25/Queue.cpp
taoyuc3/CS225
e3a8add28059c63a663ad512885ddf8df86eebd9
[ "MIT" ]
null
null
null
potd/potd-q25/Queue.cpp
taoyuc3/CS225
e3a8add28059c63a663ad512885ddf8df86eebd9
[ "MIT" ]
null
null
null
potd/potd-q25/Queue.cpp
taoyuc3/CS225
e3a8add28059c63a663ad512885ddf8df86eebd9
[ "MIT" ]
null
null
null
#include "Queue.h" // `int size()` - returns the number of elements in the stack (0 if empty) int Queue::size() const { return mySize; } // `bool isEmpty()` - returns if the list has no elements, else false bool Queue::isEmpty() const { return mySize==0 ? true : false; } // `void enqueue(int val)` - enqueue an item to the queue in O(1) time void Queue::enqueue(int value) { myQueue.push_back(value); ++mySize; } // `int dequeue()` - removes an item off the queue and returns the value in O(1) time int Queue::dequeue() { int ans = myQueue.front(); myQueue.pop_back(); --mySize; return ans; }
20.6
85
0.658576
taoyuc3
7dd86d15ec8e46a1f3049c99b0c013ece0720fb3
8,595
cpp
C++
TI_Sound/SoundManager.cpp
edhaker13/team-indecisive
290d5f8d905fbf7524bfd685336044477b316fbe
[ "CC-BY-3.0" ]
null
null
null
TI_Sound/SoundManager.cpp
edhaker13/team-indecisive
290d5f8d905fbf7524bfd685336044477b316fbe
[ "CC-BY-3.0" ]
null
null
null
TI_Sound/SoundManager.cpp
edhaker13/team-indecisive
290d5f8d905fbf7524bfd685336044477b316fbe
[ "CC-BY-3.0" ]
null
null
null
#include "SoundManager.h" namespace Indecisive { static const std::string _PATH = ".\\/Assets\\/"; bool SoundManager::Initialize(HWND hwnd) { // TODO: Too many lines, just return method bool result; // Initialize direct sound and the primary sound buffer. result = InitializeDirectSound(hwnd); if (!result) { return false; } return true; } bool SoundManager::InitializeDirectSound(HWND hwnd) { HRESULT result; DSBUFFERDESC bufferDesc; WAVEFORMATEX waveFormat; // Initialize the direct sound interface pointer for the default sound device. result = DirectSoundCreate8(NULL, &m_DirectSound, NULL); if (FAILED(result)) { return false; } // Set the cooperative level to priority so the format of the primary sound buffer can be modified. result = m_DirectSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY); if (FAILED(result)) { return false; } // Setup the primary buffer description. bufferDesc.dwSize = sizeof(DSBUFFERDESC); bufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME; bufferDesc.dwBufferBytes = 0; bufferDesc.dwReserved = 0; bufferDesc.lpwfxFormat = NULL; bufferDesc.guid3DAlgorithm = GUID_NULL; // Get control of the primary sound buffer on the default sound device. result = m_DirectSound->CreateSoundBuffer(&bufferDesc, &m_primaryBuffer, NULL); if (FAILED(result)) { return false; } // Setup the format of the primary sound bufffer. // In this case it is a .WAV file recorded at 44,100 samples per second in 16-bit stereo (cd audio format). // TODO: Read format?? waveFormat.wFormatTag = WAVE_FORMAT_PCM; waveFormat.nSamplesPerSec = 44100; waveFormat.wBitsPerSample = 16; waveFormat.nChannels = 2; waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels; waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; waveFormat.cbSize = 0; // Set the primary buffer to be the wave format specified. result = m_primaryBuffer->SetFormat(&waveFormat); if (FAILED(result)) { return false; } return true; } bool SoundManager::CanRead(const std::string& filename) const { assert(!filename.empty()); std::string::size_type pos = filename.find_last_of('.'); // No file extension - can't read if (pos == std::string::npos) return false; std::string ext = filename.substr(pos + 1); return ext.compare("wav") == 0; } bool SoundManager::Load(const std::string& filename) { int error; FILE* filePtr = nullptr; unsigned int count; WaveHeaderType waveFileHeader; WAVEFORMATEX waveFormat; DSBUFFERDESC bufferDesc; HRESULT result; IDirectSoundBuffer* tempBuffer = nullptr; IDirectSoundBuffer8* secondaryBuffer = nullptr; unsigned char* waveData; unsigned char *bufferPtr; unsigned long bufferSize; // Open the wave file in binary. error = fopen_s(&filePtr, (_PATH + filename).c_str(), "rb"); if (error != 0) { return false; } // Read in the wave file header. count = fread(&waveFileHeader, sizeof(waveFileHeader), 1, filePtr); if (count != 1) { return false; } // Check that the chunk ID is the RIFF format. if ((waveFileHeader.chunkId[0] != 'R') || (waveFileHeader.chunkId[1] != 'I') || (waveFileHeader.chunkId[2] != 'F') || (waveFileHeader.chunkId[3] != 'F')) { return false; } // Check that the file format is the WAVE format. if ((waveFileHeader.format[0] != 'W') || (waveFileHeader.format[1] != 'A') || (waveFileHeader.format[2] != 'V') || (waveFileHeader.format[3] != 'E')) { return false; } // Check that the sub chunk ID is the fmt format. if ((waveFileHeader.subChunkId[0] != 'f') || (waveFileHeader.subChunkId[1] != 'm') || (waveFileHeader.subChunkId[2] != 't') || (waveFileHeader.subChunkId[3] != ' ')) { return false; } // Check that the audio format is WAVE_FORMAT_PCM. if (waveFileHeader.audioFormat != WAVE_FORMAT_PCM) { return false; } // Check that the wave file was recorded in stereo format. if (waveFileHeader.numChannels != 2) { return false; } // Check that the wave file was recorded at a sample rate of 44.1 KHz. if (waveFileHeader.sampleRate != 44100) { return false; } // Ensure that the wave file was recorded in 16 bit format. if (waveFileHeader.bitsPerSample != 16) { return false; } // Check for the data chunk header. if ((waveFileHeader.dataChunkId[0] != 'd') || (waveFileHeader.dataChunkId[1] != 'a') || (waveFileHeader.dataChunkId[2] != 't') || (waveFileHeader.dataChunkId[3] != 'a')) { return false; } // Set the wave format of secondary buffer that this wave file will be loaded onto. waveFormat.wFormatTag = WAVE_FORMAT_PCM; waveFormat.nSamplesPerSec = 44100; waveFormat.wBitsPerSample = 16; waveFormat.nChannels = 2; waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels; waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; waveFormat.cbSize = 0; // Set the buffer description of the secondary sound buffer that the wave file will be loaded onto. bufferDesc.dwSize = sizeof(DSBUFFERDESC); bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME; bufferDesc.dwBufferBytes = waveFileHeader.dataSize; bufferDesc.dwReserved = 0; bufferDesc.lpwfxFormat = &waveFormat; bufferDesc.guid3DAlgorithm = GUID_NULL; // Create a temporary sound buffer with the specific buffer settings. result = m_DirectSound->CreateSoundBuffer(&bufferDesc, &tempBuffer, NULL); if (FAILED(result)) { return false; } // Test the buffer format against the direct sound 8 interface and create the secondary buffer. result = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, (void**)&secondaryBuffer); if (FAILED(result)) { return false; } // Release the temporary buffer. tempBuffer->Release(); tempBuffer = 0; // TODO: Read file using std::ifstream // Move to the beginning of the wave data which starts at the end of the data chunk header. fseek(filePtr, sizeof(WaveHeaderType), SEEK_SET); // Create a temporary buffer to hold the wave file data. waveData = new unsigned char[waveFileHeader.dataSize]; if (!waveData) { return false; } // Read in the wave file data into the newly created buffer. count = fread(waveData, 1, waveFileHeader.dataSize, filePtr); if (count != waveFileHeader.dataSize) { return false; } // Close the file once done reading. error = fclose(filePtr); if (error != 0) { return false; } // Lock the secondary buffer to write wave data into it. result = (secondaryBuffer)->Lock(0, waveFileHeader.dataSize, (void**)&bufferPtr, (DWORD*)&bufferSize, NULL, 0, 0); if (FAILED(result)) { return false; } // Copy the wave data into the buffer. memcpy(bufferPtr, waveData, waveFileHeader.dataSize); // Unlock the secondary buffer after the data has been written to it. result = (secondaryBuffer)->Unlock((void*)bufferPtr, bufferSize, NULL, 0); if (FAILED(result)) { return false; } // Release the wave data since it was copied into the secondary buffer. delete[] waveData; waveData = nullptr; // Add buffer to map m_Sounds.emplace(filename, secondaryBuffer); return true; } bool SoundManager::Play(const std::string& filename, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags) { HRESULT result; // TODO: use map.find and handle failure IDirectSoundBuffer8* secondaryBuffer = m_Sounds[filename]; if (secondaryBuffer == nullptr) { return false; } // Set position at the beginning of the sound buffer. result = secondaryBuffer->SetCurrentPosition(0); if (FAILED(result)) { return false; } // Set volume of the buffer to 100%. result = secondaryBuffer->SetVolume(DSBVOLUME_MAX); if (FAILED(result)) { return false; } // Play the contents of the secondary sound buffer. result = secondaryBuffer->Play(dwReserved1, dwPriority, dwFlags); if (FAILED(result)) { return false; } return true; } void SoundManager::Shutdown() { // Release the secondary buffer. for (auto& pair: m_Sounds) { if (pair.second) pair.second->Release(); } // Shutdown the Direct Sound API. ShutdownDirectSound(); return; } void SoundManager::ShutdownDirectSound() { // Release the primary sound buffer pointer. if (m_primaryBuffer) { m_primaryBuffer->Release(); m_primaryBuffer = 0; } // Release the direct sound interface pointer. if (m_DirectSound) { m_DirectSound->Release(); m_DirectSound = 0; } return; } }
26.204268
116
0.696684
edhaker13
7ddaccf6fde9087e21913df4d0594e7c10425772
10,466
cpp
C++
tests/instructions.cpp
voivoid/SynacorChallenge
8d922b290011a3a497b8933c012abc3afa9415d8
[ "MIT" ]
null
null
null
tests/instructions.cpp
voivoid/SynacorChallenge
8d922b290011a3a497b8933c012abc3afa9415d8
[ "MIT" ]
null
null
null
tests/instructions.cpp
voivoid/SynacorChallenge
8d922b290011a3a497b8933c012abc3afa9415d8
[ "MIT" ]
null
null
null
#include "boost/test/unit_test.hpp" #include "synacor/instructions.h" #include "synacor/io.h" #include "synacor/memory_storage.h" #include "synacor/stack.h" #include "test_utils.h" #include "boost/scope_exit.hpp" #include <sstream> #ifdef _MSC_VER # pragma warning( disable : 4459 ) #endif namespace { struct InstructionsFixture { InstructionsFixture() : io( io_ss, io_ss ) { memory.store( memory.get_register( 1 ), 42 ); } template <typename Instruction, typename... Args> synacor::Address exec( Args... args ) { synacor::Machine machine{ memory, stack, io }; return Instruction{ args... }.execute( machine, instruction_addr ); } synacor::Word read_result_reg() { return memory.read( result_reg ); } template <typename Instruction> auto get_unary_func_test() { const auto test = [this]( const synacor::Word from, const synacor::Word expected ) { const auto next_addr = exec<Instruction>( synacor::Word( result_reg ), from ); BOOST_CHECK_EQUAL( expected, read_result_reg() ); BOOST_CHECK_EQUAL( next_addr, instruction_addr + synacor::Address( 3 ) ); }; return test; } template <typename Instruction> auto get_binary_func_test() { const auto test = [this]( const synacor::Word from1, const synacor::Word from2, const synacor::Word expected ) { const auto next_addr = exec<Instruction>( synacor::Word( result_reg ), from1, from2 ); BOOST_CHECK_EQUAL( expected, read_result_reg() ); BOOST_CHECK_EQUAL( next_addr, instruction_addr + synacor::Address( 4 ) ); }; return test; } const synacor::Address instruction_addr = synacor::Address{ 30000 }; std::stringstream io_ss; synacor::MemoryStorage memory; synacor::Stack stack; synacor::IO io; const synacor::Address result_reg = memory.get_register( 0 ); const synacor::Address reg_with_42_num = memory.get_register( 1 ); }; #define CHECK_IS_NOT_CHANGED( var ) \ BOOST_SCOPE_EXIT( var, this_ ) \ { \ BOOST_CHECK( var == this_->var ); \ } \ BOOST_SCOPE_EXIT_END #define CHECK_MEMORY_IS_NOT_CHANGED CHECK_IS_NOT_CHANGED( memory ) #define CHECK_STACK_IS_NOT_CHANGED CHECK_IS_NOT_CHANGED( stack ) } // namespace using namespace synacor; BOOST_FIXTURE_TEST_SUITE( synacor_instructions_suite, InstructionsFixture ) // HALT BOOST_AUTO_TEST_CASE( synacor_instructions_halt ) { CHECK_STACK_IS_NOT_CHANGED; CHECK_MEMORY_IS_NOT_CHANGED; const auto next_addr = exec<synacor::instructions::Halt>(); BOOST_CHECK_EQUAL( Address( 65535 ), next_addr ); } // SET BOOST_AUTO_TEST_CASE( synacor_instructions_set ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_unary_func_test<synacor::instructions::Set>(); test( Word( reg_with_42_num ), 42 ); test( 100, 100 ); } // PUSH BOOST_AUTO_TEST_CASE( synacor_instructions_push ) { CHECK_MEMORY_IS_NOT_CHANGED; const auto test = [this]( const Word from, const Word expected ) { const auto next_addr = exec<synacor::instructions::Push>( from ); BOOST_REQUIRE( !stack.is_empty() ); BOOST_CHECK_EQUAL( stack.top(), expected ); BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 2 ) ); }; test( Word( reg_with_42_num ), 42 ); test( 100, 100 ); } // POP BOOST_AUTO_TEST_CASE( synacor_instructions_pop ) { BOOST_CHECK( stack.is_empty() ); stack.push( 42 ); const auto next_addr = exec<synacor::instructions::Pop>( Word( result_reg ) ); BOOST_CHECK_EQUAL( 42, read_result_reg() ); BOOST_CHECK( stack.is_empty() ); BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 2 ) ); } // EQ BOOST_AUTO_TEST_CASE( synacor_instructions_eq ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_binary_func_test<synacor::instructions::Eq>(); test( Word( reg_with_42_num ), Word( reg_with_42_num ), 1 ); test( Word( reg_with_42_num ), 100, 0 ); test( 100, Word( reg_with_42_num ), 0 ); test( 100, 100, 1 ); } // GT BOOST_AUTO_TEST_CASE( synacor_instructions_gt ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_binary_func_test<synacor::instructions::Gt>(); test( Word( reg_with_42_num ), Word( reg_with_42_num ), 0 ); test( Word( reg_with_42_num ), 10, 1 ); test( 100, Word( reg_with_42_num ), 1 ); test( 100, 100, 0 ); } // JMP BOOST_AUTO_TEST_CASE( synacor_instructions_jmp ) { CHECK_MEMORY_IS_NOT_CHANGED; CHECK_STACK_IS_NOT_CHANGED; const auto next_addr = exec<synacor::instructions::Jmp>( Word( 1234 ) ); BOOST_CHECK_EQUAL( next_addr, Address( 1234 ) ); } // JT BOOST_AUTO_TEST_CASE( synacor_instructions_jt ) { CHECK_MEMORY_IS_NOT_CHANGED; CHECK_STACK_IS_NOT_CHANGED; const auto test = [this]( const Word from, const Address expected ) { const auto next_addr = exec<synacor::instructions::Jt>( from, Word( 1234 ) ); BOOST_CHECK_EQUAL( next_addr, expected ); }; test( Word( reg_with_42_num ), Address( 1234 ) ); test( 0, instruction_addr + Address( 3 ) ); } // JF BOOST_AUTO_TEST_CASE( synacor_instructions_jf ) { CHECK_MEMORY_IS_NOT_CHANGED; CHECK_STACK_IS_NOT_CHANGED; const auto test = [this]( const Word from, const Address expected ) { const auto next_addr = exec<synacor::instructions::Jf>( from, Word( 1234 ) ); BOOST_CHECK_EQUAL( next_addr, expected ); }; test( 0, Address( 1234 ) ); test( Word( reg_with_42_num ), instruction_addr + Address( 3 ) ); } // ADD BOOST_AUTO_TEST_CASE( synacor_instructions_add ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_binary_func_test<synacor::instructions::Add>(); test( Word( reg_with_42_num ), Word( reg_with_42_num ), 84 ); test( 100, 200, 300 ); test( 32758, 15, 5 ); } // MULT BOOST_AUTO_TEST_CASE( synacor_instructions_mult ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_binary_func_test<synacor::instructions::Mult>(); test( Word( reg_with_42_num ), Word( reg_with_42_num ), 1764 ); test( 100, 200, 20000 ); test( 32758, 15, 32618 ); } // MOD BOOST_AUTO_TEST_CASE( synacor_instructions_mod ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_binary_func_test<synacor::instructions::Mod>(); test( Word( reg_with_42_num ), Word( reg_with_42_num ), 0 ); test( 100, 200, 100 ); test( 32758, 15, 13 ); } // AND BOOST_AUTO_TEST_CASE( synacor_instructions_and ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_binary_func_test<synacor::instructions::And>(); test( Word( reg_with_42_num ), Word( reg_with_42_num ), 42 ); test( 100, 200, 64 ); test( 32758, 15, 6 ); } // OR BOOST_AUTO_TEST_CASE( synacor_instructions_or ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_binary_func_test<synacor::instructions::Or>(); test( Word( reg_with_42_num ), Word( reg_with_42_num ), 42 ); test( 100, 200, 236 ); test( 32758, 15, 32767 ); } // NOT BOOST_AUTO_TEST_CASE( synacor_instructions_not ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = get_unary_func_test<synacor::instructions::Not>(); test( Word( reg_with_42_num ), 32725 ); test( 100, 32667 ); test( 0, 32767 ); } // RMEM BOOST_AUTO_TEST_CASE( synacor_instructions_rmem ) { CHECK_STACK_IS_NOT_CHANGED; memory.store( Address( 30000 ), 123 ); BOOST_CHECK_NE( 123, read_result_reg() ); exec<synacor::instructions::RMem>( Word( result_reg ), Word( 30000 ) ); BOOST_CHECK_EQUAL( 123, read_result_reg() ); memory.store( Address( 42 ), 4242 ); BOOST_CHECK_NE( 4242, read_result_reg() ); exec<synacor::instructions::RMem>( Word( result_reg ), Word( reg_with_42_num ) ); BOOST_CHECK_EQUAL( 4242, read_result_reg() ); } // WMEM BOOST_AUTO_TEST_CASE( synacor_instructions_wmem ) { CHECK_STACK_IS_NOT_CHANGED; BOOST_CHECK_NE( 42, memory.read( Address( 30000 ) ) ); exec<synacor::instructions::WMem>( Word( 30000 ), Word( reg_with_42_num ) ); BOOST_CHECK_EQUAL( 42, memory.read( Address( 30000 ) ) ); BOOST_CHECK_NE( 12345, memory.read( Address( 42 ) ) ); exec<synacor::instructions::WMem>( Word( reg_with_42_num ), Word( 12345 ) ); BOOST_CHECK_EQUAL( 12345, memory.read( Address( 42 ) ) ); } // CALL BOOST_AUTO_TEST_CASE( synacor_instructions_call ) { CHECK_MEMORY_IS_NOT_CHANGED; BOOST_CHECK( stack.is_empty() ); BOOST_CHECK( Address( 10000 ) != instruction_addr ); const auto next_addr = exec<synacor::instructions::Call>( Word( 10000 ) ); BOOST_CHECK_EQUAL( next_addr, Address( 10000 ) ); BOOST_CHECK( !stack.is_empty() ); BOOST_CHECK( instruction_addr + Address( 2 ) == Address( Word( stack.pop() ) ) ); } // RET BOOST_AUTO_TEST_CASE( synacor_instructions_ret ) { CHECK_MEMORY_IS_NOT_CHANGED; CHECK_STACK_IS_NOT_CHANGED; exec<synacor::instructions::Call>( Word( 10000 ) ); const auto next_addr = exec<synacor::instructions::Ret>(); BOOST_CHECK( instruction_addr + Address( 2 ) == next_addr ); } // OUT BOOST_AUTO_TEST_CASE( synacor_instructions_out ) { CHECK_MEMORY_IS_NOT_CHANGED; CHECK_STACK_IS_NOT_CHANGED; const auto test = [this]( const Word from, const char expected ) { const auto next_addr = exec<synacor::instructions::Out>( from ); BOOST_CHECK_EQUAL( expected, io_ss.get() ); BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 2 ) ); }; test( Word( reg_with_42_num ), '*' ); test( 100, 'd' ); } // IN BOOST_AUTO_TEST_CASE( synacor_instructions_in ) { CHECK_STACK_IS_NOT_CHANGED; const auto test = [this]( const char expected ) { const auto next_addr = exec<synacor::instructions::In>( Word( result_reg ) ); BOOST_CHECK_EQUAL( expected, read_result_reg() ); BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 2 ) ); }; io_ss << "abc"; test( 'a' ); test( 'b' ); test( 'c' ); } // NOOP BOOST_AUTO_TEST_CASE( synacor_instructions_noop ) { CHECK_MEMORY_IS_NOT_CHANGED; CHECK_STACK_IS_NOT_CHANGED; const auto next_addr = exec<synacor::instructions::Noop>(); BOOST_CHECK_EQUAL( next_addr, instruction_addr + Address( 1 ) ); } BOOST_AUTO_TEST_SUITE_END()
27.255208
140
0.671699
voivoid
7de18477eba6ca4f9c0f4ad6f1f10c37984e82cf
619
hpp
C++
src/Omega_h_inertia.hpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
44
2019-01-23T03:37:18.000Z
2021-08-24T02:20:29.000Z
src/Omega_h_inertia.hpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
67
2019-01-29T15:35:42.000Z
2021-08-17T20:42:40.000Z
src/Omega_h_inertia.hpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
29
2019-01-14T21:33:32.000Z
2021-08-10T11:35:24.000Z
#ifndef INERTIA_HPP #define INERTIA_HPP #include <vector> #include "Omega_h_remotes.hpp" #include "Omega_h_vector.hpp" namespace Omega_h { namespace inertia { struct Rib { std::vector<Vector<3>> axes; }; Read<I8> mark_bisection( CommPtr comm, Reals coords, Reals masses, Real tolerance, Vector<3>& axis); Read<I8> mark_bisection_given_axis( CommPtr comm, Reals coords, Reals masses, Real tolerance, Vector<3> axis); void recursively_bisect(CommPtr comm, Real tolerance, Reals* p_coords, Reals* p_masses, Remotes* p_owners, Rib* p_hints); } // namespace inertia } // end namespace Omega_h #endif
22.107143
79
0.741519
joshia5
7dea34c246d4e7b568d47cbe1d15058465638586
2,769
cpp
C++
Examples/source/ManageBarcodeImages/BarcodeImageResolution.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
3
2018-12-07T18:39:59.000Z
2021-06-08T13:08:29.000Z
Examples/source/ManageBarcodeImages/BarcodeImageResolution.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
null
null
null
Examples/source/ManageBarcodeImages/BarcodeImageResolution.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
1
2018-07-13T14:22:11.000Z
2018-07-13T14:22:11.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.BarCode for .NET API reference when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.BarCode for .NET API from http://www.aspose.com/downloads, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using http://www.aspose.com/community/forums/default.aspx */ #include "BarcodeImageResolution.h" #include <system/string.h> #include <system/shared_ptr.h> #include <system/object.h> #include <Generation/ResolutionMode.h> #include <Generation/Resolution.h> #include <system/environment.h> #include <system/console.h> #include <Generation/EncodeTypes/SymbologyEncodeType.h> #include <Generation/EncodeTypes/EncodeTypes.h> #include <Generation/Caption.h> #include <BarCode.Generation/BarcodeGenerator.h> #include <BarCode.Generation/GenerationParameters/BaseGenerationParameters.h> #include <BarCode.Generation/GenerationParameters/BarcodeParameters.h> #include <BarCode.Generation/GenerationParameters/CaptionParameters.h> #include <BarCode.Generation/Helpers/FontUnit.h> #include <BarCode.Generation/Helpers/Unit.h> #include <BarCode.Generation/GenerationParameters/TextAlignment.h> #include <drawing/string_alignment.h> #include <Generation/BarCodeImageFormat.h> #include <drawing/imaging/image_format.h> #include "RunExamples.h" using namespace Aspose::BarCode::Generation; namespace Aspose { namespace BarCode { namespace Examples { namespace CSharp { namespace ManageBarCodeImages { RTTI_INFO_IMPL_HASH(1693318637u, ::Aspose::BarCode::Examples::CSharp::ManageBarCodeImages::BarcodeImageResolution, ThisTypeBaseTypesInfo); void BarcodeImageResolution::Run() { //ExStart:BarcodeImageResolution // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir_ManageBarCodesImages(); // Instantiate barcode object and set CodeText & Barcode Symbology System::SharedPtr<BarcodeGenerator> generator = [&] { auto tmp_0 = System::MakeObject<BarcodeGenerator>(EncodeTypes::Code128, u"1234567"); tmp_0->get_Parameters()->set_Resolution(400.f); return tmp_0; }(); // Save the image to your system and set its image format to Jpeg generator->Save(dataDir + u"barcode-image-resolution_out.jpeg", BarCodeImageFormat::Jpeg); System::Console::WriteLine(System::Environment::get_NewLine() + u"Barcode saved at " + dataDir); //ExEnd:BarcodeImageResolution } } // namespace ManageBarCodeImages } // namespace CSharp } // namespace Examples } // namespace BarCode } // namespace Aspose
41.328358
211
0.772842
aspose-barcode
8fc31b5a688eea5ef79a0996e62bac80e8ff0f98
7,411
cpp
C++
src/Cpl/Container/_0test/stack.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
src/Cpl/Container/_0test/stack.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
src/Cpl/Container/_0test/stack.cpp
johnttaylor/foxtail
86e4e1d19d5e8f9c1d1064cf0939f4bf62615400
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------- * This file is part of the Colony.Core Project. The Colony.Core Project is an * open source project with a BSD type of licensing agreement. See the license * agreement (license.txt) in the top/ directory or on the Internet at * http://integerfox.com/colony.core/license.txt * * Copyright (c) 2014-2020 John T. Taylor * * Redistributions of the source code must retain the above copyright notice. *----------------------------------------------------------------------------*/ #include "Catch/catch.hpp" #include "Cpl/Container/Stack.h" #include "Cpl/System/_testsupport/Shutdown_TS.h" #include <string.h> /// using namespace Cpl::Container; using namespace Cpl::System; //////////////////////////////////////////////////////////////////////////////// int memoryStack_[5]; //////////////////////////////////////////////////////////////////////////////// TEST_CASE( "STACK: Validate member functions", "[stack]" ) { Stack<int> stack( sizeof( memoryStack_ ) / sizeof( memoryStack_[0] ), memoryStack_ ); Shutdown_TS::clearAndUseCounter(); SECTION( "Operations" ) { bool status; REQUIRE( stack.isEmpty() == true ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.peekTop() == 0 ); REQUIRE( stack.peekTop( &status ) == 0 ); REQUIRE( status == false ); REQUIRE( stack.getNumItems() == 0 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.push( 10 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 1 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop( &status ) == 10 ); REQUIRE( status == true ); REQUIRE( stack.peekTop() == 10 ); REQUIRE( stack.push( 20 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 2 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 20 ); REQUIRE( stack.peekTop( &status ) == 20 ); REQUIRE( status == true ); REQUIRE( stack.push( 30 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 3 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 30 ); REQUIRE( stack.peekTop( &status ) == 30 ); REQUIRE( status == true ); REQUIRE( stack.push( 40 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 4 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 40 ); REQUIRE( stack.peekTop( &status ) == 40 ); REQUIRE( status == true ); REQUIRE( stack.push( 50 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == true ); REQUIRE( stack.getNumItems() == 5 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 50 ); REQUIRE( stack.peekTop( &status ) == 50 ); REQUIRE( status == true ); REQUIRE( stack.push( 60 ) == false ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == true ); REQUIRE( stack.getNumItems() == 5 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 50 ); REQUIRE( stack.peekTop( &status ) == 50 ); REQUIRE( status == true ); REQUIRE( stack.pop( &status ) == 50 ); REQUIRE( status == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 4 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 40 ); REQUIRE( stack.peekTop( &status ) == 40 ); REQUIRE( status == true ); REQUIRE( stack.pop() == 40 ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 3 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 30 ); REQUIRE( stack.peekTop( &status ) == 30 ); REQUIRE( status == true ); REQUIRE( stack.push( 60 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 4 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 60 ); REQUIRE( stack.peekTop( &status ) == 60 ); REQUIRE( status == true ); REQUIRE( stack.push( 70 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == true ); REQUIRE( stack.getNumItems() == 5 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 70 ); REQUIRE( stack.peekTop( &status ) == 70 ); REQUIRE( status == true ); REQUIRE( stack.pop( &status ) == 70 ); REQUIRE( status == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 4 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 60 ); REQUIRE( stack.peekTop( &status ) == 60 ); REQUIRE( status == true ); REQUIRE( stack.pop( &status ) == 60 ); REQUIRE( status == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 3 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 30 ); REQUIRE( stack.peekTop( &status ) == 30 ); REQUIRE( status == true ); REQUIRE( stack.pop( &status ) == 30 ); REQUIRE( status == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 2 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 20 ); REQUIRE( stack.peekTop( &status ) == 20 ); REQUIRE( status == true ); REQUIRE( stack.pop( &status ) == 20 ); REQUIRE( status == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 1 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 10 ); REQUIRE( stack.peekTop( &status ) == 10 ); REQUIRE( status == true ); REQUIRE( stack.pop( &status ) == 10 ); REQUIRE( status == true ); REQUIRE( stack.isEmpty() == true ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 0 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 0 ); REQUIRE( stack.peekTop( &status ) == 0 ); REQUIRE( status == false ); REQUIRE( stack.pop( &status ) == 0 ); REQUIRE( status == false ); REQUIRE( stack.isEmpty() == true ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.peekTop() == 0 ); REQUIRE( stack.peekTop( &status ) == 0 ); REQUIRE( status == false ); REQUIRE( stack.push( 10 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 1 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 10 ); REQUIRE( stack.peekTop( &status ) == 10 ); REQUIRE( status == true ); REQUIRE( stack.push( 20 ) == true ); REQUIRE( stack.isEmpty() == false ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 2 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 20 ); REQUIRE( stack.peekTop( &status ) == 20 ); REQUIRE( status == true ); stack.clearTheStack(); REQUIRE( stack.isEmpty() == true ); REQUIRE( stack.isFull() == false ); REQUIRE( stack.getNumItems() == 0 ); REQUIRE( stack.getMaxItems() == 5 ); REQUIRE( stack.peekTop() == 0 ); REQUIRE( stack.peekTop( &status ) == 0 ); REQUIRE( status == false ); } REQUIRE( Shutdown_TS::getAndClearCounter() == 0u ); }
32.082251
86
0.586021
johnttaylor
8fcc4b6fcd37808464600f77f4c3cf0a4a9ddf61
347
hpp
C++
examples/06_ssd1306/main/include/i2c.hpp
graealex/qemu_esp32
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
[ "Apache-2.0" ]
335
2016-10-12T06:59:33.000Z
2022-03-29T14:26:04.000Z
examples/06_ssd1306/main/include/i2c.hpp
graealex/qemu_esp32
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
[ "Apache-2.0" ]
30
2016-10-30T11:23:59.000Z
2021-11-12T10:51:20.000Z
examples/06_ssd1306/main/include/i2c.hpp
graealex/qemu_esp32
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
[ "Apache-2.0" ]
48
2016-10-30T08:41:13.000Z
2022-02-15T22:15:09.000Z
#ifndef I2C_H_ #define I2C_H_ #include "driver/gpio.h" #include "rom/ets_sys.h" class I2C { private: gpio_num_t scl_pin, sda_pin; public: I2C(gpio_num_t scl, gpio_num_t sda); void init(uint8_t scl_pin, uint8_t sda_pin); bool start(void); void stop(void); bool write(uint8_t data); uint8_t read(void); void set_ack(bool ack); }; #endif
15.772727
45
0.729107
graealex
8fcc7de9d75968f69f738bf5721e91618526caa1
797
cpp
C++
codeforce2/463C. Gargari and Bishops.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce2/463C. Gargari and Bishops.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce2/463C. Gargari and Bishops.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int const N = 3001; int n, g[N][N], x, y, xx, yy; long long dp1[2 * N], dp2[2 * N], sol1 = -1, sol2 = -1; int main() { scanf("%d", &n); for(int i = 1; i <= n; ++i) for(int j = 1; j <= n; ++j) { scanf("%d", &g[i][j]); dp1[i + j] += g[i][j]; dp2[i - j + n] += g[i][j]; } for(int i = 1; i <= n; ++i) for(int j = 1; j <= n; ++j) { long long v = dp1[i + j] + dp2[i - j + n] - g[i][j]; if((i + j) & 1) { if(v > sol2) { sol2 = v; xx = i; yy = j; } } else { if(v > sol1) { sol1 = v; x = i; y = j; } } } printf("%lld\n", sol1 + sol2); printf("%d %d %d %d\n", x, y, xx, yy); return 0; }
19.439024
58
0.350063
khaled-farouk
8fd14b59b311c5b83ea91c105073dbeb16b83704
9,609
cpp
C++
sdl.cpp
bl-ackrain/PokittoEmu
928f1e7beedc80b414add4c54f88731ac64f1b73
[ "MIT" ]
null
null
null
sdl.cpp
bl-ackrain/PokittoEmu
928f1e7beedc80b414add4c54f88731ac64f1b73
[ "MIT" ]
null
null
null
sdl.cpp
bl-ackrain/PokittoEmu
928f1e7beedc80b414add4c54f88731ac64f1b73
[ "MIT" ]
null
null
null
#include "sdl.hpp" #include "./cpu.hpp" #include "./gdb.hpp" #include "./gpio.hpp" #include "./screen.hpp" #include "./state.hpp" #include "./sd.hpp" #include "./adc.hpp" #include "gif.h" extern volatile EmuState emustate; extern volatile bool hasQuit; extern std::string srcPath; extern "C" void reset(); GifWriter gif; SDL::SDL( Uint32 flags ) { if ( SDL_Init( flags ) != 0 ) throw InitError(SDL_GetError()); canTakeScreenshot = (IMG_Init( IMG_INIT_PNG ) & IMG_INIT_PNG) == IMG_INIT_PNG; m_window = SDL_CreateWindow("PokittoEmu", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 220*2, 176*2, 0); if( !m_window ) throw InitError(SDL_GetError()); m_renderer = SDL_CreateRenderer( m_window, -1, SDL_RENDERER_SOFTWARE// | SDL_RENDERER_PRESENTVSYNC ); if( !m_renderer ) throw InitError(SDL_GetError()); recording = false; // Clear the window with a black background SDL_SetRenderDrawColor( m_renderer, 0, 0, 0, 255 ); SDL_RenderClear( m_renderer ); screen = SDL_GetWindowSurface( m_window ); vscreen = SDL_CreateRGBSurface( 0, // flags 220, // w 176, // h 16, // depth 0, 0, 0, 0 ); if( !vscreen ) throw InitError(SDL_GetError()); SDL_LockSurface(vscreen); SCREEN::LCD = (u16 *) vscreen->pixels; SDL_LockSurface(screen); screenpixels = (u8 *) screen->pixels; SDL_UnlockSurface( screen ); SDL_JoystickEventState(SDL_ENABLE); u32 numJoysticks = SDL_NumJoysticks(); for( u32 i=0; i<numJoysticks; ++i ){ joysticks[i] = SDL_JoystickOpen(i); } } SDL::~SDL() { for( auto js : joysticks ) SDL_JoystickClose(js.second); hasQuit = true; if( recording ) toggleRecording(); if( vscreen ){ SDL_UnlockSurface(vscreen); SDL_FreeSurface(vscreen); } IMG_Quit(); SDL_DestroyWindow( m_window ); SDL_DestroyRenderer( m_renderer ); SDL_Quit(); } void SDL::toggleRecording(){ recording = !recording; #ifndef __EMSCRIPTEN__ std::lock_guard<std::mutex> gml(gifmut); #endif if( recording ){ gifNum++; std::string name = srcPath; name += "."; name += std::to_string(gifNum); name += ".gif"; GifBegin( &gif, name.c_str(), 220, 176, 2 ); delay = 10; }else{ GifEnd( &gif ); } } void SDL::savePNG(){ gifNum++; std::string name = srcPath; name += "."; name += std::to_string(gifNum); name += ".png"; IMG_SavePNG( vscreen, name.c_str() ); } void SDL::draw(){ if( !SCREEN::dirty ){ delay+=2; #ifndef __EMSCRIPTEN__ std::this_thread::sleep_for( 10ms ); #endif return; } SCREEN::dirty = false; SDL_UnlockSurface( vscreen ); SDL_BlitScaled( vscreen, nullptr, screen, nullptr ); SDL_LockSurface(vscreen); if( screenshot ){ screenshot--; if( !screenshot ) savePNG(); } { #ifndef __EMSCRIPTEN__ std::lock_guard<std::mutex> gml(gifmut); #endif if( recording && delay > 4 ){ uint8_t *rgbap = rgba; for( u32 i=0; i<220*176; ++i ){ u16 c = ((u16 *)SCREEN::LCD)[i]; *rgbap++ = float(c >> 11) / 0x1F * 255.0f; *rgbap++ = float((c >> 5) & 0x3F) / 0x3F * 255.0f; *rgbap++ = float(c & 0x1F) / 0x1F * 255.0f; *rgbap++ = 255; } GifWriteFrame( &gif, (u8*) rgba, 220, 176, delay, 8 ); for( u32 y=0; y<15; ++y ){ for( u32 x=0; x<15; ++x ){ screenpixels[ (((y+3)*440+x+3)<<2)+2 ] = ~CPU::cpuTotalTicks; } } delay = 2; } } SDL_UpdateWindowSurface(m_window); // SDL_RenderPresent( m_renderer ); } void SDL::emitEvents(){ std::lock_guard<std::mutex> lock(eventmut); for( EventHandler ev : eventHandlers ){ ev(); } eventHandlers.clear(); } void SDL::checkEvents(){ SDL_Event e; if( !joysticks.empty() ){ ADC::DAT8 = (int32_t(SDL_JoystickGetAxis(joysticks.begin()->second, 4))>>1)+0x8000; ADC::DAT9 = (int32_t(-SDL_JoystickGetAxis(joysticks.begin()->second, 3))>>1)+0x8000; }else{ ADC::DAT8 = 0x8000; ADC::DAT9 = 0x8000; } while (SDL_PollEvent(&e)) { std::lock_guard<std::mutex> lock(eventmut); if( e.type == SDL_QUIT ){ hasQuit = true; return; } if( e.type == SDL_JOYBUTTONUP || e.type == SDL_JOYBUTTONDOWN ){ u32 btnState = e.type == SDL_JOYBUTTONDOWN; switch( e.jbutton.button ){ case 0: // a eventHandlers.push_back( [=](){ GPIO::input(1,9,btnState); } ); break; case 1: // b eventHandlers.push_back( [=](){ GPIO::input(1,4,btnState); } ); break; case 2: // c eventHandlers.push_back( [=](){ GPIO::input(1,10,btnState); } ); break; case 3: // flash eventHandlers.push_back( [=](){ GPIO::input(0,1,btnState); } ); break; } }else if( e.type == SDL_JOYAXISMOTION ){ static int px = 0, py = 0; int x = 0, y = 0; const int deadzone = 1000; if( e.jaxis.axis == 0) { if( e.jaxis.value < -deadzone ) x = -1; else if( e.jaxis.value > deadzone ) x = 1; } if( e.jaxis.axis == 1) { if( e.jaxis.value < -deadzone ) y = -1; else if( e.jaxis.value > deadzone ) y = 1; } if( x != px ){ if( px < 0 ){ eventHandlers.push_back( [=](){ GPIO::input(1,25,false); } ); }else if( px > 0 ){ eventHandlers.push_back( [=](){ GPIO::input(1,7,false); } ); } px = x; if( px < 0 ){ eventHandlers.push_back( [=](){ GPIO::input(1,25,true); } ); }else if( px > 0 ){ eventHandlers.push_back( [=](){ GPIO::input(1,7,true); } ); } } if( y != py ){ if( py < 0 ){ eventHandlers.push_back( [=](){ GPIO::input(1,13,false); } ); }else if( py > 0 ){ eventHandlers.push_back( [=](){ GPIO::input(1,3,false); } ); } py = y; if( py < 0 ){ eventHandlers.push_back( [=](){ GPIO::input(1,13,true); } ); }else if( py > 0 ){ eventHandlers.push_back( [=](){ GPIO::input(1,3,true); } ); } } } if( e.type == SDL_KEYUP ){ switch( e.key.keysym.sym ){ case SDLK_ESCAPE: hasQuit = true; return; case SDLK_F5: eventHandlers.push_back( [](){ reset(); } ); break; case SDLK_F8: eventHandlers.push_back( [](){ if( GDB::connected() ){ if( emustate == EmuState::RUNNING ) GDB::interrupt(); }else{ if( emustate == EmuState::RUNNING ) emustate = EmuState::STOPPED; else emustate = EmuState::RUNNING; } }); break; case SDLK_F2: screenshot = 1; SCREEN::dirty = true; break; case SDLK_F10: eventHandlers.push_back([=](){ std::ofstream os( "dump.img", std::ios::binary ); if( os.is_open() ) os.write( reinterpret_cast<char *>(&SD::image[0]), SD::length ); }); break; } } if( emustate == EmuState::STOPPED ) continue; if( e.type == SDL_KEYDOWN || e.type == SDL_KEYUP ){ u32 btnState = e.type == SDL_KEYDOWN; switch( e.key.keysym.sym ){ case SDLK_F3: if(e.type == SDL_KEYDOWN) toggleRecording(); break; case SDLK_F9: eventHandlers.push_back( [](){ GDB::interrupt(); } ); break; case SDLK_UP: eventHandlers.push_back( [=](){ GPIO::input(1,13,btnState); /* std::cout << std::hex << int(MMU::read8(0xA0000020+13)) << btnState << std::endl; */ } ); break; case SDLK_DOWN: eventHandlers.push_back( [=](){ GPIO::input(1,3,btnState); } ); break; case SDLK_LEFT: eventHandlers.push_back( [=](){ GPIO::input(1,25,btnState); } ); break; case SDLK_RIGHT: eventHandlers.push_back( [=](){ GPIO::input(1,7,btnState); } ); break; case SDLK_a: eventHandlers.push_back( [=](){ GPIO::input(1,9,btnState); } ); break; case SDLK_s: case SDLK_b: eventHandlers.push_back( [=](){ GPIO::input(1,4,btnState); } ); break; case SDLK_d: case SDLK_c: eventHandlers.push_back( [=](){ GPIO::input(1,10,btnState); } ); break; case SDLK_f: eventHandlers.push_back( [=](){ GPIO::input(0,1,btnState); } ); break; } } } }
22.662736
92
0.480383
bl-ackrain
8fda5f2b74a481e41fa4bbfc7ea333ea6f5d3130
14,639
cpp
C++
windows/advcore/duser/engine/motion/scheduler.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/advcore/duser/engine/motion/scheduler.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/advcore/duser/engine/motion/scheduler.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/***************************************************************************\ * * File: Scheduler.cpp * * Description: * Scheduler.cpp maintains a collection of timers that are created and used * by the application for notifications. * * * History: * 1/18/2000: JStall: Created * * Copyright (C) 2000 by Microsoft Corporation. All rights reserved. * \***************************************************************************/ #include "stdafx.h" #include "Motion.h" #include "Scheduler.h" #include "Action.h" #include "Context.h" /***************************************************************************\ ***************************************************************************** * * class Scheduler * ***************************************************************************** \***************************************************************************/ //--------------------------------------------------------------------------- Scheduler::Scheduler() { #if DBG m_DEBUG_fLocked = FALSE; #endif // DBG } //--------------------------------------------------------------------------- Scheduler::~Scheduler() { AssertMsg(m_fShutdown, "Scheduler must be manually shutdown before destruction"); } /***************************************************************************\ * * Scheduler::xwPreDestroy * * xwPreDestroy() prepares the Scheduler for destruction while it is still * valid to callback into the application. * \***************************************************************************/ void Scheduler::xwPreDestroy() { m_fShutdown = TRUE; xwRemoveAllActions(); } /***************************************************************************\ * * Scheduler::AddAction * * AddAction() creates and adds a new Action, using the specified information. * \***************************************************************************/ Action * Scheduler::AddAction( IN const GMA_ACTION * pma) // Action information { // // Check if shutting down and don't allow any new Actions to be created. // if (m_fShutdown) { return NULL; } Action * pact; Enter(); // // Determine which list to add the action to and add it. // GList<Action> * plstParent = NULL; bool fPresent = IsPresentTime(pma->flDelay); if (fPresent) { plstParent = &m_lstacPresent; } else { plstParent = &m_lstacFuture; } DWORD dwCurTick = GetTickCount(); pact = Action::Build(plstParent, pma, dwCurTick, fPresent); if (pact == NULL) { goto Exit; } plstParent->Add(pact); // // Returning out the Action, so we need to lock the HACTION that we are // giving back. // pact->Lock(); Exit: Leave(); return pact; } /***************************************************************************\ * * Scheduler::xwRemoveAllActions * * xwRemoveAllActions() removes all Actions still "owned" by the Scheduler. * \***************************************************************************/ void Scheduler::xwRemoveAllActions() { GArrayF<Action *> aracFire; // // NOTE: We can not fire any notifications while inside the Scheduler lock, // or the Scheduler could get messed up. Instead, we need to remember all // of the Actions to fire, and then fire them when we leave the lock. // Enter(); int cItems = m_lstacPresent.GetSize() + m_lstacFuture.GetSize(); aracFire.SetSize(cItems); int idxAdd = 0; while (!m_lstacPresent.IsEmpty()) { Action * pact = m_lstacPresent.UnlinkHead(); VerifyMsg(pact->xwUnlock(), "Action should still be valid"); pact->SetParent(NULL); aracFire[idxAdd++] = pact; } while (!m_lstacFuture.IsEmpty()) { Action * pact = m_lstacFuture.UnlinkHead(); VerifyMsg(pact->xwUnlock(), "Action should still be valid"); pact->SetParent(NULL); aracFire[idxAdd++] = pact; } AssertMsg(idxAdd == cItems, "Should have added all items"); Leave(); // // Don't fire from processing when removing the Actions. Instead, only // have the destructors fire when the Action finally gets cleaned up. // xwFireNL(aracFire, FALSE); } /***************************************************************************\ * * Scheduler::xwProcessActionsNL * * xwProcessActionsNL() processes the Actions for one iteration, moving * between queues and firing notifications. * \***************************************************************************/ DWORD Scheduler::xwProcessActionsNL() { DWORD dwCurTime = ::GetTickCount(); // // NOTE: We need to leave the lock when calling back as part of the // Action::Fire() mechanism. To accomplish this, we store up all of the // Actions to callback during processing and callback after leaving the // lock. // // NOTE: We can not use a GList to store the actions to fire because they // are already stored in a list and the ListNode's would conflict. So, // we use an Array instead. // GArrayF<Action *> aracFire; Enter(); Thread * pCurThread = GetThread(); BOOL fFinishedPeriod, fFire; // // Go through and pre-process all future actions. If a future actions // time has come up, move it to the present actions list. // Action * pactCur = m_lstacFuture.GetHead(); while (pactCur != NULL) { Action * pactNext = pactCur->GetNext(); if (pactCur->GetThread() == pCurThread) { AssertMsg(!pactCur->IsPresent(), "Ensure action not yet present"); pactCur->Process(dwCurTime, &fFinishedPeriod, &fFire); AssertMsg(! fFire, "Should not fire future Actions"); if (fFinishedPeriod) { // // Action has reached the present // m_lstacFuture.Unlink(pactCur); pactCur->SetPresent(TRUE); pactCur->ResetPresent(dwCurTime); pactCur->SetParent(&m_lstacPresent); m_lstacPresent.Add(pactCur); } } pactCur = pactNext; } // // Go through and process all present actions // pactCur = m_lstacPresent.GetHead(); while (pactCur != NULL) { Action * pactNext = pactCur->GetNext(); if (pactCur->GetThread() == pCurThread) { pactCur->Process(dwCurTime, &fFinishedPeriod, &fFire); if (fFire) { // // The Action should be fired, so lock it and add it to the // delayed set of Actions to fire. It is important to lock // it if the Action is finished so that it doesn't get // destroyed. // pactCur->Lock(); if (aracFire.Add(pactCur) < 0) { // TODO: Unable to add the Action. This is pretty bad. // Need to figure out how to handle this situation, // especially if fFinishedPeriod or the app may leak resources. } } if (fFinishedPeriod) { pactCur->SetParent(NULL); m_lstacPresent.Unlink(pactCur); pactCur->EndPeriod(); // // The action has finished this round. If it is not periodic, it // will be destroyed during its callback. If it is periodic, // need to re-add it to the correct (present or future) list. // if (pactCur->IsComplete()) { pactCur->MarkDelete(TRUE); VerifyMsg(pactCur->xwUnlock(), "Should still have HANDLE lock"); } else { GList<Action> * plstParent = NULL; float flWait = pactCur->GetStartDelay(); BOOL fPresent = IsPresentTime(flWait); if (fPresent) { pactCur->ResetPresent(dwCurTime); plstParent = &m_lstacPresent; } else { pactCur->ResetFuture(dwCurTime, FALSE); plstParent = &m_lstacFuture; } pactCur->SetPresent(fPresent); pactCur->SetParent(plstParent); plstParent->Add(pactCur); } } } pactCur = pactNext; } // // Now that everything has been determined, determine how long until Actions // need to be processed again. // // NOTE: To keep Actions from overwhelming CPU and giving other tasks some // time to accumulate and process, we normally limit the granularity to // 10 ms. We actually should allow Actions to specify there own granularity // and provide a default, probably of 10 ms for continuous Actions. // // NOTE: Is is very important that this number is not too high, because it // will severly limit the framerate to 1000 / delay. After doing // significant profiling work, 10 ms was found to be ideal which gives an // upper bound of about 100 fps. // DWORD dwTimeOut = INFINITE; if (m_lstacPresent.IsEmpty()) { // // There are no present Actions, so check over the future Actions to // determine when the next one executes. // Action * pactCur = m_lstacFuture.GetHead(); while (pactCur != NULL) { Action * pactNext = pactCur->GetNext(); if (pactCur->GetThread() == pCurThread) { AssertMsg(!pactCur->IsPresent(), "Ensure action not yet present"); DWORD dwNewTimeOut = pactCur->GetIdleTimeOut(dwCurTime); AssertMsg(dwTimeOut > 0, "If Action has no TimeOut, should already be present."); if (dwNewTimeOut < dwTimeOut) { dwTimeOut = dwNewTimeOut; } } pactCur = pactNext; } } else { // // There are present Actions, so query their PauseTimeOut(). // Action * pactCur = m_lstacPresent.GetHead(); while (pactCur != NULL) { Action * pactNext = pactCur->GetNext(); DWORD dwNewTimeout = pactCur->GetPauseTimeOut(); if (dwNewTimeout < dwTimeOut) { dwTimeOut = dwNewTimeout; if (dwTimeOut == 0) { break; } } pactCur = pactNext; } } Leave(); xwFireNL(aracFire, TRUE); // // After actually execution the Actions, compute how much time to wait until // processing the next batch. We want to subtract the time we spent // processing the Actions, since if we setup timers on 50 ms intervals and // the processing takes 20 ms, we should only wait 30 ms. // // NOTE we need to do this AFTER calling xwFireNL(), since this fires the // actual notifications and does the processing. If we compute before this, // the majority of the work will not be included. // DWORD dwOldCurTime = dwCurTime; dwCurTime = ::GetTickCount(); // Update the current time DWORD dwProcessTime = ComputeTickDelta(dwCurTime, dwOldCurTime); if (dwProcessTime < dwTimeOut) { dwTimeOut -= dwProcessTime; } else { dwTimeOut = 0; } return dwTimeOut; } //--------------------------------------------------------------------------- #if DBG void DEBUG_CheckValid(const GArrayF<Action *> & aracFire, int idxStart) { int cActions = aracFire.GetSize(); for (int i = idxStart; i < cActions; i++) { DWORD * pdw = (DWORD *) aracFire[i]; AssertMsg(*pdw != 0xfeeefeee, "Should still be valid"); } } #endif // DBG /***************************************************************************\ * * Scheduler::xwFireNL * * xwFireNL() fires notifications for the specified Actions, updating Action * state as it is fired. * \***************************************************************************/ void Scheduler::xwFireNL( IN GArrayF<Action *> & aracFire, // Actions to notify IN BOOL fFire // "Fire" the notification (or just update) ) const { #if DBG // // Check that each Action is only in the list once. // { int cActions = aracFire.GetSize(); for (int i = 0; i < cActions; i++) { aracFire[i]->DEBUG_MarkInFire(TRUE); for (int j = i + 1; j < cActions; j++) { AssertMsg(aracFire[i] != aracFire[j], "Should only be in once"); } } DEBUG_CheckValid(aracFire, 0); } #endif // DBG // // Outside of the lock, so can fire the callbacks. // // NOTE: We may actually be locked by a different thread, but that's okay. // int cActions = aracFire.GetSize(); for (int idx = 0; idx < cActions; idx++) { Action * pact = aracFire[idx]; #if DBG DEBUG_CheckValid(aracFire, idx); #endif // DBG if (fFire) { pact->xwFireNL(); } #if DBG aracFire[idx]->DEBUG_MarkInFire(FALSE); #endif // DBG pact->xwUnlock(); #if DBG aracFire[idx] = NULL; #endif // DBG } // // NOTE: Since we pass in a Action * array, we don't need to worry about // the destructors getting called and the Actions being incorrectly // destroyed. // } /***************************************************************************\ ***************************************************************************** * * Global Functions * ***************************************************************************** \***************************************************************************/ //--------------------------------------------------------------------------- HACTION GdCreateAction(const GMA_ACTION * pma) { return (HACTION) GetHandle(GetMotionSC()->GetScheduler()->AddAction(pma)); }
29.633603
98
0.485074
npocmaka
8fdaa8167b9c199f632393837270d264aa7564f6
27,470
hpp
C++
multimedia/directx/dxg/d3d/ref/inc/rrutil.hpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/directx/dxg/d3d/ref/inc/rrutil.hpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/directx/dxg/d3d/ref/inc/rrutil.hpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) Microsoft Corporation, 1998. // // rrutil.hpp // // Direct3D Reference Rasterizer - Utilities // /////////////////////////////////////////////////////////////////////////////// #ifndef _RRUTIL_HPP #define _RRUTIL_HPP #include <math.h> #ifndef FASTCALL #ifdef _X86_ #define FASTCALL __fastcall #else #define FASTCALL #endif #endif #ifndef CDECL #ifdef _X86_ #define CDECL __cdecl #else #define CDECL #endif #endif /////////////////////////////////////////////////////////////////////////////// // // // Globals // // // /////////////////////////////////////////////////////////////////////////////// // memory allocation callbacks extern LPVOID (__cdecl *g_pfnMemAlloc)( size_t size ); extern void (__cdecl *g_pfnMemFree)( LPVOID lptr ); extern LPVOID (__cdecl *g_pfnMemReAlloc)( LPVOID ptr, size_t size ); // debug print controls extern int g_iDPFLevel; extern unsigned long g_uDPFMask; /////////////////////////////////////////////////////////////////////////////// // // // Typedefs // // // /////////////////////////////////////////////////////////////////////////////// #ifndef DllExport #define DllExport __declspec( dllexport ) #endif // width-specific typedefs for basic types #ifndef _BASETSD_H_ typedef signed char INT8, *PINT8; typedef short int INT16, *PINT16; typedef int INT32, *PINT32; typedef __int64 INT64, *PINT64; typedef unsigned char UINT8, *PUINT8; typedef unsigned short int UINT16, *PUINT16; typedef unsigned int UINT32, *PUINT32; typedef unsigned __int64 UINT64, *PUINT64; #endif typedef float FLOAT, *PFLOAT; typedef double DOUBLE, *PDOUBLE; typedef int BOOL; typedef struct _RRVECTOR4 { D3DVALUE x; D3DVALUE y; D3DVALUE z; D3DVALUE w; } RRVECTOR4, *LPRRVECTOR4; //----------------------------------------------------------------------------- // // Private FVF flags for texgen. // //----------------------------------------------------------------------------- #define D3DFVFP_EYENORMAL ((UINT64)1<<32) #define D3DFVFP_EYEXYZ ((UINT64)1<<33) /////////////////////////////////////////////////////////////////////////////// // // // Macros // // // /////////////////////////////////////////////////////////////////////////////// #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef NULL #define NULL 0 #endif #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define ABS(a) (((a) < 0) ? (-(a)) : (a)) // Check the return value and return if something wrong. // Assume hr has been declared #define HR_RET(exp) \ { \ hr = (exp); \ if (hr != D3D_OK) \ { \ return hr; \ } \ } //----------------------------------------------------------------------------- // // macros for accessing floating point data as 32 bit integers and vice versa // // This is used primarily to do floating point to fixed point conversion with // the unbiased nearest-even rounding that IEEE floating point does internally // between operations. Adding a big number slides the mantissa down to where // the fixed point equivalent is aligned to the LSB. IEEE applies a nearest- // even round to the bits it lops off before storing. The mantissa can then // be grabbed by the AS_INT* operations. Note that the sign and exponent are // still there, so the easiest thing is to do it with doubles and grab the low // 32 bits. // // The snap values (i.e. the "big number") is the sum of 2**n and 2**(n-1), // which makes the trick return signed numbers (at least within the mantissa). // //----------------------------------------------------------------------------- #if 0 // NOTE: vc5 optimizing compiler bug breaks this pointer casting technique #define AS_FLOAT(i) ( *(FLOAT*)&(i) ) #define AS_INT32(f) ( *(INT32*)&(f) ) #define AS_INT16(f) ( *(INT16*)&(f) ) #define AS_UINT32(f) ( *(UINT32*)&(f) ) #else // workaround using union typedef union { float f; UINT32 u; INT32 i; } VAL32; typedef union { double d; UINT64 u; INT64 i; } VAL64; inline FLOAT AS_FLOAT( long int iVal ) { VAL32 v; v.i = iVal; return v.f; } inline FLOAT AS_FLOAT( unsigned long int uVal ) { VAL32 v; v.u = uVal; return v.f; } inline INT32 AS_INT32( FLOAT fVal ) { VAL32 v; v.f = fVal; return v.i; } inline INT32 AS_INT32( DOUBLE dVal ) { VAL64 v; v.d = dVal; return (INT32)(v.u & 0xffffffff); } inline INT16 AS_INT16( FLOAT fVal ) { VAL32 v; v.f = fVal; return (INT16)(v.u & 0xffff); } inline INT16 AS_INT16( DOUBLE dVal ) { VAL64 v; v.d = dVal; return (INT16)(v.u & 0xffff); } inline INT32 AS_UINT32( FLOAT fVal ) { VAL32 v; v.f = fVal; return v.u; } #endif //----------------------------------------------------------------------------- // // Some common FP values as constants // point values // //----------------------------------------------------------------------------- #define g_fZero (0.0f) #define g_fOne (1.0f) // Integer representation of 1.0f. #define INT32_FLOAT_ONE 0x3f800000 //----------------------------------------------------------------------------- // // these are handy to form 'magic' constants to snap real values to fixed // point values // //----------------------------------------------------------------------------- #define C2POW0 1 #define C2POW1 2 #define C2POW2 4 #define C2POW3 8 #define C2POW4 16 #define C2POW5 32 #define C2POW6 64 #define C2POW7 128 #define C2POW8 256 #define C2POW9 512 #define C2POW10 1024 #define C2POW11 2048 #define C2POW12 4096 #define C2POW13 8192 #define C2POW14 16384 #define C2POW15 32768 #define C2POW16 65536 #define C2POW17 131072 #define C2POW18 262144 #define C2POW19 524288 #define C2POW20 1048576 #define C2POW21 2097152 #define C2POW22 4194304 #define C2POW23 8388608 #define C2POW24 16777216 #define C2POW25 33554432 #define C2POW26 67108864 #define C2POW27 134217728 #define C2POW28 268435456 #define C2POW29 536870912 #define C2POW30 1073741824 #define C2POW31 2147483648 #define C2POW32 4294967296 #define C2POW33 8589934592 #define C2POW34 17179869184 #define C2POW35 34359738368 #define C2POW36 68719476736 #define C2POW37 137438953472 #define C2POW38 274877906944 #define C2POW39 549755813888 #define C2POW40 1099511627776 #define C2POW41 2199023255552 #define C2POW42 4398046511104 #define C2POW43 8796093022208 #define C2POW44 17592186044416 #define C2POW45 35184372088832 #define C2POW46 70368744177664 #define C2POW47 140737488355328 #define C2POW48 281474976710656 #define C2POW49 562949953421312 #define C2POW50 1125899906842624 #define C2POW51 2251799813685248 #define C2POW52 4503599627370496 #define FLOAT_0_SNAP (FLOAT)(C2POW23+C2POW22) #define FLOAT_4_SNAP (FLOAT)(C2POW19+C2POW18) #define FLOAT_5_SNAP (FLOAT)(C2POW18+C2POW17) #define FLOAT_8_SNAP (FLOAT)(C2POW15+C2POW14) #define FLOAT_17_SNAP (FLOAT)(C2POW6 +C2POW5 ) #define FLOAT_18_SNAP (FLOAT)(C2POW5 +C2POW4 ) #define DOUBLE_0_SNAP (DOUBLE)(C2POW52+C2POW51) #define DOUBLE_4_SNAP (DOUBLE)(C2POW48+C2POW47) #define DOUBLE_5_SNAP (DOUBLE)(C2POW47+C2POW46) #define DOUBLE_8_SNAP (DOUBLE)(C2POW44+C2POW43) #define DOUBLE_17_SNAP (DOUBLE)(C2POW35+C2POW34) #define DOUBLE_18_SNAP (DOUBLE)(C2POW34+C2POW33) //----------------------------------------------------------------------------- // // Floating point related macros // //----------------------------------------------------------------------------- #define COSF(fV) ((FLOAT)cos((double)(fV))) #define SINF(fV) ((FLOAT)sin((double)(fV))) #define SQRTF(fV) ((FLOAT)sqrt((double)(fV))) #define POWF(fV, fE) ((FLOAT)pow((double)(fV), (double)(fE))) #ifdef _X86_ #define FLOAT_CMP_POS(fa, op, fb) (AS_INT32(fa) op AS_INT32(fb)) #define FLOAT_CMP_PONE(flt, op) (AS_INT32(flt) op INT32_FLOAT_ONE) __inline int FLOAT_GTZ(FLOAT f) { VAL32 fi; fi.f = f; return fi.i > 0; } __inline int FLOAT_LTZ(FLOAT f) { VAL32 fi; fi.f = f; return fi.u > 0x80000000; } __inline int FLOAT_GEZ(FLOAT f) { VAL32 fi; fi.f = f; return fi.u <= 0x80000000; } __inline int FLOAT_LEZ(FLOAT f) { VAL32 fi; fi.f = f; return fi.i <= 0; } __inline int FLOAT_EQZ(FLOAT f) { VAL32 fi; fi.f = f; return (fi.u & 0x7fffffff) == 0; } __inline int FLOAT_NEZ(FLOAT f) { VAL32 fi; fi.f = f; return (fi.u & 0x7fffffff) != 0; } // Strip sign bit in integer. __inline FLOAT ABSF(FLOAT f) { VAL32 fi; fi.f = f; fi.u &= 0x7fffffff; return fi.f; } // Requires chop rounding. __inline INT FTOI(FLOAT f) { LARGE_INTEGER i; __asm { fld f fistp i } return i.LowPart; } #else #define FLOAT_GTZ(flt) ((flt) > g_fZero) #define FLOAT_LTZ(flt) ((flt) < g_fZero) #define FLOAT_GEZ(flt) ((flt) >= g_fZero) #define FLOAT_LEZ(flt) ((flt) <= g_fZero) #define FLOAT_EQZ(flt) ((flt) == g_fZero) #define FLOAT_NEZ(flt) ((flt) != g_fZero) #define FLOAT_CMP_POS(fa, op, fb) ((fa) op (fb)) #define FLOAT_CMP_PONE(flt, op) ((flt) op g_fOne) #define ABSF(f) ((FLOAT)fabs((double)(f))) #define FTOI(f) ((INT)(f)) #endif // _X86_ //----------------------------------------------------------------------------- // // macro wrappers for memory allocation - wrapped around global function ptrs // set by RefRastSetMemif // //----------------------------------------------------------------------------- #define MEMALLOC(_size) ((*g_pfnMemAlloc)(_size)) #define MEMFREE(_ptr) { if (NULL != (_ptr)) { ((*g_pfnMemFree)(_ptr)); } } #define MEMREALLOC(_ptr,_size) ((*g_pfnMemReAlloc)((_ptr),(_size))) ////////////////////////////////////////////////////////////////////////////////// // // // Utility Functions // // // ////////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // debug printf support // //----------------------------------------------------------------------------- void RRDebugPrintfL( int iLevel, const char* pszFormat, ... ); void RRDebugPrintf( const char* pszFormat, ... ); #define _DPF_IF 0x0001 #define _DPF_INPUT 0x0002 #define _DPF_SETUP 0x0004 #define _DPF_RAST 0x0008 #define _DPF_TEX 0x0010 #define _DPF_PIX 0x0020 #define _DPF_FRAG 0x0040 #define _DPF_STATS 0x0080 #define _DPF_DRV 0x0100 #define _DPF_TNL 0x0200 #define _DPF_ANY 0xffff #define _DPF_TEMP 0x8000 #ifdef DBG #define DPFRR RRDebugPrintfL #define DPFM( _level, _mask, _message) \ if ((g_iDPFLevel >= (_level)) && (g_uDPFMask & (_DPF_##_mask))) { \ RRDebugPrintf ## _message; \ } #else #pragma warning(disable:4002) #define DPFRR() #define DPFM( _level, _mask, _message) #endif //----------------------------------------------------------------------------- // // assert macros and reporting functions // //----------------------------------------------------------------------------- // ASSERT with simple string #undef _ASSERT #define _ASSERT( value, string ) \ if ( !(value) ) { \ RRAssertReport( string, __FILE__, __LINE__ ); \ } // ASSERT with formatted string - note extra parenthesis on report // usage: _ASSERTf(foo,("foo is %d",foo)) #undef _ASSERTf #define _ASSERTf(value,report) \ if (!(value)) { \ char __sz__FILE__[] = __FILE__; \ RRAssertReportPrefix(__sz__FILE__,__LINE__); \ RRAssertReportMessage ## report; \ } // ASSERT with action field #undef _ASSERTa #define _ASSERTa(value,string,action) \ if (!(value)) { \ RRAssertReport(string,__FILE__,__LINE__); \ action \ } // ASSERTf with action field #undef _ASSERTfa #define _ASSERTfa(value,report,action) \ if (!(value)) { \ RRAssertReportPrefix(__FILE__,__LINE__); \ RRAssertReportMessage ## report; \ action \ } extern void RRAssertReport( const char* pszString, const char* pszFile, int iLine ); extern void RRAssertReportPrefix( const char* pszFile, int iLine ); extern void RRAssertReportMessage( const char* pszFormat, ... ); //----------------------------------------------------------------------------- // // bit twiddling utilities // //----------------------------------------------------------------------------- extern INT32 CountSetBits( UINT32 uVal, INT32 nBits ); extern INT32 FindFirstSetBit( UINT32 uVal, INT32 nBits ); extern INT32 FindMostSignificantSetBit( UINT32 uVal, INT32 nBits ); extern INT32 FindLastSetBit( UINT32 uVal, INT32 nBits ); // TRUE if integer is a power of 2 inline BOOL IsPowerOf2( INT32 i ) { if ( i <= 0 ) return 0; return ( 0x0 == ( i & (i-1) ) ); } //----------------------------------------------------------------------------- // // multiply/add routines & macros for unsigned 8 bit values, signed 16 bit values // // These are not currently used, but the Mult8x8Scl is an interesting routine // for hardware designers to look at. This does a 8x8 multiply combined with // a 256/255 scale which accurately solves the "0xff * value = value" issue. // There are refinements on this (involving half-adders) which are not easily // representable in C. Credits to Steve Gabriel and Jim Blinn. // //----------------------------------------------------------------------------- // straight 8x8 unsigned multiply returning 8 bits, tossing fractional // bits (no rounding) inline UINT8 Mult8x8( const UINT8 uA, const UINT8 uB ) { UINT16 uA16 = (UINT16)uA; UINT16 uB16 = (UINT16)uB; UINT16 uRes16 = uA16*uB16; UINT8 uRes8 = (UINT8)(uRes16>>8); return uRes8; } // 8x8 unsigned multiply with ff*val = val scale adjustment (scale by (256/255)) inline UINT8 Mult8x8Scl( const UINT8 uA, const UINT8 uB ) { UINT16 uA16 = (UINT16)uA; UINT16 uB16 = (UINT16)uB; UINT16 uRes16 = uA16*uB16; uRes16 += 0x0080; uRes16 += (uRes16>>8); UINT8 uRes8 = (UINT8)(uRes16>>8); return uRes8; } // 8x8 saturated addition - result > 0xff returns 0xff inline UINT8 SatAdd8x8( const UINT8 uA, const UINT8 uB ) { UINT16 uA16 = (UINT16)uA; UINT16 uB16 = (UINT16)uB; UINT16 uRes16 = uA16+uB16; UINT8 uRes8 = (uRes16 > 0xff) ? (0xff) : ((UINT8)uRes16); return uRes8; } //---------------------------------------------------------------------------- // // IntLog2 // // Do a quick, integer log2 for exact powers of 2. // //---------------------------------------------------------------------------- inline UINT32 FASTCALL IntLog2(UINT32 x) { UINT32 y = 0; x >>= 1; while(x != 0) { x >>= 1; y++; } return y; } ////////////////////////////////////////////////////////////////////////////// // FVF related macros ////////////////////////////////////////////////////////////////////////////// #define FVF_TRANSFORMED(dwFVF) ((dwFVF & D3DFVF_POSITION_MASK) == D3DFVF_XYZRHW) #define FVF_TEXCOORD_NUMBER(dwFVF) \ (((dwFVF) & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT) ////////////////////////////////////////////////////////////////////////////// // State Override Macros ////////////////////////////////////////////////////////////////////////////// #define IS_OVERRIDE(type) ((DWORD)(type) > D3DSTATE_OVERRIDE_BIAS) #define GET_OVERRIDE(type) ((DWORD)(type) - D3DSTATE_OVERRIDE_BIAS) #define STATESET_MASK(set, state) \ (set).bits[((state) - 1) >> RRSTATEOVERRIDE_DWORD_SHIFT] #define STATESET_BIT(state) (1 << (((state) - 1) & (RRSTATEOVERRIDE_DWORD_BITS - 1))) #define STATESET_ISSET(set, state) \ STATESET_MASK(set, state) & STATESET_BIT(state) #define STATESET_SET(set, state) \ STATESET_MASK(set, state) |= STATESET_BIT(state) #define STATESET_CLEAR(set, state) \ STATESET_MASK(set, state) &= ~STATESET_BIT(state) #define STATESET_INIT(set) memset(&(set), 0, sizeof(set)) //--------------------------------------------------------------------- // GetFVFVertexSize: // Computes total vertex size in bytes for given fvf // including the texture coordinates //--------------------------------------------------------------------- __inline DWORD GetFVFVertexSize( UINT64 qwFVF ) { // Texture formats size 00 01 10 11 static DWORD dwTextureSize[4] = {2*4, 3*4, 4*4, 4}; DWORD dwSize = 3 << 2; switch( qwFVF & D3DFVF_POSITION_MASK ) { case D3DFVF_XYZRHW: dwSize += 4; break; case D3DFVF_XYZB1: dwSize += 1*4; break; case D3DFVF_XYZB2: dwSize += 2*4; break; case D3DFVF_XYZB3: dwSize += 3*4; break; case D3DFVF_XYZB4: dwSize += 4*4; break; case D3DFVF_XYZB5: dwSize += 5*4; break; } if (qwFVF & D3DFVF_NORMAL) dwSize += 3*4; if (qwFVF & D3DFVF_RESERVED1) dwSize += 4; if (qwFVF & D3DFVF_DIFFUSE) dwSize += 4; if (qwFVF & D3DFVF_SPECULAR) dwSize += 4; // Texture coordinates DWORD dwNumTexCoord = (DWORD)(FVF_TEXCOORD_NUMBER(qwFVF)); DWORD dwTextureFormats = (DWORD)qwFVF >> 16; if (dwTextureFormats == 0) { dwSize += dwNumTexCoord * 2 * 4; } else { for (DWORD i=0; i < dwNumTexCoord; i++) { dwSize += dwTextureSize[dwTextureFormats & 3]; dwTextureFormats >>= 2; } } if (qwFVF & D3DFVF_S) dwSize += 4; if (qwFVF & D3DFVFP_EYENORMAL) dwSize += 3*4; if (qwFVF & D3DFVFP_EYEXYZ) dwSize += 3*4; return dwSize; } HRESULT RRFVFCheckAndStride( DWORD dwFVF, DWORD* pdwStride ); /////////////////////////////////////////////////////////////////////////////// // Matrix and Vector routines /////////////////////////////////////////////////////////////////////////////// inline void ReverseVector(const D3DVECTOR &in, D3DVECTOR &out) { out.x = -in.x; out.y = -in.y; out.z = -in.z; } inline void AddVector(const D3DVECTOR &v1, const D3DVECTOR &v2, D3DVECTOR &out) { out.x = v1.x + v2.x; out.y = v1.y + v2.y; out.z = v1.z + v2.z; } inline void SubtractVector(const D3DVECTOR &v1, const D3DVECTOR &v2, D3DVECTOR &out) { out.x = v1.x - v2.x; out.y = v1.y - v2.y; out.z = v1.z - v2.z; } inline void SetIdentity(D3DMATRIX &m) { m._11 = m._22 = m._33 = m._44 = 1.0f; m._12 = m._13 = m._14 = 0.0f; m._21 = m._23 = m._24 = 0.0f; m._31 = m._32 = m._34 = 0.0f; m._41 = m._42 = m._43 = 0.0f; } inline void SetNull(D3DMATRIX &m) { m._11 = m._22 = m._33 = m._44 = 0.0f; m._12 = m._13 = m._14 = 0.0f; m._21 = m._23 = m._24 = 0.0f; m._31 = m._32 = m._34 = 0.0f; m._41 = m._42 = m._43 = 0.0f; } inline void CopyMatrix(D3DMATRIX &s, D3DMATRIX &d) { d._11 = s._11; d._12 = s._12; d._13 = s._13; d._14 = s._14; d._21 = s._21; d._22 = s._22; d._23 = s._23; d._24 = s._24; d._31 = s._31; d._32 = s._32; d._33 = s._33; d._34 = s._34; d._41 = s._41; d._42 = s._42; d._43 = s._43; d._44 = s._44; } inline D3DVALUE SquareMagnitude (const D3DVECTOR& v) { return v.x*v.x + v.y*v.y + v.z*v.z; } inline D3DVALUE Magnitude (const D3DVECTOR& v) { return (D3DVALUE) sqrt(SquareMagnitude(v)); } inline D3DVECTOR Normalize (const D3DVECTOR& v) { D3DVECTOR nv = {0.0f, 0.0f, 0.0f}; D3DVALUE mag = Magnitude(v); nv.x = v.x/mag; nv.y = v.y/mag; nv.z = v.z/mag; return nv; } inline void Normalize (D3DVECTOR& v) { D3DVALUE mag = Magnitude(v); v.x = v.x/mag; v.y = v.y/mag; v.z = v.z/mag; return; } inline D3DVECTOR CrossProduct (const D3DVECTOR& v1, const D3DVECTOR& v2) { D3DVECTOR result; result.x = v1.y*v2.z - v1.z*v2.y; result.y = v1.z*v2.x - v1.x*v2.z; result.z = v1.x*v2.y - v1.y*v2.x; return result; } inline D3DVALUE DotProduct (const D3DVECTOR& v1, const D3DVECTOR& v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; } //--------------------------------------------------------------------- // Multiplies vector (x,y,z,w) by a 4x4 matrix transposed, // producing a homogeneous vector // // res and v should not be the same //--------------------------------------------------------------------- inline void XformPlaneBy4x4Transposed(RRVECTOR4 *v, D3DMATRIX *m, RRVECTOR4 *res) { res->x = v->x*m->_11 + v->y*m->_12 + v->z*m->_13 + v->w*m->_14; res->y = v->x*m->_21 + v->y*m->_22 + v->z*m->_23 + v->w*m->_24; res->z = v->x*m->_31 + v->y*m->_32 + v->z*m->_33 + v->w*m->_34; res->w = v->x*m->_41 + v->y*m->_42 + v->z*m->_43 + v->w*m->_44; } //--------------------------------------------------------------------- // Multiplies vector (x,y,z,w) by 4x4 matrix, producing a homogeneous vector // // res and v should not be the same //--------------------------------------------------------------------- inline void XformPlaneBy4x4(RRVECTOR4 *v, D3DMATRIX *m, RRVECTOR4 *res) { res->x = v->x*m->_11 + v->y*m->_21 + v->z*m->_31 + v->w*m->_41; res->y = v->x*m->_12 + v->y*m->_22 + v->z*m->_32 + v->w*m->_42; res->z = v->x*m->_13 + v->y*m->_23 + v->z*m->_33 + v->w*m->_43; res->w = v->x*m->_14 + v->y*m->_24 + v->z*m->_34 + v->w*m->_44; } //--------------------------------------------------------------------- // Multiplies vector (x,y,z,1) by 4x4 matrix, producing a homogeneous vector // // res and v should not be the same //--------------------------------------------------------------------- inline void XformBy4x4(D3DVECTOR *v, D3DMATRIX *m, RRVECTOR4 *res) { res->x = v->x*m->_11 + v->y*m->_21 + v->z*m->_31 + m->_41; res->y = v->x*m->_12 + v->y*m->_22 + v->z*m->_32 + m->_42; res->z = v->x*m->_13 + v->y*m->_23 + v->z*m->_33 + m->_43; res->w = v->x*m->_14 + v->y*m->_24 + v->z*m->_34 + m->_44; } //--------------------------------------------------------------------- // Multiplies vector (x,y,z,1) by 4x3 matrix // // res and v should not be the same //--------------------------------------------------------------------- inline void XformBy4x3(D3DVECTOR *v, D3DMATRIX *m, D3DVECTOR *res) { res->x = v->x*m->_11 + v->y*m->_21 + v->z*m->_31 + m->_41; res->y = v->x*m->_12 + v->y*m->_22 + v->z*m->_32 + m->_42; res->z = v->x*m->_13 + v->y*m->_23 + v->z*m->_33 + m->_43; } //--------------------------------------------------------------------- // Multiplies vector (x,y,z) by 3x3 matrix // // res and v should not be the same //--------------------------------------------------------------------- inline void Xform3VecBy3x3(D3DVECTOR *v, D3DMATRIX *m, D3DVECTOR *res) { res->x = v->x*m->_11 + v->y*m->_21 + v->z*m->_31; res->y = v->x*m->_12 + v->y*m->_22 + v->z*m->_32; res->z = v->x*m->_13 + v->y*m->_23 + v->z*m->_33; } //--------------------------------------------------------------------- // This function uses Cramer's Rule to calculate the matrix inverse. // See nt\private\windows\opengl\serever\soft\so_math.c // // Returns: // 0 - if success // -1 - if input matrix is singular //--------------------------------------------------------------------- int Inverse4x4(D3DMATRIX *src, D3DMATRIX *inverse); //////////////////////////////////////////////////////////////////////// // // Macros used to access DDRAW surface info. // //////////////////////////////////////////////////////////////////////// #define DDSurf_Width(lpLcl) ( (lpLcl)->lpGbl->wWidth ) #define DDSurf_Pitch(lpLcl) ( (lpLcl)->lpGbl->lPitch ) #define DDSurf_Height(lpLcl) ( (lpLcl)->lpGbl->wHeight ) #define DDSurf_BitDepth(lpLcl) \ ( (lpLcl->dwFlags & DDRAWISURF_HASPIXELFORMAT) ? \ (lpLcl->lpGbl->ddpfSurface.dwRGBBitCount) : \ (lpLcl->lpGbl->lpDD->vmiData.ddpfDisplay.dwRGBBitCount) \ ) #define DDSurf_PixFmt(lpLcl) \ ( ((lpLcl)->dwFlags & DDRAWISURF_HASPIXELFORMAT) ? \ ((lpLcl)->lpGbl->ddpfSurface) : \ ((lpLcl)->lpGbl->lpDD->vmiData.ddpfDisplay) \ ) #define VIDEO_MEMORY(pDDSLcl) \ (!((pDDSLcl)->lpGbl->dwGlobalFlags & DDRAWISURFGBL_SYSMEMREQUESTED)) #define SURFACE_LOCKED(pDDSLcl) \ ((pDDSLcl)->lpGbl->dwUsageCount > 0) #define SURFACE_MEMORY(surfLcl) \ (LPVOID)((surfLcl)->lpGbl->fpVidMem) //--------------------------------------------------------------------- // DDraw extern functions //--------------------------------------------------------------------- extern "C" HRESULT WINAPI DDInternalLock( LPDDRAWI_DDRAWSURFACE_LCL this_lcl, LPVOID* lpBits ); extern "C" HRESULT WINAPI DDInternalUnlock( LPDDRAWI_DDRAWSURFACE_LCL this_lcl ); extern "C" HRESULT WINAPI DDGetAttachedSurfaceLcl( LPDDRAWI_DDRAWSURFACE_LCL this_lcl, LPDDSCAPS2 lpDDSCaps, LPDDRAWI_DDRAWSURFACE_LCL *lplpDDAttachedSurfaceLcl); extern "C" LPDDRAWI_DDRAWSURFACE_LCL WINAPI GetDDSurfaceLocal( LPDDRAWI_DIRECTDRAW_LCL this_lcl, DWORD handle, BOOL* isnew ); /////////////////////////////////////////////////////////////////////////////// #endif // _RRUTIL_HPP
31.94186
96
0.484601
npocmaka
8fdac102c5f67124d3723a13e9d45c018ddda0e4
18,891
cpp
C++
src/client/SkinnedGUI/CommonDialogs.cpp
JiPRA/openlierox
1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc
[ "CECILL-B" ]
192
2015-02-13T14:53:59.000Z
2022-03-29T11:18:58.000Z
src/client/SkinnedGUI/CommonDialogs.cpp
JiPRA/openlierox
1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc
[ "CECILL-B" ]
48
2015-01-06T22:00:53.000Z
2022-01-15T18:22:46.000Z
src/client/SkinnedGUI/CommonDialogs.cpp
JiPRA/openlierox
1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc
[ "CECILL-B" ]
51
2015-01-16T00:55:16.000Z
2022-02-05T03:09:30.000Z
#include "LieroX.h" #include "SkinnedGUI/CommonDialogs.h" #include "SkinnedGUI/CButton.h" #include "SkinnedGUI/CTabControl.h" #include "SkinnedGUI/CLabel.h" #include "SkinnedGUI/CTextbox.h" #include "SkinnedGUI/CSlider.h" #include "SkinnedGUI/CCheckbox.h" #include "SkinnedGUI/CListview.h" #include "MathLib.h" #include "FindFile.h" #include "StringUtils.h" #include "CGameScript.h" #include "CWpnRest.h" #include "AuxLib.h" #include "Options.h" #include "CodeAttributes.h" namespace SkinnedGUI { #define MAX_LOADING_TIME 500 #define DEFAULT_LOADING_TIME 100 ////////////////// // Create CMessageBox::CMessageBox(CContainerWidget *parent, const std::string &title, const std::string &text, MessageBoxType type) : CDialog("_MessageBox", parent, title, true) { // Dimensions int w = MIN(VideoPostProcessor::get()->screenWidth(), GetTextWidth(cFont, text)); int h = MIN(VideoPostProcessor::get()->screenHeight(), GetTextHeight(cFont, text)); Resize((VideoPostProcessor::get()->screenWidth() - w)/2, (VideoPostProcessor::get()->screenHeight() - h)/2, w, h); iType = type; sText = text; CLEAR_EVENT(OnReturn); // Buttons if (iType == LMB_OK) { btnOk = new CButton("_Ok", this, "OK"); btnYes = btnNo = NULL; } else { btnYes = new CButton("_Yes", this, "Yes"); btnNo = new CButton("_No", this, "No"); btnOk = NULL; } } /////////////////////// // Close (internal) void CMessageBox::CloseBox(int result) { CDialog::Close(); CALL_EVENT(OnReturn, (this, result)); } /////////////////////// // Key down event int CMessageBox::DoKeyDown(UnicodeChar c, int keysym, const ModifiersState& modstate) { switch (keysym) { case SDLK_ESCAPE: CloseBox(iType == LMB_OK ? MBR_OK : MBR_NO); break; case SDLK_RETURN: case SDLK_KP_ENTER: CloseBox(iType == LMB_OK ? MBR_OK : MBR_YES); break; } CDialog::DoKeyDown(c, keysym, modstate); return WID_PROCESSED; } //////////////////////// // Button click event void CMessageBox::OnButtonClick(CWidget *sender, int x, int y, int dx, int dy, int button) { int result = MBR_OK; if (sender->getName() == "msb_Ok") result = MBR_OK; else if (sender->getName() == "msb_Yes") result = MBR_YES; else if (sender->getName() == "msb_No") result = MBR_NO; else return; CloseBox(result); } //////////////////////// // Draw the messagebox void CMessageBox::DoRepaint() { CDialog::DoRepaint(); // Draw the text SDL_Rect r = getClientRect(); DrawGameText(bmpBuffer.get(), sText, cFont, CTextProperties(&r, algCenter, algTop)); } // // File dialog (abstract class) // // File adder functor class FileDialogAdder { public: CListview* listview; std::string extension; FileDialogAdder(CListview* lv_, const std::string& ext) : listview(lv_), extension(ext) {} INLINE bool operator() (const std::string& f) { if(stringcaseequal(GetFileExtension(f), extension)) { std::string fname = GetBaseFilename(f); std::string name = fname.substr(0, fname.size() - 4); // remove the extension, the size calcing is safe here if(!listview->getItem(fname)) { listview->AddItem(fname); listview->AddTextSubitem(name); } } return true; } }; ///////////////////////////// // Constructor CFileDialog::CFileDialog(COMMON_PARAMS, const std::string &title, const std::string &directory, const std::string &extension) : CDialog(name, parent, title) { CLEAR_EVENT(OnConfirm); sDirectory = directory; sExtension = extension; // Append a slash if (*sDirectory.rbegin() != '\\' && *sDirectory.rbegin() != '/') sDirectory += '/'; btnOk = new CButton("_Ok", this, "OK"); btnCancel = new CButton("_Cancel", this, "Cancel"); lsvFileList = new CListview("_FileList", this); // Fill the listview FileDialogAdder adder(lsvFileList, sExtension); FindFiles(adder, sDirectory, false, FM_REG); } // // File load dialog // /////////////////// // Constructor CFileLoadDialog::CFileLoadDialog(COMMON_PARAMS, const std::string &title, const std::string &directory, const std::string &extension) : CFileDialog(name, parent, title, directory, extension) { } /////////////////// // Confirm click void CFileLoadDialog::OkClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { std::string file = lsvFileList->getSelectedSIndex(); if (file.size()) { CALL_EVENT(OnConfirm, (this, sDirectory + file)); Close(); } } ////////////////// // Cancel click void CFileLoadDialog::CancelClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { Close(); } ///////////////// // Double click on the file list void CFileLoadDialog::FileListDoubleClick(CListview *sender, CListviewItem *item, int index) { CALL_EVENT(OnConfirm, (this, sDirectory + item->getSIndex())); Close(); } // // File save dialog // /////////////////// // Constructor CFileSaveDialog::CFileSaveDialog(COMMON_PARAMS, const std::string &title, const std::string &directory, const std::string &extension) : CFileDialog(name, parent, title, directory, extension) { txtFileName = new CTextbox("_FileName", this); } //////////////////// // Get the file name for saving std::string CFileSaveDialog::GetFileName() { std::string file = txtFileName->getText(); if (!file.size()) return ""; // Test if the user added the extension, if not, add it bool have_ext = false; if (file.size() >= 4) have_ext = stringcaseequal(file.substr(file.size() - 4, 4), "." + sExtension); if (!have_ext) file += "." + sExtension; return file; } ////////////////////// // Confirm click void CFileSaveDialog::OkClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { std::string file = GetFileName(); if (IsFileAvailable(file, false)) { dlgConfirmOverwrite = new CMessageBox(this, "Confirm Overwrite", "The file already exists, overwrite?", LMB_YESNO); return; } if (file.size()) { CALL_EVENT(OnConfirm, (this, sDirectory + file)); Close(); } } ///////////////////// // Cancel click void CFileSaveDialog::CancelClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { Close(); } ///////////////////// // Double click in the filelist void CFileSaveDialog::FileListDoubleClick(CListview *sender, CListviewItem *item, int index) { dlgConfirmOverwrite = new CMessageBox(this, "Confirm Overwrite", "The file already exists, overwrite?", LMB_YESNO); } ////////////////////// // Listview selection change void CFileSaveDialog::FileListChange(CListview *sender, CListviewItem *newitem, int newindex, bool &cancel) { txtFileName->setText(newitem->getName()); } ////////////////////// // Overwrite confirm close void CFileSaveDialog::MessageBoxClose(CMessageBox *sender, int result) { if (result == MBR_YES) { std::string file = GetFileName(); if (file.size()) CALL_EVENT(OnConfirm, (this, file)); Close(); } } // // Game settings dialog // //////////////////// // Constructor CGameSettingsDialog::CGameSettingsDialog(COMMON_PARAMS) : CDialog(name, parent, "Game Settings") { // Default buttons btnOk = new CButton("_Ok", this, "OK"); btnDefault = new CButton("_Default", this, "Default"); tbcMain = new CTabControl("_MainTabControl", this); // Setup the tab control CTab *tbGeneral = new CTab("_General", NULL, "General"); CTab *tbBonus = new CTab("_Bonus", NULL, "Bonus"); CGuiSkinnedLayout *pgGeneral = tbcMain->AddBlankPage(tbGeneral); CGuiSkinnedLayout *pgBonus = tbcMain->AddBlankPage(tbBonus); // Setup events SET_BTNCLICK(btnOk, &CGameSettingsDialog::OkClick); SET_BTNCLICK(btnDefault, &CGameSettingsDialog::DefaultClick); // Add the widgets // // General tab // // Lives new CLabel(STATIC, pgGeneral, "Lives"); txtLives = new CTextbox("_Lives", pgGeneral); txtLives->setMax(6); // Max kills new CLabel(STATIC, pgGeneral, "Max Kills"); txtMaxKills = new CTextbox("_MaxKills", pgGeneral); txtMaxKills->setMax(6); // Loading time new CLabel(STATIC, pgGeneral, "Loading Time"); sldLoadingTime = new CSlider("_LoadingTime", pgGeneral, MAX_LOADING_TIME); lblLoadingTime = new CLabel("_LoadingTimeLabel", pgGeneral, ""); // Time limit new CLabel(STATIC, pgGeneral, "Time limit, minutes"); txtTimeLimit = new CTextbox("_TimeLimit", pgGeneral); txtTimeLimit->setMax(3); // Respawn time new CLabel(STATIC, pgGeneral, "Respawn time, seconds"); txtRespawnTime = new CTextbox("_RespawnTime", pgGeneral); txtRespawnTime->setMax(3); // Empty weapons when respawning new CLabel(STATIC, pgGeneral, "Empty weapons\nwhen respawning"); chkEmptyWeapons = new CCheckbox("_EmptyWeapons", pgGeneral, false); // Respawn in waves new CLabel(STATIC, pgGeneral, "Respawn in waves"); chkWaveRespawn = new CCheckbox("_RespawnInWaves", pgGeneral, false); // Group teams new CLabel(STATIC, pgGeneral, "Group Teams"); chkGroupTeams = new CCheckbox("_GroupTeams", pgGeneral, false); // Suicide or teamkill decreases score new CLabel(STATIC, pgGeneral, "Suicide or teamkill\ndecreases score"); chkDecreaseScore = new CCheckbox("_DecreaseScore", pgGeneral, false); // // Bonus tab // // Bonuses on new CLabel(STATIC, pgBonus, "Bonuses"); chkBonusesOn = new CCheckbox("_BonusesOn", pgBonus, false); // Bonus spawn time new CLabel(STATIC, pgBonus, "Bonus Spawn AbsTime"); txtBonusSpawnTime = new CTextbox("_BonusSpawnTime", pgBonus); // Show bonus names new CLabel(STATIC, pgBonus, "Show Bonus Names"); chkShowBonusNames = new CCheckbox("_BonusNames", pgBonus, false); // Bonus life time new CLabel(STATIC, pgBonus, "Bonus Life AbsTime"); txtBonusLifeTime = new CTextbox("_BonusLifeTime", pgBonus); // Health to weapon chance new CLabel(STATIC, pgBonus, "Health"); new CLabel(STATIC, pgBonus, "Weapon"); lblHealthChance = new CLabel(STATIC, pgBonus, ""); lblWeaponChance = new CLabel(STATIC, pgBonus, ""); sldWeaponToHealthChance = new CSlider("_WeaponToHealth", pgBonus, 100); // Load LoadFromOptions(); } //////////////////// // Load the values from options void CGameSettingsDialog::LoadFromOptions() { // TODO: Hey, there should be some way without putting here all vars from options, it's just lame // Options system uses for() on CScriptableVars::Vars() array for that, that's the whole point of the scriptable vars // Lives if ((int)gameSettings[FT_Lives] >= 0) txtLives->setText(itoa((int)gameSettings[FT_Lives])); // Kills if ((int)gameSettings[FT_KillLimit] >= 0) txtLives->setText(itoa((int)gameSettings[FT_KillLimit])); // Loading time sldLoadingTime->setValue((int)gameSettings[FT_LoadingTime]); lblLoadingTime->setText(itoa((int)gameSettings[FT_LoadingTime])); // Time limit if ((float)gameSettings[FT_TimeLimit] > 0) txtTimeLimit->setText(ftoa(gameSettings[FT_TimeLimit])); // Respawn time txtRespawnTime->setText(ftoa(gameSettings[FT_RespawnTime])); // Empty weapons when respawning chkEmptyWeapons->setValue(gameSettings[FT_EmptyWeaponsOnRespawn]); // Group teams chkGroupTeams->setValue(gameSettings[FT_RespawnGroupTeams]); // Suicide or teamkill decreases score chkDecreaseScore->setValue(gameSettings[FT_SuicideDecreasesScore]); // Bonuses on chkBonusesOn->setValue(gameSettings[FT_Bonuses]); // Bonus spawn time txtBonusSpawnTime->setText(ftoa(gameSettings[FT_BonusFreq])); // Show bonus names chkShowBonusNames->setValue(gameSettings[FT_ShowBonusName]); // Bonus life time txtBonusLifeTime->setText(ftoa(gameSettings[FT_BonusLife])); // Health to weapon chance sldWeaponToHealthChance->setValue((int)((float)gameSettings[FT_BonusHealthToWeaponChance]*100.0f)); lblHealthChance->setText(itoa(100 - sldWeaponToHealthChance->getValue()) + " %"); lblWeaponChance->setText(itoa(sldWeaponToHealthChance->getValue()) + " %"); } /////////////////////// // Save everything to tGameInfo and tLXOptions void CGameSettingsDialog::Save() { // Default to no setting #define _RESET_TO_DEF(i) tLXOptions->customSettings.isSet[i] = false _RESET_TO_DEF(FT_Lives); _RESET_TO_DEF(FT_KillLimit); _RESET_TO_DEF(FT_TimeLimit); _RESET_TO_DEF(FT_TagLimit); _RESET_TO_DEF(FT_RespawnTime); _RESET_TO_DEF(FT_Bonuses); _RESET_TO_DEF(FT_ShowBonusName); #undef _RESET_TO_DEF // // General // // Lives if(txtLives->getText().size()) gameSettings.overwrite[FT_Lives] = atoi(txtLives->getText()); // Max kills if(txtMaxKills->getText().size()) gameSettings.overwrite[FT_KillLimit] = atoi(txtMaxKills->getText()); // Loading time gameSettings.overwrite[FT_LoadingTime] = sldLoadingTime->getValue(); // Time limit if(txtTimeLimit->getText().size()) gameSettings.overwrite[FT_TimeLimit] = atof(txtTimeLimit->getText()); // Respawn time if(txtRespawnTime->getText().size()) gameSettings.overwrite[FT_RespawnTime] = atof(txtRespawnTime->getText()); // Group teams gameSettings.overwrite[FT_RespawnGroupTeams] = chkGroupTeams->getValue(); // Suicide and teamkill decrease score gameSettings.overwrite[FT_SuicideDecreasesScore] = chkDecreaseScore->getValue(); // Empty weapons on respawn gameSettings.overwrite[FT_EmptyWeaponsOnRespawn] = chkEmptyWeapons->getValue(); // // Bonuses // // Bonuses on gameSettings.overwrite[FT_Bonuses] = chkBonusesOn->getValue(); // Bonus spawn time if(txtBonusSpawnTime->getText().size()) gameSettings.overwrite[FT_BonusFreq] = atof(txtBonusSpawnTime->getText()); // Show bonus names gameSettings.overwrite[FT_ShowBonusName] = chkShowBonusNames->getValue(); // Bonus life time if(txtBonusLifeTime->getText().size()) gameSettings.overwrite[FT_BonusLife] = atof(txtBonusLifeTime->getText()); // Health to weapon chance gameSettings.overwrite[FT_BonusHealthToWeaponChance] = (float)sldWeaponToHealthChance->getValue() / 100.0f; } //////////////////////// // Set everything to default void CGameSettingsDialog::Default() { // // General // // Lives txtLives->setText("10"); // Max kills txtMaxKills->setText(""); // Loading time sldLoadingTime->setValue(100); // Time limit txtTimeLimit->setText(""); // Respawn time txtRespawnTime->setText("2.5"); // Respawn in waves chkWaveRespawn->setValue(false); // Group teams chkGroupTeams->setValue(false); // Suicide and teamkill decrease score chkDecreaseScore->setValue(false); // Empty weapons on respawn chkEmptyWeapons->setValue(false); // // Bonuses // // Bonuses on chkBonusesOn->setValue(true); // Bonus spawn time txtBonusSpawnTime->setText("30"); // Show bonus names chkShowBonusNames->setValue(true); // Bonus life time txtBonusLifeTime->setText("30"); // Health to weapon chance sldWeaponToHealthChance->setValue(50); } ///////////////// // OK button click void CGameSettingsDialog::OkClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { Save(); Close(); } ///////////////// // Default button click void CGameSettingsDialog::DefaultClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { Default(); } // // Weapon options dialog // static const std::string states[] = {"Enabled", "Bonus", "Banned"}; CWeaponOptionsDialog::CWeaponOptionsDialog(COMMON_PARAMS, const std::string& mod) : CDialog(name, parent, "Weapon Options") { // Create the widgets btnOk = new CButton("_Ok", this, "OK"); btnRandom = new CButton("_Random", this, "Random"); btnCycle = new CButton("_Cycle", this, "Reset"); btnLoad = new CButton("_Load", this, "Load"); btnSave = new CButton("_Save", this, "Save"); lsvRestrictions = new CListview("_WeaponList", this); // Events SET_BTNCLICK(btnOk, &CWeaponOptionsDialog::OkClick); SET_BTNCLICK(btnRandom, &CWeaponOptionsDialog::RandomClick); SET_BTNCLICK(btnCycle, &CWeaponOptionsDialog::CycleClick); SET_BTNCLICK(btnLoad, &CWeaponOptionsDialog::LoadClick); SET_BTNCLICK(btnSave, &CWeaponOptionsDialog::SaveClick); SET_LSVITEMCLICK(lsvRestrictions, &CWeaponOptionsDialog::ItemClick); // Allocate gamescript & weapon restrictions cGameScript = new CGameScript(); cRestrictionList = new CWpnRest(); // Load the gamescript and apply the restrictions cRestrictionList->loadList("cfg/wpnrest.dat", ""); if (cGameScript->Load(mod)) cRestrictionList->updateList(cGameScript->GetWeaponList()); UpdateListview(); } //////////////// // Destructor CWeaponOptionsDialog::~CWeaponOptionsDialog() { delete cGameScript; delete cRestrictionList; } // TODO: fix that /////////////////////// // Updates the listview void CWeaponOptionsDialog::UpdateListview() { // Clear lsvRestrictions->Clear(); // Fill the listview int i = 0; for_each_iterator(wpnrest_t, it, cRestrictionList->getList()) { if(cGameScript->weaponExists(it->get().szName)) { lsvRestrictions->AddItem(it->get().szName, i); lsvRestrictions->AddTextSubitem(it->get().szName); lsvRestrictions->AddTextSubitem(states[CLAMP(it->get().nState, 0, 2)]); } ++i; } } /////////////// // Confirm click void CWeaponOptionsDialog::OkClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { Close(); } ///////////////// // Cycle click void CWeaponOptionsDialog::CycleClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { cRestrictionList->cycleVisible(cGameScript->GetWeaponList()); } /////////////////// // Random click void CWeaponOptionsDialog::RandomClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { cRestrictionList->randomizeVisible(cGameScript->GetWeaponList()); } //////////////////// // Load click void CWeaponOptionsDialog::LoadClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { dlgLoadRest = new CFileLoadDialog("_LoadDialog", this, "Load Preset", "cfg/presets", "wps"); SET_FILEDLGCONFIRM(dlgLoadRest, &CWeaponOptionsDialog::LoadDialogConfirm); } ////////////////// // Save click void CWeaponOptionsDialog::SaveClick(CButton *sender, MouseButton button, const ModifiersState &modstate) { dlgSaveRest = new CFileSaveDialog("_SaveDialog", this, "Save Preset", "cfg/presets", "wps"); SET_FILEDLGCONFIRM(dlgSaveRest, &CWeaponOptionsDialog::SaveDialogConfirm); } //////////////////// // Confirmed the load dialog void CWeaponOptionsDialog::LoadDialogConfirm(CFileDialog *sender, const std::string &file) { cRestrictionList->loadList(file, cGameScript->directory()); cRestrictionList->updateList(cGameScript->GetWeaponList()); UpdateListview(); } /////////////////////// // Confirmed the save dialog void CWeaponOptionsDialog::SaveDialogConfirm(CFileDialog *sender, const std::string &file) { cRestrictionList->saveList(file); } /////////////////////// // Clicked on an item in the list void CWeaponOptionsDialog::ItemClick(CListview *sender, CListviewItem *item, int index) { // Update the listview CListviewSubitem *sub = item->getSubitem(1); if (!sub) return; // Get the list if( ! cRestrictionList->findWeapon(sub->getName()) ) return; // Change the state *cRestrictionList->findWeapon(sub->getName()) = (WpnRestrictionState) ((int(*cRestrictionList->findWeapon(sub->getName())) + 1) % 3); } } // namespace SkinnedGUI
26.948645
135
0.704727
JiPRA
8fdc6d6dc65687f8f0d242195602b31d2ea28ede
4,847
hpp
C++
OREData/ored/marketdata/todaysmarketcalibrationinfo.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
OREData/ored/marketdata/todaysmarketcalibrationinfo.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
OREData/ored/marketdata/todaysmarketcalibrationinfo.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2021 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file marketdata/todaysmarketcalibrationinfo.hpp \brief a container holding information on calibration results during the t0 market build \ingroup marketdata */ #pragma once #include <ql/math/array.hpp> #include <ql/time/date.hpp> #include <ql/time/period.hpp> #include <ql/utilities/null.hpp> #include <map> #include <string> #include <vector> namespace ore { namespace data { // yield curves struct YieldCurveCalibrationInfo { virtual ~YieldCurveCalibrationInfo() {} // default periods to determine pillarDates relative to asof const static std::vector<QuantLib::Period> defaultPeriods; std::string dayCounter; std::string currency; std::vector<QuantLib::Date> pillarDates; std::vector<double> zeroRates; std::vector<double> discountFactors; std::vector<double> times; }; struct PiecewiseYieldCurveCalibrationInfo : public YieldCurveCalibrationInfo { // ... add instrument types? }; struct FittedBondCurveCalibrationInfo : public YieldCurveCalibrationInfo { std::string fittingMethod; std::vector<double> solution; int iterations = 0; double costValue = QuantLib::Null<QuantLib::Real>(); double tolerance = QuantLib::Null<QuantLib::Real>(); std::vector<std::string> securities; std::vector<QuantLib::Date> securityMaturityDates; std::vector<double> marketPrices; std::vector<double> modelPrices; std::vector<double> marketYields; std::vector<double> modelYields; }; // inflation curves struct InflationCurveCalibrationInfo { virtual ~InflationCurveCalibrationInfo() {} std::string dayCounter; std::string calendar; QuantLib::Date baseDate; std::vector<QuantLib::Date> pillarDates; std::vector<double> times; }; struct ZeroInflationCurveCalibrationInfo : public InflationCurveCalibrationInfo { double baseCpi = 0.0; std::vector<double> zeroRates; std::vector<double> forwardCpis; }; struct YoYInflationCurveCalibrationInfo : public InflationCurveCalibrationInfo { std::vector<double> yoyRates; }; // fx, eq vols struct FxEqVolCalibrationInfo { virtual ~FxEqVolCalibrationInfo() {} std::string dayCounter; std::string calendar; std::string atmType; std::string deltaType; std::string longTermAtmType; std::string longTermDeltaType; std::string switchTenor; std::string riskReversalInFavorOf; std::string butterflyStyle; bool isArbitrageFree; std::vector<QuantLib::Date> expiryDates; std::vector<double> times; std::vector<std::string> deltas; std::vector<double> moneyness; std::vector<double> forwards; std::vector<std::vector<double>> moneynessGridStrikes; std::vector<std::vector<double>> moneynessGridProb; std::vector<std::vector<double>> moneynessGridImpliedVolatility; std::vector<std::vector<double>> deltaGridStrikes; std::vector<std::vector<double>> deltaGridProb; std::vector<std::vector<double>> deltaGridImpliedVolatility; std::vector<std::vector<bool>> moneynessGridCallSpreadArbitrage; std::vector<std::vector<bool>> moneynessGridButterflyArbitrage; std::vector<std::vector<bool>> moneynessGridCalendarArbitrage; std::vector<std::vector<bool>> deltaGridCallSpreadArbitrage; std::vector<std::vector<bool>> deltaGridButterflyArbitrage; std::vector<std::string> messages; }; // main container struct TodaysMarketCalibrationInfo { QuantLib::Date asof; // discount, index and yield curves std::map<std::string, boost::shared_ptr<YieldCurveCalibrationInfo>> yieldCurveCalibrationInfo; // equity dividend yield curves std::map<std::string, boost::shared_ptr<YieldCurveCalibrationInfo>> dividendCurveCalibrationInfo; // inflation curves std::map<std::string, boost::shared_ptr<InflationCurveCalibrationInfo>> inflationCurveCalibrationInfo; // fx vols std::map<std::string, boost::shared_ptr<FxEqVolCalibrationInfo>> fxVolCalibrationInfo; // eq vols std::map<std::string, boost::shared_ptr<FxEqVolCalibrationInfo>> eqVolCalibrationInfo; }; } // namespace data } // namespace ore
33.427586
106
0.744584
mrslezak
8fe3fd9e25449a7cb543fc2fec778b0d6f4729f5
5,754
cpp
C++
src/window.cpp
den-mentiei/hlsl-toy
ac80d90ff9d52abc80ba31c06bd5a048a8c08cde
[ "MIT" ]
4
2016-05-28T18:21:55.000Z
2020-01-13T01:39:28.000Z
src/window.cpp
den-mentiei/hlsl-toy
ac80d90ff9d52abc80ba31c06bd5a048a8c08cde
[ "MIT" ]
null
null
null
src/window.cpp
den-mentiei/hlsl-toy
ac80d90ff9d52abc80ba31c06bd5a048a8c08cde
[ "MIT" ]
null
null
null
#include "window.h" namespace toy { namespace { static const wchar_t* WINDOW_CLASS = L"hlsl-toy-class"; } // anonymous namespace LRESULT WINAPI Window::windows_proc(HWND handle, UINT message, WPARAM wparam, LPARAM lparam) { Window* window = reinterpret_cast<Window*>(::GetWindowLong(handle, GWL_USERDATA)); if (window == nullptr || window->is_closing()) { return DefWindowProcW(handle, message, wparam, lparam); } switch (message) { case WM_CLOSE: window->handle_close(); break; case WM_KEYDOWN: window->handle_key_down(static_cast<unsigned>(wparam)); break; case WM_LBUTTONDOWN: window->handle_mouse_down(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), Mouse::B_LEFT); break; case WM_RBUTTONDOWN: window->handle_mouse_down(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), Mouse::B_RIGHT); break; case WM_LBUTTONUP: window->handle_mouse_up(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), Mouse::B_LEFT); break; case WM_RBUTTONUP: window->handle_mouse_up(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), Mouse::B_RIGHT); break; case WM_MOUSEMOVE: window->handle_mouse_move(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16), wparam); break; case WM_SIZE: window->handle_resize(unsigned(lparam & 0xFFFF), unsigned(lparam >> 16)); break; default: return DefWindowProcW(handle, message, wparam, lparam); } return 0; } void Window::register_class(HINSTANCE instance) { WNDCLASSW window_class; window_class.style = 0; window_class.lpfnWndProc = Window::windows_proc; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = instance; window_class.hIcon = 0; window_class.hCursor = ::LoadCursor(nullptr, IDC_ARROW); window_class.hbrBackground = 0; window_class.lpszMenuName = 0; window_class.lpszClassName = WINDOW_CLASS; ::RegisterClassW(&window_class); } Window::Window() : _handle(0) , _is_closing(false) , _w(0) , _h(0) , _keypress_cb(nullptr) , _mouse_move_cb(nullptr) , _mouse_down_cb(nullptr) , _mouse_up_cb(nullptr) , _resize_cb(nullptr) {} Window::~Window() { if (_handle) { close(); } } void Window::open(HINSTANCE instance, const wchar_t* title, const unsigned w, const unsigned h) { RECT desktop_rect; ::GetClientRect(::GetDesktopWindow(), &desktop_rect); unsigned x = (desktop_rect.right - w) / 2; unsigned y = (desktop_rect.bottom - h) / 2; _w = w; _h = h; RECT window_rect; window_rect.left = x; window_rect.right = window_rect.left + w; window_rect.top = y; window_rect.bottom = window_rect.top + h; ::AdjustWindowRect(&window_rect, WS_OVERLAPPEDWINDOW, 0); _handle = ::CreateWindowW(WINDOW_CLASS, title, WS_OVERLAPPEDWINDOW, window_rect.left, window_rect.top, window_rect.right - window_rect.left, window_rect.bottom - window_rect.top, 0, 0, instance, 0); ::SetWindowLong(_handle, GWL_USERDATA, reinterpret_cast<LONG>(this)); ::ShowWindow(_handle, SW_SHOW); ::UpdateWindow(_handle); } void Window::close() { ::SetWindowLong(_handle, GWL_USERDATA, 0); ::DestroyWindow(_handle); _handle = 0; } void Window::update() { MSG message; while (::PeekMessage(&message, _handle, 0, 0, PM_REMOVE)) { ::TranslateMessage(&message); ::DispatchMessage(&message); } } bool Window::is_closing() const { return _is_closing; } HWND Window::handle() const { return _handle; } void Window::handle_close() { _is_closing = true; } void Window::handle_resize(const unsigned w, const unsigned h) { _w = w; _h = h; if (_resize_cb) { _resize_cb(w, h, _resize_cb_userdata); } } void Window::handle_key_down(const unsigned key_code) { if (_keypress_cb) { _keypress_cb(key_code, _keypress_cb_userdata); } } void Window::handle_mouse_move(const unsigned x, const unsigned y, unsigned state) { if (_mouse_move_cb) { Mouse::Button button; switch (state) { case MK_LBUTTON: button = Mouse::B_LEFT; break; case MK_RBUTTON: button = Mouse::B_RIGHT; break; default: button = Mouse::B_NONE; break; } _mouse_move_cb(x, y, button, _mouse_move_cb_userdata); } } void Window::handle_mouse_down(const unsigned x, const unsigned y, Mouse::Button button) { if (_mouse_down_cb) { _mouse_down_cb(x, y, button, _mouse_down_cb_userdata); } } void Window::handle_mouse_up(const unsigned x, const unsigned y, Mouse::Button button) { if (_mouse_up_cb) { _mouse_up_cb(x, y, button, _mouse_up_cb_userdata); } } unsigned Window::width() const { return _w; } unsigned Window::height() const { return _h; } void Window::set_keypress_callback(KeypressCallback callback, void* userdata) { _keypress_cb = callback; _keypress_cb_userdata = userdata; } void Window::set_mouse_move_callback(MouseCallback callback, void* userdata) { _mouse_move_cb = callback; _mouse_move_cb_userdata = userdata; } void Window::set_mouse_down_callback(MouseCallback callback, void* userdata) { _mouse_down_cb = callback; _mouse_down_cb_userdata = userdata; } void Window::set_mouse_up_callback(MouseCallback callback, void* userdata) { _mouse_up_cb = callback; _mouse_up_cb_userdata = userdata; } void Window::set_resize_callback(ResizeCallback callback, void* userdata) { _resize_cb = callback; _resize_cb_userdata = userdata; } std::wstring Window::choose_toy_file_dialog() { OPENFILENAMEW ofn; wchar_t buffer[MAX_PATH + 1]; buffer[0] = 0; memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = _handle; ofn.lpstrFile = buffer; ofn.nMaxFile = MAX_PATH; ofn.lpstrFilter = L"HLSL (*.hlsl)\0*.hlsl\0All (*.*)\0*.*\0"; ofn.nFilterIndex = 0; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if (TRUE == GetOpenFileNameW(&ofn)) return std::wstring(buffer); return std::wstring(); } } // namespace toy
24.176471
199
0.72367
den-mentiei
8fe5c70f858c945d7d1ac3ac9bc7f43eedde49b2
1,070
hpp
C++
ElectruxShorthandInterpretedLanguage/include/ExpressionEvaluator.hpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
6
2019-08-29T23:31:17.000Z
2021-11-14T20:35:47.000Z
ElectruxShorthandInterpretedLanguage/include/ExpressionEvaluator.hpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
null
null
null
ElectruxShorthandInterpretedLanguage/include/ExpressionEvaluator.hpp
Electrux/CCPP-Code
3c5e5b866cf050c11bced9651b112eb31dd2465d
[ "BSD-3-Clause" ]
1
2019-09-01T12:22:58.000Z
2019-09-01T12:22:58.000Z
#ifndef EXPRESSIONEVALUATOR_HPP #define EXPRESSIONEVALUATOR_HPP #include <string> #include <vector> #include "Errors.hpp" #include "DataTypes.hpp" ErrorTypes EvalExpression( const std::vector< DataType::Data > & dataline, const int & from, const int & to, Variable & result ); ErrorTypes GenPostfix( const std::vector< DataType::Data > & dataline, const int & from, const int & to, std::vector< DataType::Data > & postfix ); DataType::SymbolType GetOverallDataType( const std::vector< DataType::Data > & postfixexpr ); std::string CalculatePostfixExpression( const std::vector< DataType::Data > & postfixexpr, const DataType::SymbolType & exprtype ); std::string PerformOperation( const DataType::Data & op1, const DataType::Data & op2, const DataType::Data & op, const DataType::SymbolType & exprtype ); bool SetAllVariableValues( std::vector< DataType::Data > & postfixexpr ); bool IsValidDataType( const DataType::Data & data ); bool IsSymbol( const std::string & data ); int GetPrec( const std::string & symbol ); #endif // EXPRESSIONEVALUATOR_HPP
35.666667
131
0.740187
Electrux
8fe7ab9117a3eb60248e066eb12b55f75ff67fb9
5,536
hpp
C++
include/range/v3/view/reverse.hpp
anders-sjogren/range-v3
a7583aaf4e446d435867e54d58575d40c0575312
[ "MIT" ]
null
null
null
include/range/v3/view/reverse.hpp
anders-sjogren/range-v3
a7583aaf4e446d435867e54d58575d40c0575312
[ "MIT" ]
null
null
null
include/range/v3/view/reverse.hpp
anders-sjogren/range-v3
a7583aaf4e446d435867e54d58575d40c0575312
[ "MIT" ]
null
null
null
/// \file // Range v3 library // // Copyright Eric Niebler 2014 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_VIEW_REVERSE_HPP #define RANGES_V3_VIEW_REVERSE_HPP #include <utility> #include <iterator> #include <range/v3/range_fwd.hpp> #include <range/v3/size.hpp> #include <range/v3/begin_end.hpp> #include <range/v3/range_traits.hpp> #include <range/v3/range_adaptor.hpp> #include <range/v3/utility/meta.hpp> #include <range/v3/utility/static_const.hpp> #include <range/v3/view/view.hpp> namespace ranges { inline namespace v3 { /// \addtogroup group-views /// @{ template<typename Rng> struct reverse_view : range_adaptor<reverse_view<Rng>, Rng> { private: CONCEPT_ASSERT(BidirectionalIterable<Rng>()); CONCEPT_ASSERT(BoundedIterable<Rng>()); friend range_access; // A rather convoluted implementation to avoid the problem std::reverse_iterator // has adapting iterators that return references to internal data. struct adaptor : adaptor_base { private: reverse_view const *rng_; public: adaptor() = default; adaptor(reverse_view const &rng) : rng_(&rng) {} range_iterator_t<Rng> begin(reverse_view const &rng) const { auto it = ranges::end(rng.mutable_base()); ranges::advance(it, -1, ranges::begin(rng.mutable_base())); return it; } void next(range_iterator_t<Rng> &it) const { if(0 != ranges::advance(it, -1, ranges::begin(rng_->mutable_base()))) it = ranges::end(rng_->mutable_base()); } void prev(range_iterator_t<Rng> &it) const { if(0 != ranges::advance(it, 1, ranges::end(rng_->mutable_base()))) it = ranges::begin(rng_->mutable_base()); } CONCEPT_REQUIRES(RandomAccessIterable<Rng>()) void advance(range_iterator_t<Rng> &it, range_difference_t<Rng> n) const { if(n > 0) ranges::advance(it, -n + 1), this->next(it); else if(n < 0) this->prev(it), ranges::advance(it, -n - 1); } CONCEPT_REQUIRES(RandomAccessIterable<Rng>()) range_difference_t<Rng> distance_to(range_iterator_t<Rng> const &here, range_iterator_t<Rng> const &there, adaptor const &other_adapt) const { RANGES_ASSERT(rng_ == other_adapt.rng_); if(there == ranges::end(rng_->mutable_base())) return here == ranges::end(rng_->mutable_base()) ? 0 : (here - ranges::begin(rng_->mutable_base())) + 1; else if(here == ranges::end(rng_->mutable_base())) return (ranges::begin(rng_->mutable_base()) - there) - 1; return here - there; } }; adaptor begin_adaptor() const { return {*this}; } adaptor end_adaptor() const { return {*this}; } public: reverse_view() = default; reverse_view(Rng rng) : range_adaptor_t<reverse_view>{std::move(rng)} {} CONCEPT_REQUIRES(SizedIterable<Rng>()) range_size_t<Rng> size() const { return ranges::size(this->base()); } }; namespace view { struct reverse_fn { template<typename Rng> using Concept = meta::and_< BidirectionalIterable<Rng>, BoundedIterable<Rng>>; template<typename Rng, CONCEPT_REQUIRES_(Concept<Rng>())> reverse_view<all_t<Rng>> operator()(Rng && rng) const { return reverse_view<all_t<Rng>>{all(std::forward<Rng>(rng))}; } #ifndef RANGES_DOXYGEN_INVOKED // For error reporting template<typename Rng, CONCEPT_REQUIRES_(!Concept<Rng>())> void operator()(Rng &&) const { CONCEPT_ASSERT_MSG(BidirectionalIterable<Rng>(), "The object on which view::reverse operates must be a model of the " "BidirectionalIterable concept."); CONCEPT_ASSERT_MSG(BoundedIterable<Rng>(), "To reverse an iterable object, its end iterator must be a model of " "the BidirectionalIterator concept."); } #endif }; /// \relates reverse_fn /// \ingroup group-views namespace { constexpr auto&& reverse = static_const<view<reverse_fn>>::value; } } /// @} } } #endif
36.183007
98
0.504697
anders-sjogren
8fe7e6f7cf03cb8018f8dd228eeaf69241fc2bdd
879
cpp
C++
xfa/fxfa/parser/cxfa_list.cpp
softwarecapital/google.pdfium
d6c0f7d6aeaac79ca1eb7fb065d80dbd3504c92e
[ "Apache-2.0" ]
16
2018-09-14T12:07:14.000Z
2021-04-22T11:18:25.000Z
xfa/fxfa/parser/cxfa_list.cpp
softwarecapital/google.pdfium
d6c0f7d6aeaac79ca1eb7fb065d80dbd3504c92e
[ "Apache-2.0" ]
1
2020-12-26T16:18:40.000Z
2020-12-26T16:18:40.000Z
xfa/fxfa/parser/cxfa_list.cpp
softwarecapital/google.pdfium
d6c0f7d6aeaac79ca1eb7fb065d80dbd3504c92e
[ "Apache-2.0" ]
6
2017-09-12T14:09:32.000Z
2021-11-20T03:32:27.000Z
// Copyright 2017 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fxfa/parser/cxfa_list.h" #include "core/fxcrt/fx_extension.h" #include "fxjs/xfa/cfxjse_engine.h" #include "fxjs/xfa/cjx_treelist.h" #include "xfa/fxfa/parser/cxfa_document.h" #include "xfa/fxfa/parser/cxfa_node.h" CXFA_List::CXFA_List(CXFA_Document* pDocument, CJX_Object* obj) : CXFA_List(pDocument, XFA_ObjectType::List, XFA_Element::List, obj) {} CXFA_List::CXFA_List(CXFA_Document* pDocument, XFA_ObjectType objectType, XFA_Element eType, CJX_Object* obj) : CXFA_Object(pDocument, objectType, eType, obj) {} CXFA_List::~CXFA_List() = default;
35.16
80
0.711035
softwarecapital
8fe906850fb3f769e8eca6cbe96f58147c07e5df
26
cc
C++
boostrap/BListenUDP.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
11
2020-07-05T02:39:32.000Z
2022-03-20T18:52:44.000Z
boostrap/BListenUDP.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
null
null
null
boostrap/BListenUDP.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
4
2020-09-03T20:36:32.000Z
2022-01-19T07:42:21.000Z
#include "BListenUDP.hh"
8.666667
24
0.730769
hanswenzel
8fed68e99333ac75a57ea4c403c874ab78103776
5,173
cc
C++
neb/test/host.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
40
2015-03-10T07:55:39.000Z
2021-06-11T10:13:56.000Z
neb/test/host.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
297
2015-04-30T10:02:04.000Z
2022-03-09T13:31:54.000Z
neb/test/host.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
29
2015-08-03T10:04:15.000Z
2021-11-25T12:21:00.000Z
/* * Copyright 2011 - 2019 Centreon (https://www.centreon.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information : contact@centreon.com * */ #include "com/centreon/broker/neb/host.hh" #include <gtest/gtest.h> #include <cmath> #include "randomize.hh" using namespace com::centreon::broker; class HostTest : public ::testing::Test { public: void SetUp() override { // Initialization. randomize_init(); } void TearDown() override { // Cleanup. randomize_cleanup(); } }; TEST_F(HostTest, Assignment) { // Object #1. neb::host h1; std::vector<randval> randvals1; randomize(h1, &randvals1); // Object #2. neb::host h2; randomize(h2); // Assignment. h2 = h1; // Reset object #1. std::vector<randval> randvals2; randomize(h1, &randvals2); // Compare objects with expected results. ASSERT_TRUE(h1 == randvals2); ASSERT_TRUE(h2 == randvals1); } TEST_F(HostTest, CopyConstructor) { // Object #1. neb::host h1; std::vector<randval> randvals1; randomize(h1, &randvals1); // Object #2. neb::host h2(h1); // Reset object #1. std::vector<randval> randvals2; randomize(h1, &randvals2); // Compare objects with expected results. ASSERT_TRUE(h1 == randvals2); ASSERT_TRUE(h2 == randvals1); } TEST_F(HostTest, DefaultConstructor) { // Object. io::data::broker_id = 0; neb::host h; // Check. ASSERT_EQ(h.source_id, 0u); ASSERT_EQ(h.destination_id, 0u); ASSERT_FALSE(h.acknowledged); ASSERT_EQ(h.acknowledgement_type, 0); ASSERT_TRUE(h.action_url.empty()); ASSERT_FALSE(h.active_checks_enabled); ASSERT_TRUE(h.address.empty()); ASSERT_TRUE(h.alias.empty()); ASSERT_TRUE(h.check_command.empty()); ASSERT_FALSE((fabs(h.check_interval) > 0.0001)); ASSERT_FALSE(h.check_freshness); ASSERT_FALSE(!h.check_period.empty()); ASSERT_FALSE((h.check_type != 0)); ASSERT_FALSE((h.current_check_attempt != 0)); ASSERT_FALSE((h.current_state != 4)); ASSERT_FALSE(h.default_active_checks_enabled); ASSERT_FALSE(h.default_event_handler_enabled); ASSERT_FALSE(h.default_flap_detection_enabled); ASSERT_FALSE(h.default_notifications_enabled); ASSERT_FALSE(h.default_passive_checks_enabled); ASSERT_FALSE((h.downtime_depth != 0)); ASSERT_FALSE(!h.enabled); ASSERT_FALSE(!h.event_handler.empty()); ASSERT_FALSE(h.event_handler_enabled); ASSERT_FALSE((fabs(h.execution_time) > 0.0001)); ASSERT_FALSE((fabs(h.first_notification_delay) > 0.0001)); ASSERT_FALSE(h.flap_detection_enabled); ASSERT_FALSE(h.flap_detection_on_down); ASSERT_FALSE(h.flap_detection_on_unreachable); ASSERT_FALSE(h.flap_detection_on_up); ASSERT_FALSE((fabs(h.freshness_threshold) > 0.0001)); ASSERT_FALSE(h.has_been_checked); ASSERT_FALSE((fabs(h.high_flap_threshold) > 0.0001)); ASSERT_FALSE((h.host_id != 0)); ASSERT_FALSE(!h.host_name.empty()); ASSERT_FALSE(!h.icon_image.empty()); ASSERT_FALSE(!h.icon_image_alt.empty()); ASSERT_FALSE(h.is_flapping); ASSERT_FALSE((h.last_check != 0)); ASSERT_FALSE((h.last_hard_state != 4)); ASSERT_FALSE((h.last_hard_state_change != 0)); ASSERT_FALSE((h.last_notification != 0)); ASSERT_FALSE((h.last_state_change != 0)); ASSERT_FALSE((h.last_time_down != 0)); ASSERT_FALSE((h.last_time_unreachable != 0)); ASSERT_FALSE((h.last_time_up != 0)); ASSERT_FALSE((h.last_update != 0)); ASSERT_FALSE((fabs(h.latency) > 0.0001)); ASSERT_FALSE((fabs(h.low_flap_threshold) > 0.0001)); ASSERT_FALSE((h.max_check_attempts != 0)); ASSERT_FALSE((h.next_check != 0)); ASSERT_FALSE((h.next_notification != 0)); ASSERT_FALSE(h.no_more_notifications); ASSERT_FALSE(!h.notes.empty()); ASSERT_FALSE(!h.notes_url.empty()); ASSERT_FALSE((h.notification_number != 0)); ASSERT_FALSE(h.notifications_enabled); ASSERT_FALSE((fabs(h.notification_interval) > 0.0001)); ASSERT_FALSE(!h.notification_period.empty()); ASSERT_FALSE(h.notify_on_down); ASSERT_FALSE(h.notify_on_downtime); ASSERT_FALSE(h.notify_on_flapping); ASSERT_FALSE(h.notify_on_recovery); ASSERT_FALSE(h.notify_on_unreachable); ASSERT_FALSE(h.obsess_over); ASSERT_FALSE(!h.output.empty()); ASSERT_FALSE(h.passive_checks_enabled); ASSERT_FALSE((fabs(h.percent_state_change) > 0.0001)); ASSERT_FALSE(!h.perf_data.empty()); ASSERT_FALSE(h.retain_nonstatus_information); ASSERT_FALSE(h.retain_status_information); ASSERT_FALSE((fabs(h.retry_interval) > 0.0001)); ASSERT_FALSE(h.should_be_scheduled); ASSERT_FALSE(h.stalk_on_down); ASSERT_FALSE(h.stalk_on_unreachable); ASSERT_FALSE(h.stalk_on_up); ASSERT_FALSE((h.state_type != 0)); ASSERT_FALSE(!h.statusmap_image.empty()); }
31.351515
75
0.727238
centreon-lab
8fede4a60f7800f6498ad9ae17e9587904d49103
1,821
cc
C++
chrome/browser/permissions/last_tab_standing_tracker.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/browser/permissions/last_tab_standing_tracker.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/permissions/last_tab_standing_tracker.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 2020 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/browser/permissions/last_tab_standing_tracker.h" #include "chrome/browser/profiles/profile.h" #include "url/gurl.h" LastTabStandingTracker::LastTabStandingTracker() = default; LastTabStandingTracker::~LastTabStandingTracker() = default; void LastTabStandingTracker::Shutdown() { for (auto& observer : observer_list_) { observer.OnShutdown(); } observer_list_.Clear(); } void LastTabStandingTracker::AddObserver( LastTabStandingTrackerObserver* observer) { observer_list_.AddObserver(observer); } void LastTabStandingTracker::RemoveObserver( LastTabStandingTrackerObserver* observer) { observer_list_.RemoveObserver(observer); } void LastTabStandingTracker::WebContentsLoadedOrigin( const url::Origin& origin) { if (origin.opaque()) return; // There are cases where chrome://newtab/ and chrome://new-tab-page/ are // used synonymously causing inconsistencies in the map. So we just ignore // them. if (origin == url::Origin::Create(GURL("chrome://newtab/")) || origin == url::Origin::Create(GURL("chrome://new-tab-page/"))) return; tab_counter_[origin]++; } void LastTabStandingTracker::WebContentsUnloadedOrigin( const url::Origin& origin) { if (origin.opaque()) return; if (origin == url::Origin::Create(GURL("chrome://newtab/")) || origin == url::Origin::Create(GURL("chrome://new-tab-page/"))) return; DCHECK(tab_counter_.find(origin) != tab_counter_.end()); tab_counter_[origin]--; if (tab_counter_[origin] <= 0) { tab_counter_.erase(origin); for (auto& observer : observer_list_) observer.OnLastPageFromOriginClosed(origin); } }
30.864407
76
0.723229
zealoussnow
8fee5cae86153aa48502aff5223a103558611347
14,555
cpp
C++
src/sim/ldpcsim.cpp
patrickwillner/libldpc
d2ec2d369dd4f4c5cad33caa8e416280d048a89c
[ "MIT" ]
1
2021-01-29T17:19:57.000Z
2021-01-29T17:19:57.000Z
src/sim/ldpcsim.cpp
patrickwillner/libldpc
d2ec2d369dd4f4c5cad33caa8e416280d048a89c
[ "MIT" ]
2
2021-07-16T10:03:40.000Z
2021-08-19T21:40:53.000Z
src/sim/ldpcsim.cpp
patrickwillner/libldpc
d2ec2d369dd4f4c5cad33caa8e416280d048a89c
[ "MIT" ]
1
2021-07-16T10:40:47.000Z
2021-07-16T10:40:47.000Z
#include "ldpcsim.h" #include <omp.h> namespace ldpc { ldpc_sim::ldpc_sim(const std::shared_ptr<ldpc_code> &code, const decoder_param &decoderParams, const channel_param &channelParams, const simulation_param &simulationParams) : ldpc_sim(code, decoderParams, channelParams, simulationParams, nullptr) { } ldpc_sim::ldpc_sim(const std::shared_ptr<ldpc_code> &code, const decoder_param &decoderParams, const channel_param &channelParams, const simulation_param &simulationParams, sim_results_t *results) : mLdpcCode(code), mDecoderParams(decoderParams), mChannelParams(channelParams), mSimulationParams(simulationParams), mResults(results) { try { //results may vary with same seed, since some threads are executed more than others for (u32 i = 0; i < mSimulationParams.threads; ++i) { // initialize the correct channel if (mChannelParams.type == std::string("AWGN")) { mChannel.push_back( std::make_shared<channel_awgn>( channel_awgn( mLdpcCode, mDecoderParams, mChannelParams.seed + i, 1. ) ) ); } else if (mChannelParams.type == std::string("BSC")) { mChannel.push_back( std::make_shared<channel_bsc>( channel_bsc( mLdpcCode, mDecoderParams, mChannelParams.seed + i, 0. ) ) ); } else if (mChannelParams.type == std::string("BEC")) { mChannel.push_back( std::make_shared<channel_bec>( channel_bec( mLdpcCode, mDecoderParams, mChannelParams.seed + i, 0. ) ) ); } else { throw std::runtime_error("No channel selected."); } } } catch (std::exception &e) { std::cout << "Error: ldpc_sim::ldpc_sim() " << e.what() << std::endl; exit(EXIT_FAILURE); } } std::ostream &operator<<(std::ostream &os, const ldpc_sim &sim) { os << "== Decoder Parameters\n"; os << sim.mDecoderParams << "\n"; os << "== Channel Parameters\n"; os << sim.mChannelParams << "\n"; os << "== Simulation Parameters\n"; os << sim.mSimulationParams << "\n"; return os; } void ldpc_sim::start(bool *stopFlag) { u64 frames; u64 bec = 0; u64 fec = 0; u64 iters; ldpc::vec_double_t xVals; double val = mChannelParams.xRange[0]; while (val < mChannelParams.xRange[1]) { xVals.push_back(val); val += mChannelParams.xRange[2]; } auto minFec = mSimulationParams.fec; auto maxFrames = mSimulationParams.maxFrames; std::string xValType = "SNR"; if (mChannelParams.type == std::string("BSC") || mChannelParams.type == std::string("BEC")) { xValType = "EPS"; // reverse the epsilon values, since we should start at the worst // crossover probability increase to the best std::reverse(xVals.begin(), xVals.end()); } std::vector<std::string> printResStr(xVals.size() + 1, std::string()); std::ofstream fp; char resStr[128]; #ifndef LIB_SHARED #ifdef LOG_FRAME_TIME printResStr[0].assign("snr fer ber frames avg_iter frame_time"); #else printResStr[0].assign("snr fer ber frames avg_iter"); #endif #endif std::cout << "=============================" << "===========================================================" << std::endl; std::cout << " FEC | FRAME | " << xValType << " | BER | FER | AVGITERS | TIME/FRAME \n"; std::cout << "========+================+===" << "======+============+============+===========+==============" << std::endl; for (u64 i = 0; i < xVals.size(); ++i) { bec = 0; fec = 0; frames = 0; iters = 0; auto timeStart = std::chrono::high_resolution_clock::now(); #pragma omp parallel default(none) \ num_threads(mSimulationParams.threads) \ shared(iters, stopFlag, timeStart, mChannel, fec, xVals, stdout, \ bec, frames, printResStr, fp, resStr, minFec, maxFrames, i) { unsigned tid = omp_get_thread_num(); // reconfigure channel to match parameter mChannel[tid]->set_channel_param(xVals[i]); do { if (!mLdpcCode->G().empty()) { mChannel[tid]->encode_and_map(); } // calculate the channel transitions mChannel[tid]->simulate(); // calculate the corresponding LLRs, depending on the channel mChannel[tid]->calculate_llrs(); //decode auto it = mChannel[tid]->decode(); #pragma omp atomic update iters += it; if (fec < minFec) { #pragma omp atomic update ++frames; // count the bit errors int bec_tmp = 0; for (auto ci : mLdpcCode->bit_pos()) { bec_tmp += (mChannel[tid]->estimate()[ci] != mChannel[tid]->codeword()[ci]); } if (bec_tmp > 0) { auto timeNow = std::chrono::high_resolution_clock::now(); auto timeFrame = timeNow - timeStart; //eliminate const time for printing etc u64 tFrame = static_cast<u64>(std::chrono::duration_cast<std::chrono::microseconds>(timeFrame).count()); tFrame = tFrame / frames; #pragma omp critical { bec += bec_tmp; ++fec; #ifndef LIB_SHARED printf("\r %2lu/%2lu | %12lu | %.3f | %.2e | %.2e | %.1e | %.3fms", fec, minFec, frames, xVals[i], static_cast<double>(bec) / (frames * mLdpcCode->nc()), //ber static_cast<double>(fec) / frames, //fer static_cast<double>(iters) / frames, //avg iters static_cast<double>(tFrame) * 1e-3); //frame time tFrame fflush(stdout); #ifdef LOG_FRAME_TIME sprintf(resStr, "%lf %.3e %.3e %lu %.3e %.6f", xVals[i], static_cast<double>(fec) / frames, static_cast<double>(bec) / (frames * mLdpcCode->nc()), frames, static_cast<double>(iters) / frames, static_cast<double>(tFrame) * 1e-6); #else sprintf(resStr, "%lf %.3e %.3e %lu %.3e", xVals[i], static_cast<double>(fec) / frames, static_cast<double>(bec) / (frames * mLdpcCode->nc()), frames, static_cast<double>(iters) / frames); #endif printResStr[i + 1].assign(resStr); try { fp.open(mSimulationParams.resultFile); for (const auto &x : printResStr) { fp << x << "\n"; } fp.close(); } catch (...) { printf("Warning: can not open logfile for writing\n"); } #ifdef LOG_CW //log_error(frames, xVals[i]); #endif #endif //save to result struct if (mResults != nullptr) { mResults->fer[i] = static_cast<double>(fec) / frames; mResults->ber[i] = static_cast<double>(bec) / (frames * mLdpcCode->nc()); mResults->avg_iter[i] = static_cast<double>(iters) / frames; mResults->time[i] = static_cast<double>(tFrame) * 1e-6; mResults->fec[i] = fec; mResults->frames[i] = frames; } timeStart += std::chrono::high_resolution_clock::now() - timeNow; //dont measure time for printing files } } } } while (fec < minFec && frames < maxFrames && !*stopFlag); //end while } #ifndef LIB_SHARED printf("\n"); #endif } //end for *resStr = 0; } /* void ldpc_sim::print_file_header(const char *binaryFile, const char *codeFile, const char *simFile, const char *mapFile) { FILE *fp = fopen(mLogfile, "a+"); fprintf(fp, "%% binary: %s (Version: %s, Built: %s)\n", binaryFile, VERSION, BUILD_DATE); fprintf(fp, "%% sim file: %s\n", simFile); fprintf(fp, "%% code file: %s\n", codeFile); fprintf(fp, "%% mapping file: %s\n", mapFile); fprintf(fp, "%% result file: %s\n", mLogfile); fprintf(fp, "%% iter: %lu\n", mBPIter); fprintf(fp, "%% max frames: %lu\n", mMaxFrames); fprintf(fp, "%% min fec: %lu\n", mMinFec); fprintf(fp, "%% BP early terminate: %hu\n", 1); fprintf(fp, "%% num threads: %d\n", 1); } */ /* void ldpc_sim::log_error(u64 pFrameNum, double pSNR) { char errors_file[MAX_FILENAME_LEN]; snprintf(errors_file, MAX_FILENAME_LEN, "errors_%s", mLogfile.c_str()); FILE *fp = fopen(errors_file, "a+"); if (!fp) { printf("can not open error log file.\n"); exit(EXIT_FAILU RE); } // calculation of syndrome and failed syndrome checks u64 synd_weight = 0; for (auto si : mLdpcDecoder->syndrome()) { synd_weight += si; } std::vector<u64> failed_checks_idx(synd_weight); u64 j = 0; for (u64 i = 0; i < mLdpcCode->mc(); i++) { if (mLdpcDecoder->syndrome()[i] == 1) { failed_checks_idx[j++] = i; } } // calculation of failed codeword bits u64 cw_dis = 0; for (u64 i = 0; i < mLdpcCode->nc(); i++) { #ifdef ENCODE cw_dis += ((mLdpcDecoder->llr_out()[i] <= 0) != mC[pThreads][i]); #else cw_dis += ((mLdpcDecoder->llr_out()[i] <= 0) != 0); #endif } std::vector<u64> x(mN); std::vector<u64> xhat(mN); std::vector<u64> chat(mLdpcCode->nc()); for (u64 i = 0; i < mLdpcCode->nc(); ++i) { chat[i] = (mLdpcDecoder->llr_out()[i] <= 0); } u64 tmp; //map c to x map_c_to_x(c, x); for (u64 i = 0; i < mN; i++) { tmp = 0; for (u64 j = 0; j < mBits; j++) { tmp += mC[mBitMapper[j][i]] << (mBits - 1 - j); } x[i] = mLabelsRev[tmp]; } //map_c_to_x(chat, xhat); for (u64 i = 0; i < mN; i++) { tmp = 0; for (u64 j = 0; j < mBits; j++) { tmp += chat[mBitMapper[j][i]] << (mBits - 1 - j); } xhat[i] = mLabelsRev[tmp]; } double cw_dis_euc = 0; for (u64 i = 0; i < mN; i++) { #ifdef ENCODE cw_dis_euc += (mConstellation.X()[x[i]] - mConstellation.X()[xhat[i]]) * (mConstellation.X()[x[i]] - mConstellation.X()[xhat[i]]); #else cw_dis_euc += (mConstellation.X()[0] - mConstellation.X()[xhat[i]]) * (mConstellation.X()[0] - mConstellation.X()[xhat[i]]); #endif } std::vector<u64> failed_bits_idx(cw_dis); j = 0; for (u64 i = 0; i < mLdpcCode->nc(); i++) { #ifdef ENCODE if (chat[i] != mC[pThreads][i]) { failed_bits_idx[j++] = i; } #else if (chat[i] != 0) { failed_bits_idx[j++] = i; } #endif } // print results in file fprintf(fp, "SNR: %.2f -- frame: %lu -- is codeword: %d -- dE(c,chat): %.3f -- dH(c,chat): %lu | ", pSNR, pFrameNum, synd_weight == 0, cw_dis_euc, cw_dis); for (auto failed_bits_idx_i : failed_bits_idx) { fprintf(fp, "%lu ", failed_bits_idx_i); } fprintf(fp, " -- "); fprintf(fp, "synd weight: %lu | ", synd_weight); for (auto failed_checks_idx_i : failed_checks_idx) { fprintf(fp, "%lu ", failed_checks_idx_i); } fprintf(fp, "\n"); fclose(fp); } */ } // namespace ldpc
35.67402
159
0.419924
patrickwillner
8ff1bb73cfc65f29b37e4a2be18d431483970428
8,392
cpp
C++
server-client-sample/connectivity/classic/ServerTest.cpp
kaiostech/gonk-binder
5ab61435a1939f992e4ace372b9c694a65023927
[ "FSFAP" ]
null
null
null
server-client-sample/connectivity/classic/ServerTest.cpp
kaiostech/gonk-binder
5ab61435a1939f992e4ace372b9c694a65023927
[ "FSFAP" ]
null
null
null
server-client-sample/connectivity/classic/ServerTest.cpp
kaiostech/gonk-binder
5ab61435a1939f992e4ace372b9c694a65023927
[ "FSFAP" ]
2
2020-07-17T01:55:32.000Z
2021-08-12T06:12:29.000Z
/* (c) 2020 KAI OS TECHNOLOGIES (HONG KONG) LIMITED All rights reserved. This * file or any portion thereof may not be reproduced or used in any manner * whatsoever without the express written permission of KAI OS TECHNOLOGIES * (HONG KONG) LIMITED. KaiOS is the trademark of KAI OS TECHNOLOGIES (HONG * KONG) LIMITED or its affiliate company and may be registered in some * jurisdictions. All other trademarks are the property of their respective * owners. */ #include "ServerTest.h" #include <binder/IInterface.h> #include <binder/IServiceManager.h> #include <binder/ProcessState.h> #define KAIOS_SERVER_DEBUG(args...) \ __android_log_print(ANDROID_LOG_INFO, "KaiOS_AIDL_ConnectivityServer", ##args) using android::ProcessState; using android::sp; using android::binder::Status; // TODO: REWRITE_BY_YOURSELF_START #include "b2g/connectivity/BnConnectivity.h" using b2g::connectivity::CaptivePortalLandingParcel; using b2g::connectivity::ICaptivePortalLandingListener; using b2g::connectivity::IConnectivityEventListener; using b2g::connectivity::ITetheringStatusListener; using b2g::connectivity::NetworkInfoParcel; using b2g::connectivity::TetheringStatusParcel; // Helper function. void ServerTest::InitNetworkInfo(NetworkInfoParcel& aNetworkInfo) { aNetworkInfo.name.clear(); aNetworkInfo.netId = 0; aNetworkInfo.state = IConnectivity::NETWORK_STATE_UNKNOWN; aNetworkInfo.type = IConnectivity::NETWORK_TYPE_UNKNOWN; aNetworkInfo.prefixLengths.clear(); aNetworkInfo.ips.clear(); aNetworkInfo.gateways.clear(); aNetworkInfo.dnses.clear(); } // TODO: REWRITE_BY_YOURSELF_END ServerTest::ServerTest() { // TODO: REWRITE_BY_YOURSELF InitNetworkInfo(mActiveNetworkInfo); android::defaultServiceManager()->addService( android::String16(getServiceName()), this); sp<ProcessState> process(ProcessState::self()); process->startThreadPool(); } // TODO: REWRITE_BY_YOURSELF_START Status ServerTest::isAlive(bool* aLive) { *aLive = true; return Status::ok(); } // Network function Status ServerTest::addEventListener( const sp<IConnectivityEventListener>& listener) { std::lock_guard lock(mNetworkEventMutex); class DeathRecipient : public android::IBinder::DeathRecipient { public: DeathRecipient(ServerTest* serverTest, sp<IConnectivityEventListener> listener) : mServerTest(serverTest), mListener(std::move(listener)) {} ~DeathRecipient() override = default; void binderDied(const android::wp<android::IBinder>& /* who */) override { KAIOS_SERVER_DEBUG("Client is dead, remove listener"); mServerTest->removeEventListener(mListener); } private: ServerTest* mServerTest; sp<IConnectivityEventListener> mListener; }; sp<android::IBinder::DeathRecipient> deathRecipient = new DeathRecipient(this, listener); android::IInterface::asBinder(listener)->linkToDeath(deathRecipient); mListenerTestMap.insert({listener, deathRecipient}); return Status::ok(); } Status ServerTest::removeEventListener( const sp<IConnectivityEventListener>& listener) { std::lock_guard lock(mNetworkEventMutex); mListenerTestMap.erase(listener); return Status::ok(); } Status ServerTest::getActiveNetworkInfo(NetworkInfoParcel* aNetworkInfoParcel) { *aNetworkInfoParcel = mActiveNetworkInfo; return Status::ok(); } Status ServerTest::getNetworkInfos( std::vector<NetworkInfoParcel>* aNetworkInfoParcels) { *aNetworkInfoParcels = mNetworkInfos; return Status::ok(); } void ServerTest::updateActiveNetworkInfo( NetworkInfoParcel& aNetworkInfoParcel) { mActiveNetworkInfo = aNetworkInfoParcel; for (auto& listenerMap : mListenerTestMap) { listenerMap.first->onActiveNetworkChanged(aNetworkInfoParcel); } } void ServerTest::updateNetworkInfo(NetworkInfoParcel& aNetworkInfoParcel) { // Update NetworkInfos cache. bool found = false; for (uint32_t i = 0; i < mNetworkInfos.size(); i++) { if (mNetworkInfos[i].type == aNetworkInfoParcel.type && mNetworkInfos[i].name == aNetworkInfoParcel.name) { // Replace by new status. found = true; mNetworkInfos[i] = aNetworkInfoParcel; break; } } if (!found) { mNetworkInfos.push_back(aNetworkInfoParcel); } for (auto& listenerMap : mListenerTestMap) { listenerMap.first->onNetworkChanged(aNetworkInfoParcel); } } // Tethering function Status ServerTest::getTetheringStatus( TetheringStatusParcel* aTetheringStatusParcel) { *aTetheringStatusParcel = mTetheringStatusParcel; return Status::ok(); } Status ServerTest::addTetheringStatusListener( const sp<ITetheringStatusListener>& listener) { std::lock_guard lock(mTetheringMutex); class DeathRecipient : public android::IBinder::DeathRecipient { public: DeathRecipient(ServerTest* serverTest, sp<ITetheringStatusListener> listener) : mServerTest(serverTest), mListener(std::move(listener)) {} ~DeathRecipient() override = default; void binderDied(const android::wp<android::IBinder>& /* who */) override { KAIOS_SERVER_DEBUG("Client is dead, remove tethering listener"); mServerTest->removeTetheringStatusListener(mListener); } private: ServerTest* mServerTest; sp<ITetheringStatusListener> mListener; }; sp<android::IBinder::DeathRecipient> deathRecipient = new DeathRecipient(this, listener); android::IInterface::asBinder(listener)->linkToDeath(deathRecipient); mTetheringListenerTestMap.insert({listener, deathRecipient}); return Status::ok(); } Status ServerTest::removeTetheringStatusListener( const sp<ITetheringStatusListener>& listener) { std::lock_guard lock(mTetheringMutex); mTetheringListenerTestMap.erase(listener); return Status::ok(); } void ServerTest::updateTetheringStatus( TetheringStatusParcel& aTetheringStatusParcel) { mTetheringStatusParcel = aTetheringStatusParcel; for (auto& listenerMap : mTetheringListenerTestMap) { listenerMap.first->onTetheringStatusChanged(aTetheringStatusParcel); } } // Captive portal function Status ServerTest::getCaptivePortalLandings( std::vector<CaptivePortalLandingParcel>* aCaptivePortalLandings) { *aCaptivePortalLandings = mCaptivePortalLandings; return Status::ok(); } Status ServerTest::addCaptivePortalLandingListener( const sp<ICaptivePortalLandingListener>& listener) { std::lock_guard lock(mCaptivePortalMutex); class DeathRecipient : public android::IBinder::DeathRecipient { public: DeathRecipient(ServerTest* serverTest, sp<ICaptivePortalLandingListener> listener) : mServerTest(serverTest), mListener(std::move(listener)) {} ~DeathRecipient() override = default; void binderDied(const android::wp<android::IBinder>& /* who */) override { KAIOS_SERVER_DEBUG("Client is dead, remove captive portal listener"); mServerTest->removeCaptivePortalLandingListener(mListener); } private: ServerTest* mServerTest; sp<ICaptivePortalLandingListener> mListener; }; sp<android::IBinder::DeathRecipient> deathRecipient = new DeathRecipient(this, listener); android::IInterface::asBinder(listener)->linkToDeath(deathRecipient); mCaptivePortalListenerTestMap.insert({listener, deathRecipient}); return Status::ok(); } Status ServerTest::removeCaptivePortalLandingListener( const sp<ICaptivePortalLandingListener>& listener) { std::lock_guard lock(mCaptivePortalMutex); mCaptivePortalListenerTestMap.erase(listener); return Status::ok(); } void ServerTest::updateCaptivePortal( CaptivePortalLandingParcel& aCaptivePortalLandingParcel) { // Update captive portal status. bool found = false; for (uint32_t i = 0; i < mCaptivePortalLandings.size(); i++) { if (mCaptivePortalLandings[i].networkType == aCaptivePortalLandingParcel.networkType && mCaptivePortalLandings[i].landing == aCaptivePortalLandingParcel.landing) { // Replace by new status. found = true; mCaptivePortalLandings[i] = aCaptivePortalLandingParcel; break; } } if (!found) { mCaptivePortalLandings.push_back(aCaptivePortalLandingParcel); } for (auto& listenerMap : mCaptivePortalListenerTestMap) { listenerMap.first->onCaptivePortalLandingChanged( aCaptivePortalLandingParcel); } } // TODO: REWRITE_BY_YOURSELF_END
33.03937
80
0.750119
kaiostech
8ff22aaed87b56b031f0e7ed06f7b866a0a13819
2,043
cc
C++
voicenavigator/src/model/MoveCategoryRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
voicenavigator/src/model/MoveCategoryRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
voicenavigator/src/model/MoveCategoryRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/voicenavigator/model/MoveCategoryRequest.h> using AlibabaCloud::VoiceNavigator::Model::MoveCategoryRequest; MoveCategoryRequest::MoveCategoryRequest() : RpcServiceRequest("voicenavigator", "2018-06-12", "MoveCategory") { setMethod(HttpRequest::Method::Post); } MoveCategoryRequest::~MoveCategoryRequest() {} std::string MoveCategoryRequest::getInstanceId()const { return instanceId_; } void MoveCategoryRequest::setInstanceId(const std::string& instanceId) { instanceId_ = instanceId; setParameter("InstanceId", instanceId); } std::string MoveCategoryRequest::getTargetPreviousSiblingId()const { return targetPreviousSiblingId_; } void MoveCategoryRequest::setTargetPreviousSiblingId(const std::string& targetPreviousSiblingId) { targetPreviousSiblingId_ = targetPreviousSiblingId; setParameter("TargetPreviousSiblingId", targetPreviousSiblingId); } std::string MoveCategoryRequest::getTargetParentId()const { return targetParentId_; } void MoveCategoryRequest::setTargetParentId(const std::string& targetParentId) { targetParentId_ = targetParentId; setParameter("TargetParentId", targetParentId); } std::string MoveCategoryRequest::getCategoryId()const { return categoryId_; } void MoveCategoryRequest::setCategoryId(const std::string& categoryId) { categoryId_ = categoryId; setParameter("CategoryId", categoryId); }
27.608108
97
0.769457
iamzken
8ff25b07f1019afac31fa0b3a7cbac04c3c1114e
1,116
cpp
C++
decompiler/level_extractor/extract_common.cpp
Hat-Kid/jak-project
0e2320ca9584118316313e41e646b179a1083feb
[ "ISC" ]
null
null
null
decompiler/level_extractor/extract_common.cpp
Hat-Kid/jak-project
0e2320ca9584118316313e41e646b179a1083feb
[ "ISC" ]
null
null
null
decompiler/level_extractor/extract_common.cpp
Hat-Kid/jak-project
0e2320ca9584118316313e41e646b179a1083feb
[ "ISC" ]
null
null
null
#include <cstddef> #include "extract_common.h" u32 clean_up_vertex_indices(std::vector<u32>& idx) { std::vector<u32> fixed; u32 num_tris = 0; bool looking_for_start = true; size_t i_of_start; for (size_t i = 0; i < idx.size(); i++) { if (looking_for_start) { if (idx[i] != UINT32_MAX) { looking_for_start = false; i_of_start = i; } } else { if (idx[i] == UINT32_MAX) { looking_for_start = true; size_t num_verts = i - i_of_start; if (num_verts >= 3) { if (!fixed.empty()) { fixed.push_back(UINT32_MAX); } fixed.insert(fixed.end(), idx.begin() + i_of_start, idx.begin() + i); num_tris += (num_verts - 2); } } } } if (!looking_for_start) { size_t num_verts = idx.size() - i_of_start; if (num_verts >= 3) { if (!fixed.empty()) { fixed.push_back(UINT32_MAX); } fixed.insert(fixed.end(), idx.begin() + i_of_start, idx.begin() + idx.size()); num_tris += (num_verts - 2); } } idx = std::move(fixed); return num_tris; }
24.8
84
0.548387
Hat-Kid
8ff4c7c05e71629adadc56b321e708fdd532b0a6
5,471
cpp
C++
benchmark/BM_sinecrunch.cpp
MuAlphaOmegaEpsilon/sinecrunch
65d4f6003f60fcaa973ae67e90c9f6a5cc16bce8
[ "MIT" ]
1
2019-04-05T19:09:46.000Z
2019-04-05T19:09:46.000Z
benchmark/BM_sinecrunch.cpp
MuAlphaOmegaEpsilon/sinecrunch
65d4f6003f60fcaa973ae67e90c9f6a5cc16bce8
[ "MIT" ]
null
null
null
benchmark/BM_sinecrunch.cpp
MuAlphaOmegaEpsilon/sinecrunch
65d4f6003f60fcaa973ae67e90c9f6a5cc16bce8
[ "MIT" ]
null
null
null
#include <sltbench/Bench.h> #include <algorithm> #define _USE_MATH_DEFINES #include <math.h> #include <numeric> // A simple shorthand for single precision floating point. using floatSP = float; // A simple shorthand for double precision floating point. using floatDP = double; // A simple shorthand for quadruple precision floating point. using floatQP = long double; // The total number of samples to take. // One more is added since the sample at ZERO is also required. constexpr uint32_t samplesNum = (1 << 15) + 1; // The amount of space there is between two consecutive samples. constexpr floatDP samplePeriod = (floatSP) (M_PI * 2.0f / (samplesNum - 1)); // Since the purpose of the benchmark is about measuring sinusoid function // calls performance, we don't want to deal with angle conversions at // bench-time: lets have all the angles for every float precision already // calculated. static floatSP anglesSP [samplesNum]; static floatDP anglesDP [samplesNum]; static floatQP anglesQP [samplesNum]; // Returns the array of angles of the specified type. template <typename T> T* getAngles (); template <> floatSP* getAngles () { return anglesSP; } template <> floatDP* getAngles () { return anglesDP; } template <> floatQP* getAngles () { return anglesQP; } // The ground truth values for a sinusoid. // These samples are calculated using the highest precision function at // disposal, which returns a quad precision float. static floatQP groundTruth [samplesNum]; // A little shorthand to specify both, the BEGIN and END iterators of the // passed array. // Since the number of samples is always the same in this whole file, there's // no need to always specify the same details about array length. #define RANGE(array) array, array + samplesNum void initialize () { // Populate the single precision angles array first. // The single precision array gets populated first since its lowest // precision one, and there's no precision loss when converting to higher // precision arrays. std::iota (RANGE (anglesSP), samplePeriod); // Copy over the other precision arrays. // The copy is required instead of doing iota again: // we don't want to populate the angles arrays at different precision // levels, we want to have the EXACT same angles just converted to // different types! That's why we populated anglesSP first. std::copy (RANGE (anglesSP), anglesDP); std::copy (RANGE (anglesSP), anglesQP); // Calculate the ground truth samples. std::transform (RANGE (anglesQP), groundTruth, sinl); } template <typename T> constexpr floatDP error_abs (const T& val, const floatQP& ref) noexcept { return fabs (static_cast <floatDP> (val - static_cast <T> (ref))); } template <typename T> constexpr floatDP error_rel (const T& val, const floatQP& ref) noexcept { return fabs (1.0 - static_cast <floatDP> (val / static_cast <T> (ref))); } template <typename T, T (*sinusoid)(T)> static void benchSinusoid () { // const T* angles = getAngles <T> (); // T result [samplesNum]; // floatDP errors [samplesNum]; // double random = fmod (rand () / 1000.0, 2.0 * M_PI); // // Main funciton benchmark loop: this is where the execution of the // // function is actually measured. // for (const auto _ : state) // benchmark::DoNotOptimize (result[0] = sinusoid (random)); // std::transform (RANGE (angles), result, sinusoid); // // Total number of items processed. // // Google Benchmark will calculate how many items_per_second based on this. // state.SetItemsProcessed (state.iterations ()); // state.SetBytesProcessed (state.iterations () * sizeof (T)); // state.counters["angle"] = random; // // Absolute errors calculations // std::transform (RANGE (result), groundTruth, errors, error_abs <T>); // state.counters["AErr_avg"] = std::accumulate (RANGE (errors), 0.0L) * samplePeriod; // state.counters["AErr_max"] = *std::max_element (RANGE (errors)); // state.counters["AErr_min"] = *std::min_element (RANGE (errors)); // // Relative errors calculations // std::transform (RANGE (result), groundTruth, errors, error_rel <T>); // state.counters["RE_avg"] = std::accumulate (RANGE (errors), 0.0L) * samplePeriod; // state.counters["RE_max"] = *std::max_element (RANGE (errors)); // state.counters["RE_min"] = *std::min_element (RANGE (errors)); } // A little shorthand to mark a function for benchmarking and to rename it. // Type is at the same time the argument and the return type. // Function is the sinusoid to test. // Name defines under which tag the function should appear in the results. #define BENCH_SINUSOID(type, function, name) \ const auto SIN_ ## type ## _ ## name = benchSinusoid <type, function>; \ SLTBENCH_FUNCTION (SIN_ ## type ## _ ## name) // Register all the standard functions to benchmark. BENCH_SINUSOID (floatQP, sinl, compiler) BENCH_SINUSOID (floatDP, sin, compiler) BENCH_SINUSOID (floatSP, sinf, compiler) // Register FastTrigo functions to benchmark. #include <fasttrigo.h> BENCH_SINUSOID (floatSP, FT::sin, fasttrigo_fast) BENCH_SINUSOID (floatSP, FTA::sin, fasttrigo_precise) // Register sinecrunch functions to benchmark. #include <sinecrunch.hpp> BENCH_SINUSOID (floatSP, sinecrunch::sin<1>, sinecrunch) int main(int argc, char** argv) { initialize (); return sltbench::Main(argc, argv); }
37.993056
90
0.703528
MuAlphaOmegaEpsilon
8ff5e8b271e4fde432711382d7adc743646f5149
2,514
hh
C++
nox/src/include/timeval.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
28
2015-02-04T13:59:25.000Z
2021-12-29T03:44:47.000Z
nox/src/include/timeval.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
552
2015-01-05T18:25:54.000Z
2022-03-16T18:51:13.000Z
nox/src/include/timeval.hh
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
25
2015-02-04T18:48:20.000Z
2020-06-18T15:51:05.000Z
/* Copyright 2008 (C) Nicira, Inc. * * This file is part of NOX. * * NOX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NOX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NOX. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TIMEVAL_HH #define TIMEVAL_HH 1 #include <sys/time.h> long long int time_msec(); struct timeval do_gettimeofday(bool update = false); ::timeval operator+(const ::timeval&, const ::timeval&); ::timeval operator-(const ::timeval&, const ::timeval&); const ::timeval& operator+=(::timeval&, const ::timeval&); const ::timeval& operator-=(::timeval&, const ::timeval&); int timeval_compare(const ::timeval&, const ::timeval&); double timeval_to_double(const ::timeval&); double timespec_to_double(const ::timespec&); static inline timeval make_timeval(unsigned long int tv_sec, unsigned long int tv_usec) { timeval tv; tv.tv_sec = tv_sec; tv.tv_usec = tv_usec; return tv; } static inline timespec make_timespec(unsigned long int tv_sec, unsigned long int tv_nsec) { timespec ts; ts.tv_sec = tv_sec; ts.tv_nsec = tv_nsec; return ts; } long int timeval_to_ms(const ::timeval&); ::timeval timeval_from_ms(long int ms); long int timespec_to_ms(const ::timespec&); ::timespec timespec_from_ms(long int ms); static inline bool operator==(const ::timeval& x, const ::timeval& y) { return timeval_compare(x, y) == 0; } static inline bool operator!=(const ::timeval& x, const ::timeval& y) { return timeval_compare(x, y) != 0; } static inline bool operator<(const ::timeval& x, const ::timeval& y) { return timeval_compare(x, y) < 0; } static inline bool operator>(const ::timeval& x, const ::timeval& y) { return timeval_compare(x, y) > 0; } static inline bool operator<=(const ::timeval& x, const ::timeval& y) { return timeval_compare(x, y) <= 0; } static inline bool operator>=(const ::timeval& x, const ::timeval& y) { return timeval_compare(x, y) >= 0; } #endif /* timeval.hh */
28.247191
71
0.683373
ayjazz
8ffc731c5d2b12384e2e867f7832b11c629e86a6
1,420
cpp
C++
Testing/testCiphers.cpp
MPAGS-CPP-2019/mpags-day-5-JamesDownsLab
9af7ace33284d06aaf97143211a1646e97f458c8
[ "MIT" ]
null
null
null
Testing/testCiphers.cpp
MPAGS-CPP-2019/mpags-day-5-JamesDownsLab
9af7ace33284d06aaf97143211a1646e97f458c8
[ "MIT" ]
null
null
null
Testing/testCiphers.cpp
MPAGS-CPP-2019/mpags-day-5-JamesDownsLab
9af7ace33284d06aaf97143211a1646e97f458c8
[ "MIT" ]
null
null
null
//! Unit Tests for MPAGSCipher CaesarCipher Class #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "Cipher.hpp" #include "CipherMode.hpp" #include "CaesarCipher.hpp" #include "PlayfairCipher.hpp" #include "VigenereCipher.hpp" bool testCipher( const Cipher& cipher, const CipherMode mode, const std::string& inputText, const std::string& outputText){ if (outputText == cipher.applyCipher(inputText, mode)) { return true; } else { return false; } } TEST_CASE("Caesar Cipher", "[caesar]") { CaesarCipher cipher {10}; REQUIRE(testCipher(cipher, CipherMode::Encrypt, "HELLOWORLD", "ROVVYGYBVN")); REQUIRE(testCipher(cipher, CipherMode::Decrypt, "ROVVYGYBVN", "HELLOWORLD")); } TEST_CASE("Playfair Cipher", "[playfair]") { PlayfairCipher cipher {"hello"}; REQUIRE(testCipher(cipher, CipherMode::Encrypt, "BOBISSOMESORTOFJUNIORCOMPLEXXENOPHONEONEZEROTHING", "FHIQXLTLKLTLSUFNPQPKETFENIOLVSWLTFIAFTLAKOWATEQOKPPA")); REQUIRE(testCipher(cipher, CipherMode::Decrypt, "FHIQXLTLKLTLSUFNPQPKETFENIOLVSWLTFIAFTLAKOWATEQOKPPA", "BOBISXSOMESORTOFIUNIORCOMPLEXQXENOPHONEONEZEROTHINGZ")); } TEST_CASE("Vigenere Cipher", "[vigenere]") { VigenereCipher cipher {"key"}; REQUIRE(testCipher(cipher, CipherMode::Encrypt, "HELLOWORLD", "RIJVSUYVJN")); REQUIRE(testCipher(cipher, CipherMode::Decrypt, "RIJVSUYVJN", "HELLOWORLD")); }
33.809524
165
0.725352
MPAGS-CPP-2019
89035873afcbd1235731e594a770be55ede906d6
20,090
cxx
C++
main/sw/source/core/text/widorp.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sw/source/core/text/widorp.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sw/source/core/text/widorp.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include "hintids.hxx" #include "layfrm.hxx" #include "ftnboss.hxx" #include "ndtxt.hxx" #include "paratr.hxx" #include <editeng/orphitem.hxx> #include <editeng/widwitem.hxx> #include <editeng/keepitem.hxx> #include <editeng/spltitem.hxx> #include <frmatr.hxx> #include <txtftn.hxx> #include <fmtftn.hxx> #include <rowfrm.hxx> #include "txtcfg.hxx" #include "widorp.hxx" #include "txtfrm.hxx" #include "itrtxt.hxx" #include "sectfrm.hxx" //SwSectionFrm #include "ftnfrm.hxx" #undef WIDOWTWIPS /************************************************************************* * inline IsNastyFollow() *************************************************************************/ // Ein Follow, der auf der selben Seite steht, wie sein Master ist nasty. inline sal_Bool IsNastyFollow( const SwTxtFrm *pFrm ) { ASSERT( !pFrm->IsFollow() || !pFrm->GetPrev() || ((const SwTxtFrm*)pFrm->GetPrev())->GetFollow() == pFrm, "IsNastyFollow: Was ist denn hier los?" ); return pFrm->IsFollow() && pFrm->GetPrev(); } /************************************************************************* * SwTxtFrmBreak::SwTxtFrmBreak() *************************************************************************/ SwTxtFrmBreak::SwTxtFrmBreak( SwTxtFrm *pNewFrm, const SwTwips nRst ) : nRstHeight(nRst), pFrm(pNewFrm) { SWAP_IF_SWAPPED( pFrm ) SWRECTFN( pFrm ) nOrigin = (pFrm->*fnRect->fnGetPrtTop)(); SwSectionFrm* pSct; bKeep = !pFrm->IsMoveable() || IsNastyFollow( pFrm ) || ( pFrm->IsInSct() && (pSct=pFrm->FindSctFrm())->Lower()->IsColumnFrm() && !pSct->MoveAllowed( pFrm ) ) || !pFrm->GetTxtNode()->GetSwAttrSet().GetSplit().GetValue() || pFrm->GetTxtNode()->GetSwAttrSet().GetKeep().GetValue(); bBreak = sal_False; if( !nRstHeight && !pFrm->IsFollow() && pFrm->IsInFtn() && pFrm->HasPara() ) { nRstHeight = pFrm->GetFtnFrmHeight(); nRstHeight += (pFrm->Prt().*fnRect->fnGetHeight)() - (pFrm->Frm().*fnRect->fnGetHeight)(); if( nRstHeight < 0 ) nRstHeight = 0; } UNDO_SWAP( pFrm ) } /* BP 18.6.93: Widows. * Im Gegensatz zur ersten Implementierung werden die Widows nicht * mehr vorausschauend berechnet, sondern erst beim Formatieren des * gesplitteten Follows festgestellt. Im Master faellt die Widows- * Berechnung also generell weg (nWidows wird manipuliert). * Wenn der Follow feststellt, dass die Widowsregel zutrifft, * verschickt er an seinen Vorgaenger ein Prepare. * Ein besonderes Problem ergibt sich, wenn die Widows zuschlagen, * aber im Master noch ein paar Zeilen zur Verfuegung stehen. * */ /************************************************************************* * SwTxtFrmBreak::IsInside() *************************************************************************/ /* BP(22.07.92): Berechnung von Witwen und Waisen. * Die Methode liefert sal_True zurueck, wenn eine dieser Regelung zutrifft. * * Eine Schwierigkeit gibt es im Zusammenhang mit Widows und * unterschiedlichen Formaten zwischen Master- und Folgeframes: * Beispiel: Wenn die erste Spalte 3cm und die zweite 4cm breit ist * und Widows auf sagen wir 3 gesetzt ist, so ist erst bei der Formatierung * des Follows entscheidbar, ob die Widowsbedingung einhaltbar ist oder * nicht. Leider ist davon abhaengig, ob der Absatz als Ganzes auf die * naechste Seite rutscht. */ sal_Bool SwTxtFrmBreak::IsInside( SwTxtMargin &rLine ) const { sal_Bool bFit = sal_False; SWAP_IF_SWAPPED( pFrm ) SWRECTFN( pFrm ) // nOrigin is an absolut value, rLine referes to the swapped situation. SwTwips nTmpY; if ( pFrm->IsVertical() ) nTmpY = pFrm->SwitchHorizontalToVertical( rLine.Y() + rLine.GetLineHeight() ); else nTmpY = rLine.Y() + rLine.GetLineHeight(); SwTwips nLineHeight = (*fnRect->fnYDiff)( nTmpY , nOrigin ); // 7455 und 6114: Raum fuer die Umrandung unten einkalkulieren. nLineHeight += (pFrm->*fnRect->fnGetBottomMargin)(); if( nRstHeight ) bFit = nRstHeight >= nLineHeight; else { // Der Frm besitzt eine Hoehe, mit der er auf die Seite passt. SwTwips nHeight = (*fnRect->fnYDiff)( (pFrm->GetUpper()->*fnRect->fnGetPrtBottom)(), nOrigin ); // Wenn sich alles innerhalb des bestehenden Frames abspielt, // ist das Ergebnis sal_True; bFit = nHeight >= nLineHeight; // --> OD #i103292# if ( !bFit ) { if ( rLine.GetNext() && pFrm->IsInTab() && !pFrm->GetFollow() && !pFrm->GetIndNext() ) { // add additional space taken as lower space as last content in a table // for all text lines except the last one. nHeight += pFrm->CalcAddLowerSpaceAsLastInTableCell(); bFit = nHeight >= nLineHeight; } } // <-- if( !bFit ) { // Die LineHeight sprengt die aktuelle Frm-Hoehe. // Nun rufen wir ein Probe-Grow, um zu ermitteln, ob der // Frame um den gewuenschten Bereich wachsen wuerde. nHeight += pFrm->GrowTst( LONG_MAX ); // Das Grow() returnt die Hoehe, um die der Upper des TxtFrm // den TxtFrm wachsen lassen wuerde. // Der TxtFrm selbst darf wachsen wie er will. bFit = nHeight >= nLineHeight; } } UNDO_SWAP( pFrm ); return bFit; } /************************************************************************* * SwTxtFrmBreak::IsBreakNow() *************************************************************************/ sal_Bool SwTxtFrmBreak::IsBreakNow( SwTxtMargin &rLine ) { SWAP_IF_SWAPPED( pFrm ) // bKeep ist staerker als IsBreakNow() // Ist noch genug Platz ? if( bKeep || IsInside( rLine ) ) bBreak = sal_False; else { /* Diese Klasse geht davon aus, dass der SwTxtMargin von Top nach Bottom * durchgearbeitet wird. Aus Performancegruenden wird in folgenden * Faellen der Laden fuer das weitere Aufspalten dicht gemacht: * Wenn eine einzige Zeile nicht mehr passt. * Sonderfall: bei DummyPortions ist LineNr == 1, obwohl wir splitten * wollen. */ // 6010: DropLines mit einbeziehen sal_Bool bFirstLine = 1 == rLine.GetLineNr() && !rLine.GetPrev(); bBreak = sal_True; if( ( bFirstLine && pFrm->GetIndPrev() ) || ( rLine.GetLineNr() <= rLine.GetDropLines() ) ) { bKeep = sal_True; bBreak = sal_False; } else if(bFirstLine && pFrm->IsInFtn() && !pFrm->FindFtnFrm()->GetPrev()) { SwLayoutFrm* pTmp = pFrm->FindFtnBossFrm()->FindBodyCont(); if( !pTmp || !pTmp->Lower() ) bBreak = sal_False; } } UNDO_SWAP( pFrm ) return bBreak; } // OD 2004-02-27 #106629# - no longer inline void SwTxtFrmBreak::SetRstHeight( const SwTxtMargin &rLine ) { // OD, FME 2004-02-27 #106629# - consider bottom margin SWRECTFN( pFrm ) nRstHeight = (pFrm->*fnRect->fnGetBottomMargin)(); if ( bVert ) //Badaa: 2008-04-18 * Support for Classical Mongolian Script (SCMS) joint with Jiayanmin { if ( pFrm->IsVertLR() ) nRstHeight = (*fnRect->fnYDiff)( pFrm->SwitchHorizontalToVertical( rLine.Y() ) , nOrigin ); else nRstHeight += nOrigin - pFrm->SwitchHorizontalToVertical( rLine.Y() ); } else nRstHeight += rLine.Y() - nOrigin; } /************************************************************************* * WidowsAndOrphans::WidowsAndOrphans() *************************************************************************/ WidowsAndOrphans::WidowsAndOrphans( SwTxtFrm *pNewFrm, const SwTwips nRst, sal_Bool bChkKeep ) : SwTxtFrmBreak( pNewFrm, nRst ), nWidLines( 0 ), nOrphLines( 0 ) { SWAP_IF_SWAPPED( pFrm ) if( bKeep ) { // 5652: bei Absaetzen, die zusammengehalten werden sollen und // groesser sind als die Seite wird bKeep aufgehoben. if( bChkKeep && !pFrm->GetPrev() && !pFrm->IsInFtn() && pFrm->IsMoveable() && ( !pFrm->IsInSct() || pFrm->FindSctFrm()->MoveAllowed(pFrm) ) ) bKeep = sal_False; //Auch bei gesetztem Keep muessen Orphans beachtet werden, //z.B. bei verketteten Rahmen erhaelt ein Follow im letzten Rahmen ein Keep, //da er nicht (vorwaerts) Moveable ist, //er darf aber trotzdem vom Master Zeilen anfordern wg. der Orphanregel. if( pFrm->IsFollow() ) nWidLines = pFrm->GetTxtNode()->GetSwAttrSet().GetWidows().GetValue(); } else { const SwAttrSet& rSet = pFrm->GetTxtNode()->GetSwAttrSet(); const SvxOrphansItem &rOrph = rSet.GetOrphans(); if ( rOrph.GetValue() > 1 ) nOrphLines = rOrph.GetValue(); if ( pFrm->IsFollow() ) nWidLines = rSet.GetWidows().GetValue(); } if ( bKeep || nWidLines || nOrphLines ) { bool bResetFlags = false; if ( pFrm->IsInTab() ) { // For compatibility reasons, we disable Keep/Widows/Orphans // inside splittable row frames: if ( pFrm->GetNextCellLeaf( MAKEPAGE_NONE ) || pFrm->IsInFollowFlowRow() ) { const SwFrm* pTmpFrm = pFrm->GetUpper(); while ( !pTmpFrm->IsRowFrm() ) pTmpFrm = pTmpFrm->GetUpper(); if ( static_cast<const SwRowFrm*>(pTmpFrm)->IsRowSplitAllowed() ) bResetFlags = true; } } if( pFrm->IsInFtn() && !pFrm->GetIndPrev() ) { // Innerhalb von Fussnoten gibt es gute Gruende, das Keep-Attribut und // die Widows/Orphans abzuschalten. SwFtnFrm *pFtn = pFrm->FindFtnFrm(); sal_Bool bFt = !pFtn->GetAttr()->GetFtn().IsEndNote(); if( !pFtn->GetPrev() && pFtn->FindFtnBossFrm( bFt ) != pFtn->GetRef()->FindFtnBossFrm( bFt ) && ( !pFrm->IsInSct() || pFrm->FindSctFrm()->MoveAllowed(pFrm) ) ) { bResetFlags = true; } } if ( bResetFlags ) { bKeep = sal_False; nOrphLines = 0; nWidLines = 0; } } UNDO_SWAP( pFrm ) } /************************************************************************* * WidowsAndOrphans::FindBreak() *************************************************************************/ /* Die Find*-Methoden suchen nicht nur, sondern stellen den SwTxtMargin auf * die Zeile ein, wo der Absatz gebrochen werden soll und kuerzen ihn dort. * FindBreak() */ sal_Bool WidowsAndOrphans::FindBreak( SwTxtFrm *pFrame, SwTxtMargin &rLine, sal_Bool bHasToFit ) { // OD 2004-02-25 #i16128# - Why member <pFrm> _*and*_ parameter <pFrame>?? // Thus, assertion on situation, that these are different to figure out why. ASSERT( pFrm == pFrame, "<WidowsAndOrphans::FindBreak> - pFrm != pFrame" ); SWAP_IF_SWAPPED( pFrm ) sal_Bool bRet = sal_True; MSHORT nOldOrphans = nOrphLines; if( bHasToFit ) nOrphLines = 0; rLine.Bottom(); // OD 2004-02-25 #i16128# - method renamed if( !IsBreakNowWidAndOrp( rLine ) ) bRet = sal_False; if( !FindWidows( pFrame, rLine ) ) { sal_Bool bBack = sal_False; // OD 2004-02-25 #i16128# - method renamed while( IsBreakNowWidAndOrp( rLine ) ) { if( rLine.PrevLine() ) bBack = sal_True; else break; } // Eigentlich werden bei HasToFit Schusterjungen (Orphans) nicht // beruecksichtigt, wenn allerdings Dummy-Lines im Spiel sind und // die Orphansregel verletzt wird, machen wir mal eine Ausnahme: // Wir lassen einfach eine Dummyline zurueck und wandern mit dem Text // komplett auf die naechste Seite/Spalte. if( rLine.GetLineNr() <= nOldOrphans && rLine.GetInfo().GetParaPortion()->IsDummy() && ( ( bHasToFit && bRet ) || IsBreakNow( rLine ) ) ) rLine.Top(); rLine.TruncLines( sal_True ); bRet = bBack; } nOrphLines = nOldOrphans; UNDO_SWAP( pFrm ) return bRet; } /************************************************************************* * WidowsAndOrphans::FindWidows() *************************************************************************/ /* FindWidows positioniert den SwTxtMargin des Masters auf die umzubrechende * Zeile, indem der Follow formatiert und untersucht wird. * Liefert sal_True zurueck, wenn die Widows-Regelung in Kraft tritt, * d.h. der Absatz _zusammengehalten_ werden soll ! */ sal_Bool WidowsAndOrphans::FindWidows( SwTxtFrm *pFrame, SwTxtMargin &rLine ) { ASSERT( ! pFrame->IsVertical() || ! pFrame->IsSwapped(), "WidowsAndOrphans::FindWidows with swapped frame" ) if( !nWidLines || !pFrame->IsFollow() ) return sal_False; rLine.Bottom(); // Wir koennen noch was abzwacken SwTxtFrm *pMaster = pFrame->FindMaster(); ASSERT(pMaster, "+WidowsAndOrphans::FindWidows: Widows in a master?"); if( !pMaster ) return sal_False; // 5156: Wenn die erste Zeile des Follows nicht passt, wird der Master // wohl voll mit Dummies sein. In diesem Fall waere ein PREP_WIDOWS fatal. if( pMaster->GetOfst() == pFrame->GetOfst() ) return sal_False; // Resthoehe des Masters SWRECTFN( pFrame ) const SwTwips nDocPrtTop = (pFrame->*fnRect->fnGetPrtTop)(); SwTwips nOldHeight; SwTwips nTmpY = rLine.Y() + rLine.GetLineHeight(); if ( bVert ) { nTmpY = pFrame->SwitchHorizontalToVertical( nTmpY ); nOldHeight = -(pFrame->Prt().*fnRect->fnGetHeight)(); } else nOldHeight = (pFrame->Prt().*fnRect->fnGetHeight)(); const SwTwips nChg = (*fnRect->fnYDiff)( nTmpY, nDocPrtTop + nOldHeight ); // Unterhalb der Widows-Schwelle... if( rLine.GetLineNr() >= nWidLines ) { // 8575: Follow to Master I // Wenn der Follow *waechst*, so besteht fuer den Master die Chance, // Zeilen entgegenzunehmen, die er vor Kurzem gezwungen war an den // Follow abzugeben: Prepare(Need); diese Abfrage unterhalb von nChg! // (0W, 2O, 2M, 2F) + 1F = 3M, 2F if( rLine.GetLineNr() > nWidLines && pFrame->IsJustWidow() ) { // Wenn der Master gelockt ist, so hat er vermutlich gerade erst // eine Zeile an uns abgegeben, diese geben nicht zurueck, nur // weil bei uns daraus mehrere geworden sind (z.B. durch Rahmen). if( !pMaster->IsLocked() && pMaster->GetUpper() ) { const SwTwips nTmpRstHeight = (pMaster->Frm().*fnRect->fnBottomDist) ( (pMaster->GetUpper()->*fnRect->fnGetPrtBottom)() ); if ( nTmpRstHeight >= SwTwips(rLine.GetInfo().GetParaPortion()->Height() ) ) { pMaster->Prepare( PREP_ADJUST_FRM ); pMaster->_InvalidateSize(); pMaster->InvalidatePage(); } } pFrame->SetJustWidow( sal_False ); } return sal_False; } // 8575: Follow to Master II // Wenn der Follow *schrumpft*, so besteht fuer den Master die Chance, // den kompletten Orphan zu inhalieren. // (0W, 2O, 2M, 1F) - 1F = 3M, 0F -> PREP_ADJUST_FRM // (0W, 2O, 3M, 2F) - 1F = 2M, 2F -> PREP_WIDOWS if( 0 > nChg && !pMaster->IsLocked() && pMaster->GetUpper() ) { SwTwips nTmpRstHeight = (pMaster->Frm().*fnRect->fnBottomDist) ( (pMaster->GetUpper()->*fnRect->fnGetPrtBottom)() ); if( nTmpRstHeight >= SwTwips(rLine.GetInfo().GetParaPortion()->Height() ) ) { pMaster->Prepare( PREP_ADJUST_FRM ); pMaster->_InvalidateSize(); pMaster->InvalidatePage(); pFrame->SetJustWidow( sal_False ); return sal_False; } } // Master to Follow // Wenn der Follow nach seiner Formatierung weniger Zeilen enthaelt // als Widows, so besteht noch die Chance, einige Zeilen des Masters // abzuzwacken. Wenn dadurch die Orphans-Regel des Masters in Kraft // tritt muss im CalcPrep() des Master-Frame der Frame so vergroessert // werden, dass er nicht mehr auf seine urspruengliche Seite passt. // Wenn er noch ein paar Zeilen entbehren kann, dann muss im CalcPrep() // ein Shrink() erfolgen, der Follow mit dem Widows rutscht dann auf // die Seite des Masters, haelt sich aber zusammen, so dass er (endlich) // auf die naechste Seite rutscht. - So die Theorie! // Wir fordern nur noch ein Zeile zur Zeit an, weil eine Zeile des Masters // bei uns durchaus mehrere Zeilen ergeben koennten. // Dafuer behaelt CalcFollow solange die Kontrolle, bis der Follow alle // notwendigen Zeilen bekommen hat. MSHORT nNeed = 1; // frueher: nWidLines - rLine.GetLineNr(); // Special case: Master cannot give lines to follow // --> FME 2008-09-16 #i91421# if ( !pMaster->GetIndPrev() ) { sal_uLong nLines = pMaster->GetThisLines(); if(nLines == 0 && pMaster->HasPara()) { const SwParaPortion *pMasterPara = pMaster->GetPara(); if(pMasterPara && pMasterPara->GetNext()) nLines = 2; } if( nLines <= nNeed ) return sal_False; } pMaster->Prepare( PREP_WIDOWS, (void*)&nNeed ); return sal_True; } /************************************************************************* * WidowsAndOrphans::WouldFit() *************************************************************************/ sal_Bool WidowsAndOrphans::WouldFit( SwTxtMargin &rLine, SwTwips &rMaxHeight, sal_Bool bTst ) { // Here it does not matter, if pFrm is swapped or not. // IsInside() takes care for itself // Wir erwarten, dass rLine auf der letzten Zeile steht!! ASSERT( !rLine.GetNext(), "WouldFit: aLine::Bottom missed!" ); MSHORT nLineCnt = rLine.GetLineNr(); // Erstmal die Orphansregel und den Initialenwunsch erfuellen ... const MSHORT nMinLines = Max( GetOrphansLines(), rLine.GetDropLines() ); if ( nLineCnt < nMinLines ) return sal_False; rLine.Top(); SwTwips nLineSum = rLine.GetLineHeight(); while( nMinLines > rLine.GetLineNr() ) { DBG_LOOP; if( !rLine.NextLine() ) return sal_False; nLineSum += rLine.GetLineHeight(); } // Wenn wir jetzt schon nicht mehr passen ... if( !IsInside( rLine ) ) return sal_False; // Jetzt noch die Widows-Regel ueberpruefen if( !nWidLines && !pFrm->IsFollow() ) { // I.A. brauchen Widows nur ueberprueft werden, wenn wir ein Follow // sind. Bei WouldFit muss aber auch fuer den Master die Regel ueber- // prueft werden, weil wir ja gerade erst die Trennstelle ermitteln. // Im Ctor von WidowsAndOrphans wurde nWidLines aber nur fuer Follows // aus dem AttrSet ermittelt, deshalb holen wir es hier nach: const SwAttrSet& rSet = pFrm->GetTxtNode()->GetSwAttrSet(); nWidLines = rSet.GetWidows().GetValue(); } // Sind nach Orphans/Initialen noch genug Zeilen fuer die Widows uebrig? // #111937#: If we are currently doing a test formatting, we may not // consider the widows rule for two reasons: // 1. The columns may have different widths. // Widow lines would have wrong width. // 2. Test formatting is only done up to the given space. // we do not have any lines for widows at all. if( bTst || nLineCnt - nMinLines >= GetWidowsLines() ) { if( rMaxHeight >= nLineSum ) { rMaxHeight -= nLineSum; return sal_True; } } return sal_False; }
34.400685
99
0.609706
Grosskopf
8904f7bd15a658d3e38bd83e3df7292e443b5f28
147
cpp
C++
common/crc32.cpp
cschreib/cobalt
11184864008f411875a3321f3fb4493ebc9a79e2
[ "MIT" ]
9
2015-12-09T22:25:25.000Z
2022-01-12T23:50:56.000Z
common/crc32.cpp
cschreib/cobalt
11184864008f411875a3321f3fb4493ebc9a79e2
[ "MIT" ]
6
2019-12-28T21:18:16.000Z
2020-02-15T21:04:54.000Z
common/crc32.cpp
cschreib/cobalt
11184864008f411875a3321f3fb4493ebc9a79e2
[ "MIT" ]
null
null
null
#include "crc32.hpp" std::uint32_t get_crc32(const std::string& str) { return recursive_crc32(0, str.c_str(), 0, str.size(), 0, 0x4C11DB7); }
24.5
72
0.680272
cschreib
890b3e947225c14bf71935b487d6202fac00c508
884
hpp
C++
code/interface.hpp
BrunoFCM/CAL_projeto
1b0ebadd350dcbbc7d5ee99d93cb98a377fd8b56
[ "MIT" ]
1
2021-01-12T12:33:00.000Z
2021-01-12T12:33:00.000Z
code/interface.hpp
BrunoFCM/CAL_projeto
1b0ebadd350dcbbc7d5ee99d93cb98a377fd8b56
[ "MIT" ]
null
null
null
code/interface.hpp
BrunoFCM/CAL_projeto
1b0ebadd350dcbbc7d5ee99d93cb98a377fd8b56
[ "MIT" ]
null
null
null
#include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include "Group.hpp" #include "bus.hpp" #include "TouristGenerator.hpp" #include "TouristOrganizer.hpp" using namespace std; #define INPUT_FILE "input.txt" #define NODES_FILE "T03_nodes_X_Y_Fafe.txt" #define EDGES_FILE "T03_edges_Fafe.txt" bool loadTourists(vector<Tourist*> &tourists, vector<Bus*> &buses); void loadMap(Graph &map); void add_tourist(vector<Tourist*> &tourists); void add_bus(vector<Bus*> &buses); void check_tourist(vector<Tourist*> &tourists); void check_bus(vector<Bus*> &buses); void get_path(vector<Tourist*> &tourists, vector<Bus*> &buses, Graph &map); void get_groups(vector<Tourist*> &tourists, vector<Bus*> &buses, Graph &map); void random_tourist(vector<Tourist*> &tourists); void app_interface(vector<Tourist*> &tourists, vector<Bus*> &buses, Graph &map);
34
80
0.755656
BrunoFCM
890b513697fc86cfa7bc39c59f5da14dcfeb889c
237
cpp
C++
LeetCode/Solutions/LC0231.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
54
2019-05-13T12:13:09.000Z
2022-02-27T02:59:00.000Z
LeetCode/Solutions/LC0231.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
2
2020-10-02T07:16:43.000Z
2020-10-19T04:36:19.000Z
LeetCode/Solutions/LC0231.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
20
2020-05-26T09:48:13.000Z
2022-03-18T15:18:27.000Z
/* Problem Statement: https://leetcode.com/problems/power-of-two/ Time: O(1) Space: O(1) Author: Mohammed Shoaib, github.com/Mohammed-Shoaib */ class Solution { public: bool isPowerOfTwo(int n) { return n > 0 && !(n & (n - 1)); } };
18.230769
62
0.658228
Mohammed-Shoaib
890e53d44e8c004fb4338263bb04432caaec9846
3,146
cpp
C++
src/ipog/DitherAdapter.cpp
vallant/reta
f9eb515a956ebdb8163beda0cd927dfc64875b62
[ "MIT" ]
1
2022-01-04T17:20:13.000Z
2022-01-04T17:20:13.000Z
src/ipog/DitherAdapter.cpp
vallant/reta
f9eb515a956ebdb8163beda0cd927dfc64875b62
[ "MIT" ]
null
null
null
src/ipog/DitherAdapter.cpp
vallant/reta
f9eb515a956ebdb8163beda0cd927dfc64875b62
[ "MIT" ]
null
null
null
#include "DitherAdapter.h" #include <dither.h> #include <test/ConfigGenerator.h> #include <util/Util.h> TestConfigurations DitherAdapter::generate (Plugin* plugin, const GenerateCommand::Parameters& parameters) { return generate (plugin->getInfo(), parameters); } TestConfigurations DitherAdapter::generate (const Plugin::Info& info, const GenerateCommand::Parameters& parameters) { auto blockSizes = ConfigGenerator::blockSizes(); auto sampleRates = ConfigGenerator::sampleRates(); auto signals = ConfigGenerator::signals(); auto values = ConfigGenerator::values(); auto blockSizeIndices = util::vecToIndices (blockSizes); auto sampleRateIndices = util::vecToIndices (sampleRates); auto signalIndices = util::vecToIndices (signals); auto layoutIndices = util::vecToIndices (info.layouts); auto valueIndices = util::vecToIndices (values); auto handle = dither_ipog_new (parameters.interactions); int index = 0; dither_ipog_add_parameter_int (handle, index++, blockSizeIndices.data(), static_cast<int> (blockSizeIndices.size())); dither_ipog_add_parameter_int (handle, index++, sampleRateIndices.data(), static_cast<int> (sampleRateIndices.size())); dither_ipog_add_parameter_int (handle, index++, signalIndices.data(), static_cast<int> (signalIndices.size())); dither_ipog_add_parameter_int (handle, index++, layoutIndices.data(), static_cast<int> (layoutIndices.size())); std::vector<Plugin::ParameterInfo> includedParameters; for ( auto& param : info.parameters ) { if ( ! util::matchedByAnyWildcard (parameters.exclude, param.name) ) includedParameters.push_back (param); } for ( auto& param : includedParameters ) { auto steps = param.discrete ? util::vecToIndices (param.values) : valueIndices; dither_ipog_add_parameter_int (handle, index++, steps.data(), static_cast<int> (steps.size())); } dither_ipog_run (handle); auto numParameters = index; auto numTests = dither_ipog_size (handle); std::vector<int> result (numParameters * numTests); dither_ipog_fill (handle, result.data()); TestConfigurations configs (numTests); for ( int i = 0; i < numTests; ++i ) { auto offset = i * numParameters; configs[i].blockSize = static_cast<int> (blockSizes[result[offset + 0]]); configs[i].sampleRate = sampleRates[result[offset + 1]]; configs[i].inputSignal = signals[result[offset + 2]]; configs[i].layout = info.layouts[result[offset + 3]]; for ( size_t parameterIndex = 0; parameterIndex < includedParameters.size(); ++parameterIndex ) { auto& param = includedParameters[parameterIndex]; auto viableValues = param.discrete ? param.values : ConfigGenerator::values(); auto value = viableValues[result[offset + 4 + parameterIndex]]; configs[i].parameters.push_back ({param.name, value}); } } return configs; }
41.394737
117
0.660839
vallant
8913a1fadb946bca918fdf7792263d1e2c83ea9c
571
cpp
C++
c3dEngine2/c3dEngine/c3dEngine/core/c3dGlobalTimer.cpp
wantnon2/c3dEngine2
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
[ "MIT" ]
27
2015-01-11T15:42:21.000Z
2021-10-10T06:24:37.000Z
c3dEngine2/c3dEngine/c3dEngine/core/c3dGlobalTimer.cpp
wantnon2/c3dEngine2
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
[ "MIT" ]
null
null
null
c3dEngine2/c3dEngine/c3dEngine/core/c3dGlobalTimer.cpp
wantnon2/c3dEngine2
0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1
[ "MIT" ]
18
2015-01-11T15:42:28.000Z
2021-10-10T06:24:38.000Z
// // c3dGlobalTimer.cpp // HelloOpenGL // // Created by wantnon (yang chao) on 12-11-19. // // #include "c3dGlobalTimer.h" static Cc3dGlobalTimer*s_globalTimer=NULL; Cc3dGlobalTimer*Cc3dGlobalTimer::sharedGlobalTimer(){ if(s_globalTimer==NULL){ s_globalTimer=new Cc3dGlobalTimer(); } return s_globalTimer; } //-------------------- static Cc3dFrameCounter*s_frameCounter=NULL; Cc3dFrameCounter*Cc3dFrameCounter::sharedFrameCounter(){ if(s_frameCounter==NULL){ s_frameCounter=new Cc3dFrameCounter(); } return s_frameCounter; }
21.961538
56
0.698774
wantnon2
891d23337829d76802201a034f1fd38f24e9733f
16,168
cc
C++
mac/chatkit/cim/pb/CIM.Friend.pb.cc
xmcy0011/CoffeeChat-Desktop
20b907e95ec8b481dbbb77a3b22587ac108520fb
[ "MIT" ]
1
2021-08-05T10:32:24.000Z
2021-08-05T10:32:24.000Z
mac/chatkit/cim/pb/CIM.Friend.pb.cc
xmcy0011/CoffeeChat-Desktop
20b907e95ec8b481dbbb77a3b22587ac108520fb
[ "MIT" ]
null
null
null
mac/chatkit/cim/pb/CIM.Friend.pb.cc
xmcy0011/CoffeeChat-Desktop
20b907e95ec8b481dbbb77a3b22587ac108520fb
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: CIM.Friend.proto #include "CIM.Friend.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace CIM { namespace Friend { constexpr CIMFriendQueryUserListReq::CIMFriendQueryUserListReq( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : user_id_(PROTOBUF_ULONGLONG(0)){} struct CIMFriendQueryUserListReqDefaultTypeInternal { constexpr CIMFriendQueryUserListReqDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~CIMFriendQueryUserListReqDefaultTypeInternal() {} union { CIMFriendQueryUserListReq _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT CIMFriendQueryUserListReqDefaultTypeInternal _CIMFriendQueryUserListReq_default_instance_; constexpr CIMFriendQueryUserListRsp::CIMFriendQueryUserListRsp( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : user_info_list_() , user_id_(PROTOBUF_ULONGLONG(0)){} struct CIMFriendQueryUserListRspDefaultTypeInternal { constexpr CIMFriendQueryUserListRspDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~CIMFriendQueryUserListRspDefaultTypeInternal() {} union { CIMFriendQueryUserListRsp _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT CIMFriendQueryUserListRspDefaultTypeInternal _CIMFriendQueryUserListRsp_default_instance_; } // namespace Friend } // namespace CIM namespace CIM { namespace Friend { // =================================================================== class CIMFriendQueryUserListReq::_Internal { public: }; CIMFriendQueryUserListReq::CIMFriendQueryUserListReq(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:CIM.Friend.CIMFriendQueryUserListReq) } CIMFriendQueryUserListReq::CIMFriendQueryUserListReq(const CIMFriendQueryUserListReq& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite() { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); user_id_ = from.user_id_; // @@protoc_insertion_point(copy_constructor:CIM.Friend.CIMFriendQueryUserListReq) } void CIMFriendQueryUserListReq::SharedCtor() { user_id_ = PROTOBUF_ULONGLONG(0); } CIMFriendQueryUserListReq::~CIMFriendQueryUserListReq() { // @@protoc_insertion_point(destructor:CIM.Friend.CIMFriendQueryUserListReq) SharedDtor(); _internal_metadata_.Delete<std::string>(); } void CIMFriendQueryUserListReq::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void CIMFriendQueryUserListReq::ArenaDtor(void* object) { CIMFriendQueryUserListReq* _this = reinterpret_cast< CIMFriendQueryUserListReq* >(object); (void)_this; } void CIMFriendQueryUserListReq::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void CIMFriendQueryUserListReq::SetCachedSize(int size) const { _cached_size_.Set(size); } void CIMFriendQueryUserListReq::Clear() { // @@protoc_insertion_point(message_clear_start:CIM.Friend.CIMFriendQueryUserListReq) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; user_id_ = PROTOBUF_ULONGLONG(0); _internal_metadata_.Clear<std::string>(); } const char* CIMFriendQueryUserListReq::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint64 user_id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { user_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* CIMFriendQueryUserListReq::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:CIM.Friend.CIMFriendQueryUserListReq) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint64 user_id = 1; if (this->user_id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(1, this->_internal_user_id(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:CIM.Friend.CIMFriendQueryUserListReq) return target; } size_t CIMFriendQueryUserListReq::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:CIM.Friend.CIMFriendQueryUserListReq) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // uint64 user_id = 1; if (this->user_id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size( this->_internal_user_id()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CIMFriendQueryUserListReq::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const CIMFriendQueryUserListReq*>( &from)); } void CIMFriendQueryUserListReq::MergeFrom(const CIMFriendQueryUserListReq& from) { // @@protoc_insertion_point(class_specific_merge_from_start:CIM.Friend.CIMFriendQueryUserListReq) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.user_id() != 0) { _internal_set_user_id(from._internal_user_id()); } } void CIMFriendQueryUserListReq::CopyFrom(const CIMFriendQueryUserListReq& from) { // @@protoc_insertion_point(class_specific_copy_from_start:CIM.Friend.CIMFriendQueryUserListReq) if (&from == this) return; Clear(); MergeFrom(from); } bool CIMFriendQueryUserListReq::IsInitialized() const { return true; } void CIMFriendQueryUserListReq::InternalSwap(CIMFriendQueryUserListReq* other) { using std::swap; _internal_metadata_.Swap<std::string>(&other->_internal_metadata_); swap(user_id_, other->user_id_); } std::string CIMFriendQueryUserListReq::GetTypeName() const { return "CIM.Friend.CIMFriendQueryUserListReq"; } // =================================================================== class CIMFriendQueryUserListRsp::_Internal { public: }; void CIMFriendQueryUserListRsp::clear_user_info_list() { user_info_list_.Clear(); } CIMFriendQueryUserListRsp::CIMFriendQueryUserListRsp(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena), user_info_list_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:CIM.Friend.CIMFriendQueryUserListRsp) } CIMFriendQueryUserListRsp::CIMFriendQueryUserListRsp(const CIMFriendQueryUserListRsp& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), user_info_list_(from.user_info_list_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); user_id_ = from.user_id_; // @@protoc_insertion_point(copy_constructor:CIM.Friend.CIMFriendQueryUserListRsp) } void CIMFriendQueryUserListRsp::SharedCtor() { user_id_ = PROTOBUF_ULONGLONG(0); } CIMFriendQueryUserListRsp::~CIMFriendQueryUserListRsp() { // @@protoc_insertion_point(destructor:CIM.Friend.CIMFriendQueryUserListRsp) SharedDtor(); _internal_metadata_.Delete<std::string>(); } void CIMFriendQueryUserListRsp::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void CIMFriendQueryUserListRsp::ArenaDtor(void* object) { CIMFriendQueryUserListRsp* _this = reinterpret_cast< CIMFriendQueryUserListRsp* >(object); (void)_this; } void CIMFriendQueryUserListRsp::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void CIMFriendQueryUserListRsp::SetCachedSize(int size) const { _cached_size_.Set(size); } void CIMFriendQueryUserListRsp::Clear() { // @@protoc_insertion_point(message_clear_start:CIM.Friend.CIMFriendQueryUserListRsp) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; user_info_list_.Clear(); user_id_ = PROTOBUF_ULONGLONG(0); _internal_metadata_.Clear<std::string>(); } const char* CIMFriendQueryUserListRsp::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // uint64 user_id = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { user_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .CIM.Def.CIMUserInfo user_info_list = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_user_info_list(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<18>(ptr)); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* CIMFriendQueryUserListRsp::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:CIM.Friend.CIMFriendQueryUserListRsp) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // uint64 user_id = 1; if (this->user_id() != 0) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt64ToArray(1, this->_internal_user_id(), target); } // repeated .CIM.Def.CIMUserInfo user_info_list = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_user_info_list_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(2, this->_internal_user_info_list(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:CIM.Friend.CIMFriendQueryUserListRsp) return target; } size_t CIMFriendQueryUserListRsp::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:CIM.Friend.CIMFriendQueryUserListRsp) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .CIM.Def.CIMUserInfo user_info_list = 2; total_size += 1UL * this->_internal_user_info_list_size(); for (const auto& msg : this->user_info_list_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // uint64 user_id = 1; if (this->user_id() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt64Size( this->_internal_user_id()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CIMFriendQueryUserListRsp::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const CIMFriendQueryUserListRsp*>( &from)); } void CIMFriendQueryUserListRsp::MergeFrom(const CIMFriendQueryUserListRsp& from) { // @@protoc_insertion_point(class_specific_merge_from_start:CIM.Friend.CIMFriendQueryUserListRsp) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; user_info_list_.MergeFrom(from.user_info_list_); if (from.user_id() != 0) { _internal_set_user_id(from._internal_user_id()); } } void CIMFriendQueryUserListRsp::CopyFrom(const CIMFriendQueryUserListRsp& from) { // @@protoc_insertion_point(class_specific_copy_from_start:CIM.Friend.CIMFriendQueryUserListRsp) if (&from == this) return; Clear(); MergeFrom(from); } bool CIMFriendQueryUserListRsp::IsInitialized() const { return true; } void CIMFriendQueryUserListRsp::InternalSwap(CIMFriendQueryUserListRsp* other) { using std::swap; _internal_metadata_.Swap<std::string>(&other->_internal_metadata_); user_info_list_.InternalSwap(&other->user_info_list_); swap(user_id_, other->user_id_); } std::string CIMFriendQueryUserListRsp::GetTypeName() const { return "CIM.Friend.CIMFriendQueryUserListRsp"; } // @@protoc_insertion_point(namespace_scope) } // namespace Friend } // namespace CIM PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::CIM::Friend::CIMFriendQueryUserListReq* Arena::CreateMaybeMessage< ::CIM::Friend::CIMFriendQueryUserListReq >(Arena* arena) { return Arena::CreateMessageInternal< ::CIM::Friend::CIMFriendQueryUserListReq >(arena); } template<> PROTOBUF_NOINLINE ::CIM::Friend::CIMFriendQueryUserListRsp* Arena::CreateMaybeMessage< ::CIM::Friend::CIMFriendQueryUserListRsp >(Arena* arena) { return Arena::CreateMessageInternal< ::CIM::Friend::CIMFriendQueryUserListRsp >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
36.662132
156
0.746598
xmcy0011
89232393ffcdec7f58dda27e0baea19f45c83444
5,658
cpp
C++
dlls/usas.cpp
solidi/coldice-remastered
e383047320d8cd321d716cdd7cc336231b58bbe1
[ "Unlicense" ]
2
2022-01-04T09:37:40.000Z
2022-01-12T22:18:54.000Z
dlls/usas.cpp
solidi/coldice-remastered
e383047320d8cd321d716cdd7cc336231b58bbe1
[ "Unlicense" ]
null
null
null
dlls/usas.cpp
solidi/coldice-remastered
e383047320d8cd321d716cdd7cc336231b58bbe1
[ "Unlicense" ]
1
2022-01-06T23:03:05.000Z
2022-01-06T23:03:05.000Z
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "weapons.h" #include "nodes.h" #include "player.h" #include "gamerules.h" // special deathmatch shotgun spreads #define VECTOR_CONE_DM_SHOTGUN Vector( 0.08716, 0.04362, 0.00 )// 10 degrees by 5 degrees #define VECTOR_CONE_DM_DOUBLESHOTGUN Vector( 0.17365, 0.04362, 0.00 ) // 20 degrees by 5 degrees enum usas_e { USAS_AIM = 0, USAS_LONGIDLE, USAS_IDLE1, USAS_LAUNCH, USAS_RELOAD, USAS_DEPLOY, USAS_FIRE1, USAS_FIRE2, USAS_FIRE3, USAS_HOLSTER, }; #ifdef USAS LINK_ENTITY_TO_CLASS( weapon_usas, CUsas ); #endif void CUsas::Spawn( ) { Precache( ); m_iId = WEAPON_USAS; SET_MODEL(ENT(pev), "models/w_usas.mdl"); m_iDefaultAmmo = USAS_DEFAULT_GIVE; FallInit();// get ready to fall } void CUsas::Precache( void ) { PRECACHE_MODEL("models/v_usas.mdl"); PRECACHE_MODEL("models/w_usas.mdl"); PRECACHE_MODEL("models/p_usas.mdl"); m_iShell = PRECACHE_MODEL ("models/w_shotgunshell.mdl");// shotgun shell PRECACHE_SOUND("items/9mmclip1.wav"); PRECACHE_SOUND ("usas_fire.wav"); PRECACHE_SOUND ("weapons/reload1.wav"); // shotgun reload PRECACHE_SOUND ("weapons/reload3.wav"); // shotgun reload PRECACHE_SOUND ("weapons/357_cock1.wav"); // gun empty sound PRECACHE_SOUND ("weapons/scock1.wav"); // cock gun m_usSingleFire = PRECACHE_EVENT( 1, "events/usas.sc" ); } int CUsas::AddToPlayer( CBasePlayer *pPlayer ) { if ( CBasePlayerWeapon::AddToPlayer( pPlayer ) ) { MESSAGE_BEGIN( MSG_ONE, gmsgWeapPickup, NULL, pPlayer->pev ); WRITE_BYTE( m_iId ); MESSAGE_END(); return TRUE; } return FALSE; } int CUsas::GetItemInfo(ItemInfo *p) { p->pszName = STRING(pev->classname); p->pszAmmo1 = "buckshot"; p->iMaxAmmo1 = BUCKSHOT_MAX_CARRY; p->pszAmmo2 = NULL; p->iMaxAmmo2 = -1; p->iMaxClip = USAS_MAX_CLIP; p->iSlot = 2; p->iPosition = 3; p->iFlags = 0; p->iId = m_iId = WEAPON_USAS; p->iWeight = USAS_WEIGHT; p->pszDisplayName = "USAS-12 Auto Shotgun"; return 1; } BOOL CUsas::Deploy( ) { return DefaultDeploy( "models/v_usas.mdl", "models/p_usas.mdl", USAS_DEPLOY, "mp5" ); } void CUsas::Holster( int skiplocal /* = 0 */ ) { m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 0.5; SendWeaponAnim( USAS_HOLSTER ); } void CUsas::PrimaryAttack() { // don't fire underwater if (m_pPlayer->pev->waterlevel == 3) { PlayEmptySound( ); m_flNextPrimaryAttack = GetNextAttackDelay(0.15); return; } if (m_iClip <= 0) { Reload( ); if (m_iClip == 0) PlayEmptySound( ); return; } m_pPlayer->m_iWeaponVolume = LOUD_GUN_VOLUME; m_pPlayer->m_iWeaponFlash = NORMAL_GUN_FLASH; m_iClip--; int flags; #if defined( CLIENT_WEAPONS ) flags = FEV_NOTHOST; #else flags = 0; #endif m_pPlayer->pev->effects = (int)(m_pPlayer->pev->effects) | EF_MUZZLEFLASH; // player "shoot" animation m_pPlayer->SetAnimation( PLAYER_ATTACK1 ); Vector vecSrc = m_pPlayer->GetGunPosition( ); Vector vecAiming = m_pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES ); Vector vecDir; #ifdef CLIENT_DLL if ( bIsMultiplayer() ) #else if ( g_pGameRules->IsMultiplayer() ) #endif { vecDir = m_pPlayer->FireBulletsPlayer( 4, vecSrc, vecAiming, VECTOR_CONE_DM_SHOTGUN, 2048, BULLET_PLAYER_BUCKSHOT, 0, 0, m_pPlayer->pev, m_pPlayer->random_seed ); } else { // regular old, untouched spread. vecDir = m_pPlayer->FireBulletsPlayer( 6, vecSrc, vecAiming, VECTOR_CONE_10DEGREES, 2048, BULLET_PLAYER_BUCKSHOT, 0, 0, m_pPlayer->pev, m_pPlayer->random_seed ); } PLAYBACK_EVENT_FULL( flags, m_pPlayer->edict(), m_usSingleFire, 0.0, (float *)&g_vecZero, (float *)&g_vecZero, vecDir.x, vecDir.y, 0, 0, 0, 0 ); if (!m_iClip && m_pPlayer->m_rgAmmo[m_iPrimaryAmmoType] <= 0) // HEV suit - indicate out of ammo condition m_pPlayer->SetSuitUpdate("!HEV_AMO0", FALSE, 0); m_flNextPrimaryAttack = GetNextAttackDelay(0.25); m_flNextSecondaryAttack = UTIL_WeaponTimeBase() + 0.25; if (m_iClip != 0) m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 5.0; else m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + 0.75; m_fInSpecialReload = 0; } void CUsas::Reload( void ) { if ( m_pPlayer->ammo_buckshot <= 0 ) return; DefaultReload( USAS_MAX_CLIP, USAS_RELOAD, 1.5 ); } void CUsas::WeaponIdle( void ) { ResetEmptySound( ); m_pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES ); if ( m_flTimeWeaponIdle > UTIL_WeaponTimeBase() ) return; if ( m_pPlayer->pev->button & IN_IRONSIGHT ) return; int iAnim; switch ( RANDOM_LONG( 0, 1 ) ) { case 0: iAnim = USAS_LONGIDLE; break; default: case 1: iAnim = USAS_IDLE1; break; } SendWeaponAnim( iAnim ); m_flTimeWeaponIdle = UTIL_SharedRandomFloat( m_pPlayer->random_seed, 10, 15 ); // how long till we do this again. } void CUsas::ProvideDualItem(CBasePlayer *pPlayer, const char *item) { if (item == NULL) { return; } #ifndef CLIENT_DLL if (!stricmp(item, "weapon_usas")) { if (!pPlayer->HasNamedPlayerItem("weapon_dual_usas")) { pPlayer->GiveNamedItem("weapon_dual_usas"); ALERT(at_aiconsole, "Give weapon_dual_usas!\n"); } } #endif } void CUsas::SwapDualWeapon( void ) { m_pPlayer->SelectItem("weapon_dual_usas"); }
23.093878
164
0.711205
solidi
8929b24024e725fe891a9dc1a28aa566604596e6
7,158
cpp
C++
3rdparty/nana/source/system/dataexch.cpp
Greentwip/windy
4eb8174f952c5b600ff004827a5c85dbfb013091
[ "MIT" ]
1
2017-07-13T21:11:55.000Z
2017-07-13T21:11:55.000Z
3rdparty/nana/source/system/dataexch.cpp
Greentwip/Windy
4eb8174f952c5b600ff004827a5c85dbfb013091
[ "MIT" ]
null
null
null
3rdparty/nana/source/system/dataexch.cpp
Greentwip/Windy
4eb8174f952c5b600ff004827a5c85dbfb013091
[ "MIT" ]
null
null
null
/* * Data Exchanger Implementation * Copyright(C) 2003-2013 Jinhao(cnjinhao@hotmail.com) * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * @file: nana/system/dataexch.cpp * @description: An implementation of a data exchange mechanism through Windows Clipboard, X11 Selection. */ #include <nana/system/dataexch.hpp> #include <nana/traits.hpp> #include <nana/paint/graphics.hpp> #include <vector> #include <cassert> #if defined(NANA_WINDOWS) #include <windows.h> #elif defined(NANA_X11) #include PLATFORM_SPEC_HPP #include <nana/gui/detail/bedrock.hpp> #include <nana/gui/detail/basic_window.hpp> #endif namespace nana{ namespace system{ //class dataexch void dataexch::set(const nana::char_t* text) { _m_set(std::is_same<char, nana::char_t>::value ? format::text : format::unicode, text, (nana::strlen(text) + 1) * sizeof(nana::char_t)); } void dataexch::set(const nana::string& text) { _m_set(std::is_same<char, nana::char_t>::value ? format::text : format::unicode, text.c_str(), (text.length() + 1) * sizeof(nana::char_t)); } bool dataexch::set(const nana::paint::graphics& g) { #if defined(NANA_WINDOWS) size sz = g.size(); paint::pixel_buffer pbuffer; rectangle r; r.x = 0; r.y = 0; r.width = sz.width; r.height = sz.height; pbuffer.attach(g.handle(), r); size_t bytes_per_line = pbuffer.bytes_per_line(); size_t bitmap_bytes = bytes_per_line * r.height; struct { BITMAPINFOHEADER bmiHeader; RGBQUAD bmiColors[256]; } bmi = {0}; bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); HDC hDC = ::GetDC(NULL); if (::GetDIBits(hDC, (HBITMAP)g.pixmap(), 0, 1, NULL, (BITMAPINFO *)&bmi, DIB_RGB_COLORS) == 0) { assert(false); ::ReleaseDC(NULL, hDC); return false; } if (!::ReleaseDC(NULL, hDC)) { return false; } size_t header_size = sizeof(bmi.bmiHeader); // Bitmaps are huge, so to avoid unnegligible extra copy, this routine does not use private _m_set method. HGLOBAL h_gmem = ::GlobalAlloc(GHND | GMEM_SHARE, header_size + bitmap_bytes); void * gmem = ::GlobalLock(h_gmem); if (gmem) { char* p = (char*)gmem; // Fix BITMAPINFOHEADER obtained from GetDIBits WinAPI bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biHeight = ::abs(bmi.bmiHeader.biHeight); memcpy(p, &bmi, header_size); p += header_size; // many programs do not support bottom-up DIB, so reversing row order is needed. for (int y=0; y<bmi.bmiHeader.biHeight; ++y) { memcpy(p, pbuffer.raw_ptr(bmi.bmiHeader.biHeight - 1 - y), bytes_per_line); p += bytes_per_line; } if (::GlobalUnlock(h_gmem) || GetLastError() == NO_ERROR) if (::OpenClipboard(::GetFocus())) if (::EmptyClipboard()) if (::SetClipboardData(CF_DIB, h_gmem)) if (::CloseClipboard()) return true; } assert(false); ::GlobalFree(h_gmem); return false; //#elif defined(NANA_X11) #else throw "not implemented yet."; return false; #endif } void dataexch::get(nana::string& str) { std::size_t size; void* res = _m_get(std::is_same<char, nana::char_t>::value ? format::text : format::unicode, size); if(res) { #if defined(NANA_X11) && defined(NANA_UNICODE) nana::detail::charset_conv conv("UTF-32", "UTF-8"); const std::string & utf32str = conv.charset(reinterpret_cast<char*>(res), size); const nana::char_t * utf32ptr = reinterpret_cast<const nana::char_t*>(utf32str.c_str()); str.append(utf32ptr + 1, utf32ptr + utf32str.size() / sizeof(nana::char_t)); #else str.reserve(size / sizeof(nana::char_t)); str.append(reinterpret_cast<nana::char_t*>(res), reinterpret_cast<nana::char_t*>(res) + size / sizeof(nana::char_t)); nana::string::size_type pos = str.find_last_not_of(nana::char_t(0)); if(pos != str.npos) str.erase(pos + 1); #endif #if defined(NANA_X11) ::XFree(res); #endif } } //private: bool dataexch::_m_set(unsigned type, const void* buf, std::size_t size) { bool res = false; #if defined(NANA_WINDOWS) if(type < format::end && ::OpenClipboard(::GetFocus())) { if(::EmptyClipboard()) { HGLOBAL g = ::GlobalAlloc(GHND | GMEM_SHARE, size); void * addr = ::GlobalLock(g); memcpy(addr, buf, size); ::GlobalUnlock(g); switch(type) { case format::text: type = CF_TEXT; break; case format::unicode: type = CF_UNICODETEXT; break; case format::pixmap: type = CF_BITMAP; break; } HANDLE h = ::SetClipboardData(type, g); res = (h != NULL); } ::CloseClipboard(); } #elif defined(NANA_X11) auto & spec = ::nana::detail::platform_spec::instance(); native_window_type owner = nullptr; { internal_scope_guard lock; auto wd = detail::bedrock::instance().focus(); if(wd) owner = wd->root; } if(owner) { Atom atom_type; switch(type) { case format::text: atom_type = XA_STRING; break; case format::unicode: atom_type = spec.atombase().utf8_string; break; default: return false; } #if defined(NANA_UNICODE) //The internal clipboard stores UTF8_STRING, the parameter string should be converted from utf32 to utf8. nana::detail::charset_conv conv("UTF-8", "UTF-32"); std::string utf8str = conv.charset(reinterpret_cast<const char*>(buf), size); buf = utf8str.c_str(); size = utf8str.size(); #endif spec.write_selection(owner, atom_type, buf, size); return true; } #endif return res; } void* dataexch::_m_get(unsigned type, size_t& size) { void* res = 0; #if defined(NANA_WINDOWS) if(type < format::end && ::OpenClipboard(::GetFocus())) { switch(type) { case format::text: type = CF_TEXT; break; case format::unicode: type = CF_UNICODETEXT; break; case format::pixmap: type = CF_BITMAP; break; } HANDLE handle = ::GetClipboardData(type); if(handle) { res = reinterpret_cast<HGLOBAL>(::GlobalLock(handle)); if(res) size = ::GlobalSize(handle); } ::CloseClipboard(); } #elif defined(NANA_X11) nana::detail::platform_spec & spec = nana::detail::platform_spec::instance(); native_window_type requester = nullptr; spec.lock_xlib(); { internal_scope_guard isg; detail::bedrock::core_window_t * wd = detail::bedrock::instance().focus(); if(wd) requester = wd->root; } spec.unlock_xlib(); if(requester) { Atom atom; switch(type) { case format::text: atom = XA_STRING; break; case format::unicode: atom = spec.atombase().utf8_string; break; default: return 0; } res = spec.request_selection(requester, atom, size); } #endif return res; } //end class dataexch }//end namespace system }//end namespace nana
29.578512
142
0.627969
Greentwip
8931bfc0d91a750dc6fcb607316655ab207cc0c3
4,497
cpp
C++
assignments/a6-transform/unique.cpp
dndinh7/animation-toolkit
906b003166f5ea588333e8681448afaf33cb30b3
[ "MIT" ]
null
null
null
assignments/a6-transform/unique.cpp
dndinh7/animation-toolkit
906b003166f5ea588333e8681448afaf33cb30b3
[ "MIT" ]
null
null
null
assignments/a6-transform/unique.cpp
dndinh7/animation-toolkit
906b003166f5ea588333e8681448afaf33cb30b3
[ "MIT" ]
null
null
null
#include "atkui/framework.h" #include "atk/toolkit.h" #include <deque> using namespace atk; using glm::vec3; class Steve : public atkui::Framework { public: Steve() : atkui::Framework(atkui::Perspective) { background(vec3(0)); cameraPos = vec3(-500, 500, -500); setCameraEnabled(false); } virtual ~Steve() {} virtual void setup() { lookAt(cameraPos, vec3(0)); Joint* root = new Joint("Hip"); root->setLocalTranslation(vec3(0, 170.0f, 0)); _steve.addJoint(root); Joint* neck = new Joint("Neck"); neck->setLocalTranslation(vec3(0, 120.0f, 0)); _steve.addJoint(neck, root); Joint* head = new Joint("Head"); head->setLocalTranslation(vec3(40.0f*cos(0), 30.0f, 40.0f * sin(0))); _steve.addJoint(head, neck); Joint* lLeg = new Joint("LeftLeg"); lLeg->setLocalTranslation(vec3(20.0f, -20.0f, 0)); _steve.addJoint(lLeg, root); Joint* rLeg = new Joint("RightLeg"); rLeg->setLocalTranslation(vec3(-20.0f, -20.0f, 0)); _steve.addJoint(rLeg, root); Joint* lFoot = new Joint("LeftFoot"); lFoot->setLocalTranslation(vec3(0, -140.0f, 0)); _steve.addJoint(lFoot, lLeg); Joint* rFoot = new Joint("RightFoot"); rFoot->setLocalTranslation(vec3(0, -140.0f, 0)); _steve.addJoint(rFoot, rLeg); Joint* lShoulder = new Joint("LeftShoulder"); lShoulder->setLocalTranslation(vec3(40.0f, 0, 0)); _steve.addJoint(lShoulder, neck); Joint* rShoulder = new Joint("RightShoulder"); rShoulder->setLocalTranslation(vec3(-40.0f, 0, 0)); _steve.addJoint(rShoulder, neck); Joint* lArm = new Joint("LeftArm"); lArm->setLocalTranslation(vec3(20.0f, -120.0f, 0)); _steve.addJoint(lArm, lShoulder); Joint* rArm = new Joint("RightArm"); rArm->setLocalTranslation(vec3(-20.0f, -120.0f, 0)); _steve.addJoint(rArm, rShoulder); _steve.fk(); } virtual void scene() { setColor(vec3(52.0f/255.0f, 140.0f/255.0f, 49.0f/255.0f)); drawCube(vec3(0), vec3(5000.0f, 0.1f, 5000.0f)); setColor(vec3(1, 215.0f/255.0f, 0)); drawCube(vec3(0), vec3(300.0f, 0.2f, 5000.0f)); setColor(vec3(1)); float theta = 0.45f * sin(3.0f*elapsedTime()); float theta2 = -0.45f * sin(3.0f*elapsedTime()); _steve.getByName("Hip")->setLocalTranslation(_steve.getByName("Hip")->getLocalTranslation() + vec3(0, 0, -25.0f * dt())); _steve.getByName("Hip")->setLocalRotation(glm::angleAxis(0.60f * sin(3.0f * elapsedTime()), vec3(1, 0, 0))); _steve.getByName("LeftLeg")->setLocalRotation(glm::angleAxis(0.60f * sin(3.0f * elapsedTime()), vec3(1, 0, 0))); _steve.getByName("RightLeg")->setLocalRotation(glm::angleAxis(theta2, vec3(1, 0, 0))); _steve.getByName("LeftShoulder")->setLocalRotation(glm::angleAxis(theta2, vec3(1, 0, 1))); _steve.getByName("RightShoulder")->setLocalRotation(glm::angleAxis(theta, vec3(1, 0, 1))); _steve.getByName("Head")->setLocalTranslation(vec3(40.0f * cos(5.0f*elapsedTime()), 30.0f, 40.0f * sin(5.0f*elapsedTime()))); _steve.fk(); for (int i = 0; i < _steve.getNumJoints(); i++) { Joint* cur_joint = _steve.getByID(i); if (cur_joint == _steve.getRoot()) { continue; } Joint* parent = cur_joint->getParent(); vec3 globalParentPos = parent->getGlobalTranslation(); vec3 globalPos = cur_joint->getGlobalTranslation(); setColor(vec3(0, 1, 1)); drawEllipsoid(globalParentPos, globalPos, 12.5f); } setColor(vec3(1, 1, 0)); drawSphere(_steve.getByName("Head")->getGlobalTranslation(), 50.0f); setColor(vec3(106.0f / 255.0f, 13.0f / 255.0f, 173.0f / 255.0f)); drawSphere(_steve.getByName("LeftArm")->getGlobalTranslation(), 25.0f); drawSphere(_steve.getByName("RightArm")->getGlobalTranslation(), 25.0f); drawSphere(_steve.getByName("LeftFoot")->getGlobalTranslation(), 25.0f); drawSphere(_steve.getByName("RightFoot")->getGlobalTranslation(), 25.0f); cameraPos += vec3(0, 0, -22.5f * dt()); lookAt(cameraPos, vec3(0)); } protected: Skeleton _steve; vec3 cameraPos; }; int main(int argc, char** argv) { Steve viewer; viewer.run(); }
34.068182
133
0.596842
dndinh7
89325d137a9c5992cf978546431202f269055988
9,354
cpp
C++
data/918.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/918.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/918.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
int PL ,du ,lUu , h2, KjY1 ,ez ,Ilu ,l ,uVy8 , YaZ ,/*Bv*/ UkM , wGDvh, ho ,XNDO ,gb9nx , HW, f ,H,KHvs85Q , qvf , Pu , Vf85E, T ,//H fjK, kIb/*kl0*/ , TEE,s2 ,// rqqN38 ,HiA2 , H4av , j, Qy , /*Q8*/ Tal,bYpV , mfW /*Dk*/;void f_f0 () { volatile int sS1s, //Z Ajs ,lC//fco1 //0iGM ,C9I, /*N1*/bTl9a ; mfW=bTl9a +sS1s +Ajs + lC +C9I; // {{{{ { {}} //YCvk }{ if ( true)for//V (int i=1; i< 1 ;++i/*jK*/){ }else return/*6*/ ; }}if (true ) { {if ( true) { }else if ( true ){ int wArx ;volatile int OLeWL ;wArx =/*GWg*/OLeWL ; }else{} } {{}}} else//b { int djP;volatile int XNtr ,w ; for (int i=1 ; i< 2;++i )/*l*/djP=w+XNtr ; } return ;for(int i=1 ;/*Q*/i< 3 ;++i ) for (int i=1 ;i< 4 ;++i ) { return ;{ {{ } for (int i=1 /*wYRi*/ ;i< 5 ;++i ) {} /*g*/} } } {{ if (true) { } else { }}; } }for (int i=1 ; i<6 ;++i ) {volatile int e, P, WNb2 ;PL = //qw WNb2 + e +P//i ;// {{ }{/*7*/{ { }} }} }{{//h ; for (int i=1 ; i< 7;++i) {/*c*//*J9Rk*/{ }if( true ){ volatile int E5P , zO9; du = zO9+E5P ;} else return ; } return ; { {} } { } } return ;}{ { return //R ;for (int i=1//wA ; i<8;++i) {{} for(int i=1 ; i<9 ;++i){ volatile int//PJCz eIl ;lUu = eIl ; } } ;{for(int i=1 ; i< 10;++i) return/*Y*//*p6Np*/ ;for (int i=1;/*0*/i< 11 ;++i ) {} }}for (int i=1; i< 12;++i)/*Z*/ for(int /*q*/ i=1 ;//F i<13 /*tbpn*/;++i ){; {}/*j5*/} { volatile int bQNiFw , //R zTc , Be7 ; h2 = /*eDM*/Be7 + bQNiFw+ zTc;if (true ) { }//w else for (int i=1;i< 14 ;++i ){ } for(int i=1 ; i<15 ;++i ) { } }{{volatile int PucE ; return ;KjY1 =PucE;} ; ;//uufc2 { if( true) { }else/*6C*/ {} } {if //Bl (true ) { {for (int i=1; i<16;++i){}}}else return//V ;}}} } { //OA { return ; { volatile int ist ,x; { {{ } } }if ( true)for(int i=1 ;i< 17 ;++i/*mu*/)ez= x+ist; else ; { } } {volatile int IkbrU , UXe, K7Sq ; { } {int yzl ;volatile int zFj,xdetZ;//kZ5 for(int i=1 ; i< 18 ;++i/*0*/) { {}}yzl = xdetZ +zFj ;} Ilu = K7Sq//D + IkbrU+ UXe ;}}for (int i=1 ; i< 19;++i ) /*ng*/if(true ){{ { /*dt*/{ } { } }{return ;} } { ;} {{ ; } if ( true)// { //h47 { /*Lr*/ }/*Z*/{if/*M*/ ( true ){ } else { }} } else{for (int i=1 ; i< 20 ;++i )if ( true )for (int /*HsWf*/i=1 ;i</*dxa0*/ 21 ;++i ) {}else{ }}/*he*///yD } }else { { ; } for (int i=1 /*gKd*/ ; i<22 ;++i ) if (true ){ return ;/*x16R*/}/*Cz*/else{ int/*8*/ NTyGL0 ; volatile int n9 ,lGmgo, ysA ; NTyGL0 = ysA+//cZW n9 + lGmgo ; ; }}return ;}; return ;return ;} void//Zu f_f1() { {//C3b for(int i=1;i< 23 ;++i){ { int ytA;volatile int ADo6GK, kT3D; ytA = kT3D+ ADo6GK ; if ( true){ {} }else ;} {int mQXIf; volatile int tl ,//kv T4D ;{ ; }if (true ) { int enN ; volatile int c /*xk*/ ; if (//bQA true )enN = c ; else{} return ; } else for(int i=1; i<24 ;++i)mQXIf //5xw //BN //W0 =T4D +tl;}}// {/*dN*/{ volatile int xRFg,Bn ;/*b*/for (int /*D*///sUB i=1 ; i< 25 ;++i )if( true ){volatile int/**/ FJ , sb //N ; l= sb+ FJ /*4*/;/*c*/return ;} /*u*/else ; if ( true)return ; else uVy8 = Bn+xRFg; /*TDP4*/}{ for (int i=1 ; i<26;++i ){return ;//h {}}}/*Qto*/ { volatile int A , vKEI , Hi, /*C*/hp4, QQ ;if( true ) {int tDRkG ;volatile int gZze ,HnH; //X9 if ( true ) {} else for (int i=1 ; i< 27;++i //C ) tDRkG = /*b*/ HnH//BQ +gZze; } else for(int i=1;i< 28;++i) return ; YaZ=QQ//omN + A + vKEI+ Hi +hp4;}} {int rd0Vi ; volatile int //e2M I,//DwC8M j29iq, lm4 , Jd ; for (int //a i=1 ; i< 29;++i){ { } }{ { } }rd0Vi /*t*/= Jd+I+ j29iq +lm4; { {{}} { ;} } } }{volatile int bjG ,Iw ,eG7 /*66K*/ , kR ,aqj , Gl, J, fCU5n , ATZ, BeUR;if/**/ (true) UkM= BeUR+ //16v bjG+Iw//ng + eG7 +kR; else{ int LB5 ; volatile int NF ,n4ej, Y2i , OEl,//07H F0 ;//L LB5= /*9*/F0 +NF +n4ej+ Y2i + OEl ;{ {} } return ; } if (true) { volatile int QjRc, BL ,IM ; wGDvh=/*6Z*/ IM + /*ri5*/QjRc+BL; { { return ;} } } else//n for(int i=1 //dY6 ; i< 30;++i)return/*Hjl*//*7*/ ; { volatile int oW5W ,e98 , V , kd; for(int i=1 ; i< 31 ;++i) {int qJV/*s*/ ; volatile int GdnW , NR ,o3 ;qJV//r = o3 +GdnW + NR; for(int i=1 ;i<32 ;++i ) {return ; { }{} }{ {} }if/*dJGg*/( true ){ {//Z }} else{ ;}} { volatile int Zfg ,r ;if( true //zM ) ho= r /*OBx*/+ Zfg; else {;}}//i {; { }} for(int i=1//B ; i< 33 //Dca ;++i ) XNDO =kd +oW5W/*sGIuV*/ + e98+V ;} return ;gb9nx= aqj+ Gl+ J+ fCU5n + ATZ;/*s8S*/ }//Wml ;; return //h //DHq ;} void f_f2(){;/*hYP*/for (int i=1 ; i< 34 ;++i) { {/*tuZ*/volatile int zclz , zjQ9 ,MTs;//MNN { for (int i=1; i< 35 ;++i) { } } /*tSM*/ { { {if (//fwW1 true ) {} else {} }}} HW = MTs +//OKD zclz+ zjQ9 ; } { volatile int YRkK74, Zv ,/*KOz*/Oa,vnax, og ,PJ8 , de, L2; for (int i=1//WwA ; i< 36/*P*/ ;++i )f= L2+YRkK74 + Zv +Oa// ;H = vnax + og + PJ8 +de ;} //dOb { for(int i=1;i<37 ;++i)for (int i=1;i< 38 ;++i) ;return ; }{ for(int i=1 ; i< 39 ;++i ) { int GulC ;//3J volatile int gCh, A5; GulC = A5+ gCh ; for (int i=1 ; i< 40 ;++i ) {/*ava*/{ //OpG } { } }//F { return ; {}{ } } }; { if( true) ; else{ int PxN3O; volatile int k , Z6w ;{{} { }}PxN3O=Z6w + k; for (int i=1; i< 41 ;++i){ } } //t {{ } for (int i=1 ; i<42 ;++i ) {} } }} } {;//2jJ { volatile int Q,//mt6 Q5wxb,WR;KHvs85Q = WR +Q +Q5wxb ;{{{}}{ return ; } }return ;} ; } { volatile int U //3m , r6 , Gm ,y ,bcml ,ABY/*LH*/ ;{ /*b*/return ;{{/*WO*/}/*o*/}for(int i=1//Bnz ; i</*4*/ 43;++i ){volatile int ed , lrf ,CD4YO//WwC ;{ } if ( true )qvf = CD4YO+ ed +lrf /*yp*/ ; else return ;}} { ; { { { { for (int i=1;i</*F*/44;++i ) for (int i=1 ;i< 45 //Z ;++i ) if ( true){ } else {/*DJ9*/} for(int i=1 ;i<46;++i ) return ;} } }//4s4 }}{//V return ; for(int i=1 ; i< 47 ;++i) {for (int i=1 ;i< 48 //h ;++i) { ;}return ; } } if (true ) { return ; {{ /**/{ {{ } } } } return ; {{} } if( /**/true )if( true ){//d if (true) return ; else { } return ;} else{ } //Cd else //1g { /*Dd*/} } } else Pu = ABY + /*xK*//*BXx*/ U+r6 +Gm + y + bcml ; }{int g3q5W ; volatile int UE , wDMR, //aXA Hq4ho , Dj7Ll ,mXX,cG, z , sh ,s3MLht, /*jLag*/CFe,ROe , moUE;{ volatile int czs0 //Qw ,//gXc TS, iY1 ,I0e6; /*6*/ {return ;{//PK } /*Z1*/{{ ; } return ; }}{ volatile int X2,UO ,//qIKQ TBH, O/*CRE5J*/; Vf85E = /*x*/O+ X2 +UO +TBH // ; } /*b6*/{int gH ;/**/ volatile int VUcX , Wr4BB ; {//R for(int /*y*/i=1 ;i<49;++i ) return ;} { /**/int B ;volatile int FaoFI , YT ;if ( true) for(int i=1;i< 50;++i ) B = YT + FaoFI ;else {{ }} }if(true) gH = Wr4BB + VUcX;/*vnE*/ else for(int /*i3*/ i=1;i< 51/*s*/ ;++i) ; } /*U3*/T//b1 = I0e6+czs0 + TS +// // iY1/*P*/; } for(int i=1 ; i< 52;++i) if( true)return ; else return ;if( true) {{ ; return ;} {//Hg { }}} else{{{//xowR return ; }} if(true ) ; else{{ volatile int xH3 ,wFC; fjK = wFC+ xH3 ;;} {volatile int //p Kk, MP; for(int i=1 ; i<53;++i )for(int i=1; i< 54;++i ) kIb //9x = MP+ Kk ;} { }} return ; { {}} }if (true) TEE= moUE + UE//y + wDMR +Hq4ho /*qBv*/+ Dj7Ll+ mXX+cG/*qF9*/; //Ar else g3q5W= z + sh + s3MLht + CFe+ROe//nf ; } return ;}int main(){int JxhC ;//V7 volatile int In1Dv , Y546 , ZVW , g3uH /*oy8*/, Cr ,lj //q ; return 662632231;if( true) JxhC = lj +In1Dv + Y546 + ZVW+g3uH+Cr ; else{ int nb/*mUOBV*/;volatile int Hpk,/**/ mzIn, Glx ,/*S*/dftb,GYn ,Or, dGv, Pqr2l //x , fW, yYv,vK8I;/**/nb= vK8I + Hpk+ mzIn + Glx//eeA + dftb;{ int MzB;volatile int nYtEF ,Aa8,DSHq, O4fu;// MzB= //cE O4fu + nYtEF+Aa8+ DSHq ;{; { }}{ {} return/*2G*/ 1323723358 ; //8dMq } } s2 =GYn+ Or+dGv+Pqr2l +/*JlU*/ fW + yYv;}{ return 2146463394; {if( true ) ; else ;{return 266339152 ; } ;{ { volatile int CZ ; {}rqqN38/*WvZ*/= /*2Ao91*/CZ ; { } }} } if ( true ) for(int i=1//S ; i< 55;++i ) { int jYrv ;volatile int TJ ,CcS , CN;jYrv=CN + TJ +CcS//wE ;{ ; }/*4x*/ } else{volatile int BH,//E YLqFrR//0 ,S ,qD5, Ovl; ;HiA2= Ovl +BH+ YLqFrR+ S+ qD5 ; return/**/ 1448105849; } {{ {} return 192569863; } return 2145998470 //5QI ; }} return 167674675 ; { {{ return 491830048; { }} { return 990171621;for (int i=1 ;i< 56;++i ){ {volatile int qjTl ; H4av = qjTl;} }} { for(int i=1 ;i< 57 ;++i) ; } {volatile int J2ji ,eRyE;j = eRyE+ //oO J2ji;{} }}if ( true ){ {for(int i=1 ; i< 58;++i ) ; { //vw } } { int xd ; volatile int z477,u/*vgb*/,// rW ;xd =rW + z477 + u; }//3o if( true) ; //g else return 699246214 ; }else{ {int Tef ; volatile int/**/ C,LZ , lwec ; for(int i=1 ; i<59 ;++i) Tef = lwec + C+ LZ;}//5dr { return 2142480702;} }{volatile int C1,m8kp ,L8//K ,R ; { volatile int NeNjA, G ,DKfQY , dYtQ; // for(int i=1 ; i< 60;++i ) {volatile int VbZ; Qy /**/=VbZ;}Tal //ER = dYtQ + NeNjA + G +DKfQY;}bYpV = /*0*/ R//GCD +C1+ m8kp +L8; { {{{ }{} }} }{ int Pv;volatile int //l D6 , CsZ , ko7 ;for (int i=1 ; /*V5*/ i<61 /*r*/;++i) {}{ {{ { }} { }}{ /*o*/} }Pv=ko7+D6+ CsZ;} // } } //BS9 }
10.222951
65
0.455634
TianyiChen
89330ec7af9f1a8ee0171f1058a3c7aa4bb9bbc8
6,949
cpp
C++
src/lib/rtm/LocalServiceAdmin.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
15
2019-01-08T15:34:04.000Z
2022-03-01T08:36:17.000Z
src/lib/rtm/LocalServiceAdmin.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
448
2018-12-27T03:13:56.000Z
2022-03-24T09:57:03.000Z
src/lib/rtm/LocalServiceAdmin.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
31
2018-12-26T04:34:22.000Z
2021-11-25T04:39:51.000Z
// -*- C++ -*- /*! * @file LocalServiceAdmin.cpp * @brief SDO service administration class * @date $Date$ * @author Noriaki Ando <n-ando@aist.go.jp> * * Copyright (C) 2011 * Noriaki Ando * Intelligent Systems Research Institute, * National Institute of * Advanced Industrial Science and Technology (AIST), Japan * All rights reserved. * * $Id: SdoConfiguration.cpp 1971 2010-06-03 08:46:40Z n-ando $ * */ #include <coil/UUID.h> #include <mutex> #include <coil/stringutil.h> #include <rtm/RTObject.h> #include <rtm/CORBA_SeqUtil.h> #include <rtm/LocalServiceAdmin.h> #include <rtm/LocalServiceBase.h> #include <cstring> #include <algorithm> #include <memory> #include <vector> namespace RTM { /*! * @if jp * @brief コンストラクタ * @else * @brief Constructor * @endif */ LocalServiceAdmin::LocalServiceAdmin() : rtclog("LocalServiceAdmin") { RTC_TRACE(("LocalServiceAdmin::LocalServiceAdmin()")); } /*! * @if jp * @brief 仮想デストラクタ * @else * @brief Virtual destractor * @endif */ LocalServiceAdmin::~LocalServiceAdmin() { finalize(); } /*! * @if jp * @brief "all" 文字列探索Functor * @else * @brief A functor to search "all" * @endif */ struct find_all { bool operator()(const std::string& str) { return coil::normalize(str) == "all"; } }; /*! * @if jp * * @brief LocaServiceAdminの初期化 * @else * @brief Initialization of LocalServiceAdmin * @endif */ void LocalServiceAdmin::init(coil::Properties& props) { RTC_TRACE(("LocalServiceAdmin::init():")); RTC_DEBUG_STR((props)); coil::vstring svcs(coil::split(props["enabled_services"], ",")); bool all_enable(false); if (std::find_if(svcs.begin(), svcs.end(), find_all()) != svcs.end()) { RTC_INFO(("All the local services are enabled.")); all_enable = true; } RTM::LocalServiceFactory& factory(RTM::LocalServiceFactory::instance()); coil::vstring ids = factory.getIdentifiers(); RTC_DEBUG(("Available services: %s", coil::flatten(ids).c_str())); for (auto & id : ids) { if (all_enable || isEnabled(id, svcs)) { if (notExisting(id)) { LocalServiceBase* service(factory.createObject(id)); RTC_DEBUG(("Service created: %s", id.c_str())); coil::Properties& prop(props.getNode(id)); service->init(prop); addLocalService(service); } } } } /*! * @if jp * @brief LocalserviceAdmin の終了処理 * @else * @brief Finalization ofLocalServiceAdmin * @endif */ void LocalServiceAdmin::finalize() { RTM::LocalServiceFactory& factory(RTM::LocalServiceFactory::instance()); for (auto & service : m_services) { service->finalize(); factory.deleteObject(service); } m_services.clear(); } /*! * @if jp * @brief LocalServiceProfileListの取得 * @else * @brief Getting LocalServiceProfileList * @endif */ RTM::LocalServiceProfileList LocalServiceAdmin::getServiceProfiles() { RTM::LocalServiceProfileList profs(0); for (auto & service : m_services) { profs.emplace_back(service->getProfile()); } return profs; } /*! * @if jp * @brief LocalServiceProfile を取得する * @else * @brief Get LocalServiceProfile of an LocalService * @endif */ bool LocalServiceAdmin::getServiceProfile(const std::string& name, ::RTM::LocalServiceProfile& prof) { std::lock_guard<std::mutex> guard(m_services_mutex); for (auto & service : m_services) { if (name == service->getProfile().name) { prof = service->getProfile(); return true; } } return false; } /*! * @if jp * @brief LocalService の Service を取得する * @else * @brief Get a pointer of a LocalService * @endif */ RTM::LocalServiceBase* LocalServiceAdmin::getService(const char* id) { for (auto & service : m_services) { if (service->getProfile().name == id) { return service; } } return nullptr; } /*! * @if jp * @brief SDO service provider をセットする * @else * @brief Set a SDO service provider * @endif */ bool LocalServiceAdmin::addLocalService(::RTM::LocalServiceBase* service) { if (service == nullptr) { RTC_ERROR(("Invalid argument: addLocalService(service == NULL)")); return false; } RTC_TRACE(("LocalServiceAdmin::addLocalService(%s)", service->getProfile().name.c_str())); std::lock_guard<std::mutex> guard(m_services_mutex); m_services.emplace_back(service); return true; } /*! * @if jp * @brief LocalService を削除する * @else * @brief Remove a LocalService * @endif */ bool LocalServiceAdmin::removeLocalService(const std::string& name) { RTC_TRACE(("removeLocalService(%s)", name.c_str())); std::lock_guard<std::mutex> guard(m_services_mutex); std::vector<LocalServiceBase*>::iterator it = m_services.begin(); std::vector<LocalServiceBase*>::iterator it_end = m_services.end(); while (it != it_end) { if (name == (*it)->getProfile().name) { (*it)->finalize(); LocalServiceFactory& factory(LocalServiceFactory::instance()); factory.deleteObject(*it); m_services.erase(it); RTC_INFO(("SDO service has been deleted: %s", name.c_str())); return true; } ++it; } RTC_WARN(("Specified SDO service not found: %s", name.c_str())); return false; } //============================================================ // private functions /*! * @if jp * @brief 指定されたIDが有効かどうかチェックする * @else * @brief Check if specified ID is enabled * @endif */ bool LocalServiceAdmin::isEnabled(const std::string& id, const coil::vstring& enabled) { bool ret = std::find(enabled.begin(), enabled.end(), id) != enabled.end(); RTC_DEBUG(("Local service %s %s enabled.", id.c_str(), ret ? "is" : "is not")); return ret; } /*! * @if jp * @brief 指定されたIDがすでに存在するかどうかチェックする * @else * @brief Check if specified ID is existing * @endif */ bool LocalServiceAdmin::notExisting(const std::string& id) { std::lock_guard<std::mutex> guard(m_services_mutex); for (auto & service : m_services) { if (service->getProfile().name == id) { RTC_WARN(("Local service %s already exists.", id.c_str())); return false; } } RTC_DEBUG(("Local service %s does not exist.", id.c_str())); return true; } } // namespace RTM
24.044983
78
0.576054
r-kurose
89348a32df641913c4702660dc8ea99fc8e741b1
3,658
cpp
C++
src/UtilsString.cpp
georgedeath/TAsK
14c4abb3b3f9918accd59e9987e9403bd8a0470c
[ "MIT" ]
28
2015-03-05T04:12:58.000Z
2021-12-16T22:24:41.000Z
src/UtilsString.cpp
joshchea/TAsK
d66d0c7561e30b45308aabcf08f584326779f4ae
[ "MIT" ]
2
2017-02-07T15:37:37.000Z
2020-06-26T14:06:00.000Z
src/UtilsString.cpp
joshchea/TAsK
d66d0c7561e30b45308aabcf08f584326779f4ae
[ "MIT" ]
15
2015-07-09T11:53:16.000Z
2022-02-22T04:01:19.000Z
#include "UtilsString.h" #include "Error.h" #include <cstring> #include <algorithm> #include <stdlib.h> void Utils::checkEmptyValue(int value){ if (value == 0) { std::string message = "Some values of attributes are missing"; Error er(message); throw er; } }; FPType Utils::extractNumber(const std::string& line, size_t pos, size_t &nextPos){ int len = line.length(); int i = pos; char ch; bool dotAdded = false; for (; i < len; ++i) { ch = line.at(i); if (isdigit(ch) || (ch == '.')) { if (ch == '.') dotAdded = true; break; } } if (i == len) throw Error("Current line does not contain number."); std::string num(1, line.at(i)); int j = i + 1; for (; j < len; ++j) { ch = line.at(j); if (ch == '.') { if (dotAdded) { break; } else { dotAdded = true; } } else if (!isdigit(ch)) { break; } num.push_back(ch); } nextPos = j; return atof(num.c_str()); }; int Utils::extractInt(const std::string& line, size_t pos){ int len = line.length(); int i = pos; for (; i < len; ++i) { if (isdigit(line.at(i))) break; } if (i == len) throw Error("Current line does not contain integers."); std::string num(1, line.at(i)); char ch; for (int j = i + 1; j < len; ++j) { ch = line.at(j); if (!isdigit(ch)) break; num.push_back(ch); } return atoi(num.c_str()); }; std::string Utils::deleteWhiteSpaces(const std::string &line){ std::string lineWithoutSpaces(line); lineWithoutSpaces.erase(std::remove_if(lineWithoutSpaces.begin(), lineWithoutSpaces.end(), isspace), lineWithoutSpaces.end()); return lineWithoutSpaces; } std::string Utils::getSubString(const std::string& first, const std::string& last, const std::string& line){ size_t found = line.find(first); if (found == std::string::npos) { std::string message = first; message.append(" is missing in line: "); message.append(line); Error er(message); throw er; } size_t foundEnd = line.find(last); if (foundEnd == std::string::npos) { std::string message = last; ; message.append(" is missing in line: "); message.append(line); Error er(message); throw er; } if (found > foundEnd) { std::string message = "Field name or value is missing in line: "; message.append(line); Error er(message); throw er; } if (foundEnd - found <= 1) return ""; return line.substr(found + 1, foundEnd - found - 1); }; std::string Utils::skipOneLineComment(const std::string& comment, const std::string& line){ size_t found = line.find(comment); if (found != std::string::npos) { if (found == 0) { return ""; } else { return line.substr(0, found - 1); } } return line; }; void Utils::extractName(const char* filepath, std::string& name){ // Format of file path: "/bla/bla/bla/problemName.someextension" // We try to find the interval [begin; end) which contains "problemName" const char* end = filepath + strlen(filepath); // We rewind "end" // Find the position of the last point (filepath if there is no such point) while(end > filepath) { if(*(end-1) == '.'){ --end; break; } --end; } const char* begin = end; while( begin > filepath && *(begin-1) != '/' && *(begin-1) != '\\'){ --begin; } name.assign(begin, end); }; bool Utils::isDigits(const std::string &str){ bool hasPoint = false; int length = str.length(); for (int i = 0; i < length; ++i) { if (!isdigit(str.at(i))) { if (str.at(i) == '.' && !hasPoint && i != length-1) { hasPoint = true; } else { return false; } } } return true; }; bool Utils::isInt(const std::string &str){ return str.find_first_not_of("0123456789") == std::string::npos; };
22.8625
108
0.615364
georgedeath
8934bc258baa69177a04743b44509d032f0d45cc
4,992
cpp
C++
benchmark/runtime/integer/single.cpp
danra/scnlib
815782badc1b548c21bb151372497e1516bee806
[ "Apache-2.0" ]
556
2018-11-17T01:49:32.000Z
2022-03-25T09:35:10.000Z
benchmark/runtime/integer/single.cpp
danra/scnlib
815782badc1b548c21bb151372497e1516bee806
[ "Apache-2.0" ]
51
2019-05-09T14:36:53.000Z
2022-03-19T12:47:12.000Z
benchmark/runtime/integer/single.cpp
danra/scnlib
815782badc1b548c21bb151372497e1516bee806
[ "Apache-2.0" ]
21
2019-02-11T19:56:30.000Z
2022-03-28T02:52:27.000Z
// Copyright 2017 Elias Kosunen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This file is a part of scnlib: // https://github.com/eliaskosunen/scnlib #include "bench_int.h" template <typename Int> static void scan_int_single_scn(benchmark::State& state) { auto source = stringified_integers_list<Int>(); auto it = source.begin(); Int i; for (auto _ : state) { if (it == source.end()) { it = source.begin(); } auto result = scn::scan(*it, "{}", i); if (!result) { state.SkipWithError("Benchmark errored"); break; } } state.SetBytesProcessed( static_cast<int64_t>(state.iterations() * sizeof(Int))); } BENCHMARK_TEMPLATE(scan_int_single_scn, int); BENCHMARK_TEMPLATE(scan_int_single_scn, long long); BENCHMARK_TEMPLATE(scan_int_single_scn, unsigned); template <typename Int> static void scan_int_single_scn_default(benchmark::State& state) { auto source = stringified_integers_list<Int>(); auto it = source.begin(); Int i; for (auto _ : state) { if (it == source.end()) { it = source.begin(); } auto result = scn::scan_default(*it, i); if (!result) { state.SkipWithError("Benchmark errored"); break; } } state.SetBytesProcessed( static_cast<int64_t>(state.iterations() * sizeof(Int))); } BENCHMARK_TEMPLATE(scan_int_single_scn_default, int); BENCHMARK_TEMPLATE(scan_int_single_scn_default, long long); BENCHMARK_TEMPLATE(scan_int_single_scn_default, unsigned); template <typename Int> static void scan_int_single_scn_value(benchmark::State& state) { auto source = stringified_integers_list<Int>(); auto it = source.begin(); for (auto _ : state) { if (it == source.end()) { it = source.begin(); } auto result = scn::scan_value<Int>(*it); if (!result) { state.SkipWithError("Benchmark errored"); break; } } state.SetBytesProcessed( static_cast<int64_t>(state.iterations() * sizeof(Int))); } BENCHMARK_TEMPLATE(scan_int_single_scn_value, int); BENCHMARK_TEMPLATE(scan_int_single_scn_value, long long); BENCHMARK_TEMPLATE(scan_int_single_scn_value, unsigned); template <typename Int> static void scan_int_single_scn_parse(benchmark::State& state) { auto source = stringified_integers_list<Int>(); auto it = source.begin(); Int i{}; for (auto _ : state) { if (it == source.end()) { it = source.begin(); } auto result = scn::parse_integer<Int>( scn::string_view{it->data(), it->size()}, i); if (!result) { state.SkipWithError("Benchmark errored"); break; } } state.SetBytesProcessed( static_cast<int64_t>(state.iterations() * sizeof(Int))); } BENCHMARK_TEMPLATE(scan_int_single_scn_parse, int); BENCHMARK_TEMPLATE(scan_int_single_scn_parse, long long); BENCHMARK_TEMPLATE(scan_int_single_scn_parse, unsigned); template <typename Int> static void scan_int_single_sstream(benchmark::State& state) { auto source = stringified_integers_list<Int>(); auto it = source.begin(); Int i; for (auto _ : state) { if (it == source.end()) { it = source.begin(); } std::istringstream iss{*it}; iss >> i; if (iss.fail()) { state.SkipWithError("Benchmark errored"); break; } } state.SetBytesProcessed( static_cast<int64_t>(state.iterations() * sizeof(Int))); } BENCHMARK_TEMPLATE(scan_int_single_sstream, int); BENCHMARK_TEMPLATE(scan_int_single_sstream, long long); BENCHMARK_TEMPLATE(scan_int_single_sstream, unsigned); template <typename Int> static void scan_int_single_scanf(benchmark::State& state) { auto source = stringified_integers_list<Int>(); auto it = source.begin(); Int i; for (auto _ : state) { if (it == source.end()) { it = source.begin(); } auto ret = scanf_integral(it->c_str(), i); if (ret != 1) { state.SkipWithError("Benchmark errored"); break; } } state.SetBytesProcessed( static_cast<int64_t>(state.iterations() * sizeof(Int))); } BENCHMARK_TEMPLATE(scan_int_single_scanf, int); BENCHMARK_TEMPLATE(scan_int_single_scanf, long long); BENCHMARK_TEMPLATE(scan_int_single_scanf, unsigned);
29.538462
75
0.648037
danra
8938915a32c234de257ac62cb73ae6bdf20cf121
6,216
cc
C++
plugins/taglib/TagParser.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
75
2015-04-26T11:22:07.000Z
2022-02-12T17:18:37.000Z
plugins/taglib/TagParser.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
7
2016-05-31T21:56:01.000Z
2019-09-15T06:25:28.000Z
plugins/taglib/TagParser.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
19
2015-09-23T01:50:15.000Z
2022-02-12T17:18:41.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <vector> #include <map> #include <taglib/mpegfile.h> #include <taglib/fileref.h> #include <taglib/tag.h> #include <taglib/audioproperties.h> using namespace TagLib; #include <scx/Conv.h> #include <scx/FileHelper.h> #include <scx/IconvHelper.h> using namespace scx; #include <plugin/TagParserProto.h> using namespace mous; #include "CoverArt.h" namespace TagLib { namespace ID3v2{ class Tag; } } namespace { struct Self { std::string file_name; FileRef* file_ref = nullptr; Tag* tag = nullptr; AudioProperties* props = nullptr; std::map<std::string, CoverFormat(*)(const string&, char**, uint32_t*)> dump_funcs; std::map<std::string, bool(*)(const string&, CoverFormat, const char*, size_t)> store_funcs; std::string title; std::string artist; std::string album; std::string comment; std::string genre; }; } static string StringTostd_string(const String& str) { if (str.isLatin1()) { return str.to8Bit(); } string std_str; const ByteVector& v = str.data(String::UTF16BE); if (IconvHelper::ConvFromTo("UTF-16BE", "UTF-8", v.data(), v.size(), std_str)) { return std_str; } else { return str.to8Bit(); } } static void* Create() { auto self = new Self(); self->dump_funcs = { { "mp3", DumpMp3Cover }, { "m4a", DumpMp4Cover} }; self->store_funcs = { { "mp3", StoreMp3Cover }, { "m4a", StoreMp4Cover } }; return self; } static void Destroy(void* ptr) { Close(ptr); delete SELF; } static ErrorCode Open(void* ptr, const char* path) { SELF->file_name = path; SELF->file_ref = new FileRef(path, true);//AudioProperties::); if (!SELF->file_ref->isNull() && SELF->file_ref->tag()) { SELF->tag = SELF->file_ref->tag(); SELF->props = SELF->file_ref->audioProperties(); } return ErrorCode::Ok; } static void Close(void* ptr) { if (SELF->file_ref) { delete SELF->file_ref; SELF->file_ref = nullptr; SELF->tag = nullptr; SELF->props = nullptr; } SELF->file_name.clear(); } static bool HasTag(void* ptr) { return SELF->tag; } static const char* GetTitle(void* ptr) { if (!SELF->tag) { return nullptr; } SELF->title = StringTostd_string(SELF->tag->title()); return SELF->title.c_str(); } static const char* GetArtist(void* ptr) { if (!SELF->tag) { return nullptr; } SELF->artist = StringTostd_string(SELF->tag->artist()); return SELF->artist.c_str(); } static const char* GetAlbum(void* ptr) { if (!SELF->tag) { return nullptr; } SELF->album = StringTostd_string(SELF->tag->album()); return SELF->album.c_str(); } static const char* GetComment(void* ptr) { if (!SELF->tag) { return nullptr; } SELF->comment = StringTostd_string(SELF->tag->comment()); return SELF->comment.c_str(); } static const char* GetGenre(void* ptr) { if (!SELF->tag) { return nullptr; } SELF->genre = StringTostd_string(SELF->tag->genre()); return SELF->genre.c_str(); } static int32_t GetYear(void* ptr) { if (!SELF->tag) { return -1; } return SELF->tag->year(); } static int32_t GetTrack(void* ptr) { if (!SELF->tag) { return -1; } return SELF->tag->track(); } static bool HasAudioProperties(void* ptr) { return SELF->props; } static int32_t GetDuration(void* ptr) { if (!SELF->props) { return 0; } return SELF->props->length()*1000; } static int32_t GetBitRate(void* ptr) { if (!SELF->props) { return 0; } return SELF->props->bitrate(); } static bool CanEdit(void* ptr) { return true; } static bool Save(void* ptr) { const string& ext = ToLower(FileHelper::FileSuffix(SELF->file_name)); if (ext == "mp3") { auto ref = dynamic_cast<TagLib::MPEG::File*>(SELF->file_ref->file()); if (!ref) { printf("[taglib] bad type\n"); return false; } return ref->save(TagLib::MPEG::File::TagTypes::ID3v2, true, 3, true); } else { return SELF->file_ref ? SELF->file_ref->save() : false; } } static void SetTitle(void* ptr, const char* title) { if (SELF->tag) { SELF->tag->setTitle(title); } } static void SetArtist(void* ptr, const char* artist) { if (SELF->tag) { SELF->tag->setArtist(artist); } } static void SetAlbum(void* ptr, const char* album) { if (SELF->tag) { SELF->tag->setAlbum(album); } } static void SetComment(void* ptr, const char* comment) { if (SELF->tag) { SELF->tag->setComment(comment); } } static void SetGenre(void* ptr, const char* genre) { if (SELF->tag) { SELF->tag->setGenre(genre); } } static void SetYear(void* ptr, int32_t year) { if (SELF->tag) { SELF->tag->setYear(year); } } static void SetTrack(void* ptr, int32_t track) { if (SELF->tag) { SELF->tag->setTrack(track); } } static CoverFormat DumpCoverArt(void* ptr, char** out, uint32_t* length) { if (SELF->file_name.empty()) { return CoverFormat::None; } const string& ext = ToLower(FileHelper::FileSuffix(SELF->file_name)); if (SELF->dump_funcs.find(ext) != SELF->dump_funcs.end()) { return SELF->dump_funcs[ext](SELF->file_name, out, length); } else { return CoverFormat::None; } } static bool StoreCoverArt(void* ptr, CoverFormat fmt, const char* data, size_t length) { if (SELF->file_name.empty()) { return false; } const string& ext = ToLower(FileHelper::FileSuffix(SELF->file_name)); if (SELF->store_funcs.find(ext) != SELF->store_funcs.end()) { return SELF->store_funcs[ext](SELF->file_name, fmt, data, length); } else { return false; } } static const BaseOption** GetOptions(void* ptr) { (void) ptr; return nullptr; } static const char** GetSuffixes(void* ptr) { static const char* suffixes[] { "*", nullptr }; return suffixes; }
21.583333
100
0.598456
bsdelf
89395fc1e297359f3d2e6ca94098c6a453418625
932
cxx
C++
state/sw.cxx
kydos/dilib-demo
de5ded471adb7075d04450371d2e3a88bd57d5c7
[ "Apache-2.0" ]
null
null
null
state/sw.cxx
kydos/dilib-demo
de5ded471adb7075d04450371d2e3a88bd57d5c7
[ "Apache-2.0" ]
null
null
null
state/sw.cxx
kydos/dilib-demo
de5ded471adb7075d04450371d2e3a88bd57d5c7
[ "Apache-2.0" ]
null
null
null
#include "util.hxx" #include <dilib/state.hxx> #include <random> #include <chrono> #include <thread> int main(int argc, char *argv[]) { if (argc > 2) { std::string name = argv[1]; std::string did = argv[2]; std::cout << "StateWriter(" << name << ")" << std::endl; dilib::StateWriter<dilib::demo::DevicePosition> sw(name); std::default_random_engine generator; std::uniform_int_distribution<float> distribution(0,100); while (true) { float lon = distribution(generator); float lat = distribution(generator); float lev = distribution(generator); dilib::demo::DevicePosition sample(did, lon ,lat, lev); sw.write(sample); std::cout << "(" << did << ", " << lon << ", " << lat << ", " << lev << ")" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } else { std::cout << "USAGE:\n\tsw <name> <did>" << std::endl; } }
26.628571
95
0.590129
kydos
893b011b4350afabdf5f407733a8efb9e42337a7
4,191
cpp
C++
C++/Semester_2/class_4.cpp
Trilonka/MireaAl
2d68b6facbeb99cc4040ea206c64e95ea3c1bc92
[ "BSD-2-Clause" ]
null
null
null
C++/Semester_2/class_4.cpp
Trilonka/MireaAl
2d68b6facbeb99cc4040ea206c64e95ea3c1bc92
[ "BSD-2-Clause" ]
null
null
null
C++/Semester_2/class_4.cpp
Trilonka/MireaAl
2d68b6facbeb99cc4040ea206c64e95ea3c1bc92
[ "BSD-2-Clause" ]
1
2021-12-14T09:35:43.000Z
2021-12-14T09:35:43.000Z
#include <iostream> using namespace std; class BaseString { protected: char *p; int len; int capacity; public: BaseString(char *ptr) { //cout<<"\nBase Constructor 1\n"; len = 0; for (int i = 0; ptr[i] != '\0'; i++) { len++; } capacity = (len >= 256) ? len << 1 : 256; p = new char[capacity]; for (int i = 0; i < len; i++) { p[i] = ptr[i]; } p[len] = '\0'; } BaseString(const char *ptr) { //cout<<"\nBase Constructor 1\n"; len = 0; for (int i = 0; ptr[i] != '\0'; i++) { len++; } capacity = (len >= 256) ? len << 1 : 256; p = new char[capacity]; for (int i = 0; i < len; i++) { p[i] = ptr[i]; } p[len] = '\0'; } BaseString(int Capacity = 256) { //cout<<"\nBase Constructor 0\n"; capacity = Capacity; p = new char[capacity]; len = 0; } BaseString(const BaseString &s) { //cout<<"\nBase Copy Constructor\n"; len = s.len; capacity = s.capacity; p = new char[capacity]; for(int i=0; i<len;i++) { p[i] = s.p[i]; } p[len] = '\0'; } ~BaseString() { //cout<<"\nBase Destructor\n"; if (p != NULL) delete[] p; len = 0; } int Length() { return len; } int Capacity() { return capacity; } char *get() { return p; } char &operator[](int i) { return p[i]; } BaseString &operator=(const BaseString &s) { //cout<<"\nBase Operator = \n"; delete[] p; len = s.len; capacity = s.capacity; p = new char[capacity]; for (int i = 0; i < len; i++) { p[i] = s.p[i]; } p[len] = '\0'; return *this; } BaseString operator+(const BaseString &s) { BaseString res; res.len = len + s.len; res.capacity = (res.len >= 256) ? res.len << 1 : 256; for (int i = 0; i < len; i++) { res.p[i] = p[i]; } for (int i = len; i < res.len; i++) { res.p[i] = s.p[i - len]; } return res; } virtual void print() { int i = 0; while (p[i] != '\0') { cout << p[i++]; } } }; class String : public BaseString { public: String(char *ptr) : BaseString(ptr) {} String(const char *s) : BaseString(s) {} String(int Capacity = 256) : BaseString(Capacity) {} String(const String &s) { delete[] p; capacity = s.capacity; p = new char[capacity]; len = s.len; for (int i = 0; i < len; i++) { p[i] = s.p[i]; } p[len] = '\0'; } ~String() {} int IndexOf(char c) { for (int i = 0; i < len; i++) { if (p[i] == c) { return i; } } return -1; } int string_to_number() { int ans = 0; char k = 1; bool isNum = true; for (int i = len-1; i>=0; i--) { if(i==0 && p[i]=='-' && isNum) { return ans *= -1; } if (p[i]>='0' && p[i]<='9') { ans += k*p[i]; k *= 10; } else { isNum = false; break; } } if (!isNum) cout << "It isn't a number, returned 0" << endl; return isNum ? ans : 0; } }; int main() { BaseString str1("hi teacher, have you a good day!"); str1.print(); cout << endl; BaseString str2(" you are the best"); BaseString str3; str3 = str1 + str2; str3.print(); cout << endl; String s1("wow"); String s2(str3.get()); s2.print(); cout << endl; s1 = s2; cout << s1.IndexOf('o') << endl; String num1("4213"); num1.print(); String num2("-3213"); cout << num1.string_to_number() << endl; cout << num2.string_to_number() << endl; cout << s1.string_to_number() << endl; }
22.532258
68
0.409926
Trilonka
9f1c8ff208d697fa8730f4e81fb0f6340056fcce
1,643
cc
C++
squim/image/multi_frame_writer.cc
baranov1ch/squim
5bde052735e0dac7c87e8f7939d0168e6ee05857
[ "Apache-2.0" ]
2
2016-05-06T01:15:49.000Z
2016-05-06T01:29:00.000Z
squim/image/multi_frame_writer.cc
baranov1ch/squim
5bde052735e0dac7c87e8f7939d0168e6ee05857
[ "Apache-2.0" ]
null
null
null
squim/image/multi_frame_writer.cc
baranov1ch/squim
5bde052735e0dac7c87e8f7939d0168e6ee05857
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015 Alexey Baranov <me@kotiki.cc>. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "squim/image/multi_frame_writer.h" #include "squim/image/image_encoder.h" namespace image { MultiFrameWriter::MultiFrameWriter(std::unique_ptr<ImageEncoder> encoder) : encoder_(std::move(encoder)) {} MultiFrameWriter::~MultiFrameWriter() {} Result MultiFrameWriter::Initialize(const ImageInfo* image_info) { return encoder_->Initialize(image_info); } void MultiFrameWriter::SetMetadata(const ImageMetadata* metadata) { encoder_->SetMetadata(metadata); } Result MultiFrameWriter::WriteFrame(ImageFrame* frame) { return encoder_->EncodeFrame(frame, false); } Result MultiFrameWriter::FinishWrite(ImageOptimizationStats* stats) { auto result = encoder_->EncodeFrame(nullptr, true); // Normally pending should result in another call to this function but who // cares, finish writes up-to date does nothing which may suspend IO. If that // ever happens, add another step. if (result.error()) return result; return encoder_->FinishWrite(stats); } } // namespace image
31
79
0.752891
baranov1ch
9f1cf689e23f70318bd72ccc884671d7e91fc583
260
hpp
C++
src/algorithms/next_pos_chars.hpp
ruolin/vg
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
[ "MIT" ]
740
2016-02-23T02:31:10.000Z
2022-03-31T20:51:36.000Z
src/algorithms/next_pos_chars.hpp
ruolin/vg
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
[ "MIT" ]
2,455
2016-02-24T08:17:45.000Z
2022-03-31T20:19:41.000Z
src/algorithms/next_pos_chars.hpp
ruolin/vg
fddf5a0e3172cfc50eb6f8a561dfbe3dbbbaec04
[ "MIT" ]
169
2016-03-03T15:41:33.000Z
2022-03-31T04:01:53.000Z
#pragma once #include "../handle.hpp" #include <vg/vg.pb.h> #include <functional> #include "../position.hpp" namespace vg { namespace algorithms { using namespace std; map<pos_t, char> next_pos_chars(const PathPositionHandleGraph& graph, pos_t pos); } }
14.444444
81
0.726923
ruolin
9f1f34484b8ebf33a1f2d1fa4e8d7880dd78c071
468
cpp
C++
LuoGu/level1/P1553 1.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
LuoGu/level1/P1553 1.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
LuoGu/level1/P1553 1.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
#include <stdio.h> #include <ctype.h> int main() { int a[20], i=0; char ch; while((ch=getchar())>='0'&&ch<='9') a[i++]=ch-'0'; while(i>0&&a[--i]==0); for(;i>=0;i--) printf("%d",a[i]); if(ch=='\n') return 0; printf("%c",ch); if(ch=='%') return 0; i=0; while((ch=getchar())>='0'&&ch<='9') a[i++]=ch-'0'; int k=0; while(k<i&&a[k++]==0); while(i>0&&a[--i]==0); for(;i>=k-1;i--) printf("%d",a[i]); return 0; }
15.6
37
0.42735
Seizzzz
9f1fe650134466484ceccc8394f6fa881318d4a2
805
cc
C++
cpp/86.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/86.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/86.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
/* * https://leetcode.com/problems/partition-list/ */ #include <iostream> #include <vector> #include <string> #include <algorithm> #include <iomanip> #include <cstdlib> #include <cstdio> #include <map> #include <set> #include <deque> #include <queue> using namespace std; /* //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode lt(0), * pl = &lt; ListNode gt(0), * pg = &gt; ListNode * tmp = head; while (tmp) { if (tmp->val >= x) { pg->next = tmp; pg = pg->next; } else { pl->next = tmp; pl = pl->next; } tmp = tmp->next; } pl->next = gt.next; pg->next = nullptr; return lt.next; } }; */
16.1
48
0.596273
staugust
9f22c4205146955dee7fdc115f39997bbf0dd0d5
7,029
cc
C++
src/test-data/test-keys/reset_key_data.cc
TinkerEdgeR-Android/external_nos_test_system-test-harness
48c68c688044cad7cf7062ef9728f6b930f7c203
[ "Apache-2.0" ]
null
null
null
src/test-data/test-keys/reset_key_data.cc
TinkerEdgeR-Android/external_nos_test_system-test-harness
48c68c688044cad7cf7062ef9728f6b930f7c203
[ "Apache-2.0" ]
null
null
null
src/test-data/test-keys/reset_key_data.cc
TinkerEdgeR-Android/external_nos_test_system-test-harness
48c68c688044cad7cf7062ef9728f6b930f7c203
[ "Apache-2.0" ]
null
null
null
#include "reset_key_data.h" namespace test_data { const uint8_t kResetKeyPem[] = "-----BEGIN RSA PRIVATE KEY-----\n\ MIIEpAIBAAKCAQEAo0IoAa5cK7XyAj7u1jFStsfEcxkgAZVF9VWKzH1bofKxLioA\n\ r5Lo4D33glKehxkOlDo6GkBj1PoI8WuvYYvEUyxJNUdlVpa1C2lbewEL0rfyBrZ9\n\ 4cp0ZeUknymYHn3ynW4Z8sYMlj7BNxGttV/jbxtgtT5WHJ+hg5/4/ifCPucN17Bt\n\ heUKIBoAjy6DlB/pMg1NUQ82DaASMFe89mEzI9Zk4CRtkWjEhknY0bYm46U1ABJb\n\ YmIsHlxdADskvWFDmq8CfJr/jXstTXxZeqaxPPdSP+WPwXN/ku5W7qkF2qimEKiy\n\ DYHzY65JhfWmHOLLGNuz6iHkq93uzkKsGIIPGQIDAQABAoIBABGTvdrwetv56uRz\n\ AiPti4pCV9RMkDWbbLzNSPRbStJU3t6phwlgN9Js2YkefBLvj7JF0pug8x6rDOtx\n\ PKCz+5841Wj3FuILt9JStZa4th0p0NUIMOVudrnBwf+g6s/dn5FzmTeaOyCyAPt8\n\ 28b7W/FKcU8SNxM93JXfU1+JyFAdREqsXQfqLhCAXBb46fs5D8hg0c99RdWuJSuY\n\ HKyVXDrjmYAHS5qUDeMx0OY/q1qM03FBvHekvJ78WPpUKF7B/gYH9lBHIHE0KLJY\n\ JR6kKkzN/Ii6BsSubKKeuNntzlzd2ukvFdX4uc42dDpIXPdaQAn84KRYN7++KoGz\n\ 2LqtAAECgYEAzQt5kt9c+xDeKMPR92XQ4uMeLxTufBei1PFGZbJnJT8aEMkVhKT/\n\ Pbh1Z8OnN9YvFprDNpEilUm7xyffrE7p0pI1/qiBXZExy6pIcGAo4ZcB8ayN0JV3\n\ k+RilE73x+sKAyWOm82b273PiyHNsQI4flkO5Ev9rpZbPMKlvZYsmxkCgYEAy9RR\n\ RwxwCpvFi3um0Rwz7CI2uvVXGaLVXyR2oNGLcJG7AhusYi4FX6XJQ3vAgiDmzu/c\n\ SaEF9w7uqeueIUA7L7njYP1ojfJAUJEtQRfVJF2tDntN5YgYUTsx8n3IKTs4xFT4\n\ dBthKo16zzLv92+8m4sWJhFW2zzFFLwk+G5jlAECgYEAln1piSZus8Y5h2nRXOZZ\n\ XWyb5qpSLrmaRPegV1uM4IVjuBYduPDwdHhBkxrCS/TjMo/73ry+yRsIuq7FN03j\n\ xyyQfItoByhdh8E+0VuCJbATOTEQFJre3KiuwXMD4LLc8lpKRIevcKPrA46XzOZ4\n\ WCM9DsnHMrAf3oRt6KujqWECgYEAyu43fWUEp4suwg/5pXdOumnV040vinZzuKW0\n\ 9aeqDAkLBq5Gkfj/oJqOJoGux9+5640i5KtMJQzY0JOke7ZXNsz7dDTXQ3tMTOo9\n\ A/GWYv5grWpVw5AbpcQpliNkhKhRfCactfwMYTE6c89i2haE0NdI1d2te9ik3l/y\n\ 7uP4gAECgYA3u2CumlkjHq+LbMK6Ry+Ajyy4ssM5PKJUqSogJDUkHsG/C7yaCdq/\n\ Ljt2x2220H0pM9885C3PpKxoYwRih9dzOamnARJocAElp2b5AQB+tKddlMdwx1pQ\n\ 0IMGQ3fBYkDFLGYDk7hGYkLLlSJCZwi64xKmmfEwl83RL6JDSFupDg==\n\ -----END RSA PRIVATE KEY-----"; const size_t kResetKeyPemSize = sizeof(kResetKeyPem); // Dev-signed "null" message. static const uint8_t kNullDevSig[] = { 0x9d, 0x16, 0x0c, 0x04, 0x64, 0xd6, 0x17, 0xbc, 0xf9, 0x81, 0x4d, 0x7b, 0x15, 0x45, 0x2f, 0xa1, 0x66, 0xfa, 0x03, 0x45, 0x50, 0x9b, 0x60, 0x6e, 0x77, 0x76, 0x4d, 0x09, 0x99, 0x98, 0xe5, 0x8e, 0x0a, 0xf3, 0x4e, 0x09, 0x2c, 0xa0, 0xfd, 0x2e, 0xfa, 0x23, 0x16, 0x53, 0x61, 0x43, 0x6b, 0xba, 0xb7, 0xf8, 0x6b, 0xb4, 0xbe, 0x55, 0x3d, 0x21, 0x63, 0x84, 0x64, 0x00, 0x2d, 0xf0, 0x3c, 0x4d, 0x63, 0x4d, 0xe8, 0xf6, 0x26, 0xf7, 0x6b, 0x0e, 0x08, 0xca, 0xda, 0xa0, 0x8d, 0x0a, 0x3f, 0x06, 0x9d, 0xf7, 0x4d, 0x97, 0x86, 0xf4, 0xc2, 0x56, 0x94, 0x85, 0x46, 0xc0, 0x11, 0x0b, 0x9d, 0x12, 0x39, 0x9e, 0x3d, 0xb7, 0xcb, 0xac, 0xe9, 0x63, 0x10, 0xd7, 0xeb, 0x1c, 0x0b, 0xf7, 0x83, 0x06, 0xa8, 0xdd, 0x61, 0x38, 0xef, 0xe8, 0x13, 0x18, 0xda, 0xd8, 0xdc, 0xd6, 0x12, 0x1c, 0xf3, 0x7c, 0x6e, 0x19, 0xd6, 0x94, 0xe6, 0x3a, 0x6e, 0x8e, 0x5b, 0xcf, 0x3a, 0x69, 0x1c, 0xcf, 0xc2, 0x48, 0xc2, 0xb2, 0x1b, 0xb8, 0x24, 0xc2, 0xc5, 0x7e, 0xdc, 0x5d, 0x01, 0xe6, 0xfb, 0x14, 0xbf, 0x96, 0xc1, 0xd3, 0xdf, 0xe5, 0x14, 0x3f, 0xcb, 0xea, 0xfa, 0xef, 0xa7, 0x5c, 0xc3, 0xcb, 0x62, 0x09, 0x0e, 0x1f, 0xd9, 0x56, 0x35, 0xdb, 0x34, 0x23, 0x6a, 0xac, 0x43, 0x0d, 0x27, 0x90, 0x8e, 0x96, 0xcc, 0x89, 0xb6, 0x74, 0x45, 0x1e, 0x8f, 0x48, 0x2a, 0x1d, 0x8f, 0xba, 0xd0, 0x80, 0x7e, 0xf9, 0x1f, 0x21, 0x9b, 0x87, 0x80, 0x9b, 0x9e, 0x1a, 0xb8, 0xc3, 0xe4, 0x55, 0xaa, 0x67, 0xa5, 0x2d, 0x1a, 0x85, 0xd8, 0x6a, 0x9a, 0xc7, 0x5d, 0x1e, 0x1d, 0x51, 0x47, 0x09, 0x51, 0xf6, 0x7c, 0xe9, 0xfc, 0x1f, 0x9e, 0xea, 0xc9, 0xce, 0x77, 0xf2, 0xb1, 0x79, 0x7e, 0x17, 0xc2, 0x78, 0xab, 0xf7 }; static const uint8_t kNullProdSig[] = { 0x41, 0xcf, 0x80, 0xa7, 0x43, 0xdb, 0xb1, 0x08, 0x36, 0x5f, 0xbb, 0x23, 0xa4, 0x1c, 0xa9, 0x28, 0xdf, 0x64, 0x79, 0xeb, 0x41, 0x67, 0x5d, 0x35, 0x09, 0x76, 0x4a, 0xca, 0x74, 0xe8, 0xf0, 0x5b, 0x7d, 0x53, 0x8f, 0x5f, 0x49, 0xdb, 0x7c, 0x08, 0x70, 0xdb, 0xd3, 0xe2, 0x87, 0x51, 0x08, 0x6f, 0x13, 0x40, 0x33, 0x56, 0xa9, 0x99, 0x07, 0xee, 0x18, 0x88, 0xe0, 0x63, 0x15, 0x90, 0x4e, 0xd1, 0x4a, 0x51, 0x00, 0x91, 0x63, 0x3e, 0x55, 0x80, 0xfc, 0xde, 0x18, 0x55, 0x52, 0x89, 0xa0, 0x05, 0xdc, 0x99, 0x80, 0x2c, 0x90, 0xd1, 0x14, 0xea, 0xe0, 0xd7, 0xab, 0x26, 0x67, 0xe3, 0x75, 0xd0, 0x06, 0xa9, 0x36, 0x11, 0x21, 0xc8, 0x21, 0x4c, 0x49, 0xe2, 0x81, 0x66, 0x25, 0x2c, 0x41, 0xb6, 0x48, 0x65, 0x0b, 0x44, 0xc9, 0xcc, 0x0c, 0xad, 0x88, 0x95, 0x9d, 0x9a, 0x25, 0x71, 0xb3, 0x85, 0x22, 0xbf, 0x28, 0x05, 0x65, 0x62, 0x61, 0x54, 0x5d, 0xd9, 0xc8, 0x7c, 0x17, 0x5f, 0xec, 0xc7, 0x40, 0xaf, 0x66, 0xd3, 0x0a, 0x1f, 0x6a, 0x56, 0xbc, 0x48, 0x84, 0xf6, 0x61, 0xa3, 0xab, 0x3c, 0x81, 0x72, 0x75, 0x94, 0x5d, 0x03, 0xeb, 0xca, 0x7f, 0xb3, 0x48, 0xbc, 0x8f, 0x4c, 0xb3, 0xc2, 0xae, 0xa9, 0x53, 0x91, 0x17, 0x48, 0x48, 0x36, 0xb7, 0x7c, 0xd8, 0xe4, 0x99, 0x86, 0x1e, 0x57, 0xaa, 0xaf, 0xab, 0xe4, 0x61, 0x32, 0x58, 0xdb, 0x45, 0x38, 0x26, 0x32, 0x2c, 0xa0, 0x21, 0x34, 0xa3, 0xef, 0x6c, 0x2c, 0x8c, 0x74, 0x10, 0x3c, 0x70, 0x3e, 0xe2, 0x80, 0x7a, 0xf5, 0x9f, 0xf1, 0x92, 0x43, 0x4f, 0x21, 0xb8, 0x21, 0xd5, 0x7a, 0xa7, 0x36, 0xfc, 0x2e, 0x50, 0xd1, 0xa6, 0xbf, 0xfc, 0xc7, 0x57, 0x75, 0x19, 0xb7, 0xcf, 0x8f, 0xdb, 0x3d, 0x1c, 0xa2, 0xdc, 0x81, 0x71, 0x82 }; static const uint8_t kNullTestSig[] = { 0x95, 0x35, 0x5a, 0xb6, 0xe3, 0x8e, 0x43, 0x03, 0xd9, 0xd9, 0xd5, 0x6e, 0x99, 0x86, 0xff, 0x8e, 0x6a, 0xf1, 0x54, 0x6f, 0xa8, 0xff, 0x37, 0x38, 0xc6, 0x9b, 0x4d, 0xc6, 0x99, 0x1f, 0x37, 0x5c, 0xec, 0xf4, 0x32, 0xd8, 0xe6, 0x00, 0xcc, 0x74, 0xde, 0xa9, 0x68, 0x1a, 0xab, 0x6a, 0x6e, 0xe7, 0xa7, 0xa1, 0x59, 0xe0, 0x7c, 0x86, 0x95, 0x28, 0x94, 0x18, 0x3f, 0x0f, 0xb9, 0x0f, 0x05, 0x6c, 0x86, 0x5a, 0x6a, 0xe4, 0x6d, 0x36, 0x71, 0x86, 0x38, 0xab, 0x7a, 0x2d, 0x9c, 0xa5, 0xfa, 0xc8, 0x7c, 0x48, 0x02, 0x8c, 0x6b, 0x4d, 0xda, 0xa4, 0xb5, 0xa8, 0x17, 0x39, 0x5e, 0xe3, 0x1a, 0xd5, 0xf8, 0x87, 0x6e, 0xd9, 0xc0, 0x0c, 0x29, 0x4d, 0x93, 0xa2, 0x3b, 0xfc, 0x2d, 0x38, 0x8e, 0x2b, 0xc7, 0x49, 0x26, 0xd9, 0xcb, 0x47, 0x89, 0x4c, 0x79, 0xd3, 0x60, 0x62, 0xf9, 0x71, 0xa7, 0x73, 0x6a, 0x03, 0x65, 0x1f, 0x11, 0x0d, 0x9e, 0x27, 0x99, 0x6b, 0xa7, 0x46, 0x85, 0x75, 0xec, 0xff, 0x5b, 0x1d, 0x8d, 0x1b, 0x34, 0xd8, 0xb9, 0x4f, 0x63, 0x88, 0x08, 0xa8, 0x16, 0xba, 0xfc, 0xe7, 0x66, 0xa4, 0xe5, 0xde, 0x4e, 0x0b, 0x98, 0x80, 0xd5, 0x16, 0x55, 0xfb, 0xdb, 0xe8, 0xa2, 0x90, 0x85, 0x4e, 0xa9, 0xb6, 0x81, 0x55, 0xef, 0xbf, 0x12, 0xe3, 0xd2, 0xa9, 0xae, 0x2c, 0x43, 0x67, 0x4c, 0x09, 0x6d, 0x95, 0xaf, 0x44, 0xc2, 0xb9, 0x9d, 0x7c, 0xb1, 0x88, 0xf8, 0x6c, 0xa0, 0x13, 0x4c, 0xbf, 0x85, 0xa2, 0x8b, 0x9d, 0x06, 0xc8, 0x11, 0xdb, 0x1f, 0xfb, 0x05, 0x15, 0xd6, 0x1f, 0xe5, 0x52, 0x9c, 0xd5, 0xbd, 0xff, 0xb0, 0xce, 0x29, 0xec, 0xd8, 0x9e, 0xdb, 0x5b, 0xc9, 0x52, 0x24, 0xaf, 0x22, 0xeb, 0xce, 0x15, 0x0d, 0xfd, 0x6c, 0x76, 0x90, 0x3e, 0x4f, 0x63, 0xfd, 0xb1 }; const uint8_t *kResetSignatures[] = { [0] = kNullTestSig, [1] = kNullDevSig, [2] = kNullProdSig, }; const size_t kResetSignatureLengths[] = { 256, 256, 256, }; const size_t kResetSignatureCount = 3; } // namespace test_data
56.232
73
0.71959
TinkerEdgeR-Android
9f22d3790d88e1ac78e04f0fa1ddd96685262d2f
1,357
cpp
C++
src/zone_server.cpp
sischkg/nxnsattack
c20896e40187bbcacb5c0255ff8f3cc7d0592126
[ "MIT" ]
5
2020-05-22T10:01:51.000Z
2022-01-01T04:45:14.000Z
src/zone_server.cpp
sischkg/dns-fuzz-server
6f45079014e745537c2f564fdad069974e727da1
[ "MIT" ]
1
2020-06-07T14:09:44.000Z
2020-06-07T14:09:44.000Z
src/zone_server.cpp
sischkg/dns-fuzz-server
6f45079014e745537c2f564fdad069974e727da1
[ "MIT" ]
2
2020-03-10T03:06:20.000Z
2021-07-25T15:07:45.000Z
#include "auth_server.hpp" #include <boost/program_options.hpp> #include <iostream> #include <fstream> int main( int argc, char **argv ) { namespace po = boost::program_options; std::string bind_address; uint16_t bind_port; std::string zone_filename; std::string apex; po::options_description desc( "unbound" ); desc.add_options()( "help,h", "print this message" ) ( "bind,b", po::value<std::string>( &bind_address )->default_value( "0.0.0.0" ), "bind address" ) ( "port,p", po::value<uint16_t>( &bind_port )->default_value( 53 ), "bind port" ) ( "file,f", po::value<std::string>( &zone_filename ), "zone filename" ) ( "zone,z", po::value<std::string>( &apex), "zone apex" ); po::variables_map vm; po::store( po::parse_command_line( argc, argv, desc ), vm ); po::notify( vm ); if ( vm.count( "help" ) ) { std::cerr << desc << "\n"; return 1; } try { dns::DNSServerParameters params; params.mBindAddress = bind_address; params.mBindPort = bind_port; dns::AuthServer server( params ); server.load( apex, zone_filename ); server.start(); } catch ( std::runtime_error &e ) { std::cerr << e.what() << std::endl; } catch ( std::logic_error &e ) { std::cerr << e.what() << std::endl; } return 0; }
27.693878
105
0.590273
sischkg
9f23a340317e03cb15a7ec88a2cc6bb8c32dd96b
9,980
cpp
C++
tests/RaZ/Render/Shader.cpp
xiaohunqupo/RaZ
ad0a1e0f336d8beb20afc73c0a5e6ee8a319a8f1
[ "MIT" ]
1
2022-01-26T06:36:54.000Z
2022-01-26T06:36:54.000Z
tests/RaZ/Render/Shader.cpp
xiaohunqupo/RaZ
ad0a1e0f336d8beb20afc73c0a5e6ee8a319a8f1
[ "MIT" ]
null
null
null
tests/RaZ/Render/Shader.cpp
xiaohunqupo/RaZ
ad0a1e0f336d8beb20afc73c0a5e6ee8a319a8f1
[ "MIT" ]
null
null
null
#include "Catch.hpp" #include "RaZ/Render/Renderer.hpp" #include "RaZ/Render/Shader.hpp" namespace { inline void checkShader(const Raz::Shader& shader, const Raz::FilePath& path = {}) { CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(shader.isValid()); CHECK(shader.getPath() == path); shader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(shader.isCompiled()); } } // namespace TEST_CASE("Shader validity") { Raz::Renderer::recoverErrors(); // Flushing errors { Raz::VertexShader vertShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isValid()); vertShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(vertShader.isValid()); } // Tessellation shaders are only available in OpenGL 4.0+ if (Raz::Renderer::checkVersion(4, 0)) { { Raz::TessellationControlShader tessCtrlShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(tessCtrlShader.isValid()); tessCtrlShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(tessCtrlShader.isValid()); } { Raz::TessellationEvaluationShader tessEvalShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(tessEvalShader.isValid()); tessEvalShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(tessEvalShader.isValid()); } } { Raz::GeometryShader geomShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(geomShader.isValid()); geomShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(geomShader.isValid()); } { Raz::FragmentShader fragShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isValid()); fragShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(fragShader.isValid()); } // Compute shaders are only available in OpenGL 4.3+ if (Raz::Renderer::checkVersion(4, 3)) { Raz::ComputeShader compShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(compShader.isValid()); compShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(compShader.isValid()); } } TEST_CASE("Shader clone") { // The content of the shaders does not need to be valid for this test const Raz::FilePath shaderPath = RAZ_TESTS_ROOT "assets/shaders/basic.comp"; constexpr std::string_view shaderSource = "Shader source test"; static constexpr auto areShadersEqual = [] (const Raz::Shader& shader1, const Raz::Shader& shader2) { CHECK_FALSE(shader1.getIndex() == shader2.getIndex()); // Both shaders remain two different objects: their indices must be different CHECK(shader1.getPath() == shader2.getPath()); CHECK(Raz::Renderer::recoverShaderType(shader1.getIndex()) == Raz::Renderer::recoverShaderType(shader2.getIndex())); CHECK(Raz::Renderer::recoverShaderSource(shader1.getIndex()) == Raz::Renderer::recoverShaderSource(shader2.getIndex())); }; { const Raz::VertexShader shaderFromPath(shaderPath); areShadersEqual(shaderFromPath, shaderFromPath.clone()); const Raz::VertexShader shaderFromSource = Raz::VertexShader::loadFromSource(shaderSource); areShadersEqual(shaderFromSource, shaderFromSource.clone()); } // Tessellation shaders are only available in OpenGL 4.0+ if (Raz::Renderer::checkVersion(4, 0)) { { const Raz::TessellationControlShader shaderFromPath(shaderPath); areShadersEqual(shaderFromPath, shaderFromPath.clone()); const Raz::TessellationControlShader shaderFromSource = Raz::TessellationControlShader::loadFromSource(shaderSource); areShadersEqual(shaderFromSource, shaderFromSource.clone()); } { const Raz::TessellationEvaluationShader shaderFromPath(shaderPath); areShadersEqual(shaderFromPath, shaderFromPath.clone()); const Raz::TessellationEvaluationShader shaderFromSource = Raz::TessellationEvaluationShader::loadFromSource(shaderSource); areShadersEqual(shaderFromSource, shaderFromSource.clone()); } } { const Raz::GeometryShader shaderFromPath(shaderPath); areShadersEqual(shaderFromPath, shaderFromPath.clone()); const Raz::GeometryShader shaderFromSource = Raz::GeometryShader::loadFromSource(shaderSource); areShadersEqual(shaderFromSource, shaderFromSource.clone()); } { const Raz::FragmentShader shaderFromPath(shaderPath); areShadersEqual(shaderFromPath, shaderFromPath.clone()); const Raz::FragmentShader shaderFromSource = Raz::FragmentShader::loadFromSource(shaderSource); areShadersEqual(shaderFromSource, shaderFromSource.clone()); } // Compute shaders are only available in OpenGL 4.3+ if (Raz::Renderer::checkVersion(4, 3)) { const Raz::ComputeShader shaderFromPath(shaderPath); areShadersEqual(shaderFromPath, shaderFromPath.clone()); const Raz::ComputeShader shaderFromSource = Raz::ComputeShader::loadFromSource(shaderSource); areShadersEqual(shaderFromSource, shaderFromSource.clone()); } } TEST_CASE("Vertex shader from source") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string vertSource = R"( void main() { gl_Position = vec4(1.0); } )"; // The #version tag is automatically added if not present; if it is, nothing is changed to the source checkShader(Raz::VertexShader::loadFromSource(vertSource)); checkShader(Raz::VertexShader::loadFromSource("#version 330\n" + vertSource)); } TEST_CASE("Tessellation control shader from source") { // Tessellation shaders are only available in OpenGL 4.0+ if (!Raz::Renderer::checkVersion(4, 0)) return; Raz::Renderer::recoverErrors(); // Flushing errors const std::string tessCtrlSource = R"( layout(vertices = 3) out; void main() { gl_TessLevelOuter[0] = 1.0; gl_TessLevelOuter[1] = 2.0; gl_TessLevelOuter[2] = 3.0; gl_TessLevelOuter[3] = 4.0; gl_TessLevelInner[0] = 1.0; gl_TessLevelInner[1] = 2.0; } )"; // The #version tag is automatically added if not present; if it is, nothing is changed to the source checkShader(Raz::TessellationControlShader::loadFromSource(tessCtrlSource)); checkShader(Raz::TessellationControlShader::loadFromSource("#version 400\n" + tessCtrlSource)); } TEST_CASE("Tessellation evaluation shader from source") { // Tessellation shaders are only available in OpenGL 4.0+ if (!Raz::Renderer::checkVersion(4, 0)) return; Raz::Renderer::recoverErrors(); // Flushing errors const std::string tessEvalSource = R"( layout(triangles, equal_spacing, ccw) in; void main() { gl_Position = vec4(0.0); } )"; // The #version tag is automatically added if not present; if it is, nothing is changed to the source checkShader(Raz::TessellationEvaluationShader::loadFromSource(tessEvalSource)); checkShader(Raz::TessellationEvaluationShader::loadFromSource("#version 400\n" + tessEvalSource)); } TEST_CASE("Fragment shader from source") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string fragSource = R"( layout(location = 0) out vec4 fragColor; void main() { fragColor = vec4(1.0); } )"; // The #version tag is automatically added if not present; if it is, nothing is changed to the source checkShader(Raz::FragmentShader::loadFromSource(fragSource)); checkShader(Raz::FragmentShader::loadFromSource("#version 330\n" + fragSource)); } TEST_CASE("Compute shader from source") { // Compute shaders are only available in OpenGL 4.3+ if (!Raz::Renderer::checkVersion(4, 3)) return; Raz::Renderer::recoverErrors(); // Flushing errors const std::string compSource = R"( layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; layout(rgba32f, binding = 0) uniform image2D uniOutput; void main() { imageStore(uniOutput, ivec2(0), vec4(0.0)); } )"; // The #version tag is automatically added if not present; if it is, nothing is changed to the source checkShader(Raz::ComputeShader::loadFromSource(compSource)); checkShader(Raz::ComputeShader::loadFromSource("#version 430\n" + compSource)); } TEST_CASE("Vertex shader imported") { Raz::Renderer::recoverErrors(); // Flushing errors const Raz::FilePath vertShaderPath = RAZ_TESTS_ROOT "../shaders/common.vert"; const Raz::VertexShader vertShader(vertShaderPath); checkShader(vertShader, vertShaderPath); } TEST_CASE("Tessellation control shader imported") { // Tessellation shaders are only available in OpenGL 4.0+ if (!Raz::Renderer::checkVersion(4, 0)) return; Raz::Renderer::recoverErrors(); // Flushing errors const Raz::FilePath tessCtrlShaderPath = RAZ_TESTS_ROOT "assets/shaders/basic.tesc"; const Raz::TessellationControlShader tessCtrlShader(tessCtrlShaderPath); checkShader(tessCtrlShader, tessCtrlShaderPath); } TEST_CASE("Tessellation evaluation shader imported") { // Tessellation shaders are only available in OpenGL 4.0+ if (!Raz::Renderer::checkVersion(4, 0)) return; Raz::Renderer::recoverErrors(); // Flushing errors const Raz::FilePath tessEvalShaderPath = RAZ_TESTS_ROOT "assets/shaders/basic.tese"; const Raz::TessellationEvaluationShader tessEvalShader(tessEvalShaderPath); checkShader(tessEvalShader, tessEvalShaderPath); } TEST_CASE("Fragment shader imported") { Raz::Renderer::recoverErrors(); // Flushing errors const Raz::FilePath fragShaderPath = RAZ_TESTS_ROOT "../shaders/lambert.frag"; const Raz::FragmentShader fragShader(fragShaderPath); checkShader(fragShader, fragShaderPath); } TEST_CASE("Compute shader imported") { // Compute shaders are only available in OpenGL 4.3+ if (!Raz::Renderer::checkVersion(4, 3)) return; Raz::Renderer::recoverErrors(); // Flushing errors const Raz::FilePath compShaderPath = RAZ_TESTS_ROOT "assets/shaders/basic.comp"; const Raz::ComputeShader compShader(compShaderPath); checkShader(compShader, compShaderPath); }
32.508143
136
0.71994
xiaohunqupo
9f267d44ac326c20212e735301699300d0b135e0
1,145
cpp
C++
Engine/Renderer/GLES3/src/GLES3RenderTextureManager.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
3
2018-12-08T16:32:05.000Z
2020-06-02T11:07:15.000Z
Engine/Renderer/GLES3/src/GLES3RenderTextureManager.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
null
null
null
Engine/Renderer/GLES3/src/GLES3RenderTextureManager.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
1
2019-09-12T00:26:05.000Z
2019-09-12T00:26:05.000Z
#include "GLES3Renderer.h" CGLES3RenderTextureManager::CGLES3RenderTextureManager(void) { } CGLES3RenderTextureManager::~CGLES3RenderTextureManager(void) { for (const auto& itRenderTexture : m_pRenderTextures) { delete itRenderTexture.second; } } CGLES3RenderTexture* CGLES3RenderTextureManager::Get(uint32_t name) { mutex_autolock autolock(&lock); { const auto& itRenderTexture = m_pRenderTextures.find(name); if (itRenderTexture != m_pRenderTextures.end()) { return itRenderTexture->second; } else { return nullptr; } } } CGLES3RenderTexture* CGLES3RenderTextureManager::Create(uint32_t name) { mutex_autolock autolock(&lock); { if (m_pRenderTextures[name] == nullptr) { m_pRenderTextures[name] = new CGLES3RenderTexture(this, name); } return m_pRenderTextures[name]; } } void CGLES3RenderTextureManager::Destroy(CGLES3RenderTexture* pRenderTexture) { ASSERT(pRenderTexture); { mutex_autolock autolock(&lock); { if (m_pRenderTextures.find(pRenderTexture->GetName()) != m_pRenderTextures.end()) { m_pRenderTextures.erase(pRenderTexture->GetName()); } } } delete pRenderTexture; }
20.446429
86
0.751092
LiangYue1981816
9f2a3372e84e19137a06ffc0268222985e532a7d
3,811
cc
C++
ui/gl/android/surface_texture_bridge.cc
MIPS/external-chromium_org
e31b3128a419654fd14003d6117caa8da32697e7
[ "BSD-3-Clause" ]
2
2017-10-19T13:50:00.000Z
2019-05-26T20:11:54.000Z
ui/gl/android/surface_texture_bridge.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/gl/android/surface_texture_bridge.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 "ui/gl/android/surface_texture_bridge.h" #include <android/native_window_jni.h> // TODO(boliu): Remove this include when we move off ICS. #include "base/android/build_info.h" #include "base/android/jni_android.h" #include "base/logging.h" #include "jni/SurfaceTextureBridge_jni.h" #include "ui/gl/android/scoped_java_surface.h" #include "ui/gl/android/surface_texture_listener.h" #include "ui/gl/gl_bindings.h" // TODO(boliu): Remove this method when when we move off ICS. See // http://crbug.com/161864. bool GlContextMethodsAvailable() { bool available = base::android::BuildInfo::GetInstance()->sdk_int() >= 16; if (!available) LOG(WARNING) << "Running on unsupported device: rendering may not work"; return available; } namespace gfx { SurfaceTextureBridge::SurfaceTextureBridge(int texture_id) { JNIEnv* env = base::android::AttachCurrentThread(); j_surface_texture_.Reset(Java_SurfaceTextureBridge_create(env, texture_id)); } SurfaceTextureBridge::~SurfaceTextureBridge() { JNIEnv* env = base::android::AttachCurrentThread(); Java_SurfaceTextureBridge_destroy(env, j_surface_texture_.obj()); } void SurfaceTextureBridge::SetFrameAvailableCallback( const base::Closure& callback) { JNIEnv* env = base::android::AttachCurrentThread(); Java_SurfaceTextureBridge_setFrameAvailableCallback( env, j_surface_texture_.obj(), reinterpret_cast<int>(new SurfaceTextureListener(callback))); } void SurfaceTextureBridge::UpdateTexImage() { JNIEnv* env = base::android::AttachCurrentThread(); Java_SurfaceTextureBridge_updateTexImage(env, j_surface_texture_.obj()); } void SurfaceTextureBridge::GetTransformMatrix(float mtx[16]) { JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaLocalRef<jfloatArray> jmatrix( env, env->NewFloatArray(16)); Java_SurfaceTextureBridge_getTransformMatrix( env, j_surface_texture_.obj(), jmatrix.obj()); jboolean is_copy; jfloat* elements = env->GetFloatArrayElements(jmatrix.obj(), &is_copy); for (int i = 0; i < 16; ++i) { mtx[i] = static_cast<float>(elements[i]); } env->ReleaseFloatArrayElements(jmatrix.obj(), elements, JNI_ABORT); } void SurfaceTextureBridge::SetDefaultBufferSize(int width, int height) { JNIEnv* env = base::android::AttachCurrentThread(); if (width > 0 && height > 0) { Java_SurfaceTextureBridge_setDefaultBufferSize( env, j_surface_texture_.obj(), static_cast<jint>(width), static_cast<jint>(height)); } else { LOG(WARNING) << "Not setting surface texture buffer size - " "width or height is 0"; } } void SurfaceTextureBridge::AttachToGLContext() { if (GlContextMethodsAvailable()) { int texture_id; glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &texture_id); DCHECK(texture_id); JNIEnv* env = base::android::AttachCurrentThread(); Java_SurfaceTextureBridge_attachToGLContext( env, j_surface_texture_.obj(), texture_id); } } void SurfaceTextureBridge::DetachFromGLContext() { if (GlContextMethodsAvailable()) { JNIEnv* env = base::android::AttachCurrentThread(); Java_SurfaceTextureBridge_detachFromGLContext( env, j_surface_texture_.obj()); } } ANativeWindow* SurfaceTextureBridge::CreateSurface() { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaSurface surface(this); ANativeWindow* native_window = ANativeWindow_fromSurface( env, surface.j_surface().obj()); return native_window; } // static bool SurfaceTextureBridge::RegisterSurfaceTextureBridge(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace gfx
33.13913
78
0.741275
MIPS
9f2b822d465d8152de0081d95510fb3ea6bd72d4
1,825
cpp
C++
2020/discrete-mathematics/adjacency-table-and-adjacency-matrix/main.cpp
Overloadlightning/BIT
de85cb74523d63b22b0118c26c65f854b7d2df86
[ "MIT" ]
6
2021-10-30T06:07:42.000Z
2022-03-02T15:24:57.000Z
2020/discrete-mathematics/adjacency-table-and-adjacency-matrix/main.cpp
Overloadlightning/BIT
de85cb74523d63b22b0118c26c65f854b7d2df86
[ "MIT" ]
null
null
null
2020/discrete-mathematics/adjacency-table-and-adjacency-matrix/main.cpp
Overloadlightning/BIT
de85cb74523d63b22b0118c26c65f854b7d2df86
[ "MIT" ]
1
2022-02-21T15:37:49.000Z
2022-02-21T15:37:49.000Z
#include <algorithm> #include <cstdio> #include <cstring> struct point { char name; int neighbor_num; char neighbor[500]; }; bool comp(point a, point b) { return a.name < b.name; } int main() { point point_list[100]; char str[500] = {'\0'}; int point_num = 0; while (gets(str) != NULL) { int length = strlen(str); int index = -1; for (int i = 0; i < point_num; i++) if (str[0] == point_list[i].name) { index = i; break; } if (index != -1) { for (int i = 1; i < length; i++) { if (str[i] == ' ') continue; else point_list[index].neighbor[point_list[index].neighbor_num++] = str[i]; } } else { point_list[point_num].name = str[0]; point_list[point_num].neighbor_num = 0; for (int i = 1; i < length; i++) { if (str[i] == ' ') continue; else point_list[point_num].neighbor[point_list[point_num].neighbor_num++] = str[i]; } point_num++; } } std::sort(point_list, point_list + point_num, comp); for (int i = 0; i < point_num; i++) { for (int j = 0; j < point_num - 1; j++) { int sum = 0; for (int k = 0; k < point_list[i].neighbor_num; k++) if (point_list[j].name == point_list[i].neighbor[k]) sum += 1; printf("%d ", sum); } int sum = 0; for (int k = 0; k < point_list[i].neighbor_num; k++) if (point_list[point_num - 1].name == point_list[i].neighbor[k]) sum += 1; printf("%d\n", sum); } return 0; }
28.076923
98
0.445479
Overloadlightning
9f2d8d92c62b48c3433cc9060f68e9d2cdcfc254
5,295
hpp
C++
third_party/amo/amo/asio/tcp/client_socket.hpp
amoylel/NCUI
a3b315ebf97d9903766efdafa42c24d4212d5ad6
[ "BSD-2-Clause" ]
24
2018-11-20T14:45:57.000Z
2021-12-30T13:38:42.000Z
third_party/amo/amo/asio/tcp/client_socket.hpp
amoylel/NCUI
a3b315ebf97d9903766efdafa42c24d4212d5ad6
[ "BSD-2-Clause" ]
null
null
null
third_party/amo/amo/asio/tcp/client_socket.hpp
amoylel/NCUI
a3b315ebf97d9903766efdafa42c24d4212d5ad6
[ "BSD-2-Clause" ]
11
2018-11-29T00:09:14.000Z
2021-11-23T08:13:17.000Z
// Created by amoylel on 06/09/2018. // Copyright (c) 2018 amoylel All rights reserved. #ifndef AMO_CLIENT_SOCKET_63DEE874_EDFB_4063_A818_BA44CA9D0782_HPP__ #define AMO_CLIENT_SOCKET_63DEE874_EDFB_4063_A818_BA44CA9D0782_HPP__ #include <iostream> #define ST_ASIO_REUSE_OBJECT //use objects pool //#define ST_ASIO_FREE_OBJECT_INTERVAL 60 //it's useless if ST_ASIO_REUSE_OBJECT macro been defined //#define ST_ASIO_FORCE_TO_USE_MSG_RECV_BUFFER //force to use the msg recv buffer #define ST_ASIO_ENHANCED_STABILITY #define ST_ASIO_FULL_STATISTIC //full statistic will slightly impact efficiency //#define ST_ASIO_USE_STEADY_TIMER //#define ST_ASIO_USE_SYSTEM_TIMER #define ST_ASIO_AVOID_AUTO_STOP_SERVICE #define ST_ASIO_DECREASE_THREAD_AT_RUNTIME //#ifndef ST_ASIO_HEARTBEAT_INTERVAL //#define ST_ASIO_HEARTBEAT_INTERVAL 5 //#endif #include <amo/asio/tcp/packer.hpp> #include <amo/asio/tcp/unpacker.hpp> #include <amo/asio/st_asio_wrapper/ext/tcp.h> using namespace st_asio_wrapper; using namespace st_asio_wrapper::tcp; using namespace st_asio_wrapper::ext; using namespace st_asio_wrapper::ext::tcp; namespace amo { template<typename Packer, typename Unpacker> class client_socket : public client_socket_base<Packer, Unpacker> { public: client_socket(boost::asio::io_context & io_context_): client_socket_base(io_context_) { } protected: // virtual bool do_start() { // //#if ST_ASIO_HEARTBEAT_INTERVAL > 0 // start_heartbeat(ST_ASIO_HEARTBEAT_INTERVAL); //#endif // return normal_socket_base::do_start(); // } // // virtual bool on_msg(out_msg_type& msg) override { // if (m_fnOnMessageCallback) { // boost::system::error_code ec; // // auto ep = this->lowest_layer().remote_endpoint(ec); // // if (!ec) { // if (msg.find("{\"notify\":\"gps\"") != 0) { // unified_out::debug_out("[%s" ":%d] " "recv(" ST_ASIO_SF "): %s", // ep.address().to_string().c_str(), ep.port(), msg.size(), msg.data()); // } // } // // m_fnOnMessageCallback(msg); // // return true; // } // // return client_socket_base::on_msg(msg); // } // // virtual bool on_msg_handle(out_msg_type& msg) override { // if (m_fnOnMessageCallback) { // //unified_out::debug_out("recv(" ST_ASIO_SF "): %s", msg.size(), msg.data()); // // boost::system::error_code ec; // auto ep = this->lowest_layer().remote_endpoint(ec); // // if (!ec) { // unified_out::debug_out("[%s" ":%d] ""recv(" ST_ASIO_SF "): %s", // ep.address().to_string().c_str(), ep.port(), msg.size(), msg.data()); // } // // m_fnOnMessageCallback(msg); // return true; // } // // return client_socket_base::on_msg(msg); // } // // // virtual bool do_send_msg(in_msg_type& msg) override { // return client_socket_base::do_send_msg(msg); // } // // virtual bool do_send_msg() override { // return client_socket_base::do_send_msg(); // } // // virtual void do_recv_msg() override { // return client_socket_base::do_recv_msg(); // } // // virtual void on_connect() override { // return client_socket_base::on_connect(); // } // // virtual void on_unpack_error() override { // return client_socket_base::on_unpack_error(); // } // // virtual void on_recv_error(const boost::system::error_code& ec) override { // return client_socket_base::on_recv_error(ec); // } // // virtual void on_async_shutdown_error() override { // return client_socket_base::on_async_shutdown_error(); // } // // virtual bool on_heartbeat_error() override { // return client_socket_base::on_heartbeat_error(); // } public: std::function<bool(out_msg_type &)> get_on_message_callback() const { return m_fnOnMessageCallback; } void set_on_message_callback(std::function<bool(out_msg_type &)> val) { m_fnOnMessageCallback = val; } protected: std::function<bool(out_msg_type&)> m_fnOnMessageCallback; }; } #endif // AMO_CLIENT_SOCKET_63DEE874_EDFB_4063_A818_BA44CA9D0782_HPP__
34.607843
126
0.525212
amoylel
9f330b4981e392f286ea29795129ed4a5ede00c6
577
cpp
C++
C++/Quardratic.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
41
2021-10-03T16:03:52.000Z
2021-11-14T18:15:33.000Z
C++/Quardratic.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
175
2021-10-03T10:47:31.000Z
2021-10-20T11:55:32.000Z
C++/Quardratic.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
208
2021-10-03T11:24:04.000Z
2021-10-31T17:27:59.000Z
//3. roots of quadratic equation #include <iostream> #include <cmath> using namespace std; int main(){ cout<<" please enter a, b and c according to your quadratic equation ax^2 + bx + c = 0 "<<endl; float a,b,c,r1,r2;// where a, b and c are coefficients as per quadratic equation ax^2 + bx + c = 0 and r1, r2 are roots of the equation cout<<"enter a :"; cin>> a; cout<<"enter b :"; cin>>b; cout<<"enter c :"; cin>>c; r1= (-b+ sqrt(b*b-4*a*c))/(2*a); r2= (-b-sqrt(b*b-4*a*c))/(2*a); cout<<"roots are"<< r1 <<" "<<r2; return 0; }
28.85
139
0.568458
rj011
9f33f2dc68eb1ca8e9c6958e1e0c79e895cec810
1,534
cpp
C++
Geometry/LayeredBlock.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Geometry/LayeredBlock.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
Geometry/LayeredBlock.cpp
danielfrascarelli/esys-particle
e56638000fd9c4af77e21c75aa35a4f8922fd9f0
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////// // // // Copyright (c) 2003-2017 by The University of Queensland // // Centre for Geoscience Computing // // http://earth.uq.edu.au/centre-geoscience-computing // // // // Primary Business: Brisbane, Queensland, Australia // // Licensed under the Open Software License version 3.0 // // http://www.apache.org/licenses/LICENSE-2.0 // // // ///////////////////////////////////////////////////////////// #include "Geometry/LayeredBlock.h" CLayeredBlock2D::CLayeredBlock2D(double xmin,double xmax,double ymin,double ymax,double rmin,double rmax):CRandomBlock2D(xmin,xmax,ymin,ymax,rmin,rmax,1.05) {} CLayeredBlock2D::~CLayeredBlock2D() {} void CLayeredBlock2D::addLayerBoundary(double d) { LayerBoundaries.insert(d);; } void CLayeredBlock2D::generate(int tries,unsigned int seed) { // generate particles CRandomBlock2D::generate(tries,seed); //-- set tags according to layer -- int nlayer=0; for(set<double>::iterator it1=LayerBoundaries.begin(); it1!=LayerBoundaries.end(); it1++){ nlayer++; cout << "layer "<< nlayer << " bdry: " << *it1 << endl; for(vector<SimpleParticle>::iterator iter=m_bpart.begin(); iter!=m_bpart.end(); iter++){ if(iter->getPos().Y()>*it1){ iter->setTag(nlayer); } } } }
33.347826
156
0.529987
danielfrascarelli
9f3987fbb9f0e91edeb0403e6b34be56e630e354
3,702
cc
C++
src/usart.cc
radishkill/check_system
0f5692462ebd40a0d7b7ae2a8462df75b6fec74c
[ "Apache-2.0" ]
null
null
null
src/usart.cc
radishkill/check_system
0f5692462ebd40a0d7b7ae2a8462df75b6fec74c
[ "Apache-2.0" ]
null
null
null
src/usart.cc
radishkill/check_system
0f5692462ebd40a0d7b7ae2a8462df75b6fec74c
[ "Apache-2.0" ]
null
null
null
#include "usart.h" #include "mutils.h" Usart::Usart() : fd_(-1), device_name_("") { } Usart::Usart(const char* name, int baud_rate, int databits, int stopbits, char parity, int flow_ctrl) { Open(name, baud_rate, databits, stopbits, parity, flow_ctrl); } int Usart::Open(const char* name, int baud_rate, int databits, int stopbits, char parity, int flow_ctrl) { device_name_ = name; fd_ = open(device_name_.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); if (fd_ == -1) { perror("open serialPort fail"); return -1; } SetParity(baud_rate, databits, stopbits, parity, flow_ctrl); return 0; } int Usart::SetParity(int baud_rate, int databits, int stopbits, char parity, int flow_ctrl) { struct termios options; if ( tcgetattr( fd_, &options) != 0) { return (-1); } bzero(&options, sizeof(options)); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~CSIZE; switch (baud_rate) { case 2400: cfsetispeed(&options, B2400); cfsetospeed(&options, B2400); break; case 4800: cfsetispeed(&options, B4800); cfsetospeed(&options, B4800); break; case 9600: cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); break; case 115200: cfsetispeed(&options, B115200); cfsetospeed(&options, B115200); break; default: cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); break; } switch (databits) /*设置数据位数*/ { case 5: options.c_cflag |= CS5; break; case 6: options.c_cflag |= CS6; break; case 7: options.c_cflag |= CS7; break; case 8: options.c_cflag |= CS8; break; } /* 设置停止位*/ switch (stopbits) { case 1: options.c_cflag &= ~CSTOPB; break; case 2: options.c_cflag |= CSTOPB; break; default: fprintf(stderr,"Unsupported stop bits\n"); return -1; } // 校验码 switch (parity) { case '0': /*奇校验*/ options.c_cflag |= PARENB;/*开启奇偶校验*/ options.c_iflag |= (INPCK | ISTRIP);/*INPCK打开输入奇偶校验;ISTRIP去除字符的第八个比特 */ options.c_cflag |= PARODD;/*启用奇校验(默认为偶校验)*/ break; case 'E':/*偶校验*/ options.c_cflag |= PARENB; /*开启奇偶校验 */ options.c_iflag |= ( INPCK | ISTRIP);/*打开输入奇偶校验并去除字符第八个比特*/ options.c_cflag &= ~PARODD;/*启用偶校验*/ break; case 'N': /*无奇偶校验*/ options.c_cflag &= ~PARENB; break; } switch (flow_ctrl) { case 0: options.c_cflag &= ~CRTSCTS; break; case 1://haidware // options.c_cflag |= CRTSCTS; break; case 2://software flow_ctrl = 0; options.c_iflag |= (IXON | IXOFF | IXANY); break; default: fprintf(stderr,"error\n"); break; } /*设置最少字符和等待时间,对于接收字符和等待时间没有特别的要求时*/ options.c_cc[VTIME] = 0;/*非规范模式读取时的超时时间;*/ options.c_cc[VMIN] = 0; /*非规范模式读取时的最小字符数*/ tcflush(fd_ ,TCIFLUSH);/*tcflush清空终端未完成的输入/输出请求及数据;TCIFLUSH表示清空正收到的数据,且不读取出来 */ return tcsetattr(fd_, TCSAFLUSH, &options); } int Usart::SendData(char* buf, int len) { std::cout << "send:"; Utils::ShowRawString(buf, len); std::cout << std::endl; return write(fd_, buf, len); } int Usart::ReadData(char* buf, int len) { std::cout << "recv:"; int ret = read(fd_, buf, len); Utils::ShowRawString(buf, ret); std::cout << std::endl; return ret; } bool Usart::IsOpen() const { if (fd_ <= 0) return false; return true; } int Usart::GetFd() const { return fd_; } void Usart::Close() { close(fd_); fd_ = -1; }
23.730769
106
0.573474
radishkill
9f39f8cf75d908f2fb7704ad6e7097c4e1c0315d
960
hh
C++
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommPersonLostEventResultData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
null
null
null
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommPersonLostEventResultData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
2
2020-08-20T14:49:47.000Z
2020-10-07T16:10:07.000Z
CommTrackingObjects/smartsoft/src-gen/CommTrackingObjects/CommPersonLostEventResultData.hh
canonical-robots/DomainModelsRepositories
68b9286d84837e5feb7b200833b158ab9c2922a4
[ "BSD-3-Clause" ]
8
2018-06-25T08:41:28.000Z
2020-08-13T10:39:30.000Z
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef COMMTRACKINGOBJECTS_COMMPERSONLOSTEVENTRESULT_DATA_H_ #define COMMTRACKINGOBJECTS_COMMPERSONLOSTEVENTRESULT_DATA_H_ #include "CommTrackingObjects/enumPersonLostEventTypeData.hh" namespace CommTrackingObjectsIDL { struct CommPersonLostEventResult { CommTrackingObjectsIDL::PersonLostEventType state; }; }; #endif /* COMMTRACKINGOBJECTS_COMMPERSONLOSTEVENTRESULT_DATA_H_ */
30.967742
76
0.676042
canonical-robots
9f3b907f061965f3de5e1526686d532c2c4cd3f1
826
cpp
C++
codeforces/contests/1351/A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
codeforces/contests/1351/A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
codeforces/contests/1351/A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* A. A+B (Trial Problem) time limit per test1 second memory limit per test: 256 megabytes inputstandard input outputstandard output You are given two integers 𝑎 and 𝑏. Print 𝑎+𝑏. Input The first line contains an integer 𝑡 (1≤𝑡≤104) — the number of test cases in the input. Then 𝑡 test cases follow. Each test case is given as a line of two integers 𝑎 and 𝑏 (−1000≤𝑎,𝑏≤1000). Output Print 𝑡 integers — the required numbers 𝑎+𝑏. Example input 4 1 5 314 15 -99 99 123 987 output 6 329 0 1110 */ #include <bits/stdc++.h> using namespace std; #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) int main() { FAST_INP; int t,a,b; cin >> t; while(t--){ // take two input values cin >> a >> b; // add them together cout << (a+b) << "\n"; } return 0; }
17.208333
113
0.650121
wingkwong
9f3c5f94ce2e321af0a8047f71a3a051c3091a70
68,205
cpp
C++
Yugo/src/Editor/Editor.cpp
bd93/Yugo
4448083b2968a889d2b8bf1c83d9ba11cb358aaf
[ "MIT" ]
null
null
null
Yugo/src/Editor/Editor.cpp
bd93/Yugo
4448083b2968a889d2b8bf1c83d9ba11cb358aaf
[ "MIT" ]
null
null
null
Yugo/src/Editor/Editor.cpp
bd93/Yugo
4448083b2968a889d2b8bf1c83d9ba11cb358aaf
[ "MIT" ]
null
null
null
#include "pch.h" #include "Editor.h" #include "Animation/Components.h" #include "Animation/Animation.h" #include "Scripting/Components.h" #include "Core/Time.h" #include "Core/ModelImporter.h" #include "Renderer/SpriteRenderer.h" //#include "GameUI/Widget.h" #include <ImGuizmo.h> #include <windows.h> #include <commdlg.h> #include <entt/core/type_info.hpp> namespace Yugo { // Play mode flag static bool s_PlayMode = false; // Show/hide Scene in editor static bool s_RenderScene = true; // Show/hide in-game UI in editor static bool s_RenderUI = false; // Show/hide bounding boxes static bool s_RenderBoundingBox = false; // ImGuizmo widget data static ImGuizmo::OPERATION s_CurrentGizmoOperation(ImGuizmo::TRANSLATE); static ImGuizmo::MODE s_CurrentGizmoMode(ImGuizmo::WORLD); static bool s_UseSnap = false; static float s_Snap[3] = { 1.f, 1.f, 1.f }; static float s_Bounds[] = { -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f }; static float s_BoundsSnap[] = { 0.1f, 0.1f, 0.1f }; static bool s_BoundSizing = false; static bool s_BoundSizingSnap = false; Editor::Editor() : m_MainWindow(uPtrCreate<Window>("Editor", 1200, 800)), m_GameWindow(uPtrCreate<Window>("Game", 1200, 800)), m_Scene(sPtrCreate<Scene>()), m_UserInterface(sPtrCreate<UserInterface>()), m_ScriptEngine(uPtrCreate<ScriptEngine>()), m_SelectedSceneEntity(entt::null) { m_SceneInfo.SceneName = "Default"; m_SceneInfo.SceneFilePath = "None"; /* By default initialize width and heigh to main window size. In the next frame it will be resized to Scene ImGui window in UpdateSceneViewport method. */ m_SceneInfo.SceneWidth = m_MainWindow->m_Width; m_SceneInfo.SceneHeight = m_MainWindow->m_Height; } /** * @brief Method to be called during application OnStart stage. * * This method initialize all necessary components. */ void Editor::OnStart() { m_MainWindow->OnStart(); UserInput::SetGLFWwindow(m_MainWindow->m_GLFWwindow); // Initialize ImGui IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows // Setup Dear ImGui style ImGui::StyleColorsDark(); // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. ImGuiStyle& style = ImGui::GetStyle(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { style.WindowRounding = 0.0f; style.Colors[ImGuiCol_WindowBg].w = 1.0f; } // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(m_MainWindow->m_GLFWwindow, true); ImGui_ImplOpenGL3_Init("#version 330"); // Initially create texture framebuffer with default size (1200 x 800) CreateFrameBuffer(m_SceneInfo.SceneWidth, m_SceneInfo.SceneHeight); m_Scene->OnStart(); //m_UserInterface->OnStart(); Dispatcher::Subscribe<MouseButtonPress>(this); Dispatcher::Subscribe<KeyboardKeyPress>(this); Dispatcher::Subscribe<ImportAssetEvent>(this); Dispatcher::Subscribe<MouseScroll>(this); Dispatcher::Subscribe<WindowResize>(this); } /** * @brief Method to be called during application OnRender stage. * * This method renders ImGui widgets. * Inside Scene window it renders Scene and UI. */ void Editor::OnRender() { // ImGui rendering initialisation ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGuiWindowFlags window_flags = 0; window_flags |= ImGuiWindowFlags_MenuBar; window_flags |= ImGuiWindowFlags_NoDocking; window_flags |= ImGuiWindowFlags_NoBackground; window_flags |= ImGuiWindowFlags_NoCollapse; window_flags |= ImGuiWindowFlags_NoResize; window_flags |= ImGuiWindowFlags_NoTitleBar; window_flags |= ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoNavFocus; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus; // OS specific window viewport ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->Pos); ImGui::SetNextWindowSize(viewport->Size); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("Dock Space", NULL, window_flags); ImGui::PopStyleVar(3); ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None); /* The order of showing widgets/windows is important! E.g. ShowImGuizmo method, which is called in ShowSceneWindow method, need to be in front of ShowInspectorWindow. The reason is because of model matrix update. Editor's OnUpdate method is called first and thus model matrix is updated with TransformComponent members (Position, Rotation, Scale). Then in ShowImGuizmo method model matrix is updated if user moves entity with imguizmo widget. Then in ShowInspectorWindow method model matrix is decomposed to TransformComponent members, so user can manualy change them in Inspector window. Just right after this model matrix is recomposed (updated) with TransformComponent members. */ ShowMenuBar(); ShowSceneWindow(); if (s_RenderScene) { ShowHierarchyWindow(m_Scene->m_Registry); ShowInspectorWindow(m_Scene->m_Registry); } else if (s_RenderUI) { //ShowHierarchyWindow(m_UserInterface->m_Registry); //ShowInspectorWindow(m_UserInterface->m_Registry); } ShowProjectWindow(); //ImGui::ShowDemoWindow(); // ImGui demo window with all possible widgets/features // Render Scene in Game window when editor is in play mode if (s_PlayMode) { Window::MakeContextCurrent(m_GameWindow->m_GLFWwindow); glEnable(GL_DEPTH_TEST); glClearColor(0.3f, 0.3f, 0.3f, 1.0f); // Color of game window background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_GameWindow->m_Scene->OnRender(); // Game window scene is a copy of Editor's scene m_GameWindow->m_UserInterface->OnRender(); //Window::PollEvents(); // temp! m_GameWindow->SwapBuffers(); glDisable(GL_DEPTH_TEST); Window::MakeContextCurrent(m_MainWindow->m_GLFWwindow); if (m_GameWindow->WindowShouldClose()) { s_PlayMode = false; m_ScriptEngine->OnStop(); m_GameWindow->OnShutdown(); UserInput::SetGLFWwindow(m_MainWindow->m_GLFWwindow); m_MainWindow->SetEventCallbacks(); m_GameWindow->RemoveEventCallbacks(); Window::s_CurrentActiveWindowName = m_MainWindow->GetWindowName(); } } // Render Scene in editor's Scene window m_FrameBuffer->Bind(); glEnable(GL_DEPTH_TEST); glClearColor(0.3f, 0.3f, 0.3f, 1.0f); // Color of framebuffer's texture inside scene imgui window glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (s_RenderScene) { m_Scene->OnRender(); if (s_RenderBoundingBox) { auto& camera = m_Scene->GetCamera(); auto view = m_Scene->m_Registry.view<MeshComponent, BoundBoxComponent, TransformComponent>(); for (auto entity : view) { auto& [aabb, transform] = view.get<BoundBoxComponent, TransformComponent>(entity); MeshRenderer::DrawAABB(aabb, transform, camera, ResourceManager::GetShader("quadShader")); //for (const auto& subAABB : aabb.SubAABBs) //{ // MeshRenderer::DrawAABB(subAABB, transform, ResourceManager::GetShader("quadShader")); //} } } glDisable(GL_DEPTH_TEST); } else if (s_RenderUI) { //m_UserInterface->OnRender(); } m_FrameBuffer->BlitMultisampled(m_SceneInfo.SceneWidth, m_SceneInfo.SceneHeight, m_FrameBuffer->GetId(), m_IntermediateFrameBuffer->GetId()); m_FrameBuffer->Unbind(); // Render ImGui ImGuiIO& io = ImGui::GetIO(); int glfwWindowWidth; int glfwWindowHeight; glfwGetWindowSize(m_MainWindow->m_GLFWwindow, &glfwWindowWidth, &glfwWindowHeight); io.DisplaySize = ImVec2((float)glfwWindowWidth, (float)glfwWindowHeight); ImGui::Render(); /* Clear default framebuffer color and depth buffers which are attchaed to it; This is needed because scene is being rendered on custom framebuffer's attached texture and ImGUI is being renderd on default framebuffer */ glClearColor(0.2f, 0.2f, 0.2f, 1.0f); // Color of ImGui background (Main window) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { GLFWwindow* backup_current_context = glfwGetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); glfwMakeContextCurrent(backup_current_context); } } void Editor::OnUpdate(TimeStep ts) { if (s_PlayMode) { // The order of update is important! If scene is updated first, then script can't execute entity movement //Window::MakeContextCurrent(m_GameWindow->m_GLFWwindow); m_ScriptEngine->OnUpdate(ts); m_GameWindow->m_Scene->OnUpdate(ts); m_GameWindow->m_UserInterface->OnUpdate(ts); //Window::MakeContextCurrent(m_MainWindow->m_GLFWwindow); } else { if (s_RenderScene) m_Scene->OnUpdate(ts); else if (s_RenderUI) m_UserInterface->OnUpdate(ts); auto view = m_Scene->m_Registry.view<MeshComponent, TransformComponent, AnimationComponent>(); for (auto entity : view) { auto& [mesh, animation] = view.get<MeshComponent, AnimationComponent>(entity); if (animation.IsAnimationRunning) Animation::RunAnimation(mesh, animation); } if (UserInput::IsKeyboardKeyPressed(KEY_LEFT_CONTROL) && UserInput::IsMouseButtonPressed(MOUSE_BUTTON_LEFT) && m_IsSceneWindowHovered) { auto view = m_Scene->m_Registry.view<CameraComponent, TransformComponent, EntityTagComponent>(); for (auto entity : view) { auto& [camera, transform, tag] = view.get<CameraComponent, TransformComponent, EntityTagComponent>(entity); if (tag.Name == "Main Camera") Camera::RotateAroundPivot(transform, camera); } } } } void Editor::OnEvent(const Event& event) { if (s_PlayMode) { //Window::MakeContextCurrent(m_GameWindow->m_GLFWwindow); m_ScriptEngine->OnEvent(event); if (event.GetEventType() == EventType::WindowResize) { const auto& windowResize = static_cast<const WindowResize&>(event); int screenWidth = windowResize.GetWidth(); int screenHeight = windowResize.GetHeight(); m_GameWindow->m_UserInterface->m_FramebufferWidth = screenWidth; m_GameWindow->m_UserInterface->m_FramebufferHeight = screenHeight; auto& camera = m_GameWindow->m_Scene->GetCamera(); Camera::UpdateProjectionMatrix(camera, screenWidth, screenHeight); } //Window::MakeContextCurrent(m_MainWindow->m_GLFWwindow); } else { // Cast mouse ray, Select entity, reset mouse position offset for camera if (event.GetEventType() == EventType::MouseButtonPress) { const auto& mouseButtonPress = static_cast<const MouseButtonPress&>(event); if (mouseButtonPress.GetButtonCode() == MOUSE_BUTTON_LEFT) { if (!ImGuizmo::IsOver(s_CurrentGizmoOperation) && m_IsSceneWindowHovered) { SelectMesh(); Camera::ResetMousePositionOffset(m_Scene->GetCamera()); } } } // Import asset event is invoked when user drag and drop asset to scene imgui window if (event.GetEventType() == EventType::ImportAsset) { auto& camera = m_Scene->GetCamera(); MouseRay::CalculateRayOrigin(camera, m_MouseInfo.MousePosX, m_MouseInfo.MousePosY, m_SceneInfo.SceneWidth, m_SceneInfo.SceneHeight); const auto& importAssetEvent = static_cast<const ImportAssetEvent&>(event); const auto& importAssetFilePath = importAssetEvent.GetAssetFilePath(); ImportAsset(importAssetFilePath); } // Camera zoom in / zoom out if (event.GetEventType() == EventType::MouseScroll) { if (m_IsSceneWindowHovered) { const auto& mouseScroll = static_cast<const MouseScroll&>(event); auto& camera = m_Scene->GetCamera(); Camera::Scroll(mouseScroll.GetOffsetY(), camera); } } } } void Editor::OnShutdown() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); //m_ScriptEngine->OnShutdown(); m_Scene->OnShutdown(); m_MainWindow->OnShutdown(); Window::TerminateGLFW(); } void Editor::ShowMenuBar() { if (ImGui::BeginMenuBar()) { static bool saveSuccess = false; static bool saveError = false; if (saveSuccess) { ImGui::OpenPopup("Success!"); if (ImGui::BeginPopupModal("Success!")) { ImGui::Text("This scene has been saved"); ImGui::Separator(); if (ImGui::Button("OK", ImVec2(120, 0))) { saveSuccess = false; ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } if (saveError) { ImGui::OpenPopup("Error!"); if (ImGui::BeginPopupModal("Error!")) { ImGui::Text("First click Save As..."); ImGui::Separator(); if (ImGui::Button("OK", ImVec2(120, 0))) { saveError = false; ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("New Scene")) { m_Scene->m_Registry.clear(); m_SceneInfo.SceneName = "Default"; m_SceneInfo.SceneFilePath = "None"; } if (ImGui::MenuItem("Load Scene")) { std::string filePath; ShowFileDialogBox("Open", filePath); m_Scene->LoadScene(filePath); m_SceneInfo.SceneFilePath = filePath; std::size_t foundBegin = filePath.find_last_of("\\"); std::size_t foundEnd = filePath.find_last_of("."); std::string fileName = filePath.substr(foundBegin + 1, foundEnd - foundBegin - 1); m_SceneInfo.SceneName = fileName; } ImGui::Separator(); if (ImGui::MenuItem("Save")) { const auto& filePath = m_SceneInfo.SceneFilePath; if (filePath == "None") { saveError = true; } else { m_Scene->SaveScene(filePath); saveSuccess = true; } } if (ImGui::MenuItem("Save As...")) { std::string filePath; ShowFileDialogBox("Save As", filePath); m_Scene->SaveScene(filePath); m_SceneInfo.SceneFilePath = filePath; std::size_t foundBegin = filePath.find_last_of("\\"); std::size_t foundEnd = filePath.find_last_of("."); std::string fileName = filePath.substr(foundBegin + 1, foundEnd - foundBegin - 1); m_SceneInfo.SceneName = fileName; } ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::End(); } void Editor::ShowProjectWindow() { using TraverseFun = std::function<void(const std::string&)>; ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver); if (ImGui::Begin("Project")) { static std::string currentPath; // left ImGui::BeginChild("left pane", ImVec2(250, 0), true); static size_t selection = 0; int rootId = 1; static size_t nodeClicked = 0; ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen; if (selection == rootId) { nodeFlags |= ImGuiTreeNodeFlags_Selected; currentPath = FileSystem::GetSolutionFolderPath() + "Main\\src\\Assets"; } std::string pathToFolder = FileSystem::GetSolutionFolderPath() + "Main\\src\\Assets"; auto folderTreeMap = FileSystem::HashFolderTree(pathToFolder); bool rootNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)rootId, nodeFlags, "Assets"); if (ImGui::IsItemClicked()) { nodeClicked = rootId; currentPath = pathToFolder; } if (ImGui::IsItemClicked(1)) ImGui::OpenPopup(pathToFolder.c_str()); ShowFolderMenuPopup(pathToFolder); TraverseFun TraverseFolderTree = [&](const std::string& path) { for (const auto& entry : FileSystem::DirIter(path)) { if (entry.is_directory()) { std::string folderName = entry.path().filename().string(); std::string pathToFolder = path + "\\" + folderName; ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; if (selection == folderTreeMap[folderName]) nodeFlags |= ImGuiTreeNodeFlags_Selected; bool nodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)folderTreeMap[folderName], nodeFlags, "%s", folderName.c_str()); if (ImGui::IsItemClicked()) { nodeClicked = folderTreeMap[folderName]; currentPath = pathToFolder; } if (ImGui::IsItemClicked(1)) ImGui::OpenPopup(pathToFolder.c_str()); ShowFolderMenuPopup(pathToFolder); if (nodeOpen) { TraverseFolderTree(pathToFolder); ImGui::TreePop(); } } else { std::string fileName = entry.path().filename().string(); std::string pathToFile = path + "\\" + fileName; ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; if (selection == folderTreeMap[fileName]) nodeFlags |= ImGuiTreeNodeFlags_Selected; ImGui::TreeNodeEx((void*)(intptr_t)folderTreeMap[fileName], nodeFlags, "%s", fileName.c_str()); if (ImGui::IsItemClicked()) { nodeClicked = folderTreeMap[fileName]; } if (ImGui::IsItemClicked(1)) { ImGui::OpenPopup(pathToFile.c_str()); } if (ImGui::BeginPopup(pathToFile.c_str())) { ImGui::Text("Are you sure you want to delete this file?"); if (ImGui::Button("OK")) { FileSystem::Delete(pathToFile); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } } }; if (rootNodeOpen) { ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()); // Increase spacing to differentiate leaves from expanded contents. TraverseFolderTree(FileSystem::GetSolutionFolderPath() + "Main\\src\\Assets"); if (nodeClicked != 0) { selection = nodeClicked; } ImGui::PopStyleVar(); ImGui::TreePop(); } ImGui::EndChild(); ImGui::SameLine(); // right ImGui::BeginGroup(); ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); ImGui::Text(currentPath.c_str()); ImGui::Separator(); if (currentPath != "") { if (ImGui::Button("Add Asset")) { std::string filePath; ShowFileDialogBox("Open", filePath); std::string fileName = FileSystem::FilePath(filePath).filename().string(); FileSystem::CopyFileTo(filePath, currentPath + "\\" + fileName); } } ImGui::Text("Drag and drop asset:"); ImGui::Dummy(ImVec2(0.0f, 10.0f)); // Padding from top line separator int i = 0; if (currentPath != "") { ImGui::Columns(7); for (auto& entry : FileSystem::DirIter(currentPath)) { if (!entry.is_directory()) { std::string fileName = entry.path().filename().string(); ImGui::PushID(i++); ImGui::Button(fileName.c_str(), ImVec2(-FLT_MIN, 0.0f)); ImGui::NextColumn(); if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { ImGui::SetDragDropPayload("Import Asset", (currentPath + "\\" + fileName).c_str(), (currentPath + "\\" + fileName).size() + 1); ImGui::Text("Drag and drop %s", fileName.c_str()); ImGui::EndDragDropSource(); } ImGui::PopID(); } } } ImGui::EndChild(); ImGui::EndGroup(); } ImGui::End(); } void Editor::ShowInspectorWindow(entt::registry& registry) { ImGui::Begin("Inspector"); static int radioOption = 0; static int pastRadiooption = radioOption; ImGui::RadioButton("Show Scene", &radioOption, 0); ImGui::SameLine(); ImGui::RadioButton("Show UI", &radioOption, 1); if (radioOption == 0) { s_RenderScene = true; s_RenderUI = false; } else if (radioOption == 1) { s_RenderScene = false; s_RenderUI = true; } if (pastRadiooption != radioOption) { m_SelectedSceneEntity = entt::null; s_CurrentGizmoOperation = ImGuizmo::BOUNDS; pastRadiooption = radioOption; } ImGui::Separator(); const char* components[] = { "MeshComponent", "SpriteComponent", "AnimationComponent", "ScriptComponent" }; static bool toggles[] = { false, false, false, false }; // For toggle widget if (m_SelectedSceneEntity != entt::null) { for (int i = 0; i < IM_ARRAYSIZE(components); i++) { toggles[i] = false; // Reset previous state if (components[i] == "MeshComponent" && registry.has<MeshComponent>(m_SelectedSceneEntity)) toggles[i] = true; if (components[i] == "SpriteComponent" && registry.has<SpriteComponent>(m_SelectedSceneEntity)) toggles[i] = true; if (components[i] == "AnimationComponent" && registry.has<AnimationComponent>(m_SelectedSceneEntity)) toggles[i] = true; if (components[i] == "ScriptComponent" && registry.has<ScriptComponent>(m_SelectedSceneEntity)) toggles[i] = true; } // Always show TransformComponent auto& transform = registry.get<TransformComponent>(m_SelectedSceneEntity); ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(transform.ModelMatrix), glm::value_ptr(transform.Position), glm::value_ptr(transform.Rotation), glm::value_ptr(transform.Scale)); ImGui::InputFloat3("Translate", glm::value_ptr(transform.Position)); ImGui::InputFloat3("Rotate", glm::value_ptr(transform.Rotation)); ImGui::InputFloat3("Scale", glm::value_ptr(transform.Scale)); ImGuizmo::RecomposeMatrixFromComponents(glm::value_ptr(transform.Position), glm::value_ptr(transform.Rotation), glm::value_ptr(transform.Scale), glm::value_ptr(transform.ModelMatrix)); ImGui::NewLine(); // Show padding options for UI canvas widget //if (registry.has<CanvasWidgetComponent>(m_SelectedSceneEntity)) //{ // //auto& relationship = registry.get<RelationshipComponent>(m_SelectedSceneEntity); // static float padding[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; // left, right, top, bottom // ImGui::InputFloat4("Padding", padding); // static int dimensions[2] = { 1, 1 }; // ImGui::InputInt2("Rows x Columns", dimensions); // static float cellWidgetSize[2] = { 50.0f, 50.0f }; // ImGui::InputFloat2("Cell Widget Size", cellWidgetSize); // if (ImGui::Button("Create")) // Create canvas matrix widget // CreateCanvasMatrixWidget(dimensions, padding, cellWidgetSize, m_SelectedSceneEntity); //} //// Show text input for widget's text //if (registry.has<TextWidgetComponent>(m_SelectedSceneEntity)) //{ // static entt::entity previousEntity; // static char buf[64] = ""; // auto& text = registry.get<TextWidgetComponent>(m_SelectedSceneEntity); // if (previousEntity != m_SelectedSceneEntity) // memset(buf, 0, 64 * sizeof(char)); // if (ImGui::InputText("Text", buf, 64)) // text.Text = std::string(buf); // previousEntity = m_SelectedSceneEntity; // ImGui::NewLine(); //} if (ImGui::RadioButton("Local", s_CurrentGizmoMode == ImGuizmo::LOCAL)) s_CurrentGizmoMode = ImGuizmo::LOCAL; ImGui::SameLine(); if (ImGui::RadioButton("World", s_CurrentGizmoMode == ImGuizmo::WORLD)) s_CurrentGizmoMode = ImGuizmo::WORLD; ImGui::NewLine(); if (ImGui::IsKeyPressed((int)KEY_S)) s_UseSnap = !s_UseSnap; ImGui::PushID(0); ImGui::Checkbox("", &s_UseSnap); ImGui::PopID(); ImGui::SameLine(); switch (s_CurrentGizmoOperation) { case ImGuizmo::TRANSLATE: ImGui::InputFloat3("Snap", &s_Snap[0]); break; case ImGuizmo::ROTATE: ImGui::InputFloat("Angle Snap", &s_Snap[1]); break; case ImGuizmo::SCALE: ImGui::InputFloat("Scale Snap", &s_Snap[2]); break; } ImGui::Checkbox("Bound Sizing", &s_BoundSizing); if (s_BoundSizing) { ImGui::PushID(1); ImGui::Checkbox("", &s_BoundSizingSnap); ImGui::SameLine(); ImGui::InputFloat3("Snap", s_BoundsSnap); ImGui::PopID(); } ImGui::Separator(); for (int i = 0; i < IM_ARRAYSIZE(components); ++i) { if (toggles[i]) { if (components[i] == "MeshComponent") { ImGui::Checkbox("Show Bounding Box", &s_RenderBoundingBox); ImGui::Separator(); } if (components[i] == "AnimationComponent") { auto view = registry.view<MeshComponent, AnimationComponent>(); for (auto entity : view) { auto& [mesh, animation] = view.get<MeshComponent, AnimationComponent>(entity); if (entity == m_SelectedSceneEntity) { static std::string firstAnimationName = "None"; // Keep track of selected entity's first animation name in order to show it in Combo preview static std::string currentAnimationName = animation.AnimationNameVec[0]; if (firstAnimationName != animation.AnimationNameVec[0]) { firstAnimationName = animation.AnimationNameVec[0]; currentAnimationName = firstAnimationName; } if (ImGui::BeginCombo("Animation Names", currentAnimationName.c_str())) // The second parameter is the label previewed before opening the combo. { for (uint32_t i = 0; i < animation.AnimationNameVec.size(); ++i) { bool isSelected = (currentAnimationName == animation.AnimationNameVec[i]); if (ImGui::Selectable(animation.AnimationNameVec[i].c_str(), isSelected)) currentAnimationName = animation.AnimationNameVec[i]; if (isSelected) ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo } ImGui::EndCombo(); } if (ImGui::Button("Start Animation")) { animation.RunningAnimationName = currentAnimationName; animation.IsAnimationRunning = true; animation.AnimationMap[currentAnimationName].AnimationStartingTime = Time::CurrentRealTime(); } ImGui::SameLine(); if (ImGui::Button("Stop Animation")) { animation.IsAnimationRunning = false; animation.RunningAnimationName = "None"; } } } ImGui::Separator(); } if (components[i] == "ScriptComponent") { static std::string scriptFilePath = "Script: None"; static entt::entity previousEntity = m_SelectedSceneEntity; if (previousEntity != m_SelectedSceneEntity) { if (registry.has<ScriptComponent>(m_SelectedSceneEntity)) { auto& scriptComponent = registry.get<ScriptComponent>(m_SelectedSceneEntity); scriptFilePath = scriptComponent.ScriptFilePath; } else { scriptFilePath = "Script: None"; } previousEntity = m_SelectedSceneEntity; } ImGui::Text(scriptFilePath.c_str()); if (ImGui::Button("Select Script")) ShowFileDialogBox("Open", scriptFilePath); ImGui::SameLine(); if (ImGui::Button("Attach Script")) { auto& scriptComponent = registry.get<ScriptComponent>(m_SelectedSceneEntity); auto& entityTagComponent = registry.get<EntityTagComponent>(m_SelectedSceneEntity); scriptComponent.ScriptFilePath = scriptFilePath; //Entity entity(m_SelectedSceneEntity, entityTagComponent.Name, m_Scene.get()); //m_ScriptEngine->AttachScript(scriptFilePath, entity); m_ScriptEngine->AttachScript(scriptFilePath, m_SelectedSceneEntity); } ImGui::Separator(); } if (components[i] == "SpriteComponent") { auto view = registry.view<SpriteComponent>(); if (m_SelectedSceneEntity != entt::null) { auto& sprite = registry.get<SpriteComponent>(m_SelectedSceneEntity); auto& texture = sprite.Texture; ImGui::Text("Texture:"); ImGui::Image((void*)texture.GetId(), ImVec2(80.0f, 80.0f), ImVec2(0, 0), ImVec2(1, 1)); if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Import Asset")) { char* payloadData = (char*)payload->Data; std::string assetFilePath(payloadData); if (ResourceManager::HasTexture(assetFilePath)) { texture = ResourceManager::GetTexture(assetFilePath); } else { ResourceManager::AddTexture(assetFilePath, Texture(assetFilePath)); texture = ResourceManager::GetTexture(assetFilePath); } sprite.HasTexture = true; } ImGui::EndDragDropTarget(); } ImGui::Separator(); ImGui::Text("Color:"); static ImVec4 color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); static ImVec4 ref_color_v(1.0f, 1.0f, 1.0f, 1.0f); ImGuiColorEditFlags flags = ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaBar | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHex; if (ImGui::ColorPicker4("My Color", (float*)&color, flags, &ref_color_v.x)) { //if (registry.has<TextWidgetComponent>(m_SelectedSceneEntity)) //{ // auto& text = registry.get<TextWidgetComponent>(m_SelectedSceneEntity); // text.Color = glm::vec4(color.x, color.y, color.z, color.w); //} //else //{ // sprite.Color = glm::vec4(color.x, color.y, color.z, color.w); //} } ImGui::Separator(); } } } } if (ImGui::Button("Add Component")) ImGui::OpenPopup("addComponentPopup"); ImGui::SameLine(); if (ImGui::BeginPopup("addComponentPopup")) { for (int i = 0; i < IM_ARRAYSIZE(components); i++) { if (ImGui::MenuItem(components[i], "", &toggles[i])) { if (components[i] == "MeshComponent") { if (toggles[i]) { auto& entityTag = registry.get<EntityTagComponent>(m_SelectedSceneEntity); auto& [loadedMesh, loadedAnimation] = ModelImporter::LoadMeshFile(entityTag.AssetFilePath); auto& mesh = registry.emplace<MeshComponent>(m_SelectedSceneEntity, *loadedMesh); MeshRenderer::Submit(mesh); } else { registry.remove<MeshComponent>(m_SelectedSceneEntity); } } if (components[i] == "SpriteComponent") { if (toggles[i]) { auto& sprite = registry.emplace<SpriteComponent>(m_SelectedSceneEntity); SpriteRenderer::Submit(sprite); } else { registry.remove<SpriteComponent>(m_SelectedSceneEntity); } } if (components[i] == "AnimationComponent") { if (toggles[i]) registry.emplace<AnimationComponent>(m_SelectedSceneEntity); else registry.remove<AnimationComponent>(m_SelectedSceneEntity); } if (components[i] == "ScriptComponent") { if (toggles[i]) { registry.emplace<ScriptComponent>(m_SelectedSceneEntity); } else { registry.remove<ScriptComponent>(m_SelectedSceneEntity); } } } } ImGui::EndPopup(); } } ImGui::End(); } void Editor::ShowHierarchyWindow(entt::registry& registry) { if (ImGui::Begin("Hierarchy", NULL)) { using TraverseFun = std::function<void(entt::entity)>; static uint32_t selection = 0; uint32_t rootId = 1; static uint32_t nodeClicked = 0; ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen; if (selection == rootId) nodeFlags |= ImGuiTreeNodeFlags_Selected; const char* sceneName; sceneName = m_SceneInfo.SceneName.c_str(); bool rootNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)rootId, nodeFlags, sceneName); if (ImGui::IsItemClicked()) { nodeClicked = rootId; m_SelectedSceneEntity = entt::null; } if (ImGui::IsItemClicked(1)) ImGui::OpenPopup(std::to_string(rootId).c_str()); ShowHierarchyMenuPopup(entt::null, registry); auto view = registry.view<RelationshipComponent, EntityTagComponent>(); TraverseFun traverse = [&](entt::entity entity) { auto& tag = view.get<EntityTagComponent>(entity); /* Bug is triggered in the following situation: If I get relationship by reference, then there shouldn't be any new entity added to the registry. If it isn't the case, then relationship reference has trash values for parent entity as well as number of children value; In the line "ShowHierarchyMenuPopup(entity);" a new entity is added, thus registry is changed; Because of that I return relationship by value (anyway I don't have to modify relationship in this method); */ auto relationship = view.get<RelationshipComponent>(entity); if (relationship.NumOfChildren == 0) // Leaf node { ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; const char* entityTag; entityTag = tag.Name.c_str(); uint32_t entityId = rootId + (uint32_t)entity + 1; if (selection == entityId) nodeFlags |= ImGuiTreeNodeFlags_Selected; ImGui::TreeNodeEx((void*)(uintptr_t)entityId, nodeFlags, entityTag); if (ImGui::IsItemClicked()) { m_SelectedSceneEntity = entity; if (s_CurrentGizmoOperation == ImGuizmo::BOUNDS) s_CurrentGizmoOperation = ImGuizmo::TRANSLATE; } if (ImGui::IsItemClicked(1)) ImGui::OpenPopup(std::to_string(entityId).c_str()); ShowHierarchyMenuPopup(entity, registry); } else { ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen; uint32_t entityId = rootId + (uint32_t)entity + 1; if (selection == entityId) nodeFlags |= ImGuiTreeNodeFlags_Selected; const char* entityTag; entityTag = tag.Name.c_str(); bool rootNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)entityId, nodeFlags, entityTag); if (ImGui::IsItemClicked()) { m_SelectedSceneEntity = entity; if (s_CurrentGizmoOperation == ImGuizmo::BOUNDS) s_CurrentGizmoOperation = ImGuizmo::TRANSLATE; } if (ImGui::IsItemClicked(1)) ImGui::OpenPopup(std::to_string(entityId).c_str()); ShowHierarchyMenuPopup(entity, registry); if (rootNodeOpen) { auto relationship = view.get<RelationshipComponent>(entity); for (auto child : relationship.Children) traverse(child); ImGui::TreePop(); } } }; if (rootNodeOpen) { ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()); // Increase spacing to differentiate leaves from expanded contents. auto view = registry.view<RelationshipComponent, EntityTagComponent, TransformComponent>(); for (auto entity : view) { auto& relationship = view.get<RelationshipComponent>(entity); if (relationship.Parent == entt::null) // Recursive traverse only if entity's parent is root node (entt::null) traverse(entity); } // Nodes will be selected either by clicking on it or by clicking on model in scene if (m_SelectedSceneEntity != entt::null) nodeClicked = (uint32_t)m_SelectedSceneEntity + 2; // 0 and 1 are already reserved => Id = 0 for entt::null, Id = 1 for root node (scene name) else if (nodeClicked != rootId) nodeClicked = 0; selection = nodeClicked; ImGui::PopStyleVar(); ImGui::TreePop(); } } ImGui::End(); } void Editor::ShowSceneWindow() { ImGui::Begin("Scene", NULL); m_IsSceneWindowFocused = ImGui::IsWindowFocused(); /* Keep track of Scene Window's width and height; If scene window is resized, then Framebuffer (where scene is rendered) needs to be resized too */ float sceneWindowWidth = ImGui::GetWindowContentRegionMax().x - ImGui::GetWindowContentRegionMin().x; float sceneWindowHeight = ImGui::GetWindowContentRegionMax().y - ImGui::GetWindowContentRegionMin().y; UpdateSceneViewport(sceneWindowWidth, sceneWindowHeight); // Update Framebuffer's size and viewport // xPadding and yPadding are distances between scene framebuffer texture and scene ImGui window; float xPadding = (ImGui::GetWindowSize().x - m_SceneInfo.SceneWidth) * 0.5f; float yPadding = (ImGui::GetWindowSize().y + ImGui::GetItemRectSize().y - m_SceneInfo.SceneHeight) * 0.5f; ImGui::SetCursorPos(ImVec2(xPadding, yPadding)); //ImGui::Image((void*)m_Texture->GetId(), ImVec2((float)m_SceneInfo.SceneWidth, (float)m_SceneInfo.SceneHeight), ImVec2(0, 1), ImVec2(1, 0)); ImGui::Image((void*)m_IntermediateTexture->GetId(), ImVec2((float)m_SceneInfo.SceneWidth, (float)m_SceneInfo.SceneHeight), ImVec2(0, 1), ImVec2(1, 0)); // temp if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Import Asset")) { char* payloadData = (char*)payload->Data; std::string strPayloadData(payloadData); ImportAssetEvent importAssetEvent(strPayloadData); Dispatcher::Publish(importAssetEvent); } ImGui::EndDragDropTarget(); } float scenePosMinX = ImGui::GetWindowPos().x + xPadding; float scenePosMinY = ImGui::GetWindowPos().y + yPadding; float scenePosMaxX = scenePosMinX + m_SceneInfo.SceneWidth; float scenePosMaxY = scenePosMinY + m_SceneInfo.SceneHeight; ImVec2 scenePosMin = ImVec2(scenePosMinX, scenePosMinY); ImVec2 scenePosMax = ImVec2(scenePosMaxX, scenePosMaxY); // Relative to Scene Framebuffer m_SceneInfo.ScenePosMin = glm::vec2(scenePosMinX, scenePosMinY); m_SceneInfo.ScenePosMax = glm::vec2(scenePosMaxX, scenePosMaxY); // Relative to Scene Framebuffer m_MouseInfo.MousePosX = ImGui::GetMousePos().x - ImGui::GetWindowPos().x - xPadding; m_MouseInfo.MousePosY = ImGui::GetMousePos().y - ImGui::GetWindowPos().y - yPadding; if (ImGui::IsMouseHoveringRect(scenePosMin, scenePosMax)) m_IsSceneWindowHovered = true; else m_IsSceneWindowHovered = false; if (m_SelectedSceneEntity != entt::null) { if (s_RenderScene) { auto& transform = m_Scene->m_Registry.get<TransformComponent>(m_SelectedSceneEntity); auto& camera = m_Scene->GetCamera(); ShowImGuizmoWidget(transform, camera.Projection, camera.View); } else if (s_RenderUI) { //auto& transform = m_UserInterface->m_Registry.get<TransformComponent>(m_SelectedSceneEntity); //auto& camera = m_UserInterface->GetCamera(); // //ShowImGuizmoWidget(transform, camera.Projection, glm::mat4(1.0f)); } } ImGui::End(); ImGui::Begin("Scene Commands"); if (ImGui::Button("Play Scene")) { s_PlayMode = true; if (m_SelectedSceneEntity != entt::null) m_SelectedSceneEntity = entt::null; CreateGameWindow(); m_ScriptEngine->OnStart(m_GameWindow->m_Scene.get(), m_GameWindow->m_UserInterface.get(), m_GameWindow.get()); } ImGui::SameLine(); if (ImGui::Button("Stop Scene")) { s_PlayMode = false; m_ScriptEngine->OnStop(); m_GameWindow->OnShutdown(); UserInput::SetGLFWwindow(m_MainWindow->m_GLFWwindow); } ImGui::End(); } void Editor::ShowImGuizmoWidget(TransformComponent& transform, const glm::mat4& projectionMatrix, const glm::mat4& viewMatrix) { ImGuizmo::BeginFrame(); ImGuizmo::SetOrthographic(true); if (ImGui::IsKeyDown((int)KEY_LEFT_CONTROL) && ImGui::IsKeyPressed((int)KEY_T)) s_CurrentGizmoOperation = ImGuizmo::TRANSLATE; if (ImGui::IsKeyDown((int)KEY_LEFT_CONTROL) && ImGui::IsKeyPressed((int)KEY_R)) s_CurrentGizmoOperation = ImGuizmo::ROTATE; if (ImGui::IsKeyDown((int)KEY_LEFT_CONTROL) && ImGui::IsKeyPressed((int)KEY_Y)) s_CurrentGizmoOperation = ImGuizmo::SCALE; ImGuizmo::SetDrawlist(); ImGuizmo::SetRect( m_SceneInfo.ScenePosMin.x, m_SceneInfo.ScenePosMin.y, (float)m_SceneInfo.SceneWidth, (float)m_SceneInfo.SceneHeight ); ImGuizmo::Manipulate( glm::value_ptr(viewMatrix), glm::value_ptr(projectionMatrix), s_CurrentGizmoOperation, s_CurrentGizmoMode, glm::value_ptr(transform.ModelMatrix), NULL, s_UseSnap ? &s_Snap[0] : NULL, s_BoundSizing ? s_Bounds : NULL, s_BoundSizingSnap ? s_BoundsSnap : NULL ); // Update delta position and matrix components (position, rotation, scale) after guizmo manipulation float position[3]; float rotation[3]; float scale[3]; ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(transform.ModelMatrix), position, rotation, scale); auto deltaPosition = glm::vec3(position[0] - transform.Position.x, position[1] - transform.Position.y, position[2] - transform.Position.z); // Capture the amount by which this widget has been moved // Update delta position for all children if (s_RenderScene) { auto view = m_Scene->m_Registry.view<RelationshipComponent, TransformComponent>(); using TraverseFun = std::function<void(entt::entity)>; TraverseFun traverse = [&](entt::entity entity) { auto& relationship = view.get<RelationshipComponent>(entity); for (auto child : relationship.Children) { auto& childTransform = view.get<TransformComponent>(child); //childTransform.DeltaPosition = transform.DeltaPosition; childTransform.DeltaPosition = deltaPosition; } for (auto child : relationship.Children) { traverse(child); } }; traverse(m_SelectedSceneEntity); } else if (s_RenderUI) { //auto view = m_UserInterface->m_Registry.view<RelationshipComponent, TransformComponent>(); //using TraverseFun = std::function<void(entt::entity)>; //TraverseFun traverse = [&](entt::entity entity) { // auto& relationship = view.get<RelationshipComponent>(entity); // for (auto child : relationship.Children) // { // auto& childTransform = view.get<TransformComponent>(child); // //childTransform.DeltaPosition = transform.DeltaPosition; // childTransform.DeltaPosition = deltaPosition; // } // for (auto child : relationship.Children) // { // traverse(child); // } //}; //traverse(m_SelectedSceneEntity); } } void Editor::ShowFileDialogBox(const std::string& option, std::string& fullPath) { OPENFILENAMEA ofn; // common dialog box structure char filePath[260]; // buffer for file path HWND hwnd; // owner window HANDLE hf; // file handle // Initialize OPENFILENAMEA memset(&ofn, 0, sizeof(ofn)); memset(&hwnd, 0, sizeof(hwnd)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hwnd; ofn.lpstrFile = filePath; /* Set lpstrFile[0] to '\0' so that GetOpenFileName does not use the contents of szFile to initialize itself. */ ofn.lpstrFile[0] = '\0'; if (option == "Save As") { ofn.nMaxFile = sizeof(filePath); ofn.lpstrFilter = "*.json\0"; } ofn.nMaxFile = sizeof(filePath); ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if (option == "Save As") { // Display the Save As dialog box. if (GetSaveFileNameA(&ofn)) { std::string strFilePath(ofn.lpstrFile); std::string strFileExtension(ofn.lpstrFilter); //std::string strFileName = FileSystem::FilePath(strFilePath + strFileExtension.substr(1)).filename().string(); fullPath = strFilePath + strFileExtension.substr(1); } } if (option == "Open") { // Display the Open file dialog box. if (GetOpenFileNameA(&ofn)) { std::string strFilePath(ofn.lpstrFile); //std::string strFileName = FileSystem::FilePath(strFilePath).filename().string(); fullPath = strFilePath; } } } void Editor::ShowFolderMenuPopup(const std::string& folderPath) { static char newFolderName[32] = ""; std::string menuAction = ""; if (ImGui::BeginPopup(folderPath.c_str())) { if (ImGui::MenuItem("New")) { menuAction = "New"; } if (ImGui::MenuItem("Delete")) { menuAction = "Delete"; } if (ImGui::MenuItem("Cancel")) { menuAction = "Cancel"; } ImGui::EndPopup(); } ImGui::PushID(folderPath.c_str()); if (menuAction == "New") { ImGui::OpenPopup("New"); } if (menuAction == "Delete") { ImGui::OpenPopup("Delete"); } if (menuAction == "Cancel") {} if (ImGui::BeginPopup("New")) { ImGui::Text("Enter new folder name:"); ImGui::InputText("##folderName", newFolderName, IM_ARRAYSIZE(newFolderName)); if (ImGui::Button("OK")) { FileSystem::CreateNewFolder(folderPath + "\\" + newFolderName); memset(newFolderName, 0, 32 * sizeof(newFolderName[0])); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } if (ImGui::BeginPopup("Delete")) { ImGui::Text("Are you sure you want to delete this folder?"); ImGui::MenuItem("***before deleting click arrow to close folder***", NULL, false, false); if (ImGui::Button("OK")) { FileSystem::Delete(folderPath); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } ImGui::PopID(); } void Editor::ShowHierarchyMenuPopup(entt::entity node, entt::registry& registry) { std::string stringNodeId; bool isSceneRootNode = false; if (node == entt::null) { isSceneRootNode = true; stringNodeId = std::to_string(1); } else { stringNodeId = std::to_string((uint32_t)node + 2); } static char newUiWidgetName[32] = ""; static char newSpriteName[32] = ""; std::string menuAction = ""; if (ImGui::BeginPopup(stringNodeId.c_str())) { if (ImGui::BeginMenu("New")) { //if (ImGui::MenuItem("Canvas")) CreateWidget("Canvas", node); //if (ImGui::MenuItem("Button")) CreateWidget("Button", node); //if (ImGui::MenuItem("Text")) CreateWidget("Text", node); if (ImGui::MenuItem("Entity")) { auto newEntity = m_Scene->CreateEntity(); auto& tag = newEntity.AddComponent<EntityTagComponent>(); tag.Name = "Entity" + std::to_string(static_cast<int>(newEntity.GetEnttEntity())); auto& transform = newEntity.AddComponent<TransformComponent>(); auto& relationship = newEntity.AddComponent<RelationshipComponent>(); relationship.Parent = entt::null; } ImGui::EndMenu(); } if (!isSceneRootNode && ImGui::MenuItem("Rename")) { menuAction = "Rename"; } if (!isSceneRootNode && ImGui::MenuItem("Copy")) { menuAction = "Copy"; } if (!isSceneRootNode && ImGui::MenuItem("Delete")) { menuAction = "Delete"; } if (ImGui::MenuItem("Cancel")) { menuAction = "Cancel"; } ImGui::EndPopup(); } ImGui::PushID(stringNodeId.c_str()); if (menuAction == "Sprite") { ImGui::OpenPopup("Sprite"); } if (menuAction == "Rename") { ImGui::OpenPopup("Rename"); } if (menuAction == "Copy") { CreateCopyEntity(node); } if (menuAction == "Delete") { ImGui::OpenPopup("Delete"); } if (menuAction == "Cancel") {} if (ImGui::BeginPopup("Sprite")) { ImGui::Text("Enter sprite's name:"); ImGui::InputText("##spriteName", newSpriteName, IM_ARRAYSIZE(newSpriteName)); if (ImGui::Button("OK")) { auto newEntity = m_Scene->CreateEntity(); //auto newEntity = m_UserInterface->CreateWidget(); auto& tag = newEntity.AddComponent<EntityTagComponent>(); auto& transform = newEntity.AddComponent<TransformComponent>(); auto& relationship = newEntity.AddComponent<RelationshipComponent>(); auto& sprite = newEntity.AddComponent<SpriteComponent>(); transform.Position = glm::vec3(0.0f, 0.0f, 0.0f); transform.Rotation = glm::vec3(0.0f, 0.0f, 0.0f); transform.Scale = glm::vec3(100.0f, 100.0f, 1.0f); tag.Name = newSpriteName; relationship.Parent = node; SpriteRenderer::Submit(sprite); if (node != entt::null) { //auto& parentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(node); auto& parentRelationship = registry.get<RelationshipComponent>(node); parentRelationship.Children.push_back(newEntity.GetEnttEntity()); parentRelationship.NumOfChildren++; } memset(newSpriteName, 0, 32 * sizeof(newSpriteName[0])); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } if (ImGui::BeginPopup("Rename")) { ImGui::Text("Enter new name:"); ImGui::InputText("##name", newSpriteName, IM_ARRAYSIZE(newSpriteName)); if (ImGui::Button("OK")) { //auto& tag = m_Scene->m_Registry.get<EntityTagComponent>(node); auto& tag = registry.get<EntityTagComponent>(node); tag.Name = newSpriteName; memset(newSpriteName, 0, 32 * sizeof(newSpriteName[0])); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } if (ImGui::BeginPopup("Delete")) { ImGui::Text("Are you sure you want to delete this game object?"); ImGui::MenuItem("", NULL, false, false); using TraverseFun = std::function<void(entt::entity)>; if (ImGui::Button("OK")) { // If entity is selected, then unselect it in order to delete it (this way there won't be any bugs) if (m_SelectedSceneEntity != entt::null) m_SelectedSceneEntity = entt::null; TraverseFun Traverse = [&](entt::entity entity) { //auto relationship = m_Scene->m_Registry.get<RelationshipComponent>(entity); auto relationship = registry.get<RelationshipComponent>(entity); for (auto child : relationship.Children) Traverse(child); //m_Scene->m_Registry.destroy(entity); registry.destroy(entity); if (relationship.Parent != entt::null) { //auto& parentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(relationship.Parent); auto& parentRelationship = registry.get<RelationshipComponent>(relationship.Parent); uint32_t index = 0; for (auto child : parentRelationship.Children) { if (child == node) { parentRelationship.Children.erase(parentRelationship.Children.begin() + index); parentRelationship.NumOfChildren--; break; } index++; } } }; Traverse(node); ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } ImGui::PopID(); } void Editor::CreateWidget(const std::string& name, entt::entity parent) { auto newWidget = m_Scene->CreateEntity(); //auto newWidget = m_UserInterface->CreateWidget(); auto& tag = newWidget.AddComponent<EntityTagComponent>(); auto& transform = newWidget.AddComponent<TransformComponent>(); auto& relationship = newWidget.AddComponent<RelationshipComponent>(); auto& sprite = newWidget.AddComponent<SpriteComponent>(); if (name == "Canvas") //newWidget.AddComponent<CanvasWidgetComponent>(); if (name == "Button") //newWidget.AddComponent<ButtonWidgetComponent>(); if (name == "Text") //newWidget.AddComponent<TextWidgetComponent>(); tag.Name = name; relationship.Parent = parent; SpriteRenderer::Submit(sprite); if (parent != entt::null) { auto& parentTransform = m_Scene->m_Registry.get<TransformComponent>(parent); //auto& parentTransform = m_UserInterface->m_Registry.get<TransformComponent>(parent); transform.Position = parentTransform.Position; transform.Rotation = parentTransform.Rotation; if (name == "Text") transform.Position.x += parentTransform.Scale.x / 2.0f; // Pass center position so text can be rendered at centered position compared to parent widget auto& parentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(parent); //auto& parentRelationship = m_UserInterface->m_Registry.get<RelationshipComponent>(parent); parentRelationship.Children.push_back(newWidget.GetEnttEntity()); parentRelationship.NumOfChildren++; } else { transform.Position = glm::vec3(0.0f, 0.0f, 0.0f); transform.Rotation = glm::vec3(0.0f, 0.0f, 0.0f); } if (name == "Text") transform.Scale = glm::vec3(1.0f, 1.0f, 1.0f); else transform.Scale = glm::vec3(100.0f, 100.0f, 1.0f); } void Editor::CreateCanvasMatrixWidget(int dimensions[2], float padding[4], float cellWidgetSize[2], entt::entity parent) { int rows = dimensions[0]; int columns = dimensions[1]; float paddingLeft = padding[0]; float paddingRight = padding[1]; float paddingTop = padding[2]; float paddingBottom = padding[3]; float cellWidgetWidth = cellWidgetSize[0]; float cellWidgetHeight = cellWidgetSize[1]; float widgetWidth = paddingLeft + paddingRight + (columns - 1) * paddingLeft + columns * cellWidgetWidth; float widgetHeight = paddingTop + paddingBottom + (rows - 1) * paddingTop + rows * cellWidgetHeight; for (int row = 0; row < rows; ++row) { for (int column = 0; column < columns; ++column) { // Cell canvas widget is a slot (placeholder) for widgets such as buttons auto canvas = m_Scene->CreateEntity(); //auto& cellWidgetCanvas = canvas.AddComponent<CanvasWidgetComponent>(); auto& cellWidgetRelationship = canvas.AddComponent<RelationshipComponent>(); auto& cellWidgetSprite = canvas.AddComponent<SpriteComponent>(); auto& cellWidgetTransform = canvas.AddComponent<TransformComponent>(); auto& entityTagComponent = canvas.AddComponent<EntityTagComponent>(); entityTagComponent.Name = "Canvas"; cellWidgetSprite.Color = glm::vec4(0.8f, 0.8f, 0.8f, 0.7f); SpriteRenderer::Submit(cellWidgetSprite); auto& transform = m_Scene->m_Registry.get<TransformComponent>(parent); if (column == 0) cellWidgetTransform.Position.x = transform.Position.x + paddingLeft; else cellWidgetTransform.Position.x = transform.Position.x + (column + 1) * paddingLeft + column * cellWidgetWidth; if (row == 0) cellWidgetTransform.Position.y = transform.Position.y - paddingTop; else cellWidgetTransform.Position.y = transform.Position.y - (row + 1) * paddingTop - row * cellWidgetHeight; cellWidgetTransform.Scale.x = cellWidgetWidth; cellWidgetTransform.Scale.y = cellWidgetHeight; //cellWidgetRelationship.Parent = m_SelectedSceneEntity; cellWidgetRelationship.Parent = parent; auto& relationship = m_Scene->m_Registry.get<RelationshipComponent>(parent); relationship.Children.push_back(canvas.GetEnttEntity()); relationship.NumOfChildren++; } } auto& transform = m_Scene->m_Registry.get<TransformComponent>(parent); transform.Scale.x = widgetWidth; transform.Scale.y = widgetHeight; ImGui::NewLine(); } void Editor::CreateCopyEntity(entt::entity node) // Entity can have many children or none { using TraverseFun = std::function<void(entt::entity, entt::entity)>; TraverseFun traverse = [&](entt::entity node, entt::entity copyNode) { auto nodeRelationship = m_Scene->m_Registry.get<RelationshipComponent>(node); // Get by value because entt library change this component under the hood when new component is added to registry (TODO: Check this weird feature!) for (auto child : nodeRelationship.Children) { auto copyEntity = m_Scene->m_Registry.create(); if (m_Scene->m_Registry.has<EntityTagComponent>(child)) m_Scene->m_Registry.emplace<EntityTagComponent>(copyEntity, m_Scene->m_Registry.get<EntityTagComponent>(child)); if (m_Scene->m_Registry.has<TransformComponent>(child)) m_Scene->m_Registry.emplace<TransformComponent>(copyEntity, m_Scene->m_Registry.get<TransformComponent>(child)); if (m_Scene->m_Registry.has<MeshComponent>(child)) m_Scene->m_Registry.emplace<MeshComponent>(copyEntity, m_Scene->m_Registry.get<MeshComponent>(child)); if (m_Scene->m_Registry.has<BoundBoxComponent>(child)) m_Scene->m_Registry.emplace<BoundBoxComponent>(copyEntity, m_Scene->m_Registry.get<BoundBoxComponent>(child)); if (m_Scene->m_Registry.has<SpriteComponent>(child)) m_Scene->m_Registry.emplace<SpriteComponent>(copyEntity, m_Scene->m_Registry.get<SpriteComponent>(child)); //if (m_Scene->m_Registry.has<CanvasWidgetComponent>(child)) // m_Scene->m_Registry.emplace<CanvasWidgetComponent>(copyEntity, m_Scene->m_Registry.get<CanvasWidgetComponent>(child)); //if (m_Scene->m_Registry.has<ButtonWidgetComponent>(child)) // m_Scene->m_Registry.emplace<ButtonWidgetComponent>(copyEntity, m_Scene->m_Registry.get<ButtonWidgetComponent>(child)); //if (m_Scene->m_Registry.has<TextWidgetComponent>(child)) // m_Scene->m_Registry.emplace<TextWidgetComponent>(copyEntity, m_Scene->m_Registry.get<TextWidgetComponent>(child)); auto& copyRelationship = m_Scene->m_Registry.emplace<RelationshipComponent>(copyEntity); copyRelationship.Parent = copyNode; // copyNode is the parent of copyEntity auto& copyParentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(copyNode); copyParentRelationship.Children.push_back(copyEntity); copyParentRelationship.NumOfChildren++; } int index = 0; auto& copyNodeRelationship = m_Scene->m_Registry.get<RelationshipComponent>(copyNode); for (auto child : nodeRelationship.Children) { auto copyChild = copyNodeRelationship.Children[index]; traverse(child, copyChild); index++; } }; // Create copy root (starting) node auto copyNode = m_Scene->m_Registry.create(); auto& relationship = m_Scene->m_Registry.get<RelationshipComponent>(node); if (relationship.Parent != entt::null) // If node's parent isn't scene root node { auto& parentRelationship = m_Scene->m_Registry.get<RelationshipComponent>(relationship.Parent); parentRelationship.Children.push_back(copyNode); // Push copy node to parent's children parentRelationship.NumOfChildren++; } if (m_Scene->m_Registry.has<EntityTagComponent>(node)) m_Scene->m_Registry.emplace<EntityTagComponent>(copyNode, m_Scene->m_Registry.get<EntityTagComponent>(node)); if (m_Scene->m_Registry.has<TransformComponent>(node)) m_Scene->m_Registry.emplace<TransformComponent>(copyNode, m_Scene->m_Registry.get<TransformComponent>(node)); if (m_Scene->m_Registry.has<MeshComponent>(node)) m_Scene->m_Registry.emplace<MeshComponent>(copyNode, m_Scene->m_Registry.get<MeshComponent>(node)); if (m_Scene->m_Registry.has<BoundBoxComponent>(node)) m_Scene->m_Registry.emplace<BoundBoxComponent>(copyNode, m_Scene->m_Registry.get<BoundBoxComponent>(node)); if (m_Scene->m_Registry.has<SpriteComponent>(node)) m_Scene->m_Registry.emplace<SpriteComponent>(copyNode, m_Scene->m_Registry.get<SpriteComponent>(node)); //if (m_Scene->m_Registry.has<CanvasWidgetComponent>(node)) // m_Scene->m_Registry.emplace<CanvasWidgetComponent>(copyNode, m_Scene->m_Registry.get<CanvasWidgetComponent>(node)); //if (m_Scene->m_Registry.has<ButtonWidgetComponent>(node)) // m_Scene->m_Registry.emplace<ButtonWidgetComponent>(copyNode, m_Scene->m_Registry.get<ButtonWidgetComponent>(node)); //if (m_Scene->m_Registry.has<TextWidgetComponent>(node)) // m_Scene->m_Registry.emplace<TextWidgetComponent>(copyNode, m_Scene->m_Registry.get<TextWidgetComponent>(node)); //auto& copyRelationship = m_Scene->m_Registry.emplace<RelationshipComponent>(copyNode, m_Scene->m_Registry.get<RelationshipComponent>(node)); auto& copyRelationship = m_Scene->m_Registry.emplace<RelationshipComponent>(copyNode); copyRelationship.Parent = relationship.Parent; traverse(node, copyNode); } /** * @brief Create second window for "play" mode. * * This method creates second window, when user clicks "Play" button. * This window will render the final look of a game, together with in-game UI. */ void Editor::CreateGameWindow() { Window::Hint(GLFW_DECORATED, true); m_GameWindow->CreateGLFWwindow(NULL, m_MainWindow->m_GLFWwindow); Window::s_CurrentActiveWindowName = m_GameWindow->GetWindowName(); Window::MakeContextCurrent(m_GameWindow->m_GLFWwindow); m_GameWindow->m_UserInterface->OnStart(); //glfwSetWindowAspectRatio(m_GameWindow->m_GLFWwindow, m_GameWindow->m_Width, m_GameWindow->m_Height); m_GameWindow->SetEventCallbacks(); m_MainWindow->RemoveEventCallbacks(); UserInput::SetGLFWwindow(m_GameWindow->m_GLFWwindow); m_GameWindow->ShowWindow(); auto& fromRegistry = m_Scene->m_Registry; auto& toRegistry = m_GameWindow->m_Scene->m_Registry; toRegistry.clear(); m_Scene->m_CloneFunctions[entt::type_hash<TransformComponent>::value()] = &Scene::CloneRegistry<TransformComponent>; m_Scene->m_CloneFunctions[entt::type_hash<RelationshipComponent>::value()] = &Scene::CloneRegistry<RelationshipComponent>; m_Scene->m_CloneFunctions[entt::type_hash<EntityTagComponent>::value()] = &Scene::CloneRegistry<EntityTagComponent>; m_Scene->m_CloneFunctions[entt::type_hash<BoundBoxComponent>::value()] = &Scene::CloneRegistry<BoundBoxComponent>; m_Scene->m_CloneFunctions[entt::type_hash<MeshComponent>::value()] = &Scene::CloneRegistry<MeshComponent>; m_Scene->m_CloneFunctions[entt::type_hash<SpriteComponent>::value()] = &Scene::CloneRegistry<SpriteComponent>; m_Scene->m_CloneFunctions[entt::type_hash<AnimationComponent>::value()] = &Scene::CloneRegistry<AnimationComponent>; m_Scene->m_CloneFunctions[entt::type_hash<CameraComponent>::value()] = &Scene::CloneRegistry<CameraComponent>; m_Scene->m_CloneFunctions[entt::type_hash<ScriptComponent>::value()] = &Scene::CloneRegistry<ScriptComponent>; //m_Scene->m_CloneFunctions[entt::type_hash<TextWidgetComponent>::value()] = &Scene::CloneRegistry<TextWidgetComponent>; //m_Scene->m_CloneFunctions[entt::type_hash<CanvasWidgetComponent>::value()] = &Scene::CloneRegistry<CanvasWidgetComponent>; //m_Scene->m_CloneFunctions[entt::type_hash<ButtonWidgetComponent>::value()] = &Scene::CloneRegistry<ButtonWidgetComponent>; // Create entities with same id as entities in m_Scene fromRegistry.each([&toRegistry](auto entity) { auto copyEntity = toRegistry.create(entity); } ); // Iterate over all components of m_Editor->m_Scene and copy components to m_GameWindow->m_Scene m_Scene->m_Registry.visit([this, &fromRegistry, &toRegistry](const auto componentType) { m_Scene->m_CloneFunctions[componentType.hash()](fromRegistry, toRegistry); } ); auto view = m_GameWindow->m_Scene->GetView<MeshComponent>(); for (auto entity : view) { auto& mesh = view.get<MeshComponent>(entity); MeshRenderer::SubmitCopy(mesh); } Window::MakeContextCurrent(m_MainWindow->m_GLFWwindow); } /** * @brief Create a frame buffer. * * This method creates frame buffer, which will be used for Scene window in editor. */ void Editor::CreateFrameBuffer(int width, int height) { m_FrameBuffer = sPtrCreate<FrameBuffer>(); m_IntermediateFrameBuffer = sPtrCreate<FrameBuffer>(); m_RenderBuffer = sPtrCreate<RenderBuffer>(); //m_Texture = sPtrCreate<Texture>(width, height); m_Texture = sPtrCreate<Texture>(width, height, 4); m_IntermediateTexture = sPtrCreate<Texture>(width, height); m_FrameBuffer->Bind(); m_RenderBuffer->Bind(); //m_RenderBuffer->Storage(width, height); m_RenderBuffer->Storage(width, height, 4); m_RenderBuffer->Unbind(); m_FrameBuffer->AttachMultisampled(m_Texture->GetId(), FrameBuffer::AttachmentType::TextureBuffer); m_FrameBuffer->AttachMultisampled(m_RenderBuffer->GetId(), FrameBuffer::AttachmentType::RenderBuffer); //m_FrameBuffer->Attach(m_Texture->GetId(), FrameBuffer::AttachmentType::TextureBuffer); //m_FrameBuffer->Attach(m_RenderBuffer->GetId(), FrameBuffer::AttachmentType::RenderBuffer); m_FrameBuffer->Unbind(); m_IntermediateFrameBuffer->Bind(); m_IntermediateFrameBuffer->Attach(m_IntermediateTexture->GetId(), FrameBuffer::AttachmentType::TextureBuffer); m_IntermediateFrameBuffer->Unbind(); } /** * @brief Bind frame buffer. * * Frame buffer is bound before Scene rendering. */ void Editor::BindFrameBuffer() { m_FrameBuffer->Bind(); } /** * @brief Unbind frame buffer. * * Frame buffer is unbound after Scene rendering is done. */ void Editor::UnbindFrameBuffer() { m_FrameBuffer->Unbind(); } /** * @brief Import asset in Scene window * * Asset is imported on drag'n'drop. * Asset could be found in Project windo, in editor. */ void Editor::ImportAsset(const std::string& importAssetFilePath) { auto& [loadedMesh, loadedAnimation] = ModelImporter::LoadMeshFile(importAssetFilePath); auto meshEntity = m_Scene->CreateEntity(); auto& entityTag = meshEntity.AddComponent<EntityTagComponent>(importAssetFilePath); auto& mesh = meshEntity.AddComponent<MeshComponent>(*loadedMesh); auto& transform = meshEntity.AddComponent<TransformComponent>(); auto& relationship = meshEntity.AddComponent<RelationshipComponent>(); relationship.Parent = entt::null; meshEntity.AddComponent<BoundBoxComponent>(*loadedMesh); if (loadedMesh->HasAnimation) auto& animation = meshEntity.AddComponent<AnimationComponent>(*loadedAnimation); // Check if mouse ray intersects ground plane if (MouseRay::CheckCollisionWithPlane()) { // Place asset on the intersection point const glm::vec3& intersectionPoint = MouseRay::GetIntersectionPoint(); transform.Position = intersectionPoint; } else { // Place asset on the origin point of world coordinate system transform.Position = glm::vec3(0.0f, 0.0f, 0.0f); } transform.Scale = glm::vec3(10.0f, 10.0f, 10.0f); MeshRenderer::Submit(mesh); } /** * @brief Select mesh on left click * * Mesh is selected when user clicks on it in Scene window. * Editor will keep track of the selected entity ID, which is of the type entt::entity. */ void Editor::SelectMesh() { auto& camera = m_Scene->GetCamera(); MouseRay::CalculateRayOrigin(camera, m_MouseInfo.MousePosX, m_MouseInfo.MousePosY, m_SceneInfo.SceneWidth, m_SceneInfo.SceneHeight); auto view = m_Scene->m_Registry.view<MeshComponent, TransformComponent, BoundBoxComponent>(); bool isAnyMeshSelected = false; std::pair<entt::entity, int> minIntersectionDistance = std::make_pair(entt::null, -1); // If ray goes through many meshes, then take minimum intersection distance for (auto entity : view) { const auto& [mesh, transform] = view.get<MeshComponent, TransformComponent>(entity); // Check if mouse ray intersects AABB of a mesh if (MouseRay::CheckCollisionWithBox(mesh, transform)) { // Check if mouse ray intersects any mesh triangle if (MouseRay::CheckCollisionWithMesh(mesh, transform)) { isAnyMeshSelected = true; if (minIntersectionDistance.first == entt::null) { minIntersectionDistance.first = entity; minIntersectionDistance.second = (int)MouseRay::GetCollisionDistance(); } else { if (minIntersectionDistance.second > (int)MouseRay::GetCollisionDistance()) { minIntersectionDistance.first = entity; minIntersectionDistance.second = (int)MouseRay::GetCollisionDistance(); } } } } } if (isAnyMeshSelected) { m_SelectedSceneEntity = minIntersectionDistance.first; s_CurrentGizmoOperation = ImGuizmo::TRANSLATE; } else { m_SelectedSceneEntity = entt::null; s_CurrentGizmoOperation = ImGuizmo::BOUNDS; } } /** * @brief Update Scene texture when Scene window is resized. * * This method resizes framebuffer according to Scene window size and it also updates viewport (glViewport function). */ void Editor::UpdateSceneViewport(float sceneWindowWidth, float sceneWindowHeight) { float ratio = 1.5f; float x = sceneWindowWidth; float y = sceneWindowHeight; if ((x / y) > ratio) { x = ratio * y; } if ((x / y) < ratio) { y = (1 / ratio) * x; } //m_Texture->Resize((int)x, (int)y); m_Texture->ResizeMultisampled((int)x, (int)y, 4); m_IntermediateTexture->Resize((int)x, (int)y); m_RenderBuffer->ResizeMultisampled((int)x, (int)y, 4); //m_RenderBuffer->Resize((int)x, (int)y); glViewport(0, 0, (int)x, (int)y); m_SceneInfo.SceneWidth = (int)x; m_SceneInfo.SceneHeight = (int)y; } }
34.051423
228
0.693659
bd93
9f3d0b3a213a110f9f24124fe4be6b1e84186cb5
5,216
hpp
C++
include/indigox/utils/common.hpp
allison-group/indigox
22657cb3ceb888049cc231e73d18fb2eac099604
[ "MIT" ]
7
2019-11-24T15:51:37.000Z
2021-10-02T05:18:42.000Z
include/indigox/utils/common.hpp
allison-group/indigox
22657cb3ceb888049cc231e73d18fb2eac099604
[ "MIT" ]
2
2018-12-17T00:55:32.000Z
2019-10-11T01:47:04.000Z
include/indigox/utils/common.hpp
allison-group/indigox
22657cb3ceb888049cc231e73d18fb2eac099604
[ "MIT" ]
2
2019-10-21T01:26:56.000Z
2019-12-02T00:00:42.000Z
/*! \file common.hpp */ #ifndef INDIGOX_UTILS_COMMON_HPP #define INDIGOX_UTILS_COMMON_HPP #include <array> #include <bitset> #include <algorithm> #include <iterator> #include <memory> #include <string> #include <type_traits> // forward definitions of serilisation stuff namespace cereal { class access; class PortableBinaryInputArchive; class PortableBinaryOutputArchive; class JSONInputArchive; class JSONOutputArchive; template <class T> class construct; } // namespace cereal //! utils namespace for useful utility functions namespace indigox::utils { enum class Option { Yes = 1, No = Yes << 1, Auto = Yes << 2, Default = Yes << 3, All = Yes << 4, Some = Yes << 5, None = Yes << 6 }; inline Option operator|(Option l, Option r) { using under = std::underlying_type<Option>::type; return static_cast<Option>(static_cast<under>(l) | static_cast<under>(r)); } inline Option operator&(Option l, Option r) { using under = std::underlying_type<Option>::type; return static_cast<Option>(static_cast<under>(l) & static_cast<under>(r)); } /*! \brief Convert a string to upper case. * \param s the string to convert. * \return the uppercase version of s. */ std::string ToUpper(const std::string &s); /*! \brief Convert a string to lower case. * \param s the string to convert. * \return the lower case version of s. */ std::string ToLower(const std::string &s); /*! \brief Convert a string to lower case with a single leading upper case. * \details Acts on the string as a whole, ignoring any white space. * \param s the string the convert. * \return the lower case version of s with a leading upper case letter. */ std::string ToUpperFirst(const std::string &s); /*! \brief Generate a random string. * \details All upper and lower case letters are available. * \param length the number of characters to generate. * \param seed the seed for the random number generator. If * \return the randomly generated string. */ std::string GetRandomString(size_t length, size_t seed = 0); /*! \brief Check if a given shared_ptr<T> is in a weak_ptr<T> container. * \details Checks all weak_ptr<T> instances in the iterator range to see * if the reference the supplied shared_ptr<T>. If the supplied shared_ptr<T> * is empty, no comparisons are made. * \tparam T the element_type. * \tparam __Iter the iterator type. * \param b,e start and end of the iterator range. * \param x the shared_ptr<T> instance to search for. * \return the iterator position of the first found element. */ template <typename T, typename __Iter> inline __Iter WeakContainsShared(__Iter b, __Iter e, std::shared_ptr<T> x) { static_assert( std::is_same<typename std::weak_ptr<T>, typename std::iterator_traits<__Iter>::value_type>::value, "__Iter must be iterator over std::weak_ptr<T>."); if (!x) return e; return std::find_if(b, e, [x](std::weak_ptr<T> _x) { return _x.lock() == x; }); } /*! \brief Check if a shared_ptr is pointing to a null member. * \details Types must implement a boolean operator which returns true if * that instance is considered a null instance. * \tparam T the stored type. * \param t the shared_ptr<T> to check. * \return if the shared_ptr references a null instance. */ // template<typename T> // inline bool IsNull(std::shared_ptr<T> t) { // return !(t && *t); // } } // namespace indigox::utils #define b_cnt (uint32_t)Settings::BoolCount #define i_cnt (uint32_t)Settings::IntCount #define f_cnt (uint32_t)Settings::RealCount #define p_cnt (uint32_t)param #define DEFAULT_SETTINGS(...) \ private: \ std::bitset<b_cnt> p_bool; \ std::array<double, f_cnt - b_cnt - 2> p_num; \ \ void ResetSettings() { \ p_bool.reset(); \ p_num.fill(0.); \ } \ \ public: \ bool GetBool(Settings param) { \ if (p_cnt >= b_cnt) throw std::runtime_error("Not a boolean parameter"); \ return p_bool.test(p_cnt); \ } \ void SetBool(Settings param, bool value) { \ if (p_cnt >= b_cnt) throw std::runtime_error("Not a boolean parameter"); \ p_bool[p_cnt] = value; \ } \ int64_t GetInt(Settings param) { \ uint32_t offset = 1 + b_cnt; \ if (p_cnt <= b_cnt || p_cnt >= i_cnt) throw std::runtime_error("Not an integer parameter"); \ return int64_t(p_num[p_cnt - offset]); \ } \ void SetInt(Settings param, int64_t value) { \ uint32_t offset = 1 + b_cnt; \ if (p_cnt <= b_cnt || p_cnt >= i_cnt) throw std::runtime_error("Not an integer parameter"); \ p_num[p_cnt - offset] = double(value); \ } \ double GetReal(Settings param) { \ uint32_t offset = 2 + b_cnt; \ if (p_cnt <= i_cnt || p_cnt >= f_cnt) throw std::runtime_error("Not a real parameter"); \ return p_num[p_cnt - offset]; \ } \ void SetReal(Settings param, double value) { \ uint32_t offset = 2 + b_cnt; \ if (p_cnt <= i_cnt || p_cnt >= f_cnt) throw std::runtime_error("Not a real parameter"); \ p_num[p_cnt - offset] = value; \ } \ void DefaultSettings() #endif /* INDIGOX_UTILS_COMMON_HPP */
34.543046
97
0.66296
allison-group
9f3e51b216a6de9ee5f29eb9cd92ae51cb7f783f
4,986
cpp
C++
windows/c++/visualstudio/src/InformationManager.cpp
afskylia/bachelor-starcraft-bot
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
[ "MIT" ]
null
null
null
windows/c++/visualstudio/src/InformationManager.cpp
afskylia/bachelor-starcraft-bot
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
[ "MIT" ]
2
2021-06-27T18:57:39.000Z
2021-06-27T18:57:52.000Z
windows/c++/visualstudio/src/InformationManager.cpp
afskylia/bachelor-starcraft-bot
e9d53345d77f6243f5a2db1781cdfcb7838ebcfd
[ "MIT" ]
null
null
null
#include "InformationManager.h" #include "MiraBotMain.h" #include "Global.h" using namespace MiraBot; /// <summary> /// Here we save important information through the game e.g. enemy race and where they are. /// </summary> InformationManager::InformationManager() { //// Save positions of all chokepoints in main base //auto base = BWAPI::Broodwar->self()->getStartLocation(); //const auto area = Global::map().map.GetNearestArea(base); //for (auto cp : area->ChokePoints()) // base_chokepoints.push_back(BWAPI::Position(cp->Center())); } void InformationManager::onFrame() { if (m_should_update_ && BWAPI::Broodwar->getFrameCount() % 50 == 0) { informationIsUpdated(); m_should_update_ = false; } } /// <summary> /// Call this when information is updated, e.g. enemy is found /// </summary> void InformationManager::informationUpdateShouldHappen() { if (!m_should_update_) m_should_update_ = true; } /// <summary> /// information in the manager is send to e.g. strategy manager to update strategy. /// </summary> void InformationManager::informationIsUpdated() { updateEnemyStrategy(); Global::strategy().informationUpdate(); } /// <summary> /// Update Enemy Strategy /// </summary> void InformationManager::updateEnemyStrategy() { // Do not update if we do not know any enemies. if (enemy_units.empty()) return; for (BWAPI::UnitInterface* enemy_unit : enemy_units) { bool enemy_is_near_our_base = enemy_unit->getPosition().getApproxDistance(main_base->getPosition()) < 1000; bool enemy_is_in_own_base = enemy_unit->getPosition().getApproxDistance(BWAPI::Position(enemy_start_location)) < 1000; // Offensive if leaving base or near our base if (enemy_is_near_our_base || enemy_is_in_own_base) { m_current_enemy_strategy = Enums::offensive; return; } } m_current_enemy_strategy = Enums::defensive; } /// <summary> /// log the enemy race and starting location /// </summary> /// <param name="unit">First enemy unit found</param> void InformationManager::logEnemyRaceAndStartLocation(BWAPI::Unit unit) { // If we did not find the enemy, log it if (!found_enemy) { enemy_race = unit->getType().getRace(); found_enemy = true; std::cout << "Enemy is " << enemy_race << "\n"; auto& start_locations = BWAPI::Broodwar->getStartLocations(); // Find closest starting location to enemy unit double shortest_distance = INT_MAX; for (BWAPI::TilePosition position : start_locations) { const auto distance = position.getDistance(unit->getTilePosition()); if (distance < shortest_distance) { shortest_distance = distance; enemy_start_location = position; } } std::cout << "Enemy starting location: " << enemy_start_location << "\n"; Global::map().addCircle(BWAPI::Position(enemy_start_location), "ENEMY START LOCATION"); auto area = Global::map().map.GetNearestArea(enemy_start_location); enemy_areas.push_back(area); informationUpdateShouldHappen(); } } /// <summary> /// Keeps track of the enemy units. /// </summary> /// <param name="unit">the unit to add or remove</param> /// <param name="remove_unit">should we remove the unit, default is false</param> void InformationManager::addOrRemoveEnemyUnit(BWAPI::Unit unit, bool remove_unit) { // try find the unit in unit set auto it = enemy_units.find(unit); // if not in the unit set, add it, if in the set and should remove then remove it if (!remove_unit) { if (it != enemy_units.end()) { enemy_units.erase(it); } enemy_units.insert(unit); informationUpdateShouldHappen(); } else { enemy_units.erase(it); informationUpdateShouldHappen(); } } void InformationManager::onUnitShow(BWAPI::Unit unit) { // If we find an enemy, we should log the information if (unit->getPlayer()->isEnemy(BWAPI::Broodwar->self())) { // Save all unit bases we find (if it has buildings, we consider it a base) const auto* area = Global::map().map.GetNearestArea(unit->getTilePosition()); if (unit->getType().isBuilding() && !std::count(enemy_areas.begin(), enemy_areas.end(), area)) { enemy_areas.push_back(area); Global::map().addCircle(unit->getPosition(), "ENEMY AREA\n"); } logEnemyRaceAndStartLocation(unit); addOrRemoveEnemyUnit(unit); informationUpdateShouldHappen(); } } void InformationManager::onStart() { main_base = BWAPI::Broodwar->getClosestUnit(BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation()), BWAPI::Filter::IsResourceDepot); informationUpdateShouldHappen(); } void InformationManager::onUnitDestroy(BWAPI::Unit unit) { // If we find an enemy, we should log the information if (unit->getPlayer()->isEnemy(BWAPI::Broodwar->self())) { addOrRemoveEnemyUnit(unit, true); informationUpdateShouldHappen(); } } /// <summary> /// Gets the strategy from enemy units /// </summary> /// <returns>strategy based on units</returns> Enums::strategy_type InformationManager::getEnemyStrategy() { return m_current_enemy_strategy; }
27.854749
114
0.712796
afskylia
9f3ef13ff365f2d7b000ee73688fc5072f454092
4,165
cpp
C++
Spectre2D/source/FileSystem.cpp
DragonGamesStudios/Spectre2D
044f73f3516f92fd939349e11e89e4524c84e7fd
[ "MIT" ]
null
null
null
Spectre2D/source/FileSystem.cpp
DragonGamesStudios/Spectre2D
044f73f3516f92fd939349e11e89e4524c84e7fd
[ "MIT" ]
null
null
null
Spectre2D/source/FileSystem.cpp
DragonGamesStudios/Spectre2D
044f73f3516f92fd939349e11e89e4524c84e7fd
[ "MIT" ]
null
null
null
#include "..\include\Spectre2D\FileSystem.h" namespace sp { FileSystem::FileSystem(bool appdata) { if (appdata) { #if defined(_WIN32) char* appbuff; size_t len; _dupenv_s(&appbuff, &len, "APPDATA"); current_path = appbuff; #elif defined(__linux__) current_path = "~/.local/"; #endif } else { current_path = fs::current_path(); } } bool FileSystem::create_dir(const std::string& dirname) { return fs::create_directory(current_path / dirname); } bool FileSystem::delete_dir_recursively(const std::string& dirname) { return fs::remove_all(current_path / dirname) > 0; } bool FileSystem::enter_dir(const std::string& path) { if (exists(path)) { current_path = get_correct_path(path); return true; } return false; } bool FileSystem::enter_dir(const fs::path& path) { if (exists(path)) { current_path = get_correct_path(path); return true; } return false; } std::string FileSystem::get_directory() const { return current_path.filename().string(); } fs::path FileSystem::get_current_path() const { return current_path; } void FileSystem::exit() { current_path = current_path.parent_path(); } void FileSystem::exit_to(const fs::path& dirname) { while ( current_path.filename() != dirname && fs::absolute(current_path) != fs::absolute(dirname) && !current_path.empty() ) { this->exit(); } } bool FileSystem::create_dir_if_necessary(const std::string& dirname) { if (!exists(dirname)) return create_dir(dirname); return true; } std::ifstream FileSystem::open_file(const std::string& path) const { return std::ifstream(current_path / path); } std::ifstream FileSystem::open_file(const fs::path& path) const { return std::ifstream(current_path / path); } std::ofstream FileSystem::open_ofile(const std::string& path) const { return std::ofstream(current_path / path); } std::ofstream FileSystem::open_ofile(const fs::path& path) const { return std::ofstream(current_path / path); } bool FileSystem::create_file(const std::string& filename) { std::ofstream f(filename); bool worked = f.is_open(); f.close(); return worked; } bool FileSystem::create_file_if_necessary(const std::string& filename) { if (!exists(filename)) return create_file(filename); return true; } bool FileSystem::delete_file(const std::string& filename) { return fs::remove(filename); } bool FileSystem::delete_file(const fs::path& filename) { return fs::remove(filename); } bool FileSystem::delete_file_if_exists(const std::string& filename) { if (exists(filename)) return fs::remove(filename); return true; } bool FileSystem::delete_file_if_exists(const fs::path& filename) { if (exists(filename)) return fs::remove(filename); return true; } bool FileSystem::exists(const fs::path& path) const { return fs::exists(get_correct_path(path)); } bool FileSystem::add_path_template(const std::string& temp, const fs::path& target) { fs::path correct = target; if (!correct.is_absolute()) correct = current_path / correct; size_t s = temp.size(); if (s > 4 && temp[0] == temp[1] && temp[1] == temp[s - 1] && temp[s - 1] == temp[s - 2] && temp[s - 2] == '_') { path_templates.insert(std::make_pair(temp, correct)); return true; } return false; } bool FileSystem::is_template(const std::string& name) { size_t s = name.size(); return (s > 4 && name[0] == name[1] && name[1] == name[s - 1] && name[s - 1] == name[s - 2] && name[s - 2] == '_'); } fs::path FileSystem::get_correct_path(const fs::path& path) const { if (path.empty()) return current_path; if (path.has_root_path()) return path; std::string root = (*path.begin()).string(); fs::path rest; for (auto it = ++path.begin(); it != path.end(); it++) rest /= *it; if (is_template(root) && path_templates.find(root) != path_templates.end()) return path_templates.at(root) / rest; return current_path / path; } fs::directory_iterator FileSystem::get_files_in_directory(const fs::path& dirname) { return fs::directory_iterator(get_correct_path(dirname)); } }
20.218447
117
0.669148
DragonGamesStudios
9f4248b73d87945f377b354bbecd0c62904b6fa2
427
cpp
C++
1010.cpp
matheusfbonfim/URI-solutions
a368c271e2940dc2d0c575ea6cc468b50d76ce6f
[ "MIT" ]
null
null
null
1010.cpp
matheusfbonfim/URI-solutions
a368c271e2940dc2d0c575ea6cc468b50d76ce6f
[ "MIT" ]
null
null
null
1010.cpp
matheusfbonfim/URI-solutions
a368c271e2940dc2d0c575ea6cc468b50d76ce6f
[ "MIT" ]
null
null
null
#include<iostream> #include<iomanip> using namespace std; int main(){ int cod_peca1, num_peca1, cod_peca2, num_peca2; double valor_unit_peca1, valor_unit_peca2; cin >> cod_peca1 >> num_peca1 >> valor_unit_peca1; cin >> cod_peca2 >> num_peca2 >> valor_unit_peca2; cout << fixed << setprecision(2); cout << "VALOR A PAGAR: R$ " << (num_peca1*valor_unit_peca1) + (num_peca2*valor_unit_peca2)<< endl; return 0; }
25.117647
101
0.709602
matheusfbonfim
9f46e62c023b9a42a3184aa2e447b9596181f220
860
cpp
C++
src/peakIndexInMountainArray.cpp
guitargeek/leetcode
7d587774d3f922020b5ba3ca2d533b2686891fed
[ "MIT" ]
null
null
null
src/peakIndexInMountainArray.cpp
guitargeek/leetcode
7d587774d3f922020b5ba3ca2d533b2686891fed
[ "MIT" ]
null
null
null
src/peakIndexInMountainArray.cpp
guitargeek/leetcode
7d587774d3f922020b5ba3ca2d533b2686891fed
[ "MIT" ]
null
null
null
/** 852. Peak Index in a Mountain Array Let's call an array A a mountain if the following properties hold: A.length >= 3 There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. Example 1: ``` Input: [0,1,0] Output: 1 ``` Example 2: ``` Input: [0,2,1,0] Output: 1 ``` Note: 3 <= A.length <= 10000 0 <= A[i] <= 10^6 A is a mountain, as defined above. */ #include "leet.h" namespace leet { using namespace std; int peakIndexInMountainArray(vector<int>& A) { for (int i = 1; i < A.size(); ++i) { if (A[i] - A[i - 1] < 0) return i - 1; } return -1; } } // namespace leet
17.2
117
0.517442
guitargeek
9f488e046a44a1c69f4910c46d8195b6e47a9356
3,286
cpp
C++
src/panels/wx_id_list.cpp
KeyWorksRW/wxUiEditor
fc58bb37284430fa5901579ae121d4482b588c75
[ "Apache-2.0" ]
7
2021-10-22T02:43:12.000Z
2022-01-15T10:52:58.000Z
src/panels/wx_id_list.cpp
KeyWorksRW/wxUiEditor
fc58bb37284430fa5901579ae121d4482b588c75
[ "Apache-2.0" ]
288
2021-05-16T19:12:04.000Z
2022-03-30T13:22:31.000Z
src/panels/wx_id_list.cpp
KeyWorksRW/wxUiEditor
fc58bb37284430fa5901579ae121d4482b588c75
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Purpose: wxID_ strings // Author: Ralph Walden // Copyright: Copyright (c) 2020 KeyWorks Software (Ralph Walden) // License: Apache License -- see ../../LICENSE ///////////////////////////////////////////////////////////////////////////// // This file is designed to be #included into propgrid_panel.cpp, so it doesn't have the normal precompiled header. // clang-format off inline const char* list_wx_ids[] = { "wxID_ABORT", "wxID_ABOUT", "wxID_ADD", "wxID_ANY", "wxID_APPLY", "wxID_BACKWARD", "wxID_BOLD", "wxID_BOTTOM", "wxID_CANCEL", "wxID_CDROM", "wxID_CLEAR", "wxID_CLOSE", "wxID_CLOSE_ALL", "wxID_CLOSE_FRAME", "wxID_CONTEXT_HELP", "wxID_CONVERT", "wxID_COPY", "wxID_CUT", "wxID_DEFAULT", "wxID_DELETE", "wxID_DOWN", "wxID_DUPLICATE", "wxID_EDIT", "wxID_EXECUTE", "wxID_EXIT", "wxID_FILE", "wxID_FILE1", "wxID_FILE2", "wxID_FILE3", "wxID_FILE4", "wxID_FILE5", "wxID_FILE6", "wxID_FILE7", "wxID_FILE8", "wxID_FILE9", "wxID_FIND", "wxID_FIRST", "wxID_FLOPPY", "wxID_FORWARD", "wxID_HARDDISK", "wxID_HELP", "wxID_HELP_COMMANDS", "wxID_HELP_CONTENTS", "wxID_HELP_CONTEXT", "wxID_HELP_INDEX", "wxID_HELP_PROCEDURES", "wxID_HELP_SEARCH", "wxID_HOME", "wxID_ICONIZE_FRAME", "wxID_IGNORE", "wxID_INDENT", "wxID_INDEX", "wxID_INFO", "wxID_ITALIC", "wxID_JUMP_TO", "wxID_JUSTIFY_CENTER", "wxID_JUSTIFY_FILL", "wxID_JUSTIFY_LEFT", "wxID_JUSTIFY_RIGHT", "wxID_LAST", "wxID_MAXIMIZE_FRAME", "wxID_MDI_WINDOW_ARRANGE_ICONS", "wxID_MDI_WINDOW_CASCADE", "wxID_MDI_WINDOW_FIRST", "wxID_MDI_WINDOW_LAST", "wxID_MDI_WINDOW_NEXT", "wxID_MDI_WINDOW_PREV", "wxID_MDI_WINDOW_TILE_HORZ", "wxID_MDI_WINDOW_TILE_VERT", "wxID_MORE", "wxID_MOVE_FRAME", "wxID_NETWORK", "wxID_NEW", "wxID_NO", "wxID_NONE", "wxID_NOTOALL", "wxID_OK", "wxID_OPEN", "wxID_PAGE_SETUP", "wxID_PASTE", "wxID_PREFERENCES", "wxID_PREVIEW", "wxID_PRINT", "wxID_PRINT_SETUP", "wxID_PROPERTIES", "wxID_REDO", "wxID_REFRESH", "wxID_REMOVE", "wxID_REPLACE", "wxID_REPLACE_ALL", "wxID_RESET", "wxID_RESIZE_FRAME", "wxID_RESTORE_FRAME", "wxID_RETRY", "wxID_REVERT", "wxID_REVERT_TO_SAVED", "wxID_SAVE", "wxID_SAVEAS", "wxID_SELECTALL", "wxID_SELECT_COLOR", "wxID_SELECT_FONT", "wxID_SEPARATOR", "wxID_SETUP", "wxID_SORT_ASCENDING", "wxID_SORT_DESCENDING", "wxID_SPELL_CHECK", "wxID_STATIC", "wxID_STOP", "wxID_STRIKETHROUGH", "wxID_SYSTEM_MENU", "wxID_TOP", "wxID_UNDELETE", "wxID_UNDERLINE", "wxID_UNDO", "wxID_UNINDENT", "wxID_UP", "wxID_VIEW_DETAILS", "wxID_VIEW_LARGEICONS", "wxID_VIEW_LIST", "wxID_VIEW_SMALLICONS", "wxID_VIEW_SORTDATE", "wxID_VIEW_SORTNAME", "wxID_VIEW_SORTSIZE", "wxID_VIEW_SORTTYPE", "wxID_YES", "wxID_YESTOALL", "wxID_ZOOM_100", "wxID_ZOOM_FIT", "wxID_ZOOM_IN", "wxID_ZOOM_OUT", }; // clang-format on
22.506849
115
0.602252
KeyWorksRW
9f49c7a5b74af2b4895012b19f979731cdb85e87
882
hpp
C++
Library/Deps/MessagePack/Include/msgpack/v2/adaptor/nil_decl.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
Library/Deps/MessagePack/Include/msgpack/v2/adaptor/nil_decl.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
Library/Deps/MessagePack/Include/msgpack/v2/adaptor/nil_decl.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
// // MessagePack for C++ static resolution routine // // Copyright (C) 2008-2016 FURUHASHI Sadayuki and KONDO Takatoshi // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef MSGPACK_V2_TYPE_NIL_DECL_HPP #define MSGPACK_V2_TYPE_NIL_DECL_HPP #include "msgpack/v1/adaptor/nil_decl.hpp" namespace msgpack { /// @cond MSGPACK_API_VERSION_NAMESPACE(v2) { /// @endcond namespace type { using v1::type::nil_t; #if defined(MSGPACK_USE_LEGACY_NIL) typedef nil_t nil; #endif // defined(MSGPACK_USE_LEGACY_NIL) using v1::type::operator<; using v1::type::operator==; } // namespace type /// @cond } // MSGPACK_API_VERSION_NAMESPACE(v2) /// @endcond } // namespace msgpack #endif // MSGPACK_V2_TYPE_NIL_DECL_HPP
20.511628
66
0.701814
rneogns
9f501130ee9ec309f963f799258da5453751b003
155
cpp
C++
C++/subtracao.cpp
alinemarchiori/NEPS_Exercises_Solved
429402c6a86f64d54b80bf965f9ec3e95a5e5db8
[ "MIT" ]
null
null
null
C++/subtracao.cpp
alinemarchiori/NEPS_Exercises_Solved
429402c6a86f64d54b80bf965f9ec3e95a5e5db8
[ "MIT" ]
null
null
null
C++/subtracao.cpp
alinemarchiori/NEPS_Exercises_Solved
429402c6a86f64d54b80bf965f9ec3e95a5e5db8
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int n, m, resultado; cin >> n; cin >> m; resultado=n-m; cout << resultado << endl; return 0; }
12.916667
27
0.619355
alinemarchiori
9f527ae3a9e3cc87fc724c86a3c08884f97f8c7b
51
cpp
C++
src/dna_block.cpp
dyigitpolat/relaxase
bb183197b48ca448afe71cb801c9cdafb8d418a1
[ "MIT" ]
1
2020-10-22T11:27:51.000Z
2020-10-22T11:27:51.000Z
src/dna_block.cpp
dyigitpolat/relaxase
bb183197b48ca448afe71cb801c9cdafb8d418a1
[ "MIT" ]
null
null
null
src/dna_block.cpp
dyigitpolat/relaxase
bb183197b48ca448afe71cb801c9cdafb8d418a1
[ "MIT" ]
null
null
null
#include "dna_block.hpp" DNABlock::DNABlock() { }
8.5
24
0.686275
dyigitpolat
9f542b5f07245ea8acda91d4cbc1761ec9aa5684
1,415
hpp
C++
examples_tf2/include/examples_tf2/listener.hpp
ROBOTIS-Platform/ros2_examples
5b1cfff84c7d6baaaee5239a717475c65f8a7a90
[ "Apache-2.0" ]
10
2019-08-13T01:41:34.000Z
2021-12-06T14:11:17.000Z
examples_tf2/include/examples_tf2/listener.hpp
ROBOTIS-Platform/ros2_examples
5b1cfff84c7d6baaaee5239a717475c65f8a7a90
[ "Apache-2.0" ]
4
2019-09-29T22:53:18.000Z
2020-11-08T23:29:17.000Z
examples_tf2/include/examples_tf2/listener.hpp
ROBOTIS-Platform/ros2_examples
5b1cfff84c7d6baaaee5239a717475c65f8a7a90
[ "Apache-2.0" ]
2
2020-09-25T13:12:35.000Z
2021-12-06T14:11:18.000Z
/******************************************************************************* * Copyright 2019 ROBOTIS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* Authors: Darby Lim, Pyo */ #ifndef EXAMPLES_TF2_LISTENER_HPP_ #define EXAMPLES_TF2_LISTENER_HPP_ #include <cmath> #include <string> #include <geometry_msgs/msg/transform_stamped.hpp> #include <rclcpp/rclcpp.hpp> #include <tf2/LinearMath/Transform.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2_ros/transform_listener.h> #define RAD_TO_DEG 180/M_PI #define DEG_TO_RAD M_PI/180 namespace robotis { class Listener : public rclcpp::Node { public: explicit Listener(); private: rclcpp::TimerBase::SharedPtr timer_; tf2_ros::Buffer tf_buffer_; tf2_ros::TransformListener tf_listener_; }; } // robotis #endif // EXAMPLES_TF2_LISTENER_HPP_
28.877551
80
0.681979
ROBOTIS-Platform