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
109
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
48.5k
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
068f41ee5c4d1a547e30fde1bd45ff15e98483af
2,335
cpp
C++
ch13-02-single-segment/src/main.cpp
pulpobot/C-SFML-html5-animation
14154008b853d1235e8ca35a5b23b6a70366f914
[ "MIT" ]
73
2017-12-14T00:33:23.000Z
2022-02-09T12:04:52.000Z
ch13-02-single-segment/src/main.cpp
threaderic/C-SFML-html5-animation
22f302cdf7c7c00247609da30e1bcf472d134583
[ "MIT" ]
null
null
null
ch13-02-single-segment/src/main.cpp
threaderic/C-SFML-html5-animation
22f302cdf7c7c00247609da30e1bcf472d134583
[ "MIT" ]
5
2017-12-26T03:30:07.000Z
2020-07-05T04:58:24.000Z
#include <iostream> #include "SFML\Graphics.hpp" #include "Segment.h" #include "Utils.h" #include "Slider.h" void OnHandleMoveCallback(Slider *slider){ slider->handle.setPosition(slider->background.getPosition().x, slider->handleY + slider->background.getPosition().y); } int main() { //You can turn off antialiasing if your graphics card doesn't support it sf::ContextSettings context; context.antialiasingLevel = 4; sf::RenderWindow window(sf::VideoMode(400, 400), "Single Segment", sf::Style::Titlebar | sf::Style::Close, context); window.setFramerateLimit(60); sf::Font font; if(!font.loadFromFile("res/cour.ttf")){ std::cerr << "Error loading cour.ttf file" << std::endl; return -1; } sf::Text infoText; infoText.setFont(font); infoText.setCharacterSize(15); infoText.setFillColor(sf::Color::Black); infoText.setPosition(sf::Vector2f(10,window.getSize().y - 30)); infoText.setString("Press and drag slider handle with mouse."); Segment segment = Segment(100, 20); segment.SetX(100); segment.SetY(100); Slider slider = Slider(-90,90,0); slider.SetX(300); slider.SetY(20); slider.onChange = &OnHandleMoveCallback; bool mouseOnSlider = false; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { sf::Vector2f mousePos; switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::MouseButtonPressed: mousePos = sf::Vector2f(event.mouseButton.x, event.mouseButton.y); slider.CaptureMouse(mousePos); break; case sf::Event::MouseButtonReleased: slider.OnMouseRelease(); break; case sf::Event::MouseMoved: mousePos = sf::Vector2f(event.mouseMove.x, event.mouseMove.y); slider.OnMouseMove(mousePos); break; } } segment.SetRotation(slider.value); window.clear(sf::Color::White); segment.Draw(window); slider.Draw(window); window.draw(infoText); window.display(); } }
32.430556
121
0.582441
pulpobot
06985a43292318fac4c3ffbe711bfb3098f0548c
1,192
hpp
C++
include/mold/domain/mustache/parser.hpp
duzy/mold
52a813bf2858e9719b89b1250702c82be4c2a78d
[ "BSL-1.0" ]
7
2016-10-02T13:29:55.000Z
2022-02-06T09:21:00.000Z
include/mold/domain/mustache/parser.hpp
extbit/mold
68cc3dd815c4e7a39ab5f68f7525a6c36a1e036f
[ "BSL-1.0" ]
1
2020-06-09T01:26:21.000Z
2020-06-09T01:26:21.000Z
include/mold/domain/mustache/parser.hpp
extbit/mold
68cc3dd815c4e7a39ab5f68f7525a6c36a1e036f
[ "BSL-1.0" ]
2
2019-09-08T05:30:31.000Z
2020-08-27T13:03:49.000Z
/** * \file boost/mold/domain/mustache/grammar.hpp * * Copyright 2016~2019 Duzy Chan <code@extbit.io>, ExtBit Limited * * 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 _BOOST_MOLD_DOMAIN_MUSTACHE_PARSER_HPP_ #define _BOOST_MOLD_DOMAIN_MUSTACHE_PARSER_HPP_ 1 #include <mold/domain/mustache/ast.hpp> #include <boost/spirit/home/x3/support/traits/is_variant.hpp> #include <boost/spirit/home/x3/support/traits/tuple_traits.hpp> #include <boost/spirit/home/x3/nonterminal/rule.hpp> namespace mold { namespace domain { namespace mustache { namespace parser { namespace x3 = boost::spirit::x3; using mustache_type = x3::rule<struct mustache_class, ast::node_list>; BOOST_SPIRIT_DECLARE(mustache_type) } const parser::mustache_type &spec(); }}} // namespace mold::domain::mustache #define BOOST_MOLD_MUSTACHE_INSTANTIATE(iterator_type) \ namespace mold { namespace domain { namespace mustache { namespace parser \ { BOOST_SPIRIT_INSTANTIATE(mustache_type, iterator_type, ::mold::value) }}}} #endif//_BOOST_MOLD_DOMAIN_MUSTACHE_PARSER_HPP_
36.121212
80
0.765101
duzy
069917eabac71dc9c402d5ee286ea3ee8ea2d6e0
15,795
cpp
C++
sycl/source/detail/program_manager/program_manager.cpp
Ralender/sycl
1fcd1e6d3da10024be92148501aced30ae3aa2be
[ "Apache-2.0" ]
1
2020-09-25T23:33:05.000Z
2020-09-25T23:33:05.000Z
sycl/source/detail/program_manager/program_manager.cpp
Ralender/sycl
1fcd1e6d3da10024be92148501aced30ae3aa2be
[ "Apache-2.0" ]
null
null
null
sycl/source/detail/program_manager/program_manager.cpp
Ralender/sycl
1fcd1e6d3da10024be92148501aced30ae3aa2be
[ "Apache-2.0" ]
null
null
null
//==------ program_manager.cpp --- SYCL program manager---------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <CL/sycl/context.hpp> #include <CL/sycl/detail/common.hpp> #include <CL/sycl/detail/os_util.hpp> #include <CL/sycl/detail/program_manager/program_manager.hpp> #include <CL/sycl/detail/util.hpp> #include <CL/sycl/device.hpp> #include <CL/sycl/exception.hpp> #include <CL/sycl/stl.hpp> #include <boost/container_hash/hash.hpp> // uuid_hasher #include <boost/uuid/uuid_generators.hpp> // sha name_gen/generator #include <boost/uuid/uuid_io.hpp> // uuid to_string #include <assert.h> #include <cstdlib> #include <fstream> #include <memory> #include <mutex> #include <sstream> namespace cl { namespace sycl { namespace detail { static constexpr int DbgProgMgr = 0; ProgramManager &ProgramManager::getInstance() { // The singleton ProgramManager instance, uses the "magic static" idiom. static ProgramManager Instance; return Instance; } static RT::PiDevice getFirstDevice(RT::PiContext Context) { cl_uint NumDevices = 0; PI_CALL(RT::piContextGetInfo(Context, PI_CONTEXT_INFO_NUM_DEVICES, sizeof(NumDevices), &NumDevices, /*param_value_size_ret=*/nullptr)); assert(NumDevices > 0 && "Context without devices?"); vector_class<RT::PiDevice> Devices(NumDevices); size_t ParamValueSize = 0; PI_CALL(RT::piContextGetInfo(Context, PI_CONTEXT_INFO_DEVICES, sizeof(cl_device_id) * NumDevices, &Devices[0], &ParamValueSize)); assert(ParamValueSize == sizeof(cl_device_id) * NumDevices && "Number of CL_CONTEXT_DEVICES should match CL_CONTEXT_NUM_DEVICES."); return Devices[0]; } static RT::PiProgram createBinaryProgram(const RT::PiContext Context, const unsigned char *Data, size_t DataLen) { // FIXME: we don't yet support multiple devices with a single binary. #ifndef _NDEBUG cl_uint NumDevices = 0; PI_CALL(RT::piContextGetInfo(Context, PI_CONTEXT_INFO_NUM_DEVICES, sizeof(NumDevices), &NumDevices, /*param_value_size_ret=*/nullptr)); assert(NumDevices > 0 && "Only a single device is supported for AOT compilation"); #endif RT::PiDevice Device = getFirstDevice(Context); RT::PiResult Err = PI_SUCCESS; pi_int32 BinaryStatus = CL_SUCCESS; RT::PiProgram Program; PI_CALL((Program = RT::piclProgramCreateWithBinary( Context, 1 /*one binary*/, &Device, &DataLen, &Data, &BinaryStatus, &Err), Err)); return Program; } static RT::PiProgram createSpirvProgram(const RT::PiContext Context, const unsigned char *Data, size_t DataLen) { RT::PiResult Err = PI_SUCCESS; RT::PiProgram Program; PI_CALL((Program = pi::pi_cast<pi_program>( pi::piProgramCreate(pi::pi_cast<pi_context>(Context), Data, DataLen, pi::pi_cast<pi_result *>(&Err))), Err)); return Program; } RT::PiProgram ProgramManager::getBuiltOpenCLProgram(OSModuleHandle M, const context &Context) { RT::PiProgram &Program = m_CachedSpirvPrograms[std::make_pair(Context, M)]; if (!Program) { DeviceImage *Img = nullptr; Program = loadProgram(M, Context, &Img); build(Program, Img->BuildOptions); } return Program; } // Gets a unique name to a kernel name which is currently computed from a SHA-1 // hash of the kernel name. This unique name is used in place of the kernels // mangled name inside of xocc computed binaries containing the kernels. // // This is in part due to a limitation of xocc in which it requires kernel names // to be passed to it when compiling kernels and it doesn't handle certain // characters in mangled names very well e.g. '$'. static std::string getUniqueName(const char *KernelName) { boost::uuids::name_generator_latest gen{boost::uuids::ns::dns()}; boost::uuids::uuid udoc = gen(KernelName); boost::hash<boost::uuids::uuid> uuid_hasher; std::size_t uuid_hash_value = uuid_hasher(udoc); return "xSYCL" + std::to_string(uuid_hash_value); } RT::PiKernel ProgramManager::getOrCreateKernel(OSModuleHandle M, const context &Context, const string_class &KernelName) { /// \todo: Extend this to work for more than the first device in the context /// most of the run-time only works with a single device right now, but this /// should be changed long term. /// \todo: This works at the moment, but there needs to be a change earlier on /// in the runtime to exchange the real kernel name with the hashed kernel /// name so the hashed variant is always used when its a Xilinx device. auto Devices = Context.get_devices(); std::string uniqueName = KernelName; if (!Devices.empty() && Devices[0].get_info<info::device::vendor>() == "Xilinx") uniqueName = getUniqueName(uniqueName.c_str()); if (DbgProgMgr > 0) { std::cerr << ">>> ProgramManager::getOrCreateKernel(" << M << ", " << getRawSyclObjImpl(Context) << ", " << uniqueName << ")\n"; } RT::PiProgram Program = getBuiltOpenCLProgram(M, Context); std::map<string_class, RT::PiKernel> &KernelsCache = m_CachedKernels[Program]; RT::PiKernel &Kernel = KernelsCache[uniqueName]; if (!Kernel) { RT::PiResult Err = PI_SUCCESS; PI_CALL((Kernel = RT::piKernelCreate( Program, uniqueName.c_str(), &Err), Err)); } return Kernel; } RT::PiProgram ProgramManager::getClProgramFromClKernel(RT::PiKernel Kernel) { RT::PiProgram Program; PI_CALL(RT::piKernelGetInfo( Kernel, CL_KERNEL_PROGRAM, sizeof(cl_program), &Program, nullptr)); return Program; } void ProgramManager::build(RT::PiProgram &Program, const string_class &Options, std::vector<RT::PiDevice> Devices) { if (DbgProgMgr > 0) { std::cerr << ">>> ProgramManager::build(" << Program << ", " << Options << ", ... " << Devices.size() << ")\n"; } const char *Opts = std::getenv("SYCL_PROGRAM_BUILD_OPTIONS"); for (const auto &DeviceId : Devices) { if (!createSyclObjFromImpl<device>(std::make_shared<device_impl_pi>(DeviceId)). get_info<info::device::is_compiler_available>()) { throw feature_not_supported( "Online compilation is not supported by this device"); } } if (!Opts) Opts = Options.c_str(); if (PI_CALL_RESULT(RT::piProgramBuild( Program, Devices.size(), Devices.data(), Opts, nullptr, nullptr)) == PI_SUCCESS) return; // Get OpenCL build log and add it to the exception message. size_t Size = 0; PI_CALL(RT::piProgramGetInfo( Program, CL_PROGRAM_DEVICES, 0, nullptr, &Size)); std::vector<RT::PiDevice> DevIds(Size / sizeof(RT::PiDevice)); PI_CALL(RT::piProgramGetInfo( Program, CL_PROGRAM_DEVICES, Size, DevIds.data(), nullptr)); std::string Log; for (RT::PiDevice &DevId : DevIds) { PI_CALL(RT::piProgramGetBuildInfo( Program, DevId, CL_PROGRAM_BUILD_LOG, 0, nullptr, &Size)); std::vector<char> BuildLog(Size); PI_CALL(RT::piProgramGetBuildInfo( Program, DevId, CL_PROGRAM_BUILD_LOG, Size, BuildLog.data(), nullptr)); device Dev = createSyclObjFromImpl<device>( std::make_shared<device_impl_pi>(DevId)); Log += "\nBuild program fail log for '" + Dev.get_info<info::device::name>() + "':\n" + BuildLog.data(); } throw compile_program_error(Log.c_str()); } bool ProgramManager::ContextAndModuleLess:: operator()(const std::pair<context, OSModuleHandle> &LHS, const std::pair<context, OSModuleHandle> &RHS) const { if (LHS.first != RHS.first) return getRawSyclObjImpl(LHS.first) < getRawSyclObjImpl(RHS.first); return reinterpret_cast<intptr_t>(LHS.second) < reinterpret_cast<intptr_t>(RHS.second); } void ProgramManager::addImages(pi_device_binaries DeviceBinary) { std::lock_guard<std::mutex> Guard(Sync::getGlobalLock()); for (int I = 0; I < DeviceBinary->NumDeviceBinaries; I++) { pi_device_binary Img = &(DeviceBinary->DeviceBinaries[I]); OSModuleHandle M = OSUtil::getOSModuleHandle(Img); auto &Imgs = m_DeviceImages[M]; if (Imgs == nullptr) Imgs.reset(new std::vector<DeviceImage *>()); Imgs->push_back(Img); } } void ProgramManager::debugDumpBinaryImage(const DeviceImage *Img) const { std::cerr << " --- Image " << Img << "\n"; if (!Img) return; std::cerr << " Version : " << (int)Img->Version << "\n"; std::cerr << " Kind : " << (int)Img->Kind << "\n"; std::cerr << " Format : " << (int)Img->Format << "\n"; std::cerr << " Target : " << Img->DeviceTargetSpec << "\n"; std::cerr << " Options : " << (Img->BuildOptions ? Img->BuildOptions : "NULL") << "\n"; std::cerr << " Bin size : " << ((intptr_t)Img->BinaryEnd - (intptr_t)Img->BinaryStart) << "\n"; } void ProgramManager::debugDumpBinaryImages() const { for (const auto &ModImgvec : m_DeviceImages) { std::cerr << " ++++++ Module: " << ModImgvec.first << "\n"; for (const auto *Img : *(ModImgvec.second)) { debugDumpBinaryImage(Img); } } } struct ImageDeleter { void operator()(DeviceImage *I) { delete[] I->BinaryStart; delete I; } }; RT::PiProgram ProgramManager::loadProgram(OSModuleHandle M, const context &Context, DeviceImage **I) { std::lock_guard<std::mutex> Guard(Sync::getGlobalLock()); if (DbgProgMgr > 0) { std::cerr << ">>> ProgramManager::loadProgram(" << M << "," << getRawSyclObjImpl(Context) << ")\n"; } DeviceImage *Img = nullptr; bool UseKernelSpv = false; const std::string UseSpvEnv("SYCL_USE_KERNEL_SPV"); if (const char *Spv = std::getenv(UseSpvEnv.c_str())) { // The env var requests that the program is loaded from a SPIRV file on disk UseKernelSpv = true; std::string Fname(Spv); std::ifstream File(Fname, std::ios::binary); if (!File.is_open()) { throw runtime_error(std::string("Can't open file specified via ") + UseSpvEnv + ": " + Fname); } File.seekg(0, std::ios::end); size_t Size = File.tellg(); auto *Data = new unsigned char[Size]; File.seekg(0); File.read(reinterpret_cast<char *>(Data), Size); File.close(); if (!File.good()) { delete[] Data; throw runtime_error(std::string("read from ") + Fname + std::string(" failed")); } Img = new DeviceImage(); Img->Version = PI_DEVICE_BINARY_VERSION; Img->Kind = PI_DEVICE_BINARY_OFFLOAD_KIND_SYCL; Img->Format = PI_DEVICE_BINARY_TYPE_NONE; Img->DeviceTargetSpec = PI_DEVICE_BINARY_TARGET_UNKNOWN; Img->BuildOptions = ""; Img->ManifestStart = nullptr; Img->ManifestEnd = nullptr; Img->BinaryStart = Data; Img->BinaryEnd = Data + Size; Img->EntriesBegin = nullptr; Img->EntriesEnd = nullptr; std::unique_ptr<DeviceImage, ImageDeleter> ImgPtr(Img, ImageDeleter()); m_OrphanDeviceImages.emplace_back(std::move(ImgPtr)); if (DbgProgMgr > 0) { std::cerr << "loaded device image from " << Fname << "\n"; } } else { // Take all device images in module M and ask the native runtime under the // given context to choose one it prefers. auto ImgIt = m_DeviceImages.find(M); if (ImgIt == m_DeviceImages.end()) { throw runtime_error("No device program image found"); } std::vector<DeviceImage *> *Imgs = (ImgIt->second).get(); PI_CALL(RT::piextDeviceSelectBinary( 0, Imgs->data(), (cl_uint)Imgs->size(), &Img)); if (DbgProgMgr > 0) { std::cerr << "available device images:\n"; debugDumpBinaryImages(); std::cerr << "selected device image: " << Img << "\n"; debugDumpBinaryImage(Img); } } // perform minimal sanity checks on the device image and the descriptor if (Img->BinaryEnd < Img->BinaryStart) { throw runtime_error("Malformed device program image descriptor"); } if (Img->BinaryEnd == Img->BinaryStart) { throw runtime_error("Invalid device program image: size is zero"); } size_t ImgSize = static_cast<size_t>(Img->BinaryEnd - Img->BinaryStart); auto Format = pi::pi_cast<RT::PiDeviceBinaryType>(Img->Format); // Determine the format of the image if not set already if (Format == PI_DEVICE_BINARY_TYPE_NONE) { struct { RT::PiDeviceBinaryType Fmt; const uint32_t Magic; } Fmts[] = {{PI_DEVICE_BINARY_TYPE_SPIRV, 0x07230203}, {PI_DEVICE_BINARY_TYPE_LLVMIR_BITCODE, 0xDEC04342}}; if (ImgSize >= sizeof(Fmts[0].Magic)) { std::remove_const<decltype(Fmts[0].Magic)>::type Hdr = 0; std::copy(Img->BinaryStart, Img->BinaryStart + sizeof(Hdr), reinterpret_cast<char *>(&Hdr)); for (const auto &Fmt : Fmts) { if (Hdr == Fmt.Magic) { Format = Fmt.Fmt; // Image binary format wasn't set but determined above - update it; if (UseKernelSpv) { Img->Format = Format; } else { // TODO the binary image is a part of the fat binary, the clang // driver should have set proper format option to the // clang-offload-wrapper. The fix depends on AOT compilation // implementation, so will be implemented together with it. // Img->Format can't be updated as it is inside of the in-memory // OS module binary. // throw runtime_error("Image format not set"); } if (DbgProgMgr > 1) { std::cerr << "determined image format: " << (int)Format << "\n"; } break; } } } } // Dump program image if requested if (std::getenv("SYCL_DUMP_IMAGES") && !UseKernelSpv) { std::string Fname("sycl_"); Fname += Img->DeviceTargetSpec; std::string Ext; if (Format == PI_DEVICE_BINARY_TYPE_SPIRV) { Ext = ".spv"; } else if (Format == PI_DEVICE_BINARY_TYPE_LLVMIR_BITCODE) { Ext = ".bc"; } else { Ext = ".bin"; } Fname += Ext; std::ofstream F(Fname, std::ios::binary); if (!F.is_open()) { throw runtime_error(std::string("Can not write ") + Fname); } F.write(reinterpret_cast<const char *>(Img->BinaryStart), ImgSize); F.close(); } // Load the selected image const RT::PiContext &Ctx = getRawSyclObjImpl(Context)->getHandleRef(); RT::PiProgram Res = nullptr; Res = Format == PI_DEVICE_BINARY_TYPE_SPIRV ? createSpirvProgram(Ctx, Img->BinaryStart, ImgSize) : createBinaryProgram(Ctx, Img->BinaryStart, ImgSize); if (I) *I = Img; if (DbgProgMgr > 1) { std::cerr << "created native program: " << Res << "\n"; } return Res; } } // namespace detail } // namespace sycl } // namespace cl extern "C" void __tgt_register_lib(pi_device_binaries desc) { cl::sycl::detail::ProgramManager::getInstance().addImages(desc); } // Executed as a part of current module's (.exe, .dll) static initialization extern "C" void __tgt_unregister_lib(pi_device_binaries desc) { // TODO implement the function }
36.394009
83
0.628807
Ralender
069ce545b7142abfb5d8fb450aa5255937f6ae1c
1,772
cpp
C++
Modules/MitkExt/Testing/mitkSurfaceToImageFilterTest.cpp
rfloca/MITK
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
[ "BSD-3-Clause" ]
null
null
null
Modules/MitkExt/Testing/mitkSurfaceToImageFilterTest.cpp
rfloca/MITK
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
[ "BSD-3-Clause" ]
null
null
null
Modules/MitkExt/Testing/mitkSurfaceToImageFilterTest.cpp
rfloca/MITK
b7dcb830dc36a5d3011b9828c3d71e496d3936ad
[ "BSD-3-Clause" ]
null
null
null
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkIOUtil.h> #include "mitkSurfaceToImageFilter.h" #include <vtkPolyData.h> int mitkSurfaceToImageFilterTest(int argc, char* argv[]) { MITK_TEST_BEGIN( "mitkSurfaceToImageFilterTest"); mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); mitk::Surface::Pointer inputSurface = mitk::IOUtil::LoadSurface( std::string(argv[1]) ); //todo I don't know if this image is always needed. There is no documentation of the filter. Use git blame and ask the author. mitk::Image::Pointer additionalInputImage = mitk::Image::New(); additionalInputImage->Initialize( mitk::MakeScalarPixelType<unsigned int>(), *inputSurface->GetGeometry()); //Arrange the filter //The docu does not really tell if this is always needed. Could we skip SetImage in any case? surfaceToImageFilter->MakeOutputBinaryOn(); surfaceToImageFilter->SetInput(inputSurface); surfaceToImageFilter->SetImage(additionalInputImage); surfaceToImageFilter->Update(); MITK_TEST_CONDITION_REQUIRED( surfaceToImageFilter->GetOutput()->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR, "SurfaceToImageFilter_AnyInputImageAndModeSetToBinary_ResultIsImageWithUCHARPixelType"); MITK_TEST_END(); }
37.702128
217
0.727991
rfloca
069e66fc88cbf726fc258b498a056d146fcd611a
370
cpp
C++
docs/examples/problems/addition/submissions/js.cpp
bilsen/omogenexec
331f8e4ac48a190de289b5e1737741bac0d7a09a
[ "MIT" ]
null
null
null
docs/examples/problems/addition/submissions/js.cpp
bilsen/omogenexec
331f8e4ac48a190de289b5e1737741bac0d7a09a
[ "MIT" ]
null
null
null
docs/examples/problems/addition/submissions/js.cpp
bilsen/omogenexec
331f8e4ac48a190de289b5e1737741bac0d7a09a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int add(int a, int b) { if (a == 0) return b; int what[1000]; what[0] = add(a - 1, b + 1); what[1] = add(0, -10); what[2] = add(0, 10); return what[0] + what[1] + what[2]; } int main() { int a, b; cin >> a >> b; if (a + b <= 2000) { cout << add(a, b) << endl; } else { cout << a + b << endl; } }
16.086957
37
0.472973
bilsen
069e6fe49b5580546b2126a25991a5c1c243a6be
3,403
cpp
C++
ArrayList/ArrayList/ArrayListLib.cpp
UnicornMane/spbu-homework1
665c71cfa1e37a5b88fb1d58ad0070842d0b6b2b
[ "Apache-2.0" ]
null
null
null
ArrayList/ArrayList/ArrayListLib.cpp
UnicornMane/spbu-homework1
665c71cfa1e37a5b88fb1d58ad0070842d0b6b2b
[ "Apache-2.0" ]
null
null
null
ArrayList/ArrayList/ArrayListLib.cpp
UnicornMane/spbu-homework1
665c71cfa1e37a5b88fb1d58ad0070842d0b6b2b
[ "Apache-2.0" ]
null
null
null
#include "ArrayListLib.h" #include <iostream> void ArrayList::expand(int count) { int* newdata = new int[count + this->capacity]; for (int i = 0; i < this->capacity; ++i) { newdata[i] = this->data[i]; } delete[] this->data; this->data = newdata; this->capacity += count; } void ArrayList::swap(int posi, int posj) { int tmp = this->data[posi]; this->data[posi] = this->data[posj]; this->data[posj] = tmp; } int ArrayList::ind(int index) { if (index < 0) { pushbegin(0); return 0; } if (index >= this->count) { pushend(0); return this->count - 1; } return index; } ArrayList::ArrayList(int capacity) { this->capacity = capacity; this->count = 0; this->data = new int[capacity]; } ArrayList::ArrayList(const ArrayList& list) { this->capacity = list.count; this->count = list.count; this->data = new int[list.count]; for (int i = 0; i < list.count; ++i) { this->data[i] = list.data[i]; } } ArrayList::~ArrayList() { for (int i = 0; i < this->capacity; ++i) { this->data[i] = 0; } this->count = 0; this->capacity = 0; delete[] this->data; } int ArrayList::size() { return this->count; } void ArrayList::pushend(int element) { if (this->count == this->capacity) { expand(this->capacity); } this->data[this->count] = element; this->count++; } void ArrayList::insert(int element, int position) { if (this->count == this->capacity) { expand(this->capacity); } this->count++; for (int i = this->count - 1; i > position; --i) { this->data[i] = this->data[i - 1]; } this->data[position] = element; } void ArrayList::pushbegin(int element) { this->insert(element, 0); } int ArrayList::extract(int position) { int ans = this->data[position]; this->count--; for (int i = position; i < this->count; ++i) { this->data[i] = this->data[i + 1]; } this->data[this->count] = 0; return ans; } int ArrayList::extractbegin() { return extract(0); } int ArrayList::extractend() { this->count--; int tmp = this->data[this->count]; this->data[this->count] = 0; return tmp; } int& ArrayList::operator[](int pos) { return data[ind(pos)]; } ArrayList merge(ArrayList l, ArrayList r) { if (l.size() == 0) { return r; } else if (r.size() == 0) { return l; } ArrayList ans(l.size() + r.size()); int i = 0; int j = 0; while ((i != l.size()) || (j != r.size())) { if ((j == r.size()) || ((i != l.size()) && (l[i] <= r[j]))) { ans.pushend(l[i]); i++; } else { ans.pushend(r[j]); j++; } } return ans; } ArrayList quickSort(ArrayList arr) { int l = 0; int r = arr.size(); if (r - l == 1) { ArrayList tmp(1); tmp.pushend(arr[l]); return tmp; } int mid = ((l + r) >> 1); ArrayList arr_l(mid); ArrayList arr_r(r - mid); for (int i = 0; i < mid; ++i) { arr_l.pushend(arr[i]); } for (int i = mid; i < r; ++i) { arr_r.pushend(arr[i]); } return merge(quickSort(arr_l), quickSort(arr_r)); } void ArrayList::sort() { ArrayList tmp(quickSort(*this)); for (int i = 0; i < tmp.count; ++i) { this->data[i] = tmp.data[i]; } } std::ostream& operator<<(std::ostream& stream, ArrayList& list) { stream << "[" << list.count << "/" << list.capacity << "] {"; if (list.count == 0) { stream << "EMPTY"; } else { for (int i = 0; i < list.count - 1; ++i) { stream << list.data[i] << ", "; } stream << list.data[list.count - 1]; } stream << "}"; return stream; }
15.610092
63
0.577432
UnicornMane
069e92ce79b2fd81b8500829e6ce9e536bfe2d3c
4,896
cpp
C++
include/delfem2/opengl/old/rigv3.cpp
mmer547/delfem2
4f4b28931c96467ac30948e6b3f83150ea530c92
[ "MIT" ]
1
2020-07-18T17:03:36.000Z
2020-07-18T17:03:36.000Z
include/delfem2/opengl/old/rigv3.cpp
mmer547/delfem2
4f4b28931c96467ac30948e6b3f83150ea530c92
[ "MIT" ]
null
null
null
include/delfem2/opengl/old/rigv3.cpp
mmer547/delfem2
4f4b28931c96467ac30948e6b3f83150ea530c92
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 Nobuyuki Umetani * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "delfem2/opengl/old/funcs.h" #include "delfem2/opengl/old/v3q.h" #include "delfem2/opengl/old/rigv3.h" #include "delfem2/rig_geo3.h" #if defined(_WIN32) // windows #define NOMINMAX // to remove min,max macro #include <windows.h> #endif #if defined(__APPLE__) && defined(__MACH__) // mac #define GL_SILENCE_DEPRECATION #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif #ifndef M_PI #define M_PI 3.1415926535 #endif // ------------------------------------------------------- DFM2_INLINE void delfem2::opengl::Draw_RigBone( int ibone, bool is_selected, [[maybe_unused]] int ielem_selected, const std::vector<CRigBone>& aBone, double rad_bone_sphere, [[maybe_unused]] double rad_rot_hndlr) { { // draw point if (is_selected) { ::glColor3d(0, 1, 1); } else { ::glColor3d(1, 0, 0); } const CVec3d pos = aBone[ibone].RootPosition(); delfem2::opengl::DrawSphereAt(32, 32, rad_bone_sphere, pos.x, pos.y, pos.z); } /* if(is_selected){ opengl::DrawHandlerRotation_Mat4(aBone[ibone].affmat3Global, rad_rot_hndlr, ielem_selected); int ibone_parent = aBone[ibone].ibone_parent; if( ibone_parent>=0&&ibone_parent<(int)aBone.size() ){ const CVec3d pp(aBone[ibone_parent].Pos()); } else{ } } */ } DFM2_INLINE void delfem2::opengl::DrawBone_Line( const std::vector<CRigBone>& aBone, int ibone_selected, int ielem_selected, double rad_bone_sphere, double rad_rot_hndlr) { glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); for(unsigned int iskel=0;iskel<aBone.size();++iskel){ const bool is_selected = (int)iskel==ibone_selected; Draw_RigBone(iskel, is_selected,ielem_selected,aBone, rad_bone_sphere,rad_rot_hndlr); } for(unsigned int ibone=0;ibone<aBone.size();++ibone){ const CRigBone& bone = aBone[ibone]; const int ibone_p = aBone[ibone].ibone_parent; if( ibone_p < 0 || ibone_p >= (int)aBone.size() ){ continue; } const CRigBone& bone_p = aBone[ibone_p]; bool is_selected_p = (ibone_p == ibone_selected); if(is_selected_p){ ::glColor3d(1.0,1.0,1.0); } // white if selected else{ ::glColor3d(0.0,0.0,0.0); } // black if not selected ::glBegin(GL_LINES); opengl::myGlVertex(bone.RootPosition()); opengl::myGlVertex(bone_p.RootPosition()); ::glEnd(); } } DFM2_INLINE void delfem2::opengl::DrawBone_Octahedron( const std::vector<CRigBone>& aBone, unsigned int ibone_selected, [[maybe_unused]] unsigned int ielem_selected, [[maybe_unused]] double rad_bone_sphere, [[maybe_unused]] double rad_rot_hndlr) { namespace dfm2 = delfem2; glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); /* for(unsigned int iskel=0;iskel<aBone.size();++iskel){ const bool is_selected = (iskel==ibone_selected); Draw_RigBone( iskel, is_selected,ielem_selected,aBone, rad_bone_sphere,rad_rot_hndlr); } */ for(unsigned int ibone=0;ibone<aBone.size();++ibone){ const CRigBone& bone = aBone[ibone]; const int ibone_p = aBone[ibone].ibone_parent; if( ibone_p < 0 || ibone_p >= (int)aBone.size() ){ continue; } const CRigBone& bone_p = aBone[ibone_p]; bool is_selected_p = (ibone_p == (int)ibone_selected); const CVec3d p0(bone_p.invBindMat[3], bone_p.invBindMat[7], bone_p.invBindMat[11]); const CVec3d p1(bone.invBindMat[3], bone.invBindMat[7], bone.invBindMat[11]); ::glPushMatrix(); double At[16]; dfm2::Transpose_Mat4(At,bone_p.affmat3Global); ::glMultMatrixd(At); ::glEnable(GL_LIGHTING); delfem2::opengl::DrawArrowOcta_FaceNrm( dfm2::CVec3d(0,0,0), p0-p1, 0.1, 0.2); // ::glDisable(GL_LIGHTING); if(is_selected_p){ ::glColor3d(1.0,1.0,1.0); } // white if selected else{ ::glColor3d(0.0,0.0,0.0); } // black if not selected delfem2::opengl::DrawArrowOcta_Edge( dfm2::CVec3d(0,0,0), p0-p1, 0.1, 0.2); /* delfem2::opengl::DrawArrow( dfm2::CVec3d(0,0,0), p0-p1); */ ::glPopMatrix(); } } DFM2_INLINE void delfem2::opengl::DrawJoints( const std::vector<double>& aJntPos, const std::vector<int>& aIndBoneParent) { for(unsigned int ib=0;ib<aJntPos.size()/3;++ib){ const double* p = aJntPos.data()+ib*3; ::glColor3d(0,0,1); ::glDisable(GL_LIGHTING); ::glDisable(GL_DEPTH_TEST); opengl::DrawSphereAt(8, 8, 0.01, p[0], p[1], p[2]); int ibp = aIndBoneParent[ib]; if( ibp == -1 ){ continue; } const double* pp = aJntPos.data()+ibp*3; ::glColor3d(0,0,0); ::glBegin(GL_LINES); ::glVertex3dv(p); ::glVertex3dv(pp); ::glEnd(); } }
30.222222
96
0.642565
mmer547
069efb2b5b3595ecabae8c74dbc4dd26699bb3b0
4,460
cpp
C++
src/68. Text Justification/main.cpp
sheepduke/leetcode
7808b3370e4c3e19b2b0bc2bcee62f659906c3eb
[ "MIT" ]
null
null
null
src/68. Text Justification/main.cpp
sheepduke/leetcode
7808b3370e4c3e19b2b0bc2bcee62f659906c3eb
[ "MIT" ]
null
null
null
src/68. Text Justification/main.cpp
sheepduke/leetcode
7808b3370e4c3e19b2b0bc2bcee62f659906c3eb
[ "MIT" ]
null
null
null
/* Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left justified and no extra space is inserted between words. Note: A word is defined as a character sequence consisting of non-space characters only. Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. The input array words contains at least one word. Example 1: Input: words = ["This", "is", "an", "example", "of", "text", "justification."] maxWidth = 16 Output: [ "This is an", "example of text", "justification. " ] Example 2: Input: words = ["What","must","be","acknowledgment","shall","be"] maxWidth = 16 Output: [ "What must be", "acknowledgment ", "shall be " ] Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified becase it contains only one word. Example 3: Input: words = ["Science","is","what","we","understand","well","enough","to","explain", "to","a","computer.","Art","is","everything","else","we","do"] maxWidth = 20 Output: [ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ] */ #include "../util/common.hpp" class Solution { public: vector<string> fullJustify(vector<string>& words, int max_width) { // Group the words into lines. auto lines = vector<vector<vector<string>::iterator>>{{}}; auto total_width = 0; for (auto it = begin(words); it != end(words); it++) { if (total_width + it->length() > max_width) { lines.push_back(vector<vector<string>::iterator>{it}); total_width = it->length() + 1; } else { lines.back().push_back(it); total_width += it->length() + 1; } } // For each line, justify the words. auto result = vector<string>(); for (auto it = begin(lines); it != end(lines); it++) { result.push_back(get_justified_string(*it, max_width, (it == end(lines) - 1 ? true : false))); } return result; } private: string get_justified_string(const vector<vector<string>::iterator> &iterators, int max_width, bool left_justified = false) { if (iterators.size() == 1) left_justified = true; stringstream ss; if (left_justified) { ss << *iterators.front(); auto width = iterators.front()->length(); for (auto word = next(begin(iterators)); word != end(iterators); word++) { ss << " " << **word; width += (*word)->length() + 1; } ss << string(max_width - width, ' '); } else { auto total_width = 0; for (auto it: iterators) { total_width += it->length(); } auto base_space_width = (max_width - total_width) / (iterators.size() - 1); auto extra_sapce_count = (max_width - total_width) % (iterators.size() - 1); ss << *iterators.front(); for (auto itt = begin(iterators) + 1; itt != end(iterators); itt++) { auto space_count = base_space_width; if (extra_sapce_count > 0) { space_count++; extra_sapce_count--; } ss << string(space_count, ' '); ss << **itt; } } return ss.str(); } }; void run(vector<string> &words, int max_width) { cout << "Input: " << words << endl; auto result = Solution().fullJustify(words, max_width); cout << "Result: " << endl; for (auto line: result) { cout << "\"" << line << "\"" << endl; } } int main() { Solution solution; auto words = vector<string>{"This", "is", "an", "example", "of", "text", "justification."}; run(words, 16); words = {"What", "must", "be", "acknowledgment", "shall", "be"}; run(words, 16); return 0; }
30.135135
95
0.606054
sheepduke
06a061758728508aa54e85df8d53f1b10cb29e2e
8,069
cpp
C++
src/tut27/Engine/Engine/graphicsclass.cpp
Scillman/rastertek-dx11-tutorials
3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6
[ "Unlicense" ]
null
null
null
src/tut27/Engine/Engine/graphicsclass.cpp
Scillman/rastertek-dx11-tutorials
3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6
[ "Unlicense" ]
null
null
null
src/tut27/Engine/Engine/graphicsclass.cpp
Scillman/rastertek-dx11-tutorials
3aee1e19eaf6e4e8e9a44c88a83ac50acdcb05c6
[ "Unlicense" ]
1
2018-06-26T01:29:41.000Z
2018-06-26T01:29:41.000Z
//////////////////////////////////////////////////////////////////////////////// // Filename: graphicsclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "graphicsclass.h" GraphicsClass::GraphicsClass() { m_D3D = 0; m_Camera = 0; m_Model = 0; m_TextureShader = 0; m_RenderTexture = 0; m_FloorModel = 0; m_ReflectionShader = 0; } GraphicsClass::GraphicsClass(const GraphicsClass& other) { } GraphicsClass::~GraphicsClass() { } bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd) { bool result; // Create the Direct3D object. m_D3D = new D3DClass; if(!m_D3D) { return false; } // Initialize the Direct3D object. result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR); if(!result) { MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK); return false; } // Create the camera object. m_Camera = new CameraClass; if(!m_Camera) { return false; } // Create the model object. m_Model = new ModelClass; if(!m_Model) { return false; } // Initialize the model object. result = m_Model->Initialize(m_D3D->GetDevice(), L"../Engine/data/seafloor.dds", "../Engine/data/cube.txt"); if(!result) { MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK); return false; } // Create the texture shader object. m_TextureShader = new TextureShaderClass; if(!m_TextureShader) { return false; } // Initialize the texture shader object. result = m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the texture shader object.", L"Error", MB_OK); return false; } // Create the render to texture object. m_RenderTexture = new RenderTextureClass; if(!m_RenderTexture) { return false; } // Initialize the render to texture object. result = m_RenderTexture->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight); if(!result) { return false; } // Create the floor model object. m_FloorModel = new ModelClass; if(!m_FloorModel) { return false; } // Initialize the floor model object. result = m_FloorModel->Initialize(m_D3D->GetDevice(), L"../Engine/data/blue01.dds", "../Engine/data/floor.txt"); if(!result) { MessageBox(hwnd, L"Could not initialize the floor model object.", L"Error", MB_OK); return false; } // Create the reflection shader object. m_ReflectionShader = new ReflectionShaderClass; if(!m_ReflectionShader) { return false; } // Initialize the reflection shader object. result = m_ReflectionShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the reflection shader object.", L"Error", MB_OK); return false; } return true; } void GraphicsClass::Shutdown() { // Release the reflection shader object. if(m_ReflectionShader) { m_ReflectionShader->Shutdown(); delete m_ReflectionShader; m_ReflectionShader = 0; } // Release the floor model object. if(m_FloorModel) { m_FloorModel->Shutdown(); delete m_FloorModel; m_FloorModel = 0; } // Release the render to texture object. if(m_RenderTexture) { m_RenderTexture->Shutdown(); delete m_RenderTexture; m_RenderTexture = 0; } // Release the texture shader object. if(m_TextureShader) { m_TextureShader->Shutdown(); delete m_TextureShader; m_TextureShader = 0; } // Release the model object. if(m_Model) { m_Model->Shutdown(); delete m_Model; m_Model = 0; } // Release the camera object. if(m_Camera) { delete m_Camera; m_Camera = 0; } // Release the D3D object. if(m_D3D) { m_D3D->Shutdown(); delete m_D3D; m_D3D = 0; } return; } bool GraphicsClass::Frame() { // Set the position of the camera. m_Camera->SetPosition(0.0f, 0.0f, -10.0f); return true; } bool GraphicsClass::Render() { bool result; // Render the entire scene as a reflection to the texture first. result = RenderToTexture(); if(!result) { return false; } // Render the scene as normal to the back buffer. result = RenderScene(); if(!result) { return false; } return true; } bool GraphicsClass::RenderToTexture() { D3DXMATRIX worldMatrix, reflectionViewMatrix, projectionMatrix; static float rotation = 0.0f; // Set the render target to be the render to texture. m_RenderTexture->SetRenderTarget(m_D3D->GetDeviceContext(), m_D3D->GetDepthStencilView()); // Clear the render to texture. m_RenderTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), m_D3D->GetDepthStencilView(), 0.0f, 0.0f, 0.0f, 1.0f); // Use the camera to calculate the reflection matrix. m_Camera->RenderReflection(-1.5f); // Get the camera reflection view matrix instead of the normal view matrix. reflectionViewMatrix = m_Camera->GetReflectionViewMatrix(); // Get the world and projection matrices. m_D3D->GetWorldMatrix(worldMatrix); m_D3D->GetProjectionMatrix(projectionMatrix); // Update the rotation variable each frame. rotation += (float)D3DX_PI * 0.005f; if(rotation > 360.0f) { rotation -= 360.0f; } D3DXMatrixRotationY(&worldMatrix, rotation); // Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing. m_Model->Render(m_D3D->GetDeviceContext()); // Render the model using the texture shader and the reflection view matrix. m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, reflectionViewMatrix, projectionMatrix, m_Model->GetTexture()); // Reset the render target back to the original back buffer and not the render to texture anymore. m_D3D->SetBackBufferRenderTarget(); return true; } bool GraphicsClass::RenderScene() { D3DXMATRIX worldMatrix, viewMatrix, projectionMatrix, reflectionMatrix; bool result; static float rotation = 0.0f; // Clear the buffers to begin the scene. m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world, view, and projection matrices from the camera and d3d objects. m_D3D->GetWorldMatrix(worldMatrix); m_Camera->GetViewMatrix(viewMatrix); m_D3D->GetProjectionMatrix(projectionMatrix); // Update the rotation variable each frame. rotation += (float)D3DX_PI * 0.005f; if(rotation > 360.0f) { rotation -= 360.0f; } // Multiply the world matrix by the rotation. D3DXMatrixRotationY(&worldMatrix, rotation); // Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing. m_Model->Render(m_D3D->GetDeviceContext()); // Render the model with the texture shader. result = m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture()); if(!result) { return false; } // Get the world matrix again and translate down for the floor model to render underneath the cube. m_D3D->GetWorldMatrix(worldMatrix); D3DXMatrixTranslation(&worldMatrix, 0.0f, -1.5f, 0.0f); // Get the camera reflection view matrix. reflectionMatrix = m_Camera->GetReflectionViewMatrix(); // Put the floor model vertex and index buffers on the graphics pipeline to prepare them for drawing. m_FloorModel->Render(m_D3D->GetDeviceContext()); // Render the floor model using the reflection shader, reflection texture, and reflection view matrix. result = m_ReflectionShader->Render(m_D3D->GetDeviceContext(), m_FloorModel->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix, m_FloorModel->GetTexture(), m_RenderTexture->GetShaderResourceView(), reflectionMatrix); // Present the rendered scene to the screen. m_D3D->EndScene(); return true; }
24.451515
120
0.681125
Scillman
a628cd64c745f4515c57ae13c584c08c20132222
832
cpp
C++
extern/shiny/Main/MaterialInstancePass.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
4
2020-07-04T06:05:05.000Z
2022-02-14T22:53:27.000Z
extern/shiny/Main/MaterialInstancePass.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
extern/shiny/Main/MaterialInstancePass.cpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
1
2018-10-20T08:17:41.000Z
2018-10-20T08:17:41.000Z
#include "MaterialInstancePass.hpp" #include <fstream> namespace sh { MaterialInstanceTextureUnit* MaterialInstancePass::createTextureUnit (const std::string& name) { mTexUnits.push_back(MaterialInstanceTextureUnit(name)); return &mTexUnits.back(); } void MaterialInstancePass::save(std::ofstream &stream) { if (mShaderProperties.listProperties().size()) { stream << "\t\t" << "shader_properties" << '\n'; stream << "\t\t{\n"; mShaderProperties.save(stream, "\t\t\t"); stream << "\t\t}\n"; } PropertySetGet::save(stream, "\t\t"); for (std::vector <MaterialInstanceTextureUnit>::iterator it = mTexUnits.begin(); it != mTexUnits.end(); ++it) { stream << "\t\ttexture_unit " << it->getName() << '\n'; stream << "\t\t{\n"; it->save(stream, "\t\t\t"); stream << "\t\t}\n"; } } }
23.111111
95
0.635817
Bodillium
a62b718533981567bed358140f97ff07c7a0c58e
2,634
cpp
C++
src/ScoreEvaluation/VCValueEvaluator.cpp
AhmedSalemElhady/Scrabble-Game.ai
b75e19dac5f3096a82b4cbe54e9c66501b9a051b
[ "MIT" ]
8
2019-02-25T17:32:09.000Z
2022-02-25T04:00:40.000Z
src/ScoreEvaluation/VCValueEvaluator.cpp
AhmedSalemElhady/Scrabble-Game.ai
b75e19dac5f3096a82b4cbe54e9c66501b9a051b
[ "MIT" ]
2
2019-04-20T15:49:47.000Z
2019-04-28T16:48:55.000Z
src/ScoreEvaluation/VCValueEvaluator.cpp
AhmedSalemElhady/Scrabble-Game.ai
b75e19dac5f3096a82b4cbe54e9c66501b9a051b
[ "MIT" ]
9
2019-02-19T18:00:11.000Z
2021-01-26T16:36:26.000Z
#include "VCValueEvaluator.hpp" VCValueEvaluator::VCValueEvaluator(int bagSize, bool isEmptyBoard) : RackLeaveEvaluator(bagSize, isEmptyBoard) { } VCValueEvaluator::VCValueEvaluator(LoadHeuristics *heuristicsValues, std::vector<char> *opponentRack, int bagSize, bool isEmptyBoard) : RackLeaveEvaluator(heuristicsValues, bagSize, isEmptyBoard) { this->heuristicsValues = heuristicsValues; this->opponentRack = opponentRack; } double VCValueEvaluator::equity(std::vector<char> *Rack, Move *move) { if (this->isEmptyBoard) { double adjustment = 0; //if (move.action == Move::Place) // //{ if (move->word == "pawed") { std::cout << "HERE:" << std::endl; } int start = move->startPosition.COL; if (move->startPosition.ROW < start) { start = move->startPosition.ROW; } std::string wordString = Options::regularWordString(move); std::vector<char> *wordTiles = Options::moveTiles(move); int length = wordTiles->size(); int consbits = 0; for (signed int index = wordTiles->size() - 1; index >= 0; --index) { consbits <<= 1; if (Options::isVowel(&(*wordTiles)[index])) { consbits |= 1; } } adjustment = heuristicsValues->vcPlace(start, length, consbits); // else // { // adjustment = 3.5; // } move->testHScore = RackLeaveEvaluator::equity(Rack, move); return move->testHScore + adjustment; } else if (this->bagSize > 0) { int leftInBagPlusSeven = bagSize - move->moveUsedTiles + 7; // ! BAG BEFORE PLAY double heuristicArray[13] = { 0.0, -8.0, 0.0, -0.5, -2.0, -3.5, -2.0, 2.0, 10.0, 7.0, 4.0, -1.0, -2.0}; double timingHeuristic = 0.0; if (leftInBagPlusSeven < 13) { timingHeuristic = heuristicArray[leftInBagPlusSeven]; } return RackLeaveEvaluator::equity(Rack, move) + timingHeuristic; } else { return endgameResult(Rack, move); // + move->moveScore; } } double VCValueEvaluator::endgameResult(std::vector<char> *Rack, Move *move) { std::vector<char> *remainingRack = Options::unusedRackTiles(Rack, move); if (remainingRack->empty()) { double deadwood = 0; deadwood += Options::rackScore(opponentRack); // deadwood = move->moveScore; return deadwood * 2; } return -8.00 - 2.61 * Options::rackScore(remainingRack); }
30.988235
195
0.572893
AhmedSalemElhady
a62c78e2650b294cdab375d5bf97bbcedaa27e1a
5,818
cpp
C++
Processor/Processor.cpp
Inpher/XorPublic
63f0bc679b618230bb786f0b7dea09bf8bdddd7a
[ "BSD-4-Clause-UC" ]
2
2021-04-24T11:36:29.000Z
2021-04-24T11:43:15.000Z
Processor/Processor.cpp
Inpher/Inpher-SPDZ
63f0bc679b618230bb786f0b7dea09bf8bdddd7a
[ "BSD-4-Clause-UC" ]
2
2017-03-21T20:05:23.000Z
2017-03-27T17:36:55.000Z
Processor/Processor.cpp
Inpher/Inpher-SPDZ
63f0bc679b618230bb786f0b7dea09bf8bdddd7a
[ "BSD-4-Clause-UC" ]
1
2018-10-01T11:48:30.000Z
2018-10-01T11:48:30.000Z
// (C) 2016 University of Bristol. See License.txt #include "Processor/Processor.h" #include "Auth/MAC_Check.h" #include "Auth/fake-stuff.h" Processor::Processor(int thread_num,Data_Files& DataF,Player& P, MAC_Check<gf2n>& MC2,MAC_Check<gfp>& MCp,Machine& machine, int num_regs2,int num_regsp,int num_regi) : thread_num(thread_num),socket_is_open(false),DataF(DataF),P(P),MC2(MC2),MCp(MCp),machine(machine), input2(*this,MC2),inputp(*this,MCp),privateOutput2(*this),privateOutputp(*this),sent(0),rounds(0) { reset(num_regs2,num_regsp,num_regi,0); public_input.open(get_filename("Programs/Public-Input/",false).c_str()); private_input.open(get_filename("Player-Data/Private-Input-",true).c_str()); public_output.open(get_filename("Player-Data/Public-Output-",true).c_str(), ios_base::out); private_output.open(get_filename("Player-Data/Private-Output-",true).c_str(), ios_base::out); } Processor::~Processor() { cerr << "Sent " << sent << " elements in " << rounds << " rounds" << endl; } string Processor::get_filename(const char* prefix, bool use_number) { stringstream filename; filename << prefix; if (!use_number) filename << machine.progname; if (use_number) filename << P.my_num(); if (thread_num > 0) filename << "-" << thread_num; cerr << "Opening file " << filename.str() << endl; return filename.str(); } void Processor::reset(int num_regs2,int num_regsp,int num_regi,int arg) { reg_max2 = num_regs2; reg_maxp = num_regsp; reg_maxi = num_regi; C2.resize(reg_max2); Cp.resize(reg_maxp); S2.resize(reg_max2); Sp.resize(reg_maxp); Ci.resize(reg_maxi); this->arg = arg; close_socket(); #ifdef DEBUG rw2.resize(2*reg_max2); for (int i=0; i<2*reg_max2; i++) { rw2[i]=0; } rwp.resize(2*reg_maxp); for (int i=0; i<2*reg_maxp; i++) { rwp[i]=0; } rwi.resize(2*reg_maxi); for (int i=0; i<2*reg_maxi; i++) { rwi[i]=0; } #endif } #include "Networking/sockets.h" // Set up a server socket for some client void Processor::open_socket(int portnum_base) { if (!socket_is_open) { socket_is_open = true; sockaddr_in dest; set_up_server_socket(dest, final_socket_fd, socket_fd, portnum_base + P.my_num()); } } void Processor::close_socket() { if (socket_is_open) { socket_is_open = false; close_server_socket(final_socket_fd, socket_fd); } } // Receive 32-bit int void Processor::read_socket(int& x) { octet bytes[4]; receive(final_socket_fd, bytes, 4); x = BYTES_TO_INT(bytes); } // Send 32-bit int void Processor::write_socket(int x) { octet bytes[4]; INT_TO_BYTES(bytes, x); send(final_socket_fd, bytes, 4); } // Receive field element template <class T> void Processor::read_socket(T& x) { socket_stream.reset_write_head(); socket_stream.Receive(final_socket_fd); x.unpack(socket_stream); } // Send field element template <class T> void Processor::write_socket(const T& x) { socket_stream.reset_write_head(); x.pack(socket_stream); socket_stream.Send(final_socket_fd); } template <class T> void Processor::POpen_Start(const vector<int>& reg,const Player& P,MAC_Check<T>& MC,int size) { int sz=reg.size(); vector< Share<T> >& Sh_PO = get_Sh_PO<T>(); vector<T>& PO = get_PO<T>(); Sh_PO.clear(); Sh_PO.reserve(sz*size); if (size>1) { for (typename vector<int>::const_iterator reg_it=reg.begin(); reg_it!=reg.end(); reg_it++) { typename vector<Share<T> >::iterator begin=get_S<T>().begin()+*reg_it; Sh_PO.insert(Sh_PO.end(),begin,begin+size); } } else { for (int i=0; i<sz; i++) { Sh_PO.push_back(get_S_ref<T>(reg[i])); } } PO.resize(sz*size); MC.POpen_Begin(PO,Sh_PO,P); } template <class T> void Processor::POpen_Stop(const vector<int>& reg,const Player& P,MAC_Check<T>& MC,int size) { vector< Share<T> >& Sh_PO = get_Sh_PO<T>(); vector<T>& PO = get_PO<T>(); vector<T>& C = get_C<T>(); int sz=reg.size(); PO.resize(sz*size); MC.POpen_End(PO,Sh_PO,P); if (size>1) { typename vector<T>::iterator PO_it=PO.begin(); for (typename vector<int>::const_iterator reg_it=reg.begin(); reg_it!=reg.end(); reg_it++) { for (typename vector<T>::iterator C_it=C.begin()+*reg_it; C_it!=C.begin()+*reg_it+size; C_it++) { *C_it=*PO_it; PO_it++; } } } else { for (unsigned int i=0; i<reg.size(); i++) { get_C_ref<T>(reg[i]) = PO[i]; } } sent += reg.size() * size; rounds++; } ostream& operator<<(ostream& s,const Processor& P) { s << "Processor State" << endl; s << "Char 2 Registers" << endl; s << "Val\tClearReg\tSharedReg" << endl; for (int i=0; i<P.reg_max2; i++) { s << i << "\t"; P.read_C2(i).output(s,true); s << "\t"; P.read_S2(i).output(s,true); s << endl; } s << "Char p Registers" << endl; s << "Val\tClearReg\tSharedReg" << endl; for (int i=0; i<P.reg_maxp; i++) { s << i << "\t"; P.read_Cp(i).output(s,true); s << "\t"; P.read_Sp(i).output(s,true); s << endl; } return s; } template void Processor::POpen_Start(const vector<int>& reg,const Player& P,MAC_Check<gf2n>& MC,int size); template void Processor::POpen_Start(const vector<int>& reg,const Player& P,MAC_Check<gfp>& MC,int size); template void Processor::POpen_Stop(const vector<int>& reg,const Player& P,MAC_Check<gf2n>& MC,int size); template void Processor::POpen_Stop(const vector<int>& reg,const Player& P,MAC_Check<gfp>& MC,int size); template void Processor::read_socket(gfp& x); template void Processor::read_socket(gf2n& x); template void Processor::write_socket(const gfp& x); template void Processor::write_socket(const gf2n& x);
26.089686
106
0.642661
Inpher
a62f25a7d04eb7d3ebfb3348eb9d6b9d81cb56f1
16,297
cpp
C++
gpe/Array.cpp
erli1/GPE-Solver
636fc84bc50144471596ff99cc99edb92a6ef5c1
[ "MIT" ]
8
2015-08-23T09:12:00.000Z
2021-09-10T21:41:27.000Z
gpe/Array.cpp
erli1/GPE-Solver
636fc84bc50144471596ff99cc99edb92a6ef5c1
[ "MIT" ]
1
2018-02-23T19:33:26.000Z
2018-02-24T09:43:18.000Z
gpe/Array.cpp
erli1/GPE-Solver
636fc84bc50144471596ff99cc99edb92a6ef5c1
[ "MIT" ]
5
2015-02-18T17:31:41.000Z
2021-11-09T22:18:45.000Z
#include "Array.h" #include "omp.h" #include <cmath> #include <iostream> #include <cstdlib> #include <fstream> using namespace std; bool Array::_fftwInitialized = false; bool Array::_fftwWisdomLoaded = false; bool Array::_fftwWisdomExported = false; Array::Array(const SimulationParameters & sp) : Field(sp) { _initialized = false; _space = SPACE_UNDEFINED; _fourierPlan = 0; _fourierPlanInverse = 0; _values = new complex_t[_sp.size()]; } void Array::initialize() { int i, j, k; #pragma omp parallel for private(i, j, k) for (i = 0; i < _sp.sizeX(); i++) { for (j = 0; j < _sp.sizeY(); j++) { for (k = 0; k < _sp.sizeZ(); k++) { (*this)(i, j, k) = initialValue(i, j, k); } } } _initialized = true; } complex_t Array::operator()(int i, int j, int k, double t) const { #ifdef DEBUG_GPE assureInitialized(); if (i < 0 || j < 0 || k < 0 || i > _sp.sizeX() || j > _sp.sizeY() || k > _sp.sizeZ()) { cerr << "Error: out-of-bound access to array" << endl; exit(1); } #endif return _values[(i * _sp.sizeY() + j) * _sp.sizeZ() + k]; } complex_t & Array::operator()(int i, int j, int k, double t) { #ifdef DEBUG_GPE if (i < 0 || j < 0 || k < 0 || i > _sp.sizeX() || j > _sp.sizeY() || k > _sp.sizeZ()) { cerr << "Error: out-of-bound access to array" << endl; exit(1); } #endif return _values[(i * _sp.sizeY() + j) * _sp.sizeZ() + k]; } Array & Array::operator=(const Array & a) { #ifdef DEBUG_GPE a.assureInitialized(); #endif if (this != &a) { int i; #pragma omp parallel for private(i) for (i = 0; i < _sp.size(); i++) { _values[i] = a._values[i]; } } _initialized = true; _space = a._space; return *this; } Array & Array::operator*=(const Array & a) { #ifdef DEBUG_GPE assureInitialized(); #endif int i; #pragma omp parallel for private(i) for (i = 0; i < _sp.size(); i++) { _values[i] *= a._values[i]; } return *this; } Array & Array::operator*=(complex_t factor) { #ifdef DEBUG_GPE assureInitialized(); #endif int i; #pragma omp parallel for private(i) for (i = 0; i < _sp.size(); i++) { _values[i] *= factor; } return *this; } double Array::integral(const Field & f) const { // Calculates the following integral (a = this Array object): // int dr^3 (conj(a) * f * a) // // warning: the real part of conj(a) * f * a is taken // to make the whole integral real. #ifdef DEBUG_GPE assureInitialized(); #endif double sum = 0.0; int i, j, k; #pragma omp parallel for private (i, j, k) reduction(+:sum) for (i = 0; i < _sp.sizeX(); i++) { for (j = 0; j < _sp.sizeY(); j++) { for (k = 0; k < _sp.sizeZ(); k++) { sum += real(conj((*this)(i, j, k)) * f(i, j, k) * (*this)(i, j, k)); } } } // The multiplication by dx*dy*dz is also correct // in fourier space (due to some scaling during the FFT)! return sum * (_sp.dX() * _sp.dY() * _sp.dZ()); } #ifndef __INTEL_COMPILER double Array::integral(function<complex_t (double, double, double)> lambdaExpression) const { double sum = 0.0; #ifdef DEBUG_GPE assureInitialized(); #endif int i, j, k; #pragma omp parallel for private (i, j, k) reduction(+:sum) for (i = 0; i < _sp.sizeX(); i++) { for (j = 0; j < _sp.sizeY(); j++) { for (k = 0; k < _sp.sizeZ(); k++) { sum += real(conj((*this)(i, j, k)) * lambdaExpression(_sp.x(i), _sp.y(j), _sp.z(k)) * (*this)(i, j, k)); } } } return sum * (_sp.dX() * _sp.dY() * _sp.dZ()); } #endif void Array::initFourierPlans() { int mx = _sp.sizeX(); int my = _sp.sizeY(); int mz = _sp.sizeZ(); if (!_fftwInitialized) { if (!fftw_init_threads()) { cerr << "Error during FFTW thread initialization." << endl; exit(1); } #ifdef _OPENMP int nthreads; #pragma omp parallel { nthreads = omp_get_num_threads(); } fftw_plan_with_nthreads(nthreads); #ifdef DEBUG_GPE cerr << "Initializing FFTW for " << nthreads << " thread(s)" << endl; #endif #endif _fftwInitialized = true; } // Read FFTW wisdom from file if (!_fftwWisdomLoaded) { #ifdef DEBUG_GPE cerr << "Importing FFTW wisdom" << endl; #endif FILE * wisdomFile = fopen("fftw.wisdom", "r"); if (wisdomFile) { fftw_import_wisdom_from_file(wisdomFile); fclose(wisdomFile); } else { #ifdef DEBUG_GPE cerr << "No wisdom file available" << endl; #endif } _fftwWisdomLoaded = true; } #ifdef DEBUG_GPE cerr << "Creating FFTW plans" << endl; #endif // -1 = Fourier Transform, +1 = Inverse Fourier Transform _fourierPlan = fftw_plan_dft_3d(mx, my, mz, reinterpret_cast<fftw_complex*>(_values), reinterpret_cast<fftw_complex*>(_values), -1, FFTW_PATIENT); _fourierPlanInverse = fftw_plan_dft_3d(mx, my, mz, reinterpret_cast<fftw_complex*>(_values), reinterpret_cast<fftw_complex*>(_values), +1, FFTW_PATIENT); } void Array::fourierTransform() { #ifdef DEBUG_GPE assureInitialized(); if (_space == SPACE_MOMENTUM) { cerr << "Array is already in momentum space" << endl; } #endif if (!_fourierPlan) { cerr << "Fourier plan has not been initialized!" << endl; exit(1); } fftw_execute(_fourierPlan); _space = SPACE_MOMENTUM; } void Array::fourierTransformInverse() { #ifdef DEBUG_GPE assureInitialized(); if (_space == SPACE_POSITION) { cerr << "Array is already in position space" << endl; } #endif if (!_fourierPlanInverse) { cerr << "Fourier plan has not been initialized!" << endl; exit(1); } fftw_execute(_fourierPlanInverse); _space = SPACE_POSITION; } double Array::dispersion(int direction, bool realSpace) { // Calculates the following integral (a = this Array object): // int dr^3 (conj(a) * * a) #ifdef DEBUG_GPE assureInitialized(); #endif if (!realSpace) { fftw_execute(_fourierPlan); } double sum = 0.0; int i, j, k; #pragma omp parallel for private (i, j, k) reduction(+:sum) for (i = 0; i < _sp.sizeX(); i++) { for (j = 0; j < _sp.sizeY(); j++) { for (k = 0; k < _sp.sizeZ(); k++) { if (direction == 0) { sum += real(conj((*this)(i, j, k)) * pow(_sp.coord(direction, i, realSpace) , 2.0) * (*this)(i, j, k)); } else if (direction == 1) { sum += real(conj((*this)(i, j, k)) * pow(_sp.coord(direction, j, realSpace) , 2.0) * (*this)(i, j, k)); } else { sum += real(conj((*this)(i, j, k)) * pow(_sp.coord(direction, k, realSpace) , 2.0) * (*this)(i, j, k)); } } } } if (!realSpace) { #pragma omp parallel for private (i, j, k) reduction(+:sum) for (i = 0; i < _sp.sizeX(); ++i) { for (j = 0; j < _sp.sizeY(); ++j) { for (k = 0; k < _sp.sizeZ(); ++k) { (*this)(i, j, k) *= 1.0 / (_sp.sizeX() * _sp.sizeY() * _sp.sizeZ()); } } } fftw_execute(_fourierPlanInverse); } // The multiplication by dx*dy*dz is also correct // in fourier space (due to some scaling during the FFT)! return real( sqrt( 2.0 * sum * (_sp.dX() * _sp.dY() * _sp.dZ()) ) ); } double Array::averageXK(int direction) const { // Calculates the following integral (a = this Array object): // int dr^3 (conj(a) * * a) #ifdef DEBUG_GPE assureInitialized(); #endif double sum = 0.0; bool realSpace = 1; int i, j, k; // #pragma omp parallel for private (i, j, k) reduction(+:sum) for (i = 0; i < _sp.sizeX()-1; i++) { for (j = 0; j < _sp.sizeY()-1; j++) { for (k = 0; k < _sp.sizeZ()-1; k++) { if (direction == 0) { sum += imag( (*this)(i, j, k) * _sp.coord(direction, i, realSpace) * (*this)(i+1, j, k) / ( _sp.dX() ) ); } else if (direction == 1) { sum += imag( (*this)(i, j, k) * _sp.coord(direction, j, realSpace) * (*this)(i, j+1, k) / ( _sp.dY() ) ); } else { sum += imag( (*this)(i, j, k) * _sp.coord(direction, k, realSpace) * (*this)(i, j, k+1) / ( _sp.dZ() ) ); } } } } return sum; } void Array::cut1D(string fileName, int direction) const { #ifdef DEBUG_GPE assureInitialized(); #endif bool realSpace = (_space == SPACE_POSITION); int k, kmax, sx, sy, sz, c1, c2, index; ofstream fout; fout.open(fileName.c_str()); kmax = _sp.size(direction); sx = _sp.size(0); sy = _sp.size(1); sz = _sp.size(2); if (direction == 0) { c1 = (sy * sz + sz) * realSpace / 2; c2 = sy * sz; } else if (direction == 1) { c1 = (sy * sz * sx + sz) * realSpace / 2; c2 = sz; } else { c1 = (sy * sz * sx + sz * sy) * realSpace / 2; c2 = 1; } for (k = 0; k < kmax; ++k) { index = c1 + c2 * k; fout << _sp.coord(direction, k, realSpace) << " " << real(_values[index]) << " " << imag(_values[index]) << "\n"; } fout.close(); } void Array::projectMatlab2D(string fileName) const { #ifdef DEBUG_GPE assureInitialized(); #endif int sx, sy, sz; int i, j, k; double sum; ofstream fout; fout.open(fileName.c_str()); sx = _sp.size(0); sy = _sp.size(1); sz = _sp.size(2); fout << "x = ["; for (i = 0; i < sx; i++) { fout << _sp.x(i) << " "; } fout << "];"; fout << "z = ["; for (k = 0; k < sz; k++) { fout << _sp.z(k) << " "; } fout << "];"; fout << "density = ["; for (i = 0; i < sx; ++i) { for (k = 0; k < sz; ++k) { sum = 0.0; for (j = 0; j < sy/2; ++j) { sum += abs( (*this)(i, j, k) ); } fout << sum << " "; } fout << ";" << endl; } fout << "];" << endl; fout.close(); } void Array::projectFourierMatlab2D(string fileName) { #ifdef DEBUG_GPE assureInitialized(); #endif fftw_execute(_fourierPlan); int sx, sy, sz; int i, j, k; double sum; ofstream fout; fout.open(fileName.c_str()); sx = _sp.size(0); sy = _sp.size(1); sz = _sp.size(2); for (j = 0; j < sy/2; ++j) { for (k = 0; k < sz/2; ++k) { sum = 0.0; for (i = 0; i < sx; ++i) { sum += abs( (*this)(i, j, k) ); } fout << sum << " "; } fout << endl; } for (i = 0; i < sx; ++i) { for (j = 0; j < sy; ++j) { for (k = 0; k < sz; ++k) { (*this)(i, j, k) *= 1.0 / (sx * sy * sz); } } } fftw_execute(_fourierPlanInverse); fout.close(); } void Array::cut2D(string fileName, int direction) const { #ifdef DEBUG_GPE assureInitialized(); #endif bool realSpace = (_space == SPACE_POSITION); int sx, sy, sz, c1, c2, c3, index; int dir1, dir2; int imax, jmax; int i, j, i1, j1; ofstream fout; fout.open(fileName.c_str()); sx = _sp.size(0); sy = _sp.size(1); sz = _sp.size(2); if (direction == 0) { dir1 = 1; dir2 = 2; c1 = (sy * sz * sx) * realSpace / 2; c2 = 1; c3 = sz; imax = sy; jmax = sz; } else if (direction == 1) { dir1 = 0; dir2 = 2; c1 = (sy * sz) * realSpace / 2; c2 = 1; c3 = sy * sz; imax = sx; jmax = sz; } else { dir1 = 0; dir2 = 1; c1 = sz * realSpace / 2; c2 = sz; c3 = sy * sz; imax = sx; jmax = sy; } for (i1 = 0; i1 < imax - 1; ++i1) { for (j1 = 0; j1 < jmax - 1; ++j1) { i = (i1 + imax / 2 * (realSpace + 1)) % imax; j = (j1 + jmax / 2 * (realSpace + 1)) % jmax; index = c1 + c2 * j + c3 * i; fout << _sp.coord(dir1, i, realSpace) << " "; fout << _sp.coord(dir2, j, realSpace) << " "; fout << abs(_values[index]) << "\n"; fout << _sp.coord(dir1, i, realSpace) << " "; fout << _sp.coord(dir2, j + 1, realSpace) << " "; fout << abs(_values[index]) << "\n"; } fout << "\n"; for (j1 = 0; j1 < jmax - 1; ++j1) { i = (i1 + imax / 2 * (realSpace + 1)) % imax; j = (j1 + jmax / 2 * (realSpace + 1)) % jmax; index = c1 + c2 * j + c3 * i; fout << _sp.coord(dir1, i + 1, realSpace) << " "; fout << _sp.coord(dir2, j, realSpace) << " "; fout << abs(_values[index]) << "\n"; fout << _sp.coord(dir1, i + 1, realSpace) << " "; fout << _sp.coord(dir2, j + 1, realSpace) << " "; fout << abs(_values[index]) << "\n"; } fout << "\n"; } fout.close(); } void Array::project1D(string fileName, int direction) const { #ifdef DEBUG_GPE assureInitialized(); #endif double sum; // The two "other" directions which are summed over int d_2 = (direction + 1) % 3; int d_3 = (direction + 2) % 3; int i, j, k; ofstream fout; fout.open(fileName.c_str()); for (i = 0; i < _sp.size(direction); i++) { sum = 0.0; for (j = 0; j < _sp.size(d_2); j++) { for (k = 0; k < _sp.size(d_3); k++) { if (direction == 0) { sum += abs((*this)(i, j, k)); } else if (direction == 1) { sum += abs((*this)(k, i, j)); } else { sum += abs((*this)(j, k, i)); } } } sum *= _sp.d(d_2, _space) * _sp.d(d_3, _space); fout << _sp.coord(direction, i, _space) << " " << sum << "\n"; } fout.close(); } void Array::project2D(string fileName) const { // Print column density profile in YZ plane // TODO generalize for arbitrary direction #ifdef DEBUG_GPE assureInitialized(); #endif double sum; int i, j, k; bool realSpace = _space; ofstream fout; fout.open(fileName.c_str()); for (j = 0; j < _sp.size(1) - 1; ++j) { for (k = 0; k < _sp.size(2) - 1; ++k) { sum = 0.0; for (i = 0; i < _sp.size(0); ++i) { sum += abs((*this)(i, j, k)); } sum *= _sp.dX(); fout << _sp.coord(1, j, realSpace) << " "; fout << _sp.coord(2, k, realSpace) << " "; fout << sum << "\n"; fout << _sp.coord(1, j, realSpace) << " "; fout << _sp.coord(2, k + 1, realSpace) << " "; fout << sum << "\n"; } fout << "\n"; for (k = 0; k < _sp.size(2) - 1; ++k) { sum = 0.0; for (i = 0; i < _sp.size(0); ++i) { sum += abs((*this)(i, j, k)); } sum *= _sp.dX(); fout << _sp.coord(1, j + 1, realSpace) << " "; fout << _sp.coord(2, k, realSpace) << " "; fout << sum << "\n"; fout << _sp.coord(1, j + 1, realSpace) << " "; fout << _sp.coord(2, k + 1, realSpace) << " "; fout << sum << "\n"; } fout << "\n"; } fout.close(); } Array::~Array() { delete[] _values; if (_fourierPlan) { #ifdef DEBUG_GPE cerr << "Destroying Fourier Plans" << endl; #endif fftw_destroy_plan(_fourierPlan); fftw_destroy_plan(_fourierPlanInverse); if (!_fftwWisdomExported) { // Export FFTW wisdom #ifdef DEBUG_GPE cerr << "Exporting FFTW wisdom" << endl; #endif FILE * wisdomFile = fopen("fftw.wisdom", "w"); fftw_export_wisdom_to_file(wisdomFile); fclose(wisdomFile); _fftwWisdomExported = true; } } }
25.033794
157
0.483709
erli1
a62fa6151e44bacc43b40a2ec1766e4d7e39cda1
1,094
hpp
C++
lumino/LuminoEngine/include/LuminoEngine/PostEffect/TonePostEffect.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
30
2016-01-24T05:35:45.000Z
2020-03-03T09:54:27.000Z
lumino/LuminoEngine/include/LuminoEngine/PostEffect/TonePostEffect.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
35
2016-04-18T06:14:08.000Z
2020-02-09T15:51:58.000Z
lumino/LuminoEngine/include/LuminoEngine/PostEffect/TonePostEffect.hpp
lriki/Lumino
1a80430f4a83dbdfbe965b3d5b16064991b3edb0
[ "MIT" ]
5
2016-04-03T02:52:05.000Z
2018-01-02T16:53:06.000Z
#pragma once #include <LuminoGraphics/Animation/EasingFunctions.hpp> #include "PostEffect.hpp" namespace ln { namespace detail { class TonePostEffectInstance; } class TonePostEffect : public PostEffect { public: static Ref<TonePostEffect> create(); // [experimental] void play(const ColorTone& tone, double time); protected: virtual void onUpdateFrame(float elapsedSeconds) override; virtual Ref<PostEffectInstance> onCreateInstance() override; LN_CONSTRUCT_ACCESS: TonePostEffect(); virtual ~TonePostEffect(); void init(); private: EasingValue<Vector4> m_toneValue; friend class detail::TonePostEffectInstance; }; namespace detail { class TonePostEffectInstance : public PostEffectInstance { protected: bool onRender(RenderView* renderView, CommandList* context, RenderTargetTexture* source, RenderTargetTexture* destination) override; LN_CONSTRUCT_ACCESS: TonePostEffectInstance(); bool init(TonePostEffect* owner); private: TonePostEffect* m_owner; Ref<Material> m_material; }; } // namespace detail } // namespace ln
21.038462
136
0.75777
lriki
a630f575527f809cbe2afc68d4de1a542df4ffc1
194
cpp
C++
Foreign/SonyLE/LevelEditorNativeRendering/LvEdRenderingEngine/GobSystem/MeshComponent.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
796
2015-01-02T12:25:52.000Z
2022-03-22T18:45:03.000Z
Foreign/SonyLE/LevelEditorNativeRendering/LvEdRenderingEngine/GobSystem/MeshComponent.cpp
yorung/XLE
083ce4c9d3fe32002ff5168e571cada2715bece4
[ "MIT" ]
22
2015-02-06T03:41:40.000Z
2020-09-29T19:21:20.000Z
Foreign/SonyLE/LevelEditorNativeRendering/LvEdRenderingEngine/GobSystem/MeshComponent.cpp
yorung/XLE
083ce4c9d3fe32002ff5168e571cada2715bece4
[ "MIT" ]
218
2015-01-01T15:58:25.000Z
2022-02-21T05:17:37.000Z
#include "MeshComponent.h" using namespace LvEdEngine; void MeshComponent::SetRef(const wchar_t* path) { } void MeshComponent::Update(const FrameTime& fr, UpdateTypeEnum updateType) { }
14.923077
74
0.757732
alexgithubber
a63176e26125bff1f6d71a354977b2b764ea837e
1,211
cpp
C++
src/interfaces/DMSUT.cpp
dotweiba/dbt5
39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42
[ "Artistic-1.0" ]
3
2017-08-30T12:57:33.000Z
2022-02-08T14:25:03.000Z
src/interfaces/DMSUT.cpp
dotweiba/dbt5
39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42
[ "Artistic-1.0" ]
1
2020-09-28T05:36:28.000Z
2021-03-15T10:38:29.000Z
src/interfaces/DMSUT.cpp
dotweiba/dbt5
39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42
[ "Artistic-1.0" ]
5
2017-01-18T20:16:06.000Z
2021-03-09T12:23:50.000Z
/* * This file is released under the terms of the Artistic License. Please see * the file LICENSE, included in this package, for details. * * Copyright (C) 2006-2010 Rilson Nascimento * * 12 August 2006 */ #include "DMSUT.h" // constructor CDMSUT::CDMSUT(char *addr, const int iListenPort, ofstream *pflog, ofstream *pfmix, CMutex *pLogLock, CMutex *pMixLock) : CBaseInterface(addr, iListenPort, pflog, pfmix, pLogLock, pMixLock) { } // destructor CDMSUT::~CDMSUT() { } // Data Maintenance bool CDMSUT::DataMaintenance(PDataMaintenanceTxnInput pTxnInput) { PMsgDriverBrokerage pRequest = new TMsgDriverBrokerage; memset(pRequest, 0, sizeof(TMsgDriverBrokerage)); pRequest->TxnType = DATA_MAINTENANCE; memcpy(&(pRequest->TxnInput.DataMaintenanceTxnInput), pTxnInput, sizeof(TDataMaintenanceTxnInput)); return talkToSUT(pRequest); } // Trade Cleanup bool CDMSUT::TradeCleanup(PTradeCleanupTxnInput pTxnInput) { PMsgDriverBrokerage pRequest = new TMsgDriverBrokerage; memset(pRequest, 0, sizeof(TMsgDriverBrokerage)); pRequest->TxnType = TRADE_CLEANUP; memcpy(&(pRequest->TxnInput.TradeCleanupTxnInput), pTxnInput, sizeof(TTradeCleanupTxnInput)); return talkToSUT(pRequest); }
24.714286
77
0.765483
dotweiba
a63bf17f03622781852d02b01c1d36716300278b
3,220
cpp
C++
lab7/150101033_1.cpp
mayank-myk/Basic-Datastructure-implementations
4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356
[ "MIT" ]
null
null
null
lab7/150101033_1.cpp
mayank-myk/Basic-Datastructure-implementations
4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356
[ "MIT" ]
null
null
null
lab7/150101033_1.cpp
mayank-myk/Basic-Datastructure-implementations
4bf5f79c2c5ad636fe9d61c0be36a0a3e1238356
[ "MIT" ]
null
null
null
//mayank agrawal //150101033 #include <stdio.h> #include <iostream> #include <stdlib.h> using namespace std; struct set{ int size; struct node *head; struct node *tail; }; struct node{ int data; struct set *rep ; struct node *next; }; //initializing struct node abject and struct set object struct node *make_set(int a) { struct set *newSet = new struct set; newSet->head = new struct node; newSet->tail = newSet->head; newSet->size=1; struct node *temp = newSet->head; temp->data = a; temp->rep = newSet; temp->next = NULL; return temp; } //returns the representative struct set of any struct node struct set *find_set(struct node *a){ return a->rep; } void *unions(struct node *x,struct node *y){ struct set *a = find_set(x); //find_set returns representative of any node struct set *b = find_set(y); if (a->size > b->size) { a->size=a->size + b->size; a->tail->next=b->head ; //combining smaller set into bigger set a->tail = b->tail; struct node *temp=b->head; //changing representative pointer of all elements of smaller while(temp){ //set to that of bigger set temp->rep= a; temp = temp->next; } } else{ b->size =a->size + b->size ; b->tail->next=a->head; b->tail = a->tail; struct node *temp=a->head ; while(temp) { temp->rep= b; temp = temp->next; } } } //function to print the whole list void pprint(struct node **arr,int arr1[],int k){ int i,j,check[100]={0} ; cout << endl; for(i=0;i<k;i++){ j=arr1[i]; if(check[j]==0){ struct node *temp=arr[j]; struct set *temp1=temp->rep; struct node *temp2=temp1->head; while(temp2){ cout << temp2->data << " " ; check[temp2->data]=1; temp2 = temp2->next; } cout << endl; } } cout <<endl; } int main(){ int k,j,n=0; cout<< "Input the value of k: "; cin >> k ; int arr1[k]; struct node ** arr=new struct node* [100]; //array to store all the struct node according to index for(int i=0;i<k;i++){ cout << "input the data (between 0 to 99):" ; cin >> j; arr[j] = make_set(j); arr1[i]=j; //array to store value of each node } while(1){ int m,a,b,c; cout << "1 for union, 2 for find_set, 3 for exit" << endl; cin >> m ; switch(m){ case 1: cout << "type the number whose union you want to find" << endl; cin >> a >> b; unions(arr[a],arr[b]); pprint(arr,arr1,k); break; case 2: cout << "type the number whose find_set you need" << endl; cin >> c ; struct set *y; y=find_set(arr[c]); cout << "the set representative is "<< y->head->data << endl; break; default: exit(0); } } return 0; }
25.555556
105
0.497205
mayank-myk
a63f2c38b77b58a5070fb4d338e1ed514a4d2a91
1,977
tcc
C++
nheqminer/zcash/circuit/utils.tcc
Maroc-OS/nheqminer
b1451be01151d535118900daf3b2309d91401fcb
[ "MIT" ]
4
2017-06-30T08:19:05.000Z
2017-11-26T21:29:35.000Z
nheqminer/zcash/circuit/utils.tcc
Maroc-OS/nheqminer
b1451be01151d535118900daf3b2309d91401fcb
[ "MIT" ]
null
null
null
nheqminer/zcash/circuit/utils.tcc
Maroc-OS/nheqminer
b1451be01151d535118900daf3b2309d91401fcb
[ "MIT" ]
1
2019-07-04T22:36:20.000Z
2019-07-04T22:36:20.000Z
#include "uint252.h" template <typename FieldT> pb_variable_array<FieldT> from_bits(std::vector<bool> bits, pb_variable<FieldT> &ZERO) { pb_variable_array<FieldT> acc; BOOST_FOREACH (bool bit, bits) { acc.emplace_back(bit ? ONE : ZERO); } return acc; } std::vector<bool> trailing252(std::vector<bool> input) { if (input.size() != 256) { throw std::length_error("trailing252 input invalid length"); } return std::vector<bool>(input.begin() + 4, input.end()); } template <typename T> std::vector<bool> to_bool_vector(T input) { std::vector<unsigned char> input_v(input.begin(), input.end()); return convertBytesVectorToVector(input_v); } std::vector<bool> uint256_to_bool_vector(uint256 input) { return to_bool_vector(input); } std::vector<bool> uint252_to_bool_vector(uint252 input) { return trailing252(to_bool_vector(input)); } std::vector<bool> uint64_to_bool_vector(uint64_t input) { auto num_bv = convertIntToVectorLE(input); return convertBytesVectorToVector(num_bv); } void insert_uint256(std::vector<bool> &into, uint256 from) { std::vector<bool> blob = uint256_to_bool_vector(from); into.insert(into.end(), blob.begin(), blob.end()); } void insert_uint64(std::vector<bool> &into, uint64_t from) { std::vector<bool> num = uint64_to_bool_vector(from); into.insert(into.end(), num.begin(), num.end()); } template <typename T> T swap_endianness_u64(T v) { if (v.size() != 64) { throw std::length_error("invalid bit length for 64-bit unsigned integer"); } for (size_t i = 0; i < 4; i++) { for (size_t j = 0; j < 8; j++) { std::swap(v[i * 8 + j], v[((7 - i) * 8) + j]); } } return v; } template <typename FieldT> linear_combination<FieldT> packed_addition(pb_variable_array<FieldT> input) { auto input_swapped = swap_endianness_u64(input); return pb_packing_sum<FieldT>( pb_variable_array<FieldT>(input_swapped.rbegin(), input_swapped.rend())); }
27.458333
79
0.686394
Maroc-OS
a643ec41c2ff3108dce42925e50ea6574d7938e2
49,919
cpp
C++
src/render/IrradianceCube.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
2
2019-12-24T04:00:36.000Z
2022-01-26T02:44:04.000Z
src/render/IrradianceCube.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
null
null
null
src/render/IrradianceCube.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
2
2020-09-26T04:19:40.000Z
2021-02-19T07:24:57.000Z
#include "renderer/IrradianceCube.h" #include "utils/loadshader.h" IrradianceCube::IrradianceCube(vks::VulkanDevice *vulkanDevice, VkCommandPool &cmdPool, std::shared_ptr<VertexDescriptions> &vdo_, vks::Model &skybox, VkQueue &queue) { this->vulkanDevice = vulkanDevice; this->cmdPool = cmdPool; this->vdo_ = vdo_; this->skybox = skybox; this->queue = queue; this->device = vulkanDevice->logicalDevice; } IrradianceCube::~IrradianceCube() { } VkCommandBuffer IrradianceCube::createCommandBuffer(VkCommandBufferLevel level, bool begin) { VkCommandBuffer cmdBuffer; VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo( cmdPool, level, 1); VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &cmdBuffer)); // If requested, also start the new command buffer if (begin) { VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); VK_CHECK_RESULT(vkBeginCommandBuffer(cmdBuffer, &cmdBufInfo)); } return cmdBuffer; } void IrradianceCube::flushCommandBuffer(VkCommandBuffer commandBuffer, VkQueue queue, bool free) { if (commandBuffer == VK_NULL_HANDLE) { return; } VK_CHECK_RESULT(vkEndCommandBuffer(commandBuffer)); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK_RESULT(vkQueueWaitIdle(queue)); if (free) { vkFreeCommandBuffers(device, cmdPool, 1, &commandBuffer); } } void IrradianceCube::generateIrradianceCube(vks::TextureCubeMap &cubeMap) { auto tStart = std::chrono::high_resolution_clock::now(); const VkFormat format = VK_FORMAT_R32G32B32A32_SFLOAT; const int32_t dim = 64; const uint32_t numMips = static_cast<uint32_t>(floor(log2(dim))) + 1; // Pre-filtered cube map // Image VkImageCreateInfo imageCI = vks::initializers::imageCreateInfo(); imageCI.imageType = VK_IMAGE_TYPE_2D; imageCI.format = format; imageCI.extent.width = dim; imageCI.extent.height = dim; imageCI.extent.depth = 1; imageCI.mipLevels = numMips; imageCI.arrayLayers = 6; imageCI.samples = VK_SAMPLE_COUNT_1_BIT; imageCI.tiling = VK_IMAGE_TILING_OPTIMAL; imageCI.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; imageCI.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; VK_CHECK_RESULT(vkCreateImage(device, &imageCI, nullptr, &textures.irradianceCube.image)); VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; vkGetImageMemoryRequirements(device, textures.irradianceCube.image, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &textures.irradianceCube.deviceMemory)); VK_CHECK_RESULT(vkBindImageMemory(device, textures.irradianceCube.image, textures.irradianceCube.deviceMemory, 0)); // Image view VkImageViewCreateInfo viewCI = vks::initializers::imageViewCreateInfo(); viewCI.viewType = VK_IMAGE_VIEW_TYPE_CUBE; viewCI.format = format; viewCI.subresourceRange = {}; viewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; viewCI.subresourceRange.levelCount = numMips; viewCI.subresourceRange.layerCount = 6; viewCI.image = textures.irradianceCube.image; VK_CHECK_RESULT(vkCreateImageView(device, &viewCI, nullptr, &textures.irradianceCube.view)); // Sampler VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo(); samplerCI.magFilter = VK_FILTER_LINEAR; samplerCI.minFilter = VK_FILTER_LINEAR; samplerCI.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerCI.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.minLod = 0.0f; samplerCI.maxLod = static_cast<float>(numMips); samplerCI.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK_RESULT(vkCreateSampler(device, &samplerCI, nullptr, &textures.irradianceCube.sampler)); textures.irradianceCube.descriptor.imageView = textures.irradianceCube.view; textures.irradianceCube.descriptor.sampler = textures.irradianceCube.sampler; textures.irradianceCube.descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; textures.irradianceCube.device = vulkanDevice; // FB, Att, RP, Pipe, etc. VkAttachmentDescription attDesc = {}; // Color attachment attDesc.format = format; attDesc.samples = VK_SAMPLE_COUNT_1_BIT; attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE; attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorReference; // Use subpass dependencies for layout transitions std::array<VkSubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; // Renderpass VkRenderPassCreateInfo renderPassCI = vks::initializers::renderPassCreateInfo(); renderPassCI.attachmentCount = 1; renderPassCI.pAttachments = &attDesc; renderPassCI.subpassCount = 1; renderPassCI.pSubpasses = &subpassDescription; renderPassCI.dependencyCount = 2; renderPassCI.pDependencies = dependencies.data(); VkRenderPass renderpass; VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &renderpass)); struct { VkImage image; VkImageView view; VkDeviceMemory memory; VkFramebuffer framebuffer; } offscreen; // Offfscreen framebuffer { // Color attachment VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo(); imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = format; imageCreateInfo.extent.width = dim; imageCreateInfo.extent.height = dim; imageCreateInfo.extent.depth = 1; imageCreateInfo.mipLevels = 1; imageCreateInfo.arrayLayers = 1; imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageCreateInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &offscreen.image)); VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; vkGetImageMemoryRequirements(device, offscreen.image, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &offscreen.memory)); VK_CHECK_RESULT(vkBindImageMemory(device, offscreen.image, offscreen.memory, 0)); VkImageViewCreateInfo colorImageView = vks::initializers::imageViewCreateInfo(); colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D; colorImageView.format = format; colorImageView.flags = 0; colorImageView.subresourceRange = {}; colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; colorImageView.subresourceRange.baseMipLevel = 0; colorImageView.subresourceRange.levelCount = 1; colorImageView.subresourceRange.baseArrayLayer = 0; colorImageView.subresourceRange.layerCount = 1; colorImageView.image = offscreen.image; VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &offscreen.view)); VkFramebufferCreateInfo fbufCreateInfo = vks::initializers::framebufferCreateInfo(); fbufCreateInfo.renderPass = renderpass; fbufCreateInfo.attachmentCount = 1; fbufCreateInfo.pAttachments = &offscreen.view; fbufCreateInfo.width = dim; fbufCreateInfo.height = dim; fbufCreateInfo.layers = 1; VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &offscreen.framebuffer)); VkCommandBuffer layoutCmd = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); vks::tools::setImageLayout( layoutCmd, offscreen.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); flushCommandBuffer(layoutCmd, queue, true); } // Descriptors VkDescriptorSetLayout descriptorsetlayout; std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0), }; VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout)); // Descriptor Pool std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) }; VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); VkDescriptorPool descriptorpool; VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool)); // Descriptor sets VkDescriptorSet descriptorset; VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset)); VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(descriptorset, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &cubeMap.descriptor); vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); // Pipeline layout struct PushBlock { glm::mat4 mvp; // Sampling deltas float deltaPhi = (2.0f * float(M_PI)) / 180.0f; float deltaTheta = (0.5f * float(M_PI)) / 64.0f; } pushBlock; VkPipelineLayout pipelinelayout; std::vector<VkPushConstantRange> pushConstantRanges = { vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(PushBlock), 0), }; VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1); pipelineLayoutCI.pushConstantRangeCount = 1; pipelineLayoutCI.pPushConstantRanges = pushConstantRanges.data(); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelinelayout)); // Pipeline VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); // Vertex input state VkVertexInputBindingDescription vertexInputBinding = vks::initializers::vertexInputBindingDescription(0, vdo_->vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX); VkVertexInputAttributeDescription vertexInputAttribute = vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0); VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); vertexInputState.vertexBindingDescriptionCount = 1; vertexInputState.pVertexBindingDescriptions = &vertexInputBinding; vertexInputState.vertexAttributeDescriptionCount = 1; vertexInputState.pVertexAttributeDescriptions = &vertexInputAttribute; std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelinelayout, renderpass); pipelineCI.pInputAssemblyState = &inputAssemblyState; pipelineCI.pRasterizationState = &rasterizationState; pipelineCI.pColorBlendState = &colorBlendState; pipelineCI.pMultisampleState = &multisampleState; pipelineCI.pViewportState = &viewportState; pipelineCI.pDepthStencilState = &depthStencilState; pipelineCI.pDynamicState = &dynamicState; pipelineCI.stageCount = 2; pipelineCI.pStages = shaderStages.data(); pipelineCI.pVertexInputState = &vertexInputState; pipelineCI.renderPass = renderpass; shaderStages[0] = loadShader(getAssetPath + "/pbribl/filtercube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT,device, shaderModules); shaderStages[1] = loadShader(getAssetPath + "/pbribl/irradiancecube.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT,device, shaderModules); VkPipeline pipeline; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, 0, 1, &pipelineCI, nullptr, &pipeline)); // Render VkClearValue clearValues[1]; clearValues[0].color = { { 0.0f, 0.0f, 0.2f, 0.0f } }; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); // Reuse render pass from example pass renderPassBeginInfo.renderPass = renderpass; renderPassBeginInfo.framebuffer = offscreen.framebuffer; renderPassBeginInfo.renderArea.extent.width = dim; renderPassBeginInfo.renderArea.extent.height = dim; renderPassBeginInfo.clearValueCount = 1; renderPassBeginInfo.pClearValues = clearValues; std::vector<glm::mat4> matrices = { // POSITIVE_X glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // NEGATIVE_X glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // POSITIVE_Y glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // NEGATIVE_Y glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // POSITIVE_Z glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // NEGATIVE_Z glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)), }; VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f); VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0); vkCmdSetViewport(cmdBuf, 0, 1, &viewport); vkCmdSetScissor(cmdBuf, 0, 1, &scissor); VkImageSubresourceRange subresourceRange = {}; subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = numMips; subresourceRange.layerCount = 6; // Change image layout for all cubemap faces to transfer destination vks::tools::setImageLayout( cmdBuf, textures.irradianceCube.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresourceRange); for (uint32_t m = 0; m < numMips; m++) { for (uint32_t f = 0; f < 6; f++) { viewport.width = static_cast<float>(dim * std::pow(0.5f, m)); viewport.height = static_cast<float>(dim * std::pow(0.5f, m)); vkCmdSetViewport(cmdBuf, 0, 1, &viewport); // Render scene from cube face's point of view vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); // Update shader push constant block pushBlock.mvp = glm::perspective((float)(M_PI / 2.0), 1.0f, 0.1f, 512.0f) * matrices[f]; vkCmdPushConstants(cmdBuf, pipelinelayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushBlock), &pushBlock); vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelinelayout, 0, 1, &descriptorset, 0, NULL); VkDeviceSize offsets[1] = { 0 }; vkCmdBindVertexBuffers(cmdBuf, 0, 1, &skybox.vertices.buffer, offsets); vkCmdBindIndexBuffer(cmdBuf, skybox.indices.buffer, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(cmdBuf, skybox.indexCount, 1, 0, 0, 0); vkCmdEndRenderPass(cmdBuf); vks::tools::setImageLayout( cmdBuf, offscreen.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); // Copy region for transfer from framebuffer to cube face VkImageCopy copyRegion = {}; copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copyRegion.srcSubresource.baseArrayLayer = 0; copyRegion.srcSubresource.mipLevel = 0; copyRegion.srcSubresource.layerCount = 1; copyRegion.srcOffset = { 0, 0, 0 }; copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copyRegion.dstSubresource.baseArrayLayer = f; copyRegion.dstSubresource.mipLevel = m; copyRegion.dstSubresource.layerCount = 1; copyRegion.dstOffset = { 0, 0, 0 }; copyRegion.extent.width = static_cast<uint32_t>(viewport.width); copyRegion.extent.height = static_cast<uint32_t>(viewport.height); copyRegion.extent.depth = 1; vkCmdCopyImage( cmdBuf, offscreen.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, textures.irradianceCube.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copyRegion); // Transform framebuffer color attachment back vks::tools::setImageLayout( cmdBuf, offscreen.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); } } vks::tools::setImageLayout( cmdBuf, textures.irradianceCube.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresourceRange); vulkanDevice->flushCommandBuffer(cmdBuf, queue); // todo: cleanup vkDestroyRenderPass(device, renderpass, nullptr); vkDestroyFramebuffer(device, offscreen.framebuffer, nullptr); vkFreeMemory(device, offscreen.memory, nullptr); vkDestroyImageView(device, offscreen.view, nullptr); vkDestroyImage(device, offscreen.image, nullptr); vkDestroyDescriptorPool(device, descriptorpool, nullptr); vkDestroyDescriptorSetLayout(device, descriptorsetlayout, nullptr); vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipelineLayout(device, pipelinelayout, nullptr); auto tEnd = std::chrono::high_resolution_clock::now(); auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count(); std::cout << "Generating irradiance cube with " << numMips << " mip levels took " << tDiff << " ms" << std::endl; } void IrradianceCube::generatePrefilteredCube(vks::TextureCubeMap &cubeMap) { auto tStart = std::chrono::high_resolution_clock::now(); const VkFormat format = VK_FORMAT_R16G16B16A16_SFLOAT; const int32_t dim = 512; const uint32_t numMips = static_cast<uint32_t>(floor(log2(dim))) + 1; // Pre-filtered cube map // Image VkImageCreateInfo imageCI = vks::initializers::imageCreateInfo(); imageCI.imageType = VK_IMAGE_TYPE_2D; imageCI.format = format; imageCI.extent.width = dim; imageCI.extent.height = dim; imageCI.extent.depth = 1; imageCI.mipLevels = numMips; imageCI.arrayLayers = 6; imageCI.samples = VK_SAMPLE_COUNT_1_BIT; imageCI.tiling = VK_IMAGE_TILING_OPTIMAL; imageCI.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; imageCI.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; VK_CHECK_RESULT(vkCreateImage(device, &imageCI, nullptr, &textures.prefilteredCube.image)); VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; vkGetImageMemoryRequirements(device, textures.prefilteredCube.image, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &textures.prefilteredCube.deviceMemory)); VK_CHECK_RESULT(vkBindImageMemory(device, textures.prefilteredCube.image, textures.prefilteredCube.deviceMemory, 0)); // Image view VkImageViewCreateInfo viewCI = vks::initializers::imageViewCreateInfo(); viewCI.viewType = VK_IMAGE_VIEW_TYPE_CUBE; viewCI.format = format; viewCI.subresourceRange = {}; viewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; viewCI.subresourceRange.levelCount = numMips; viewCI.subresourceRange.layerCount = 6; viewCI.image = textures.prefilteredCube.image; VK_CHECK_RESULT(vkCreateImageView(device, &viewCI, nullptr, &textures.prefilteredCube.view)); // Sampler VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo(); samplerCI.magFilter = VK_FILTER_LINEAR; samplerCI.minFilter = VK_FILTER_LINEAR; samplerCI.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerCI.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.minLod = 0.0f; samplerCI.maxLod = static_cast<float>(numMips); samplerCI.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK_RESULT(vkCreateSampler(device, &samplerCI, nullptr, &textures.prefilteredCube.sampler)); textures.prefilteredCube.descriptor.imageView = textures.prefilteredCube.view; textures.prefilteredCube.descriptor.sampler = textures.prefilteredCube.sampler; textures.prefilteredCube.descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; textures.prefilteredCube.device = vulkanDevice; // FB, Att, RP, Pipe, etc. VkAttachmentDescription attDesc = {}; // Color attachment attDesc.format = format; attDesc.samples = VK_SAMPLE_COUNT_1_BIT; attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE; attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorReference; // Use subpass dependencies for layout transitions std::array<VkSubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; // Renderpass VkRenderPassCreateInfo renderPassCI = vks::initializers::renderPassCreateInfo(); renderPassCI.attachmentCount = 1; renderPassCI.pAttachments = &attDesc; renderPassCI.subpassCount = 1; renderPassCI.pSubpasses = &subpassDescription; renderPassCI.dependencyCount = 2; renderPassCI.pDependencies = dependencies.data(); VkRenderPass renderpass; VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &renderpass)); struct { VkImage image; VkImageView view; VkDeviceMemory memory; VkFramebuffer framebuffer; } offscreen; // Offfscreen framebuffer { // Color attachment VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo(); imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = format; imageCreateInfo.extent.width = dim; imageCreateInfo.extent.height = dim; imageCreateInfo.extent.depth = 1; imageCreateInfo.mipLevels = 1; imageCreateInfo.arrayLayers = 1; imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageCreateInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &offscreen.image)); VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; vkGetImageMemoryRequirements(device, offscreen.image, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &offscreen.memory)); VK_CHECK_RESULT(vkBindImageMemory(device, offscreen.image, offscreen.memory, 0)); VkImageViewCreateInfo colorImageView = vks::initializers::imageViewCreateInfo(); colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D; colorImageView.format = format; colorImageView.flags = 0; colorImageView.subresourceRange = {}; colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; colorImageView.subresourceRange.baseMipLevel = 0; colorImageView.subresourceRange.levelCount = 1; colorImageView.subresourceRange.baseArrayLayer = 0; colorImageView.subresourceRange.layerCount = 1; colorImageView.image = offscreen.image; VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &offscreen.view)); VkFramebufferCreateInfo fbufCreateInfo = vks::initializers::framebufferCreateInfo(); fbufCreateInfo.renderPass = renderpass; fbufCreateInfo.attachmentCount = 1; fbufCreateInfo.pAttachments = &offscreen.view; fbufCreateInfo.width = dim; fbufCreateInfo.height = dim; fbufCreateInfo.layers = 1; VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &offscreen.framebuffer)); VkCommandBuffer layoutCmd = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); vks::tools::setImageLayout( layoutCmd, offscreen.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); flushCommandBuffer(layoutCmd, queue, true); } // Descriptors VkDescriptorSetLayout descriptorsetlayout; std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0), }; VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout)); // Descriptor Pool std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) }; VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); VkDescriptorPool descriptorpool; VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool)); // Descriptor sets VkDescriptorSet descriptorset; VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset)); VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(descriptorset, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &cubeMap.descriptor); vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); // Pipeline layout struct PushBlock { glm::mat4 mvp; float roughness; uint32_t numSamples = 32u; } pushBlock; VkPipelineLayout pipelinelayout; std::vector<VkPushConstantRange> pushConstantRanges = { vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(PushBlock), 0), }; VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1); pipelineLayoutCI.pushConstantRangeCount = 1; pipelineLayoutCI.pPushConstantRanges = pushConstantRanges.data(); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelinelayout)); // Pipeline VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); // Vertex input state VkVertexInputBindingDescription vertexInputBinding = vks::initializers::vertexInputBindingDescription(0, vdo_->vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX); VkVertexInputAttributeDescription vertexInputAttribute = vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0); VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); vertexInputState.vertexBindingDescriptionCount = 1; vertexInputState.pVertexBindingDescriptions = &vertexInputBinding; vertexInputState.vertexAttributeDescriptionCount = 1; vertexInputState.pVertexAttributeDescriptions = &vertexInputAttribute; std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelinelayout, renderpass); pipelineCI.pInputAssemblyState = &inputAssemblyState; pipelineCI.pRasterizationState = &rasterizationState; pipelineCI.pColorBlendState = &colorBlendState; pipelineCI.pMultisampleState = &multisampleState; pipelineCI.pViewportState = &viewportState; pipelineCI.pDepthStencilState = &depthStencilState; pipelineCI.pDynamicState = &dynamicState; pipelineCI.stageCount = 2; pipelineCI.pStages = shaderStages.data(); pipelineCI.pVertexInputState = &vertexInputState; pipelineCI.renderPass = renderpass; shaderStages[0] = loadShader(getAssetPath + "/pbribl/filtercube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT, device, shaderModules); shaderStages[1] = loadShader(getAssetPath + "/pbribl/prefilterenvmap.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT, device, shaderModules); VkPipeline pipeline; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, 0, 1, &pipelineCI, nullptr, &pipeline)); // Render VkClearValue clearValues[1]; clearValues[0].color = { { 0.0f, 0.0f, 0.2f, 0.0f } }; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); // Reuse render pass from example pass renderPassBeginInfo.renderPass = renderpass; renderPassBeginInfo.framebuffer = offscreen.framebuffer; renderPassBeginInfo.renderArea.extent.width = dim; renderPassBeginInfo.renderArea.extent.height = dim; renderPassBeginInfo.clearValueCount = 1; renderPassBeginInfo.pClearValues = clearValues; std::vector<glm::mat4> matrices = { // POSITIVE_X glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // NEGATIVE_X glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // POSITIVE_Y glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // NEGATIVE_Y glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // POSITIVE_Z glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), // NEGATIVE_Z glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)), }; VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f); VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0); vkCmdSetViewport(cmdBuf, 0, 1, &viewport); vkCmdSetScissor(cmdBuf, 0, 1, &scissor); VkImageSubresourceRange subresourceRange = {}; subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = numMips; subresourceRange.layerCount = 6; // Change image layout for all cubemap faces to transfer destination vks::tools::setImageLayout( cmdBuf, textures.prefilteredCube.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresourceRange); for (uint32_t m = 0; m < numMips; m++) { pushBlock.roughness = (float)m / (float)(numMips - 1); for (uint32_t f = 0; f < 6; f++) { viewport.width = static_cast<float>(dim * std::pow(0.5f, m)); viewport.height = static_cast<float>(dim * std::pow(0.5f, m)); vkCmdSetViewport(cmdBuf, 0, 1, &viewport); // Render scene from cube face's point of view vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); // Update shader push constant block pushBlock.mvp = glm::perspective((float)(M_PI / 2.0), 1.0f, 0.1f, 512.0f) * matrices[f]; vkCmdPushConstants(cmdBuf, pipelinelayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushBlock), &pushBlock); vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelinelayout, 0, 1, &descriptorset, 0, NULL); VkDeviceSize offsets[1] = { 0 }; vkCmdBindVertexBuffers(cmdBuf, 0, 1, &skybox.vertices.buffer, offsets); vkCmdBindIndexBuffer(cmdBuf, skybox.indices.buffer, 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(cmdBuf, skybox.indexCount, 1, 0, 0, 0); vkCmdEndRenderPass(cmdBuf); vks::tools::setImageLayout( cmdBuf, offscreen.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); // Copy region for transfer from framebuffer to cube face VkImageCopy copyRegion = {}; copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copyRegion.srcSubresource.baseArrayLayer = 0; copyRegion.srcSubresource.mipLevel = 0; copyRegion.srcSubresource.layerCount = 1; copyRegion.srcOffset = { 0, 0, 0 }; copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copyRegion.dstSubresource.baseArrayLayer = f; copyRegion.dstSubresource.mipLevel = m; copyRegion.dstSubresource.layerCount = 1; copyRegion.dstOffset = { 0, 0, 0 }; copyRegion.extent.width = static_cast<uint32_t>(viewport.width); copyRegion.extent.height = static_cast<uint32_t>(viewport.height); copyRegion.extent.depth = 1; vkCmdCopyImage( cmdBuf, offscreen.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, textures.prefilteredCube.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copyRegion); // Transform framebuffer color attachment back vks::tools::setImageLayout( cmdBuf, offscreen.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); } } vks::tools::setImageLayout( cmdBuf, textures.prefilteredCube.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresourceRange); vulkanDevice->flushCommandBuffer(cmdBuf, queue); // todo: cleanup vkDestroyRenderPass(device, renderpass, nullptr); vkDestroyFramebuffer(device, offscreen.framebuffer, nullptr); vkFreeMemory(device, offscreen.memory, nullptr); vkDestroyImageView(device, offscreen.view, nullptr); vkDestroyImage(device, offscreen.image, nullptr); vkDestroyDescriptorPool(device, descriptorpool, nullptr); vkDestroyDescriptorSetLayout(device, descriptorsetlayout, nullptr); vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipelineLayout(device, pipelinelayout, nullptr); auto tEnd = std::chrono::high_resolution_clock::now(); auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count(); std::cout << "Generating pre-filtered enivornment cube with " << numMips << " mip levels took " << tDiff << " ms" << std::endl; } // Generate a BRDF integration map used as a look-up-table (stores roughness / NdotV) void IrradianceCube::generateBRDFLUT(vks::TextureCubeMap &cubeMap) { auto tStart = std::chrono::high_resolution_clock::now(); const VkFormat format = VK_FORMAT_R16G16_SFLOAT; // R16G16 is supported pretty much everywhere const int32_t dim = 512; // Image VkImageCreateInfo imageCI = vks::initializers::imageCreateInfo(); imageCI.imageType = VK_IMAGE_TYPE_2D; imageCI.format = format; imageCI.extent.width = dim; imageCI.extent.height = dim; imageCI.extent.depth = 1; imageCI.mipLevels = 1; imageCI.arrayLayers = 1; imageCI.samples = VK_SAMPLE_COUNT_1_BIT; imageCI.tiling = VK_IMAGE_TILING_OPTIMAL; imageCI.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; VK_CHECK_RESULT(vkCreateImage(device, &imageCI, nullptr, &textures.lutBrdf.image)); VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; vkGetImageMemoryRequirements(device, textures.lutBrdf.image, &memReqs); memAlloc.allocationSize = memReqs.size; memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &textures.lutBrdf.deviceMemory)); VK_CHECK_RESULT(vkBindImageMemory(device, textures.lutBrdf.image, textures.lutBrdf.deviceMemory, 0)); // Image view VkImageViewCreateInfo viewCI = vks::initializers::imageViewCreateInfo(); viewCI.viewType = VK_IMAGE_VIEW_TYPE_2D; viewCI.format = format; viewCI.subresourceRange = {}; viewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; viewCI.subresourceRange.levelCount = 1; viewCI.subresourceRange.layerCount = 1; viewCI.image = textures.lutBrdf.image; VK_CHECK_RESULT(vkCreateImageView(device, &viewCI, nullptr, &textures.lutBrdf.view)); // Sampler VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo(); samplerCI.magFilter = VK_FILTER_LINEAR; samplerCI.minFilter = VK_FILTER_LINEAR; samplerCI.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerCI.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerCI.minLod = 0.0f; samplerCI.maxLod = 1.0f; samplerCI.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK_RESULT(vkCreateSampler(device, &samplerCI, nullptr, &textures.lutBrdf.sampler)); textures.lutBrdf.descriptor.imageView = textures.lutBrdf.view; textures.lutBrdf.descriptor.sampler = textures.lutBrdf.sampler; textures.lutBrdf.descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; textures.lutBrdf.device = vulkanDevice; // FB, Att, RP, Pipe, etc. VkAttachmentDescription attDesc = {}; // Color attachment attDesc.format = format; attDesc.samples = VK_SAMPLE_COUNT_1_BIT; attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE; attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attDesc.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = 1; subpassDescription.pColorAttachments = &colorReference; // Use subpass dependencies for layout transitions std::array<VkSubpassDependency, 2> dependencies; dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; dependencies[0].dstSubpass = 0; dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies[1].srcSubpass = 0; dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; // Create the actual renderpass VkRenderPassCreateInfo renderPassCI = vks::initializers::renderPassCreateInfo(); renderPassCI.attachmentCount = 1; renderPassCI.pAttachments = &attDesc; renderPassCI.subpassCount = 1; renderPassCI.pSubpasses = &subpassDescription; renderPassCI.dependencyCount = 2; renderPassCI.pDependencies = dependencies.data(); VkRenderPass renderpass; VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &renderpass)); VkFramebufferCreateInfo framebufferCI = vks::initializers::framebufferCreateInfo(); framebufferCI.renderPass = renderpass; framebufferCI.attachmentCount = 1; framebufferCI.pAttachments = &textures.lutBrdf.view; framebufferCI.width = dim; framebufferCI.height = dim; framebufferCI.layers = 1; VkFramebuffer framebuffer; VK_CHECK_RESULT(vkCreateFramebuffer(device, &framebufferCI, nullptr, &framebuffer)); // Desriptors VkDescriptorSetLayout descriptorsetlayout; std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {}; VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout)); // Descriptor Pool std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) }; VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); VkDescriptorPool descriptorpool; VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool)); // Descriptor sets VkDescriptorSet descriptorset; VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset)); // Pipeline layout VkPipelineLayout pipelinelayout; VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelinelayout)); // Pipeline VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); VkPipelineVertexInputStateCreateInfo emptyInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelinelayout, renderpass); pipelineCI.pInputAssemblyState = &inputAssemblyState; pipelineCI.pRasterizationState = &rasterizationState; pipelineCI.pColorBlendState = &colorBlendState; pipelineCI.pMultisampleState = &multisampleState; pipelineCI.pViewportState = &viewportState; pipelineCI.pDepthStencilState = &depthStencilState; pipelineCI.pDynamicState = &dynamicState; pipelineCI.stageCount = 2; pipelineCI.pStages = shaderStages.data(); pipelineCI.pVertexInputState = &emptyInputState; // Look-up-table (from BRDF) pipeline shaderStages[0] = loadShader(getAssetPath + "/pbribl/genbrdflut.vert.spv", VK_SHADER_STAGE_VERTEX_BIT, device, shaderModules); shaderStages[1] = loadShader(getAssetPath + "/pbribl/genbrdflut.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT, device, shaderModules); VkPipeline pipeline; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, 0, 1, &pipelineCI, nullptr, &pipeline)); // Render VkClearValue clearValues[1]; clearValues[0].color = { { 0.0f, 0.0f, 0.0f, 1.0f } }; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); renderPassBeginInfo.renderPass = renderpass; renderPassBeginInfo.renderArea.extent.width = dim; renderPassBeginInfo.renderArea.extent.height = dim; renderPassBeginInfo.clearValueCount = 1; renderPassBeginInfo.pClearValues = clearValues; renderPassBeginInfo.framebuffer = framebuffer; VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f); VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0); vkCmdSetViewport(cmdBuf, 0, 1, &viewport); vkCmdSetScissor(cmdBuf, 0, 1, &scissor); vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdDraw(cmdBuf, 3, 1, 0, 0); vkCmdEndRenderPass(cmdBuf); vulkanDevice->flushCommandBuffer(cmdBuf, queue); vkQueueWaitIdle(queue); // todo: cleanup vkDestroyPipeline(device, pipeline, nullptr); vkDestroyPipelineLayout(device, pipelinelayout, nullptr); vkDestroyRenderPass(device, renderpass, nullptr); vkDestroyFramebuffer(device, framebuffer, nullptr); vkDestroyDescriptorSetLayout(device, descriptorsetlayout, nullptr); vkDestroyDescriptorPool(device, descriptorpool, nullptr); auto tEnd = std::chrono::high_resolution_clock::now(); auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count(); std::cout << "Generating BRDF LUT took " << tDiff << " ms" << std::endl; }
47.678128
191
0.809131
liuhongyi0101
a644162d87e582ffc312ceca6f64e1dcc19b38cb
2,547
cpp
C++
Source/ThirdParty/strtk/strtk/strtk_random_line.cpp
morrow1nd/ToyUtility
0df3364a516de7a396b1cbb7975263506f41121d
[ "MIT" ]
null
null
null
Source/ThirdParty/strtk/strtk/strtk_random_line.cpp
morrow1nd/ToyUtility
0df3364a516de7a396b1cbb7975263506f41121d
[ "MIT" ]
null
null
null
Source/ThirdParty/strtk/strtk/strtk_random_line.cpp
morrow1nd/ToyUtility
0df3364a516de7a396b1cbb7975263506f41121d
[ "MIT" ]
null
null
null
/* ***************************************************************** * String Toolkit Library * * * * Random Line Selection * * Author: Arash Partow (2002-2018) * * URL: http://www.partow.net/programming/strtk/index.html * * * * Copyright notice: * * Free use of the String Toolkit Library is permitted under the * * guidelines and in accordance with the most current version of * * the MIT License. * * http://www.opensource.org/licenses/MIT * * * ***************************************************************** */ /* Description: This is a solution to the problem of randomly selecting a line from a text file in the most efficient way possible taking into account time and space complexities, also ensuring that the probability of the line selected is exactly 1/N where N is the number of lines in the text file - It should be noted that the lines can be of varying length. */ #include <cstddef> #include <iostream> #include <iterator> #include <string> #include <deque> #include <ctime> #include <boost/random.hpp> //#include <random> #include "strtk.hpp" #ifndef strtk_enable_random #error This example requires random #endif class random_line_selector { public: random_line_selector(std::string& line, const std::size_t& seed = 0xA5A5A5A5) : line_count_(1), line_(line), rng_(seed) {} inline void operator()(const std::string& s) { if (rng_() < (1.0 / line_count_)) line_ = s; ++line_count_; } private: random_line_selector operator=(const random_line_selector&); std::size_t line_count_; // should be long long std::string& line_; strtk::uniform_real_rng rng_; }; int main(int argc, char* argv[]) { if (2 != argc) { std::cout << "usage: strtk_random_line <file name>" << std::endl; return 1; } std::string file_name = argv[1]; std::string line; strtk::for_each_line(file_name, random_line_selector(line,static_cast<std::size_t>(::time(0)))); std::cout << line << std::endl; return 0; }
28.3
88
0.506086
morrow1nd
a64481e6bc733eaebbb065b5395c64d06c293ac8
5,122
cpp
C++
tileconv/tilethreadpool_win32.cpp
Argent77/tileconv
b1b4479e7223d7d3cc0ffe17b86ada60f7fd0b0e
[ "MIT" ]
1
2015-03-03T21:30:28.000Z
2015-03-03T21:30:28.000Z
tileconv/tilethreadpool_win32.cpp
InfinityTools/tileconv
b1b4479e7223d7d3cc0ffe17b86ada60f7fd0b0e
[ "MIT" ]
1
2015-05-11T09:26:14.000Z
2015-05-11T09:26:14.000Z
tileconv/tilethreadpool_win32.cpp
Argent77/tileconv
b1b4479e7223d7d3cc0ffe17b86ada60f7fd0b0e
[ "MIT" ]
1
2022-02-16T17:47:50.000Z
2022-02-16T17:47:50.000Z
/* Copyright (c) 2014 Argent77 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. */ #ifdef USE_WINTHREADS #include "tilethreadpool_win32.h" namespace tc { unsigned getThreadPoolAutoThreads() { SYSTEM_INFO sysinfo; ::GetSystemInfo(&sysinfo); return std::max(1u, (unsigned)sysinfo.dwNumberOfProcessors); } ThreadPoolPtr createThreadPool(int threadNum, int tileNum) { return ThreadPoolPtr(new TileThreadPoolWin32(threadNum, tileNum)); } TileThreadPoolWin32::TileThreadPoolWin32(unsigned threadNum, unsigned tileNum) noexcept : TileThreadPool(tileNum) , m_activeThreads(0) , m_mainThread(::GetCurrentThread()) , m_activeMutex(::CreateMutex(NULL, FALSE, NULL)) , m_tilesMutex(::CreateMutex(NULL, FALSE, NULL)) , m_resultsMutex(::CreateMutex(NULL, FALSE, NULL)) , m_threadsNum() , m_threads(nullptr) { m_threadsNum = std::max(1u, std::min(MAX_THREADS, threadNum)); m_threads.reset(new HANDLE[m_threadsNum], std::default_delete<HANDLE[]>()); for (unsigned i = 0; i < threadNum; i++) { m_threads.get()[i] = ::CreateThread(NULL, 0, TileThreadPoolWin32::threadMain, this, 0, NULL); } } TileThreadPoolWin32::~TileThreadPoolWin32() noexcept { setTerminate(true); ::WaitForMultipleObjects(m_threadsNum, m_threads.get(), TRUE, INFINITE); for (unsigned i = 0; i < m_threadsNum; i++) { ::CloseHandle(m_threads.get()[i]); } ::CloseHandle(m_activeMutex); ::CloseHandle(m_tilesMutex); ::CloseHandle(m_resultsMutex); } void TileThreadPoolWin32::addTileData(TileDataPtr tileData) noexcept { while (!canAddTileData()) { ::Sleep(50); } ::WaitForSingleObject(m_tilesMutex, INFINITE); getTileQueue().emplace(tileData); ::ReleaseMutex(m_tilesMutex); } TileDataPtr TileThreadPoolWin32::getResult() noexcept { ::WaitForSingleObject(m_resultsMutex, INFINITE); if (!getResultQueue().empty()) { TileDataPtr retVal = getResultQueue().top(); getResultQueue().pop(); ::ReleaseMutex(m_resultsMutex); return retVal; } else { ::ReleaseMutex(m_resultsMutex); return TileDataPtr(nullptr); } } const TileDataPtr TileThreadPoolWin32::peekResult() noexcept { ::WaitForSingleObject(m_resultsMutex, INFINITE); if (!getResultQueue().empty()) { TileDataPtr retVal = getResultQueue().top(); ::ReleaseMutex(m_resultsMutex); return retVal; } else { ::ReleaseMutex(m_resultsMutex); return TileDataPtr(nullptr); } } void TileThreadPoolWin32::waitForResult() noexcept { while (!hasResult() && !finished()) { ::Sleep(50); } } bool TileThreadPoolWin32::finished() noexcept { HANDLE locks[] = { m_tilesMutex, m_activeMutex, m_resultsMutex }; ::WaitForMultipleObjects(3, locks, TRUE, INFINITE); bool retVal = (getTileQueue().empty() && getActiveThreads() == 0 && getResultQueue().empty()); ::ReleaseMutex(m_tilesMutex); ::ReleaseMutex(m_activeMutex); ::ReleaseMutex(m_resultsMutex); return retVal; } DWORD WINAPI TileThreadPoolWin32::threadMain(LPVOID lpParam) { TileThreadPoolWin32 *instance = (TileThreadPoolWin32*)lpParam; if (instance != nullptr) { while (!instance->terminate()) { ::WaitForSingleObject(instance->m_tilesMutex, INFINITE); if (!instance->getTileQueue().empty()) { instance->threadActivated(); TileDataPtr tileData = instance->getTileQueue().front(); instance->getTileQueue().pop(); ::ReleaseMutex(instance->m_tilesMutex); (*tileData)(); // storing results ::WaitForSingleObject(instance->m_resultsMutex, INFINITE); instance->getResultQueue().push(tileData); ::ReleaseMutex(instance->m_resultsMutex); instance->threadDeactivated(); } else { ::ReleaseMutex(instance->m_tilesMutex); ::Sleep(50); } } } return 0; } void TileThreadPoolWin32::threadActivated() noexcept { ::WaitForSingleObject(m_activeMutex, INFINITE); m_activeThreads++; ::ReleaseMutex(m_activeMutex); } void TileThreadPoolWin32::threadDeactivated() noexcept { ::WaitForSingleObject(m_activeMutex, INFINITE); m_activeThreads--; ::ReleaseMutex(m_activeMutex); } } // namespace tc #endif // USE_WINTHREADS
28.142857
97
0.725303
Argent77
a6492cd038b8462ce1d77d5d4e1154f9c8b953ff
5,608
cpp
C++
lib/data.cpp
bkj/delphi
14972e783551029ddf7db83961b73cf99c4c48e9
[ "Apache-2.0" ]
null
null
null
lib/data.cpp
bkj/delphi
14972e783551029ddf7db83961b73cf99c4c48e9
[ "Apache-2.0" ]
null
null
null
lib/data.cpp
bkj/delphi
14972e783551029ddf7db83961b73cf99c4c48e9
[ "Apache-2.0" ]
null
null
null
#include "data.hpp" #include "utils.hpp" #include <fmt/format.h> #include <sqlite3.h> #include <chrono> #include <range/v3/all.hpp> #include <thread> using namespace std; vector<double> get_observations_for(string indicator, string country, string state, string county, int year, int month, string unit, bool use_heuristic) { using fmt::print; using namespace fmt::literals; sqlite3* db = nullptr; vector<double> observations = {}; int rc; rc = sqlite3_open(getenv("DELPHI_DB"), &db); if (rc != SQLITE_OK) { throw runtime_error("Could not open db. Do you have the DELPHI_DB " "environment correctly set to point to the Delphi database?"); } sqlite3_stmt* stmt = nullptr; string query = "select Unit, Value from indicator where `Variable` like '{}'"_format( indicator); string check_q; if (!country.empty()) { check_q = "{0} and `Country` is '{1}'"_format(query, country); rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL); if (rc == SQLITE_OK) { rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { query = check_q; } else { print("Could not find data for country {0}. Averaging data over all " "countries for given axes (Default Setting)\n", country); } sqlite3_finalize(stmt); stmt = nullptr; } } if (!state.empty()) { check_q = "{0} and `State` is '{1}'"_format(query, state); rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL); rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { query = check_q; } else { print("Could not find data for state {0}. Only obtaining data " "of the country level (Default Setting)\n", state); } sqlite3_finalize(stmt); stmt = nullptr; } if (!county.empty()) { check_q = "{0} and `County` is '{1}'"_format(query, county); rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL); rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { query = check_q; } else { print("Could not find data for county {0}. Only obtaining data " "of the state level (Default Setting)\n", county); } sqlite3_finalize(stmt); stmt = nullptr; } if (!unit.empty()) { check_q = "{0} and `Unit` is '{1}'"_format(query, unit); rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL); rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { query = check_q; } else { sqlite3_finalize(stmt); stmt = nullptr; print("Could not find data for unit {0}. Using first unit in " "alphabetical order (Default Setting)\n", unit); vector<string> units; rc = sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, NULL); while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { string ind_unit = string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))); units.push_back(ind_unit); } sqlite3_finalize(stmt); stmt = nullptr; if (!units.empty()) { ranges::sort(units); query = "{0} and `Unit` is '{1}'"_format(query, units.front()); } else { print("No units found for indicator {0}", indicator); } } } sqlite3_finalize(stmt); stmt = nullptr; if (!(year == -1)) { check_q = "{0} and `Year` is '{1}'"_format(query, year); rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL); rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { query = check_q; } else { print("Could not find data for year {0}. Aggregating data " "over all years (Default Setting)\n", year); } sqlite3_finalize(stmt); stmt = nullptr; } if (month != 0) { check_q = "{0} and `Month` is '{1}'"_format(query, month); rc = sqlite3_prepare_v2(db, check_q.c_str(), -1, &stmt, NULL); rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { query = check_q; } else { print("Could not find data for month {0}. Aggregating data " "over all months (Default Setting)\n", month); } sqlite3_finalize(stmt); stmt = nullptr; } double observation; rc = sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, NULL); while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { observation = sqlite3_column_double(stmt, 1); observations.push_back(observation); } sqlite3_finalize(stmt); stmt = nullptr; if (observations.empty() and use_heuristic) { string final_query = "{0} and `Year` is '{1}' and `Month` is '0'"_format(query, year); sqlite3_prepare_v2(db, final_query.c_str(), -1, &stmt, NULL); while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { observation = sqlite3_column_double(stmt, 1); // TODO: This math is only valid if the observation we query is an annual // aggregate. For example if it is an yearly sample or an yearly average // this is not correct. We need a more intelligent way to handle this // situation. observation = observation / 12; observations.push_back(observation); } sqlite3_finalize(stmt); stmt = nullptr; } rc = sqlite3_finalize(stmt); rc = sqlite3_close(db); stmt = nullptr; db = nullptr; return observations; }
28.907216
80
0.570078
bkj
a64bf3427ecce34d37cc506c30e5465e6f223b8f
2,706
cpp
C++
src/frame/frame_list.cpp
monopoldesign/M5Paper
27c49dab9340a82d7bb6748383217e80f9b2ac31
[ "MIT" ]
1
2021-10-10T09:45:36.000Z
2021-10-10T09:45:36.000Z
src/frame/frame_list.cpp
monopoldesign/M5Paper
27c49dab9340a82d7bb6748383217e80f9b2ac31
[ "MIT" ]
null
null
null
src/frame/frame_list.cpp
monopoldesign/M5Paper
27c49dab9340a82d7bb6748383217e80f9b2ac31
[ "MIT" ]
null
null
null
#include "frame_list.h" #include "frame_list_menu.h" #include "../epdgui/epdgui_button.h" Frame_List::Frame_List(bool isHorizontal) : Frame_Base() { _frame_name = "Frame_List"; const uint16_t kKeyBaseY = 628; key_run1 = new EPDGUI_Button("RUN1", 4, kKeyBaseY, 250, 52); key_run2 = new EPDGUI_Button("RUN2", 286, kKeyBaseY, 250, 52); inputbox1 = new EPDGUI_Textbox(4, 100, 532, 250); inputbox1->SetState(EPDGUI_Textbox::EVENT_PRESSED); inputbox1->SetTextSize(48); inputbox2 = new EPDGUI_Textbox(4, 360, 532, 250); inputbox2->SetState(EPDGUI_Textbox::EVENT_PRESSED); inputbox2->SetTextSize(48); keyboard = new EPDGUI_Keyboard(isHorizontal); exitbtn("Home"); menubtn("Menu"); _canvas_title->drawString("Keyboard", 270, 34); key_run1->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)inputbox1); key_run1->Bind(EPDGUI_Button::EVENT_RELEASED, key_run_cb); key_run2->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)inputbox2); key_run2->Bind(EPDGUI_Button::EVENT_RELEASED, key_run_cb); _key_exit->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)(&_is_run)); _key_exit->Bind(EPDGUI_Button::EVENT_RELEASED, &Frame_Base::exit_cb); _key_menu->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)(&_is_run)); _key_menu->Bind(EPDGUI_Button::EVENT_RELEASED, showMenu); } Frame_List::~Frame_List(void) { delete inputbox1; delete inputbox2; delete keyboard; delete _key_exit; delete _key_menu; delete key_run1; delete key_run2; } int Frame_List::init(epdgui_args_vector_t &args) { _is_run = 1; M5.EPD.Clear(); _canvas_title->pushCanvas(0, 8, UPDATE_MODE_NONE); EPDGUI_AddObject(_key_exit); EPDGUI_AddObject(_key_menu); EPDGUI_AddObject(key_run1); EPDGUI_AddObject(key_run2); EPDGUI_AddObject(inputbox1); EPDGUI_AddObject(inputbox2); EPDGUI_AddObject(keyboard); if (args.size() > 0) { String *result = (String*)(args[0]); inputbox2->SetText(""); inputbox2->AddText(*result); delete result; args.pop_back(); } else { inputbox1->SetText(""); inputbox2->SetText(""); } return 6; } int Frame_List::run() { Frame_Base::run(); if (inputbox1->isSelected()) inputbox1->AddText(keyboard->getData()); else if (inputbox2->isSelected()) inputbox2->AddText(keyboard->getData()); return 1; } void Frame_List::key_run_cb(epdgui_args_vector_t &args) { ((EPDGUI_Textbox*)(args[0]))->SetText(""); } void Frame_List::showMenu(epdgui_args_vector_t &args) { Frame_Base *frame = EPDGUI_GetFrame("Frame_List_Menu"); if (frame == NULL) { frame = new Frame_List_Menu(); EPDGUI_AddFrame("Frame_List_Menu", frame); } EPDGUI_PushFrame(frame); *((int*)(args[0])) = 0; }
23.736842
77
0.708795
monopoldesign
a64cdf35625182747eace5440734c4bc9171c2d9
27,773
cpp
C++
crnlib/crn_ktx_texture.cpp
bmorel/crunch
78b8a3f290e417f39cdda5d2b1355958303cfbdd
[ "Zlib" ]
null
null
null
crnlib/crn_ktx_texture.cpp
bmorel/crunch
78b8a3f290e417f39cdda5d2b1355958303cfbdd
[ "Zlib" ]
null
null
null
crnlib/crn_ktx_texture.cpp
bmorel/crunch
78b8a3f290e417f39cdda5d2b1355958303cfbdd
[ "Zlib" ]
null
null
null
// File: crn_ktx_texture.cpp #include "crn_core.h" #include "crn_ktx_texture.h" #include "crn_console.h" // Set #if CRNLIB_KTX_PVRTEX_WORKAROUNDS to 1 to enable various workarounds for oddball KTX files written by PVRTexTool. #define CRNLIB_KTX_PVRTEX_WORKAROUNDS 1 namespace crnlib { const uint8 s_ktx_file_id[12] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; bool is_packed_pixel_ogl_type(uint32 ogl_type) { switch (ogl_type) { case KTX_UNSIGNED_BYTE_3_3_2: case KTX_UNSIGNED_BYTE_2_3_3_REV: case KTX_UNSIGNED_SHORT_5_6_5: case KTX_UNSIGNED_SHORT_5_6_5_REV: case KTX_UNSIGNED_SHORT_4_4_4_4: case KTX_UNSIGNED_SHORT_4_4_4_4_REV: case KTX_UNSIGNED_SHORT_5_5_5_1: case KTX_UNSIGNED_SHORT_1_5_5_5_REV: case KTX_UNSIGNED_INT_8_8_8_8: case KTX_UNSIGNED_INT_8_8_8_8_REV: case KTX_UNSIGNED_INT_10_10_10_2: case KTX_UNSIGNED_INT_2_10_10_10_REV: case KTX_UNSIGNED_INT_24_8: case KTX_UNSIGNED_INT_10F_11F_11F_REV: case KTX_UNSIGNED_INT_5_9_9_9_REV: return true; } return false; } uint get_ogl_type_size(uint32 ogl_type) { switch (ogl_type) { case KTX_UNSIGNED_BYTE: case KTX_BYTE: return 1; case KTX_HALF_FLOAT: case KTX_UNSIGNED_SHORT: case KTX_SHORT: return 2; case KTX_FLOAT: case KTX_UNSIGNED_INT: case KTX_INT: return 4; case KTX_UNSIGNED_BYTE_3_3_2: case KTX_UNSIGNED_BYTE_2_3_3_REV: return 1; case KTX_UNSIGNED_SHORT_5_6_5: case KTX_UNSIGNED_SHORT_5_6_5_REV: case KTX_UNSIGNED_SHORT_4_4_4_4: case KTX_UNSIGNED_SHORT_4_4_4_4_REV: case KTX_UNSIGNED_SHORT_5_5_5_1: case KTX_UNSIGNED_SHORT_1_5_5_5_REV: return 2; case KTX_UNSIGNED_INT_8_8_8_8: case KTX_UNSIGNED_INT_8_8_8_8_REV: case KTX_UNSIGNED_INT_10_10_10_2: case KTX_UNSIGNED_INT_2_10_10_10_REV: case KTX_UNSIGNED_INT_24_8: case KTX_UNSIGNED_INT_10F_11F_11F_REV: case KTX_UNSIGNED_INT_5_9_9_9_REV: return 4; } return 0; } uint32 get_ogl_base_internal_fmt(uint32 ogl_fmt) { switch (ogl_fmt) { case KTX_ETC1_RGB8_OES: case KTX_COMPRESSED_RGB8_ETC2: case KTX_RGB_S3TC: case KTX_RGB4_S3TC: case KTX_COMPRESSED_RGB_S3TC_DXT1_EXT: case KTX_COMPRESSED_SRGB_S3TC_DXT1_EXT: return KTX_RGB; case KTX_COMPRESSED_RGBA8_ETC2_EAC: case KTX_COMPRESSED_RGBA_S3TC_DXT1_EXT: case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: case KTX_RGBA_S3TC: case KTX_RGBA4_S3TC: case KTX_COMPRESSED_RGBA_S3TC_DXT3_EXT: case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: case KTX_COMPRESSED_RGBA_S3TC_DXT5_EXT: case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: case KTX_RGBA_DXT5_S3TC: case KTX_RGBA4_DXT5_S3TC: return KTX_RGBA; case 1: case KTX_RED: case KTX_RED_INTEGER: case KTX_GREEN: case KTX_GREEN_INTEGER: case KTX_BLUE: case KTX_BLUE_INTEGER: case KTX_R8: case KTX_R8UI: case KTX_LUMINANCE8: case KTX_ALPHA: case KTX_LUMINANCE: case KTX_COMPRESSED_RED_RGTC1_EXT: case KTX_COMPRESSED_SIGNED_RED_RGTC1_EXT: case KTX_COMPRESSED_LUMINANCE_LATC1_EXT: case KTX_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT: return KTX_RED; case 2: case KTX_RG: case KTX_RG8: case KTX_RG_INTEGER: case KTX_LUMINANCE_ALPHA: case KTX_COMPRESSED_RED_GREEN_RGTC2_EXT: case KTX_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: case KTX_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT: case KTX_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT: return KTX_RG; case 3: case KTX_SRGB: case KTX_RGB: case KTX_RGB_INTEGER: case KTX_BGR: case KTX_BGR_INTEGER: case KTX_RGB8: case KTX_SRGB8: return KTX_RGB; case 4: case KTX_RGBA: case KTX_BGRA: case KTX_RGBA_INTEGER: case KTX_BGRA_INTEGER: case KTX_SRGB_ALPHA: case KTX_SRGB8_ALPHA8: case KTX_RGBA8: return KTX_RGBA; } return 0; } bool get_ogl_fmt_desc(uint32 ogl_fmt, uint32 ogl_type, uint& block_dim, uint& bytes_per_block) { uint ogl_type_size = get_ogl_type_size(ogl_type); block_dim = 1; bytes_per_block = 0; switch (ogl_fmt) { case KTX_COMPRESSED_RED_RGTC1_EXT: case KTX_COMPRESSED_SIGNED_RED_RGTC1_EXT: case KTX_COMPRESSED_LUMINANCE_LATC1_EXT: case KTX_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT: case KTX_ETC1_RGB8_OES: case KTX_COMPRESSED_RGB8_ETC2: case KTX_RGB_S3TC: case KTX_RGB4_S3TC: case KTX_COMPRESSED_RGB_S3TC_DXT1_EXT: case KTX_COMPRESSED_RGBA_S3TC_DXT1_EXT: case KTX_COMPRESSED_SRGB_S3TC_DXT1_EXT: case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: { block_dim = 4; bytes_per_block = 8; break; } case KTX_COMPRESSED_RGBA8_ETC2_EAC: case KTX_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT: case KTX_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT: case KTX_COMPRESSED_RED_GREEN_RGTC2_EXT: case KTX_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT: case KTX_RGBA_S3TC: case KTX_RGBA4_S3TC: case KTX_COMPRESSED_RGBA_S3TC_DXT3_EXT: case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: case KTX_COMPRESSED_RGBA_S3TC_DXT5_EXT: case KTX_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: case KTX_RGBA_DXT5_S3TC: case KTX_RGBA4_DXT5_S3TC: { block_dim = 4; bytes_per_block = 16; break; } case 1: case KTX_ALPHA: case KTX_RED: case KTX_GREEN: case KTX_BLUE: case KTX_RED_INTEGER: case KTX_GREEN_INTEGER: case KTX_BLUE_INTEGER: case KTX_LUMINANCE: { bytes_per_block = ogl_type_size; break; } case KTX_R8: case KTX_R8UI: case KTX_ALPHA8: case KTX_LUMINANCE8: { bytes_per_block = 1; break; } case 2: case KTX_RG: case KTX_RG_INTEGER: case KTX_LUMINANCE_ALPHA: { bytes_per_block = 2 * ogl_type_size; break; } case KTX_RG8: case KTX_LUMINANCE8_ALPHA8: { bytes_per_block = 2; break; } case 3: case KTX_SRGB: case KTX_RGB: case KTX_BGR: case KTX_RGB_INTEGER: case KTX_BGR_INTEGER: { bytes_per_block = is_packed_pixel_ogl_type(ogl_type) ? ogl_type_size : (3 * ogl_type_size); break; } case KTX_RGB8: case KTX_SRGB8: { bytes_per_block = 3; break; } case 4: case KTX_RGBA: case KTX_BGRA: case KTX_RGBA_INTEGER: case KTX_BGRA_INTEGER: case KTX_SRGB_ALPHA: { bytes_per_block = is_packed_pixel_ogl_type(ogl_type) ? ogl_type_size : (4 * ogl_type_size); break; } case KTX_SRGB8_ALPHA8: case KTX_RGBA8: { bytes_per_block = 4; break; } default: return false; } return true; } bool ktx_texture::compute_pixel_info() { if ((!m_header.m_glType) || (!m_header.m_glFormat)) { if ((m_header.m_glType) || (m_header.m_glFormat)) return false; // Must be a compressed format. if (!get_ogl_fmt_desc(m_header.m_glInternalFormat, m_header.m_glType, m_block_dim, m_bytes_per_block)) { #if CRNLIB_KTX_PVRTEX_WORKAROUNDS if ((!m_header.m_glInternalFormat) && (!m_header.m_glType) && (!m_header.m_glTypeSize) && (!m_header.m_glBaseInternalFormat)) { // PVRTexTool writes bogus headers when outputting ETC1. console::warning("ktx_texture::compute_pixel_info: Header doesn't specify any format, assuming ETC1 and hoping for the best"); m_header.m_glBaseInternalFormat = KTX_RGB; m_header.m_glInternalFormat = KTX_ETC1_RGB8_OES; m_header.m_glTypeSize = 1; m_block_dim = 4; m_bytes_per_block = 8; return true; } #endif return false; } if (m_block_dim == 1) return false; } else { // Must be an uncompressed format. if (!get_ogl_fmt_desc(m_header.m_glFormat, m_header.m_glType, m_block_dim, m_bytes_per_block)) return false; if (m_block_dim > 1) return false; } return true; } bool ktx_texture::read_from_stream(data_stream_serializer& serializer) { clear(); // Read header if (serializer.read(&m_header, 1, sizeof(m_header)) != sizeof(ktx_header)) return false; // Check header if (memcmp(s_ktx_file_id, m_header.m_identifier, sizeof(m_header.m_identifier))) return false; if ((m_header.m_endianness != KTX_OPPOSITE_ENDIAN) && (m_header.m_endianness != KTX_ENDIAN)) return false; m_opposite_endianness = (m_header.m_endianness == KTX_OPPOSITE_ENDIAN); if (m_opposite_endianness) { m_header.endian_swap(); if ((m_header.m_glTypeSize != sizeof(uint8)) && (m_header.m_glTypeSize != sizeof(uint16)) && (m_header.m_glTypeSize != sizeof(uint32))) return false; } if (!check_header()) return false; if (!compute_pixel_info()) return false; uint8 pad_bytes[3]; // Read the key value entries uint num_key_value_bytes_remaining = m_header.m_bytesOfKeyValueData; while (num_key_value_bytes_remaining) { if (num_key_value_bytes_remaining < sizeof(uint32)) return false; uint32 key_value_byte_size; if (serializer.read(&key_value_byte_size, 1, sizeof(uint32)) != sizeof(uint32)) return false; num_key_value_bytes_remaining -= sizeof(uint32); if (m_opposite_endianness) key_value_byte_size = utils::swap32(key_value_byte_size); if (key_value_byte_size > num_key_value_bytes_remaining) return false; uint8_vec key_value_data; if (key_value_byte_size) { key_value_data.resize(key_value_byte_size); if (serializer.read(&key_value_data[0], 1, key_value_byte_size) != key_value_byte_size) return false; } m_key_values.push_back(key_value_data); uint padding = 3 - ((key_value_byte_size + 3) % 4); if (padding) { if (serializer.read(pad_bytes, 1, padding) != padding) return false; } num_key_value_bytes_remaining -= key_value_byte_size; if (num_key_value_bytes_remaining < padding) return false; num_key_value_bytes_remaining -= padding; } // Now read the mip levels uint total_faces = get_num_mips() * get_array_size() * get_num_faces() * get_depth(); if ((!total_faces) || (total_faces > 65535)) return false; // See Section 2.8 of KTX file format: No rounding to block sizes should be applied for block compressed textures. // OK, I'm going to break that rule otherwise KTX can only store a subset of textures that DDS can handle for no good reason. #if 0 const uint mip0_row_blocks = m_header.m_pixelWidth / m_block_dim; const uint mip0_col_blocks = CRNLIB_MAX(1, m_header.m_pixelHeight) / m_block_dim; #else const uint mip0_row_blocks = (m_header.m_pixelWidth + m_block_dim - 1) / m_block_dim; const uint mip0_col_blocks = (CRNLIB_MAX(1, m_header.m_pixelHeight) + m_block_dim - 1) / m_block_dim; #endif if ((!mip0_row_blocks) || (!mip0_col_blocks)) return false; bool has_valid_image_size_fields = true; bool disable_mip_and_cubemap_padding = false; #if CRNLIB_KTX_PVRTEX_WORKAROUNDS { // PVRTexTool has a bogus KTX writer that doesn't write any imageSize fields. Nice. size_t expected_bytes_remaining = 0; for (uint mip_level = 0; mip_level < get_num_mips(); mip_level++) { uint mip_width, mip_height, mip_depth; get_mip_dim(mip_level, mip_width, mip_height, mip_depth); const uint mip_row_blocks = (mip_width + m_block_dim - 1) / m_block_dim; const uint mip_col_blocks = (mip_height + m_block_dim - 1) / m_block_dim; if ((!mip_row_blocks) || (!mip_col_blocks)) return false; expected_bytes_remaining += sizeof(uint32); if ((!m_header.m_numberOfArrayElements) && (get_num_faces() == 6)) { for (uint face = 0; face < get_num_faces(); face++) { uint slice_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block; expected_bytes_remaining += slice_size; uint num_cube_pad_bytes = 3 - ((slice_size + 3) % 4); expected_bytes_remaining += num_cube_pad_bytes; } } else { uint total_mip_size = 0; for (uint array_element = 0; array_element < get_array_size(); array_element++) { for (uint face = 0; face < get_num_faces(); face++) { for (uint zslice = 0; zslice < mip_depth; zslice++) { uint slice_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block; total_mip_size += slice_size; } } } expected_bytes_remaining += total_mip_size; uint num_mip_pad_bytes = 3 - ((total_mip_size + 3) % 4); expected_bytes_remaining += num_mip_pad_bytes; } } if (serializer.get_stream()->get_remaining() < expected_bytes_remaining) { has_valid_image_size_fields = false; disable_mip_and_cubemap_padding = true; console::warning("ktx_texture::read_from_stream: KTX file size is smaller than expected - trying to read anyway without imageSize fields"); } } #endif for (uint mip_level = 0; mip_level < get_num_mips(); mip_level++) { uint mip_width, mip_height, mip_depth; get_mip_dim(mip_level, mip_width, mip_height, mip_depth); const uint mip_row_blocks = (mip_width + m_block_dim - 1) / m_block_dim; const uint mip_col_blocks = (mip_height + m_block_dim - 1) / m_block_dim; if ((!mip_row_blocks) || (!mip_col_blocks)) return false; uint32 image_size = 0; if (!has_valid_image_size_fields) image_size = mip_depth * mip_row_blocks * mip_col_blocks * m_bytes_per_block * get_array_size() * get_num_faces(); else { if (serializer.read(&image_size, 1, sizeof(image_size)) != sizeof(image_size)) return false; if (m_opposite_endianness) image_size = utils::swap32(image_size); } if (!image_size) return false; uint total_mip_size = 0; if ((!m_header.m_numberOfArrayElements) && (get_num_faces() == 6)) { // plain non-array cubemap for (uint face = 0; face < get_num_faces(); face++) { CRNLIB_ASSERT(m_image_data.size() == get_image_index(mip_level, 0, face, 0)); m_image_data.push_back(uint8_vec()); uint8_vec& image_data = m_image_data.back(); image_data.resize(image_size); if (serializer.read(&image_data[0], 1, image_size) != image_size) return false; if (m_opposite_endianness) utils::endian_swap_mem(&image_data[0], image_size, m_header.m_glTypeSize); uint num_cube_pad_bytes = disable_mip_and_cubemap_padding ? 0 : (3 - ((image_size + 3) % 4)); if (serializer.read(pad_bytes, 1, num_cube_pad_bytes) != num_cube_pad_bytes) return false; total_mip_size += image_size + num_cube_pad_bytes; } } else { // 1D, 2D, 3D (normal or array texture), or array cubemap uint num_image_bytes_remaining = image_size; for (uint array_element = 0; array_element < get_array_size(); array_element++) { for (uint face = 0; face < get_num_faces(); face++) { for (uint zslice = 0; zslice < mip_depth; zslice++) { CRNLIB_ASSERT(m_image_data.size() == get_image_index(mip_level, array_element, face, zslice)); uint slice_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block; if ((!slice_size) || (slice_size > num_image_bytes_remaining)) return false; m_image_data.push_back(uint8_vec()); uint8_vec& image_data = m_image_data.back(); image_data.resize(slice_size); if (serializer.read(&image_data[0], 1, slice_size) != slice_size) return false; if (m_opposite_endianness) utils::endian_swap_mem(&image_data[0], slice_size, m_header.m_glTypeSize); num_image_bytes_remaining -= slice_size; total_mip_size += slice_size; } } } if (num_image_bytes_remaining) return false; } uint num_mip_pad_bytes = disable_mip_and_cubemap_padding ? 0 : (3 - ((total_mip_size + 3) % 4)); if (serializer.read(pad_bytes, 1, num_mip_pad_bytes) != num_mip_pad_bytes) return false; } return true; } bool ktx_texture::write_to_stream(data_stream_serializer& serializer, bool no_keyvalue_data) { if (!consistency_check()) { CRNLIB_ASSERT(0); return false; } memcpy(m_header.m_identifier, s_ktx_file_id, sizeof(m_header.m_identifier)); m_header.m_endianness = m_opposite_endianness ? KTX_OPPOSITE_ENDIAN : KTX_ENDIAN; if (m_block_dim == 1) { m_header.m_glTypeSize = get_ogl_type_size(m_header.m_glType); m_header.m_glBaseInternalFormat = m_header.m_glFormat; } else { m_header.m_glBaseInternalFormat = get_ogl_base_internal_fmt(m_header.m_glInternalFormat); } m_header.m_bytesOfKeyValueData = 0; if (!no_keyvalue_data) { for (uint i = 0; i < m_key_values.size(); i++) m_header.m_bytesOfKeyValueData += sizeof(uint32) + ((m_key_values[i].size() + 3) & ~3); } if (m_opposite_endianness) m_header.endian_swap(); bool success = (serializer.write(&m_header, sizeof(m_header), 1) == 1); if (m_opposite_endianness) m_header.endian_swap(); if (!success) return success; uint total_key_value_bytes = 0; const uint8 padding[3] = {0, 0, 0}; if (!no_keyvalue_data) { for (uint i = 0; i < m_key_values.size(); i++) { uint32 key_value_size = m_key_values[i].size(); if (m_opposite_endianness) key_value_size = utils::swap32(key_value_size); success = (serializer.write(&key_value_size, sizeof(key_value_size), 1) == 1); total_key_value_bytes += sizeof(key_value_size); if (m_opposite_endianness) key_value_size = utils::swap32(key_value_size); if (!success) return false; if (key_value_size) { if (serializer.write(&m_key_values[i][0], key_value_size, 1) != 1) return false; total_key_value_bytes += key_value_size; uint num_padding = 3 - ((key_value_size + 3) % 4); if ((num_padding) && (serializer.write(padding, num_padding, 1) != 1)) return false; total_key_value_bytes += num_padding; } } (void)total_key_value_bytes; } CRNLIB_ASSERT(total_key_value_bytes == m_header.m_bytesOfKeyValueData); for (uint mip_level = 0; mip_level < get_num_mips(); mip_level++) { uint mip_width, mip_height, mip_depth; get_mip_dim(mip_level, mip_width, mip_height, mip_depth); const uint mip_row_blocks = (mip_width + m_block_dim - 1) / m_block_dim; const uint mip_col_blocks = (mip_height + m_block_dim - 1) / m_block_dim; if ((!mip_row_blocks) || (!mip_col_blocks)) return false; uint32 image_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block; if ((m_header.m_numberOfArrayElements) || (get_num_faces() == 1)) image_size *= (get_array_size() * get_num_faces() * get_depth()); if (!image_size) return false; if (m_opposite_endianness) image_size = utils::swap32(image_size); success = (serializer.write(&image_size, sizeof(image_size), 1) == 1); if (m_opposite_endianness) image_size = utils::swap32(image_size); if (!success) return false; uint total_mip_size = 0; if ((!m_header.m_numberOfArrayElements) && (get_num_faces() == 6)) { // plain non-array cubemap for (uint face = 0; face < get_num_faces(); face++) { const uint8_vec& image_data = get_image_data(get_image_index(mip_level, 0, face, 0)); if ((!image_data.size()) || (image_data.size() != image_size)) return false; if (m_opposite_endianness) { uint8_vec tmp_image_data(image_data); utils::endian_swap_mem(&tmp_image_data[0], tmp_image_data.size(), m_header.m_glTypeSize); if (serializer.write(&tmp_image_data[0], tmp_image_data.size(), 1) != 1) return false; } else if (serializer.write(&image_data[0], image_data.size(), 1) != 1) return false; uint num_cube_pad_bytes = 3 - ((image_data.size() + 3) % 4); if ((num_cube_pad_bytes) && (serializer.write(padding, num_cube_pad_bytes, 1) != 1)) return false; total_mip_size += image_size + num_cube_pad_bytes; } } else { // 1D, 2D, 3D (normal or array texture), or array cubemap for (uint array_element = 0; array_element < get_array_size(); array_element++) { for (uint face = 0; face < get_num_faces(); face++) { for (uint zslice = 0; zslice < mip_depth; zslice++) { const uint8_vec& image_data = get_image_data(get_image_index(mip_level, array_element, face, zslice)); if (!image_data.size()) return false; if (m_opposite_endianness) { uint8_vec tmp_image_data(image_data); utils::endian_swap_mem(&tmp_image_data[0], tmp_image_data.size(), m_header.m_glTypeSize); if (serializer.write(&tmp_image_data[0], tmp_image_data.size(), 1) != 1) return false; } else if (serializer.write(&image_data[0], image_data.size(), 1) != 1) return false; total_mip_size += image_data.size(); } } } uint num_mip_pad_bytes = 3 - ((total_mip_size + 3) % 4); if ((num_mip_pad_bytes) && (serializer.write(padding, num_mip_pad_bytes, 1) != 1)) return false; total_mip_size += num_mip_pad_bytes; } CRNLIB_ASSERT((total_mip_size & 3) == 0); } return true; } bool ktx_texture::init_2D(uint width, uint height, uint num_mips, uint32 ogl_internal_fmt, uint32 ogl_fmt, uint32 ogl_type) { clear(); m_header.m_pixelWidth = width; m_header.m_pixelHeight = height; m_header.m_numberOfMipmapLevels = num_mips; m_header.m_glInternalFormat = ogl_internal_fmt; m_header.m_glFormat = ogl_fmt; m_header.m_glType = ogl_type; m_header.m_numberOfFaces = 1; if (!compute_pixel_info()) return false; return true; } bool ktx_texture::init_2D_array(uint width, uint height, uint num_mips, uint array_size, uint32 ogl_internal_fmt, uint32 ogl_fmt, uint32 ogl_type) { clear(); m_header.m_pixelWidth = width; m_header.m_pixelHeight = height; m_header.m_numberOfMipmapLevels = num_mips; m_header.m_numberOfArrayElements = array_size; m_header.m_glInternalFormat = ogl_internal_fmt; m_header.m_glFormat = ogl_fmt; m_header.m_glType = ogl_type; m_header.m_numberOfFaces = 1; if (!compute_pixel_info()) return false; return true; } bool ktx_texture::init_3D(uint width, uint height, uint depth, uint num_mips, uint32 ogl_internal_fmt, uint32 ogl_fmt, uint32 ogl_type) { clear(); m_header.m_pixelWidth = width; m_header.m_pixelHeight = height; m_header.m_pixelDepth = depth; m_header.m_numberOfMipmapLevels = num_mips; m_header.m_glInternalFormat = ogl_internal_fmt; m_header.m_glFormat = ogl_fmt; m_header.m_glType = ogl_type; m_header.m_numberOfFaces = 1; if (!compute_pixel_info()) return false; return true; } bool ktx_texture::init_cubemap(uint dim, uint num_mips, uint32 ogl_internal_fmt, uint32 ogl_fmt, uint32 ogl_type) { clear(); m_header.m_pixelWidth = dim; m_header.m_pixelHeight = dim; m_header.m_numberOfMipmapLevels = num_mips; m_header.m_glInternalFormat = ogl_internal_fmt; m_header.m_glFormat = ogl_fmt; m_header.m_glType = ogl_type; m_header.m_numberOfFaces = 6; if (!compute_pixel_info()) return false; return true; } bool ktx_texture::check_header() const { if (((get_num_faces() != 1) && (get_num_faces() != 6)) || (!m_header.m_pixelWidth)) return false; if ((!m_header.m_pixelHeight) && (m_header.m_pixelDepth)) return false; if ((get_num_faces() == 6) && ((m_header.m_pixelDepth) || (!m_header.m_pixelHeight))) return false; if (m_header.m_numberOfMipmapLevels) { const uint max_mipmap_dimension = 1U << (m_header.m_numberOfMipmapLevels - 1U); if (max_mipmap_dimension > (CRNLIB_MAX(CRNLIB_MAX(m_header.m_pixelWidth, m_header.m_pixelHeight), m_header.m_pixelDepth))) return false; } return true; } bool ktx_texture::consistency_check() const { if (!check_header()) return false; uint block_dim = 0, bytes_per_block = 0; if ((!m_header.m_glType) || (!m_header.m_glFormat)) { if ((m_header.m_glType) || (m_header.m_glFormat)) return false; if (!get_ogl_fmt_desc(m_header.m_glInternalFormat, m_header.m_glType, block_dim, bytes_per_block)) return false; if (block_dim == 1) return false; //if ((get_width() % block_dim) || (get_height() % block_dim)) // return false; } else { if (!get_ogl_fmt_desc(m_header.m_glFormat, m_header.m_glType, block_dim, bytes_per_block)) return false; if (block_dim > 1) return false; } if ((m_block_dim != block_dim) || (m_bytes_per_block != bytes_per_block)) return false; if (m_image_data.size() != get_total_images()) return false; for (uint mip_level = 0; mip_level < get_num_mips(); mip_level++) { uint mip_width, mip_height, mip_depth; get_mip_dim(mip_level, mip_width, mip_height, mip_depth); const uint mip_row_blocks = (mip_width + m_block_dim - 1) / m_block_dim; const uint mip_col_blocks = (mip_height + m_block_dim - 1) / m_block_dim; if ((!mip_row_blocks) || (!mip_col_blocks)) return false; for (uint array_element = 0; array_element < get_array_size(); array_element++) { for (uint face = 0; face < get_num_faces(); face++) { for (uint zslice = 0; zslice < mip_depth; zslice++) { const uint8_vec& image_data = get_image_data(get_image_index(mip_level, array_element, face, zslice)); uint expected_image_size = mip_row_blocks * mip_col_blocks * m_bytes_per_block; if (image_data.size() != expected_image_size) return false; } } } } return true; } const uint8_vec* ktx_texture::find_key(const char* pKey) const { const size_t n = strlen(pKey) + 1; for (uint i = 0; i < m_key_values.size(); i++) { const uint8_vec& v = m_key_values[i]; if ((v.size() >= n) && (!memcmp(&v[0], pKey, n))) return &v; } return nullptr; } bool ktx_texture::get_key_value_as_string(const char* pKey, dynamic_string& str) const { const uint8_vec* p = find_key(pKey); if (!p) { str.clear(); return false; } const uint ofs = (static_cast<uint>(strlen(pKey)) + 1); const uint8* pValue = p->get_ptr() + ofs; const uint n = p->size() - ofs; uint i; for (i = 0; i < n; i++) if (!pValue[i]) break; str.set_from_buf(pValue, i); return true; } uint ktx_texture::add_key_value(const char* pKey, const void* pVal, uint val_size) { const uint idx = m_key_values.size(); m_key_values.resize(idx + 1); uint8_vec& v = m_key_values.back(); v.append(reinterpret_cast<const uint8*>(pKey), static_cast<uint>(strlen(pKey)) + 1); v.append(static_cast<const uint8*>(pVal), val_size); return idx; } } // namespace crnlib
33.261078
149
0.666259
bmorel
a64e43083ff408bf380c68a25f3c9c8ab5a75320
1,193
hh
C++
Exos/Serie04/poisson/simulation.hh
vkeller/math-454
0bf3a81214f094dbddec868d3d133986b31f4b01
[ "BSD-2-Clause" ]
1
2021-05-19T13:31:49.000Z
2021-05-19T13:31:49.000Z
Exos/Serie05/poisson/simulation.hh
vkeller/math-454
0bf3a81214f094dbddec868d3d133986b31f4b01
[ "BSD-2-Clause" ]
null
null
null
Exos/Serie05/poisson/simulation.hh
vkeller/math-454
0bf3a81214f094dbddec868d3d133986b31f4b01
[ "BSD-2-Clause" ]
null
null
null
#ifndef SIMULATION_HH #define SIMULATION_HH /* -------------------------------------------------------------------------- */ #include "double_buffer.hh" #include "dumpers.hh" #include "grid.hh" /* -------------------------------------------------------------------------- */ #include <tuple> /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ class Simulation { public: Simulation(int m, int n); /// set the initial conditions, Dirichlet and source term virtual void set_initial_conditions(); /// perform the simulation std::tuple<float, int> compute(); /// access the precision void set_epsilon(float epsilon); float epsilon() const; protected: /// compute one step and return an error virtual float compute_step(); private: /// Global problem size int m_global_m, m_global_n; /// Precision to achieve float m_epsilon; /// grid spacing float m_h_m; float m_h_n; /// Grids storage DoubleBuffer m_grids; /// source term Grid m_f; /// Dumper to use for outputs std::unique_ptr<Dumper> m_dumper; }; #endif /* SIMULATION_HH */
22.509434
80
0.511316
vkeller
a64e65567c46b7fb53a5795b932de4def851d6a5
3,909
hpp
C++
C64/src/Emulator/UnitTest/TestEmulator.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
1
2015-03-26T02:35:13.000Z
2015-03-26T02:35:13.000Z
C64/src/Emulator/UnitTest/TestEmulator.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
null
null
null
C64/src/Emulator/UnitTest/TestEmulator.hpp
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
null
null
null
// // Emulator - Simple C64 emulator // Copyright (C) 2003-2016 Michael Fink // /// \file TestEmulator.hpp Emulator implementation for unit tests // #pragma once // includes #include "Machine.hpp" #include "PC64File.hpp" #include "PETASCIIString.hpp" /// Emulator for unit tests class TestEmulator : public C64::Machine, public C64::IProcessorCallback { public: /// ctor TestEmulator() :m_bExit(false), m_bTestResult(false) { GetProcessor().AddProcessorCallback(this); } /// dtor ~TestEmulator() { GetProcessor().RemoveProcessorCallback(this); } /// Loads test from path, with filename bool LoadTest(LPCTSTR pszTestPath, LPCTSTR pszTestName) { CString cszFilename; cszFilename.Format(_T("%s\\%s.p00"), pszTestPath, pszTestName); C64::PC64File file(cszFilename); if (!file.IsValid()) return false; return file.Load(GetMemoryManager().GetRAM()); } /// Runs test and checks if test executes OK bool Run() { C64::Processor6510& proc = GetProcessor(); proc.SetDebugOutput(true); // set IRQ handler GetMemoryManager().Poke(0xfffe, 0x48); GetMemoryManager().Poke(0xffff, 0xff); // set stack pointer to a reasonable value proc.SetRegister(C64::regSP, 0xff); m_bExit = m_bTestResult = false; for (; !m_bExit;) { // check if program wants to exit per RTS /* if (proc.GetRegister(C64::regSP) == 0xff && GetMemoryManager().Peek(proc.GetProgramCounter()) == C64::opRTS) { m_bExit = true; break; } */ proc.Step(); } // create output string std::string output = m_strOutput.ToString(); ATLTRACE(_T("%hs\n"), output.c_str()); // search output for string " - OK" m_bTestResult = std::string::npos != output.find("- OK"); return m_bTestResult; } private: /// called when program counter has changed virtual void OnProgramCounterChange() { C64::Processor6510& proc = GetProcessor(); C64::MemoryManager& mem = GetMemoryManager(); WORD wPC = proc.GetProgramCounter(); switch (wPC) { case 0x0000: // indirect jump to $0000 case 0xe16f: // LOAD command m_bExit = true; break; case 0xff48: { ATLTRACE(_T("KERNAL: IRQ Handler\n")); proc.Push(proc.GetRegister(C64::regA)); // save A proc.SetRegister(C64::regA, proc.GetRegister(C64::regX)); // save X proc.Push(proc.GetRegister(C64::regA)); proc.SetRegister(C64::regA, proc.GetRegister(C64::regY)); // save Y proc.Push(proc.GetRegister(C64::regA)); proc.SetRegister(C64::regX, proc.GetRegister(C64::regSP)); // get stack pointer // load status register from stack BYTE bSR = mem.Peek(0x0100 + ((proc.GetRegister(C64::regX) + 4) & 0xff)); // decide which type of interrupt WORD wAddr = (bSR & 0x10) == 0 ? 0x0314 : 0x0316; proc.SetProgramCounter(mem.Peek16(wAddr)); } break; case 0xffd2: // BSOUT { BYTE bRegA = proc.GetRegister(C64::regA); if (bRegA != 0) m_strOutput += bRegA; proc.Return(); //ATLTRACE(_T("KERNAL: BSOUT: %c #$%02x\n"), bRegA < 0x20 ? _T('?') : bRegA, bRegA); } break; case 0xffe4: // GETIN ATLTRACE(_T("KERNAL: GETIN\n")); proc.SetRegister(C64::regA, 0x3); // simulate keypress with code 3 proc.Return(); break; default: //ATLTRACE("test emulator changed PC to $%04x\n", wPC); break; } } private: /// set to true when test can exit bool m_bExit; /// test result bool m_bTestResult; /// output as PETASCII string C64::PETASCIIString m_strOutput; };
25.383117
93
0.585828
vividos
a65080732f7156bd13a0c3cf3b38673cade613ce
50,152
cpp
C++
tests/auto/datasync/TestAppServer/tst_appserver.cpp
wangyangyangisme/QtDataSync
0cc47ca4e8aeee2683aae52662c40f1a7c7b1d93
[ "BSD-3-Clause" ]
1
2022-02-22T07:18:33.000Z
2022-02-22T07:18:33.000Z
tests/auto/datasync/TestAppServer/tst_appserver.cpp
wyyrepo/QtDataSync
0cc47ca4e8aeee2683aae52662c40f1a7c7b1d93
[ "BSD-3-Clause" ]
null
null
null
tests/auto/datasync/TestAppServer/tst_appserver.cpp
wyyrepo/QtDataSync
0cc47ca4e8aeee2683aae52662c40f1a7c7b1d93
[ "BSD-3-Clause" ]
1
2018-12-20T04:31:16.000Z
2018-12-20T04:31:16.000Z
#include <QString> #include <QtTest> #include <QCoreApplication> #include <QProcess> #include <testlib.h> #include <mockclient.h> #ifdef Q_OS_UNIX #include <sys/types.h> #include <signal.h> #elif Q_OS_WIN #include <qt_windows.h> #endif #include <QtDataSync/private/identifymessage_p.h> #include <QtDataSync/private/registermessage_p.h> #include <QtDataSync/private/accountmessage_p.h> #include <QtDataSync/private/loginmessage_p.h> #include <QtDataSync/private/welcomemessage_p.h> #include <QtDataSync/private/accessmessage_p.h> #include <QtDataSync/private/proofmessage_p.h> #include <QtDataSync/private/grantmessage_p.h> #include <QtDataSync/private/macupdatemessage_p.h> #include <QtDataSync/private/changemessage_p.h> #include <QtDataSync/private/changedmessage_p.h> #include <QtDataSync/private/syncmessage_p.h> #include <QtDataSync/private/devicechangemessage_p.h> #include <QtDataSync/private/keychangemessage_p.h> #include <QtDataSync/private/devicekeysmessage_p.h> #include <QtDataSync/private/newkeymessage_p.h> #include <QtDataSync/private/devicesmessage_p.h> #include <QtDataSync/private/removemessage_p.h> using namespace QtDataSync; Q_DECLARE_METATYPE(QSharedPointer<Message>) class TestAppServer : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void testStart(); void testInvalidVersion(); void testInvalidRegisterNonce(); void testInvalidRegisterSignature(); void testRegister(); void testInvalidLoginNonce(); void testInvalidLoginSignature(); void testInvalidLoginDevId(); void testLogin(); void testAddDevice(); void testInvalidAccessNonce(); void testInvalidAccessSignature(); void testDenyAddDevice(); void testOfflineAddDevice(); void testInvalidAcceptSignature(); void testAddDeviceInvalidKeyIndex(); void testSendDoubleAccept(); void testChangeUpload(); void testChangeDownloadOnLogin(); void testLiveChanges(); void testSyncCommand(); void testDeviceUploading(); void testChangeKey(); void testChangeKeyInvalidIndex(); void testChangeKeyDuplicate(); void testChangeKeyPendingChanges(); void testAddNewKeyInvalidIndex(); void testAddNewKeyInvalidSignature(); void testAddNewKeyPendingChanges(); void testKeyChangeNoAck(); void testListAndRemoveDevices(); void testUnexpectedMessage_data(); void testUnexpectedMessage(); void testUnknownMessage(); void testBrokenMessage(); #ifdef TEST_PING_MSG void testPingMessages(); #endif void testRemoveSelf(); void testStop(); private: QProcess *server; MockClient *client; QString devName; QUuid devId; ClientCrypto *crypto; MockClient *partner; QString partnerName; QUuid partnerDevId; ClientCrypto *partnerCrypto; void testAddDevice(MockClient *&partner, QUuid &partnerDevId, bool keepPartner = false); void clean(bool disconnect = true); void clean(MockClient *&client, bool disconnect = true); template <typename TMessage, typename... Args> inline QSharedPointer<Message> create(Args... args); template <typename TMessage, typename... Args> inline QSharedPointer<Message> createNonced(Args... args); }; void TestAppServer::initTestCase() { #ifdef Q_OS_LINUX if(!qgetenv("LD_PRELOAD").contains("Qt5DataSync")) qWarning() << "No LD_PRELOAD set - this may fail on systems with multiple version of the modules"; #endif QByteArray confPath { SETUP_FILE }; QVERIFY(QFile::exists(QString::fromUtf8(confPath))); qputenv("QDSAPP_CONFIG_FILE", confPath); #ifdef Q_OS_UNIX QString binPath { QStringLiteral(BUILD_BIN_DIR "qdsappd") }; #elif Q_OS_WIN QString binPath { QStringLiteral(BUILD_BIN_DIR "qdsappsvc") }; #else QString binPath { QStringLiteral(BUILD_BIN_DIR "qdsapp") }; #endif QVERIFY(QFile::exists(binPath)); server = new QProcess(this); server->setProgram(binPath); server->setProcessChannelMode(QProcess::ForwardedErrorChannel); try { client = nullptr; devName = QStringLiteral("client"); crypto = new ClientCrypto(this); crypto->generate(Setup::RSA_PSS_SHA3_512, 2048, Setup::RSA_OAEP_SHA3_512, 2048); partner = nullptr; partnerName = QStringLiteral("partner"); partnerCrypto = new ClientCrypto(this); partnerCrypto->generate(Setup::RSA_PSS_SHA3_512, 2048, Setup::RSA_OAEP_SHA3_512, 2048); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::cleanupTestCase() { clean(); clean(partner); if(server->isOpen()) { server->kill(); QVERIFY(server->waitForFinished(5000)); } server->deleteLater(); } void TestAppServer::testStart() { server->start(); QVERIFY(server->waitForStarted(5000)); QVERIFY(!server->waitForFinished(5000)); } void TestAppServer::testInvalidVersion() { try { //establish connection client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a register message with invalid version RegisterMessage reply { devName, mNonce, crypto->signKey(), crypto->cryptKey(), crypto, "cmac" }; reply.protocolVersion = QVersionNumber(0,5); client->send(reply); //wait for the error QVERIFY(client->waitForError(ErrorMessage::IncompatibleVersionError)); clean(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testInvalidRegisterNonce() { try { //establish connection client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); ok = true; })); //send back a register message with invalid nonce client->send(RegisterMessage { devName, "not the original nonce, but still long enough to be considered one", crypto->signKey(), crypto->cryptKey(), crypto, "cmac" }); //wait for the error QVERIFY(client->waitForError(ErrorMessage::ClientError)); clean(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testInvalidRegisterSignature() { try { //establish connection client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a register message with invalid signature QByteArray sData = RegisterMessage { devName, mNonce, crypto->signKey(), crypto->cryptKey(), crypto, "cmac" }.serializeSigned(crypto->privateSignKey(), crypto->rng(), crypto); sData[sData.size() - 1] = sData[sData.size() - 1] + 'x'; client->sendBytes(sData); //message + fake signature //wait for the error QVERIFY(client->waitForError(ErrorMessage::AuthenticationError)); clean(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testRegister() { try { //establish connection client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid register message client->sendSigned(RegisterMessage { devName, mNonce, crypto->signKey(), crypto->cryptKey(), crypto, devId.toByteArray() //dummy cmac }, crypto); //wait for the account message QVERIFY(client->waitForReply<AccountMessage>([&](AccountMessage message, bool &ok) { devId = message.deviceId; ok = true; })); clean(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testInvalidLoginNonce() { try { //establish connection client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); ok = true; })); //send back a valid login message client->sendSigned(LoginMessage { devId, devName, "not the original nonce, but still long enough to be considered one", }, crypto); //wait for the error QVERIFY(client->waitForError(ErrorMessage::ClientError)); clean(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testInvalidLoginSignature() { try { //establish connection client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message QByteArray sData = LoginMessage { devId, devName, mNonce }.serializeSigned(crypto->privateSignKey(), crypto->rng(), crypto); sData[sData.size() - 1] = sData[sData.size() - 1] + 'x'; client->sendBytes(sData); //message + fake signature //wait for the error QVERIFY(client->waitForError(ErrorMessage::AuthenticationError)); clean(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testInvalidLoginDevId() { try { //establish connection client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message client->sendSigned(LoginMessage { QUuid::createUuid(), //wrong devId devName, mNonce }, crypto); //wait for the error QVERIFY(client->waitForError(ErrorMessage::AuthenticationError)); clean(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testLogin() { try { //establish connection client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message client->sendSigned(LoginMessage { devId, devName, mNonce }, crypto); //wait for the account message QVERIFY(client->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) { QVERIFY(!message.hasChanges); QCOMPARE(message.keyIndex, 0u); QVERIFY(message.scheme.isNull()); QVERIFY(message.key.isNull()); QVERIFY(message.cmac.isNull()); ok = true; })); //keep session active } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testAddDevice() { testAddDevice(partner, partnerDevId); } void TestAppServer::testAddDevice(MockClient *&partner, QUuid &partnerDevId, bool keepPartner) //not executed as test { QByteArray pNonce = "partner_nonce"; QByteArray macscheme = "macscheme"; QByteArray cmac = "cmac"; QByteArray trustmac = "trustmac"; quint32 keyIndex = 0; QByteArray keyScheme = "keyScheme"; QByteArray keySecret = "keySecret"; try { QVERIFY(client); //establish connection partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //Send access message partner->sendSigned(AccessMessage { partnerName, mNonce, partnerCrypto->signKey(), partnerCrypto->cryptKey(), partnerCrypto, pNonce, devId, macscheme, cmac, trustmac }, partnerCrypto); //wait for proof message on client QVERIFY(client->waitForReply<ProofMessage>([&](ProofMessage message, bool &ok) { QCOMPARE(message.pNonce, pNonce); QVERIFY(!message.deviceId.isNull()); partnerDevId = message.deviceId; QCOMPARE(message.deviceName, partnerName); QCOMPARE(message.macscheme, macscheme); QCOMPARE(message.cmac, cmac); QCOMPARE(message.trustmac, trustmac); AsymmetricCryptoInfo cInfo {crypto->rng(), message.signAlgorithm, message.signKey, message.cryptAlgorithm, message.cryptKey }; QCOMPARE(cInfo.ownFingerprint(), partnerCrypto->ownFingerprint()); ok = true; })); //accept the proof AcceptMessage accMsg { partnerDevId }; accMsg.index = keyIndex; accMsg.scheme = keyScheme; accMsg.secret = keySecret; client->sendSigned(accMsg, crypto); QVERIFY(client->waitForReply<AcceptAckMessage>([&](AcceptAckMessage message, bool &ok) { QCOMPARE(message.deviceId, partnerDevId); ok = true; })); //wait for granted QVERIFY(partner->waitForReply<GrantMessage>([&](GrantMessage message, bool &ok) { QCOMPARE(message.deviceId, partnerDevId); QCOMPARE(message.index, keyIndex); QCOMPARE(message.scheme, keyScheme); QCOMPARE(message.secret, keySecret); ok = true; })); //send mac update partner->send(MacUpdateMessage { keyIndex, partnerDevId.toByteArray() //dummy cmac }); //wait for mac ack QVERIFY(partner->waitForReply<MacUpdateAckMessage>([&](MacUpdateAckMessage message, bool &ok) { Q_UNUSED(message); ok = true; })); if(!keepPartner) clean(partner); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testInvalidAccessNonce() { try { QVERIFY(client); MockClient *partner = nullptr; //use crypto and name from real partner //establish connection partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); ok = true; })); //Send access message partner->sendSigned(AccessMessage { partnerName, "not the original nonce, but still long enough to be considered one", partnerCrypto->signKey(), partnerCrypto->cryptKey(), partnerCrypto, "pNonce", devId, "macscheme", "cmac", "trustmac" }, partnerCrypto); QVERIFY(partner->waitForError(ErrorMessage::ClientError)); clean(partner); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testInvalidAccessSignature() { try { QVERIFY(client); MockClient *partner = nullptr; //use crypto and name from real partner //establish connection partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //Send access message QByteArray sData = AccessMessage { partnerName, mNonce, partnerCrypto->signKey(), partnerCrypto->cryptKey(), partnerCrypto, "pNonce", devId, "macscheme", "cmac", "trustmac" }.serializeSigned(partnerCrypto->privateSignKey(), partnerCrypto->rng(), partnerCrypto); sData[sData.size() - 1] = sData[sData.size() - 1] + 'x'; partner->sendBytes(sData); //message + fake signature QVERIFY(partner->waitForError(ErrorMessage::AuthenticationError)); clean(partner); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testDenyAddDevice() { QByteArray pNonce = "partner_nonce"; QByteArray macscheme = "macscheme"; QByteArray cmac = "cmac"; QByteArray trustmac = "trustmac"; try { QVERIFY(client); MockClient *partner = nullptr; QUuid partnerDevId; //use crypto and name from real partner //establish connection partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //Send access message partner->sendSigned(AccessMessage { partnerName, mNonce, partnerCrypto->signKey(), partnerCrypto->cryptKey(), partnerCrypto, pNonce, devId, macscheme, cmac, trustmac }, partnerCrypto); //wait for proof message on client QVERIFY(client->waitForReply<ProofMessage>([&](ProofMessage message, bool &ok) { QCOMPARE(message.pNonce, pNonce); QVERIFY(!message.deviceId.isNull()); partnerDevId = message.deviceId; QCOMPARE(message.deviceName, partnerName); QCOMPARE(message.macscheme, macscheme); QCOMPARE(message.cmac, cmac); QCOMPARE(message.trustmac, trustmac); AsymmetricCryptoInfo cInfo {crypto->rng(), message.signAlgorithm, message.signKey, message.cryptAlgorithm, message.cryptKey }; QCOMPARE(cInfo.ownFingerprint(), partnerCrypto->ownFingerprint()); ok = true; })); //accept the proof client->send(DenyMessage { partnerDevId }); QVERIFY(partner->waitForError(ErrorMessage::AccessError)); clean(partner); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testOfflineAddDevice() { try { QVERIFY(client); clean(client); MockClient *partner = nullptr; //use crypto and name from real partner //establish connection partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //Send access message for offline device partner->sendSigned(AccessMessage { partnerName, mNonce, partnerCrypto->signKey(), partnerCrypto->cryptKey(), partnerCrypto, "pNonce", devId, "macscheme", "cmac", "trustmac" }, partnerCrypto); QVERIFY(partner->waitForError(ErrorMessage::AccessError)); clean(partner); //reconnect main device testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testInvalidAcceptSignature() { try { QVERIFY(client); //invalid accept AcceptMessage accMsg { QUuid::createUuid() }; accMsg.index = 42; accMsg.scheme = "keyScheme"; accMsg.secret = "keySecret"; auto sData = accMsg.serializeSigned(crypto->privateSignKey(), crypto->rng(), crypto); sData[sData.size() - 1] = sData[sData.size() - 1] + 'x'; client->sendBytes(sData); //message + fake signature QVERIFY(client->waitForError(ErrorMessage::AuthenticationError)); clean(client); testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testAddDeviceInvalidKeyIndex() { QByteArray pNonce = "partner_nonce"; QByteArray macscheme = "macscheme"; QByteArray cmac = "cmac"; QByteArray trustmac = "trustmac"; quint32 keyIndex = 5; //fake key index QByteArray keyScheme = "keyScheme"; QByteArray keySecret = "keySecret"; try { QVERIFY(client); MockClient *partner = nullptr; QUuid partnerDevId; //establish connection partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //Send access message partner->sendSigned(AccessMessage { partnerName, mNonce, partnerCrypto->signKey(), partnerCrypto->cryptKey(), partnerCrypto, pNonce, devId, macscheme, cmac, trustmac }, partnerCrypto); //wait for proof message on client QVERIFY(client->waitForReply<ProofMessage>([&](ProofMessage message, bool &ok) { QCOMPARE(message.pNonce, pNonce); QVERIFY(!message.deviceId.isNull()); partnerDevId = message.deviceId; QCOMPARE(message.deviceName, partnerName); QCOMPARE(message.macscheme, macscheme); QCOMPARE(message.cmac, cmac); QCOMPARE(message.trustmac, trustmac); AsymmetricCryptoInfo cInfo {crypto->rng(), message.signAlgorithm, message.signKey, message.cryptAlgorithm, message.cryptKey }; QCOMPARE(cInfo.ownFingerprint(), partnerCrypto->ownFingerprint()); ok = true; })); //accept the proof AcceptMessage accMsg { partnerDevId }; accMsg.index = keyIndex; accMsg.scheme = keyScheme; accMsg.secret = keySecret; client->sendSigned(accMsg, crypto); QVERIFY(client->waitForReply<AcceptAckMessage>([&](AcceptAckMessage message, bool &ok) { QCOMPARE(message.deviceId, partnerDevId); ok = true; })); //wait for granted QVERIFY(partner->waitForReply<GrantMessage>([&](GrantMessage message, bool &ok) { QCOMPARE(message.deviceId, partnerDevId); QCOMPARE(message.index, keyIndex); QCOMPARE(message.scheme, keyScheme); QCOMPARE(message.secret, keySecret); ok = true; })); //send mac update partner->send(MacUpdateMessage { keyIndex, partnerDevId.toByteArray() //dummy cmac }); QVERIFY(partner->waitForError(ErrorMessage::KeyIndexError)); clean(partner); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testSendDoubleAccept() { QByteArray pNonce = "partner_nonce"; QByteArray macscheme = "macscheme"; QByteArray cmac = "cmac"; QByteArray trustmac = "trustmac"; quint32 keyIndex = 0; QByteArray keyScheme = "keyScheme"; QByteArray keySecret = "keySecret"; try { QVERIFY(client); MockClient *partner = nullptr; QUuid partnerDevId; //establish connection partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //Send access message partner->sendSigned(AccessMessage { partnerName, mNonce, partnerCrypto->signKey(), partnerCrypto->cryptKey(), partnerCrypto, pNonce, devId, macscheme, cmac, trustmac }, partnerCrypto); //wait for proof message on client QVERIFY(client->waitForReply<ProofMessage>([&](ProofMessage message, bool &ok) { QCOMPARE(message.pNonce, pNonce); QVERIFY(!message.deviceId.isNull()); partnerDevId = message.deviceId; QCOMPARE(message.deviceName, partnerName); QCOMPARE(message.macscheme, macscheme); QCOMPARE(message.cmac, cmac); QCOMPARE(message.trustmac, trustmac); AsymmetricCryptoInfo cInfo {crypto->rng(), message.signAlgorithm, message.signKey, message.cryptAlgorithm, message.cryptKey }; QCOMPARE(cInfo.ownFingerprint(), partnerCrypto->ownFingerprint()); ok = true; })); //accept the proof AcceptMessage accMsg { partnerDevId }; accMsg.index = keyIndex; accMsg.scheme = keyScheme; accMsg.secret = keySecret; client->sendSigned(accMsg, crypto); QVERIFY(client->waitForReply<AcceptAckMessage>([&](AcceptAckMessage message, bool &ok) { QCOMPARE(message.deviceId, partnerDevId); ok = true; })); //wait for granted QVERIFY(partner->waitForReply<GrantMessage>([&](GrantMessage message, bool &ok) { QCOMPARE(message.deviceId, partnerDevId); QCOMPARE(message.index, keyIndex); QCOMPARE(message.scheme, keyScheme); QCOMPARE(message.secret, keySecret); ok = true; })); //send mac update partner->send(MacUpdateMessage { keyIndex, partnerDevId.toByteArray() //dummy cmac }); //wait for mac ack QVERIFY(partner->waitForReply<MacUpdateAckMessage>([&](MacUpdateAckMessage message, bool &ok) { Q_UNUSED(message); ok = true; })); //send another proof accept client->sendSigned(accMsg, crypto); QVERIFY(client->waitForNothing()); //no accept ack QVERIFY(partner->waitForNothing()); //no grant //clean partner clean(partner); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testChangeUpload() { QByteArray dataId1 = "dataId1"; QByteArray dataId2 = "dataId2"; quint32 keyIndex = 0; QByteArray salt = "salt"; QByteArray data = "data"; try { QVERIFY(client); QVERIFY(!partner); //send an upload 1 and 2 ChangeMessage changeMsg { dataId1 }; changeMsg.keyIndex = keyIndex; changeMsg.salt = salt; changeMsg.data = data; client->send(changeMsg); changeMsg.dataId = dataId2; client->send(changeMsg); //wait for ack QVERIFY(client->waitForReply<ChangeAckMessage>([&](ChangeAckMessage message, bool &ok) { QCOMPARE(message.dataId, dataId1); ok = true; })); QVERIFY(client->waitForReply<ChangeAckMessage>([&](ChangeAckMessage message, bool &ok) { QCOMPARE(message.dataId, dataId2); ok = true; })); //send 1 again changeMsg.dataId = dataId1; client->send(changeMsg); //wait for ack QVERIFY(client->waitForReply<ChangeAckMessage>([&](ChangeAckMessage message, bool &ok) { QCOMPARE(message.dataId, dataId1); ok = true; })); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testChangeDownloadOnLogin() { quint32 keyIndex = 0; QByteArray salt = "salt"; QByteArray data = "data"; try { QVERIFY(client); QVERIFY(!partner); //establish connection partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message partner->sendSigned(LoginMessage { partnerDevId, partnerName, mNonce }, partnerCrypto); //wait for the account message QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) { QVERIFY(message.hasChanges);//Must have changes now QCOMPARE(message.keyIndex, 0u); QVERIFY(message.scheme.isNull()); QVERIFY(message.key.isNull()); QVERIFY(message.cmac.isNull()); ok = true; })); //wait for change info message quint64 dataId1 = 0; QVERIFY(partner->waitForReply<ChangedInfoMessage>([&](ChangedInfoMessage message, bool &ok) { QCOMPARE(message.changeEstimate, 2u); QCOMPARE(message.keyIndex, keyIndex); QCOMPARE(message.salt, salt); QCOMPARE(message.data, data); dataId1 = message.dataIndex; ok = true; })); //wait for the second message quint64 dataId2 = 0; QVERIFY(partner->waitForReply<ChangedMessage>([&](ChangedMessage message, bool &ok) { QCOMPARE(message.keyIndex, keyIndex); QCOMPARE(message.salt, salt); QCOMPARE(message.data, data); dataId2 = message.dataIndex; ok = true; })); //send the first ack partner->send(ChangedAckMessage { dataId1 }); QVERIFY(partner->waitForNothing()); //send second ack partner->send(ChangedAckMessage { dataId2 }); QVERIFY(partner->waitForReply<LastChangedMessage>([&](LastChangedMessage message, bool &ok) { Q_UNUSED(message) ok = true; })); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testLiveChanges() { QByteArray dataId1 = "dataId3"; quint32 keyIndex = 0; QByteArray salt = "salt"; QByteArray data = "data"; try { QVERIFY(client); QVERIFY(partner); //send an upload ChangeMessage changeMsg { dataId1 }; changeMsg.keyIndex = keyIndex; changeMsg.salt = salt; changeMsg.data = data; client->send(changeMsg); //wait for ack QVERIFY(client->waitForReply<ChangeAckMessage>([&](ChangeAckMessage message, bool &ok) { QCOMPARE(message.dataId, dataId1); ok = true; })); //wait for change info message quint64 dataId2 = 0; QVERIFY(partner->waitForReply<ChangedInfoMessage>([&](ChangedInfoMessage message, bool &ok) { QCOMPARE(message.changeEstimate, 1u); QCOMPARE(message.keyIndex, keyIndex); QCOMPARE(message.salt, salt); QCOMPARE(message.data, data); dataId2 = message.dataIndex; ok = true; })); //send the ack partner->send(ChangedAckMessage { dataId2 }); QVERIFY(partner->waitForReply<LastChangedMessage>([&](LastChangedMessage message, bool &ok) { Q_UNUSED(message) ok = true; })); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testSyncCommand() { try { QVERIFY(client); //send sync client->send(SyncMessage{}); //wait for last changed (as no changes are present) QVERIFY(client->waitForReply<LastChangedMessage>([&](LastChangedMessage message, bool &ok) { Q_UNUSED(message) ok = true; })); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testDeviceUploading() { QByteArray dataId1 = "dataId4"; quint32 keyIndex = 0; QByteArray salt = "salt"; QByteArray data = "data"; try { QVERIFY(client); QVERIFY(partner); MockClient *partner3 = nullptr; QUuid partner3DevId; testAddDevice(partner3, partner3DevId, true); QVERIFY(partner3); //send an upload for partner only DeviceChangeMessage changeMsg { dataId1, partnerDevId }; changeMsg.keyIndex = keyIndex; changeMsg.salt = salt; changeMsg.data = data; client->send(changeMsg); //wait for ack QVERIFY(client->waitForReply<DeviceChangeAckMessage>([&](DeviceChangeAckMessage message, bool &ok) { QCOMPARE(message.deviceId, partnerDevId); QCOMPARE(message.dataId, dataId1); ok = true; })); //wait for change info message quint64 dataId2 = 0; QVERIFY(partner->waitForReply<ChangedInfoMessage>([&](ChangedInfoMessage message, bool &ok) { QCOMPARE(message.changeEstimate, 1u); QCOMPARE(message.keyIndex, keyIndex); QCOMPARE(message.salt, salt); QCOMPARE(message.data, data); dataId2 = message.dataIndex; ok = true; })); //send the ack partner->send(ChangedAckMessage { dataId2 }); QVERIFY(partner->waitForReply<LastChangedMessage>([&](LastChangedMessage message, bool &ok) { Q_UNUSED(message) ok = true; })); //patner3: nothing QVERIFY(partner3->waitForNothing()); clean(partner3); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testChangeKey() { quint32 nextIndex = 1; QByteArray scheme = "scheme"; QByteArray key = "key"; QByteArray cmac = "cmac"; try { QVERIFY(client); QVERIFY(partner); //Send the key change proposal client->send(KeyChangeMessage { nextIndex }); QList<DeviceKeysMessage::DeviceKey> keys; QVERIFY(client->waitForReply<DeviceKeysMessage>([&](DeviceKeysMessage message, bool &ok) { QCOMPARE(message.keyIndex, nextIndex); QVERIFY(!message.duplicated); QCOMPARE(message.devices.size(), 4); //testAddDevice, testAddDeviceInvalidKeyIndex, testSendDoubleAccept, testDeviceUploading keys = message.devices; ok = true; })); //verify the keys, extract partner 1 key DeviceKeysMessage::DeviceKey mKey; do { mKey = keys.takeFirst(); if(partnerDevId == std::get<0>(mKey)) break; } while(!keys.isEmpty()); QCOMPARE(std::get<0>(mKey), partnerDevId); QCOMPARE(std::get<3>(mKey), partnerDevId.toByteArray()); //dummy cmac //send the actual key update message (ignoring the other 3) NewKeyMessage keyMsg; keyMsg.keyIndex = nextIndex; keyMsg.cmac = devName.toUtf8(); keyMsg.scheme = scheme; keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, key, cmac)); client->sendSigned(keyMsg, crypto); //wait for ack QVERIFY(client->waitForReply<NewKeyAckMessage>([&](NewKeyAckMessage message, bool &ok) { QCOMPARE(message.keyIndex, nextIndex); ok = true; })); //wait for partner to be disconnected QVERIFY(partner->waitForDisconnect()); partner->deleteLater(); partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message partner->sendSigned(LoginMessage { partnerDevId, partnerName, mNonce }, partnerCrypto); //wait for the account message QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) { QVERIFY(!message.hasChanges);//Must have changes now QCOMPARE(message.keyIndex, nextIndex); QCOMPARE(message.scheme, scheme); QCOMPARE(message.key, key); QCOMPARE(message.cmac, cmac); ok = true; })); //update the mac accordingly partner->send(MacUpdateMessage { nextIndex, partnerName.toUtf8() }); QVERIFY(partner->waitForReply<MacUpdateAckMessage>([&](MacUpdateAckMessage message, bool &ok) { Q_UNUSED(message) ok = true; })); //connect again, to make shure the ack was stored clean(partner); partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message partner->sendSigned(LoginMessage { partnerDevId, partnerName, mNonce }, partnerCrypto); //wait for the account message QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) { QVERIFY(!message.hasChanges);//Must have changes now QCOMPARE(message.keyIndex, 0u); QVERIFY(message.scheme.isNull()); QVERIFY(message.key.isNull()); QVERIFY(message.cmac.isNull()); ok = true; })); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testChangeKeyInvalidIndex() { try { QVERIFY(partner); //Send the key change proposal partner->send(KeyChangeMessage { 42 }); QVERIFY(partner->waitForError(ErrorMessage::KeyIndexError)); clean(partner); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testChangeKeyDuplicate() { quint32 nextIndex = 1;//duplicate to current try { QVERIFY(client); //Send the key change proposal client->send(KeyChangeMessage { nextIndex }); QVERIFY(client->waitForReply<DeviceKeysMessage>([&](DeviceKeysMessage message, bool &ok) { QCOMPARE(message.keyIndex, nextIndex); QVERIFY(message.duplicated); QVERIFY(message.devices.isEmpty()); ok = true; })); //make shure no disconnect QVERIFY(client->waitForNothing()); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testChangeKeyPendingChanges() { quint32 nextIndex = 2;//valid QByteArray scheme = "scheme2"; QByteArray key = "key2"; QByteArray cmac = "cmac2"; try { QVERIFY(client); QVERIFY(!partner); //Send the key change proposal client->send(KeyChangeMessage { nextIndex }); QVERIFY(client->waitForReply<DeviceKeysMessage>([&](DeviceKeysMessage message, bool &ok) { QCOMPARE(message.keyIndex, nextIndex); QVERIFY(!message.duplicated); //skip key checks ok = true; })); //send the actual key update message (ignoring the other 3) NewKeyMessage keyMsg; keyMsg.keyIndex = nextIndex; keyMsg.cmac = devName.toUtf8(); keyMsg.scheme = scheme; keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, key, cmac)); client->sendSigned(keyMsg, crypto); //wait for ack QVERIFY(client->waitForReply<NewKeyAckMessage>([&](NewKeyAckMessage message, bool &ok) { QCOMPARE(message.keyIndex, nextIndex); ok = true; })); //try to send another keychange client->send(KeyChangeMessage { ++nextIndex }); QVERIFY(client->waitForError(ErrorMessage::KeyPendingError));//should have it's own error message clean(client); testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testAddNewKeyInvalidIndex() { quint32 nextIndex = 42;//invalid index try { QVERIFY(client); NewKeyMessage keyMsg; keyMsg.keyIndex = nextIndex; keyMsg.cmac = "cmac"; keyMsg.scheme = "scheme"; keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, "key", "cmac")); client->sendSigned(keyMsg, crypto); //make shure no disconnect QVERIFY(client->waitForError(ErrorMessage::KeyIndexError)); clean(client); testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testAddNewKeyInvalidSignature() { quint32 nextIndex = 3;//valid index try { QVERIFY(client); NewKeyMessage keyMsg; keyMsg.keyIndex = nextIndex; keyMsg.cmac = "cmac"; keyMsg.scheme = "scheme"; keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, "key", "cmac")); auto sData = keyMsg.serializeSigned(crypto->privateSignKey(), crypto->rng(), crypto); sData[sData.size() - 1] = sData[sData.size() - 1] + 'x'; client->sendBytes(sData); //message + fake signature //make shure no disconnect QVERIFY(client->waitForError(ErrorMessage::AuthenticationError)); clean(client); testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testAddNewKeyPendingChanges() { //theoretical situtation, that cannot occur normally quint32 nextIndex = 3;//valid index try { QVERIFY(client); NewKeyMessage keyMsg; keyMsg.keyIndex = nextIndex; keyMsg.cmac = "cmac"; keyMsg.scheme = "scheme"; keyMsg.deviceKeys.append(std::make_tuple(partnerDevId, "key", "cmac")); client->sendSigned(keyMsg, crypto); //make shure no disconnect QVERIFY(client->waitForError(ErrorMessage::ServerError, true));//is ok here, as this case is typically detected by the KeyChangeMessage. clean(client); testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testKeyChangeNoAck() { quint32 nextIndex = 2; QByteArray scheme = "scheme2"; QByteArray key = "key2"; QByteArray cmac = "cmac2"; try { QVERIFY(!partner); partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message partner->sendSigned(LoginMessage { partnerDevId, partnerName, mNonce }, partnerCrypto); //wait for the account message QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) { QVERIFY(!message.hasChanges);//Must have changes now QCOMPARE(message.keyIndex, nextIndex); QCOMPARE(message.scheme, scheme); QCOMPARE(message.key, key); QCOMPARE(message.cmac, cmac); ok = true; })); //do NOT send the mac, but reconnect clean(partner); partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message partner->sendSigned(LoginMessage { partnerDevId, partnerName, mNonce }, partnerCrypto); //wait for the account message QVERIFY(partner->waitForReply<WelcomeMessage>([&](WelcomeMessage message, bool &ok) { QVERIFY(!message.hasChanges);//Must have changes now QCOMPARE(message.keyIndex, nextIndex); QCOMPARE(message.scheme, scheme); QCOMPARE(message.key, key); QCOMPARE(message.cmac, cmac); ok = true; })); //update the mac accordingly partner->send(MacUpdateMessage { nextIndex, partnerName.toUtf8() }); QVERIFY(partner->waitForReply<MacUpdateAckMessage>([&](MacUpdateAckMessage message, bool &ok) { Q_UNUSED(message) ok = true; })); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testListAndRemoveDevices() { try { QVERIFY(client); QVERIFY(partner); //list devices client->send(ListDevicesMessage {}); QList<DevicesMessage::DeviceInfo> infos; QVERIFY(client->waitForReply<DevicesMessage>([&](DevicesMessage message, bool &ok) { QCOMPARE(message.devices.size(), 4); //testAddDevice, testAddDeviceInvalidKeyIndex, testSendDoubleAccept, testDeviceUploading infos = message.devices; ok = true; })); //verify the keys, verify partner, remove others auto ok = false; for(auto info : infos) { QVERIFY(std::get<0>(info) != devId); if(std::get<0>(info) == partnerDevId) { QCOMPARE(std::get<1>(info), partnerName); QCOMPARE(std::get<2>(info), partnerCrypto->ownFingerprint()); ok = true; } else { client->send(RemoveMessage {std::get<0>(info)}); QVERIFY(client->waitForReply<RemoveAckMessage>([&](RemoveAckMessage message, bool &ok) { QCOMPARE(message.deviceId, std::get<0>(info)); ok = true; })); } } QVERIFY(ok); //list from partners side partner->send(ListDevicesMessage {}); QVERIFY(partner->waitForReply<DevicesMessage>([&](DevicesMessage message, bool &ok) { QCOMPARE(message.devices.size(), 1); auto info = message.devices.first(); QCOMPARE(std::get<0>(info), devId); QCOMPARE(std::get<1>(info), devName); QCOMPARE(std::get<2>(info), crypto->ownFingerprint()); ok = true; })); //now delete partner client->send(RemoveMessage {partnerDevId}); QVERIFY(client->waitForReply<RemoveAckMessage>([&](RemoveAckMessage message, bool &ok) { QCOMPARE(message.deviceId, partnerDevId); ok = true; })); //wait for partner disconnect and reconnect QVERIFY(partner->waitForDisconnect()); partner->deleteLater(); partner = new MockClient(this); QVERIFY(partner->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(partner->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message (but partner does not exist anymore partner->sendSigned(LoginMessage { partnerDevId, partnerName, mNonce }, partnerCrypto); QVERIFY(partner->waitForError(ErrorMessage::AuthenticationError)); clean(partner); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testUnexpectedMessage_data() { QTest::addColumn<QSharedPointer<Message>>("message"); QTest::addColumn<bool>("whenIdle"); QTest::addColumn<bool>("isSigned"); QTest::newRow("RegisterMessage") << createNonced<RegisterMessage>() << true << true; QTest::newRow("LoginMessage") << createNonced<LoginMessage>(devId, devName, "nonce") << true << true; QTest::newRow("AccessMessage") << createNonced<AccessMessage>() << true << true; QTest::newRow("SyncMessage") << create<SyncMessage>() << false << false; QTest::newRow("ChangeMessage") << create<ChangeMessage>("data_id") << false << false; QTest::newRow("DeviceChangeMessage") << create<DeviceChangeMessage>("data_id", partnerDevId) << false << false; QTest::newRow("ChangedAckMessage") << create<ChangedAckMessage>(42ull) << false << false; QTest::newRow("ListDevicesMessage") << create<ListDevicesMessage>() << false << false; QTest::newRow("RemoveMessage") << create<RemoveMessage>(partnerDevId) << false << false; QTest::newRow("AcceptMessage") << create<AcceptMessage>(partnerDevId) << false << true; QTest::newRow("DenyMessage") << create<DenyMessage>(partnerDevId) << false << false; QTest::newRow("MacUpdateMessage") << create<MacUpdateMessage>(42, "cmac") << false << false; QTest::newRow("KeyChangeMessage") << create<KeyChangeMessage>(42) << false << false; QTest::newRow("NewKeyMessage") << create<NewKeyMessage>() << false << true; } void TestAppServer::testUnexpectedMessage() { QFETCH(QSharedPointer<Message>, message); QFETCH(bool, whenIdle); QFETCH(bool, isSigned); QVERIFY(message); try { //assume already logged in QVERIFY(client); if(!whenIdle) { clean(client); client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); ok = true; })); } if(isSigned) client->sendSigned(*message, crypto); else client->send(*message); QVERIFY(client->waitForError(ErrorMessage::UnexpectedMessageError, true)); clean(client); testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testUnknownMessage() { try { //assume already logged in QVERIFY(client); client->send(LastChangedMessage()); //unknown of the server QVERIFY(client->waitForError(ErrorMessage::IncompatibleVersionError)); clean(client); testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testBrokenMessage() { try { //assume already logged in QVERIFY(client); client->sendBytes("\x00\x00\x00\x06Change\x00followed_by_gibberish");//header looks right, but not the rest QVERIFY(client->waitForError(ErrorMessage::ClientError)); clean(client); testLogin(); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testRemoveSelf() { try { QVERIFY(client); //list devices client->send(ListDevicesMessage {}); QList<DevicesMessage::DeviceInfo> infos; QVERIFY(client->waitForReply<DevicesMessage>([&](DevicesMessage message, bool &ok) { QVERIFY(message.devices.isEmpty()); ok = true; })); //now delete self client->send(RemoveMessage {devId}); QVERIFY(client->waitForReply<RemoveAckMessage>([&](RemoveAckMessage message, bool &ok) { QCOMPARE(message.deviceId, devId); ok = true; })); clean(client); client = new MockClient(this); QVERIFY(client->waitForConnected()); //wait for identify message QByteArray mNonce; QVERIFY(client->waitForReply<IdentifyMessage>([&](IdentifyMessage message, bool &ok) { QVERIFY(message.nonce.size() >= InitMessage::NonceSize); QCOMPARE(message.protocolVersion, InitMessage::CurrentVersion); mNonce = message.nonce; ok = true; })); //send back a valid login message (but partner does not exist anymore client->sendSigned(LoginMessage { devId, devName, mNonce }, crypto); QVERIFY(client->waitForError(ErrorMessage::AuthenticationError)); clean(client); } catch(std::exception &e) { QFAIL(e.what()); } } void TestAppServer::testStop() { //send a signal to stop #ifdef Q_OS_UNIX server->terminate(); //same as kill(SIGTERM) #elif Q_OS_WIN GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, server->processId()); #endif QVERIFY(server->waitForFinished(5000)); QCOMPARE(server->exitStatus(), QProcess::NormalExit); QCOMPARE(server->exitCode(), 0); server->close(); } void TestAppServer::clean(bool disconnect) { clean(client, disconnect); } void TestAppServer::clean(MockClient *&client, bool disconnect) { if(!client) return; if(disconnect) client->close(); QVERIFY(client->waitForDisconnect()); client->deleteLater(); client = nullptr; } template<typename TMessage, typename... Args> inline QSharedPointer<Message> TestAppServer::create(Args... args) { return QSharedPointer<TMessage>::create(args...).template staticCast<Message>(); } template<typename TMessage, typename... Args> inline QSharedPointer<Message> TestAppServer::createNonced(Args... args) { auto msg = create<TMessage>(args...).template dynamicCast<InitMessage>(); msg->nonce = QByteArray(InitMessage::NonceSize, 'x'); return msg; } QTEST_MAIN(TestAppServer) #include "tst_appserver.moc"
26.819251
138
0.695207
wangyangyangisme
a650c158002bc3fd7675ae8d83eac8d5ca2afca2
2,402
cpp
C++
app/handlers/normalizer.cpp
freelandy/RobustPalmRoi
c94ec3c2a9d14ffe4d5f544796abf3754764b809
[ "MIT" ]
1
2019-05-10T08:46:35.000Z
2019-05-10T08:46:35.000Z
app/handlers/normalizer.cpp
freelandy/RobustPalmRoi
c94ec3c2a9d14ffe4d5f544796abf3754764b809
[ "MIT" ]
null
null
null
app/handlers/normalizer.cpp
freelandy/RobustPalmRoi
c94ec3c2a9d14ffe4d5f544796abf3754764b809
[ "MIT" ]
null
null
null
// Copyright (c) 2018 leosocy. All rights reserved. // Use of this source code is governed by a MIT-style license // that can be found in the LICENSE file. #include "handlers/normalizer.h" namespace rpr { Status OrigNormalizer::Init(const YAML::Node& parameters) { try { scaling_= parameters["scaling"].IsNull() ? 0.0 : parameters["scaling"]["value"].as<double>(); width_ = parameters["width"].IsNull() ? 350 : parameters["width"]["value"].as<int>(); } catch (const std::exception& e) { return Status::LoadConfigYamlError(e.what()); } if (scaling_ <= 0 || scaling_ > 1) { return Status::LoadConfigYamlError("Original image scaling must in range [0.0, 1.0]"); } return Status::Ok(); } Status OrigNormalizer::Handle(PalmInfoDTO& palm) { using utility::ResizeImageOperator; const cv::Mat& orig = palm.PrevHandleRes(); cv::Mat res; ResizeImageOperator *op = new ResizeImageOperator(orig, width_ == 0 ? scaling_ * orig.cols : width_); op->Do(&res); palm.SetCurHandleRes(res); palm.SetImageOperator(std::unique_ptr<rpr::utility::ImageOperator>(op)); return Status::Ok(); } Status IncircleRoiNormalizer::Init(const YAML::Node& parameters) { try { width_ = parameters["width"].IsNull() ? 256 : parameters["width"]["value"].as<int>(); } catch (const std::exception& e) { return Status::LoadConfigYamlError(e.what()); } return Status::Ok(); } Status IncircleRoiNormalizer::Normalize(PalmInfoDTO& palm) { const cv::Mat& roi(palm.roi()); cv::Mat balance_roi; ColorBalance(roi, &balance_roi); cv::Mat mask_roi; MaskIncircle(balance_roi, &mask_roi); palm.SetRoi(mask_roi); return Status::Ok(); } void IncircleRoiNormalizer::MaskIncircle(const cv::Mat& src, cv::Mat* dst) { int radius = src.cols / 2; cv::Mat mask(cv::Mat::zeros(src.size(), CV_8UC1)); circle(mask, cv::Point(src.cols / 2, src.rows / 2), radius, cv::Scalar(255), CV_FILLED); src.copyTo(*dst, mask); } void IncircleRoiNormalizer::ColorBalance(const cv::Mat& src, cv::Mat* dst) { std::vector<cv::Mat> rgb; split(src, rgb); double r, g, b; b = cv::mean(rgb[0])[0]; g = cv::mean(rgb[1])[0]; r = cv::mean(rgb[2])[0]; double kr, kg, kb; kb = (r + g + b) / (3 * b); kg = (r + g + b) / (3 * g); kr = (r + g + b) / (3 * r); rgb[0] = rgb[0] * kb; rgb[1] = rgb[1] * kg; rgb[2] = rgb[2] * kr; merge(rgb, *dst); } } // namespace rpr
28.258824
103
0.641965
freelandy
a650fe3a45c990c0b193fb6ca4bfad93c2741057
6,920
cpp
C++
remodet_repository_wdh_part/src/caffe/tracker/fe_roi_maker.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/src/caffe/tracker/fe_roi_maker.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/src/caffe/tracker/fe_roi_maker.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
#include "caffe/tracker/fe_roi_maker.hpp" namespace caffe { template <typename Dtype> FERoiMaker<Dtype>::FERoiMaker(const std::string& network_proto, const std::string& caffe_model, const int gpu_id, const std::string& features, const int resized_width, const int resized_height) { // Get Net LOG(INFO) << "Using GPU mode in Caffe with device: " << gpu_id; caffe::Caffe::SetDevice(gpu_id); caffe::Caffe::set_mode(caffe::Caffe::GPU); net_.reset(new Net<Dtype>(network_proto, caffe::TEST)); if (caffe_model != "NONE") { net_->CopyTrainedLayersFrom(caffe_model); } else { LOG(FATAL) << "Must define a pre-trained model."; } CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output."; Blob<Dtype>* input_layer = net_->input_blobs()[0]; input_width_ = input_layer->width(); input_height_ = input_layer->height(); LOG(INFO) << "Network requires input size: (width, height) " << input_width_ << ", " << input_height_; CHECK_EQ(input_layer->channels(), 3) << "Input layer should have 3 channels."; // Get Layer LayerParameter layer_param; layer_param.set_name("roi_resize_layer"); layer_param.set_type("RoiResize"); RoiResizeParameter* roi_resize_param = layer_param.mutable_roi_resize_param(); roi_resize_param->set_target_spatial_width(resized_width); roi_resize_param->set_target_spatial_height(resized_height); roi_resize_layer_ = LayerRegistry<Dtype>::CreateLayer(layer_param); vector<Blob<Dtype>*> resize_bottom_vec; vector<Blob<Dtype>*> resize_top_vec; Blob<Dtype> bot_0(1,1,12,12); Blob<Dtype> bot_1(1,1,1,4); Blob<Dtype> top_0(1,1,resized_height,resized_width); resize_bottom_vec.push_back(&bot_0); resize_bottom_vec.push_back(&bot_1); resize_top_vec.push_back(&top_0); roi_resize_layer_->SetUp(resize_bottom_vec, resize_top_vec); // features features_ = features; } template <typename Dtype> void FERoiMaker<Dtype>::getFeatures(const std::string& feature, const Blob<Dtype>* map) { const boost::shared_ptr<Blob<Dtype> > feature_blob = net_->blob_by_name(feature.c_str()); map = feature_blob.get(); } template <typename Dtype> void FERoiMaker<Dtype>::load(const cv::Mat& image) { Blob<Dtype>* input_blob = net_->input_blobs()[0]; CHECK_EQ(image.channels(), 3); int w = image.cols; int h = image.rows; CHECK_GT(w,0); CHECK_GT(h,0); if (!image.data) { LOG(FATAL) << "Image data open failed."; } Dtype scalar = sqrt(512*288/w/h); cv::Mat resized_image; cv::resize(image,resized_image,cv::Size(),scalar,scalar,CV_INTER_LINEAR); input_blob->Reshape(1, 3, resized_image.rows, resized_image.cols); net_->Reshape(); Dtype* transformed_data = input_blob->mutable_cpu_data(); const int offset = resized_image.rows * resized_image.cols; bool normalize = false; for (int i = 0; i < resized_image.rows; ++i) { for (int j = 0; j < resized_image.cols; ++j) { cv::Vec3b& rgb = resized_image.at<cv::Vec3b>(i, j); if (normalize) { transformed_data[i * resized_image.cols + j] = (rgb[0] - 128)/256.0; transformed_data[offset + i * resized_image.cols + j] = (rgb[1] - 128)/256.0; transformed_data[2 * offset + i * resized_image.cols + j] = (rgb[2] - 128)/256.0; } else { transformed_data[i * resized_image.cols + j] = rgb[0] - 104; transformed_data[offset + i * resized_image.cols + j] = rgb[1] - 117;; transformed_data[2 * offset + i * resized_image.cols + j] = rgb[2] - 123;; } } } } template <typename Dtype> void FERoiMaker<Dtype>::roi_resize(const Blob<Dtype>* feature, const BoundingBox<Dtype>& bbox, Blob<Dtype>* resize_fmap) { // get bbox Blob<Dtype> bbox_blob(1,1,1,4); Dtype* bbox_data = bbox_blob.mutable_cpu_data(); bbox_data[0] = bbox.x1_; bbox_data[1] = bbox.y1_; bbox_data[2] = bbox.x2_; bbox_data[3] = bbox.y2_; vector<Blob<Dtype>*> resize_bottom_vec; vector<Blob<Dtype>*> resize_top_vec; Blob<Dtype> fmap; fmap.ReshapeLike(*feature); fmap.ShareData(*feature); resize_bottom_vec.push_back(&fmap); resize_bottom_vec.push_back(&bbox_blob); resize_top_vec.push_back(resize_fmap); roi_resize_layer_->Reshape(resize_bottom_vec, resize_top_vec); roi_resize_layer_->Forward(resize_bottom_vec, resize_top_vec); } template <typename Dtype> void FERoiMaker<Dtype>::get_features(const cv::Mat& image, const BoundingBox<Dtype>& bbox, Blob<Dtype>* resized_fmap) { // Load load(image); // Forward net_->Forward(); // Get features const Blob<Dtype>* feature_blob = NULL; getFeatures(features_, feature_blob); // roi resize roi_resize(feature_blob,bbox,resized_fmap); // done. } template <typename Dtype> void FERoiMaker<Dtype>::get_fmap(const cv::Mat& image, const BoundingBox<Dtype>& bbox, Blob<Dtype>* resized_fmap, Blob<Dtype>* fmap) { // Load load(image); // Forward net_->Forward(); // Get features getFeatures(features_, fmap); // roi resize roi_resize(fmap,bbox,resized_fmap); } template <typename Dtype> void FERoiMaker<Dtype>::get_features(const cv::Mat& image_prev, const cv::Mat& image_curr, const BoundingBox<Dtype>& bbox_prev, const BoundingBox<Dtype>& bbox_curr, Blob<Dtype>* resized_prev, Blob<Dtype>* resized_curr) { get_features(image_prev, bbox_prev, resized_prev); get_features(image_curr, bbox_curr, resized_curr); } template <typename Dtype> void FERoiMaker<Dtype>::get_features(const cv::Mat& image_prev, const cv::Mat& image_curr, const BoundingBox<Dtype>& bbox_prev, const BoundingBox<Dtype>& bbox_curr, Blob<Dtype>* resized_unified_map) { Blob<Dtype> resized_prev; Blob<Dtype> resized_curr; get_features(image_prev, bbox_prev, &resized_prev); get_features(image_curr, bbox_curr, &resized_curr); CHECK_EQ(resized_prev.num(), resized_curr.num()); CHECK_EQ(resized_prev.channels(), resized_curr.channels()); CHECK_EQ(resized_prev.height(), resized_curr.height()); CHECK_EQ(resized_prev.width(), resized_curr.width()); resized_unified_map->Reshape(1,2*resized_prev.channels(),resized_prev.height(),resized_prev.width()); caffe_copy(resized_prev.count(),resized_prev.cpu_data(),resized_unified_map->mutable_cpu_data()); caffe_copy(resized_curr.count(),resized_curr.cpu_data(), resized_unified_map->mutable_cpu_data()+resized_prev.count()); } INSTANTIATE_CLASS(FERoiMaker); }
39.542857
103
0.656936
UrwLee
a6563881b008a1f94b1e58f6854fac0b380d3ebb
65,831
cc
C++
graph/igraph-0.6/src/bliss_graph.cc
FlyerMaxwell/Bubble
70ca988bca3a5debce5d9c61f203b08005bdefaf
[ "MIT" ]
3
2017-09-05T03:06:12.000Z
2019-04-28T13:17:11.000Z
graph/igraph-0.6/src/bliss_graph.cc
FlyerMaxwell/Bubble
70ca988bca3a5debce5d9c61f203b08005bdefaf
[ "MIT" ]
null
null
null
graph/igraph-0.6/src/bliss_graph.cc
FlyerMaxwell/Bubble
70ca988bca3a5debce5d9c61f203b08005bdefaf
[ "MIT" ]
1
2019-03-05T06:24:02.000Z
2019-03-05T06:24:02.000Z
/* Copyright (C) 2003-2006 Tommi Junttila This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ /* FSF address fixed in the above notice on 1 Oct 2009 by Tamas Nepusz */ #include <cstdio> #include <cassert> #include <cctype> #include <set> #include <list> #include <algorithm> #include "bliss_defs.hh" #include "bliss_timer.hh" #include "bliss_graph.hh" #include "bliss_partition.hh" #include <climits> // INT_MAX, etc #include "igraph_datatype.h" #include "igraph_interface.h" #include "igraph_topology.h" #include "igraph_statusbar.h" using namespace std; extern bool bliss_verbose; // extern FILE *bliss_verbstr; namespace igraph { static const bool should_not_happen = false; /*------------------------------------------------------------------------- * * Constructor and destructor routines for the abstract graph class * *-------------------------------------------------------------------------*/ AbstractGraph::AbstractGraph() { /* Initialize stuff */ first_path_labeling = 0; first_path_labeling_inv = 0; best_path_labeling = 0; best_path_labeling_inv = 0; first_path_automorphism = 0; best_path_automorphism = 0; //certificate = 0; in_search = false; } AbstractGraph::~AbstractGraph() { if(first_path_labeling) { free(first_path_labeling); first_path_labeling = 0; } if(first_path_labeling_inv) { free(first_path_labeling_inv); first_path_labeling_inv = 0; } if(best_path_labeling) { free(best_path_labeling); best_path_labeling = 0; } if(best_path_labeling_inv) { free(best_path_labeling_inv); best_path_labeling_inv = 0; } if(first_path_automorphism) { free(first_path_automorphism); first_path_automorphism = 0; } if(best_path_automorphism) { free(best_path_automorphism); best_path_automorphism = 0; } //if(certificate) { // free(certificate); certificate = 0; } while(!long_prune_fixed.empty()) { delete long_prune_fixed.back(); long_prune_fixed.pop_back(); } while(!long_prune_mcrs.empty()) { delete long_prune_mcrs.back(); long_prune_mcrs.pop_back(); } } /*------------------------------------------------------------------------- * * Routines for refinement to equitable partition * *-------------------------------------------------------------------------*/ void AbstractGraph::refine_to_equitable() { assert(p.splitting_queue.is_empty()); for(Cell *cell = p.first_cell; cell; cell = cell->next) { p.add_in_splitting_queue(cell); } return do_refine_to_equitable(); } void AbstractGraph::refine_to_equitable(Cell *cell1) { DEBUG_ASSERT(cell1->length == 1); #ifdef EXPENSIVE_CONSISTENCY_CHECKS for(Cell *cell = p.first_cell; cell; cell = cell->next) { assert(cell->in_splitting_queue == false); assert(cell->in_neighbour_heap == false); } #endif assert(p.splitting_queue.is_empty()); p.add_in_splitting_queue(cell1); return do_refine_to_equitable(); } void AbstractGraph::refine_to_equitable(Cell *cell1, Cell *cell2) { DEBUG_ASSERT(cell1->length == 1); DEBUG_ASSERT(cell2->length == 1); #ifdef EXPENSIVE_CONSISTENCY_CHECKS for(Cell *cell = p.first_cell; cell; cell = cell->next) { assert(cell->in_splitting_queue == false); assert(cell->in_neighbour_heap == false); } #endif assert(p.splitting_queue.is_empty()); p.add_in_splitting_queue(cell1); p.add_in_splitting_queue(cell2); return do_refine_to_equitable(); } void AbstractGraph::do_refine_to_equitable() { assert(!p.splitting_queue.is_empty()); assert(neighbour_heap.is_empty()); eqref_hash.reset(); while(!p.splitting_queue.is_empty()) { Cell *cell = p.splitting_queue.pop_front(); DEBUG_ASSERT(cell->in_splitting_queue); cell->in_splitting_queue = false; if(cell->length == 1) { if(in_search) { if(first_path_automorphism) { /* Build the (potential) automorphism on-the-fly */ assert(first_path_labeling_inv); first_path_automorphism[first_path_labeling_inv[cell->first]] = p.elements[cell->first]; } if(best_path_automorphism) { /* Build the (potential) automorphism on-the-fly */ assert(best_path_labeling_inv); best_path_automorphism[best_path_labeling_inv[cell->first]] = p.elements[cell->first]; } } bool worse = split_neighbourhood_of_unit_cell(cell); if(in_search && worse) goto worse_exit; } else { split_neighbourhood_of_cell(cell); } } eqref_worse_than_certificate = false; return; worse_exit: /* Clear splitting_queue */ p.clear_splitting_queue(); eqref_worse_than_certificate = true; return; } /*------------------------------------------------------------------------- * * Routines for handling the canonical labeling * *-------------------------------------------------------------------------*/ void AbstractGraph::update_labeling(unsigned int * const labeling) { const unsigned int N = get_nof_vertices(); unsigned int *ep = p.elements; for(unsigned int i = 0; i < N; i++, ep++) labeling[*ep] = i; } void AbstractGraph::update_labeling_and_its_inverse(unsigned int * const labeling, unsigned int * const labeling_inv) { const unsigned int N = get_nof_vertices(); unsigned int *ep = p.elements; unsigned int *clip = labeling_inv; for(unsigned int i = 0; i < N; ) { labeling[*ep] = i; i++; *clip = *ep; ep++; clip++; } } /*------------------------------------------------------------------------- * * Routines for handling automorphisms * *-------------------------------------------------------------------------*/ void AbstractGraph::reset_permutation(unsigned int *perm) { const unsigned int N = get_nof_vertices(); for(unsigned int i = 0; i < N; i++, perm++) *perm = i; } bool AbstractGraph::is_automorphism(unsigned int * const perm) { assert(should_not_happen); return false; } /*------------------------------------------------------------------------- * * Long prune code * *-------------------------------------------------------------------------*/ void AbstractGraph::long_prune_init() { const unsigned int N = get_nof_vertices(); long_prune_temp.clear(); long_prune_temp.resize(N); #ifdef DEBUG for(unsigned int i = 0; i < N; i++) assert(long_prune_temp[i] == false); #endif const unsigned int nof_fitting_in_max_mem = (long_prune_options_max_mem * 1024 * 1024) / (((N * 2) / 8)+1); long_prune_max_stored_autss = long_prune_options_max_stored_auts; /* Had some problems with g++ in using (a<b)?a:b when constants involved, so had to make this in a stupid way...*/ if(nof_fitting_in_max_mem < long_prune_options_max_stored_auts) long_prune_max_stored_autss = nof_fitting_in_max_mem; while(!long_prune_fixed.empty()) { delete long_prune_fixed.back(); long_prune_fixed.pop_back(); } while(!long_prune_mcrs.empty()) { delete long_prune_mcrs.back(); long_prune_mcrs.pop_back(); } for(unsigned int i = 0; i < long_prune_max_stored_autss; i++) { long_prune_fixed.push_back(new std::vector<bool>(N)); long_prune_mcrs.push_back(new std::vector<bool>(N)); } long_prune_begin = 0; long_prune_end = 0; } void AbstractGraph::long_prune_swap(const unsigned int i, const unsigned int j) { assert(long_prune_begin <= long_prune_end); assert(long_prune_end - long_prune_end <= long_prune_max_stored_autss); assert(i >= long_prune_begin); assert(i < long_prune_end); assert(j >= long_prune_begin); assert(j < long_prune_end); const unsigned int real_i = i % long_prune_max_stored_autss; const unsigned int real_j = j % long_prune_max_stored_autss; std::vector<bool> * tmp = long_prune_fixed[real_i]; long_prune_fixed[real_i] = long_prune_fixed[real_j]; long_prune_fixed[real_j] = tmp; tmp = long_prune_mcrs[real_i]; long_prune_mcrs[real_i] = long_prune_mcrs[real_j]; long_prune_mcrs[real_j] = tmp; } std::vector<bool> &AbstractGraph::long_prune_get_fixed(const unsigned int index) { assert(long_prune_begin <= long_prune_end); assert(long_prune_end - long_prune_end <= long_prune_max_stored_autss); assert(index >= long_prune_begin); assert(index < long_prune_end); return *long_prune_fixed[index % long_prune_max_stored_autss]; } std::vector<bool> &AbstractGraph::long_prune_get_mcrs(const unsigned int index) { assert(long_prune_begin <= long_prune_end); assert(long_prune_end - long_prune_end <= long_prune_max_stored_autss); assert(index >= long_prune_begin); assert(index < long_prune_end); return *long_prune_mcrs[index % long_prune_max_stored_autss]; } void AbstractGraph::long_prune_add_automorphism(const unsigned int *aut) { if(long_prune_max_stored_autss == 0) return; const unsigned int N = get_nof_vertices(); #ifdef DEBUG assert(long_prune_temp.size() == N); for(unsigned int i = 0; i < N; i++) assert(long_prune_temp[i] == false); #endif DEBUG_ASSERT(long_prune_fixed.size() == long_prune_mcrs.size()); assert(long_prune_begin <= long_prune_end); assert(long_prune_end - long_prune_end <= long_prune_max_stored_autss); if(long_prune_end - long_prune_begin == long_prune_max_stored_autss) { long_prune_begin++; } long_prune_end++; std::vector<bool> &fixed = long_prune_get_fixed(long_prune_end-1); std::vector<bool> &mcrs = long_prune_get_mcrs(long_prune_end-1); for(unsigned int i = 0; i < N; i++) { fixed[i] = (aut[i] == i); if(!long_prune_temp[i]) { mcrs[i] = true; unsigned int j = aut[i]; while(j != i) { assert(i <= j); long_prune_temp[j] = true; j = aut[j]; } } else { mcrs[i] = false; } long_prune_temp[i] = false; } #ifdef DEBUG for(unsigned int i = 0; i < N; i++) assert(long_prune_temp[i] == false); #endif } /*------------------------------------------------------------------------- * * Routines for handling orbit information * *-------------------------------------------------------------------------*/ void AbstractGraph::update_orbit_information(Orbit &o, const unsigned int *p) { const unsigned int N = get_nof_vertices(); for(unsigned int i = 0; i < N; i++) if(p[i] != i) o.merge_orbits(i, p[i]); } /*------------------------------------------------------------------------- * * Print a permutation in cycle notation * *-------------------------------------------------------------------------*/ void AbstractGraph::print_permutation(FILE *fp, const unsigned int *perm) { const unsigned int N = get_nof_vertices(); for(unsigned int i = 0; i < N; i++) { unsigned int j = perm[i]; if(j == i) continue; bool is_first = true; while(j != i) { if(j < i) { is_first = false; break; } j = perm[j]; } if(!is_first) continue; fprintf(fp, "(%u,", i); j = perm[i]; while(j != i) { fprintf(fp, "%u", j); j = perm[j]; if(j != i) fprintf(fp, ","); } fprintf(fp, ")"); } } /*------------------------------------------------------------------------- * * The actual backtracking search * *-------------------------------------------------------------------------*/ typedef struct { int split_element; unsigned int split_cell_first; unsigned int refinement_stack_size; unsigned int certificate_index; bool in_first_path; bool in_best_path; bool equal_to_first_path; int cmp_to_best_path; bool needs_long_prune; unsigned int long_prune_begin; std::set<unsigned int, std::less<unsigned int> > long_prune_redundant; EqrefHash eqref_hash; unsigned int subcertificate_length; } LevelInfo; typedef struct t_path_info { unsigned int splitting_element; unsigned int certificate_index; unsigned int subcertificate_length; EqrefHash eqref_hash; } PathInfo; void AbstractGraph::search(const bool canonical, Stats &stats) { const unsigned int N = get_nof_vertices(); // const bool write_automorphisms = 0; unsigned int all_same_level = UINT_MAX; p.graph = this; /* * Must be done! */ remove_duplicate_edges(); /* * Reset search statistics */ stats.group_size.assign(1); stats.nof_nodes = 1; stats.nof_leaf_nodes = 1; stats.nof_bad_nodes = 0; stats.nof_canupdates = 0; stats.nof_generators = 0; stats.max_level = 0; if(first_path_labeling) { free(first_path_labeling); first_path_labeling = 0; } if(first_path_labeling_inv) { free(first_path_labeling_inv); first_path_labeling_inv = 0; } if(first_path_automorphism) { free(first_path_automorphism); first_path_automorphism = 0; } if(best_path_labeling) { free(best_path_labeling); best_path_labeling = 0; } if(best_path_labeling_inv) { free(best_path_labeling_inv); best_path_labeling_inv = 0; } if(best_path_automorphism) { free(best_path_automorphism); best_path_automorphism = 0; } if(N == 0) return; p.init(N); neighbour_heap.init(N); in_search = false; p.level = 0; Timer t1; t1.start(); make_initial_equitable_partition(); #if defined(VERIFY_EQUITABLEDNESS) assert(is_equitable()); #endif t1.stop(); igraph_statusf("Initial partition computed in %.2fs", 0, t1.get_duration()); /* * Allocate space for the labelings */ if(first_path_labeling) free(first_path_labeling); first_path_labeling = (unsigned int*)calloc(N, sizeof(unsigned int)); if(best_path_labeling) free(best_path_labeling); best_path_labeling = (unsigned int*)calloc(N, sizeof(unsigned int)); /* * Are there any non-singleton cells? */ if(p.is_discrete()) { update_labeling(best_path_labeling); return; } //p.print_signature(stderr); fprintf(stderr, "\n"); /* * Allocate space for the inverses of the labelings */ if(first_path_labeling_inv) free(first_path_labeling_inv); first_path_labeling_inv = (unsigned int*)calloc(N, sizeof(unsigned int)); if(best_path_labeling_inv) free(best_path_labeling_inv); best_path_labeling_inv = (unsigned int*)calloc(N, sizeof(unsigned int)); /* * Allocate space for the automorphisms */ if(first_path_automorphism) free(first_path_automorphism); first_path_automorphism = (unsigned int*)malloc(N * sizeof(unsigned int)); if(best_path_automorphism) free(best_path_automorphism); best_path_automorphism = (unsigned int*)malloc(N * sizeof(unsigned int)); /* * Initialize orbit information */ first_path_orbits.init(N); best_path_orbits.init(N); /* * Initialize certificate memory */ initialize_certificate(); //assert(certificate); assert(certificate_index == 0); LevelInfo info; std::vector<LevelInfo> search_stack; std::vector<PathInfo> first_path_info; std::vector<PathInfo> best_path_info; search_stack.clear(); p.refinement_stack.clean(); assert(neighbour_heap.is_empty()); /* * Initialize long prune */ long_prune_init(); /* * Build the first level info */ info.split_cell_first = find_next_cell_to_be_splitted(p.first_cell)->first; info.split_element = -1; info.refinement_stack_size = p.refinement_stack.size(); info.certificate_index = 0; info.in_first_path = false; info.in_best_path = false; info.long_prune_begin = 0; search_stack.push_back(info); /* * Set status and global flags for search related procedures */ in_search = true; refine_compare_certificate = false; stats.nof_leaf_nodes = 0; #ifdef PRINT_SEARCH_TREE_DOT dotty_output = fopen("debug_stree.dot", "w"); fprintf(dotty_output, "digraph stree {\n"); fprintf(dotty_output, "\"n\" [label=\""); fprintf(dotty_output, "M"); //p.print(dotty_output); fprintf(dotty_output, "\"];\n"); #endif p.consistency_check(); /* * The actual backtracking search */ while(!search_stack.empty()) { info = search_stack.back(); search_stack.pop_back(); p.consistency_check(); /* * Restore partition, certificate index, and split cell */ p.unrefine(p.level, info.refinement_stack_size); assert(info.certificate_index <= certificate_size); certificate_index = info.certificate_index; certificate_current_path.resize(certificate_index); Cell * const cell = p.element_to_cell_map[p.elements[info.split_cell_first]]; assert(cell->length > 1); p.consistency_check(); if(p.level > 0 && !info.in_first_path) { if(info.split_element == -1) { info.needs_long_prune = true; } else if(info.needs_long_prune) { info.needs_long_prune = false; /* THIS IS A QUITE HORRIBLE HACK! */ unsigned int begin = (info.long_prune_begin>long_prune_begin)?info.long_prune_begin:long_prune_begin; for(unsigned int i = begin; i < long_prune_end; i++) { const std::vector<bool> &fixed = long_prune_get_fixed(i); bool fixes_all = true; for(unsigned int l = 0; l < p.level; l++) { if(fixed[search_stack[l].split_element] == false) { fixes_all = false; break; } } if(!fixes_all) { long_prune_swap(begin, i); begin++; info.long_prune_begin = begin; continue; } const std::vector<bool> &mcrs = long_prune_get_mcrs(i); unsigned int *ep = p.elements + cell->first; for(unsigned int j = cell->length; j > 0; j--, ep++) { if(mcrs[*ep] == false) { info.long_prune_redundant.insert(*ep); } } } } } /* * Find the next smallest element in cell */ unsigned int next_split_element = UINT_MAX; unsigned int *next_split_element_pos = 0; unsigned int *ep = p.elements + cell->first; if(info.in_first_path) { /* Find the next larger splitting element that is a mor */ for(unsigned int i = cell->length; i > 0; i--, ep++) { if((int)(*ep) > info.split_element && *ep < next_split_element && first_path_orbits.is_minimal_representative(*ep)) { next_split_element = *ep; next_split_element_pos = ep; } } } else if(info.in_best_path) { /* Find the next larger splitting element that is a mor */ for(unsigned int i = cell->length; i > 0; i--, ep++) { if((int)(*ep) > info.split_element && *ep < next_split_element && best_path_orbits.is_minimal_representative(*ep) && (info.long_prune_redundant.find(*ep) == info.long_prune_redundant.end())) { next_split_element = *ep; next_split_element_pos = ep; } } } else { /* Find the next larger splitting element */ for(unsigned int i = cell->length; i > 0; i--, ep++) { if((int)(*ep) > info.split_element && *ep < next_split_element && (info.long_prune_redundant.find(*ep) == info.long_prune_redundant.end())) { next_split_element = *ep; next_split_element_pos = ep; } } } if(next_split_element == UINT_MAX) { /* * No more splitting elements (unexplored children) in the cell */ /* Update group size if required */ if(info.in_first_path == true) { const unsigned int index = first_path_orbits.orbit_size(first_path_info[p.level].splitting_element); stats.group_size.multiply(index); /* * Update all_same_level */ if(index == cell->length && all_same_level == p.level+1) all_same_level = p.level; igraph_statusf("Level %u: orbits=%u, index=%u/%u, " "all_same_level=%u", 0, p.level, first_path_orbits.nof_orbits(), index, cell->length, all_same_level); } /* Backtrack to the previous level */ p.level--; continue; } /* Split on smallest */ info.split_element = next_split_element; /* * Save the current search situation */ search_stack.push_back(info); /* * No more in the first path */ info.in_first_path = false; /* * No more in the best path */ info.in_best_path = false; p.level++; stats.nof_nodes++; if(p.level > stats.max_level) stats.max_level = p.level; p.consistency_check(); /* * Move the split element to be the last in the cell */ *next_split_element_pos = p.elements[cell->first + cell->length - 1]; p.in_pos[*next_split_element_pos] = next_split_element_pos; p.elements[cell->first + cell->length - 1] = next_split_element; p.in_pos[next_split_element] = p.elements+ cell->first + cell->length -1; /* * Split the cell in two: * the last element in the cell (split element) forms a singleton cell */ Cell * const new_cell = p.aux_split_in_two(cell, cell->length - 1); p.element_to_cell_map[p.elements[new_cell->first]] = new_cell; p.consistency_check(); /* const bool prev_equal_to_first_path = info.equal_to_first_path; const int prev_cmp_to_best_path = info.cmp_to_best_path; */ //assert(!(!info.equal_to_first_path && info.cmp_to_best_path < 0)); if(!first_path_info.empty()) { refine_equal_to_first = info.equal_to_first_path; if(refine_equal_to_first) refine_first_path_subcertificate_end = first_path_info[p.level-1].certificate_index + first_path_info[p.level-1].subcertificate_length; if(canonical) { refine_cmp_to_best = info.cmp_to_best_path; if(refine_cmp_to_best == 0) refine_best_path_subcertificate_end = best_path_info[p.level-1].certificate_index + best_path_info[p.level-1].subcertificate_length; } else refine_cmp_to_best = -1; } /* * Refine the new partition to equitable */ if(cell->length == 1) refine_to_equitable(cell, new_cell); else refine_to_equitable(new_cell); p.consistency_check(); #ifdef PRINT_SEARCH_TREE_DOT fprintf(dotty_output, "\"n"); for(unsigned int i = 0; i < search_stack.size(); i++) { fprintf(dotty_output, "%u", search_stack[i].split_element); if(i < search_stack.size() - 1) fprintf(dotty_output, "."); } fprintf(dotty_output, "\""); fprintf(dotty_output, " [label=\""); fprintf(dotty_output, "%u",cell->first); /*p.print(dotty_output);*/ fprintf(dotty_output, "\"]"); if(!first_path_info.empty() && canonical && refine_cmp_to_best > 0) { fprintf(dotty_output, "[color=green]"); } fprintf(dotty_output, ";\n"); fprintf(dotty_output, "\"n"); for(unsigned int i = 0; i < search_stack.size() - 1; i++) { fprintf(dotty_output, "%u", search_stack[i].split_element); if(i < search_stack.size() - 2) fprintf(dotty_output, "."); } fprintf(dotty_output, "\" -> \"n"); for(unsigned int i = 0; i < search_stack.size(); i++) { fprintf(dotty_output, "%u", search_stack[i].split_element); if(i < search_stack.size() - 1) fprintf(dotty_output, "."); } fprintf(dotty_output, "\" [label=\"%d\"];\n", next_split_element); #endif /* if(prev_cmp_to_best_path == 0 && refine_cmp_to_best < 0) fprintf(stderr, "BP- "); if(prev_cmp_to_best_path == 0 && refine_cmp_to_best > 0) fprintf(stderr, "BP+ "); */ if(p.is_discrete()) { /* Update statistics */ stats.nof_leaf_nodes++; /* if(stats.nof_leaf_nodes % 100 == 0) { fprintf(stdout, "Nodes: %lu, Leafs: %lu, Bad: %lu\n", stats.nof_nodes, stats.nof_leaf_nodes, stats.nof_bad_nodes); fflush(stdout); } */ } if(!first_path_info.empty()) { /* We are no longer on the first path */ assert(best_path_info.size() > 0); assert(certificate_current_path.size() >= certificate_index); const unsigned int subcertificate_length = certificate_current_path.size() - certificate_index; if(refine_equal_to_first) { /* Was equal to the first path so far */ assert(first_path_info.size() >= p.level); PathInfo &first_pinfo = first_path_info[p.level-1]; assert(first_pinfo.certificate_index == certificate_index); if(subcertificate_length != first_pinfo.subcertificate_length) { refine_equal_to_first = false; } else if(first_pinfo.eqref_hash.cmp(eqref_hash) != 0) { refine_equal_to_first = false; } } if(canonical && (refine_cmp_to_best == 0)) { /* Was equal to the best path so far */ assert(best_path_info.size() >= p.level); PathInfo &best_pinfo = best_path_info[p.level-1]; assert(best_pinfo.certificate_index == certificate_index); if(subcertificate_length < best_pinfo.subcertificate_length) { refine_cmp_to_best = -1; //fprintf(stderr, "BSCL- "); } else if(subcertificate_length > best_pinfo.subcertificate_length) { refine_cmp_to_best = 1; //fprintf(stderr, "BSCL+ "); } else if(best_pinfo.eqref_hash.cmp(eqref_hash) > 0) { refine_cmp_to_best = -1; //fprintf(stderr, "BHL- "); } else if(best_pinfo.eqref_hash.cmp(eqref_hash) < 0) { refine_cmp_to_best = 1; //fprintf(stderr, "BHL+ "); } } if(refine_equal_to_first == false && (!canonical || (refine_cmp_to_best < 0))) { /* Backtrack */ #ifdef PRINT_SEARCH_TREE_DOT fprintf(dotty_output, "\"n"); for(unsigned int i = 0; i < search_stack.size(); i++) { fprintf(dotty_output, "%u", search_stack[i].split_element); if(i < search_stack.size() - 1) fprintf(dotty_output, "."); } fprintf(dotty_output, "\" [color=red];\n"); #endif stats.nof_bad_nodes++; if(search_stack.back().equal_to_first_path == true && p.level > all_same_level) { assert(all_same_level >= 1); for(unsigned int i = all_same_level; i < search_stack.size(); i++) { search_stack[i].equal_to_first_path = false; } } while(!search_stack.empty()) { p.level--; LevelInfo &info2 = search_stack.back(); if(!(info2.equal_to_first_path == false && (!canonical || (info2.cmp_to_best_path < 0)))) break; search_stack.pop_back(); } continue; } } #if defined(VERIFY_EQUITABLEDNESS) /* The new partition should be equitable */ assert(is_equitable()); #endif info.equal_to_first_path = refine_equal_to_first; info.cmp_to_best_path = refine_cmp_to_best; certificate_index = certificate_current_path.size(); search_stack.back().eqref_hash = eqref_hash; search_stack.back().subcertificate_length = certificate_index - info.certificate_index; if(!p.is_discrete()) { /* * An internal, non-leaf node */ /* Build the next node info */ /* Find the next cell to be splitted */ assert(cell == p.element_to_cell_map[p.elements[info.split_cell_first]]); Cell * const next_split_cell = find_next_cell_to_be_splitted(cell); assert(next_split_cell); /* Copy current info to the search stack */ search_stack.push_back(info); LevelInfo &new_info = search_stack.back(); new_info.split_cell_first = next_split_cell->first; new_info.split_element = -1; new_info.certificate_index = certificate_index; new_info.refinement_stack_size = p.refinement_stack.size(); new_info.long_prune_redundant.clear(); new_info.long_prune_begin = info.long_prune_begin; continue; } /* * A leaf node */ assert(certificate_index == certificate_size); if(first_path_info.empty()) { /* The first path, update first_path and best_path */ //fprintf(stdout, "Level %u: FIRST\n", p.level); fflush(stdout); stats.nof_canupdates++; /* * Update labelings and their inverses */ update_labeling_and_its_inverse(first_path_labeling, first_path_labeling_inv); update_labeling_and_its_inverse(best_path_labeling, best_path_labeling_inv); /* * Reset automorphism array */ reset_permutation(first_path_automorphism); reset_permutation(best_path_automorphism); /* * Reset orbit information */ first_path_orbits.reset(); best_path_orbits.reset(); /* * Reset group size */ stats.group_size.assign(1); /* * Reset all_same_level */ all_same_level = p.level; /* * Mark the current path to be the first and best one and save it */ const unsigned int base_size = search_stack.size(); assert(p.level == base_size); best_path_info.clear(); //fprintf(stdout, " New base is: "); for(unsigned int i = 0; i < base_size; i++) { search_stack[i].in_first_path = true; search_stack[i].in_best_path = true; search_stack[i].equal_to_first_path = true; search_stack[i].cmp_to_best_path = 0; PathInfo path_info; path_info.splitting_element = search_stack[i].split_element; path_info.certificate_index = search_stack[i].certificate_index; path_info.eqref_hash = search_stack[i].eqref_hash; path_info.subcertificate_length = search_stack[i].subcertificate_length; first_path_info.push_back(path_info); best_path_info.push_back(path_info); //fprintf(stdout, "%u ", search_stack[i].split_element); } //fprintf(stdout, "\n"); fflush(stdout); certificate_first_path = certificate_current_path; certificate_best_path = certificate_current_path; refine_compare_certificate = true; /* * Backtrack to the previous level */ p.level--; continue; } DEBUG_ASSERT(first_path_info.size() > 0); //fprintf(stdout, "Level %u: LEAF %d %d\n", p.level, info.equal_to_first_path, info.cmp_to_best_path); fflush(stdout); if(info.equal_to_first_path) { /* * An automorphism found: aut[i] = elements[first_path_labeling[i]] */ assert(!info.in_first_path); //fprintf(stdout, "A"); fflush(stdout); #ifdef PRINT_SEARCH_TREE_DOT fprintf(dotty_output, "\"n"); for(unsigned int i = 0; i < search_stack.size(); i++) { fprintf(dotty_output, "%u", search_stack[i].split_element); if(i < search_stack.size() - 1) fprintf(dotty_output, "."); } fprintf(dotty_output, "\" [color=blue];\n"); #endif #if defined(DEBUG) /* Verify that the automorphism is correctly built */ for(unsigned int i = 0; i < N; i++) assert(first_path_automorphism[i] == p.elements[first_path_labeling[i]]); #endif #if defined(VERIFY_AUTOMORPHISMS) /* Verify that it really is an automorphism */ assert(is_automorphism(first_path_automorphism)); #endif long_prune_add_automorphism(first_path_automorphism); /* * Update orbit information */ update_orbit_information(first_path_orbits, first_path_automorphism); /* * Compute backjumping level */ unsigned int backjumping_level = 0; for(unsigned int i = search_stack.size(); i > 0; i--) { const unsigned int split_element = search_stack[backjumping_level].split_element; if(first_path_automorphism[split_element] != split_element) break; backjumping_level++; } assert(backjumping_level < p.level); /* * Go back to backjumping_level */ p.level = backjumping_level; search_stack.resize(p.level + 1); // if(write_automorphisms) // { // print_permutation(stdout, first_path_automorphism); // fprintf(stdout, "\n"); // } stats.nof_generators++; continue; } assert(canonical); assert(info.cmp_to_best_path >= 0); if(info.cmp_to_best_path > 0) { /* * A new, better representative found */ //fprintf(stdout, "Level %u: NEW BEST\n", p.level); fflush(stdout); stats.nof_canupdates++; /* * Update canonical labeling and its inverse */ update_labeling_and_its_inverse(best_path_labeling, best_path_labeling_inv); /* Reset best path automorphism */ reset_permutation(best_path_automorphism); /* Reset best path orbit structure */ best_path_orbits.reset(); /* * Mark the current path to be the best one and save it */ const unsigned int base_size = search_stack.size(); assert(p.level == base_size); best_path_info.clear(); //fprintf(stdout, " New base is: "); for(unsigned int i = 0; i < base_size; i++) { search_stack[i].cmp_to_best_path = 0; search_stack[i].in_best_path = true; PathInfo path_info; path_info.splitting_element = search_stack[i].split_element; path_info.certificate_index = search_stack[i].certificate_index; path_info.eqref_hash = search_stack[i].eqref_hash; path_info.subcertificate_length = search_stack[i].subcertificate_length; best_path_info.push_back(path_info); //fprintf(stdout, "%u ", search_stack[i].split_element); } certificate_best_path = certificate_current_path; //fprintf(stdout, "\n"); fflush(stdout); /* * Backtrack to the previous level */ p.level--; continue; } { //fprintf(stderr, "BAUT "); /* * Equal to the previous best path */ #if defined(DEBUG) /* Verify that the automorphism is correctly built */ for(unsigned int i = 0; i < N; i++) assert(best_path_automorphism[i] == p.elements[best_path_labeling[i]]); #endif #if defined(VERIFY_AUTOMORPHISMS) /* Verify that it really is an automorphism */ assert(is_automorphism(best_path_automorphism)); #endif unsigned int gca_level_with_first = 0; for(unsigned int i = search_stack.size(); i > 0; i--) { if((int)first_path_info[gca_level_with_first].splitting_element != search_stack[gca_level_with_first].split_element) break; gca_level_with_first++; } assert(gca_level_with_first < p.level); unsigned int gca_level_with_best = 0; for(unsigned int i = search_stack.size(); i > 0; i--) { if((int)best_path_info[gca_level_with_best].splitting_element != search_stack[gca_level_with_best].split_element) break; gca_level_with_best++; } assert(gca_level_with_best < p.level); long_prune_add_automorphism(best_path_automorphism); /* * Update orbit information */ update_orbit_information(best_path_orbits, best_path_automorphism); /* * Update orbit information */ const unsigned int nof_old_orbits = first_path_orbits.nof_orbits(); update_orbit_information(first_path_orbits, best_path_automorphism); if(nof_old_orbits != first_path_orbits.nof_orbits()) { // if(write_automorphisms) // { // print_permutation(stdout, best_path_automorphism); // fprintf(stdout, "\n"); // } stats.nof_generators++; } /* * Compute backjumping level */ unsigned int backjumping_level = p.level - 1; if(!first_path_orbits.is_minimal_representative(search_stack[gca_level_with_first].split_element)) { backjumping_level = gca_level_with_first; /*fprintf(stderr, "bj1: %u %u\n", p.level, backjumping_level);*/ } else { assert(!best_path_orbits.is_minimal_representative(search_stack[gca_level_with_best].split_element)); backjumping_level = gca_level_with_best; /*fprintf(stderr, "bj2: %u %u\n", p.level, backjumping_level);*/ } /* Backtrack */ search_stack.resize(backjumping_level + 1); p.level = backjumping_level; continue; } } #ifdef PRINT_SEARCH_TREE_DOT fprintf(dotty_output, "}\n"); fclose(dotty_output); #endif } void AbstractGraph::find_automorphisms(Stats &stats) { search(false, stats); if(first_path_labeling) { free(first_path_labeling); first_path_labeling = 0; } if(best_path_labeling) { free(best_path_labeling); best_path_labeling = 0; } } const unsigned int *AbstractGraph::canonical_form(Stats &stats) { search(true, stats); return best_path_labeling; } /*------------------------------------------------------------------------- * * Routines for undirected graphs * *-------------------------------------------------------------------------*/ Graph::Vertex::Vertex() { label = 1; nof_edges = 0; } Graph::Vertex::~Vertex() { ; } void Graph::Vertex::add_edge(const unsigned int other_vertex) { edges.push_back(other_vertex); nof_edges++; DEBUG_ASSERT(nof_edges == edges.size()); } void Graph::Vertex::remove_duplicate_edges(bool * const duplicate_array) { for(std::vector<unsigned int>::iterator iter = edges.begin(); iter != edges.end(); ) { const unsigned int dest_vertex = *iter; if(duplicate_array[dest_vertex] == true) { /* A duplicate edge found! */ iter = edges.erase(iter); nof_edges--; DEBUG_ASSERT(nof_edges == edges.size()); } else { /* Not seen earlier, mark as seen */ duplicate_array[dest_vertex] = true; iter++; } } /* Clear duplicate_array */ for(std::vector<unsigned int>::iterator iter = edges.begin(); iter != edges.end(); iter++) { duplicate_array[*iter] = false; } } /*------------------------------------------------------------------------- * * Constructor and destructor for undirected graphs * *-------------------------------------------------------------------------*/ Graph::Graph(const unsigned int nof_vertices) { vertices.resize(nof_vertices); sh = sh_flm; } Graph::~Graph() { ; } unsigned int Graph::add_vertex(const unsigned int new_label) { const unsigned int new_vertex_num = vertices.size(); vertices.resize(new_vertex_num + 1); vertices.back().label = new_label; return new_vertex_num; } void Graph::add_edge(const unsigned int vertex1, const unsigned int vertex2) { //fprintf(stderr, "(%u,%u) ", vertex1, vertex2); assert(vertex1 < vertices.size()); assert(vertex2 < vertices.size()); vertices[vertex1].add_edge(vertex2); vertices[vertex2].add_edge(vertex1); } void Graph::change_label(const unsigned int vertex, const unsigned int new_label) { assert(vertex < vertices.size()); vertices[vertex].label = new_label; } /*------------------------------------------------------------------------- * * Read graph in the DIMACS format * *-------------------------------------------------------------------------*/ // Graph *Graph::read_dimacs(FILE *fp) // { // Graph *g = 0; // unsigned int nof_vertices, nof_edges; // unsigned int line_num = 1; // int c; // /* read comments and problem line*/ // while(1) { // c = getc(fp); // if(c == 'c') { // while((c = getc(fp)) != '\n') { // if(c == EOF) { // fprintf(stderr, "error in line %u: not in DIMACS format\n", // line_num); // goto error_exit; // } // } // line_num++; // continue; // } // if(c == 'p') { // if(fscanf(fp, " edge %u %u\n", &nof_vertices, &nof_edges) != 2) { // fprintf(stderr, "error in line %u: not in DIMACS format\n", // line_num); // goto error_exit; } // line_num++; // break; // } // fprintf(stderr, "error in line %u: not in DIMACS format\n", line_num); // goto error_exit; // } // if(nof_vertices <= 0) { // fprintf(stderr, "error: no vertices\n"); // goto error_exit; // } // #if 0 // if(nof_edges <= 0) { // fprintf(stderr, "error: no edges\n"); // goto error_exit; // } // #endif // if(bliss_verbose) { // fprintf(bliss_verbstr, "Instance has %d vertices and %d edges\n", // nof_vertices, nof_edges); // fflush(bliss_verbstr); // } // g = new Graph(nof_vertices); // // // // Read vertex labels // // // if(bliss_verbose) { // fprintf(bliss_verbstr, "Reading vertex labels...\n"); // fflush(bliss_verbstr); } // while(1) { // c = getc(fp); // if(c != 'n') { // ungetc(c, fp); // break; // } // ungetc(c, fp); // unsigned int vertex, label; // if(fscanf(fp, "n %u %u\n", &vertex, &label) != 2) { // fprintf(stderr, "error in line %u: not in DIMACS format\n", // line_num); // goto error_exit; // } // if(vertex > nof_vertices) { // fprintf(stderr, "error in line %u: not in DIMACS format\n", // line_num); // goto error_exit; // } // line_num++; // g->change_label(vertex - 1, label); // } // if(bliss_verbose) { // fprintf(bliss_verbstr, "Done\n"); // fflush(bliss_verbstr); } // // // // Read edges // // // if(bliss_verbose) { // fprintf(bliss_verbstr, "Reading edges...\n"); // fflush(bliss_verbstr); } // for(unsigned i = 0; i < nof_edges; i++) { // unsigned int from, to; // if(fscanf(fp, "e %u %u\n", &from, &to) != 2) { // fprintf(stderr, "error in line %u: not in DIMACS format\n", // line_num); // goto error_exit; // } // if(from > nof_vertices || to > nof_vertices) { // fprintf(stderr, "error in line %u: not in DIMACS format\n", // line_num); // goto error_exit; // } // line_num++; // g->add_edge(from - 1, to - 1); // } // if(bliss_verbose) { // fprintf(bliss_verbstr, "Done\n"); // fflush(bliss_verbstr); // } // return g; // error_exit: // if(g) // delete g; // return 0; // } Graph *Graph::from_igraph(const igraph_t *graph) { unsigned int nof_vertices= (unsigned int)igraph_vcount(graph); unsigned int nof_edges= (unsigned int)igraph_ecount(graph); Graph *g=new Graph(nof_vertices); // for (unsigned int i=0; i<nof_vertices; i++) { // g->change_label(i, i); // } for (unsigned int i=0; i<nof_edges; i++) { g->add_edge((unsigned int)IGRAPH_FROM(graph, i), (unsigned int)IGRAPH_TO(graph, i)); } return g; } void Graph::print_dimacs(FILE *fp) { unsigned int nof_edges = 0; for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; for(std::vector<unsigned int>::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int dest_i = *ei; if(dest_i < i) continue; nof_edges++; } } fprintf(fp, "p edge %u %u\n", get_nof_vertices(), nof_edges); for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; if(v.label != 1) { fprintf(fp, "n %u %u\n", i+1, v.label); } } for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; for(std::vector<unsigned int>::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int dest_i = *ei; if(dest_i < i) continue; fprintf(fp, "e %u %u\n", i+1, dest_i+1); } } } Graph *Graph::permute(const unsigned int *perm) { Graph *g = new Graph(get_nof_vertices()); for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; Vertex &permuted_v = g->vertices[perm[i]]; permuted_v.label = v.label; for(std::vector<unsigned int>::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int dest_v = *ei; permuted_v.add_edge(perm[dest_v]); } std::sort(permuted_v.edges.begin(), permuted_v.edges.end()); } return g; } /*------------------------------------------------------------------------- * * Print graph in graphviz format * *-------------------------------------------------------------------------*/ void Graph::to_dot(const char *file_name) { FILE *fp = fopen(file_name, "w"); if(fp) to_dot(fp); fclose(fp); } void Graph::to_dot(FILE *fp) { remove_duplicate_edges(); fprintf(fp, "graph g {\n"); unsigned int vnum = 0; for(std::vector<Vertex>::iterator vi = vertices.begin(); vi != vertices.end(); vi++, vnum++) { Vertex &v = *vi; fprintf(fp, "v%u [label=\"%u:%u\"];\n", vnum, vnum, v.label); for(std::vector<unsigned int>::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int vnum2 = *ei; if(vnum2 > vnum) fprintf(fp, "v%u -- v%u\n", vnum, vnum2); } } fprintf(fp, "}\n"); } void Graph::remove_duplicate_edges() { bool *duplicate_array = (bool*)calloc(vertices.size(), sizeof(bool)); for(std::vector<Vertex>::iterator vi = vertices.begin(); vi != vertices.end(); vi++) { #ifdef EXPENSIVE_CONSISTENCY_CHECKS for(unsigned int i = 0; i < vertices.size(); i++) assert(duplicate_array[i] == false); #endif Vertex &v = *vi; v.remove_duplicate_edges(duplicate_array); } free(duplicate_array); } /*------------------------------------------------------------------------- * * Partition independent invariants * *-------------------------------------------------------------------------*/ unsigned int Graph::label_invariant(Graph *g, unsigned int v) { DEBUG_ASSERT(v < g->vertices.size()); return g->vertices[v].label; } unsigned int Graph::degree_invariant(Graph *g, unsigned int v) { DEBUG_ASSERT(v < g->vertices.size()); DEBUG_ASSERT(g->vertices[v].edges.size() == g->vertices[v].nof_edges); return g->vertices[v].nof_edges; } /*------------------------------------------------------------------------- * * Refine the partition p according to a partition independent invariant * *-------------------------------------------------------------------------*/ bool Graph::refine_according_to_invariant(unsigned int (*inv)(Graph * const g, unsigned int v)) { bool refined = false; for(Cell *cell = p.first_cell; cell; ) { assert(cell->max_ival == 0); assert(cell->max_ival_count == 0); Cell * const next_cell = cell->next; if(cell->length == 1) { cell = next_cell; continue; } const unsigned int *ep = p.elements + cell->first; for(unsigned int i = cell->length; i > 0; i--, ep++) { unsigned int ival = inv(this, *ep); p.invariant_values[*ep] = ival; if(ival > cell->max_ival) { cell->max_ival = ival; cell->max_ival_count = 1; } else if(ival == cell->max_ival) { cell->max_ival_count++; } } Cell * const last_new_cell = p.zplit_cell(cell, true); refined = (last_new_cell != cell); cell = next_cell; } return refined; } /*------------------------------------------------------------------------- * * Split the neighbourhood of a cell according to the equitable invariant * *-------------------------------------------------------------------------*/ void Graph::split_neighbourhood_of_cell(Cell * const cell) { DEBUG_ASSERT(neighbour_heap.is_empty()); DEBUG_ASSERT(cell->length > 1); eqref_hash.update(cell->first); eqref_hash.update(cell->length); unsigned int *ep = p.elements + cell->first; for(unsigned int i = cell->length; i > 0; i--) { const Vertex &v = vertices[*ep]; ep++; std::vector<unsigned int>::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges; j > 0; j--) { const unsigned int dest_vertex = *ei++; Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex]; if(neighbour_cell->length == 1) continue; const unsigned int ival = p.invariant_values[dest_vertex] + 1; p.invariant_values[dest_vertex] = ival; if(ival > neighbour_cell->max_ival) { neighbour_cell->max_ival = ival; neighbour_cell->max_ival_count = 1; } else if(ival == neighbour_cell->max_ival) { neighbour_cell->max_ival_count++; } if(!neighbour_cell->in_neighbour_heap) { neighbour_cell->in_neighbour_heap = true; neighbour_heap.insert(neighbour_cell->first); } } } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Cell * const neighbour_cell = p.element_to_cell_map[p.elements[start]]; DEBUG_ASSERT(neighbour_cell->first == start); DEBUG_ASSERT(neighbour_cell->in_neighbour_heap); neighbour_cell->in_neighbour_heap = false; DEBUG_ASSERT(neighbour_cell->length > 1); DEBUG_ASSERT(neighbour_cell->max_ival >= 1); DEBUG_ASSERT(neighbour_cell->max_ival_count >= 1); eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(neighbour_cell->max_ival); eqref_hash.update(neighbour_cell->max_ival_count); Cell * const last_new_cell = p.zplit_cell(neighbour_cell, true); /* Update hash */ const Cell *c = neighbour_cell; while(1) { eqref_hash.update(c->first); eqref_hash.update(c->length); if(c == last_new_cell) break; c = c->next; } } } bool Graph::split_neighbourhood_of_unit_cell(Cell * const unit_cell) { DEBUG_ASSERT(neighbour_heap.is_empty()); DEBUG_ASSERT(unit_cell->length == 1); DEBUG_ASSERT(p.element_to_cell_map[p.elements[unit_cell->first]] == unit_cell); DEBUG_ASSERT(p.in_pos[p.elements[unit_cell->first]] == p.elements + unit_cell->first); eqref_hash.update(0x87654321); eqref_hash.update(unit_cell->first); eqref_hash.update(1); const Vertex &v = vertices[p.elements[unit_cell->first]]; std::vector<unsigned int>::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges; j > 0; j--) { const unsigned int dest_vertex = *ei++; Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex]; DEBUG_ASSERT(*p.in_pos[dest_vertex] == dest_vertex); if(neighbour_cell->length == 1) { DEBUG_ASSERT(!neighbour_cell->in_neighbour_heap); if(in_search) { neighbour_cell->in_neighbour_heap = true; neighbour_heap.insert(neighbour_cell->first); } continue; } if(!neighbour_cell->in_neighbour_heap) { neighbour_cell->in_neighbour_heap = true; neighbour_heap.insert(neighbour_cell->first); } neighbour_cell->max_ival_count++; DEBUG_ASSERT(neighbour_cell->max_ival_count <= neighbour_cell->length); unsigned int * const swap_position = p.elements + neighbour_cell->first + neighbour_cell->length - neighbour_cell->max_ival_count; DEBUG_ASSERT(p.in_pos[dest_vertex] <= swap_position); *p.in_pos[dest_vertex] = *swap_position; p.in_pos[*swap_position] = p.in_pos[dest_vertex]; *swap_position = dest_vertex; p.in_pos[dest_vertex] = swap_position; } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Cell *neighbour_cell = p.element_to_cell_map[p.elements[start]]; DEBUG_ASSERT(neighbour_cell->in_neighbour_heap); neighbour_cell->in_neighbour_heap = false; #ifdef DEBUG assert(neighbour_cell->first == start); if(neighbour_cell->length == 1) { assert(neighbour_cell->max_ival_count == 0); } else { assert(neighbour_cell->max_ival_count > 0); assert(neighbour_cell->max_ival_count <= neighbour_cell->length); } #endif eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(neighbour_cell->max_ival_count); if(neighbour_cell->length > 1 && neighbour_cell->max_ival_count != neighbour_cell->length) { p.consistency_check(); Cell * const new_cell = p.aux_split_in_two(neighbour_cell, neighbour_cell->length - neighbour_cell->max_ival_count); unsigned int *ep = p.elements + new_cell->first; unsigned int * const lp = p.elements+new_cell->first+new_cell->length; while(ep < lp) { DEBUG_ASSERT(p.in_pos[*ep] == ep); p.element_to_cell_map[*ep] = new_cell; ep++; } neighbour_cell->max_ival_count = 0; p.consistency_check(); /* update hash */ eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(0); eqref_hash.update(new_cell->first); eqref_hash.update(new_cell->length); eqref_hash.update(1); /* Add cells in splitting_queue */ DEBUG_ASSERT(!new_cell->in_splitting_queue); if(neighbour_cell->in_splitting_queue) { /* Both cells must be included in splitting_queue in order to have refinement to equitable partition */ p.add_in_splitting_queue(new_cell); } else { Cell *min_cell, *max_cell; if(neighbour_cell->length <= new_cell->length) { min_cell = neighbour_cell; max_cell = new_cell; } else { min_cell = new_cell; max_cell = neighbour_cell; } /* Put the smaller cell in splitting_queue */ p.add_in_splitting_queue(min_cell); if(max_cell->length == 1) { /* Put the "larger" cell also in splitting_queue */ p.add_in_splitting_queue(max_cell); } } /* Update pointer for certificate generation */ neighbour_cell = new_cell; } else neighbour_cell->max_ival_count = 0; /* * Build certificate if required */ if(in_search) { for(unsigned int i = neighbour_cell->first, j = neighbour_cell->length, c_index = certificate_current_path.size(); j > 0; j--, i++, c_index += 2) { if(refine_compare_certificate) { if(refine_equal_to_first) { if(c_index >= refine_first_path_subcertificate_end) refine_equal_to_first = false; else if(certificate_first_path[c_index] != unit_cell->first) refine_equal_to_first = false; else if(certificate_first_path[c_index+1] != i) refine_equal_to_first = false; } if(refine_cmp_to_best == 0) { if(c_index >= refine_best_path_subcertificate_end) { refine_cmp_to_best = 1; } else if(unit_cell->first>certificate_best_path[c_index]) { refine_cmp_to_best = 1; } else if(unit_cell->first<certificate_best_path[c_index]) { refine_cmp_to_best = -1; } else if(i > certificate_best_path[c_index+1]) { refine_cmp_to_best = 1; } else if(i < certificate_best_path[c_index+1]) { refine_cmp_to_best = -1; } } if((refine_equal_to_first == false) && (refine_cmp_to_best < 0)) goto worse_exit; } certificate_current_path.push_back(unit_cell->first); certificate_current_path.push_back(i); } } /* if(in_search) */ } /* while(!neighbour_heap.is_empty()) */ return false; worse_exit: while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Cell * const neighbour_cell = p.element_to_cell_map[p.elements[start]]; DEBUG_ASSERT(neighbour_cell->in_neighbour_heap); neighbour_cell->in_neighbour_heap = false; neighbour_cell->max_ival_count = 0; } return true; } /*------------------------------------------------------------------------- * * Check whether the current partition p is equitable * Slow: use only for debugging purposes * Side effect: resets max_ival and max_ival_count fields in cells * *-------------------------------------------------------------------------*/ bool Graph::is_equitable() { bool result = true; /* * Max ival and max_ival_count are used for counting purposes, * they should be reset... */ for(Cell *cell = p.first_cell; cell; cell = cell->next) { assert(cell->prev_next_ptr && *(cell->prev_next_ptr) == cell); assert(cell->max_ival == 0); assert(cell->max_ival_count == 0); } for(Cell *cell = p.first_cell; cell; cell = cell->next) { if(cell->length == 1) continue; unsigned int *ep = p.elements + cell->first; Vertex &first_vertex = vertices[*ep++]; /* Count edges of the first vertex for cells in max_ival */ std::vector<unsigned int>::const_iterator ei = first_vertex.edges.begin(); for(unsigned int j = first_vertex.nof_edges; j > 0; j--) { p.element_to_cell_map[*ei++]->max_ival++; } /* Count and compare edges of the other vertices */ for(unsigned int i = cell->length; i > 1; i--) { Vertex &vertex = vertices[*ep++]; std::vector<unsigned int>::const_iterator ei = vertex.edges.begin(); for(unsigned int j = vertex.nof_edges; j > 0; j--) { p.element_to_cell_map[*ei++]->max_ival_count++; } for(Cell *cell2 = p.first_cell; cell2; cell2 = cell2->next) { if(cell2->max_ival != cell2->max_ival_count) { result = false; goto done; } cell2->max_ival_count = 0; } } /* Reset max_ival */ for(Cell *cell2 = p.first_cell; cell2; cell2 = cell2->next) { cell2->max_ival = 0; assert(cell2->max_ival_count == 0); } } done: for(Cell *cell = p.first_cell; cell; cell = cell->next) { cell->max_ival = 0; cell->max_ival_count = 0; } return result; } /*------------------------------------------------------------------------- * * Build the initial equitable partition * *-------------------------------------------------------------------------*/ void Graph::make_initial_equitable_partition() { refine_according_to_invariant(&label_invariant); p.clear_splitting_queue(); //p.print_signature(stderr); fprintf(stderr, "\n"); refine_according_to_invariant(&degree_invariant); p.clear_splitting_queue(); //p.print_signature(stderr); fprintf(stderr, "\n"); /* To do: add loop invariant */ refine_to_equitable(); p.refinement_stack.clean(); //p.print_signature(stderr); fprintf(stderr, "\n"); } /*------------------------------------------------------------------------- * * Find the next cell to be splitted * *-------------------------------------------------------------------------*/ Cell *Graph::find_next_cell_to_be_splitted(Cell *cell) { assert(!p.is_discrete()); switch(sh) { case sh_f: return sh_first(cell); case sh_fs: return sh_first_smallest(cell); case sh_fl: return sh_first_largest(cell); case sh_fm: return sh_first_max_neighbours(cell); case sh_fsm: return sh_first_smallest_max_neighbours(cell); case sh_flm: return sh_first_largest_max_neighbours(cell); default: assert(false && "Unknown splitting heuristics"); return 0; } } /* First nonsingleton cell */ Cell *Graph::sh_first(Cell *cell) { return p.first_nonsingleton_cell; } /* First smallest nonsingleton cell. */ Cell *Graph::sh_first_smallest(Cell *cell) { Cell *best_cell = 0; unsigned int best_size = UINT_MAX; for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { assert(cell->length > 1); if(cell->length < best_size) { best_size = cell->length; best_cell = cell; } } assert(best_cell); return best_cell; } /* First largest nonsingleton cell. */ Cell *Graph::sh_first_largest(Cell *cell) { Cell *best_cell = 0; unsigned int best_size = 0; for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { assert(cell->length > 1); if(cell->length > best_size) { best_size = cell->length; best_cell = cell; } } assert(best_cell); return best_cell; } /* First nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Messes up in_neighbour_heap and max_ival fields of cells * (assumes they are false/0). */ Cell *Graph::sh_first_max_neighbours(Cell *cell) { Cell *best_cell = 0; int best_value = -1; for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { assert(cell->length > 1); const Vertex &v = vertices[p.elements[cell->first]]; std::vector<unsigned int>::const_iterator ei = v.edges.begin(); std::list<Cell*> neighbour_cells_visited; for(unsigned int j = v.nof_edges; j > 0; j--) { const unsigned int dest_vertex = *ei++; Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex]; if(neighbour_cell->length == 1) continue; neighbour_cell->max_ival++; if(neighbour_cell->in_neighbour_heap) continue; neighbour_cell->in_neighbour_heap = true; neighbour_cells_visited.push_back(neighbour_cell); } int value = 0; while(!neighbour_cells_visited.empty()) { Cell * const neighbour_cell = neighbour_cells_visited.front(); neighbour_cells_visited.pop_front(); assert(neighbour_cell->in_neighbour_heap); neighbour_cell->in_neighbour_heap = false; if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if(value > best_value) { best_value = value; best_cell = cell; } } assert(best_cell); return best_cell; } /* First smallest nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Messes up in_neighbour_heap and max_ival fields of cells * (assumes they are false). */ Cell *Graph::sh_first_smallest_max_neighbours(Cell *cell) { Cell *best_cell = 0; int best_value = -1; int best_size = INT_MAX; for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { assert(cell->length > 1); const Vertex &v = vertices[p.elements[cell->first]]; std::vector<unsigned int>::const_iterator ei = v.edges.begin(); std::list<Cell*> neighbour_cells_visited; for(unsigned int j = v.nof_edges; j > 0; j--) { const unsigned int dest_vertex = *ei++; Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex]; if(neighbour_cell->length == 1) continue; neighbour_cell->max_ival++; if(neighbour_cell->in_neighbour_heap) continue; neighbour_cell->in_neighbour_heap = true; neighbour_cells_visited.push_back(neighbour_cell); } int value = 0; while(!neighbour_cells_visited.empty()) { Cell * const neighbour_cell = neighbour_cells_visited.front(); neighbour_cells_visited.pop_front(); assert(neighbour_cell->in_neighbour_heap); neighbour_cell->in_neighbour_heap = false; if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if((value > best_value) || (value == best_value && (int)cell->length < best_size)) { best_value = value; best_size = cell->length; best_cell = cell; } } assert(best_cell); return best_cell; } /* First largest nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Messes up in_neighbour_heap and max_ival fields of cells * (assumes they are false/0). */ Cell *Graph::sh_first_largest_max_neighbours(Cell *cell) { Cell *best_cell = 0; int best_value = -1; int best_size = -1; for(cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { assert(cell->length > 1); const Vertex &v = vertices[p.elements[cell->first]]; std::vector<unsigned int>::const_iterator ei = v.edges.begin(); std::list<Cell*> neighbour_cells_visited; for(unsigned int j = v.nof_edges; j > 0; j--) { const unsigned int dest_vertex = *ei++; Cell * const neighbour_cell = p.element_to_cell_map[dest_vertex]; if(neighbour_cell->length == 1) continue; neighbour_cell->max_ival++; if(neighbour_cell->in_neighbour_heap) continue; neighbour_cell->in_neighbour_heap = true; neighbour_cells_visited.push_back(neighbour_cell); } int value = 0; while(!neighbour_cells_visited.empty()) { Cell * const neighbour_cell = neighbour_cells_visited.front(); neighbour_cells_visited.pop_front(); assert(neighbour_cell->in_neighbour_heap); neighbour_cell->in_neighbour_heap = false; if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if((value > best_value) || (value == best_value && (int)cell->length > best_size)) { best_value = value; best_size = cell->length; best_cell = cell; } } assert(best_cell); return best_cell; } /*------------------------------------------------------------------------- * * Initialize the certificate size and memory * *-------------------------------------------------------------------------*/ void Graph::initialize_certificate() { certificate_size = 0; for(Cell *cell = p.first_cell; cell; cell = cell->next) { if(cell->length > 1) { certificate_size += vertices[p.elements[cell->first]].nof_edges * 2 * cell->length; } } //if(certificate) // free(certificate); //certificate = (unsigned int*)malloc(certificate_size * sizeof(unsigned int)); certificate_index = 0; certificate_current_path.clear(); certificate_first_path.clear(); certificate_best_path.clear(); } /*------------------------------------------------------------------------- * * Check whether perm is an automorphism * *-------------------------------------------------------------------------*/ bool Graph::is_automorphism(unsigned int * const perm) { std::set<unsigned int, std::less<unsigned int> > edges1; std::set<unsigned int, std::less<unsigned int> > edges2; bool result = true; for(unsigned int i = 0; i < vertices.size(); i++) { Vertex &v1 = vertices[i]; edges1.clear(); for(std::vector<unsigned int>::iterator ei = v1.edges.begin(); ei != v1.edges.end(); ei++) edges1.insert(perm[*ei]); Vertex &v2 = vertices[perm[i]]; edges2.clear(); for(std::vector<unsigned int>::iterator ei = v2.edges.begin(); ei != v2.edges.end(); ei++) edges2.insert(*ei); if(!(edges1 == edges2)) { result = false; goto done; } } done: return result; } }
26.353483
124
0.626589
FlyerMaxwell
a659a259e67a8172c5a4ac3047508f60291a54f2
433
cpp
C++
Ex4_3_master.cpp
DF4IAH/OpenMP
9eb4c429d3d9da799fe0a5767d91b2c654358bdf
[ "MIT" ]
null
null
null
Ex4_3_master.cpp
DF4IAH/OpenMP
9eb4c429d3d9da799fe0a5767d91b2c654358bdf
[ "MIT" ]
null
null
null
Ex4_3_master.cpp
DF4IAH/OpenMP
9eb4c429d3d9da799fe0a5767d91b2c654358bdf
[ "MIT" ]
null
null
null
#include <stdio.h> #include "omp.h" const int NUM_SLICES = 16; const int NUM_THREADS = 4; int main(void) { long id; omp_set_num_threads(NUM_THREADS); #pragma omp parallel { id = omp_get_thread_num(); #pragma omp master { id += 100; printf("master: id = %ld\r\n", id); } //#pragma omp barrier id = omp_get_thread_num(); printf("id = %ld\r\n", id); } printf("done.\n"); return 0; }
13.121212
38
0.591224
DF4IAH
a65adb063771c6bfc88c0a3bd474e16cb971570e
3,065
cpp
C++
03_elementaryDataStructure/stack/cpp/StackLinkedListMain.cpp
haxpor/algo-cpp-c
5c88523072701765ad126d0a0946e2e76a09f3bb
[ "MIT" ]
1
2019-11-17T09:03:30.000Z
2019-11-17T09:03:30.000Z
03_elementaryDataStructure/stack/cpp/StackLinkedListMain.cpp
haxpor/algocpp-study
5c88523072701765ad126d0a0946e2e76a09f3bb
[ "MIT" ]
null
null
null
03_elementaryDataStructure/stack/cpp/StackLinkedListMain.cpp
haxpor/algocpp-study
5c88523072701765ad126d0a0946e2e76a09f3bb
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include "StackLinkedList.h" /** compile-time logging functions for convenient **/ template<typename Arg> constexpr void LOG(Arg && arg) { std::cout << arg << "\n"; } template<typename Arg1, typename Arg2> constexpr void LOG2(Arg1 && arg1, Arg2 && arg2) { std::cout << arg1 << arg2 << "\n"; } template<typename Arg1, typename Arg2, typename Arg3> constexpr void LOG3(Arg1 && arg1, Arg2 && arg2, Arg3 && arg3) { std::cout << arg1 << arg2 << arg3 << "\n"; } /** end of logging functions **/ struct Data { int val; inline friend std::ostream& operator <<(std::ostream& out, const Data& d) { out << "val: " << d.val; return out; } }; /** * Convert fully parenthesized infix expression to postfix expression. */ std::string ConvertToPostfix(const std::string& infix) { std::stringstream ss; StackLinkedList<char> ts; for (auto it = infix.begin(); it != infix.end(); ++it) { char c = *it; if (c == '+' || c == '-' || c == '*') { ts.Push(c); } else if (c >= '0' && c <= '9') { ss << c << " "; } else if (c == ')') { ss << ts.Pop() << " "; // if it's the last element if (it == infix.end() - 1) { while (!ts.IsEmpty()) { ss << ts.Pop(); } } } } // usually if you check pointer address of ss.str() via std::addressof() // and with normal compilation flags of gcc, it will be the same externally // at the call site. This is because of RVO (return value optimization). // We can disable it via -fno-elide-constructors return ss.str(); } /** * Compute result from value from postfix expression. */ int ComputePostfix(const std::string& postfix) { StackLinkedList<int> ts; for (const char c : postfix) { if (c >= '0' && c <= '9') { ts.Push(static_cast<int>(c-'0')); } else if (c == '+') { ts.Push((ts.Pop() + ts.Pop())); } else if (c == '-') { ts.Push((ts.Pop() - ts.Pop())); } else if (c == '*') { ts.Push((ts.Pop() * ts.Pop())); } } return ts.Pop(); } int main() { /** Testing section **/ StackLinkedList<int> s; s.Push(1); s.Push(2); LOG(s.Pop()); LOG2(std::boolalpha, s.IsEmpty()); LOG(s.Pop()); LOG2(std::boolalpha, s.IsEmpty()); StackLinkedList<Data> s2; s2.Push(Data {100}); s2.Push(Data {200}); LOG(s2.Pop()); LOG2(std::boolalpha, s.IsEmpty()); LOG(s2.Pop()); LOG2(std::boolalpha, s.IsEmpty()); std::cout << "\n"; /** Infix/Postfix and its calculation **/ const std::string infix ( "5 * (((9+8) * (4*6)) + 7)" ); const std::string postfix = ConvertToPostfix(infix); LOG2("Postfix: ", postfix); int result = ComputePostfix(postfix); LOG2("Result: ", result); std::cout << std::endl; return 0; }
24.133858
79
0.511256
haxpor
a661edb27e91f66dde83c0237b810901875bc92b
16,823
cpp
C++
bbs/diredit.cpp
uriel1998/wwiv
623cca6862540a5dc4ce355d7966766bf5d0fd0d
[ "Apache-2.0" ]
null
null
null
bbs/diredit.cpp
uriel1998/wwiv
623cca6862540a5dc4ce355d7966766bf5d0fd0d
[ "Apache-2.0" ]
null
null
null
bbs/diredit.cpp
uriel1998/wwiv
623cca6862540a5dc4ce355d7966766bf5d0fd0d
[ "Apache-2.0" ]
null
null
null
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)1998-2020, WWIV Software Services */ /* */ /* 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 "bbs/conf.h" #include "bbs/acs.h" #include "bbs/bbs.h" #include "bbs/bbsutl.h" #include "bbs/bbsutl1.h" #include "bbs/confutil.h" #include "bbs/wqscn.h" #include "common/com.h" #include "common/input.h" #include "common/pause.h" #include "core/datafile.h" #include "core/stl.h" #include "core/strings.h" #include "fmt/printf.h" #include "sdk/files/dirs.h" #include "sdk/usermanager.h" #include <string> using std::string; using wwiv::common::InputMode; using wwiv::core::DataFile; using namespace wwiv::core; using namespace wwiv::sdk; using namespace wwiv::stl; using namespace wwiv::strings; // // Local Function Prototypes // void modify_dir(int n); void swap_dirs(int dir1, int dir2); void insert_dir(int n); void delete_dir(int n); static std::string tail(const std::string& s, int len) { return len >= ssize(s) ? s : s.substr(s.size() - len); } static std::string dirdata(int n) { const auto& r = a()->dirs()[n]; return fmt::sprintf("|#2%4d |#1%-24.24s |#2%-8s |#9%-3d |#3%-23.23s |#1%s", n, stripcolors(r.name), r.filename, r.maxfiles, tail(r.path, 23), r.conf.to_string()); } static void showdirs() { bout.cls(); bout << "|#7(|#1File Areas Editor|#7) Enter Substring: "; const auto pattern = bin.input_text(20); bout.cls(); bool abort = false; bout.bpla("|#2## Description Filename Num Path Conf", &abort); bout.bpla("|#7==== ======================== -------- === ----------------------- -------", &abort); for (auto i = 0; i < wwiv::stl::ssize(a()->dirs()) && !abort; i++) { auto text = StrCat(a()->dirs()[i].name, " ", a()->dirs()[i].filename); if (ifind_first(text, pattern)) { bout.bpla(dirdata(i), &abort); } } } std::optional<net_networks_rec> select_network() { std::map<int, net_networks_rec> nets; auto num = 0; for (const auto& n : a()->nets().networks()) { if (n.type == network_type_t::ftn) { nets.emplace(++num, n); } } bout << "|#5Networks: " << wwiv::endl; for (const auto& n : nets) { bout << "|#1" << n.first << "|#9) |#2" << n.second.name << wwiv::endl; } bout.nl(); bout << "|#2(Q=Quit) Select Network Number : "; const auto r = bin.input_number_hotkey(0, {'Q'}, 1, num, false); if (r.key == 'Q') { return std::nullopt; } auto it = nets.find(r.num); if (it == std::end(nets)) { return std::nullopt; } return {it->second}; } enum class list_area_tags_style_t { number, indent }; static void list_area_tags(const std::vector<wwiv::sdk::files::dir_area_t>& area_tags, list_area_tags_style_t style) { if (area_tags.empty()) { bout << "|#6(None)" << wwiv::endl; return; } net_networks_rec empty{}; empty.name = "(Unknown)"; auto nn = 0; auto first{true}; for (const auto& t : area_tags) { if (style == list_area_tags_style_t::number) { bout << "|#2" << nn++ << "|#9) "; } else if (style == list_area_tags_style_t::indent) { if (!first) { bout << " "; } first = false; } bout << "|#1" << t.area_tag << "|#9@|#5" << a()->nets().by_uuid(t.net_uuid).value_or(empty).name << wwiv::endl; } } static void edit_ftn_area_tags(std::vector<wwiv::sdk::files::dir_area_t>& area_tags) { auto done{false}; do { bout.cls(); bout.litebar("Editing File Area Tags"); bout.nl(); list_area_tags(area_tags, list_area_tags_style_t::number); bout.nl(); bout << "|#7(|#2Q|#7=|#1Quit|#7) Which (|#2A|#7dd, |#2E|#7dit, or |#2D|#7elete) : "; const auto ch = onek("QAED", true); switch (ch) { case 'A': { files::dir_area_t da{}; bout << "Enter Name? "; da.area_tag = bin.input_upper(12); const auto r = select_network(); if (!r) { break; } da.net_uuid = r.value().uuid; area_tags.push_back(da); } break; case 'D': { if (area_tags.empty()) { break; } bout << "(Q=Quit, 1=" << area_tags.size() << ") Enter Number? "; const auto r = bin.input_number_hotkey(0, {'Q'}, 1, size_int(area_tags), false); if (r.key == 'Q') { break; } bout << "Are you sure?"; if (bin.noyes()) { erase_at(area_tags, r.num - 1); } } break; case 'E': { bout << "Edit!"; if (area_tags.empty()) { break; } bout << "(Q=Quit, 1=" << area_tags.size() << ") Enter Number? "; const auto r = bin.input_number_hotkey(0, {'Q'}, 1, size_int(area_tags), false); if (r.key == 'Q') { break; } files::dir_area_t da{}; bout << "Enter Name? "; da.area_tag = bin.input_upper(12); const auto nr = select_network(); if (!nr) { break; } da.net_uuid = nr.value().uuid; bout << "Are you sure?"; if (bin.noyes()) { area_tags[r.num - 1] = da; } } break; case 'Q': done = true; break; } } while (!done && !a()->sess().hangup()); } void modify_dir(int n) { auto r = a()->dirs()[n]; auto done = false; do { bout.cls(); bout.litebar(StrCat("Editing File Area #", n)); bout << "|#9A) Name : |#2" << r.name << wwiv::endl; bout << "|#9B) Filename : |#2" << r.filename << wwiv::endl; bout << "|#9C) Path : |#2" << r.path << wwiv::endl; bout << "|#9D) ACS : |#2" << r.acs << wwiv::endl; bout << "|#9F) Max Files : |#2" << r.maxfiles << wwiv::endl; bout << "|#9H) Require PD : |#2" << YesNoString((r.mask & mask_PD) ? true : false) << wwiv::endl; bout << "|#9J) Uploads : |#2" << ((r.mask & mask_no_uploads) ? "Disallowed" : "Allowed") << wwiv::endl; bout << "|#9K) Arch. only : |#2" << YesNoString((r.mask & mask_archive) ? true : false) << wwiv::endl; bout << "|#9L) Drive Type : |#2" << ((r.mask & mask_cdrom) ? "|#3CD ROM" : "HARD DRIVE") << wwiv::endl; if (r.mask & mask_cdrom) { bout << "|#9M) Available : |#2" << YesNoString((r.mask & mask_offline) ? true : false) << wwiv::endl; } bout << "|#9N) //UPLOADALL : |#2" << YesNoString((r.mask & mask_uploadall) ? true : false) << wwiv::endl; bout << "|#9O) WWIV Reg : |#2" << YesNoString((r.mask & mask_wwivreg) ? true : false) << wwiv::endl; bout << "|#9T) FTN Area Tags: |#2"; list_area_tags(r.area_tags, list_area_tags_style_t::indent); bout << "|#9 Conferences : |#2" << r.conf.to_string() << wwiv::endl; bout.nl(2); bout << "|#7(|#2Q|#7=|#1Quit|#7) Which (|#1A|#7-|#1O|#7,|#1[T|#7,|#1[|#7,|#1]|#7) : "; const auto ch = onek("QABCDEFGHJKLMNOT[]", true); switch (ch) { case 'Q': done = true; break; case '[': a()->dirs()[n] = r; if (--n < 0) { n = a()->dirs().size() - 1; } r = a()->dirs()[n]; break; case ']': a()->dirs()[n] = r; if (++n >= a()->dirs().size()) { n = 0; } r = a()->dirs()[n]; break; case 'A': { bout.nl(); bout << "|#2New name? "; auto s = bin.input_text(r.name, 40); if (!s.empty()) { r.name = s; } } break; case 'B': { bout.nl(); bout << "|#2New filename? "; auto s = bin.input_filename(r.filename, 8); if (!s.empty() && !contains(s, '.')) { r.filename = s; } } break; case 'C': { bout.nl(); bout << "|#9Enter new path, optionally with drive specifier.\r\n" << "|#9No backslash on end.\r\n\n" << "|#9The current path is:\r\n" << "|#1" << r.path << wwiv::endl << wwiv::endl; bout << " \b"; auto s = bin.input_path(r.path, 79); if (!s.empty()) { const string dir{s}; if (!File::Exists(dir)) { File::set_current_directory(a()->bbspath()); if (!File::mkdirs(dir)) { bout << "|#6Unable to create or change to directory." << wwiv::endl; bout.pausescr(); s.clear(); } } if (!s.empty()) { s = File::EnsureTrailingSlash(s); r.path = s; bout.nl(2); bout << "|#3The path for this directory is changed.\r\n"; bout << "|#9If there are any files in it, you must manually move them to the new " "directory.\r\n"; bout.pausescr(); } } } break; case 'D': { bout.nl(); bout << "|#2New ACS? \r\n:"; r.acs = wwiv::bbs::input_acs(bin, bout, r.acs, 77); } break; case 'F': { bout.nl(); bout << "|#2New max files? "; r.maxfiles = bin.input_number(r.maxfiles); } break; case 'H': r.mask ^= mask_PD; break; case 'J': r.mask ^= mask_no_uploads; break; case 'K': r.mask ^= mask_archive; break; case 'L': r.mask ^= mask_cdrom; if (r.mask & mask_cdrom) { r.mask |= mask_no_uploads; } else { r.mask &= ~mask_offline; } break; case 'M': if (r.mask & mask_cdrom) { r.mask ^= mask_offline; } break; case 'N': r.mask ^= mask_uploadall; break; case 'O': r.mask &= ~mask_wwivreg; bout.nl(); bout << "|#5Require WWIV 4.xx registration? "; if (bin.yesno()) { r.mask |= mask_wwivreg; } break; case 'T': { edit_ftn_area_tags(r.area_tags); } break; } } while (!done && !a()->sess().hangup()); a()->dirs()[n] = r; } void swap_dirs(int dir1, int dir2) { if (dir1 < 0 || dir1 >= a()->dirs().size() || dir2 < 0 || dir2 >= a()->dirs().size()) { return; } const int num_user_records = a()->users()->num_user_records(); auto* pTempQScan = static_cast<uint32_t*>(BbsAllocA(a()->config()->qscn_len())); if (pTempQScan) { for (auto i = 1; i <= num_user_records; i++) { read_qscn(i, pTempQScan, true); auto* pTempQScan_n = pTempQScan + 1; int i1 = 0; if (pTempQScan_n[dir1 / 32] & (1L << (dir1 % 32))) { i1 = 1; } int i2 = 0; if (pTempQScan_n[dir2 / 32] & (1L << (dir2 % 32))) { i2 = 1; } if (i1 + i2 == 1) { pTempQScan_n[dir1 / 32] ^= (1L << (dir1 % 32)); pTempQScan_n[dir2 / 32] ^= (1L << (dir2 % 32)); } write_qscn(i, pTempQScan, true); } close_qscn(); free(pTempQScan); } const auto drt = a()->dirs()[dir1]; a()->dirs()[dir1] = a()->dirs()[dir2]; a()->dirs()[dir2] = drt; } void insert_dir(int n) { if (n < 0 || n > a()->dirs().size()) { return; } files::directory_t r{}; r.name = "** NEW DIR **"; r.filename = "noname"; r.path = a()->config()->dloadsdir(); r.acs = "user.sl >= 10"; r.maxfiles = 50; r.mask = 0; a()->dirs().insert(n, r); const auto num_user_records = a()->users()->num_user_records(); auto* pTempQScan = static_cast<uint32_t*>(BbsAllocA(a()->config()->qscn_len())); if (pTempQScan) { auto* pTempQScan_n = pTempQScan + 1; const uint32_t m1 = 1L << (n % 32); const uint32_t m2 = 0xffffffff << ((n % 32) + 1); const uint32_t m3 = 0xffffffff >> (32 - (n % 32)); for (int i = 1; i <= num_user_records; i++) { read_qscn(i, pTempQScan, true); int i1; for (i1 = a()->dirs().size() / 32; i1 > n / 32; i1--) { pTempQScan_n[i1] = (pTempQScan_n[i1] << 1) | (pTempQScan_n[i1 - 1] >> 31); } pTempQScan_n[i1] = m1 | (m2 & (pTempQScan_n[i1] << 1)) | (m3 & pTempQScan_n[i1]); write_qscn(i, pTempQScan, true); } close_qscn(); free(pTempQScan); } } void delete_dir(int n) { if (n < 0 || n >= a()->dirs().size()) { return; } a()->dirs().erase(n); const auto num_users = a()->users()->num_user_records(); const auto pTempQScan = std::make_unique<uint32_t[]>(a()->config()->qscn_len()); if (pTempQScan) { auto* pTempQScan_n = pTempQScan.get() + 1; const uint32_t m2 = 0xffffffff << (n % 32); const uint32_t m3 = 0xffffffff >> (32 - (n % 32)); for (auto i = 1; i <= num_users; i++) { read_qscn(i, pTempQScan.get(), true); pTempQScan_n[n / 32] = (pTempQScan_n[n / 32] & m3) | ((pTempQScan_n[n / 32] >> 1) & m2) | (pTempQScan_n[(n / 32) + 1] << 31); for (auto i1 = (n / 32) + 1; i1 <= a()->dirs().size() / 32; i1++) { pTempQScan_n[i1] = (pTempQScan_n[i1] >> 1) | (pTempQScan_n[i1 + 1] << 31); } write_qscn(i, pTempQScan.get(), true); } close_qscn(); } } void dlboardedit() { char s[81]; if (!ValidateSysopPassword()) { return; } showdirs(); auto done = false; do { bout.nl(); bout << "|#9(|#2Q|#9)uit (|#2D|#9)elete, (|#2I|#9)nsert, (|#2M|#9)odify, (|#2S|#9)wapDirs, (|#2C|#9)onference : "; const auto ch = onek("QSDIMC?"); switch (ch) { case '?': showdirs(); break; case 'C': edit_conf_subs(a()->all_confs().dirs_conf()); break; case 'Q': done = true; break; case 'M': { bout.nl(); bout << "|#2(Q=Quit) Dir number? "; const auto r = bin.input_number_hotkey(0, {'Q'}, 0, a()->dirs().size()); if (r.key == 'Q') { break; } modify_dir(r.num); } break; case 'S': if (a()->dirs().size() < a()->config()->max_dirs()) { bout.nl(); bout << "|#2Take dir number? "; bin.input(s, 4); auto i1 = to_number<int>(s); if (!s[0] || i1 < 0 || i1 >= a()->dirs().size()) { break; } bout.nl(); bout << "|#2And put before dir number? "; bin.input(s, 4); const auto i2 = to_number<int>(s); if (!s[0] || i2 < 0 || i2 % 32 == 0 || i2 > a()->dirs().size() || i1 == i2) { break; } bout.nl(); if (i2 < i1) { i1++; } write_qscn(a()->sess().user_num(), a()->sess().qsc, true); bout << "|#1Moving dir now...Please wait..."; insert_dir(i2); swap_dirs(i1, i2); delete_dir(i1); showdirs(); } else { bout << "\r\n|#6You must increase the number of dirs in WWIVconfig first.\r\n"; } break; case 'I': { if (a()->dirs().size() < a()->config()->max_dirs()) { bout.nl(); bout << "|#2Insert before which dir? "; bin.input(s, 4); const auto i = to_number<int>(s); if (s[0] != 0 && i >= 0 && i <= a()->dirs().size()) { insert_dir(i); modify_dir(i); } } } break; case 'D': { bout.nl(); bout << "|#2Delete which dir? "; bin.input(s, 4); const auto i = to_number<int>(s); if (s[0] != 0 && i >= 0 && i < a()->dirs().size()) { bout.nl(); bout << "|#5Delete " << a()->dirs()[i].name << "? "; if (bin.yesno()) { delete_dir(i); bout.nl(); bout << "|#5Delete data files (.DIR/.EXT) for dir also? "; if (bin.yesno()) { const auto& fn = a()->dirs()[i].filename; File::Remove(FilePath(a()->config()->datadir(), StrCat(fn, ".dir"))); File::Remove(FilePath(a()->config()->datadir(), StrCat(fn, ".ext"))); } } } } break; } } while (!done && !a()->sess().hangup()); a()->dirs().Save(); if (!a()->at_wfc()) { changedsl(); } }
30.257194
118
0.479641
uriel1998
a66b46c629e4b99993025f7d654d4477f0eaddf1
1,485
cpp
C++
chp3_oscillation/NOC_3_10_PendulumExample/src/ofApp.cpp
ikbenmacje/NatureOfCode
98692398b0458765a6e77ae6f652392f99de050f
[ "MIT" ]
null
null
null
chp3_oscillation/NOC_3_10_PendulumExample/src/ofApp.cpp
ikbenmacje/NatureOfCode
98692398b0458765a6e77ae6f652392f99de050f
[ "MIT" ]
null
null
null
chp3_oscillation/NOC_3_10_PendulumExample/src/ofApp.cpp
ikbenmacje/NatureOfCode
98692398b0458765a6e77ae6f652392f99de050f
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetFrameRate(60); p = new Pendulum(ofVec2f(ofGetWidth()/2,0),175); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(255); p->go(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ p->clicked(ofGetMouseX(),ofGetMouseY()); } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ p->stopDragging(); } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
22.5
64
0.307071
ikbenmacje
a671545285703c2885d3d08de0ed53d466aa666c
2,203
cpp
C++
SGIPC practice contests/stl sgipc cntst/New folder/New folder/New folder/New folder/Codeforces Round #478 (Div. 2)A.cpp
YaminArafat/Vjudge
d8d2afc4b1a0fbada46d75cb080efc37965dfe9d
[ "Apache-2.0" ]
null
null
null
SGIPC practice contests/stl sgipc cntst/New folder/New folder/New folder/New folder/Codeforces Round #478 (Div. 2)A.cpp
YaminArafat/Vjudge
d8d2afc4b1a0fbada46d75cb080efc37965dfe9d
[ "Apache-2.0" ]
null
null
null
SGIPC practice contests/stl sgipc cntst/New folder/New folder/New folder/New folder/Codeforces Round #478 (Div. 2)A.cpp
YaminArafat/Vjudge
d8d2afc4b1a0fbada46d75cb080efc37965dfe9d
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool flag2[100000]; //map<string,bool>mp2; int main() { int n,ans=0; //cout<<'a'-0<<endl; scanf("%d",&n); string str; //vector<string>vec; map<string,int>mp; for(int i=0; i<n; i++) { cin>>str; sort(str.begin(),str.end()); mp[str]++; //vec.push_back(str); } //sort(mp.begin(),mp.end()); for(map<string,int>::iterator it=mp.begin(); it!=mp.end(); ++it) { string temp=it->first; int i=0,cnt=0; while(i<temp.size()-1) { if(temp[i]==temp[i+1]) { cnt++; } else { break; } i++; } if(cnt==temp.size()-1) { temp.erase(temp.begin()+1,temp.end()); } if(temp.size()==1) { if(!flag2[temp[0]-0]) { ans++; flag2[temp[0]-0]=1; } } else { i=0; cnt=0; bool flag[500]= {0}; while(temp[i]!='\0') { if(!flag[temp[i]-0]) { flag[temp[i]-0]=1; cnt++; } else { break; } i++; } if(cnt==temp.size()) { ans++; //mp2[temp]=1; //if(cnt==1) //flag2[temp[0]-0]=1; } } /*else if(cnt==1) { //string tmp=NULL; //char s=temp[0]; //tmp.append(s); if(!flag2[temp[0]-0]) ans++; }*/ //cout<<temp<<" "<<cnt<<endl; } if(!ans) ans++; printf("%d\n",ans); /*for(int i=0;i<n;i++) { sort(vec[i].begin(),vec[i].end()); }*/ return 0; } /*getline(cin,str); for(int i=0;i<str.size();i++) { while(str[i]!=' ') { if(!flag[str[i]-'0']) { flag[] } } }*/
20.588785
68
0.312301
YaminArafat
a67956139c4a2dad295eea2905a68856f7235af6
1,371
hpp
C++
ext/kintinuous/kfusion/include/kfusion/LVRPipeline.hpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
38
2019-06-19T15:10:35.000Z
2022-02-16T03:08:24.000Z
ext/kintinuous/kfusion/include/kfusion/LVRPipeline.hpp
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
9
2019-06-19T16:19:51.000Z
2021-09-17T08:31:25.000Z
ext/kintinuous/kfusion/include/kfusion/LVRPipeline.hpp
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
13
2019-04-16T11:50:32.000Z
2020-11-26T07:47:44.000Z
#ifndef LVR2_PIPELINE_HPP_ #define LVR2_PIPELINE_HPP_ #include <lvr/reconstruction/FastReconstruction.hpp> #include <lvr/reconstruction/TSDFGrid.hpp> #include <lvr/reconstruction/PointsetSurface.hpp> #include <lvr/reconstruction/FastBox.hpp> #include <lvr/io/PointBuffer.hpp> #include <lvr/io/DataStruct.hpp> #include <lvr/io/Timestamp.hpp> #include <lvr/geometry/HalfEdgeVertex.hpp> #include <lvr/geometry/HalfEdgeKinFuMesh.hpp> #include <lvr/geometry/BoundingBox.hpp> #include <kfusion/types.hpp> #include <kfusion/cuda/tsdf_volume.hpp> #include <kfusion/cuda/projective_icp.hpp> #include <kfusion/LinearPipeline.hpp> #include <kfusion/GridStage.hpp> #include <kfusion/MeshStage.hpp> #include <kfusion/OptimizeStage.hpp> #include <kfusion/FusionStage.hpp> using namespace lvr; typedef ColorVertex<float, unsigned char> cVertex; typedef HalfEdgeKinFuMesh<cVertex, lvr::Normal<float> > HMesh; typedef HMesh* MeshPtr; namespace kfusion { class LVRPipeline { public: LVRPipeline(KinFuParams params); ~LVRPipeline(); void addTSDFSlice(TSDFSlice slice, const bool last_shift); void resetMesh(); MeshPtr getMesh() {return pl_.GetResult();} double calcTimeStats(); private: MeshPtr meshPtr_; size_t slice_count_; std::vector<double> timeStats_; LinearPipeline<pair<TSDFSlice, bool> , MeshPtr> pl_; }; } #endif
23.637931
62
0.760759
uos
a679fae8c6775e32ac4f0f9439e1c9b4f12b3847
5,250
cpp
C++
projects/vs2019/mfc/iutest_mfc_sample.cpp
dsyoi/iutest
b7b08c6ac4c75f98f87aa5756244afc93e4b624f
[ "BSD-3-Clause" ]
58
2015-07-20T04:30:18.000Z
2021-12-28T17:18:00.000Z
projects/vs2019/mfc/iutest_mfc_sample.cpp
dsyoi/iutest
b7b08c6ac4c75f98f87aa5756244afc93e4b624f
[ "BSD-3-Clause" ]
467
2015-05-07T10:42:47.000Z
2022-03-26T04:01:00.000Z
projects/vs2019/mfc/iutest_mfc_sample.cpp
dsyoi/iutest
b7b08c6ac4c75f98f87aa5756244afc93e4b624f
[ "BSD-3-Clause" ]
13
2015-10-05T08:30:27.000Z
2021-04-30T18:56:03.000Z
// iutest_mfc_sample.cpp : コンソール アプリケーションのエントリ ポイントを定義します。 // #include "stdafx.h" #include "iutest_mfc_sample.h" #include "iutest.hpp" #include <map> #ifdef _DEBUG #define new DEBUG_NEW #endif // 唯一のアプリケーション オブジェクトです。 CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { IUTEST_UNUSED_VAR(envp); int nRetCode = 0; HMODULE hModule = ::GetModuleHandle(NULL); if (hModule != NULL) { // MFC を初期化して、エラーの場合は結果を印刷します。 if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) { // TODO: 必要に応じてエラー コードを変更してください。 _tprintf(_T("致命的なエラー: MFC の初期化ができませんでした。\n")); nRetCode = 1; } else { // TODO: アプリケーションの動作を記述するコードをここに挿入してください。 IUTEST_INIT(&argc, argv); nRetCode = IUTEST_RUN_ALL_TESTS(); } } else { // TODO: 必要に応じてエラー コードを変更してください。 _tprintf(_T("致命的なエラー: GetModuleHandle が失敗しました\n")); nRetCode = 1; } return nRetCode; } IUTEST(MFC, String) { CString str = _T("Test"); IUTEST_ASSERT_EQ(_T("Test"), str); IUTEST_ASSERT_STREQ(_T("Test"), str); IUTEST_ASSERT_STREQ(str, str); IUTEST_ASSERT_STRIN(str, _T("Test")); } IUTEST(MFC, Rect) { CRect r = { 0, 0, 100, 100 }; IUTEST_ASSERT_EQ(r, r); } template<typename T> struct test_value { static T get(int index) { return static_cast<T>(index); } }; template<typename T> struct test_value< T* > { static T* get(int) { return NULL; } }; template<> struct test_value < CString > { static CString get(int index) { CString s; s.Format(_T("%d"), index); return s; } }; template<typename T> class MFCArrayTypedTest : public ::iutest::Test {}; IUTEST_TYPED_TEST_SUITE(MFCArrayTypedTest, ::iutest::Types<CArray<int>, CTypedPtrArray<CPtrArray, int*> , CByteArray, CWordArray, CDWordArray, CUIntArray, CStringArray, CPtrArray, CObArray>); IUTEST_TYPED_TEST(MFCArrayTypedTest, EqCollections) { typename iutest::mfc::CContainer<TypeParam>::BASE_TYPE a[10]; TypeParam ar; ar.SetSize(IUTEST_PP_COUNTOF(a)); for(int i = 0; i < IUTEST_PP_COUNTOF(a); ++i) { a[i] = test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i); ar[i] = test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i); } IUTEST_ASSERT_EQ_COLLECTIONS( ::iutest::mfc::begin(ar) , ::iutest::mfc::end(ar) , ::std::begin(a) , ::std::end(a) ); } template<typename T> class MFCListTypedTest : public ::iutest::Test {}; IUTEST_TYPED_TEST_SUITE(MFCListTypedTest, ::iutest::Types<CList<int>, CTypedPtrList<CPtrList, int*> , CStringList, CPtrList, CObList>); IUTEST_TYPED_TEST(MFCListTypedTest, EqCollections) { typename iutest::mfc::CContainer<TypeParam>::BASE_TYPE a[10]; TypeParam list; for(int i = 0; i < IUTEST_PP_COUNTOF(a); ++i) { a[i] = test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i); list.AddTail(test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i)); } IUTEST_ASSERT_EQ_COLLECTIONS( ::iutest::mfc::begin(list) , ::iutest::mfc::end(list) , ::std::begin(a) , ::std::end(a) ); } template<typename T> class MFCMapTypedTest : public ::iutest::Test {}; IUTEST_TYPED_TEST_SUITE(MFCMapTypedTest, ::iutest::Types< CMap<int, int, int, int> , CTypedPtrMap<CMapPtrToPtr, int*, int*>, CTypedPtrMap<CMapPtrToWord, int*, WORD> , CTypedPtrMap<CMapWordToPtr, WORD, int*>, CTypedPtrMap<CMapStringToPtr, CString, int*> , CMapWordToPtr, CMapWordToOb, CMapPtrToPtr, CMapPtrToWord , CMapStringToPtr, CMapStringToOb, CMapStringToString >); IUTEST_TYPED_TEST(MFCMapTypedTest, EqCollections) { TypeParam map; for(int i = 0; i < 10; ++i) { map.SetAt(test_value<iutest::mfc::CContainer<TypeParam>::BASE_KEY>::get(i) , test_value<iutest::mfc::CContainer<TypeParam>::BASE_VALUE>::get(i) ); } IUTEST_ASSERT_EQ_COLLECTIONS( ::iutest::mfc::begin(map) , ::iutest::mfc::end(map) , ::iutest::mfc::begin(map) , ::iutest::mfc::end(map) ); } #if IUTEST_HAS_MATCHERS using namespace ::iutest::matchers; IUTEST_TYPED_TEST(MFCArrayTypedTest, Matcher) { TypeParam ar; ar.SetSize(10); for(int i = 0; i < 10; ++i) { ar[i] = test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i); } IUTEST_EXPECT_THAT(::iutest::mfc::make_container(ar), Each(_)); } IUTEST_TYPED_TEST(MFCListTypedTest, Matcher) { TypeParam list; for(int i = 0; i < 10; ++i) { list.AddTail(test_value<iutest::mfc::CContainer<TypeParam>::BASE_TYPE>::get(i)); } IUTEST_EXPECT_THAT(::iutest::mfc::make_container(list), Each(_)); } IUTEST_TYPED_TEST(MFCMapTypedTest, Matcher) { TypeParam map; for(int i = 0; i < 10; ++i) { map.SetAt(test_value<iutest::mfc::CContainer<TypeParam>::BASE_KEY>::get(i) , test_value<iutest::mfc::CContainer<TypeParam>::BASE_VALUE>::get(i)); } IUTEST_EXPECT_THAT(::iutest::mfc::make_container(map), Each(Key(_))); IUTEST_EXPECT_THAT(::iutest::mfc::make_container(map), Each(Pair(_, _))); } #endif
27.202073
103
0.640381
dsyoi
a67fdd8870c208c19c891fc122c70fc83865786b
1,583
cpp
C++
Plugins/Tweaks/ItemChargesCost.cpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
111
2018-01-16T18:49:19.000Z
2022-03-13T12:33:54.000Z
Plugins/Tweaks/ItemChargesCost.cpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
636
2018-01-17T10:05:31.000Z
2022-03-28T20:06:03.000Z
Plugins/Tweaks/ItemChargesCost.cpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
110
2018-01-16T19:05:54.000Z
2022-03-28T03:44:16.000Z
#include "nwnx.hpp" #include "API/CNWItemProperty.hpp" #include "API/CNWRules.hpp" #include "API/CNWSItem.hpp" namespace Tweaks { using namespace NWNXLib; using namespace NWNXLib::API; static int s_ChargesCostBehavior; void ItemChargesCost() __attribute__((constructor)); void ItemChargesCost() { s_ChargesCostBehavior = Config::Get<int>("ITEM_CHARGES_COST_MODE", 0); if (s_ChargesCostBehavior == 0) return; else if (s_ChargesCostBehavior < 0 || s_ChargesCostBehavior > 3) { LOG_INFO("Unknown value for NWNX_TWEAKS_ITEM_CHARGES_COST_MODE."); return; } LOG_INFO("Changing cost for items with charges."); static Hooks::Hook s_CalculateBaseCostsHook = Hooks::HookFunction(Functions::_ZN8CNWSItem18CalculateBaseCostsEv, (void*)+[](CNWSItem* pThis) -> void { int32_t savedCharges = pThis->m_nNumCharges; switch (s_ChargesCostBehavior) { case 1: pThis->m_nNumCharges = std::min(pThis->m_nNumCharges * 5, 250); break; case 2: pThis->m_nNumCharges = std::min(pThis->m_nNumCharges, 50) * 5 + std::max(pThis->m_nNumCharges - 50, 0) * 1.25; break; case 3: pThis->m_nNumCharges *= 5; break; default: break; } s_CalculateBaseCostsHook->CallOriginal<void>(pThis); pThis->m_nNumCharges = savedCharges; }, Hooks::Order::Early); } }
26.830508
130
0.587492
summonFox
a6804e9c6a6a50f611b51c279b00e6de74ad18ea
1,136
cpp
C++
codes/CodeForces/Round #224/cf394C.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/CodeForces/Round #224/cf394C.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/CodeForces/Round #224/cf394C.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <string.h> const int N = 1e3+10; const int M = 4; const char sign[M][M] = { "00", "01", "10", "11"}; int n, m, c[M], g[N][N]; void init() { char str[M]; memset(g, 0, sizeof(g)); memset(c, 0, sizeof(c)); scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%s", str); if (str[0] == '1' && str[1] == '1') c[2]++; else if (str[0] == '0' && str[1] == '0') c[0]++; else c[1]++; } } } void set() { for (int i = 0; i < n; i++) { if (i&1) { for (int j = m-1; j >= 0; j--) { if (c[2]) { g[i][j] = 3; c[2]--; } else if (c[1]) { g[i][j] = 1; c[1]--; } if (c[1] == 0 && c[2] == 0) return; } } else { for (int j = 0; j < m; j++) { if (c[2]) { g[i][j] = 3; c[2]--; } else if (c[1]) { g[i][j] = 2; c[1]--; } if (c[1] == 0 && c[2] == 0) return ; } } } } void solve() { set(); for (int i = 0; i < n; i++) { printf("%s", sign[g[i][0]]); for (int j = 1; j < m; j++) printf(" %s", sign[g[i][j]]); printf("\n"); } } int main () { init(); solve(); return 0; }
16.705882
59
0.37412
JeraKrs
a68226e4a30b9061509eba4a2e909e98f5380abf
1,920
cpp
C++
src/snail/detail/sdl_impl.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/snail/detail/sdl_impl.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/snail/detail/sdl_impl.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
#ifdef ANDROID #include "sdl.hpp" #endif namespace elona { namespace snail { namespace detail { void enforce_sdl(int result) { if (result != 0) { throw SDLError{::SDL_GetError()}; } } void enforce_ttf(int result) { if (result != 0) { throw SDLError{::TTF_GetError()}; } } void enforce_image(int result) { if (result != 0) { throw SDLError{::IMG_GetError()}; } } void enforce_mixer(int result) { if (result != 0) { throw SDLError{::Mix_GetError()}; } } void* enforce_sdl_internal(void* result) { return result ? result : throw SDLError(::SDL_GetError()); } void* enforce_ttf_internal(void* result) { return result ? result : throw SDLError(::TTF_GetError()); } void* enforce_img_internal(void* result) { return result ? result : throw SDLError(::IMG_GetError()); } void* enforce_mixer_internal(void* result) { return result ? result : throw SDLError(::Mix_GetError()); } SDLCore::SDLCore() { enforce_sdl(::SDL_Init(SDL_INIT_EVERYTHING)); } SDLCore::~SDLCore() { ::SDL_Quit(); } SDLTTF::SDLTTF() { enforce_ttf(::TTF_Init()); } SDLTTF::~SDLTTF() { ::TTF_Quit(); } SDLImage::SDLImage() { auto flags = IMG_INIT_PNG | IMG_INIT_JPG; auto result = ::IMG_Init(flags); if ((flags & result) != flags) { throw SDLError{"Failed to initialize SDL2Image"}; } } SDLImage::~SDLImage() { ::IMG_Quit(); } SDLMixer::SDLMixer() { // auto flags = MIX_INIT_OGG | MIX_INIT_MP3; auto flags = 0; auto result = ::Mix_Init(flags); if ((flags & result) != flags) { throw SDLError{"Failed to initialize SDL2Mixer"}; } enforce_mixer(::Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048)); } SDLMixer::~SDLMixer() { ::Mix_CloseAudio(); ::Mix_Quit(); } } // namespace detail } // namespace snail } // namespace elona
12.631579
71
0.610938
XrosFade
a6874da4708fe9f3e9010e7cc5f26a55dc68045e
28,009
cc
C++
test/retic/fddTest.cc
enotnadoske/drunos
79b72078e613c9c5d4e5c37721b726ca3374299b
[ "Apache-2.0" ]
9
2019-04-04T18:03:36.000Z
2019-05-03T23:48:59.000Z
test/retic/fddTest.cc
enotnadoske/drunos
79b72078e613c9c5d4e5c37721b726ca3374299b
[ "Apache-2.0" ]
16
2019-04-04T12:22:19.000Z
2019-04-09T19:04:42.000Z
test/retic/fddTest.cc
enotnadoske/drunos
79b72078e613c9c5d4e5c37721b726ca3374299b
[ "Apache-2.0" ]
2
2019-10-11T14:17:26.000Z
2022-03-15T10:06:08.000Z
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "common.hh" #include "retic/fdd.hh" #include "retic/fdd_compiler.hh" #include "retic/policies.hh" #include "retic/traverse_fdd.hh" #include "oxm/openflow_basic.hh" using namespace runos; using namespace retic; using namespace ::testing; using sec = std::chrono::seconds; TEST(TypeComprassion, Types) { const auto ofb_switch_id = oxm::switch_id(); const auto ofb_eth_src = oxm::eth_src(); const auto ofb_eth_type = oxm::eth_type(); EXPECT_EQ(0, fdd::compare_types(ofb_switch_id, ofb_switch_id)); EXPECT_EQ(0, fdd::compare_types(ofb_eth_src, ofb_eth_src)); EXPECT_EQ(0, fdd::compare_types(ofb_eth_type, ofb_eth_type)); EXPECT_GT(0, fdd::compare_types(ofb_eth_type, ofb_switch_id)); EXPECT_GT(0, fdd::compare_types(ofb_eth_type, ofb_eth_src)); } TEST(EqualFdd, EqualTest) { fdd::diagram node1 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{}}; fdd::diagram node2 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{}}; fdd::diagram node3 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<1>() == 1}}}}; fdd::diagram node4 = fdd::node{F<1>() == 2, fdd::leaf{}, fdd::leaf{}}; fdd::diagram node5 = fdd::node{F<2>() == 1, fdd::leaf{}, fdd::leaf{}}; fdd::diagram node6 = fdd::node{F<1>() == 1, fdd::leaf{{oxm::field_set{F<1>() == 1}}}, fdd::leaf{}}; fdd::diagram node7 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<2>() == 2}, oxm::field_set{F<1>() == 1}}}}; fdd::diagram node8 = fdd::node{F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<1>() == 1}, oxm::field_set{F<2>() == 2}}}}; EXPECT_EQ(node1, node2); EXPECT_NE(node1, node3); EXPECT_NE(node1, node4); EXPECT_NE(node1, node5); EXPECT_NE(node1, node5); EXPECT_EQ(node7, node8); } TEST(EqualFdd, EqualWithFlowSettings) { fdd::diagram d1 = fdd::leaf{{oxm::field_set{}}, FlowSettings{sec(10), sec(20)}}; fdd::diagram d2 = fdd::leaf{{oxm::field_set{}}, FlowSettings{sec(10), sec(20)}}; fdd::diagram d3 = fdd::leaf{{oxm::field_set{}}, FlowSettings{sec(1234), sec(20)}}; fdd::diagram d4 = fdd::leaf{{oxm::field_set{}}, FlowSettings{sec(10), sec(1234)}}; EXPECT_EQ(d1, d2); EXPECT_NE(d1, d3); EXPECT_NE(d1, d4); } TEST(FddCompilerTest, StopCompile) { policy p = stop(); fdd::diagram diagram = fdd::compile(p); fdd::leaf leaf = boost::get<fdd::leaf>(diagram); ASSERT_TRUE(leaf.sets.empty()); } TEST(FddCompilerTest, IdCompile) { policy p = id(); fdd::diagram diagram = fdd::compile(p); fdd::diagram true_value = fdd::leaf{{ oxm::field_set{} }}; ASSERT_EQ(diagram, true_value); } TEST(FddCompilerTest, Modify) { policy p = modify(F<1>() << 100); fdd::diagram diagram = fdd::compile(p); fdd::leaf leaf = boost::get<fdd::leaf>(diagram); ASSERT_THAT(leaf.sets, SizeIs(1)); ASSERT_EQ(oxm::field_set{F<1>() == 100}, leaf.sets[0]); } TEST(FddCompilerTest, Filter) { policy p = filter(F<1>() == 100); fdd::diagram diagram = fdd::compile(p); fdd::node node = boost::get<fdd::node>(diagram); fdd::diagram true_value = fdd::node { F<1>() == 100, fdd::leaf {{ oxm::field_set{} }}, fdd::leaf { } }; ASSERT_EQ(true_value, diagram); } TEST(FddCompilerTest, ParallelLeafLeaf) { policy p = modify(F<1>() << 100) + modify(F<2>() << 200); fdd::diagram diagram = fdd::compile(p); fdd::leaf leaf = boost::get<fdd::leaf>(diagram); ASSERT_THAT(leaf.sets, SizeIs(2)); EXPECT_THAT(leaf.sets, UnorderedElementsAre( oxm::field_set{F<1>() == 100}, oxm::field_set{F<2>() == 200} )); } TEST(FddCompilerTest, ParallellNodeLeaf) { policy p = filter(F<1>() == 1) + modify(F<3>() << 3); fdd::diagram diagram = fdd::compile(p); fdd::node node = boost::get<fdd::node>(diagram); oxm::field<> true_value = F<1>() == 1; EXPECT_EQ(true_value, node.field); fdd::leaf pos = boost::get<fdd::leaf>(node.positive); EXPECT_THAT(pos.sets, UnorderedElementsAre( oxm::field_set{F<3>() == 3}, oxm::field_set() // filter empty value )); fdd::leaf neg = boost::get<fdd::leaf>(node.negative); EXPECT_THAT(neg.sets, UnorderedElementsAre(oxm::field_set{F<3>() == 3})); } TEST(FddCompilerTest, ParallellLeafNode) { policy p = modify(F<3>() << 3) + filter(F<1>() == 1); fdd::diagram diagram = fdd::compile(p); fdd::node node = boost::get<fdd::node>(diagram); oxm::field<> true_value = F<1>() == 1; EXPECT_EQ(true_value, node.field); fdd::leaf pos = boost::get<fdd::leaf>(node.positive); EXPECT_THAT(pos.sets, UnorderedElementsAre( oxm::field_set{F<3>() == 3}, oxm::field_set() // filter empty value )); fdd::leaf neg = boost::get<fdd::leaf>(node.negative); EXPECT_THAT(neg.sets, UnorderedElementsAre(oxm::field_set{F<3>() == 3})); } TEST(FddCompilerTest, ParallelNodeNodeEquals) { fdd::diagram node1 = fdd::node{ {F<1>() == 1}, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; fdd::diagram node2 = fdd::node{ {F<1>() == 1}, fdd::leaf{{oxm::field_set{F<5>() == 5}}}, fdd::leaf{{oxm::field_set{F<6>() == 6}}} }; fdd::parallel_composition pc; fdd::diagram diagram = boost::apply_visitor(pc, node1, node2); fdd::node node = boost::get<fdd::node>(diagram); EXPECT_EQ(oxm::field<>(F<1>() == 1), node.field); fdd::leaf pos = boost::get<fdd::leaf>(node.positive); EXPECT_THAT(pos.sets, UnorderedElementsAre( oxm::field_set{F<2>() == 2}, oxm::field_set{F<5>() == 5} )); fdd::leaf neg = boost::get<fdd::leaf>(node.negative); EXPECT_THAT(neg.sets, UnorderedElementsAre( oxm::field_set{F<3>() == 3}, oxm::field_set{F<6>() == 6} )); } TEST(FddCompilerTest, ParallelNodeNodeEqualFields) { fdd::diagram node1 = fdd::node{ {F<1>() == 1}, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; fdd::diagram node2 = fdd::node{ {F<1>() == 2}, fdd::leaf{{oxm::field_set{F<5>() == 5}}}, fdd::leaf{{oxm::field_set{F<6>() == 6}}} }; fdd::parallel_composition pc; fdd::diagram result_value1 = boost::apply_visitor(pc, node1, node2); fdd::diagram result_value2 = boost::apply_visitor(pc, node2, node1); fdd::diagram true_value = fdd::node { {F<1>() == 1}, fdd::leaf {{ oxm::field_set{F<2>() == 2}, oxm::field_set{F<6>() == 6} }}, fdd::node{ {F<1>() == 2}, fdd::leaf{{ oxm::field_set{F<3>() == 3}, oxm::field_set{F<5>() == 5} }}, fdd::leaf{{ oxm::field_set{F<6>() == 6}, oxm::field_set{F<3>() == 3} }} } }; EXPECT_EQ(true_value, result_value1); EXPECT_EQ(true_value, result_value2); } TEST(FddCompilerTest, ParallelNodeNodeDiffFields) { fdd::diagram node1 = fdd::node{ {F<1>() == 1}, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; fdd::diagram node2 = fdd::node{ {F<2>() == 2}, fdd::leaf{{oxm::field_set{F<5>() == 5}}}, fdd::leaf{{oxm::field_set{F<6>() == 6}}} }; fdd::parallel_composition pc; fdd::diagram result_value1 = boost::apply_visitor(pc, node1, node2); fdd::diagram result_value2 = boost::apply_visitor(pc, node2, node1); fdd::diagram true_value = fdd::node { {F<1>() == 1}, fdd::node { {F<2>() == 2}, fdd::leaf{{ oxm::field_set{F<2>() == 2}, oxm::field_set{F<5>() == 5} }}, fdd::leaf{{ oxm::field_set{F<2>() == 2}, oxm::field_set{F<6>() == 6} }} }, fdd::node{ {F<2>() == 2}, fdd::leaf{{ oxm::field_set{F<3>() == 3}, oxm::field_set{F<5>() == 5} }}, fdd::leaf{{ oxm::field_set{F<3>() == 3}, oxm::field_set{F<6>() == 6} }} } }; EXPECT_EQ(true_value, result_value1); EXPECT_EQ(true_value, result_value2); } TEST(FddCompilerTest, RestrictionLeafTrue) { fdd::diagram d = fdd::leaf{{oxm::field_set{F<2>() == 2}}}; auto r = fdd::restriction{ F<1>() == 1, d, true }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{} }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeEqualTrue) { fdd::diagram d = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<1>() == 1, d, true }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{} }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeEqualTypesTrue) { fdd::diagram d = fdd::node { F<1>() == 2, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<1>() == 1, d, true }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<3>() == 3}}}, fdd::leaf{} }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeDiffTypes1Less2True) { fdd::diagram d = fdd::node { F<2>() == 2, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<1>() == 1, d, true }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::node { F<2>() == 2, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }, fdd::leaf{} }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeOtherwiseTrue) { fdd::diagram d = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<2>() == 2, d, true }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::node { F<2>() == 2, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{} }, fdd::node { F<2>() == 2, fdd::leaf{{oxm::field_set{F<3>() == 3}}}, fdd::leaf{} }, }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionLeafFalse) { fdd::diagram d = fdd::leaf{{oxm::field_set{F<2>() == 2}}}; auto r = fdd::restriction{ F<1>() == 1, d, false }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<2>() == 2}}} }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeEqualFalse) { fdd::diagram d = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<1>() == 1, d, false }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeEqualTypesFalseOrdering1) { fdd::diagram d = fdd::node { F<1>() == 2, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<1>() == 1, d, false }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{}, fdd::node { F<1>() == 2, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} } }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeEqualTypesFalseOrdering2) { fdd::diagram d = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<1>() == 2, d, false }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::node { F<1>() == 2, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} } }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeDiffTypesFalseOrdering1) { fdd::diagram d = fdd::node { F<2>() == 2, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<1>() == 1, d, false }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{}, fdd::node { F<2>() == 2, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} } }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, RestrictionNodeDiffTypesFalseOrdering2) { fdd::diagram d = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; auto r = fdd::restriction{ F<2>() == 2, d, false }; fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::node { F<2>() == 2, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<2>() == 2}}} }, fdd::node { F<2>() == 2, fdd::leaf{}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} } }; EXPECT_EQ(true_value, r.apply()); } TEST(FddCompilerTest, SequentialLeafLeaf) { fdd::diagram d1 = fdd::leaf {{ oxm::field_set{F<1>() == 1} }}; fdd::diagram d2 = fdd::leaf {{ oxm::field_set{F<2>() == 2} }}; fdd::sequential_composition composition; fdd::diagram result = boost::apply_visitor(composition, d1, d2); fdd::diagram true_value = fdd::leaf {{ oxm::field_set{ {F<1>() == 1}, {F<2>() == 2} } }}; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, SequentialLeafLeafOneField) { fdd::diagram d1 = fdd::leaf {{ oxm::field_set{F<1>() == 1} }}; fdd::diagram d2 = fdd::leaf {{ oxm::field_set{F<1>() == 2} }}; fdd::sequential_composition composition; fdd::diagram result = boost::apply_visitor(composition, d1, d2); fdd::diagram true_value = fdd::leaf {{ oxm::field_set{ {F<1>() == 2} } }}; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, SequentialLeafLeafMulti) { fdd::diagram d1 = fdd::leaf {{ oxm::field_set{F<1>() == 1}, oxm::field_set{F<3>() == 3}, oxm::field_set{F<4>() == 4} }}; fdd::diagram d2 = fdd::leaf {{ oxm::field_set{F<2>() == 2}, oxm::field_set{F<3>() == 300}, }}; fdd::sequential_composition composition; fdd::diagram result = boost::apply_visitor(composition, d1, d2); fdd::diagram true_value = fdd::leaf {{ oxm::field_set{ {F<1>() == 1}, {F<2>() == 2} }, oxm::field_set{ {F<1>() == 1}, {F<3>() == 300} }, oxm::field_set{ {F<3>() == 3}, {F<2>() == 2} }, oxm::field_set{ {F<3>() == 300} }, oxm::field_set{ {F<4>() == 4}, {F<2>() == 2} }, oxm::field_set{ {F<4>() == 4}, {F<3>() == 300} } }}; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, SequentialLeafNodeWriteThisValue) { fdd::diagram d1 = fdd::leaf{{ oxm::field_set{F<1>() == 1} }}; fdd::diagram d2 = fdd::node{ F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2); fdd::diagram true_value = fdd::leaf {{ oxm::field_set{ {F<1>() == 1}, {F<2>() == 2} } }}; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, SequentialLeafNodeWriteAnotherValue) { fdd::diagram d1 = fdd::leaf{{ oxm::field_set{F<1>() == 100} }}; fdd::diagram d2 = fdd::node{ F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2); fdd::diagram true_value = fdd::leaf {{ oxm::field_set{ {F<1>() == 100}, {F<3>() == 3} } }}; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, SequentialLeafNodeWriteAnotherType) { fdd::diagram d1 = fdd::leaf{{ oxm::field_set{F<100>() == 100} }}; fdd::diagram d2 = fdd::node{ F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2); fdd::diagram true_value = fdd::node{ F<1>() == 1, fdd::leaf{{ oxm::field_set{ {F<2>() == 2}, {F<100>() == 100} } }}, fdd::leaf{{ oxm::field_set{ {F<3>() == 3}, {F<100>() == 100} } }} }; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, SequentialNodeLeaf) { fdd::diagram d1 = fdd::node{ F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 2}}}, fdd::leaf{{oxm::field_set{F<3>() == 3}}} }; fdd::diagram d2 = fdd::leaf{{ oxm::field_set{F<100>() == 100} }}; fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2); fdd::diagram true_value = fdd::node{ F<1>() == 1, fdd::leaf{{ oxm::field_set{ {F<2>() == 2}, {F<100>() == 100} } }}, fdd::leaf{{ oxm::field_set{ {F<3>() == 3}, {F<100>() == 100} } }} }; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, CompileSequential) { policy p = modify(F<1>() == 1) >> modify(F<2>() == 2); fdd::diagram result = fdd::compile(p); fdd::diagram true_value = fdd::leaf{{ oxm::field_set{ {F<1>() == 1}, {F<2>() == 2} } }}; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, CompileParallel) { policy p = modify(F<1>() == 1) + modify(F<2>() == 2); fdd::diagram result = fdd::compile(p); fdd::diagram true_value = fdd::leaf{{ oxm::field_set{F<1>() == 1}, oxm::field_set{F<2>() == 2} }}; EXPECT_EQ(true_value, result); } TEST(FddCompilerTest, CompilePacketFunction) { policy p = handler([](Packet& pkt){ return stop(); }); PacketFunction pf = boost::get<PacketFunction>(p); fdd::diagram result = fdd::compile(p); fdd::diagram true_value = fdd::leaf{{ {oxm::field_set{}, pf} }}; ASSERT_THAT(true_value, result); } TEST(FddCompilerTest, SeqAction1If) { policy p1 = handler([](Packet& pkt){ return stop(); }); policy p2 = handler([](Packet& pkt){ return fwd(1); }); auto pf1 = boost::get<PacketFunction>(p1); auto pf2 = boost::get<PacketFunction>(p2); fdd::diagram d1 = fdd::leaf{{ {oxm::field_set{F<1>() == 1}, pf1} }}; fdd::diagram d2 = fdd::leaf{{ {oxm::field_set{F<2>() == 2}, pf2} }}; fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2); fdd::action_unit au = fdd::action_unit{oxm::field_set{F<2>() == 2}, pf2}; fdd::diagram true_value = fdd::leaf{{ {oxm::field_set{F<1>() == 1}, pf1, au}}}; ASSERT_EQ(true_value, result); } TEST(FddCompilerTest, SeqAction2If) { policy p2 = handler([](Packet& pkt){ return fwd(1); }); auto pf2 = boost::get<PacketFunction>(p2); fdd::diagram d1 = fdd::leaf{{ {oxm::field_set{F<1>() == 1}} }}; fdd::diagram d2 = fdd::leaf{{ {oxm::field_set{F<2>() == 2}, pf2} }}; fdd::diagram result = boost::apply_visitor(fdd::sequential_composition{}, d1, d2); fdd::diagram true_value = fdd::leaf{{ {oxm::field_set{F<1>() == 1, F<2>() == 2}, pf2}}}; ASSERT_EQ(true_value, result); } TEST(FddCompilerTest, FlowSettings) { policy p = idle_timeout(sec(10)); auto settings = boost::get<FlowSettings>(p); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::leaf{{oxm::field_set{}}, settings}; EXPECT_EQ(true_value, d); } TEST(FddCompilerTest, FlowSettingsSeq) { policy p = idle_timeout(sec(10)) >> idle_timeout(sec(5)); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout = sec(5)}}; EXPECT_EQ(true_value, d); } TEST(FddCompilerTest, FlowSettingsSeq2) { policy p = idle_timeout(sec(5)) >> idle_timeout(sec(10)); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout = sec(5)}}; EXPECT_EQ(true_value, d); } TEST(FddCompilerTest, FlowSettingsParallel) { policy p = idle_timeout(sec(10)) + idle_timeout(sec(5)); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout = sec(5)}}; EXPECT_EQ(true_value, d); } TEST(FddCompilerTest, FlowSettingsWithTwoActions) { policy p = (modify(F<1>() == 1) >> idle_timeout(sec(20))) + (modify(F<2>() == 2) >> idle_timeout(sec(30))); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::leaf { { oxm::field_set{F<1>() == 1}, oxm::field_set{F<2>() == 2} }, FlowSettings{.idle_timeout = sec(20)} }; EXPECT_EQ(true_value, d); } TEST(FddCompilerTest, FilterFlowSettings) { policy p = filter(F<1>() == 1) >> idle_timeout(sec(20)); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout=sec(20)}}, fdd::leaf{} }; EXPECT_EQ(true_value, d); } TEST(FddCompilerTest, NegationTest) { policy p = filter_not(F<1>() == 1); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{}}} }; EXPECT_EQ(true_value, d); } TEST(FddCompilerTest, NegationTestWithSettings) { policy p = filter_not(F<1>() == 1) >> idle_timeout(sec(20)); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{}, fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout=sec(20)}} }; EXPECT_EQ(true_value, d); } TEST(DISABLED_FddCompilerTest, NegationX2TestWithSettings) { // I think this test should failed. // But I have no idea why NegationTestWithSettings is works // policy p = filter_not(F<1>() == 1) >> (filter_not(F<1>() == 1) >> idle_timeout(sec(20))); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{}}, FlowSettings{.idle_timeout=sec(20)}}, fdd::leaf{} }; EXPECT_EQ(true_value, d); } TEST(FddCompilerTest, ComplexNegationTest) { policy p = (filter(F<1>() == 1) >> modify(F<2>() == 1)) + (filter_not(F<1>() == 1) >> modify(F<2>() == 2)); fdd::diagram d = fdd::compile(p); fdd::diagram true_value = fdd::node { F<1>() == 1, fdd::leaf{{oxm::field_set{F<2>() == 1}}}, fdd::leaf{{oxm::field_set{F<2>() == 2}}} }; EXPECT_EQ(true_value, d); } TEST(FddTraverseTest, FddTraverse) { fdd::diagram d = fdd::node{ F<1>() == 1, fdd::leaf{{ oxm::field_set{F<2>() == 2}}}, fdd::leaf{{ oxm::field_set{F<3>() == 3}}} }; oxm::field_set fs1{F<1>() == 1}; oxm::field_set fs2{F<1>() == 2}; fdd::Traverser traverser1{fs1}, traverser2{fs2}; fdd::leaf l1 = boost::apply_visitor(traverser1, d); fdd::leaf l2 = boost::apply_visitor(traverser2, d); EXPECT_EQ(l1, fdd::leaf{{ oxm::field_set{F<2>() == 2}}}); EXPECT_EQ(l2, fdd::leaf{{ oxm::field_set{F<3>() == 3}}}); } TEST(FddTraverseTest, FddTraverseWithMaple) { policy p = handler([](Packet& pkt) { // Test with nested function return handler([](Packet& pkt) { return modify(F<2>() << 2); }); }); auto pf = boost::get<PacketFunction>(p); fdd::diagram d = fdd::node { F<1>() == 1, fdd::leaf{{ {oxm::field_set{}, pf} }}, fdd::leaf{} }; oxm::field_set fs{F<1>() == 1}; fdd::Traverser traverser{fs}; fdd::leaf& l = boost::apply_visitor(traverser, d); EXPECT_EQ(l, fdd::leaf{{ oxm::field_set{F<2>() == 2} }}); } TEST(FddTraverseTest, FddTraverseWithMapleCallMeTwice) { int call_count = 0; policy p = handler([&call_count](Packet& pkt) { call_count++; return hard_timeout(duration::zero()); }); oxm::field_set fs{F<1>() == 1}; fdd::diagram d = fdd::compile(p); for (int i = 0; i < 2; i++) { fdd::Traverser traverser{fs}; boost::apply_visitor(traverser, d); } EXPECT_EQ(call_count, 2); } using match = std::vector<oxm::field_set>; TEST(FddTraverseTest, FddTraverseWithMapleWithBackend) { MockBackend backend; policy p = handler([](Packet& pkt) { pkt.test(F<1>() == 1); // should't be called becouse of cache pkt.test(F<3>() == 3); // should be called return modify(F<2>() << 2); }); auto pf = boost::get<PacketFunction>(p); fdd::diagram d = fdd::node { F<1>() == 1, fdd::leaf{{ {oxm::field_set{}, pf} }}, fdd::leaf{} }; oxm::field_set fs{F<1>() == 1, F<2>() == 2, F<3>() == 3}; fdd::Traverser traverser{fs, &backend}; EXPECT_CALL(backend, installBarrier(oxm::field_set{F<1>() == 1, F<3>() == 3}, _)).Times(1); EXPECT_CALL(backend, installBarrier(oxm::field_set{F<1>() == 1}, _)).Times(0); EXPECT_CALL( backend, install( oxm::field_set{F<1>() == 1, F<3>() == 3}, match{oxm::field_set{F<2>() == 2}}, _, _ ) ).Times(1); fdd::leaf& l = boost::apply_visitor(traverser, d); EXPECT_EQ(l, fdd::leaf{{ oxm::field_set{F<2>() == 2} }}); } TEST(FddTraverseTest, FddTraverseWithMapleWithBackendNestedFunction) { MockBackend backend; policy p = handler([](Packet& pkt) { // Test with nested function pkt.test(F<1>() == 1); // should't be called becouse of cache pkt.test(F<3>() == 3); // should be called return handler([](Packet& pkt) { return modify(F<2>() << 2); }); }); auto pf = boost::get<PacketFunction>(p); fdd::diagram d = fdd::node { F<1>() == 1, fdd::leaf{{ {oxm::field_set{}, pf} }}, fdd::leaf{} }; oxm::field_set fs{F<1>() == 1, F<2>() == 2, F<3>() == 3}; fdd::Traverser traverser{fs, &backend}; EXPECT_CALL(backend, installBarrier(oxm::field_set{F<1>() == 1, F<3>() == 3}, _)).Times(Between(1,2)); EXPECT_CALL(backend, installBarrier(oxm::field_set{F<1>() == 1}, _)).Times(0); EXPECT_CALL( backend, install( oxm::field_set{F<1>() == 1, F<3>() == 3}, match{oxm::field_set{F<2>() == 2}}, _, _ ) ).Times(1); fdd::leaf& l = boost::apply_visitor(traverser, d); EXPECT_EQ(l, fdd::leaf{{ oxm::field_set{F<2>() == 2} }}); }
31.260045
132
0.529009
enotnadoske
a687955d189ad55a59b1bc5a58fa1ecff1fc3a04
9,549
cpp
C++
src/lib/object_store/test/ObjectStoreTests.cpp
gecheim/SoftHSMv2
42fbff713e77afe27d7b466b24cfad9dea69df1f
[ "BSD-2-Clause" ]
486
2015-01-04T05:57:25.000Z
2022-03-30T02:40:52.000Z
src/lib/object_store/test/ObjectStoreTests.cpp
gecheim/SoftHSMv2
42fbff713e77afe27d7b466b24cfad9dea69df1f
[ "BSD-2-Clause" ]
486
2015-01-12T08:51:33.000Z
2022-03-22T09:06:15.000Z
src/lib/object_store/test/ObjectStoreTests.cpp
gecheim/SoftHSMv2
42fbff713e77afe27d7b466b24cfad9dea69df1f
[ "BSD-2-Clause" ]
274
2015-01-21T21:41:45.000Z
2022-03-30T15:05:54.000Z
/* * Copyright (c) 2010 SURFnet bv * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /***************************************************************************** ObjectStoreTests.cpp Contains test cases to test the object store implementation *****************************************************************************/ #include <stdlib.h> #include <string.h> #include <cppunit/extensions/HelperMacros.h> #include "ObjectStoreTests.h" #include "ObjectStore.h" #include "File.h" #include "Directory.h" #include "OSAttribute.h" #include "OSAttributes.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(ObjectStoreTests); // FIXME: all pathnames in this file are *NIX/BSD specific void ObjectStoreTests::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); } void ObjectStoreTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void ObjectStoreTests::testEmptyStore() { // Create the store for an empty dir #ifndef _WIN32 ObjectStore store("./testdir", DEFAULT_UMASK); #else ObjectStore store(".\\testdir", DEFAULT_UMASK); #endif CPPUNIT_ASSERT(store.getTokenCount() == 0); } void ObjectStoreTests::testNewTokens() { ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; { // Create an empty store #ifndef _WIN32 ObjectStore store("./testdir", DEFAULT_UMASK); #else ObjectStore store(".\\testdir", DEFAULT_UMASK); #endif CPPUNIT_ASSERT(store.getTokenCount() == 0); // Create a new token ObjectStoreToken* token1 = store.newToken(label1); CPPUNIT_ASSERT(token1 != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 1); // Create another new token ObjectStoreToken* token2 = store.newToken(label2); CPPUNIT_ASSERT(token2 != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 2); } // Now reopen that same store #ifndef _WIN32 ObjectStore store("./testdir", DEFAULT_UMASK); #else ObjectStore store(".\\testdir", DEFAULT_UMASK); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* token1 = store.getToken(0); ObjectStoreToken* token2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2; CPPUNIT_ASSERT(token1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(token2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel2 == label1)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); ByteString retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(token1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(token2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } void ObjectStoreTests::testExistingTokens() { // Create some tokens ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ByteString serial1 = "0011001100110011"; ByteString serial2 = "2233223322332233"; #ifndef _WIN32 ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", DEFAULT_UMASK, label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", DEFAULT_UMASK, label2, serial2); #else ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", DEFAULT_UMASK, label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", DEFAULT_UMASK, label2, serial2); #endif CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL)); delete token1; delete token2; // Now associate a store with the test directory #ifndef _WIN32 ObjectStore store("./testdir", DEFAULT_UMASK); #else ObjectStore store(".\\testdir", DEFAULT_UMASK); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1 = store.getToken(0); ObjectStoreToken* retrieveToken2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(retrieveToken1 != NULL); CPPUNIT_ASSERT(retrieveToken2 != NULL); CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2)); CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } void ObjectStoreTests::testDeleteToken() { // Create some tokens ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ByteString serial1 = "0011001100110011"; ByteString serial2 = "2233223322332233"; #ifndef _WIN32 ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", DEFAULT_UMASK, label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", DEFAULT_UMASK, label2, serial2); #else ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", DEFAULT_UMASK, label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", DEFAULT_UMASK, label2, serial2); #endif CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL)); delete token1; delete token2; // Now associate a store with the test directory #ifndef _WIN32 ObjectStore store("./testdir", DEFAULT_UMASK); #else ObjectStore store(".\\testdir", DEFAULT_UMASK); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1 = store.getToken(0); ObjectStoreToken* retrieveToken2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(retrieveToken1 != NULL); CPPUNIT_ASSERT(retrieveToken2 != NULL); CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2)); CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); // Now, delete token #1 CPPUNIT_ASSERT(store.destroyToken(retrieveToken1)); CPPUNIT_ASSERT(store.getTokenCount() == 1); ObjectStoreToken* retrieveToken_ = store.getToken(0); ByteString retrieveLabel_,retrieveSerial_; CPPUNIT_ASSERT(retrieveToken_->getTokenLabel(retrieveLabel_)); CPPUNIT_ASSERT(retrieveToken_->getTokenSerial(retrieveSerial_)); CPPUNIT_ASSERT(((retrieveLabel_ == label1) && (retrieveSerial_ == serial1)) || ((retrieveLabel_ == label2) && (retrieveSerial_ == serial2))); // Now add a new token ByteString label3 = "DEADC0FFEEBEEF"; // Create a new token ObjectStoreToken* tokenNew = store.newToken(label3); CPPUNIT_ASSERT(tokenNew != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1_ = store.getToken(0); ObjectStoreToken* retrieveToken2_ = store.getToken(1); CPPUNIT_ASSERT(retrieveToken1_ != NULL); CPPUNIT_ASSERT(retrieveToken2_ != NULL); CPPUNIT_ASSERT(retrieveToken1_->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2_->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1_->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2_->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label3) || (retrieveLabel2 == label3)); CPPUNIT_ASSERT(((retrieveLabel1 == label1) && (retrieveLabel2 != label2)) || ((retrieveLabel1 == label2) && (retrieveLabel2 != label1))); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); }
34.225806
114
0.749084
gecheim
a68bd737c94e49440b86f9c0a481d1e3b408fdb3
574
hpp
C++
lab3/11_waterconsumer/waterconsumer.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
2
2015-10-08T15:07:07.000Z
2017-09-17T10:08:36.000Z
lab3/11_waterconsumer/waterconsumer.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
lab3/11_waterconsumer/waterconsumer.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
// (C) 2013-2014, Sergei Zaychenko, KNURE, Kharkiv, Ukraine #ifndef _WATERCONSUMER_HPP_ #define _WATERCONSUMER_HPP_ /*****************************************************************************/ class WaterConsumer { /*-----------------------------------------------------------------*/ public: /*-----------------------------------------------------------------*/ // TODO ... /*-----------------------------------------------------------------*/ }; /*****************************************************************************/ #endif // _WATERCONSUMER_HPP_
21.259259
79
0.252613
zaychenko-sergei
a690b73000ae0b25e4d6a8f139f9512f647d9a36
12,398
cpp
C++
Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0071.cpp
Dschee/Neptune
016d132f8e4449e6b0f79fbc5ce25de365eab983
[ "BSD-3-Clause" ]
17
2015-09-17T06:53:47.000Z
2021-08-09T03:41:21.000Z
Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0071.cpp
Dschee/Neptune
016d132f8e4449e6b0f79fbc5ce25de365eab983
[ "BSD-3-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0071.cpp
Dschee/Neptune
016d132f8e4449e6b0f79fbc5ce25de365eab983
[ "BSD-3-Clause" ]
18
2015-12-09T21:27:41.000Z
2020-11-27T11:38:49.000Z
/***************************************************************** | | Neptune - Trust Anchors | | This file is automatically generated by a script, do not edit! | | Copyright (c) 2002-2010, Axiomatic Systems, LLC. | All rights reserved. | | Redistribution and use in source and binary forms, with or without | modification, are permitted provided that the following conditions are met: | * Redistributions of source code must retain the above copyright | notice, this list of conditions and the following disclaimer. | * Redistributions in binary form must reproduce the above copyright | notice, this list of conditions and the following disclaimer in the | documentation and/or other materials provided with the distribution. | * Neither the name of Axiomatic Systems nor the | names of its contributors may be used to endorse or promote products | derived from this software without specific prior written permission. | | THIS SOFTWARE IS PROVIDED BY AXIOMATIC SYSTEMS ''AS IS'' AND ANY | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | DISCLAIMED. IN NO EVENT SHALL AXIOMATIC SYSTEMS BE LIABLE FOR ANY | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ****************************************************************/ /* IPS CLASEA1 root */ const unsigned char NptTlsTrustAnchor_Base_0071_Data[2043] = { 0x30,0x82,0x07,0xf7,0x30,0x82,0x07,0x60 ,0xa0,0x03,0x02,0x01,0x02,0x02,0x01,0x00 ,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86 ,0xf7,0x0d,0x01,0x01,0x05,0x05,0x00,0x30 ,0x82,0x01,0x14,0x31,0x0b,0x30,0x09,0x06 ,0x03,0x55,0x04,0x06,0x13,0x02,0x45,0x53 ,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04 ,0x08,0x13,0x09,0x42,0x61,0x72,0x63,0x65 ,0x6c,0x6f,0x6e,0x61,0x31,0x12,0x30,0x10 ,0x06,0x03,0x55,0x04,0x07,0x13,0x09,0x42 ,0x61,0x72,0x63,0x65,0x6c,0x6f,0x6e,0x61 ,0x31,0x2e,0x30,0x2c,0x06,0x03,0x55,0x04 ,0x0a,0x13,0x25,0x49,0x50,0x53,0x20,0x49 ,0x6e,0x74,0x65,0x72,0x6e,0x65,0x74,0x20 ,0x70,0x75,0x62,0x6c,0x69,0x73,0x68,0x69 ,0x6e,0x67,0x20,0x53,0x65,0x72,0x76,0x69 ,0x63,0x65,0x73,0x20,0x73,0x2e,0x6c,0x2e ,0x31,0x2b,0x30,0x29,0x06,0x03,0x55,0x04 ,0x0a,0x14,0x22,0x69,0x70,0x73,0x40,0x6d ,0x61,0x69,0x6c,0x2e,0x69,0x70,0x73,0x2e ,0x65,0x73,0x20,0x43,0x2e,0x49,0x2e,0x46 ,0x2e,0x20,0x20,0x42,0x2d,0x36,0x30,0x39 ,0x32,0x39,0x34,0x35,0x32,0x31,0x2f,0x30 ,0x2d,0x06,0x03,0x55,0x04,0x0b,0x13,0x26 ,0x49,0x50,0x53,0x20,0x43,0x41,0x20,0x43 ,0x4c,0x41,0x53,0x45,0x41,0x31,0x20,0x43 ,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61 ,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75,0x74 ,0x68,0x6f,0x72,0x69,0x74,0x79,0x31,0x2f ,0x30,0x2d,0x06,0x03,0x55,0x04,0x03,0x13 ,0x26,0x49,0x50,0x53,0x20,0x43,0x41,0x20 ,0x43,0x4c,0x41,0x53,0x45,0x41,0x31,0x20 ,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63 ,0x61,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75 ,0x74,0x68,0x6f,0x72,0x69,0x74,0x79,0x31 ,0x1e,0x30,0x1c,0x06,0x09,0x2a,0x86,0x48 ,0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x0f ,0x69,0x70,0x73,0x40,0x6d,0x61,0x69,0x6c ,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x30 ,0x1e,0x17,0x0d,0x30,0x31,0x31,0x32,0x32 ,0x39,0x30,0x31,0x30,0x35,0x33,0x32,0x5a ,0x17,0x0d,0x32,0x35,0x31,0x32,0x32,0x37 ,0x30,0x31,0x30,0x35,0x33,0x32,0x5a,0x30 ,0x82,0x01,0x14,0x31,0x0b,0x30,0x09,0x06 ,0x03,0x55,0x04,0x06,0x13,0x02,0x45,0x53 ,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04 ,0x08,0x13,0x09,0x42,0x61,0x72,0x63,0x65 ,0x6c,0x6f,0x6e,0x61,0x31,0x12,0x30,0x10 ,0x06,0x03,0x55,0x04,0x07,0x13,0x09,0x42 ,0x61,0x72,0x63,0x65,0x6c,0x6f,0x6e,0x61 ,0x31,0x2e,0x30,0x2c,0x06,0x03,0x55,0x04 ,0x0a,0x13,0x25,0x49,0x50,0x53,0x20,0x49 ,0x6e,0x74,0x65,0x72,0x6e,0x65,0x74,0x20 ,0x70,0x75,0x62,0x6c,0x69,0x73,0x68,0x69 ,0x6e,0x67,0x20,0x53,0x65,0x72,0x76,0x69 ,0x63,0x65,0x73,0x20,0x73,0x2e,0x6c,0x2e ,0x31,0x2b,0x30,0x29,0x06,0x03,0x55,0x04 ,0x0a,0x14,0x22,0x69,0x70,0x73,0x40,0x6d ,0x61,0x69,0x6c,0x2e,0x69,0x70,0x73,0x2e ,0x65,0x73,0x20,0x43,0x2e,0x49,0x2e,0x46 ,0x2e,0x20,0x20,0x42,0x2d,0x36,0x30,0x39 ,0x32,0x39,0x34,0x35,0x32,0x31,0x2f,0x30 ,0x2d,0x06,0x03,0x55,0x04,0x0b,0x13,0x26 ,0x49,0x50,0x53,0x20,0x43,0x41,0x20,0x43 ,0x4c,0x41,0x53,0x45,0x41,0x31,0x20,0x43 ,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61 ,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75,0x74 ,0x68,0x6f,0x72,0x69,0x74,0x79,0x31,0x2f ,0x30,0x2d,0x06,0x03,0x55,0x04,0x03,0x13 ,0x26,0x49,0x50,0x53,0x20,0x43,0x41,0x20 ,0x43,0x4c,0x41,0x53,0x45,0x41,0x31,0x20 ,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63 ,0x61,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75 ,0x74,0x68,0x6f,0x72,0x69,0x74,0x79,0x31 ,0x1e,0x30,0x1c,0x06,0x09,0x2a,0x86,0x48 ,0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x0f ,0x69,0x70,0x73,0x40,0x6d,0x61,0x69,0x6c ,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x30 ,0x81,0x9f,0x30,0x0d,0x06,0x09,0x2a,0x86 ,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01,0x05 ,0x00,0x03,0x81,0x8d,0x00,0x30,0x81,0x89 ,0x02,0x81,0x81,0x00,0xbb,0x30,0xd7,0xdc ,0xd0,0x54,0xbd,0x35,0x4e,0x9f,0xc5,0x4c ,0x82,0xea,0xd1,0x50,0x3c,0x47,0x98,0xfc ,0x9b,0x69,0x9d,0x77,0xcd,0x6e,0xe0,0x3f ,0xee,0xeb,0x32,0x5f,0x5f,0x9f,0xd2,0xd0 ,0x79,0xe5,0x95,0x73,0x44,0x21,0x32,0xe0 ,0x0a,0xdb,0x9d,0xd7,0xce,0x8d,0xab,0x52 ,0x8b,0x2b,0x78,0xe0,0x9b,0x5b,0x7d,0xf4 ,0xfd,0x6d,0x09,0xe5,0xae,0xe1,0x6c,0x1d ,0x07,0x23,0xa0,0x17,0xd1,0xf9,0x7d,0xa8 ,0x46,0x46,0x91,0x22,0xa8,0xb2,0x69,0xc6 ,0xad,0xf7,0xf5,0xf5,0x94,0xa1,0x30,0x94 ,0xbd,0x00,0xcc,0x44,0x7f,0xee,0xc4,0x9e ,0xc9,0xc1,0xe6,0x8f,0x0a,0x36,0xc1,0xfd ,0x24,0x3d,0x01,0xa0,0xf5,0x7b,0xe2,0x7c ,0x78,0x66,0x43,0x8b,0x4f,0x59,0xf2,0x9b ,0xd9,0xfa,0x49,0xb3,0x02,0x03,0x01,0x00 ,0x01,0xa3,0x82,0x04,0x53,0x30,0x82,0x04 ,0x4f,0x30,0x1d,0x06,0x03,0x55,0x1d,0x0e ,0x04,0x16,0x04,0x14,0x67,0x26,0x96,0xe7 ,0xa1,0xbf,0xd8,0xb5,0x03,0x9d,0xfe,0x3b ,0xdc,0xfe,0xf2,0x8a,0xe6,0x15,0xdd,0x30 ,0x30,0x82,0x01,0x46,0x06,0x03,0x55,0x1d ,0x23,0x04,0x82,0x01,0x3d,0x30,0x82,0x01 ,0x39,0x80,0x14,0x67,0x26,0x96,0xe7,0xa1 ,0xbf,0xd8,0xb5,0x03,0x9d,0xfe,0x3b,0xdc ,0xfe,0xf2,0x8a,0xe6,0x15,0xdd,0x30,0xa1 ,0x82,0x01,0x1c,0xa4,0x82,0x01,0x18,0x30 ,0x82,0x01,0x14,0x31,0x0b,0x30,0x09,0x06 ,0x03,0x55,0x04,0x06,0x13,0x02,0x45,0x53 ,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04 ,0x08,0x13,0x09,0x42,0x61,0x72,0x63,0x65 ,0x6c,0x6f,0x6e,0x61,0x31,0x12,0x30,0x10 ,0x06,0x03,0x55,0x04,0x07,0x13,0x09,0x42 ,0x61,0x72,0x63,0x65,0x6c,0x6f,0x6e,0x61 ,0x31,0x2e,0x30,0x2c,0x06,0x03,0x55,0x04 ,0x0a,0x13,0x25,0x49,0x50,0x53,0x20,0x49 ,0x6e,0x74,0x65,0x72,0x6e,0x65,0x74,0x20 ,0x70,0x75,0x62,0x6c,0x69,0x73,0x68,0x69 ,0x6e,0x67,0x20,0x53,0x65,0x72,0x76,0x69 ,0x63,0x65,0x73,0x20,0x73,0x2e,0x6c,0x2e ,0x31,0x2b,0x30,0x29,0x06,0x03,0x55,0x04 ,0x0a,0x14,0x22,0x69,0x70,0x73,0x40,0x6d ,0x61,0x69,0x6c,0x2e,0x69,0x70,0x73,0x2e ,0x65,0x73,0x20,0x43,0x2e,0x49,0x2e,0x46 ,0x2e,0x20,0x20,0x42,0x2d,0x36,0x30,0x39 ,0x32,0x39,0x34,0x35,0x32,0x31,0x2f,0x30 ,0x2d,0x06,0x03,0x55,0x04,0x0b,0x13,0x26 ,0x49,0x50,0x53,0x20,0x43,0x41,0x20,0x43 ,0x4c,0x41,0x53,0x45,0x41,0x31,0x20,0x43 ,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61 ,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75,0x74 ,0x68,0x6f,0x72,0x69,0x74,0x79,0x31,0x2f ,0x30,0x2d,0x06,0x03,0x55,0x04,0x03,0x13 ,0x26,0x49,0x50,0x53,0x20,0x43,0x41,0x20 ,0x43,0x4c,0x41,0x53,0x45,0x41,0x31,0x20 ,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63 ,0x61,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75 ,0x74,0x68,0x6f,0x72,0x69,0x74,0x79,0x31 ,0x1e,0x30,0x1c,0x06,0x09,0x2a,0x86,0x48 ,0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x0f ,0x69,0x70,0x73,0x40,0x6d,0x61,0x69,0x6c ,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x82 ,0x01,0x00,0x30,0x0c,0x06,0x03,0x55,0x1d ,0x13,0x04,0x05,0x30,0x03,0x01,0x01,0xff ,0x30,0x0c,0x06,0x03,0x55,0x1d,0x0f,0x04 ,0x05,0x03,0x03,0x07,0xff,0x80,0x30,0x6b ,0x06,0x03,0x55,0x1d,0x25,0x04,0x64,0x30 ,0x62,0x06,0x08,0x2b,0x06,0x01,0x05,0x05 ,0x07,0x03,0x01,0x06,0x08,0x2b,0x06,0x01 ,0x05,0x05,0x07,0x03,0x02,0x06,0x08,0x2b ,0x06,0x01,0x05,0x05,0x07,0x03,0x03,0x06 ,0x08,0x2b,0x06,0x01,0x05,0x05,0x07,0x03 ,0x04,0x06,0x08,0x2b,0x06,0x01,0x05,0x05 ,0x07,0x03,0x08,0x06,0x0a,0x2b,0x06,0x01 ,0x04,0x01,0x82,0x37,0x02,0x01,0x15,0x06 ,0x0a,0x2b,0x06,0x01,0x04,0x01,0x82,0x37 ,0x02,0x01,0x16,0x06,0x0a,0x2b,0x06,0x01 ,0x04,0x01,0x82,0x37,0x0a,0x03,0x01,0x06 ,0x0a,0x2b,0x06,0x01,0x04,0x01,0x82,0x37 ,0x0a,0x03,0x04,0x30,0x11,0x06,0x09,0x60 ,0x86,0x48,0x01,0x86,0xf8,0x42,0x01,0x01 ,0x04,0x04,0x03,0x02,0x00,0x07,0x30,0x1a ,0x06,0x03,0x55,0x1d,0x11,0x04,0x13,0x30 ,0x11,0x81,0x0f,0x69,0x70,0x73,0x40,0x6d ,0x61,0x69,0x6c,0x2e,0x69,0x70,0x73,0x2e ,0x65,0x73,0x30,0x1a,0x06,0x03,0x55,0x1d ,0x12,0x04,0x13,0x30,0x11,0x81,0x0f,0x69 ,0x70,0x73,0x40,0x6d,0x61,0x69,0x6c,0x2e ,0x69,0x70,0x73,0x2e,0x65,0x73,0x30,0x42 ,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xf8 ,0x42,0x01,0x0d,0x04,0x35,0x16,0x33,0x43 ,0x4c,0x41,0x53,0x45,0x41,0x31,0x20,0x43 ,0x41,0x20,0x43,0x65,0x72,0x74,0x69,0x66 ,0x69,0x63,0x61,0x74,0x65,0x20,0x69,0x73 ,0x73,0x75,0x65,0x64,0x20,0x62,0x79,0x20 ,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77 ,0x77,0x77,0x2e,0x69,0x70,0x73,0x2e,0x65 ,0x73,0x2f,0x30,0x29,0x06,0x09,0x60,0x86 ,0x48,0x01,0x86,0xf8,0x42,0x01,0x02,0x04 ,0x1c,0x16,0x1a,0x68,0x74,0x74,0x70,0x3a ,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69,0x70 ,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70,0x73 ,0x32,0x30,0x30,0x32,0x2f,0x30,0x3b,0x06 ,0x09,0x60,0x86,0x48,0x01,0x86,0xf8,0x42 ,0x01,0x04,0x04,0x2e,0x16,0x2c,0x68,0x74 ,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77 ,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x2f ,0x69,0x70,0x73,0x32,0x30,0x30,0x32,0x2f ,0x69,0x70,0x73,0x32,0x30,0x30,0x32,0x43 ,0x4c,0x41,0x53,0x45,0x41,0x31,0x2e,0x63 ,0x72,0x6c,0x30,0x40,0x06,0x09,0x60,0x86 ,0x48,0x01,0x86,0xf8,0x42,0x01,0x03,0x04 ,0x33,0x16,0x31,0x68,0x74,0x74,0x70,0x3a ,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69,0x70 ,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70,0x73 ,0x32,0x30,0x30,0x32,0x2f,0x72,0x65,0x76 ,0x6f,0x63,0x61,0x74,0x69,0x6f,0x6e,0x43 ,0x4c,0x41,0x53,0x45,0x41,0x31,0x2e,0x68 ,0x74,0x6d,0x6c,0x3f,0x30,0x3d,0x06,0x09 ,0x60,0x86,0x48,0x01,0x86,0xf8,0x42,0x01 ,0x07,0x04,0x30,0x16,0x2e,0x68,0x74,0x74 ,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e ,0x69,0x70,0x73,0x2e,0x65,0x73,0x2f,0x69 ,0x70,0x73,0x32,0x30,0x30,0x32,0x2f,0x72 ,0x65,0x6e,0x65,0x77,0x61,0x6c,0x43,0x4c ,0x41,0x53,0x45,0x41,0x31,0x2e,0x68,0x74 ,0x6d,0x6c,0x3f,0x30,0x3b,0x06,0x09,0x60 ,0x86,0x48,0x01,0x86,0xf8,0x42,0x01,0x08 ,0x04,0x2e,0x16,0x2c,0x68,0x74,0x74,0x70 ,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69 ,0x70,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70 ,0x73,0x32,0x30,0x30,0x32,0x2f,0x70,0x6f ,0x6c,0x69,0x63,0x79,0x43,0x4c,0x41,0x53 ,0x45,0x41,0x31,0x2e,0x68,0x74,0x6d,0x6c ,0x30,0x75,0x06,0x03,0x55,0x1d,0x1f,0x04 ,0x6e,0x30,0x6c,0x30,0x32,0xa0,0x30,0xa0 ,0x2e,0x86,0x2c,0x68,0x74,0x74,0x70,0x3a ,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69,0x70 ,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70,0x73 ,0x32,0x30,0x30,0x32,0x2f,0x69,0x70,0x73 ,0x32,0x30,0x30,0x32,0x43,0x4c,0x41,0x53 ,0x45,0x41,0x31,0x2e,0x63,0x72,0x6c,0x30 ,0x36,0xa0,0x34,0xa0,0x32,0x86,0x30,0x68 ,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77 ,0x77,0x62,0x61,0x63,0x6b,0x2e,0x69,0x70 ,0x73,0x2e,0x65,0x73,0x2f,0x69,0x70,0x73 ,0x32,0x30,0x30,0x32,0x2f,0x69,0x70,0x73 ,0x32,0x30,0x30,0x32,0x43,0x4c,0x41,0x53 ,0x45,0x41,0x31,0x2e,0x63,0x72,0x6c,0x30 ,0x2f,0x06,0x08,0x2b,0x06,0x01,0x05,0x05 ,0x07,0x01,0x01,0x04,0x23,0x30,0x21,0x30 ,0x1f,0x06,0x08,0x2b,0x06,0x01,0x05,0x05 ,0x07,0x30,0x01,0x86,0x13,0x68,0x74,0x74 ,0x70,0x3a,0x2f,0x2f,0x6f,0x63,0x73,0x70 ,0x2e,0x69,0x70,0x73,0x2e,0x65,0x73,0x2f ,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86 ,0xf7,0x0d,0x01,0x01,0x05,0x05,0x00,0x03 ,0x81,0x81,0x00,0x7e,0xba,0x8a,0xac,0x80 ,0x00,0x84,0x15,0x0a,0xd5,0x98,0x51,0x0c ,0x64,0xc5,0x9c,0x02,0x58,0x83,0x66,0xca ,0xad,0x1e,0x07,0xcd,0x7e,0x6a,0xda,0x80 ,0x07,0xdf,0x03,0x34,0x4a,0x1c,0x93,0xc4 ,0x4b,0x58,0x20,0x35,0x36,0x71,0xed,0xa2 ,0x0a,0x35,0x12,0xa5,0xa6,0x65,0xa7,0x85 ,0x69,0x0a,0x0e,0xe3,0x61,0xee,0xea,0xbe ,0x28,0x93,0x33,0xd5,0xec,0xe8,0xbe,0xc4 ,0xdb,0x5f,0x7f,0xa8,0xf9,0x63,0x31,0xc8 ,0x6b,0x96,0xe2,0x29,0xc2,0x5b,0xa0,0xe7 ,0x97,0x36,0x9d,0x77,0x5e,0x31,0x6b,0xfe ,0xd3,0xa7,0xdb,0x2a,0xdb,0xdb,0x96,0x8b ,0x1f,0x66,0xde,0xb6,0x03,0xc0,0x2b,0xb3 ,0x78,0xd6,0x55,0x07,0xe5,0x8f,0x39,0x50 ,0xde,0x07,0x23,0x72,0xe6,0xbd,0x20,0x14 ,0x4b,0xb4,0x86}; const unsigned int NptTlsTrustAnchor_Base_0071_Size = 2043;
42.313993
79
0.769882
Dschee
a69143e9abf587347b57187bda9f3624ecb386f6
2,331
cpp
C++
projects/PathosEngine/src/pathos/wrapper/transform.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
11
2016-08-30T12:01:35.000Z
2021-12-29T15:34:03.000Z
projects/PathosEngine/src/pathos/wrapper/transform.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
9
2016-05-19T03:14:22.000Z
2021-01-17T05:45:52.000Z
projects/PathosEngine/src/pathos/wrapper/transform.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
null
null
null
#include "pathos/wrapper/transform.h" #include <glm/gtc/matrix_transform.hpp> namespace pathos { Transform::Transform() :matrix(glm::mat4(1.0f)) {} Transform::Transform(const glm::mat4& _matrix) { matrix = _matrix; } const glm::mat4& Transform::getMatrix() const { return matrix; } void Transform::identity() { matrix = glm::mat4(1.0f); } void Transform::append(const glm::mat4& t) { matrix = t * matrix; } //void Transform::appendMove(const glm::vec3& movement) { matrix = glm::translate(matrix, movement); } void Transform::appendMove(const glm::vec3& movement) { matrix = glm::translate(glm::mat4(1.0f), movement) * matrix; } void Transform::appendMove(float dx, float dy, float dz) { appendMove(glm::vec3(dx, dy, dz)); } void Transform::appendRotation(float angle, const glm::vec3& axis) { matrix = glm::rotate(glm::mat4(1.0f), angle, axis) * matrix; } void Transform::appendScale(const glm::vec3& scale) { matrix = glm::scale(glm::mat4(1.0f), scale) * matrix; } //void Transform::appendScale(const glm::vec3& scale) { matrix = glm::scale(matrix, scale); } void Transform::appendScale(float sx, float sy, float sz) { appendScale(glm::vec3(sx, sy, sz)); } void Transform::prepend(const glm::mat4& t) { matrix = matrix * t; } void Transform::prependMove(const glm::vec3& movement) { //matrix = glm::translate(matrix, movement); prepend(glm::translate(glm::mat4(1.0f), movement)); } void Transform::prependMove(float dx, float dy, float dz) { prependMove(glm::vec3(dx, dy, dz)); } void Transform::prependRotation(float angle, const glm::vec3& axis) { matrix = glm::rotate(matrix, angle, axis); } void Transform::prependScale(const glm::vec3& scale) { matrix = glm::scale(matrix, scale); } void Transform::prependScale(float sx, float sy, float sz) { prependScale(glm::vec3(sx, sy, sz)); } glm::vec3 Transform::transformVector(glm::vec3 v) { return glm::vec3(matrix * glm::vec4(v, 0.0f)); } glm::vec3 Transform::inverseTransformVector(glm::vec3 v) const { return glm::vec3(glm::transpose(matrix) * glm::vec4(v, 0.0f)); } glm::vec3 Transform::transformPoint(glm::vec3 v) { return glm::vec3(matrix * glm::vec4(v, 1.0f)); } glm::vec3 Transform::inverseTransformPoint(glm::vec3 v) { return glm::vec3(glm::transpose(matrix) * glm::vec4(v, 1.0f)); } }
31.5
103
0.681253
codeonwort
a69268faabb732483d24cc1b969714805e8d073b
9,591
cpp
C++
lib/PhasarLLVM/ControlFlow/LLVMBasedCFG.cpp
ddiepo-pjr/phasar
78c93057360f71bcd49bf98e275135c70eb27e90
[ "MIT" ]
null
null
null
lib/PhasarLLVM/ControlFlow/LLVMBasedCFG.cpp
ddiepo-pjr/phasar
78c93057360f71bcd49bf98e275135c70eb27e90
[ "MIT" ]
null
null
null
lib/PhasarLLVM/ControlFlow/LLVMBasedCFG.cpp
ddiepo-pjr/phasar
78c93057360f71bcd49bf98e275135c70eb27e90
[ "MIT" ]
1
2020-11-06T06:19:29.000Z
2020-11-06T06:19:29.000Z
/****************************************************************************** * Copyright (c) 2017 Philipp Schubert. * All rights reserved. This program and the accompanying materials are made * available under the terms of LICENSE.txt. * * Contributors: * Philipp Schubert and others *****************************************************************************/ /* * LLVMBasedCFG.cpp * * Created on: 07.06.2017 * Author: philipp */ #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "phasar/Config/Configuration.h" #include "phasar/PhasarLLVM/ControlFlow/LLVMBasedCFG.h" #include "phasar/Utils/LLVMShorthands.h" #include "phasar/Utils/Logger.h" #include "phasar/Utils/Utilities.h" #include <algorithm> #include <cassert> #include <iterator> using namespace std; using namespace psr; namespace psr { const llvm::Function * LLVMBasedCFG::getFunctionOf(const llvm::Instruction *Stmt) const { return Stmt->getFunction(); } vector<const llvm::Instruction *> LLVMBasedCFG::getPredsOf(const llvm::Instruction *I) const { vector<const llvm::Instruction *> Preds; if (!IgnoreDbgInstructions) { if (I->getPrevNode()) { Preds.push_back(I->getPrevNode()); } } else { if (I->getPrevNonDebugInstruction()) { Preds.push_back(I->getPrevNonDebugInstruction()); } } // If we do not have a predecessor yet, look for basic blocks which // lead to our instruction in question! if (Preds.empty()) { std::transform(llvm::pred_begin(I->getParent()), llvm::pred_end(I->getParent()), back_inserter(Preds), [](const llvm::BasicBlock *BB) { assert(BB && "BB under analysis was not well formed."); return BB->getTerminator(); }); } return Preds; } vector<const llvm::Instruction *> LLVMBasedCFG::getSuccsOf(const llvm::Instruction *I) const { vector<const llvm::Instruction *> Successors; // case we wish to consider LLVM's debug instructions if (!IgnoreDbgInstructions) { if (I->getNextNode()) { Successors.push_back(I->getNextNode()); } } else { if (I->getNextNonDebugInstruction()) { Successors.push_back(I->getNextNonDebugInstruction()); } } if (I->isTerminator()) { Successors.reserve(I->getNumSuccessors() + Successors.size()); std::transform(llvm::succ_begin(I), llvm::succ_end(I), back_inserter(Successors), [](const llvm::BasicBlock *BB) { return &BB->front(); }); } return Successors; } vector<pair<const llvm::Instruction *, const llvm::Instruction *>> LLVMBasedCFG::getAllControlFlowEdges(const llvm::Function *Fun) const { vector<pair<const llvm::Instruction *, const llvm::Instruction *>> Edges; for (const auto &BB : *Fun) { for (const auto &I : BB) { if (IgnoreDbgInstructions) { // Check for call to intrinsic debug function if (const auto *DbgCallInst = llvm::dyn_cast<llvm::CallInst>(&I)) { if (DbgCallInst->getCalledFunction() && DbgCallInst->getCalledFunction()->isIntrinsic() && (DbgCallInst->getCalledFunction()->getName() == "llvm.dbg.declare")) { continue; } } } auto Successors = getSuccsOf(&I); for (const auto *Successor : Successors) { Edges.emplace_back(&I, Successor); } } } return Edges; } vector<const llvm::Instruction *> LLVMBasedCFG::getAllInstructionsOf(const llvm::Function *Fun) const { vector<const llvm::Instruction *> Instructions; for (const auto &BB : *Fun) { for (const auto &I : BB) { Instructions.push_back(&I); } } return Instructions; } std::set<const llvm::Instruction *> LLVMBasedCFG::getStartPointsOf(const llvm::Function *Fun) const { if (!Fun) { return {}; } if (!Fun->isDeclaration()) { return {&Fun->front().front()}; } else { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Could not get starting points of '" << Fun->getName().str() << "' because it is a declaration"); return {}; } } std::set<const llvm::Instruction *> LLVMBasedCFG::getExitPointsOf(const llvm::Function *Fun) const { if (!Fun) { return {}; } if (!Fun->isDeclaration()) { return {&Fun->back().back()}; } else { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Could not get exit points of '" << Fun->getName().str() << "' which is declaration!"); return {}; } } bool LLVMBasedCFG::isCallStmt(const llvm::Instruction *Stmt) const { return llvm::isa<llvm::CallInst>(Stmt) || llvm::isa<llvm::InvokeInst>(Stmt); } bool LLVMBasedCFG::isExitStmt(const llvm::Instruction *Stmt) const { return llvm::isa<llvm::ReturnInst>(Stmt); } bool LLVMBasedCFG::isStartPoint(const llvm::Instruction *Stmt) const { return (Stmt == &Stmt->getFunction()->front().front()); } bool LLVMBasedCFG::isFieldLoad(const llvm::Instruction *Stmt) const { if (const auto *Load = llvm::dyn_cast<llvm::LoadInst>(Stmt)) { if (const auto *GEP = llvm::dyn_cast<llvm::GetElementPtrInst>( Load->getPointerOperand())) { return true; } } return false; } bool LLVMBasedCFG::isFieldStore(const llvm::Instruction *Stmt) const { if (const auto *Store = llvm::dyn_cast<llvm::StoreInst>(Stmt)) { if (const auto *GEP = llvm::dyn_cast<llvm::GetElementPtrInst>( Store->getPointerOperand())) { return true; } } return false; } bool LLVMBasedCFG::isFallThroughSuccessor(const llvm::Instruction *Stmt, const llvm::Instruction *Succ) const { // assert(false && "FallThrough not valid in LLVM IR"); if (const auto *B = llvm::dyn_cast<llvm::BranchInst>(Stmt)) { if (B->isConditional()) { return &B->getSuccessor(1)->front() == Succ; } else { return &B->getSuccessor(0)->front() == Succ; } } return false; } bool LLVMBasedCFG::isBranchTarget(const llvm::Instruction *Stmt, const llvm::Instruction *Succ) const { if (Stmt->isTerminator()) { for (const auto *BB : llvm::successors(Stmt->getParent())) { if (&BB->front() == Succ) { return true; } } } return false; } bool LLVMBasedCFG::isHeapAllocatingFunction(const llvm::Function *Fun) const { static const std::set<std::string> HeapAllocatingFunctions = { "_Znwm", "_Znam", "malloc", "calloc", "realloc"}; if (!Fun) { return false; } if (Fun->hasName() && HeapAllocatingFunctions.find(Fun->getName().str()) != HeapAllocatingFunctions.end()) { return true; } return false; } bool LLVMBasedCFG::isSpecialMemberFunction(const llvm::Function *Fun) const { return getSpecialMemberFunctionType(Fun) != SpecialMemberFunctionType::None; } SpecialMemberFunctionType LLVMBasedCFG::getSpecialMemberFunctionType(const llvm::Function *Fun) const { if (!Fun) { return SpecialMemberFunctionType::None; } auto FunctionName = Fun->getName(); // TODO this looks terrible and needs fix static const std::map<std::string, SpecialMemberFunctionType> Codes{ {"C1", SpecialMemberFunctionType::Constructor}, {"C2", SpecialMemberFunctionType::Constructor}, {"C3", SpecialMemberFunctionType::Constructor}, {"D0", SpecialMemberFunctionType::Destructor}, {"D1", SpecialMemberFunctionType::Destructor}, {"D2", SpecialMemberFunctionType::Destructor}, {"aSERKS_", SpecialMemberFunctionType::CopyAssignment}, {"aSEOS_", SpecialMemberFunctionType::MoveAssignment}}; std::vector<std::pair<std::size_t, SpecialMemberFunctionType>> Found; std::size_t Blacklist = 0; auto It = Codes.begin(); while (It != Codes.end()) { if (std::size_t Index = FunctionName.find(It->first, Blacklist)) { if (Index != std::string::npos) { Found.emplace_back(Index, It->second); Blacklist = Index + 1; } else { ++It; Blacklist = 0; } } } if (Found.empty()) { return SpecialMemberFunctionType::None; } // test if codes are in function name or type information bool NoName = true; for (auto Index : Found) { for (auto C = FunctionName.begin(); C < FunctionName.begin() + Index.first; ++C) { if (isdigit(*C)) { short I = 0; while (isdigit(*(C + I))) { ++I; } std::string ST(C, C + I); if (Index.first <= std::distance(FunctionName.begin(), C) + stoul(ST)) { NoName = false; break; } else { C = C + *C; } } } if (NoName) { return Index.second; } else { NoName = true; } } return SpecialMemberFunctionType::None; } string LLVMBasedCFG::getStatementId(const llvm::Instruction *Stmt) const { return llvm::cast<llvm::MDString>( Stmt->getMetadata(PhasarConfig::MetaDataKind())->getOperand(0)) ->getString() .str(); } string LLVMBasedCFG::getFunctionName(const llvm::Function *Fun) const { return Fun->getName().str(); } std::string LLVMBasedCFG::getDemangledFunctionName(const llvm::Function *Fun) const { return cxxDemangle(getFunctionName(Fun)); } void LLVMBasedCFG::print(const llvm::Function *F, std::ostream &OS) const { OS << llvmIRToString(F); } nlohmann::json LLVMBasedCFG::getAsJson(const llvm::Function *F) const { return ""; } } // namespace psr
30.255521
80
0.620686
ddiepo-pjr
a6972419470e24f0ba08520476ada6e9abb7018f
177
hh
C++
vpp/algorithms/line_tracker_4_sfm/hough_extruder.hh
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
624
2015-01-05T16:40:41.000Z
2022-03-01T03:09:43.000Z
vpp/algorithms/line_tracker_4_sfm/hough_extruder.hh
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
10
2015-01-22T20:50:13.000Z
2018-05-15T10:41:34.000Z
vpp/algorithms/line_tracker_4_sfm/hough_extruder.hh
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
113
2015-01-19T11:58:35.000Z
2022-03-28T05:15:20.000Z
#pragma once #include "hough_extruder/draw_trajectories_hough.hh" #include "symbols.hh" #include "hough_extruder/paint.hh" #include "hough_extruder/feature_matching_hough.hh"
22.125
52
0.819209
WLChopSticks
a6a3bcc076f85e16b9f3ecd155ccd6d9e102980f
1,639
cpp
C++
NNGameFramework/ProjectWugargar/PoorZombie.cpp
quxn6/wugargar
79e71a83e1240052ec4217d5223359ca5f1c3890
[ "MIT" ]
1
2017-02-13T06:09:17.000Z
2017-02-13T06:09:17.000Z
NNGameFramework/ProjectWugargar/PoorZombie.cpp
quxn6/wugargar
79e71a83e1240052ec4217d5223359ca5f1c3890
[ "MIT" ]
null
null
null
NNGameFramework/ProjectWugargar/PoorZombie.cpp
quxn6/wugargar
79e71a83e1240052ec4217d5223359ca5f1c3890
[ "MIT" ]
null
null
null
#include "PoorZombie.h" CPoorZombie::CPoorZombie(void) { initStatus(); } CPoorZombie::~CPoorZombie(void) { } void CPoorZombie::initStatus( void ) { m_zombieType = POOR_ZOMBIE; m_HealthPoint = 40; m_FullHP = m_HealthPoint; m_MovingSpeed = 40.0f; m_AttackPower = 15; m_DefensivePower = 2; m_AttackRange = 30.0f; m_NumberOfTarget = 1; m_AttackSpeed = 1500; m_CreateCost = 50; m_Identity = Zombie; m_SplashAttack = false; ApplyZombieLevel(); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/0.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/1.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/2.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/3.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/4.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/5.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/6.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/7.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/0.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/1.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/2.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/3.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/4.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/5.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/6.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/7.png"); InitZombieAnimation(); } void CPoorZombie::Render() { NNObject::Render(); } void CPoorZombie::Update( float dTime ) { CCharacter::Update(dTime); }
26.015873
63
0.775473
quxn6
16f57350fc1bff2228952b0cc63072a9c9488e02
39,862
cpp
C++
src/Storage_base.cpp
yingjerkao/Cytnx
37ac8493fd7a9ace78c32c9281da25c03542c112
[ "Apache-2.0" ]
null
null
null
src/Storage_base.cpp
yingjerkao/Cytnx
37ac8493fd7a9ace78c32c9281da25c03542c112
[ "Apache-2.0" ]
null
null
null
src/Storage_base.cpp
yingjerkao/Cytnx
37ac8493fd7a9ace78c32c9281da25c03542c112
[ "Apache-2.0" ]
null
null
null
#ifdef UNI_OMP #include <omp.h> #endif #include "Storage.hpp" #include "utils/utils_internal_interface.hpp" #include "utils/vec_print.hpp" using namespace std; namespace cytnx{ //Storage Init interface. //============================= boost::intrusive_ptr<Storage_base> SIInit_cd(){ boost::intrusive_ptr<Storage_base> out(new ComplexDoubleStorage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_cf(){ boost::intrusive_ptr<Storage_base> out(new ComplexFloatStorage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_d(){ boost::intrusive_ptr<Storage_base> out(new DoubleStorage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_f(){ boost::intrusive_ptr<Storage_base> out(new FloatStorage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_u64(){ boost::intrusive_ptr<Storage_base> out(new Uint64Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_i64(){ boost::intrusive_ptr<Storage_base> out(new Int64Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_u32(){ boost::intrusive_ptr<Storage_base> out(new Uint32Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_i32(){ boost::intrusive_ptr<Storage_base> out(new Int32Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_u16(){ boost::intrusive_ptr<Storage_base> out(new Uint16Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_i16(){ boost::intrusive_ptr<Storage_base> out(new Int16Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_b(){ boost::intrusive_ptr<Storage_base> out(new BoolStorage()); return out; } Storage_init_interface::Storage_init_interface(){ USIInit.resize(N_Type); USIInit[this->Double] = SIInit_d; USIInit[this->Float] = SIInit_f; USIInit[this->ComplexDouble] = SIInit_cd; USIInit[this->ComplexFloat] = SIInit_cf; USIInit[this->Uint64] = SIInit_u64; USIInit[this->Int64] = SIInit_i64; USIInit[this->Uint32]= SIInit_u32; USIInit[this->Int32] = SIInit_i32; USIInit[this->Uint16]= SIInit_u16; USIInit[this->Int16] = SIInit_i16; USIInit[this->Bool] = SIInit_b; } //========================== void Storage_base::Init(const unsigned long long &len_in,const int &device){ //cout << "Base.init" << endl; } Storage_base::Storage_base(const unsigned long long &len_in,const int &device){ this->Init(len_in,device); } Storage_base& Storage_base::operator=(Storage_base &Rhs){ cout << "dev"<< endl; return *this; } Storage_base::Storage_base(Storage_base &Rhs){ cout << "dev" << endl; } void Storage_base::resize(const cytnx_uint64 &newsize){ cytnx_error_msg(1, "[ERROR][internal] resize should not be called by base%s","\n"); } boost::intrusive_ptr<Storage_base> Storage_base::astype(const unsigned int &dtype){ boost::intrusive_ptr<Storage_base> out(new Storage_base()); if(dtype == this->dtype) return boost::intrusive_ptr<Storage_base>(this); if(this->device==Device.cpu){ if(utils_internal::uii.ElemCast[this->dtype][dtype]==NULL){ cytnx_error_msg(1, "[ERROR] not support type with dtype=%d",dtype); }else{ utils_internal::uii.ElemCast[this->dtype][dtype](this,out,this->len,1); } }else{ #ifdef UNI_GPU if(utils_internal::uii.cuElemCast[this->dtype][dtype]==NULL){ cytnx_error_msg(1,"[ERROR] not support type with dtype=%d",dtype); }else{ //std::cout << this->device << std::endl; utils_internal::uii.cuElemCast[this->dtype][dtype](this,out,this->len,this->device); } #else cytnx_error_msg(1,"%s","[ERROR][Internal Error] enter GPU section without CUDA support @ Storage.astype()"); #endif } return out; } boost::intrusive_ptr<Storage_base> Storage_base::_create_new_sametype(){ cytnx_error_msg(1,"%s","[ERROR] call _create_new_sametype in base"); return nullptr; } boost::intrusive_ptr<Storage_base> Storage_base::clone(){ boost::intrusive_ptr<Storage_base> out(new Storage_base()); return out; } string Storage_base::dtype_str()const{ return Type.getname(this->dtype); } string Storage_base::device_str()const{ return Device.getname(this->device); } void Storage_base::_Init_byptr(void *rawptr, const unsigned long long &len_in, const int &device, const bool &iscap, const unsigned long long &cap_in){ cytnx_error_msg(1,"%s","[ERROR] call _Init_byptr in base"); } Storage_base::~Storage_base(){ //cout << "delet" << endl; if(Mem != NULL){ if(this->device==Device.cpu){ free(Mem); }else{ #ifdef UNI_GPU cudaFree(Mem); #else cytnx_error_msg(1,"%s","[ERROR] trying to free an GPU memory without CUDA install"); #endif } } } void Storage_base::Move_memory_(const std::vector<cytnx_uint64> &old_shape, const std::vector<cytnx_uint64> &mapper, const std::vector<cytnx_uint64> &invmapper){ cytnx_error_msg(1,"%s","[ERROR] call Move_memory_ directly on Void Storage."); } boost::intrusive_ptr<Storage_base> Storage_base::Move_memory(const std::vector<cytnx_uint64> &old_shape, const std::vector<cytnx_uint64> &mapper, const std::vector<cytnx_uint64> &invmapper){ cytnx_error_msg(1,"%s","[ERROR] call Move_memory_ directly on Void Storage."); return nullptr; } void Storage_base::to_(const int &device){ cytnx_error_msg(1,"%s","[ERROR] call to_ directly on Void Storage."); } boost::intrusive_ptr<Storage_base> Storage_base::to(const int &device){ cytnx_error_msg(1,"%s","[ERROR] call to directly on Void Storage."); return nullptr; } void Storage_base::PrintElem_byShape(std::ostream &os, const std::vector<cytnx_uint64> &shape, const std::vector<cytnx_uint64> &mapper){ cytnx_error_msg(1,"%s","[ERROR] call PrintElem_byShape directly on Void Storage."); } void Storage_base::print_info(){ cout << "dtype : " << this->dtype_str() << endl; cout << "device: " << Device.getname(this->device) << endl; cout << "size : " << this->len << endl; } void Storage_base::print_elems(){ cytnx_error_msg(1,"%s","[ERROR] call print_elems directly on Void Storage."); } void Storage_base::print(){ this->print_info(); this->print_elems(); } // shadow new: // [0] shape: shape of current TN // [x] direct feed-in accessor? accessor->.next() to get next index? no // we dont need mapper's information! // if len(locators) < shape.size(), it means last shape.size()-len(locators) axes are grouped. void Storage_base::GetElem_byShape_v2(boost::intrusive_ptr<Storage_base> &out, const std::vector<cytnx_uint64> &shape, const std::vector<std::vector<cytnx_uint64> > &locators,const cytnx_uint64 &Nunit){ #ifdef UNI_DEBUG cytnx_error_msg(out->dtype != this->dtype, "%s","[ERROR][DEBUG] %s","internal, the output dtype does not match current storage dtype.\n"); #endif cytnx_uint64 TotalElem = 1; for(cytnx_uint32 i=0;i<locators.size();i++){ if(locators[i].size()) TotalElem*=locators[i].size(); else //axis get all! TotalElem*=shape[i]; } //cytnx_error_msg(out->size() != TotalElem, "%s", "[ERROR] internal, the out Storage size does not match the no. of elems calculated from Accessors.%s","\n"); std::vector<cytnx_uint64> c_offj(locators.size()); std::vector<cytnx_uint64> new_offj(locators.size()); cytnx_uint64 caccu=1,new_accu=1; for(cytnx_int32 i=locators.size()-1;i>=0;i--){ c_offj[i] = caccu; caccu*=shape[i]; new_offj[i] = new_accu; if(locators[i].size()) new_accu*=locators[i].size(); else new_accu*=shape[i]; } //std::cout << c_offj << std::endl; //std::cout << new_offj << std::endl; //std::cout << TotalElem << std::endl; if(this->device == Device.cpu){ utils_internal::uii.GetElems_conti_ii[this->dtype](out->Mem,this->Mem,c_offj,new_offj,locators,TotalElem,Nunit); }else{ #ifdef UNI_GPU checkCudaErrors(cudaSetDevice(this->device)); cytnx_error_msg(true,"[Developing][GPU Getelem v2][Note, currently slice on GPU is disabled for further inspection]%s","\n"); //utils_internal::uii.cuGetElems_contiguous_ii[this->dtype](out->Mem,this->Mem,c_offj,new_offj,locators,TotalElem,Nunit); #else cytnx_error_msg(true,"[ERROR][GetElem_byShape] fatal internal%s","the Storage is set on gpu without CUDA support\n"); #endif } } void Storage_base::GetElem_byShape(boost::intrusive_ptr<Storage_base> &out, const std::vector<cytnx_uint64> &shape, const std::vector<cytnx_uint64> &mapper, const std::vector<cytnx_uint64> &len, const std::vector<std::vector<cytnx_uint64> > &locators){ #ifdef UNI_DEBUG cytnx_error_msg(shape.size() != len.size(),"%s","[ERROR][DEBUG] internal Storage, shape.size() != len.size()"); cytnx_error_msg(out->dtype != this->dtype, "%s","[ERROR][DEBUG] %s","internal, the output dtype does not match current storage dtype.\n"); #endif //std::cout <<"=====" << len.size() << " " << locators.size() << std::endl; //create new instance: cytnx_uint64 TotalElem = 1; for(cytnx_uint32 i=0;i<len.size();i++) TotalElem*=len[i]; cytnx_error_msg(out->size() != TotalElem, "%s", "[ERROR] internal, the out Storage size does not match the no. of elems calculated from Accessors.%s","\n"); std::vector<cytnx_uint64> c_offj(shape.size()); std::vector<cytnx_uint64> new_offj(shape.size()); std::vector<cytnx_uint64> offj(shape.size()); cytnx_uint64 accu=1; for(cytnx_int32 i=shape.size()-1;i>=0;i--){ c_offj[i] = accu; accu*=shape[mapper[i]]; } accu = 1; for(cytnx_int32 i=len.size()-1;i>=0;i--){ new_offj[i] = accu; accu*=len[i]; //count-in the mapper: offj[i] = c_offj[mapper[i]]; } if(this->device == Device.cpu){ utils_internal::uii.GetElems_ii[this->dtype](out->Mem,this->Mem,offj,new_offj,locators,TotalElem); }else{ #ifdef UNI_GPU checkCudaErrors(cudaSetDevice(this->device)); utils_internal::uii.cuGetElems_ii[this->dtype](out->Mem,this->Mem,offj,new_offj,locators,TotalElem); #else cytnx_error_msg(true,"[ERROR][GetElem_byShape] fatal internal%s","the Storage is set on gpu without CUDA support\n"); #endif } } // This is deprecated !! void Storage_base::SetElem_byShape(boost::intrusive_ptr<Storage_base> &in, const std::vector<cytnx_uint64> &shape, const std::vector<cytnx_uint64> &mapper, const std::vector<cytnx_uint64> &len, const std::vector<std::vector<cytnx_uint64> > &locators, const bool &is_scalar){ #ifdef UNI_DEBUG cytnx_error_msg(shape.size() != len.size(),"%s","[ERROR][DEBUG] internal Storage, shape.size() != len.size()"); #endif //std::cout <<"=====" << len.size() << " " << locators.size() << std::endl; //create new instance: cytnx_uint64 TotalElem = 1; for(cytnx_uint32 i=0;i<len.size();i++) TotalElem*=len[i]; if(!is_scalar) cytnx_error_msg(in->size() != TotalElem, "%s", "[ERROR] internal, the out Storage size does not match the no. of elems calculated from Accessors.%s","\n"); //[warning] this version only work for scalar currently!. std::vector<cytnx_uint64> c_offj(shape.size()); std::vector<cytnx_uint64> new_offj(shape.size()); std::vector<cytnx_uint64> offj(shape.size()); cytnx_uint64 accu=1; for(cytnx_int32 i=shape.size()-1;i>=0;i--){ c_offj[i] = accu; accu*=shape[i]; } accu = 1; for(cytnx_int32 i=len.size()-1;i>=0;i--){ new_offj[i] = accu; accu*=len[i]; //count-in the mapper: offj[i] = c_offj[mapper[i]]; } if(this->device == Device.cpu){ if(utils_internal::uii.SetElems_ii[in->dtype][this->dtype] == NULL){ cytnx_error_msg(true, "[ERROR] %s","cannot assign complex element to real container.\n"); } utils_internal::uii.SetElems_ii[in->dtype][this->dtype](in->Mem,this->Mem,c_offj,new_offj,locators,TotalElem,is_scalar); }else{ #ifdef UNI_GPU if(utils_internal::uii.cuSetElems_ii[in->dtype][this->dtype] == NULL){ cytnx_error_msg(true, "%s","[ERROR] %s","cannot assign complex element to real container.\n"); } checkCudaErrors(cudaSetDevice(this->device)); utils_internal::uii.cuSetElems_ii[in->dtype][this->dtype](in->Mem,this->Mem,offj,new_offj,locators,TotalElem,is_scalar); #else cytnx_error_msg(true,"[ERROR][SetElem_byShape] fatal internal%s","the Storage is set on gpu without CUDA support\n"); #endif } } void Storage_base::SetElem_byShape_v2(boost::intrusive_ptr<Storage_base> &in, const std::vector<cytnx_uint64> &shape, const std::vector<std::vector<cytnx_uint64> > &locators,const cytnx_uint64 &Nunit, const bool &is_scalar){ // plan: we assume in is contiguous for now! // //std::cout <<"=====" << len.size() << " " << locators.size() << std::endl; //create new instance: cytnx_uint64 TotalElem = 1; for(cytnx_uint32 i=0;i<locators.size();i++){ if(locators[i].size()) TotalElem*=locators[i].size(); else //axis get all! TotalElem*=shape[i]; } //if(!is_scalar) // cytnx_error_msg(in->size() != TotalElem, "%s", "[ERROR] internal, the out Storage size does not match the no. of elems calculated from Accessors.%s","\n"); //[warning] this version only work for scalar currently!. std::vector<cytnx_uint64> c_offj(locators.size()); std::vector<cytnx_uint64> new_offj(locators.size()); cytnx_uint64 caccu=1,new_accu=1; for(cytnx_int32 i=locators.size()-1;i>=0;i--){ c_offj[i] = caccu; caccu*=shape[i]; new_offj[i] = new_accu; if(locators[i].size()) new_accu*=locators[i].size(); else new_accu*=shape[i]; } if(this->device == Device.cpu){ if(utils_internal::uii.SetElems_conti_ii[in->dtype][this->dtype] == NULL){ cytnx_error_msg(true, "[ERROR] %s","cannot assign complex element to real container.\n"); } utils_internal::uii.SetElems_conti_ii[in->dtype][this->dtype](in->Mem,this->Mem,c_offj,new_offj,locators,TotalElem,Nunit,is_scalar); }else{ #ifdef UNI_GPU //if(utils_internal::uii.cuSetElems_ii[in->dtype][this->dtype] == NULL){ // cytnx_error_msg(true, "%s","[ERROR] %s","cannot assign complex element to real container.\n"); //} //checkCudaErrors(cudaSetDevice(this->device)); //utils_internal::uii.cuSetElems_conti_ii[in->dtype][this->dtype](in->Mem,this->Mem,offj,new_offj,locators,TotalElem,Nunit,is_scalar); cytnx_error_msg(true,"[Developing][SetElem on gpu is now down for further inspection]%s","\n"); #else cytnx_error_msg(true,"[ERROR][SetElem_byShape] fatal internal%s","the Storage is set on gpu without CUDA support\n"); #endif } } //generators: void Storage_base::fill(const cytnx_complex128 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_complex64 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_double &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_float &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_int64 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_uint64 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_int32 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_uint32 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_int16 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_uint16 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_bool &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::set_zeros(){ cytnx_error_msg(1,"%s","[ERROR] call set_zeros directly on Void Storage."); } void Storage_base::append(const cytnx_complex128 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_complex64 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_double &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_float &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_int64 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_uint64 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_int32 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_uint32 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_int16 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_uint16 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_bool &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } //instantiation: //================================================ template<> float* Storage_base::data<float>()const{ //check type cytnx_error_msg(dtype != Type.Float, "[ERROR] type mismatch. try to get <float> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<float*>(this->Mem); } template<> double* Storage_base::data<double>()const{ cytnx_error_msg(dtype != Type.Double, "[ERROR] type mismatch. try to get <double> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<double*>(this->Mem); } template<> std::complex<double>* Storage_base::data<std::complex<double> >()const{ cytnx_error_msg(dtype != Type.ComplexDouble, "[ERROR] type mismatch. try to get < complex<double> > type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cytnx_error_msg(this->device!=Device.cpu, "%s","[ERROR] the Storage is on GPU but try to get with CUDA complex type complex<double>. use type <cuDoubleComplex> instead."); cudaDeviceSynchronize(); #endif return static_cast<std::complex<double>*>(this->Mem); } template<> std::complex<float>* Storage_base::data<std::complex<float> >()const{ cytnx_error_msg(dtype != Type.ComplexFloat, "[ERROR] type mismatch. try to get < complex<float> > type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cytnx_error_msg(this->device!=Device.cpu, "%s","[ERROR] the Storage is on GPU but try to get with CUDA complex type complex<float>. use type <cuFloatComplex> instead."); cudaDeviceSynchronize(); #endif return static_cast<std::complex<float>*>(this->Mem); } template<> uint32_t* Storage_base::data<uint32_t>()const{ cytnx_error_msg(dtype != Type.Uint32, "[ERROR] type mismatch. try to get <uint32_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint32_t*>(this->Mem); } template<> int32_t* Storage_base::data<int32_t>()const{ cytnx_error_msg(dtype != Type.Int32, "[ERROR] type mismatch. try to get <int32_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int32_t*>(this->Mem); } template<> uint64_t* Storage_base::data<uint64_t>()const{ cytnx_error_msg(dtype != Type.Uint64, "[ERROR] type mismatch. try to get <uint64_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint64_t*>(this->Mem); } template<> int64_t* Storage_base::data<int64_t>()const{ cytnx_error_msg(dtype != Type.Int64, "[ERROR] type mismatch. try to get <int64_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int64_t*>(this->Mem); } template<> int16_t* Storage_base::data<int16_t>()const{ cytnx_error_msg(dtype != Type.Int16, "[ERROR] type mismatch. try to get <int16_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int16_t*>(this->Mem); } template<> uint16_t* Storage_base::data<uint16_t>()const{ cytnx_error_msg(dtype != Type.Uint16, "[ERROR] type mismatch. try to get <uint16_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint16_t*>(this->Mem); } template<> bool* Storage_base::data<bool>()const{ cytnx_error_msg(dtype != Type.Bool, "[ERROR] type mismatch. try to get <bool> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<bool*>(this->Mem); } // get complex raw pointer using CUDA complex type #ifdef UNI_GPU template<> cuDoubleComplex* Storage_base::data<cuDoubleComplex>()const{ cytnx_error_msg(dtype != Type.ComplexDouble, "[ERROR] type mismatch. try to get <cuDoubleComplex> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->device==Device.cpu, "%s","[ERROR] the Storage is on CPU(Host) but try to get with CUDA complex type cuDoubleComplex. use type <cytnx_complex128> or < complex<double> > instead."); cudaDeviceSynchronize(); return static_cast<cuDoubleComplex*>(this->Mem); } template<> cuFloatComplex* Storage_base::data<cuFloatComplex>()const{ cytnx_error_msg(dtype != Type.ComplexFloat, "[ERROR] type mismatch. try to get <cuFloatComplex> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->device==Device.cpu, "%s","[ERROR] the Storage is on CPU(Host) but try to get with CUDA complex type cuFloatComplex. use type <cytnx_complex64> or < complex<float> > instead."); cudaDeviceSynchronize(); return static_cast<cuFloatComplex*>(this->Mem); } #endif //instantiation: //==================================================== template<> float& Storage_base::at<float>(const cytnx_uint64 &idx) const{ cytnx_error_msg(dtype != Type.Float, "[ERROR] type mismatch. try to get <float> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<float*>(this->Mem)[idx]; } template<> double& Storage_base::at<double>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Double, "[ERROR] type mismatch. try to get <double> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<double*>(this->Mem)[idx]; } template<> std::complex<float>& Storage_base::at<std::complex<float> >(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.ComplexFloat, "[ERROR] type mismatch. try to get < complex<float> > type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<complex<float>*>(this->Mem)[idx]; } template<> std::complex<double>& Storage_base::at<std::complex<double> >(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.ComplexDouble, "[ERROR] type mismatch. try to get < complex<double> > type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<complex<double>*>(this->Mem)[idx]; } template<> uint32_t& Storage_base::at<uint32_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Uint32, "[ERROR] type mismatch. try to get <uint32_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint32_t*>(this->Mem)[idx]; } template<> int32_t& Storage_base::at<int32_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Int32, "[ERROR] type mismatch. try to get <int32_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int32_t*>(this->Mem)[idx]; } template<> uint64_t& Storage_base::at<uint64_t>(const cytnx_uint64 &idx) const{ cytnx_error_msg(dtype != Type.Uint64, "[ERROR] type mismatch. try to get <uint64_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint64_t*>(this->Mem)[idx]; } template<> int64_t& Storage_base::at<int64_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Int64, "[ERROR] type mismatch. try to get <int64_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int64_t*>(this->Mem)[idx]; } template<> uint16_t& Storage_base::at<uint16_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Uint16, "[ERROR] type mismatch. try to get <uint16_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint16_t*>(this->Mem)[idx]; } template<> int16_t& Storage_base::at<int16_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Int16, "[ERROR] type mismatch. try to get <int16_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int16_t*>(this->Mem)[idx]; } template<> bool& Storage_base::at<bool>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Bool, "[ERROR] type mismatch. try to get <bool> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<bool*>(this->Mem)[idx]; } //instantiation: //==================================================== template<> float& Storage_base::back<float>() const{ cytnx_error_msg(dtype != Type.Float, "[ERROR] type mismatch. try to get <float> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<float*>(this->Mem)[this->len-1]; } template<> double& Storage_base::back<double>()const{ cytnx_error_msg(dtype != Type.Double, "[ERROR] type mismatch. try to get <double> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<double*>(this->Mem)[this->len-1]; } template<> std::complex<float>& Storage_base::back<std::complex<float> >()const{ cytnx_error_msg(dtype != Type.ComplexFloat, "[ERROR] type mismatch. try to get < complex<float> > type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<complex<float>*>(this->Mem)[this->len-1]; } template<> std::complex<double>& Storage_base::back<std::complex<double> >()const{ cytnx_error_msg(dtype != Type.ComplexDouble, "[ERROR] type mismatch. try to get < complex<double> > type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<complex<double>*>(this->Mem)[this->len-1]; } template<> uint32_t& Storage_base::back<uint32_t>()const{ cytnx_error_msg(dtype != Type.Uint32, "[ERROR] type mismatch. try to get <uint32_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint32_t*>(this->Mem)[this->len-1]; } template<> int32_t& Storage_base::back<int32_t>()const{ cytnx_error_msg(dtype != Type.Int32, "[ERROR] type mismatch. try to get <int32_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int32_t*>(this->Mem)[this->len-1]; } template<> uint64_t& Storage_base::back<uint64_t>() const{ cytnx_error_msg(dtype != Type.Uint64, "[ERROR] type mismatch. try to get <uint64_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint64_t*>(this->Mem)[this->len-1]; } template<> int64_t& Storage_base::back<int64_t>()const{ cytnx_error_msg(dtype != Type.Int64, "[ERROR] type mismatch. try to get <int64_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int64_t*>(this->Mem)[this->len-1]; } template<> uint16_t& Storage_base::back<uint16_t>()const{ cytnx_error_msg(dtype != Type.Uint16, "[ERROR] type mismatch. try to get <uint16_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint16_t*>(this->Mem)[this->len-1]; } template<> int16_t& Storage_base::back<int16_t>()const{ cytnx_error_msg(dtype != Type.Int16, "[ERROR] type mismatch. try to get <int16_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int16_t*>(this->Mem)[this->len-1]; } template<> bool& Storage_base::back<bool>()const{ cytnx_error_msg(dtype != Type.Bool, "[ERROR] type mismatch. try to get <bool> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<bool*>(this->Mem)[this->len-1]; } void Storage_base::_cpy_bool(void *ptr, const std::vector<cytnx_bool> &vin){ bool *tmp = static_cast<bool*>(ptr); #ifdef UNI_OMP #pragma omp parallel for schedule(dynamic) #endif for(cytnx_uint64 i=0;i<vin.size();i++){ tmp[i] = vin[i]; } } boost::intrusive_ptr<Storage_base> Storage_base::real(){ cytnx_error_msg(true,"[ERROR] trying to call Storage.real() from void Storage%s","\n"); } boost::intrusive_ptr<Storage_base> Storage_base::imag(){ cytnx_error_msg(true,"[ERROR] trying to call Storage.imag() from void Storage%s","\n"); } Scalar Storage_base::get_item(const cytnx_uint64 &idx) const{ cytnx_error_msg(true,"[ERROR] trying to call Storage.get_item() from void Storage%s","\n"); return Scalar(); } void Storage_base::set_item(const cytnx_uint64 &idx,const Scalar &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_complex128 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_complex64 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_double &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_float &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_int64 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_uint64 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_int32 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_uint32 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_int16 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_uint16 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_bool &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } }//namespace cytnx;
43.565027
278
0.6086
yingjerkao
16fafdd8af96e9317de9b4a6cf6798a73b43c408
7,601
cpp
C++
tree.cpp
ramenhut/simple-rdf
ca6f9fb52dfa2fb464a0593ce71972d263dfd92c
[ "BSD-2-Clause" ]
3
2019-08-18T05:44:42.000Z
2019-09-02T06:19:30.000Z
tree.cpp
ramenhut/simple-rdf
ca6f9fb52dfa2fb464a0593ce71972d263dfd92c
[ "BSD-2-Clause" ]
null
null
null
tree.cpp
ramenhut/simple-rdf
ca6f9fb52dfa2fb464a0593ce71972d263dfd92c
[ "BSD-2-Clause" ]
null
null
null
#include "tree.h" #include "numeric.h" namespace base { float32 ComputeInformationGain(const Histogram& parent, const Histogram& left, const Histogram& right) { // Our computations use integer variables but must occur at float precision. float32 parent_total = parent.GetSampleTotal(); return parent.GetEntropy() - (((left.GetSampleTotal() / parent_total) * (left.GetEntropy())) + ((right.GetSampleTotal() / parent_total) * (right.GetEntropy()))); } bool DecisionNode::Train(const DecisionTreeParams& params, uint32 depth, vector<TrainSet>* samples, const Histogram& sample_histogram, string* error) { if (!samples) { if (error) { *error = "Invalid parameter(s) specified to DecisionNode::Train."; } return false; } // Cache our incoming histogram, which defines the statitics at the // current node. This is useful during training, and potentially useful // for classification if the current node ends up being a leaf. histogram_ = sample_histogram; // If we've reached our exit criteria then we early exit, leaving this // node as a leaf in the tree. if (depth >= params.max_tree_depth || !samples->size() || samples->size() < params.min_sample_count) { is_leaf_ = true; return true; } float32 node_entropy = histogram_.GetEntropy(); // If our incoming entropy is zero then our data set is of uniform // type, and we can declare this node a leaf. if (0.0f == node_entropy || -0.0f == node_entropy) { is_leaf_ = true; return true; } // Perform a maximum of params.node_trial_count trials to find // a best candidate split function for this node. We're guaranteed // to finish with a candidate, even if it's only a local best. float32 best_info_gain = -1.0f; Histogram best_left_hist, best_right_hist; vector<TrainSet> best_left_samples, best_right_samples; SplitFunction best_split_function, trial_split_function; for (uint32 i = 0; i < params.node_trial_count; i++) { Histogram trial_left_hist, trial_right_hist; vector<TrainSet> trial_left_samples, trial_right_samples; trial_left_hist.Initialize(params.class_count); trial_right_hist.Initialize(params.class_count); trial_left_samples.reserve(samples->size()); trial_right_samples.reserve(samples->size()); trial_split_function.Initialize(params.visual_search_radius); // Iterate over all samples, performing split. True goes right. for (uint32 j = 0; j < samples->size(); j++) { SplitCoord current_coord = samples->at(j).coord; uint8 sample_label = samples->at(j).data_source->label.GetPixel( current_coord.x, current_coord.y); if (trial_split_function.Split(current_coord, &samples->at(j).data_source->image)) { trial_right_samples.push_back(samples->at(j)); trial_right_hist.IncrementValue(sample_label); } else { trial_left_samples.push_back(samples->at(j)); trial_left_hist.IncrementValue(sample_label); } } float32 current_info_gain = ComputeInformationGain(histogram_, trial_left_hist, trial_right_hist); if (current_info_gain >= best_info_gain) { best_info_gain = current_info_gain; best_left_hist = trial_left_hist; best_right_hist = trial_right_hist; best_left_samples = std::move(trial_left_samples); best_right_samples = std::move(trial_right_samples); best_split_function = trial_split_function; // If our current info gain equals entropy (i.e. both buckets have zero // entropy), then we can immediately select this as our best option. if (current_info_gain == node_entropy) { break; } } } // Bind the best split function that we found during our trials. function_ = best_split_function; is_leaf_ = false; // We have our best so we allocate children and attempt to train them. left_child_.reset(new DecisionNode); right_child_.reset(new DecisionNode); if (!left_child_ || !right_child_) { if (error) { *error = "Failed to allocate child nodes."; } return false; } if (!left_child_->Train(params, depth + 1, &best_left_samples, best_left_hist, error) || !right_child_->Train(params, depth + 1, &best_right_samples, best_right_hist, error)) { return false; } return true; } bool DecisionNode::Classify(const SplitCoord& coord, Image* data_source, Histogram* output, string* error) { if ((!!left_child_) ^ (!!right_child_)) { if (error) { *error = "Invalid tree structure."; } return false; } if (!output || !data_source) { if (error) { *error = "Invalid parameter specified to DecisionNode::Classify."; } return false; } if (is_leaf_) { *output = histogram_; return true; } if (function_.Split(coord, data_source)) { return right_child_->Classify(coord, data_source, output); } return left_child_->Classify(coord, data_source, output); } bool DecisionTree::Train(const DecisionTreeParams& params, vector<ImageSet>* training_data, uint32 training_start_index, uint32 training_count, string* error) { if (training_data->empty() || training_count > training_data->size()) { if (error) { *error = "Invalid parameter specified to DecisionTree::Train."; } return false; } Histogram initial_histogram(params.class_count); vector<TrainSet> tree_training_set; // Cache a copy of our tree params for later use during classification. params_ = params; // This is one of the most expensive operations in our system, so we // estimate the required size and reserve memory for it. uint64 required_size = training_count * training_data->at(0).image.width * training_data->at(0).image.height; tree_training_set.reserve(required_size); for (uint32 i = 0; i < training_count; i++) { uint32 index = (training_start_index + i) % training_data->size(); uint32 width = training_data->at(index).image.width; uint32 height = training_data->at(index).image.height; for (uint32 y = 0; y < height; y++) for (uint32 x = 0; x < width; x++) { uint8 label_value = training_data->at(index).label.GetPixel(x, y); tree_training_set.emplace_back(&training_data->at(index), x, y); initial_histogram.IncrementValue(label_value); } } root_node_.reset(new DecisionNode); if (!root_node_) { if (error) { *error = "Failed allocation of decision tree root node."; } return false; } return root_node_->Train(params, 0, &tree_training_set, initial_histogram); } bool DecisionTree::ClassifyPixel(uint32 x, uint32 y, Image* input, Histogram* output, string* error) { if (!root_node_) { if (error) { *error = "Invalid root node detected."; } return false; } if (!input || !output) { if (error) { *error = "Invalid parameter specified to DecisionTree::ClassifyPixel."; } return false; } SplitCoord coord = {x, y}; return root_node_->Classify(coord, input, output, error); } } // namespace base
34.238739
81
0.641626
ramenhut
e5054599457e0656b4c7ef8ba221feaef6d81690
7,404
cpp
C++
ROS/topico/src/printint.cpp
zal-jlange/TopiCo
d9cf99d4510599c2fc506cbe866cdb8861f360c8
[ "BSD-3-Clause" ]
53
2021-03-16T09:55:42.000Z
2022-02-15T22:10:44.000Z
ROS/topico/src/printint.cpp
zal-jlange/TopiCo
d9cf99d4510599c2fc506cbe866cdb8861f360c8
[ "BSD-3-Clause" ]
14
2021-03-23T17:52:12.000Z
2021-08-17T01:00:32.000Z
ROS/topico/src/printint.cpp
zal-jlange/TopiCo
d9cf99d4510599c2fc506cbe866cdb8861f360c8
[ "BSD-3-Clause" ]
14
2021-04-11T06:12:24.000Z
2022-03-22T12:21:51.000Z
// // Academic License - for use in teaching, academic research, and meeting // course requirements at degree granting institutions only. Not for // government, commercial, or other organizational use. // // printint.cpp // // Code generation for function 'printint' // // Include files #include "printint.h" #include "i64ddiv.h" #include "rt_nonfinite.h" #include "topico_wrapper_data.h" #include "topico_wrapper_rtwutil.h" #include "topico_wrapper_types.h" #include <cmath> #include <sstream> #include <stdexcept> #include <stdio.h> #include <string> // Function Declarations static unsigned long _u64_d_(double b); static unsigned long _u64_div__(unsigned long b, unsigned long c); static unsigned long _u64_minus__(unsigned long b, unsigned long c); static unsigned long _u64_s32_(int b); static void mul_wide_u64(unsigned long in0, unsigned long in1, unsigned long *ptrOutBitsHi, unsigned long *ptrOutBitsLo); static unsigned long mulv_u64(unsigned long a, unsigned long b); static void rtDivisionByZeroErrorN(); // Function Definitions static unsigned long _u64_d_(double b) { unsigned long a; a = static_cast<unsigned long>(b); if ((b < 0.0) || (a != std::floor(b))) { rtIntegerOverflowErrorN(); } return a; } static unsigned long _u64_div__(unsigned long b, unsigned long c) { if (c == 0UL) { rtDivisionByZeroErrorN(); } return b / c; } static unsigned long _u64_minus__(unsigned long b, unsigned long c) { unsigned long a; a = b - c; if (b < c) { rtIntegerOverflowErrorN(); } return a; } static unsigned long _u64_s32_(int b) { unsigned long a; a = static_cast<unsigned long>(b); if (b < 0) { rtIntegerOverflowErrorN(); } return a; } static void mul_wide_u64(unsigned long in0, unsigned long in1, unsigned long *ptrOutBitsHi, unsigned long *ptrOutBitsLo) { unsigned long in0Hi; unsigned long in0Lo; unsigned long in1Hi; unsigned long in1Lo; unsigned long outBitsLo; unsigned long productHiLo; unsigned long productLoHi; in0Hi = in0 >> 32UL; in0Lo = in0 & 4294967295UL; in1Hi = in1 >> 32UL; in1Lo = in1 & 4294967295UL; productHiLo = in0Hi * in1Lo; productLoHi = in0Lo * in1Hi; in0Lo *= in1Lo; in1Lo = 0UL; outBitsLo = in0Lo + (productLoHi << 32UL); if (outBitsLo < in0Lo) { in1Lo = 1UL; } in0Lo = outBitsLo; outBitsLo += productHiLo << 32UL; if (outBitsLo < in0Lo) { in1Lo++; } *ptrOutBitsHi = ((in1Lo + in0Hi * in1Hi) + (productLoHi >> 32UL)) + (productHiLo >> 32UL); *ptrOutBitsLo = outBitsLo; } static unsigned long mulv_u64(unsigned long a, unsigned long b) { unsigned long result; unsigned long u64_chi; mul_wide_u64(a, b, &u64_chi, &result); if (u64_chi) { rtIntegerOverflowErrorN(); } return result; } static void rtDivisionByZeroErrorN() { std::stringstream outStream; outStream << "Division by zero detected.\nEarly termination due to division " "by zero."; outStream << "\n"; throw std::runtime_error(outStream.str()); } void printint(unsigned int number) { unsigned long b_number; unsigned long divisor; bool b_leading; b_number = number; b_leading = true; divisor = 10000000000000000000UL; while (divisor >= 1UL) { unsigned long d; if (divisor == 0UL) { d_rtErrorWithMessageID(f_emlrtRTEI.fName, f_emlrtRTEI.lineNo); } d = _u64_div__(b_number, divisor); b_leading = ((d == 0UL) && b_leading); if (!b_leading) { b_number = _u64_minus__(b_number, mulv_u64(d, divisor)); switch (d) { case 0UL: printf("0"); fflush(stdout); break; case 1UL: printf("1"); fflush(stdout); break; case 2UL: printf("2"); fflush(stdout); break; case 3UL: printf("3"); fflush(stdout); break; case 4UL: printf("4"); fflush(stdout); break; case 5UL: printf("5"); fflush(stdout); break; case 6UL: printf("6"); fflush(stdout); break; case 7UL: printf("7"); fflush(stdout); break; case 8UL: printf("8"); fflush(stdout); break; case 9UL: printf("9"); fflush(stdout); break; } } divisor = coder::internal::i64ddiv(divisor); } if (b_leading) { printf("0"); fflush(stdout); } } void printint(int number) { unsigned long b_number; unsigned long divisor; bool b_leading; b_number = _u64_s32_(number); b_leading = true; divisor = 10000000000000000000UL; while (divisor >= 1UL) { unsigned long d; if (divisor == 0UL) { d_rtErrorWithMessageID(f_emlrtRTEI.fName, f_emlrtRTEI.lineNo); } d = _u64_div__(b_number, divisor); b_leading = ((d == 0UL) && b_leading); if (!b_leading) { b_number = _u64_minus__(b_number, mulv_u64(d, divisor)); switch (d) { case 0UL: printf("0"); fflush(stdout); break; case 1UL: printf("1"); fflush(stdout); break; case 2UL: printf("2"); fflush(stdout); break; case 3UL: printf("3"); fflush(stdout); break; case 4UL: printf("4"); fflush(stdout); break; case 5UL: printf("5"); fflush(stdout); break; case 6UL: printf("6"); fflush(stdout); break; case 7UL: printf("7"); fflush(stdout); break; case 8UL: printf("8"); fflush(stdout); break; case 9UL: printf("9"); fflush(stdout); break; } } divisor = coder::internal::i64ddiv(divisor); } if (b_leading) { printf("0"); fflush(stdout); } } void printint(double number) { unsigned long b_number; unsigned long divisor; bool b_leading; b_number = _u64_d_(rt_roundd_snf(std::abs(number))); b_leading = true; divisor = 10000000000000000000UL; while (divisor >= 1UL) { unsigned long d; if (divisor == 0UL) { d_rtErrorWithMessageID(f_emlrtRTEI.fName, f_emlrtRTEI.lineNo); } d = _u64_div__(b_number, divisor); b_leading = ((d == 0UL) && b_leading); if (!b_leading) { b_number = _u64_minus__(b_number, mulv_u64(d, divisor)); switch (d) { case 0UL: printf("0"); fflush(stdout); break; case 1UL: printf("1"); fflush(stdout); break; case 2UL: printf("2"); fflush(stdout); break; case 3UL: printf("3"); fflush(stdout); break; case 4UL: printf("4"); fflush(stdout); break; case 5UL: printf("5"); fflush(stdout); break; case 6UL: printf("6"); fflush(stdout); break; case 7UL: printf("7"); fflush(stdout); break; case 8UL: printf("8"); fflush(stdout); break; case 9UL: printf("9"); fflush(stdout); break; } } divisor = coder::internal::i64ddiv(divisor); } if (b_leading) { printf("0"); fflush(stdout); } } // End of code generation (printint.cpp)
21.905325
80
0.581037
zal-jlange
e507364b38266b298cc052de7af6ff34572656de
528
cpp
C++
Code/Chapter-4/rayaabb.cpp
SampleText2k77/graphics-book
2b6ff89be1c27683744a8b64145d5a6a9de37d5d
[ "MIT" ]
16
2019-07-09T11:49:13.000Z
2022-02-22T03:01:30.000Z
Code/Chapter-4/rayaabb.cpp
SampleText2k77/graphics-book
2b6ff89be1c27683744a8b64145d5a6a9de37d5d
[ "MIT" ]
null
null
null
Code/Chapter-4/rayaabb.cpp
SampleText2k77/graphics-book
2b6ff89be1c27683744a8b64145d5a6a9de37d5d
[ "MIT" ]
5
2019-09-09T17:44:50.000Z
2021-04-29T20:16:51.000Z
#define GLM_FORCE_RADIANS #define GLM_SWIZZLE #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/gtx/quaternion.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <glm/geometric.hpp> #include "bbox.h" inline glm::vec3 closestPoint ( const glm::vec3& n, const bbox& box ) { return glm::vec3 ( n.x <= 0 ? box.getMaxPoint().x : box.getMinPoint().x, n.y <= 0 ? box.getMaxPoint().y : box.getMinPoint().y, n.z <= 0 ? box.getMaxPoint().z : box.getMinPoint().z ); }
31.058824
82
0.617424
SampleText2k77
e508d32acc6e92da93071f9728c4abfaaa042691
325
cpp
C++
Cpp/1189.maximum-number-of-ballons.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/1189.maximum-number-of-ballons.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/1189.maximum-number-of-ballons.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: int maxNumberOfBalloons(string text) { vector<int> cnts(26, 0); for (char c : text) { cnts[c-'a'] ++; } vector<int> ballon{cnts[0], cnts[1], cnts[11]/2, cnts[14]/2, cnts[13]}; return *min_element(ballon.begin(), ballon.end()); } };
27.083333
79
0.513846
zszyellow
e50da8dce16ecc613a3f2edd07f12ed8d9459177
532
cpp
C++
source/algorithms/gmi.cpp
tasseff/gomory
d18b9aac036d2ef6d8c582a26f68060994590eba
[ "MIT" ]
2
2017-04-27T23:24:32.000Z
2018-09-20T21:19:34.000Z
source/algorithms/gmi.cpp
tasseff/gomory
d18b9aac036d2ef6d8c582a26f68060994590eba
[ "MIT" ]
null
null
null
source/algorithms/gmi.cpp
tasseff/gomory
d18b9aac036d2ef6d8c582a26f68060994590eba
[ "MIT" ]
null
null
null
#include <common/document.h> #include <common/error.h> #include "gomory.h" int main(int argc, char* argv[]) { // Check if a JSON file has been specified. if (argc <= 1) { PrintErrorAndExit("JSON file has not been specified."); } // Read the scenario file. File model_file(argv[1]); // Parse the scenario file as a JSON document. Document json(model_file); // Set up the model. Gomory model(json.root["parameters"], argv[2], argv[3]); // Run the model. model.Run(); // Program executed successfully. return 0; }
20.461538
57
0.676692
tasseff
e5141d2137f8d0fee721a0dec66e794ad3fb72de
3,721
cpp
C++
tests/test_user_defined.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
tests/test_user_defined.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
tests/test_user_defined.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "wad/integer.hpp" #include "wad/floating.hpp" #include "wad/string.hpp" #include "wad/in_place.hpp" #include "wad/archive.hpp" #include "wad/interface.hpp" #include "utility.hpp" namespace extlib { struct X { std::string s; std::int32_t i; double d; template<typename Arc> bool archive(Arc& arc) { return wad::archive<wad::type::map>(arc, "s", s, "i", i, "d", d); } }; struct Y { std::string s; std::int32_t i; double d; template<typename Arc> bool archive(Arc& arc) { return wad::archive<wad::type::array>(arc, s, i, d); } }; struct Z { std::string s; std::int32_t i; double d; template<typename Arc> bool save(Arc& arc) const { return wad::save<wad::type::map>(arc, "s", s, "i", i, "d", d); } template<typename Arc> bool load(Arc& arc) { return wad::load<wad::type::map>(arc, "s", s, "i", i, "d", d); } }; struct W { std::string s; std::int32_t i; double d; template<typename Arc> bool save(Arc& arc) const { return wad::save<wad::type::array>(arc, s, i, d); } template<typename Arc> bool load(Arc& arc) { return wad::load<wad::type::array>(arc, s, i, d); } }; struct V { std::string s; std::int32_t i; double d; }; template<typename Arc> bool save(Arc& arc, const V& v) { return wad::save<wad::type::array>(arc, v.s, v.i, v.d); } template<typename Arc> bool load(Arc& arc, V& v) { return wad::load<wad::type::array>(arc, v.s, v.i, v.d); } } // extlib TEST_CASE( "user_defined<map>::archive()", "[user_defined<map>::archive()]" ) { extlib::X x{"foo", 42, 3.14}; { extlib::X x1; wad::test_write_archive warc; wad::save(warc, x); wad::test_read_archive rarc(warc); wad::load(rarc, x1); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } { extlib::X x1; wad::test_write_archive warc; wad::archive(warc, x); wad::test_read_archive rarc(warc); wad::archive(rarc, x1); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } } TEST_CASE( "user_defined<array>::archive()", "[user_defined<array>::archive()]" ) { extlib::Y x{"foo", 42, 3.14}; { extlib::Y x1; wad::test_write_archive warc; wad::save(warc, x); wad::test_read_archive rarc(warc); wad::load(rarc, x1); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } { extlib::Y x1; wad::test_write_archive warc; wad::archive(warc, x); wad::test_read_archive rarc(warc); wad::archive(rarc, x1); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } } TEST_CASE( "user_defined<map>::save/load()", "[user_defined<map>::save/load()]" ) { const extlib::Z x{"foo", 42, 3.14}; const extlib::Z x1 = wad::save_load(x); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } TEST_CASE( "user_defined<array>::save/load()", "[user_defined<array>::save/load()]" ) { const extlib::W x{"foo", 42, 3.14}; const extlib::W x1 = wad::save_load(x); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } TEST_CASE( "save/load(user_defined<array>)", "[save/load(user_defined<array>)]" ) { const extlib::V x{"foo", 42, 3.14}; const extlib::V x1 = wad::save_load(x); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); }
21.262857
85
0.536684
ToruNiina
e51437479bf53620e86d489a138390efad5c728b
362
cpp
C++
book/Chap3/trythis.cpp
mjakebarrington/CPP-Exercises
9bb01f66ae9861c4d5323738fb478f15ad7e691c
[ "MIT" ]
null
null
null
book/Chap3/trythis.cpp
mjakebarrington/CPP-Exercises
9bb01f66ae9861c4d5323738fb478f15ad7e691c
[ "MIT" ]
null
null
null
book/Chap3/trythis.cpp
mjakebarrington/CPP-Exercises
9bb01f66ae9861c4d5323738fb478f15ad7e691c
[ "MIT" ]
null
null
null
/* * In chapter 3's "Try This" exercise, students are asked to print someones name out in months. */ #include <iostream> using namespace std; int main() { cout << "What is your name and age in years? \n"; string name; double age; cin >> name >> age; age *= 12; cout << "Hello, " << name << ", you are roughly " << age << " months old!\n"; return 0; }
21.294118
95
0.616022
mjakebarrington
e5167bc0f2f4370b07d763432feb78963c1397b6
487
hpp
C++
Chess/connector.hpp
classix-ps/Chess
1165cb3e5aab67de562b029f65c80f5156d6c26b
[ "CC-BY-4.0" ]
null
null
null
Chess/connector.hpp
classix-ps/Chess
1165cb3e5aab67de562b029f65c80f5156d6c26b
[ "CC-BY-4.0" ]
null
null
null
Chess/connector.hpp
classix-ps/Chess
1165cb3e5aab67de562b029f65c80f5156d6c26b
[ "CC-BY-4.0" ]
null
null
null
#pragma once #include <windows.h> #include <stdio.h> #include <iostream> #include <string> class Engine { public: Engine(LPCWSTR); void ConnectToEngine(); std::string getNextMove(std::string); void CloseConnection(); private: LPCWSTR enginePath; STARTUPINFO sti = { 0 }; SECURITY_ATTRIBUTES sats = { 0 }; PROCESS_INFORMATION pi = { 0 }; HANDLE pipin_w, pipin_r, pipout_w, pipout_r; BYTE buffer[8192]; DWORD writ, excode, read, available; };
21.173913
48
0.669405
classix-ps
e516cf6690454e4c5011ee2ba91596f67bf58444
1,822
cpp
C++
bruter/bruter/tests/bruter3.cpp
flyyee/riwlan-brute
0c886d48518a7f5258751c6a1dc43c51fa7f7fa1
[ "MIT" ]
null
null
null
bruter/bruter/tests/bruter3.cpp
flyyee/riwlan-brute
0c886d48518a7f5258751c6a1dc43c51fa7f7fa1
[ "MIT" ]
null
null
null
bruter/bruter/tests/bruter3.cpp
flyyee/riwlan-brute
0c886d48518a7f5258751c6a1dc43c51fa7f7fa1
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <fstream> #include <algorithm> #include <sstream> #include <iterator> void generate_words(const std::vector<char> &alphabet, size_t &word_length, std::vector<std::string> &results) { std::vector<size_t> index(word_length, 0); for (;;) { std::string word(index.size(), ' '); for (size_t i = 0; i < index.size(); ++i) { word[i] = alphabet[index[i]]; } results.emplace_back(word); for (int i = index.size() - 1; ; --i) { if (i < 0) { return; } ++index[i]; if (index[i] == alphabet.size()) { index[i] = 0; } else { break; } } } } int main(int argc, char **argv) { std::ifstream infile(argv[1], std::ios::in | std::ifstream::binary); std::string line; while (infile.good() && getline(infile, line)) { size_t word_length = std::stoi(line.substr(0, line.find(','))); std::string letters = line.substr(line.find(',') + 1); std::vector<char> alphabet; for (const auto &it : letters) { alphabet.push_back(it); } std::sort(alphabet.begin(), alphabet.end()); auto last = std::unique(alphabet.begin(), alphabet.end()); alphabet.erase(last, alphabet.end()); std::vector<std::string> results; generate_words(alphabet, word_length, results); std::ostringstream result_line; std::copy(results.begin(), results.end() - 1, std::ostream_iterator<std::string>(result_line, ",")); result_line << results.back(); std::cout << result_line.str() << "\n"; } }
25.305556
110
0.513172
flyyee
e51922575b32b9367b11b762324e23a9a87793cc
5,936
cpp
C++
WaveSabreCore/src/Twister.cpp
armak/WaveSabre
e72bf68e3bdd215cf8d310d106839cb234587793
[ "MIT" ]
3
2019-03-01T21:33:54.000Z
2021-09-16T09:40:56.000Z
WaveSabreCore/src/Twister.cpp
djh0ffman/WaveSabre
6a3885134fd9ef1ba31d60e7bb2be41de68f1a3b
[ "MIT" ]
null
null
null
WaveSabreCore/src/Twister.cpp
djh0ffman/WaveSabre
6a3885134fd9ef1ba31d60e7bb2be41de68f1a3b
[ "MIT" ]
1
2021-01-02T13:28:55.000Z
2021-01-02T13:28:55.000Z
#include <WaveSabreCore/Twister.h> #include <WaveSabreCore/Helpers.h> int const lookAhead = 4; namespace WaveSabreCore { Twister::Twister() : Device((int)ParamIndices::NumParams) { type = 0; amount = 0; feedback = 0.0f; spread = Spread::Mono; vibratoFreq = Helpers::ParamToVibratoFreq(0.0f); vibratoAmount = 0.0f; vibratoPhase = 0.0; lowCutFreq = 20.0f; highCutFreq = 20000.0f- 20.0f; dryWet = .5f; leftBuffer.SetLength(1000); rightBuffer.SetLength(1000); lastLeft = 0.0f; lastRight = 0.0f; for (int i = 0; i < 2; i++) { lowCutFilter[i].SetType(StateVariableFilterType::Highpass); highCutFilter[i].SetType(StateVariableFilterType::Lowpass); } } Twister::~Twister() { } void Twister::Run(double songPosition, float **inputs, float **outputs, int numSamples) { double vibratoDelta = (vibratoFreq / Helpers::CurrentSampleRate) * 0.25f; float outputLeft = 0.0f; float outputRight = 0.0f; float positionLeft = 0.0f; float positionRight = 0.0f; for (int i = 0; i < 2; i++) { lowCutFilter[i].SetFreq(lowCutFreq); highCutFilter[i].SetFreq(highCutFreq); } for (int i = 0; i < numSamples; i++) { float leftInput = inputs[0][i]; float rightInput = inputs[1][i]; double freq = Helpers::FastSin(vibratoPhase) * vibratoAmount; switch (spread) { case Spread::Mono: default: positionLeft = Helpers::Clamp((amount + (float)freq), 0.0f, 1.0f); positionRight = positionLeft; break; case Spread::FullInvert: positionLeft = Helpers::Clamp((amount + (float)freq), 0.0f, 1.0f); positionRight = (1.0f - Helpers::Clamp((amount + (float)freq), 0.0f, 1.0f)); break; case Spread::ModInvert: positionLeft = Helpers::Clamp((amount + (float)freq), 0.0f, 1.0f); positionRight = Helpers::Clamp((amount - (float)freq), 0.0f, 1.0f); break; } switch (type) { case 0: positionLeft *= 132.0f; positionRight *= 132.0f; outputLeft = highCutFilter[0].Next(lowCutFilter[0].Next(leftBuffer.ReadPosition(positionLeft + 2))); outputRight = highCutFilter[1].Next(lowCutFilter[1].Next(rightBuffer.ReadPosition(positionRight + 2))); leftBuffer.WriteSample(leftInput + (outputLeft * feedback)); rightBuffer.WriteSample(rightInput + (outputRight * feedback)); break; case 1: positionLeft *= 132.0f; positionRight *= 132.0f; outputLeft = highCutFilter[0].Next(lowCutFilter[0].Next(leftBuffer.ReadPosition(positionLeft + 2))); outputRight = highCutFilter[1].Next(lowCutFilter[1].Next(rightBuffer.ReadPosition(positionRight + 2))); leftBuffer.WriteSample(leftInput - (outputLeft * feedback)); rightBuffer.WriteSample(rightInput - (outputRight * feedback)); break; case 2: for (int i = 0; i<6; i++) allPassLeft[i].Delay(positionLeft); for (int i = 0; i<6; i++) allPassRight[i].Delay(positionRight); outputLeft = highCutFilter[0].Next(lowCutFilter[0].Next(AllPassUpdateLeft(leftInput + lastLeft * feedback))); outputRight = highCutFilter[1].Next(lowCutFilter[1].Next(AllPassUpdateRight(rightInput + lastRight * feedback))); lastLeft = outputLeft; lastRight = outputRight; break; case 3: for (int i = 0; i<6; i++) allPassLeft[i].Delay(positionLeft); for (int i = 0; i<6; i++) allPassRight[i].Delay(positionRight); outputLeft = highCutFilter[0].Next(lowCutFilter[0].Next(AllPassUpdateLeft(leftInput - lastLeft * feedback))); outputRight = highCutFilter[1].Next(lowCutFilter[1].Next(AllPassUpdateRight(rightInput - lastRight * feedback))); lastLeft = outputLeft; lastRight = outputRight; break; default: outputLeft = 0.0f; outputRight = 0.0f; break; } outputs[0][i] = (leftInput * (1.0f - dryWet)) + (outputLeft * dryWet); outputs[1][i] = (rightInput * (1.0f - dryWet)) + (outputRight * dryWet); vibratoPhase += vibratoDelta; } } float Twister::AllPassUpdateLeft(float input) { return( allPassLeft[0].Update( allPassLeft[1].Update( allPassLeft[2].Update( allPassLeft[3].Update( allPassLeft[4].Update( allPassLeft[5].Update(input))))))); } float Twister::AllPassUpdateRight(float input) { return( allPassRight[0].Update( allPassRight[1].Update( allPassRight[2].Update( allPassRight[3].Update( allPassRight[4].Update( allPassRight[5].Update(input))))))); } void Twister::SetParam(int index, float value) { switch ((ParamIndices)index) { case ParamIndices::Type: type = (int)(value * 3.0f); break; case ParamIndices::Amount: amount = value; break; case ParamIndices::Feedback: feedback = value; break; case ParamIndices::Spread: spread = Helpers::ParamToSpread(value); break; case ParamIndices::VibratoFreq: vibratoFreq = Helpers::ParamToVibratoFreq(value); break; case ParamIndices::VibratoAmount: vibratoAmount = value; break; case ParamIndices::LowCutFreq: lowCutFreq = Helpers::ParamToFrequency(value); break; case ParamIndices::HighCutFreq: highCutFreq = Helpers::ParamToFrequency(value); break; case ParamIndices::DryWet: dryWet = value; break; } } float Twister::GetParam(int index) const { switch ((ParamIndices)index) { case ParamIndices::Type: default: return type / 3.0f; case ParamIndices::Amount: return amount; case ParamIndices::Feedback: return feedback; case ParamIndices::Spread: return Helpers::SpreadToParam(spread); case ParamIndices::VibratoFreq: return Helpers::VibratoFreqToParam(vibratoFreq); case ParamIndices::VibratoAmount: return vibratoAmount; case ParamIndices::LowCutFreq: return Helpers::FrequencyToParam(lowCutFreq); case ParamIndices::HighCutFreq: return Helpers::FrequencyToParam(highCutFreq); case ParamIndices::DryWet: return dryWet; } } }
32.26087
118
0.670654
armak
e51931254833e9daae0b21d79018cb7aea95ea64
2,903
cpp
C++
tests/rwops/load/main.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
8
2018-04-21T07:49:58.000Z
2019-02-21T15:04:28.000Z
tests/rwops/load/main.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
null
null
null
tests/rwops/load/main.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
2
2018-04-21T02:25:47.000Z
2018-04-21T15:03:15.000Z
/* SDL C++ Classes Copyright (C) 2017-2018 Mateus Carmo M. de F. Barbosa This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <iostream> #include <stdexcept> #include <SDL.h> #include "rwops.hpp" using SDL::RWops; using SDL::FromRWops; const int ERR_SDL_INIT = -1; char mem[] = { 0, 1, 2, 3 }; bool init(Uint32 sdlInitFlags) { if(SDL_Init(sdlInitFlags) < 0) { return false; } return true; } void quit() { SDL_Quit(); } void printRWopsType(SDL_RWops *rwops) { std::cout << "RWops type: "; switch(rwops->type) { case SDL_RWOPS_UNKNOWN: std::cout << "unknown"; break; case SDL_RWOPS_WINFILE: std::cout << "win32 file"; break; case SDL_RWOPS_STDFILE: std::cout << "stdio file"; break; case SDL_RWOPS_JNIFILE: std::cout << "android asset"; break; case SDL_RWOPS_MEMORY: std::cout << "memory (read-write)"; break; case SDL_RWOPS_MEMORY_RO: std::cout << "memory (read-only)"; break; } std::cout << std::endl; } struct PseudoDeleter { void operator()(char *) {} }; // has to return the same type that PseudoDeleter::operator() recieves char * pseudoLoad(SDL_RWops *rwops, int freesrc, int extraArg) { if(freesrc != 0) { std::cout << "error: non-zero freesrc!" << std::endl; } printRWopsType(rwops); std::cout << "extra argument: " << extraArg << std::endl; if(extraArg < 0) { return NULL; } return mem; // could be any non-null char* } void test() { RWops rwops(mem, sizeof(mem)); // in both cases, we ignore load's return value try { FromRWops<PseudoDeleter>::load(rwops, pseudoLoad, "error: first load throws, but it shouldn't", 42); } catch(const std::exception &ex) { std::cout << ex.what() << std::endl; } try { FromRWops<PseudoDeleter>::load(rwops, pseudoLoad, "success: second load throws, as it should", -2); } catch(const std::exception &ex) { std::cout << ex.what() << std::endl; } } int main(int argc, char **argv) { Uint32 sdlFlags = SDL_INIT_VIDEO; if(!init(sdlFlags)) { SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "couldn't initialize SDL\n"); return ERR_SDL_INIT; } test(); quit(); return 0; }
23.41129
76
0.689631
jamesl-github
e51aec93c0d6f35d933af1768b3d9eadc13b8639
312
cpp
C++
cpp_solutions/lexf.cpp
lbovard/rosalind
92d0bde3282caf6af512114bdc0133ee3a1d6418
[ "Unlicense" ]
null
null
null
cpp_solutions/lexf.cpp
lbovard/rosalind
92d0bde3282caf6af512114bdc0133ee3a1d6418
[ "Unlicense" ]
null
null
null
cpp_solutions/lexf.cpp
lbovard/rosalind
92d0bde3282caf6af512114bdc0133ee3a1d6418
[ "Unlicense" ]
null
null
null
#include <iostream> #include <algorithm> int main() { std::vector<char> alphabet; int n; std::cout << facts[n] << std::endl; do { for(unsigned int i=0;i<n;++i) { std::cout << nums[i] << " "; } std::cout << std::endl; } while (std::next_permutation(nums,nums+n)); return 0; }
17.333333
47
0.544872
lbovard
e51ece6da259c4785f3f97b091e589df208d648f
1,010
cpp
C++
MainWindow.cpp
Evgenii-Evgenevich/qt-the-interface
0d12d110b09b5ff9c52adc7da70104b219220267
[ "Apache-2.0" ]
null
null
null
MainWindow.cpp
Evgenii-Evgenevich/qt-the-interface
0d12d110b09b5ff9c52adc7da70104b219220267
[ "Apache-2.0" ]
null
null
null
MainWindow.cpp
Evgenii-Evgenevich/qt-the-interface
0d12d110b09b5ff9c52adc7da70104b219220267
[ "Apache-2.0" ]
null
null
null
#include "MainWindow.h" #include <QLocale> #include <QScrollArea> #include <QTabWidget> #include <QPushButton> #include <QStatusBar> #include <QMenuBar> #include <QShowEvent> #include "Beam.h" MainWindow::MainWindow() : QMainWindow() { QScrollArea* scrollArea = new QScrollArea; scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setWidgetResizable(true); m_beam = new Beam(this); setWindowTitle("Beam"); setCentralWidget(scrollArea); scrollArea->setWidget(m_beam); QMenu* fileMenu = menuBar()->addMenu("&File"); statusBar()->addWidget(new QPushButton("Start Simulation")); const QIcon exitIcon = QIcon::fromTheme("application-exit"); QAction* exitAct = fileMenu->addAction(exitIcon, tr("E&xit"), this, &QWidget::close); exitAct->setShortcuts(QKeySequence::Quit); exitAct->setStatusTip(tr("Exit the application")); } void MainWindow::showEvent(QShowEvent* event) { QMainWindow::showEvent(event); }
25.897436
86
0.757426
Evgenii-Evgenevich
e524f5ed1b49b0b7b9ded472ec03bea8b73d32ab
400
cpp
C++
RayTracer/TexturedMaterial.cpp
MatthewSmit/RayTracer
86aff1867a6a6fa3f493a489b4848e75ca7370f0
[ "MIT" ]
2
2018-03-26T21:59:26.000Z
2019-11-14T13:54:44.000Z
RayTracer/TexturedMaterial.cpp
MatthewSmit/RayTracer
86aff1867a6a6fa3f493a489b4848e75ca7370f0
[ "MIT" ]
null
null
null
RayTracer/TexturedMaterial.cpp
MatthewSmit/RayTracer
86aff1867a6a6fa3f493a489b4848e75ca7370f0
[ "MIT" ]
null
null
null
#include "TexturedMaterial.h" #include "Image.h" #include "SceneObject.h" vec4 TexturedMaterial::getColour(const vec4& hitPoint, const SceneObject* object) const { auto textureCoordinates = object->getTextureCoordinates(hitPoint); textureCoordinates /= scaling; textureCoordinates = (textureCoordinates % vec4{ 1.0f } + vec4{ 1.0f }) % vec4 { 1.0f }; return image->sample(textureCoordinates); }
33.333333
89
0.7575
MatthewSmit
e52571a5af3bf5d17b16c3c5499490c303bf4d33
1,204
cc
C++
p2p/base/proxy_packet_socket_factory.cc
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
p2p/base/proxy_packet_socket_factory.cc
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
p2p/base/proxy_packet_socket_factory.cc
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
#include "p2p/base/proxy_packet_socket_factory.h" namespace rtc { ProxyPacketSocketFactory::ProxyPacketSocketFactory() : BasicPacketSocketFactory() {} ProxyPacketSocketFactory::ProxyPacketSocketFactory(Thread* thread) : BasicPacketSocketFactory(thread) {} ProxyPacketSocketFactory::ProxyPacketSocketFactory( SocketFactory* socket_factory) : BasicPacketSocketFactory(socket_factory) {} ProxyPacketSocketFactory::~ProxyPacketSocketFactory() {} void ProxyPacketSocketFactory::SetProxyInformation(const ProxyInfo& proxy_info) { proxy_info_ = proxy_info; } AsyncPacketSocket* ProxyPacketSocketFactory::CreateClientTcpSocket( const SocketAddress& local_address, const SocketAddress& remote_address, const ProxyInfo& proxy_info, const std::string& user_agent, const PacketSocketTcpOptions& tcp_options) { return BasicPacketSocketFactory::CreateClientTcpSocket(local_address, remote_address, proxy_info_, user_agent, tcp_options); } }
34.4
81
0.656146
eagle3dstreaming
e52bf446ef1233cb4737b10c7b4bff5bf6cb606a
2,330
hpp
C++
src/backend/MoveList.hpp
Witek902/Caissa
07bb81e7cae23ea18bb44870d1c1eaa038ab0355
[ "MIT" ]
3
2022-01-11T22:37:06.000Z
2022-01-18T17:40:48.000Z
src/backend/MoveList.hpp
Witek902/Caissa
07bb81e7cae23ea18bb44870d1c1eaa038ab0355
[ "MIT" ]
1
2021-11-12T00:38:30.000Z
2021-11-12T00:38:30.000Z
src/backend/MoveList.hpp
Witek902/Caissa
07bb81e7cae23ea18bb44870d1c1eaa038ab0355
[ "MIT" ]
null
null
null
#pragma once #include "Move.hpp" class MoveList { friend class Position; friend class Search; friend class MoveOrderer; public: struct MoveEntry { Move move; int32_t score; }; static constexpr uint32_t MaxMoves = 255; uint32_t Size() const { return numMoves; } const Move& GetMove(uint32_t index) const { ASSERT(index < numMoves); return moves[index].move; } const MoveEntry& operator [] (uint32_t index) const { ASSERT(index < numMoves); return moves[index]; } MoveEntry& operator [] (uint32_t index) { ASSERT(index < numMoves); return moves[index]; } void RemoveMove(const Move& move); void Clear() { numMoves = 0; } void Push(const Move move) { ASSERT(numMoves < MaxMoves); for (uint32_t i = 0; i < numMoves; ++i) { ASSERT(move != moves[i].move); } uint32_t index = numMoves++; moves[index] = { move, 0 }; } uint32_t AssignTTScores(const TTEntry& ttEntry); void AssignPVScore(const Move pvMove); const Move PickBestMove(uint32_t index, int32_t& outMoveScore) { ASSERT(index < numMoves); int32_t bestScore = INT32_MIN; uint32_t bestMoveIndex = index; for (uint32_t i = index; i < numMoves; ++i) { if (moves[i].score > bestScore) { bestScore = moves[i].score; bestMoveIndex = i; } } if (bestMoveIndex != index) { std::swap(moves[index], moves[bestMoveIndex]); } outMoveScore = moves[index].score; return moves[index].move; } bool HasMove(const Move move) const { for (uint32_t i = 0; i < numMoves; ++i) { if (moves[i].move == move) { return true; } } return false; } bool HasMove(const PackedMove move) const { for (uint32_t i = 0; i < numMoves; ++i) { if (moves[i].move == move) { return true; } } return false; } void Shuffle(); void Print(const Position& pos, bool sorted = true) const; private: uint32_t numMoves = 0; MoveEntry moves[MaxMoves]; };
21.376147
106
0.535193
Witek902
e530686d7270d6309e2924632daac74183c88c65
982
hpp
C++
src/view/facing_dir.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2020-04-10T14:39:00.000Z
2021-02-11T15:52:16.000Z
src/view/facing_dir.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2019-12-17T08:50:20.000Z
2020-02-03T09:37:56.000Z
src/view/facing_dir.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
1
2020-08-19T03:06:52.000Z
2020-08-19T03:06:52.000Z
#ifndef NINJACLOWN_VIEW_FACING_DIR_HPP #define NINJACLOWN_VIEW_FACING_DIR_HPP #include <array> #include <optional> #include <string_view> #include "utils/utils.hpp" namespace view::facing_direction { enum type : unsigned int { N, S, E, W, NE, NW, SE, SW, MAX_VAL }; constexpr std::array values = {N, S, E, W, NE, NW, SE, SW, MAX_VAL}; static_assert(utils::has_all_sorted(values, MAX_VAL), "values array might not contain every enum value"); constexpr std::string_view to_string(facing_direction::type val) noexcept { constexpr std::array<std::string_view, MAX_VAL + 1> direction_map = { "N", "S", "E", "W", "NE", "NW", "SE", "SW", "MAX_VAL", }; return direction_map[val]; } type from_angle(float rad); constexpr std::optional<facing_direction::type> from_string(std::string_view str) noexcept { for (auto val : values) { if (to_string(val) == str) { return val; } } return {}; } } // namespace view::facing_direction #endif //NINJACLOWN_VIEW_FACING_DIR_HPP
26.540541
105
0.709776
TiWinDeTea
e531843510969f3066e08d658b6e9b0b21f32499
8,891
cpp
C++
iterators/program.cpp
MatthewCalligaro/CS70Textbook
c7fb8e2163a0da562972aea37e35f2b5825a9b80
[ "MIT" ]
8
2020-01-24T20:50:59.000Z
2021-08-01T17:57:37.000Z
iterators/program.cpp
cs70-grutoring/CS70Textbook
c7fb8e2163a0da562972aea37e35f2b5825a9b80
[ "MIT" ]
null
null
null
iterators/program.cpp
cs70-grutoring/CS70Textbook
c7fb8e2163a0da562972aea37e35f2b5825a9b80
[ "MIT" ]
1
2020-04-04T17:15:19.000Z
2020-04-04T17:15:19.000Z
/** * \file program.cpp * \copyright Matthew Calligaro * \date January 2020 * \brief A command line program demonstrating the use of iterators */ #include <cassert> #include <iostream> #include <list> #include <string> int main() { std::list<std::string> list = {"alpha", "bravo", "charlie", "delta", "echo"}; std::list<std::string> list2; const std::list<std::string>& clist = list; std::list<double> dlist = {0.0, 1.0, 2.0, 3.0, 4.0}; /***************************************************************************** * Iterator Basics ****************************************************************************/ std::cout << std::endl << ">> Iterator Basics" << std::endl; // If a data structure supports an iterator, it should have a begin method // which returns an iterator pointing to the first element of the data // structure std::list<std::string>::iterator i1 = list.begin(); // operator* returns a reference to the element to which the iterator points std::cout << *i1 << std::endl; // operator-> returns a pointer to the element to which the iterator points std::cout << i1->size() << std::endl; // operator++ moves the iterator to the next element in the data structure ++i1; std::cout << *i1 << std::endl; // For a bidirectional iterator, operator-- moves the iterator to the previous // element in the data structure. A forward iterator need not support // operator--. --i1; std::cout << *i1 << std::endl; // It is undefined behavior to decrement an iterator equal to begin /** * --list.begin(); */ // If a data structure supports an iterator, it should have an end method // which returns an iterator pointing to the past-the-end element of the data // structure. This iterator is equal to an iterator that was pointing // to the last element and then was incremented. std::cout << *(--list.end()) << std::endl; // It is undefined behavior to use the *, ->, or ++ operators on an iterator // equal to end /** * std::list<std::string>::iterator end = list.end(); * *end; * end->size(); * ++end; */ // Two iterators will compare as equal if they point to the same location in // the data structure std::list<std::string>::iterator i2 = list.begin(); std::cout << (i1 == i2) << std::endl; ++i2; std::cout << (i1 == i2) << std::endl; // In an empty data structure, the iterators returned by begin and end must // compare as equal assert(list2.begin() == list2.end()); // This will cause a compile-time error because it compares iterators to // data structures of different types /** * list.begin() == dlist.begin(); */ // It is undefined behavior to compare two iterators pointing to different // data structures of the same type /** * list.begin() == list2.begin(); */ /***************************************************************************** * Default Iterators ****************************************************************************/ // STL data structures must support a default iterator std::list<std::string>::iterator default1; std::list<std::string>::iterator default2; // Two default iterators must be equal assert(default1 == default2); // It is undefined behavior to use the *, ->, ++, or -- operators on a default // iterator /** * *default1; * default1->size(); * ++default1; * --default1; */ // Once we give a default iterator a value, we can use it as normal default1 = list.begin(); ++default1; /***************************************************************************** * iterators vs. const_iterators ****************************************************************************/ std::cout << std::endl << ">> iterators vs const_iterators" << std::endl; // If a data structure supports an iterator, it should have a cbegin method // which returns an const_iterator pointing to the first element of the data // structure std::list<std::string>::const_iterator c1 = list.cbegin(); // If a data structure (or a reference to a data structure) is declared as // const, begin will return a const_iterator rather than an iterator std::list<std::string>::const_iterator c2 = clist.begin(); // A const_iterator is identical to an iterator except that operator* returns // a const reference rather than a reference and operator-> returns a const // pointer rather than a pointer. This means that we cannot use a // const_iterator to modify the elements of the data structure. std::cout << *c1 << std::endl; ++c1; std::cout << c2->substr(1, 3) << std::endl; // These would cause compile-time errors because they attempt to modify an // element of the data structure with a const reference/pointer /** * *c1 = "beta"; * c1->resize(2); */ // Iterators support a constructor and assignment operator which convert an // iterator to a const_iterator std::list<std::string>::const_iterator c3 = i1; c1 = i1; // These will cause compile time errors because Iterators do NOT support // conversion from const_iterator to iterator /** * std::list<std::string>::iterator i3 = c1; * i1 = c1; */ // If we declare an iterator or const_iterator with the const keyword, this // prevents the iterator itself from being changed (such as with ++ or --). // This is unrelated to the iterator/const_iterator distinction. const std::list<std::string>::iterator i4 = list.begin(); const std::list<std::string>::const_iterator c4 = c1; *i4 = "alfa"; std::cout << *c4 << std::endl; std::cout << (c4 == i4) << std::endl; // These will cause compile-time errors because i4 and c4 were declared with // the const keyword so cannot be modified /** * ++i4; * --i4; * c4 = c3; */ /***************************************************************************** * Using Iterators ****************************************************************************/ std::cout << std::endl << ">> Using Iterators" << std::endl; // std::next creates a copy of an iterator and increments (or decrements) the // copy n times without changing the original std::list<std::string>::iterator j1 = list.begin(); std::list<std::string>::iterator j2 = std::next(j1, 4); std::list<std::string>::iterator j3 = std::next(j2, -2); std::cout << *j1 << std::endl; std::cout << *j2 << std::endl; std::cout << *j3 << std::endl; // We can use an iterator to iterate through the elements of a data structure std::cout << std::endl << "For loop:" << std::endl; for (std::list<std::string>::const_iterator i = list.cbegin(); i != list.end(); ++i) { std::cout << *i << std::endl; } std::cout << std::endl; // The range-based for loop automatically iterates through a data structure // using the data structure's iterator. The following range-based for loop // has the exact same behavior as the previous for loop. std::cout << "Ranged-base for loop:" << std::endl; for (std::string str : list) { std::cout << str << std::endl; } std::cout << std::endl; // If a data structure implements an iterator, we can use several standard // library functions on the data structure. For example, std::equal compares // two data structures using their iterators. std::cout << std::equal(list.begin(), list.end(), list2.begin(), list2.end()) << std::endl; // If you are writing your own data structure with an iterator, it is often // easiest to use these standard library functions to implement methods of // your data structure, such as using std::equal for operator== // Sometimes, methods of a data structure will take an iterator as a parameter // and/or return an iterator. For example, std::list::erase takes an iterator // specifying which element to erase and returns an iterator to the element // directly after the element that was erased. std::list<std::string>::iterator j4 = list.erase(j3); std::cout << *j4 << std::endl; /***************************************************************************** * Invalid Iterators ****************************************************************************/ // Methods of a data structure may invalidate existing iterators. For // example, std::list::erase invalidates any iterator pointing to the element // that was erased. std::list<std::string>::iterator k1 = list.begin(); list.erase(list.begin()); // k1 is now invalid. It is undefined behavior to use an invalid iterator // in any way. /** * *k1; * ++k1; * --k1; * k1->size(); * k1 == j1; * std::list<std::string>::iterator k2 = k1; */ // If a method invalidates any iterators, it should explicitly specify which // iterators it invalidates in its documentation. A const method cannot // invalidate any iterators. return 0; }
35.706827
80
0.59982
MatthewCalligaro
e53387adb403d6c6c407a75760b8962b81ac3df6
13,764
cpp
C++
samples/snippets/cpp/VS_Snippets_Wpf/System.Windows.Interop.D3DImage/cpp/renderermanager.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_Wpf/System.Windows.Interop.D3DImage/cpp/renderermanager.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_Wpf/System.Windows.Interop.D3DImage/cpp/renderermanager.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
// <snippetRendererManagerCPP> //+----------------------------------------------------------------------------- // // CRendererManager // // Manages the list of CRenderers. Managed code pinvokes into this class // and this class forwards to the appropriate CRenderer. // //------------------------------------------------------------------------------ #include "StdAfx.h" const static TCHAR szAppName[] = TEXT("D3DImageSample"); typedef HRESULT (WINAPI *DIRECT3DCREATE9EXFUNCTION)(UINT SDKVersion, IDirect3D9Ex**); //+----------------------------------------------------------------------------- // // Member: // CRendererManager ctor // //------------------------------------------------------------------------------ CRendererManager::CRendererManager() : m_pD3D(NULL), m_pD3DEx(NULL), m_cAdapters(0), m_hwnd(NULL), m_pCurrentRenderer(NULL), m_rgRenderers(NULL), m_uWidth(1024), m_uHeight(1024), m_uNumSamples(0), m_fUseAlpha(false), m_fSurfaceSettingsChanged(true) { } //+----------------------------------------------------------------------------- // // Member: // CRendererManager dtor // //------------------------------------------------------------------------------ CRendererManager::~CRendererManager() { DestroyResources(); if (m_hwnd) { DestroyWindow(m_hwnd); UnregisterClass(szAppName, NULL); } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::Create // // Synopsis: // Creates the manager // //------------------------------------------------------------------------------ HRESULT CRendererManager::Create(CRendererManager **ppManager) { HRESULT hr = S_OK; *ppManager = new CRendererManager(); IFCOOM(*ppManager); Cleanup: return hr; } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::EnsureRenderers // // Synopsis: // Makes sure the CRenderer objects exist // //------------------------------------------------------------------------------ HRESULT CRendererManager::EnsureRenderers() { HRESULT hr = S_OK; if (!m_rgRenderers) { IFC(EnsureHWND()); assert(m_cAdapters); m_rgRenderers = new CRenderer*[m_cAdapters]; IFCOOM(m_rgRenderers); ZeroMemory(m_rgRenderers, m_cAdapters * sizeof(m_rgRenderers[0])); for (UINT i = 0; i < m_cAdapters; ++i) { IFC(CTriangleRenderer::Create(m_pD3D, m_pD3DEx, m_hwnd, i, &m_rgRenderers[i])); } // Default to the default adapter m_pCurrentRenderer = m_rgRenderers[0]; } Cleanup: return hr; } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::EnsureHWND // // Synopsis: // Makes sure an HWND exists if we need it // //------------------------------------------------------------------------------ // <snippetRendererManager_EnsureHWND> HRESULT CRendererManager::EnsureHWND() { HRESULT hr = S_OK; if (!m_hwnd) { WNDCLASS wndclass; wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = DefWindowProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = NULL; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szAppName; if (!RegisterClass(&wndclass)) { IFC(E_FAIL); } m_hwnd = CreateWindow(szAppName, TEXT("D3DImageSample"), WS_OVERLAPPEDWINDOW, 0, // Initial X 0, // Initial Y 0, // Width 0, // Height NULL, NULL, NULL, NULL); } Cleanup: return hr; } // </snippetRendererManager_EnsureHWND> //+----------------------------------------------------------------------------- // // Member: // CRendererManager::EnsureD3DObjects // // Synopsis: // Makes sure the D3D objects exist // //------------------------------------------------------------------------------ // <snippetRendererManager_EnsureD3DObjects> HRESULT CRendererManager::EnsureD3DObjects() { HRESULT hr = S_OK; HMODULE hD3D = NULL; if (!m_pD3D) { hD3D = LoadLibrary(TEXT("d3d9.dll")); DIRECT3DCREATE9EXFUNCTION pfnCreate9Ex = (DIRECT3DCREATE9EXFUNCTION)GetProcAddress(hD3D, "Direct3DCreate9Ex"); if (pfnCreate9Ex) { IFC((*pfnCreate9Ex)(D3D_SDK_VERSION, &m_pD3DEx)); IFC(m_pD3DEx->QueryInterface(__uuidof(IDirect3D9), reinterpret_cast<void **>(&m_pD3D))); } else { m_pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (!m_pD3D) { IFC(E_FAIL); } } m_cAdapters = m_pD3D->GetAdapterCount(); } Cleanup: if (hD3D) { FreeLibrary(hD3D); } return hr; } // </snippetRendererManager_EnsureD3DObjects> //+----------------------------------------------------------------------------- // // Member: // CRendererManager::CleanupInvalidDevices // // Synopsis: // Checks to see if any devices are bad and if so, deletes all resources // // We could delete resources and wait for D3DERR_DEVICENOTRESET and reset // the devices, but if the device is lost because of an adapter order // change then our existing D3D objects would have stale adapter // information. We'll delete everything to be safe rather than sorry. // //------------------------------------------------------------------------------ void CRendererManager::CleanupInvalidDevices() { for (UINT i = 0; i < m_cAdapters; ++i) { if (FAILED(m_rgRenderers[i]->CheckDeviceState())) { DestroyResources(); break; } } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::GetBackBufferNoRef // // Synopsis: // Returns the surface of the current renderer without adding a reference // // This can return NULL if we're in a bad device state. // //------------------------------------------------------------------------------ HRESULT CRendererManager::GetBackBufferNoRef(IDirect3DSurface9 **ppSurface) { HRESULT hr = S_OK; // Make sure we at least return NULL *ppSurface = NULL; CleanupInvalidDevices(); IFC(EnsureD3DObjects()); // // Even if we never render to another adapter, this sample creates devices // and resources on each one. This is a potential waste of video memory, // but it guarantees that we won't have any problems (e.g. out of video // memory) when switching to render on another adapter. In your own code // you may choose to delay creation but you'll need to handle the issues // that come with it. // IFC(EnsureRenderers()); if (m_fSurfaceSettingsChanged) { if (FAILED(TestSurfaceSettings())) { IFC(E_FAIL); } for (UINT i = 0; i < m_cAdapters; ++i) { IFC(m_rgRenderers[i]->CreateSurface(m_uWidth, m_uHeight, m_fUseAlpha, m_uNumSamples)); } m_fSurfaceSettingsChanged = false; } if (m_pCurrentRenderer) { *ppSurface = m_pCurrentRenderer->GetSurfaceNoRef(); } Cleanup: // If we failed because of a bad device, ignore the failure for now and // we'll clean up and try again next time. if (hr == D3DERR_DEVICELOST) { hr = S_OK; } return hr; } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::TestSurfaceSettings // // Synopsis: // Checks to see if our current surface settings are allowed on all // adapters. // //------------------------------------------------------------------------------ // <snippetRendererManager_TestSurfaceSettings> HRESULT CRendererManager::TestSurfaceSettings() { HRESULT hr = S_OK; D3DFORMAT fmt = m_fUseAlpha ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8; // // We test all adapters because because we potentially use all adapters. // But even if this sample only rendered to the default adapter, you // should check all adapters because WPF may move your surface to // another adapter for you! // for (UINT i = 0; i < m_cAdapters; ++i) { // Can we get HW rendering? IFC(m_pD3D->CheckDeviceType( i, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, fmt, TRUE )); // Is the format okay? IFC(m_pD3D->CheckDeviceFormat( i, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, D3DUSAGE_RENDERTARGET | D3DUSAGE_DYNAMIC, // We'll use dynamic when on XP D3DRTYPE_SURFACE, fmt )); // D3DImage only allows multisampling on 9Ex devices. If we can't // multisample, overwrite the desired number of samples with 0. if (m_pD3DEx && m_uNumSamples > 1) { assert(m_uNumSamples <= 16); if (FAILED(m_pD3D->CheckDeviceMultiSampleType( i, D3DDEVTYPE_HAL, fmt, TRUE, static_cast<D3DMULTISAMPLE_TYPE>(m_uNumSamples), NULL ))) { m_uNumSamples = 0; } } else { m_uNumSamples = 0; } } Cleanup: return hr; } // </snippetRendererManager_TestSurfaceSettings> //+----------------------------------------------------------------------------- // // Member: // CRendererManager::DestroyResources // // Synopsis: // Delete all D3D resources // //------------------------------------------------------------------------------ void CRendererManager::DestroyResources() { SAFE_RELEASE(m_pD3D); SAFE_RELEASE(m_pD3DEx); for (UINT i = 0; i < m_cAdapters; ++i) { delete m_rgRenderers[i]; } delete [] m_rgRenderers; m_rgRenderers = NULL; m_pCurrentRenderer = NULL; m_cAdapters = 0; m_fSurfaceSettingsChanged = true; } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::SetSize // // Synopsis: // Update the size of the surface. Next render will create a new surface. // //------------------------------------------------------------------------------ void CRendererManager::SetSize(UINT uWidth, UINT uHeight) { if (uWidth != m_uWidth || uHeight != m_uHeight) { m_uWidth = uWidth; m_uHeight = uHeight; m_fSurfaceSettingsChanged = true; } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::SetAlpha // // Synopsis: // Update the format of the surface. Next render will create a new surface. // //------------------------------------------------------------------------------ void CRendererManager::SetAlpha(bool fUseAlpha) { if (fUseAlpha != m_fUseAlpha) { m_fUseAlpha = fUseAlpha; m_fSurfaceSettingsChanged = true; } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::SetNumDesiredSamples // // Synopsis: // Update the MSAA settings of the surface. Next render will create a // new surface. // //------------------------------------------------------------------------------ void CRendererManager::SetNumDesiredSamples(UINT uNumSamples) { if (m_uNumSamples != uNumSamples) { m_uNumSamples = uNumSamples; m_fSurfaceSettingsChanged = true; } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::SetAdapter // // Synopsis: // Update the current renderer. Next render will use the new renderer. // //------------------------------------------------------------------------------ // <snippetRendererManager_SetAdapter> void CRendererManager::SetAdapter(POINT screenSpacePoint) { CleanupInvalidDevices(); // // After CleanupInvalidDevices, we may not have any D3D objects. Rather than // recreate them here, ignore the adapter update and wait for render to recreate. // if (m_pD3D && m_rgRenderers) { HMONITOR hMon = MonitorFromPoint(screenSpacePoint, MONITOR_DEFAULTTONULL); for (UINT i = 0; i < m_cAdapters; ++i) { if (hMon == m_pD3D->GetAdapterMonitor(i)) { m_pCurrentRenderer = m_rgRenderers[i]; break; } } } } // </snippetRendererManager_SetAdapter> //+----------------------------------------------------------------------------- // // Member: // CRendererManager::Render // // Synopsis: // Forward to the current renderer // //------------------------------------------------------------------------------ HRESULT CRendererManager::Render() { return m_pCurrentRenderer ? m_pCurrentRenderer->Render() : S_OK; } // </snippetRendererManagerCPP>
26.571429
118
0.483944
BaruaSourav
e5409732acd3c4b8aeace4d355997d0ce71657a6
2,115
cpp
C++
linear_structures/string/1236_web-crawler.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
linear_structures/string/1236_web-crawler.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
linear_structures/string/1236_web-crawler.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
// Author: b1tank // Email: b1tank@outlook.com //================================= /* 1236_web-crawler LeetCode Solution: - s.substr(0, s.find('/', 7)) */ #include <iostream> #include <sstream> // stringstream, istringstream, ostringstream #include <string> // to_string(), stoi() #include <cctype> // isalnum, isalpha, isdigit, islower, isupper, isspace; toupper, tolower #include <climits> // INT_MAX 2147483647 #include <cmath> // pow(3.0, 4.0) #include <cstdlib> // rand() % 100 + 1 #include <vector> #include <stack> #include <queue> #include <deque> #include <unordered_set> // unordered_set, unordered_multiset #include <set> // set, multiset #include <unordered_map> // unordered_map, unordered_multimap #include <map> // map, multimap #include <utility> // pair<> #include <tuple> // tuple<> #include <algorithm> // reverse, sort, transform, find, remove, count, count_if #include <memory> // shared_ptr<>, make_shared<> #include <stdexcept> // invalid_argument using namespace std; /** * // This is the HtmlParser's API interface. * // You should not implement it, or speculate about its implementation * class HtmlParser { * public: * vector<string> getUrls(string url); * }; */ class Solution { public: vector<string> crawl(string startUrl, HtmlParser htmlParser) { vector<string> res; queue<string> q; q.push(startUrl); unordered_set<string> visited; string hostname = startUrl.substr(7, startUrl.find('/', 7) - 7); // nice use of find and substr to extract something while (!q.empty()) { string cur = q.front(); q.pop(); visited.insert(cur); res.push_back(cur); vector<string> ns = htmlParser.getUrls(cur); for (auto& n : ns) { if (n.find(hostname) != string::npos && visited.find(n) == visited.end()) { // find substr in a string q.push(n); visited.insert(n); } } } return res; } };
31.567164
125
0.585343
b1tank
e5418770bc36e7c4c9b6d8dadd22b410d35e7e0f
29,091
cpp
C++
LJ_Argon_MD2.cpp
dc1394/LJ_Argon_MD2
d010df2563541008eb0bf76a382537038ded3e6f
[ "BSD-2-Clause" ]
null
null
null
LJ_Argon_MD2.cpp
dc1394/LJ_Argon_MD2
d010df2563541008eb0bf76a382537038ded3e6f
[ "BSD-2-Clause" ]
null
null
null
LJ_Argon_MD2.cpp
dc1394/LJ_Argon_MD2
d010df2563541008eb0bf76a382537038ded3e6f
[ "BSD-2-Clause" ]
1
2018-08-05T21:18:09.000Z
2018-08-05T21:18:09.000Z
/*! \file LJ_Argon_MD.cpp \brief 分子動力学シミュレーションを描画する Copyright © 2015 @dc1394 All Rights Reserved. This software is released under the BSD 2-Clause License. */ #include "DXUT.h" #include "SDKmisc.h" #include "DXUTcamera.h" #include "DXUTgui.h" #include "DXUTsettingsDlg.h" #include "DXUTShapes.h" #include "moleculardynamics/Ar_moleculardynamics.h" #include "utility/utility.h" #include <array> // for std::array #include <memory> // for std::unique_ptr #include <vector> // for std::vector #include <boost/assert.hpp> // for BOOST_ASSERT #include <boost/cast.hpp> // for boost::numeric_cast #include <boost/format.hpp> // for boost::wformat //! A function. /*! UIに変更があったときに呼ばれるコールバック関数 */ void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext); //! A function. /*! 球のメッシュを生成する \param pd3dDevice Direct3Dのデバイス */ void CreateSphereMesh(ID3D10Device* pd3dDevice); //! A function. /*! 箱を描画する \param pd3dDevice Direct3Dのデバイス */ void RenderBox(ID3D10Device* pd3dDevice); //! A function. /*! 画面の左上に情報を表示する \param pd3dDevice Direct3Dのデバイス */ void RenderText(ID3D10Device* pd3dDevice); //! A function. /*! UIを配置する */ void SetUI(); //! A global variable (constant). /*! 色の比率 */ static auto const COLORRATIO = 0.025f; //! A global variable (constant). /*! 格子定数の比率 */ static auto const LATTICERATIO = 50.0; //! A global variable (constant). /*! インデックスバッファの個数 */ static auto const NUMINDEXBUFFER = 16U; //! A global variable (constant). /*! 頂点バッファの個数 */ static auto const NUMVERTEXBUFFER = 8U; //! A global variable (constant). /*! 頂点バッファの個数 */ static auto const TINY = 1.0E-30f; //! A global variable (constant). /*! 画面サイズ(高さ) */ static auto const WINDOWHEIGHT = 960; //! A global variable (constant). /*! 画面サイズ(幅) */ static auto const WINDOWWIDTH = 1280; //! A global variable. /*! 分子動力学シミュレーションのオブジェクト */ moleculardynamics::Ar_moleculardynamics armd; //! A global variable. /*! 箱の色 */ D3DXVECTOR4 boxColor(1.0f, 1.0f, 1.0f, 1.0f); //! A global variable. /*! バッファー リソース */ D3D10_BUFFER_DESC bd; //! A global variable. /*! 背景の色 */ D3DXVECTOR4 clearColor(0.176f, 0.196f, 0.667f, 1.0f); //! A global variable. /*! Font for drawing text */ std::unique_ptr<ID3DX10Font, utility::Safe_Release<ID3DX10Font>> font; //! A global variable. /*! 格子定数が変更されたことを通知するフラグ */ bool modLatconst = false; //! A global variable. /*! スーパーセルが変更されたことを通知するフラグ */ bool modNc = false; //! A global variable. /*! ブレンディング・ステート */ std::unique_ptr<ID3D10BlendState, utility::Safe_Release<ID3D10BlendState>> pBlendStateNoBlend; //! A global variable. /*! エフェクト=シェーダプログラムを読ませるところ */ std::unique_ptr<ID3D10Effect, utility::Safe_Release<ID3D10Effect>> pEffect; //! A global variable. /*! インデックスバッファ */ std::unique_ptr<ID3D10Buffer, utility::Safe_Release<ID3D10Buffer>> pIndexBuffer; //! A global variable. /*! 入力レイアウト インターフェイス */ std::unique_ptr<ID3D10InputLayout, utility::Safe_Release<ID3D10InputLayout>> pInputLayout; //! A global variable. /*! メッシュへのスマートポインタが格納された可変長配列 */ std::vector<std::unique_ptr<ID3DX10Mesh, utility::Safe_Release<ID3DX10Mesh>>> pmeshvec; //! A global variable. /*! 頂点バッファ */ std::unique_ptr<ID3D10Buffer, utility::Safe_Release<ID3D10Buffer>> pVertexBuffer; //! A global variable. /*! 球の色 */ D3DXVECTOR4 sphereColor(1.0f, 0.0f, 1.0f, 1.0f); //! A global variable. /*! Sprite for batching text drawing */ std::unique_ptr<ID3DX10Sprite, utility::Safe_Release<ID3DX10Sprite>> sprite; //! A global variable. /*! テキスト表示用 */ std::unique_ptr<CDXUTTextHelper, utility::Safe_Delete<CDXUTTextHelper>> txthelper; //! A global variable. /*! A model viewing camera */ CModelViewerCamera g_Camera; //! A global variable. /*! manager for shared resources of dialogs */ CDXUTDialogResourceManager g_DialogResourceManager; //! A global variable. /*! Device settings dialog */ CD3DSettingsDlg g_D3DSettingsDlg; //! A global variable. /*! manages the 3D UI */ CDXUTDialog g_HUD; //! A global variable. /*! */ ID3D10EffectVectorVariable* g_pColorVariable = nullptr; //! A global variable. /*! */ ID3D10EffectMatrixVariable* g_pProjectionVariable = nullptr; //! A global variable. /*! */ ID3D10EffectTechnique* g_pRender = nullptr; //! A global variable. /*! */ ID3D10EffectMatrixVariable* g_pViewVariable = nullptr; //! A global variable. /*! */ ID3D10EffectMatrixVariable* g_pWorldVariable = nullptr; //! A global variable. /*! ビュー行列 */ D3DXMATRIX g_View; //-------------------------------------------------------------------------------------- // Structures //-------------------------------------------------------------------------------------- struct SimpleVertex { D3DXVECTOR3 Pos; }; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_CHANGEDEVICE 2 #define IDC_RECALC 3 #define IDC_OUTPUT 4 #define IDC_OUTPUT2 5 #define IDC_OUTPUT3 6 #define IDC_OUTPUT4 7 #define IDC_OUTPUT5 8 #define IDC_SLIDER 9 #define IDC_SLIDER2 10 #define IDC_SLIDER3 11 #define IDC_RADIOA 12 #define IDC_RADIOB 13 #define IDC_RADIOC 14 #define IDC_RADIOD 15 #define IDC_RADIOE 16 //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { g_D3DSettingsDlg.Init(&g_DialogResourceManager); g_HUD.Init(&g_DialogResourceManager); g_HUD.SetCallback(OnGUIEvent); SetUI(); } //-------------------------------------------------------------------------------------- // Render the scene using the D3D10 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { if (g_D3DSettingsDlg.IsActive()) { auto pRTV = DXUTGetD3D10RenderTargetView(); pd3dDevice->ClearRenderTargetView(pRTV, clearColor); g_D3DSettingsDlg.OnRender(fElapsedTime); return; } else { if (modLatconst) { RenderBox(pd3dDevice); modLatconst = false; } if (modNc) { CreateSphereMesh(pd3dDevice); RenderBox(pd3dDevice); modNc = false; } armd.runCalc(); // Clear render target and the depth stencil pd3dDevice->ClearRenderTargetView(DXUTGetD3D10RenderTargetView(), clearColor); pd3dDevice->ClearDepthStencilView(DXUTGetD3D10DepthStencilView(), D3D10_CLEAR_DEPTH, 1.0, 0); // Update variables g_pWorldVariable->SetMatrix(reinterpret_cast<float *>(const_cast<D3DXMATRIX *>(&(*g_Camera.GetWorldMatrix())))); g_pViewVariable->SetMatrix(reinterpret_cast<float *>(const_cast<D3DXMATRIX *>(&(*g_Camera.GetViewMatrix())))); g_pProjectionVariable->SetMatrix(reinterpret_cast<float *>(const_cast<D3DXMATRIX *>(&(*g_Camera.GetProjMatrix())))); D3D10_TECHNIQUE_DESC techDesc; g_pRender->GetDesc(&techDesc); g_pColorVariable->SetFloatVector(boxColor); // Set vertex buffer auto const stride = sizeof(SimpleVertex); auto const offset = 0U; auto const pVertexBuffertmp2 = pVertexBuffer.get(); pd3dDevice->IASetVertexBuffers(0, 1, &pVertexBuffertmp2, reinterpret_cast<UINT const *>(&stride), &offset); // Set index buffer pd3dDevice->IASetIndexBuffer(pIndexBuffer.get(), DXGI_FORMAT_R32_UINT, 0); // Set primitive topology pd3dDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP); for (auto p = 0U; p < techDesc.Passes; p++) { g_pRender->GetPassByIndex(p)->Apply(0); pd3dDevice->DrawIndexed(NUMINDEXBUFFER, 0, 0); } auto const pos = boost::numeric_cast<float>(armd.periodiclen()) * 0.5f; auto const size = pmeshvec.size(); for (auto i = 0U; i < size; i++) { auto color = sphereColor; auto const rcolor = COLORRATIO * armd.getForce(i); color.x = rcolor > 1.0f ? 1.0f : rcolor; g_pColorVariable->SetFloatVector(color); D3DXMATRIX World; D3DXMatrixTranslation( &World, boost::numeric_cast<float>(armd.Atoms()[i].r[0]) - pos, boost::numeric_cast<float>(armd.Atoms()[i].r[1]) - pos, boost::numeric_cast<float>(armd.Atoms()[i].r[2]) - pos); D3DXMatrixMultiply(&World, &(*g_Camera.GetWorldMatrix()), &World); // Update variables auto mWorld = World * (*g_Camera.GetWorldMatrix()); g_pWorldVariable->SetMatrix(reinterpret_cast<float *>(&mWorld)); UINT NumSubsets; pmeshvec[i]->GetAttributeTable(nullptr, &NumSubsets); for (auto p = 0U; p < techDesc.Passes; p++) { g_pRender->GetPassByIndex(p)->Apply(0); for (auto s = 0U; s < NumSubsets; s++) { pmeshvec[i]->DrawSubset(s); } } } DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, L"HUD / Stats"); g_HUD.OnRender(fElapsedTime); RenderText(pd3dDevice); DXUT_EndPerfEvent(); } } //-------------------------------------------------------------------------------------- // Reject any D3D10 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr = S_OK; V_RETURN(g_DialogResourceManager.OnD3D10CreateDevice(pd3dDevice)); V_RETURN(g_D3DSettingsDlg.OnD3D10CreateDevice(pd3dDevice)); ID3DX10Font * fonttemp; V_RETURN(D3DX10CreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &fonttemp)); font.reset(fonttemp); ID3DX10Sprite * spritetmp; V_RETURN(D3DX10CreateSprite(pd3dDevice, 512, &spritetmp)); sprite.reset(spritetmp); txthelper.reset(new CDXUTTextHelper(nullptr, nullptr, font.get(), sprite.get(), 15)); // Find the D3DX effect file std::array<WCHAR, MAX_PATH> str; V_RETURN( DXUTFindDXSDKMediaFileCch( str.data(), MAX_PATH, L"LJ_Argon_MD2.fx" ) ); auto dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) dwShaderFlags |= D3D10_SHADER_DEBUG; #endif ID3D10Effect * pEffecttmp; V_RETURN( D3DX10CreateEffectFromFile( str.data(), nullptr, nullptr, "fx_4_0", dwShaderFlags, 0, pd3dDevice, nullptr, nullptr, &pEffecttmp, nullptr, nullptr) ); pEffect.reset(pEffecttmp); // Obtain the technique g_pRender = pEffect->GetTechniqueByName( "Render" ); // Obtain the variables g_pWorldVariable = pEffect->GetVariableByName( "World" )->AsMatrix(); g_pViewVariable = pEffect->GetVariableByName( "View" )->AsMatrix(); g_pProjectionVariable = pEffect->GetVariableByName( "Projection" )->AsMatrix(); g_pColorVariable = pEffect->GetVariableByName( "Color" )->AsVector(); // Create an input layout D3D10_INPUT_ELEMENT_DESC const layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; D3D10_PASS_DESC PassDesc; g_pRender->GetPassByIndex( 0 )->GetDesc( &PassDesc ); ID3D10InputLayout * pInputLayouttmp; V_RETURN( pd3dDevice->CreateInputLayout( layout, sizeof(layout) / sizeof(layout[0]), PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &pInputLayouttmp) ); pInputLayout.reset(pInputLayouttmp); pd3dDevice->IASetInputLayout(pInputLayout.get()); D3D10_BLEND_DESC BlendState; ZeroMemory(&BlendState, sizeof(D3D10_BLEND_DESC)); BlendState.BlendEnable[0] = FALSE; BlendState.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL; ID3D10BlendState * pBlendStateNoBlendtmp = nullptr; pd3dDevice->CreateBlendState(&BlendState, &pBlendStateNoBlendtmp); pBlendStateNoBlend.reset(pBlendStateNoBlendtmp); RenderBox(pd3dDevice); CreateSphereMesh(pd3dDevice); D3DXVECTOR3 vEye(0.0f, 115.0f, 115.0f); D3DXVECTOR3 vLook(0.0f, 0.0f, 0.0f); D3DXVECTOR3 const Up(0.0f, 1.0f, 0.0f); D3DXMatrixLookAtLH(&g_View, &vEye, &vLook, &Up); // Update Variables that never change g_pViewVariable->SetMatrix(reinterpret_cast<float *>(&g_View)); g_Camera.SetViewParams(&vEye, &vLook); return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10ResizedSwapChain( ID3D10Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN(g_DialogResourceManager.OnD3D10ResizedSwapChain(pd3dDevice, pBackBufferSurfaceDesc)); V_RETURN(g_D3DSettingsDlg.OnD3D10ResizedSwapChain(pd3dDevice, pBackBufferSurfaceDesc)); g_HUD.SetLocation(pBackBufferSurfaceDesc->Width - 170, 0); g_HUD.SetSize(170, 170); auto const fAspectRatio = static_cast<float>(pBackBufferSurfaceDesc->Width) / static_cast<float>(pBackBufferSurfaceDesc->Height); g_Camera.SetProjParams(D3DX_PI / 4, fAspectRatio, 0.1f, 1000.0f); g_Camera.SetWindow(pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height); return S_OK; } //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { g_Camera.FrameMove(fElapsedTime); } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext) { switch (nControlID) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_CHANGEDEVICE: g_D3DSettingsDlg.SetActive(!g_D3DSettingsDlg.IsActive()); break; case IDC_RECALC: armd.recalc(); break; case IDC_SLIDER: armd.setTgiven(static_cast<double>((reinterpret_cast<CDXUTSlider *>(pControl))->GetValue())); break; case IDC_SLIDER2: armd.setScale(static_cast<double>((reinterpret_cast<CDXUTSlider *>(pControl))->GetValue()) / LATTICERATIO); modLatconst = true; break; case IDC_SLIDER3: armd.setNc(reinterpret_cast<CDXUTSlider *>(pControl)->GetValue()); modNc = true; break; case IDC_RADIOA: armd.setEnsemble(moleculardynamics::EnsembleType::NVT); break; case IDC_RADIOB: armd.setEnsemble(moleculardynamics::EnsembleType::NVE); break; case IDC_RADIOC: armd.setTempContMethod(moleculardynamics::TempControlMethod::LANGEVIN); break; case IDC_RADIOD: armd.setTempContMethod(moleculardynamics::TempControlMethod::NOSE_HOOVER); break; case IDC_RADIOE: armd.setTempContMethod(moleculardynamics::TempControlMethod::VELOCITY); break; default: break; } } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10ReleasingSwapChain( void* pUserContext ) { g_DialogResourceManager.OnD3D10ReleasingSwapChain(); } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10DestroyDevice( void* pUserContext ) { font.reset(); pBlendStateNoBlend.reset(); pEffect.reset(); pInputLayout.reset(); pIndexBuffer.reset(); pVertexBuffer.reset(); sprite.reset(); txthelper.reset(); for (auto & pmesh : pmeshvec) { pmesh.reset(); } g_DialogResourceManager.OnD3D10DestroyDevice(); g_D3DSettingsDlg.OnD3D10DestroyDevice(); DXUTGetGlobalResourceCache().OnDestroyDevice(); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Pass messages to dialog resource manager calls so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if (*pbNoFurtherProcessing) return 0; // Pass messages to settings dialog if its active if (g_D3DSettingsDlg.IsActive()) { g_D3DSettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if (*pbNoFurtherProcessing) return 0; g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Handle mouse button presses //-------------------------------------------------------------------------------------- void CALLBACK OnMouse( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Call if device was removed. Return true to find a new device, false to quit //-------------------------------------------------------------------------------------- bool CALLBACK OnDeviceRemoved( void* pUserContext ) { return true; } void CreateSphereMesh(ID3D10Device* pd3dDevice) { using namespace moleculardynamics; auto const size = armd.NumAtom(); pmeshvec.resize(size); for (auto & pmesh : pmeshvec) { ID3DX10Mesh * pmeshtmp = nullptr; DXUTCreateSphere( pd3dDevice, static_cast<float>(Ar_moleculardynamics::VDW_RADIUS / Ar_moleculardynamics::SIGMA), 16, 16, &pmeshtmp); pmesh.reset(pmeshtmp); } } void RenderBox(ID3D10Device* pd3dDevice) { auto const pos = boost::numeric_cast<float>(armd.periodiclen()) * 0.5f; // Create vertex buffer std::array<SimpleVertex, NUMVERTEXBUFFER> const vertices = { D3DXVECTOR3(-pos, pos, -pos), D3DXVECTOR3(pos, pos, -pos), D3DXVECTOR3(pos, pos, pos), D3DXVECTOR3(-pos, pos, pos), D3DXVECTOR3(-pos, -pos, -pos), D3DXVECTOR3(pos, -pos, -pos), D3DXVECTOR3(pos, -pos, pos), D3DXVECTOR3(-pos, -pos, pos), }; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof(SimpleVertex) * NUMVERTEXBUFFER; bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = vertices.data(); ID3D10Buffer * pVertexBuffertmp; utility::v_return(pd3dDevice->CreateBuffer(&bd, &InitData, &pVertexBuffertmp)); pVertexBuffer.reset(pVertexBuffertmp); // Create index buffer // Create vertex buffer std::array<DWORD, NUMINDEXBUFFER> const indices = { 0, 1, 2, 3, 0, 4, 5, 1, 2, 6, 5, 4, 7, 3, 7, 6 }; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof(DWORD) * NUMINDEXBUFFER; bd.BindFlags = D3D10_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; InitData.pSysMem = indices.data(); ID3D10Buffer * pIndexBuffertmp; utility::v_return(pd3dDevice->CreateBuffer(&bd, &InitData, &pIndexBuffertmp)); pIndexBuffer.reset(pIndexBuffertmp); } //-------------------------------------------------------------------------------------- // Render the help and statistics text //-------------------------------------------------------------------------------------- void RenderText(ID3D10Device* pd3dDevice) { txthelper->Begin(); txthelper->SetInsertionPos(2, 0); txthelper->SetForegroundColor(D3DXCOLOR(1.000f, 0.945f, 0.059f, 1.000f)); txthelper->DrawTextLine(DXUTGetFrameStats(DXUTIsVsyncEnabled())); txthelper->DrawTextLine(DXUTGetDeviceStats()); txthelper->DrawTextLine((boost::wformat(L"原子数: %d") % armd.NumAtom).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"スーパーセルの個数: %d") % armd.Nc).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"MDのステップ数: %d") % armd.MD_iter).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"経過時間: %.3f (ps)") % armd.getDeltat()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"格子定数: %.3f (nm)") % armd.getLatticeconst()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"箱の一辺の長さ: %.3f (nm)") % armd.getPeriodiclen()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"設定された温度: %.3f (K)") % armd.getTgiven()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"計算された温度: %.3f (K)") % armd.getTcalc()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"運動エネルギー: %.3f (Hartree)") % armd.Uk).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"ポテンシャルエネルギー: %.3f (Hartree)") % armd.Up).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"全エネルギー: %.3f (Hartree)") % armd.Utot).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"圧力: %.3f (atm)") % armd.getPressure()).str().c_str()); txthelper->DrawTextLine(L"原子の色の違いは働いている力の違いを表す"); txthelper->DrawTextLine(L"赤色に近いほどその原子に働いている力が強い"); txthelper->End(); pd3dDevice->IASetInputLayout(pInputLayout.get()); auto const blendFactor = 0.0f; auto const sampleMask = 0xffffffff; pd3dDevice->OMSetBlendState(pBlendStateNoBlend.get(), &blendFactor, sampleMask); } void SetUI() { g_HUD.RemoveAllControls(); auto iY = 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22); g_HUD.AddButton(IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2); g_HUD.AddButton(IDC_RECALC, L"再計算", 35, iY += 34, 125, 22); // 温度の変更 g_HUD.AddStatic(IDC_OUTPUT, L"温度", 20, iY += 34, 125, 22); g_HUD.GetStatic(IDC_OUTPUT)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddSlider( IDC_SLIDER, 35, iY += 24, 125, 22, 1, 3000, boost::numeric_cast<int>(moleculardynamics::Ar_moleculardynamics::FIRSTTEMP)); // 格子定数の変更 g_HUD.AddStatic(IDC_OUTPUT2, L"格子定数", 20, iY += 34, 125, 22); g_HUD.GetStatic(IDC_OUTPUT2)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddSlider( IDC_SLIDER2, 35, iY += 24, 125, 22, 30, 1000, boost::numeric_cast<int>(moleculardynamics::Ar_moleculardynamics::FIRSTSCALE * LATTICERATIO)); // スーパーセルの個数の変更 g_HUD.AddStatic(IDC_OUTPUT3, L"スーパーセルの個数", 20, iY += 34, 125, 22); g_HUD.GetStatic(IDC_OUTPUT3)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddSlider( IDC_SLIDER3, 35, iY += 24, 125, 22, 1, 16, moleculardynamics::Ar_moleculardynamics::FIRSTNC); // アンサンブルの変更 g_HUD.AddStatic(IDC_OUTPUT4, L"アンサンブル", 20, iY += 40, 125, 22); g_HUD.GetStatic(IDC_OUTPUT4)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddRadioButton(IDC_RADIOA, 1, L"NVTアンサンブル", 35, iY += 24, 125, 22, true); g_HUD.AddRadioButton(IDC_RADIOB, 1, L"NVEアンサンブル", 35, iY += 28, 125, 22, false); // 温度制御法の変更 g_HUD.AddStatic(IDC_OUTPUT4, L"温度制御の方法", 20, iY += 40, 125, 22); g_HUD.GetStatic(IDC_OUTPUT4)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddRadioButton(IDC_RADIOC, 2, L"Langevin法", 35, iY += 24, 125, 22, false); g_HUD.AddRadioButton(IDC_RADIOD, 2, L"Nose-Hoover法", 35, iY += 28, 125, 22, false); g_HUD.AddRadioButton(IDC_RADIOE, 2, L"速度スケーリング法", 35, iY += 28, 125, 22, true); } //-------------------------------------------------------------------------------------- // Initialize everything and go into a render loop //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // Set general DXUT callbacks DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackKeyboard( OnKeyboard ); DXUTSetCallbackMouse( OnMouse ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackDeviceRemoved( OnDeviceRemoved ); // Set the D3D10 DXUT callbacks. Remove these sets if the app doesn't need to support D3D10 DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable ); DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice ); DXUTSetCallbackD3D10SwapChainResized( OnD3D10ResizedSwapChain ); DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender ); DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10ReleasingSwapChain ); DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice ); DXUTInit( true, true, nullptr ); // Parse the command line, show msgboxes on error, no extra command line params DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen InitApp(); // ウィンドウを生成 auto const dispx = ::GetSystemMetrics(SM_CXSCREEN); auto const dispy = ::GetSystemMetrics(SM_CYSCREEN); auto const xpos = (dispx - WINDOWWIDTH) / 2; auto const ypos = (dispy - WINDOWHEIGHT) / 2; DXUTCreateWindow(L"アルゴンの古典分子動力学シミュレーション", nullptr, nullptr, nullptr, xpos, ypos); DXUTCreateDevice(true, WINDOWWIDTH, WINDOWHEIGHT); // 垂直同期をオフにする auto ds = DXUTGetDeviceSettings(); ds.d3d10.SyncInterval = 0; DXUTCreateDeviceFromSettings(&ds); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); }
32.323333
165
0.594411
dc1394
e54280b14e701389df64bcf55a6e4b43a2d1b1ac
1,432
hpp
C++
module_04/ex03/MateriaSource.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
4
2021-12-14T18:02:53.000Z
2022-03-24T01:12:38.000Z
module_04/ex03/MateriaSource.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
null
null
null
module_04/ex03/MateriaSource.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
3
2021-11-01T00:34:50.000Z
2022-01-29T19:57:30.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* MateriaSource.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: phemsi-a <phemsi-a@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/12 12:50:12 by phemsi-a #+# #+# */ /* Updated: 2021/10/17 11:30:06 by phemsi-a ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MATERIASOURCE_HPP #define MATERIASOURCE_HPP #include "IMateriaSource.hpp" #define MAX_MAGICS 4 class MateriaSource : public IMateriaSource { private: AMateria *_magicBook[MAX_MAGICS]; void _storeMateria(AMateria *materia, int i); void _initBook(void); public: MateriaSource(void); MateriaSource(MateriaSource const &instace); ~MateriaSource(void); MateriaSource &operator=(MateriaSource const &rightHandSide); void learnMateria(AMateria*) ; AMateria* createMateria(std::string const & type); }; #endif
35.8
80
0.363827
paulahemsi
e54362429cb0f41b3fcd49c00c8008e615077cac
2,355
cpp
C++
src/QtComponents/Configurators/CtrlPadRectF.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
src/QtComponents/Configurators/CtrlPadRectF.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
src/QtComponents/Configurators/CtrlPadRectF.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
#include <qtcomponents.h> #include "ui_CtrlPadRectF.h" N::CtrlPadRectF:: CtrlPadRectF ( QWidget * parent , Plan * p ) : Widget ( parent , p ) , ui ( new Ui::CtrlPadRectF ) , rect ( NULL ) , identifier ( 0 ) { WidgetClass ; Configure ( ) ; } N::CtrlPadRectF::~CtrlPadRectF(void) { delete ui ; } void N::CtrlPadRectF::closeEvent(QCloseEvent * event) { emit Closed ( identifier , this ) ; QWidget :: closeEvent ( event ) ; } void N::CtrlPadRectF::Configure (void) { ui -> setupUi ( this ) ; plan -> setFont ( this ) ; } void N::CtrlPadRectF::setIdentifier(int id) { identifier = id ; } void N::CtrlPadRectF::ValueChanged(double) { if ( IsNull(rect) ) return ; rect -> setX ( ui->X->value() ) ; rect -> setY ( ui->Y->value() ) ; rect -> setWidth ( ui->W->value() ) ; rect -> setHeight ( ui->H->value() ) ; emit Changed ( identifier , this ) ; } QRectF & N::CtrlPadRectF::Create(void) { rect = new QRectF ( ) ; rect -> setX ( 0 ) ; rect -> setY ( 0 ) ; rect -> setWidth ( 0 ) ; rect -> setHeight ( 0 ) ; return ( *rect ) ; } QRectF & N::CtrlPadRectF::Value(void) { return ( *rect ) ; } QRectF & N::CtrlPadRectF::setValue(QRectF & p) { rect = &p ; ui -> X -> blockSignals ( true ) ; ui -> Y -> blockSignals ( true ) ; ui -> W -> blockSignals ( true ) ; ui -> H -> blockSignals ( true ) ; ui -> X -> setValue ( p.x () ) ; ui -> Y -> setValue ( p.y () ) ; ui -> W -> setValue ( p.width () ) ; ui -> H -> setValue ( p.height() ) ; ui -> X -> blockSignals ( false ) ; ui -> Y -> blockSignals ( false ) ; ui -> W -> blockSignals ( false ) ; ui -> H -> blockSignals ( false ) ; return ( *rect ) ; } QDoubleSpinBox * N::CtrlPadRectF::SpinBox(int index) { switch ( index ) { case 0 : return ui -> X ; case 1 : return ui -> Y ; case 2 : return ui -> W ; case 3 : return ui -> H ; } ; return NULL ; }
25.322581
62
0.449682
Vladimir-Lin
e5491219797554063211f8295cafc70f5da501b2
2,503
cpp
C++
include/obnsim_basic.cpp
sduerr85/OpenBuildNet
126feb4d17558e7bfe1e2e6f081bbfbf1514496f
[ "MIT" ]
null
null
null
include/obnsim_basic.cpp
sduerr85/OpenBuildNet
126feb4d17558e7bfe1e2e6f081bbfbf1514496f
[ "MIT" ]
null
null
null
include/obnsim_basic.cpp
sduerr85/OpenBuildNet
126feb4d17558e7bfe1e2e6f081bbfbf1514496f
[ "MIT" ]
null
null
null
/* -*- mode: C++; indent-tabs-mode: nil; -*- */ /** \file * \brief Basic definitions. * * This file is part of the openBuildNet simulation framework * (OBN-Sim) developed at EPFL. * * \author Truong X. Nghiem (xuan.nghiem@epfl.ch) */ #include <cassert> #include <obnsim_basic.h> #include <cctype> // Name of the GC port on any node const char *OBNsim::NODE_GC_PORT_NAME = "_gc_"; // std::chrono::time_point<std::chrono::steady_clock> OBNsim::clockStart; std::string OBNsim::Utils::trim(const std::string& s0) { std::string s(s0); std::size_t found = s.find_last_not_of(" \t\f\v\n\r"); if (found != std::string::npos) { s.erase(found+1); found = s.find_first_not_of(" \t\f\v\n\r"); s.erase(0, found); } else { s.clear(); } return s; } std::string OBNsim::Utils::toUpper(const std::string& s0) { std::string s(s0); for (auto& c: s) { c = std::toupper(c); } return s; } std::string OBNsim::Utils::toLower(const std::string& s0) { std::string s(s0); for (auto& c: s) { c = std::tolower(c); } return s; } bool OBNsim::Utils::isValidIdentifier(const std::string &name) { if (name.empty() || name[0] == '_') { return false; } return name.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") == std::string::npos; } bool OBNsim::Utils::isValidNodeName(const std::string &name) { if (name.empty() || name.front() == '_' || name.front() == '/' || name.back() == '/') { return false; } if (name.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/") != std::string::npos) { return false; } // Double forward slashes are invalid // Underscore following / is also invalid return (name.find("//") == std::string::npos) && (name.find("/_") == std::string::npos); } void OBNsim::ResizableBuffer::allocateData(std::size_t newsize) { m_data_size = newsize; if (m_data) { // If _allocsize >= _size, we reuse the memory block if (m_data_allocsize < m_data_size) { delete [] m_data; } } else { m_data_allocsize = 0; // Make sure that _allocsize < _size } if (m_data_allocsize < m_data_size) { m_data_allocsize = (m_data_size & 0x0F)?(((m_data_size >> 4)+1) << 4):m_data_size; assert(m_data_allocsize >= m_data_size); m_data = new char[m_data_allocsize]; } }
28.443182
122
0.603676
sduerr85
e54aa0a914225501eaa3d5c768628a6730d5babf
1,374
cpp
C++
tools.cpp
PapaSinku/SinkuEngine
2202162d12a52df8438d7cb8c5ffc37847fd87c4
[ "MIT" ]
null
null
null
tools.cpp
PapaSinku/SinkuEngine
2202162d12a52df8438d7cb8c5ffc37847fd87c4
[ "MIT" ]
null
null
null
tools.cpp
PapaSinku/SinkuEngine
2202162d12a52df8438d7cb8c5ffc37847fd87c4
[ "MIT" ]
null
null
null
#include "tools.hpp" using namespace std; void sdl_error(string error_message) { cout << error_message << endl << "SDL_Error: " << SDL_GetError() << endl; } void sdl_image_error(std::string error_message) { cout << error_message << endl << "SDL_Error: " << IMG_GetError() << endl; } SDL_Surface* imageSurfaceRead(std::string path, SDL_Surface *window_surface) { SDL_Surface* optimizedSurface = NULL; SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if(loadedSurface == NULL) { sdl_image_error("Unable to load image"); return NULL; } optimizedSurface = SDL_ConvertSurface( loadedSurface, window_surface->format, 0 ); if( optimizedSurface == NULL ) { sdl_error("Unable to optimize image"); return loadedSurface; } SDL_FreeSurface( loadedSurface ); return optimizedSurface; } SDL_Texture* imageTextureRead(std::string path, SDL_Renderer *renderer) { SDL_Texture* optimizedSurface = NULL; SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if(loadedSurface == NULL) { sdl_image_error("Unable to load image"); return NULL; } optimizedSurface = SDL_CreateTextureFromSurface(renderer, loadedSurface); if( optimizedSurface == NULL ) { sdl_error("Unable to create texture"); return NULL; } SDL_FreeSurface( loadedSurface ); return optimizedSurface; }
26.941176
86
0.694323
PapaSinku
e558a98dae94c13e4419d76686d76602c313ba65
2,220
hpp
C++
third_party/boost/sandbox/boost/logging/detail/tss/tss_ensure_proper_delete.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
third_party/boost/sandbox/boost/logging/detail/tss/tss_ensure_proper_delete.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
third_party/boost/sandbox/boost/logging/detail/tss/tss_ensure_proper_delete.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
// tss_ensure_proper_delete.hpp // Boost Logging library // // Author: John Torjo, www.torjo.com // // Copyright (C) 2007 John Torjo (see www.torjo.com for email) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org for updates, documentation, and revision history. // See http://www.torjo.com/log2/ for more details #ifndef JT28092007_tss_ensure_proper_delete_HPP_DEFINED #define JT28092007_tss_ensure_proper_delete_HPP_DEFINED #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/logging/detail/fwd.hpp> #include <vector> #include <stdlib.h> namespace boost { namespace logging { namespace detail { struct do_delete_base { virtual ~do_delete_base () {} }; template<class type> struct do_delete : do_delete_base { do_delete(type * val) : m_val(val) {} ~do_delete() { delete m_val; } type * m_val; }; #ifdef BOOST_LOG_TEST_TSS // just for testing void on_end_delete_objects(); #endif struct delete_array : std::vector< do_delete_base* > { typedef boost::logging::threading::mutex mutex; typedef std::vector< do_delete_base* > vector_base; delete_array() {} ~delete_array () { for ( const_iterator b = begin(), e = end(); b != e; ++b) delete *b; #ifdef BOOST_LOG_TEST_TSS on_end_delete_objects(); #endif } void push_back(do_delete_base* p) { mutex::scoped_lock lk(cs); vector_base::push_back(p); } private: mutex cs; }; inline delete_array & object_deleter() { static delete_array a ; return a; } template<class type> inline type * new_object_ensure_delete() { type * val = new type; delete_array & del = object_deleter(); del.push_back( new do_delete<type>(val) ); return val; } template<class type> inline type * new_object_ensure_delete(const type & init) { type * val = new type(init); delete_array & del = object_deleter(); del.push_back( new do_delete<type>(val) ); return val; } }}} #endif
24.395604
81
0.653604
gbucknell
e55e95f3f44d6adfe3cc7adb5b1f81e818affae0
306
hpp
C++
tests/chrono/chrono_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
11
2021-03-15T07:06:21.000Z
2021-09-27T13:54:25.000Z
tests/chrono/chrono_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
null
null
null
tests/chrono/chrono_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
1
2021-06-24T10:46:46.000Z
2021-06-24T10:46:46.000Z
#pragma once //------------------------------------------------------------------------------ namespace chrono_tests { //------------------------------------------------------------------------------ void run_full(); //------------------------------------------------------------------------------ }
21.857143
80
0.140523
olegpublicprofile
e56119450b708afa3994d4c459b6626cf86cb226
6,154
cpp
C++
WinAPI/L13/L13.cpp
virtualmode/Archive
04c41b29edd9b6df1c13ab2318b7c138e59dd81d
[ "MIT" ]
null
null
null
WinAPI/L13/L13.cpp
virtualmode/Archive
04c41b29edd9b6df1c13ab2318b7c138e59dd81d
[ "MIT" ]
null
null
null
WinAPI/L13/L13.cpp
virtualmode/Archive
04c41b29edd9b6df1c13ab2318b7c138e59dd81d
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <process.h> #include <windows.h> #define TEXT_SIZE 128 struct Thread { HANDLE hThread; unsigned Id; }; int k, n, p; // n - номер потока, p - приоритет. HDC hDC; // Указатель на контекст для рисования. HWND hWndControl[4]; Thread Threads[2]; HINSTANCE Instance; LRESULT Result; WNDPROC DefTextProc; // Указатель на функцию обработки текстового поля. wchar_t Text[TEXT_SIZE]; // Обработка сообщений текстового поля: LRESULT CALLBACK TextProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { Result = DefTextProc(hWnd, Message, wParam, lParam); switch (Message) { case WM_GETTEXT: // Обработка полученных данных: k = 0; n = 1; p = 0; while (Text[k] != 0 && Text[k] != L',') { k++; } Text[k] = 0; n = _wtoi(Text) - 1; p = _wtoi(Text + k + 1); if (n >= 0 && n < 2) { if (!SetThreadPriority(Threads[n].hThread, p)) { MessageBox(0, L"Невозможно изменить приоритет.", L"", 0); } else { swprintf(Text, TEXT_SIZE, L"Поток %i [Приоритет %i]", n + 1, p); SendMessage(hWndControl[n], WM_SETTEXT, 0, (LPARAM)Text); } } else { MessageBox(0, L"Введенный поток отсутствует.", L"", 0); } break; default: break; } return Result; } // Функция, работающая в первом потоке. Ее задача - тупо подвигать кнопку 1: unsigned __stdcall FirstThreadFunc( void* pArguments ) { bool d = false; int x = 30; for (int i = 0; i < 1480; i++) { Sleep(1); if (d == false) x++; else x--; if (x > 400) d = true; else if (x < 30) d = false; MoveWindow(hWndControl[0], x, 75, 250, 25, TRUE); } return 0; } // Функция, работающая в первом потоке. Ее задача - тупо подвигать кнопку 2: unsigned __stdcall SecondThreadFunc( void* pArguments ) { bool d = false; int y = 105; for (int i = 0; i < 600; i++) { Sleep(1); if (d == false) y++; else y--; if (y > 205) d = true; else if (y < 105) d = false; MoveWindow(hWndControl[1], 30, y, 250, 25, TRUE); } return 0; } // Функция обработки сообщений ОС Windows (!!! ЭТА ФУНКЦИЯ РАБОТАЕТ В ОСНОВНОМ ПОТОКЕ): LRESULT CALLBACK MainWinProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_CREATE: // Инициализация основного окна и создание на нем элементов управления: hWndControl[0] = CreateWindowW(L"BUTTON", L"Поток 1 [Приоритет 0]", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD, 30, 75, 250, 25, hWnd, (HMENU)0, Instance, 0); hWndControl[1] = CreateWindowW(L"BUTTON", L"Поток 2 [Приоритет 0]", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD, 30, 105, 250, 25, hWnd, (HMENU)1, Instance, 0); hWndControl[2] = CreateWindowW(L"EDIT", 0, WS_CHILD | WS_BORDER | WS_VISIBLE | ES_LEFT, 30, 30, 200, 26, hWnd, (HMENU)2, Instance, 0); // Неиспользуемый указатель. hWndControl[3] = CreateWindowW(L"BUTTON", L"Установить приоритет [Номер потока, Приоритет]", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD, 240, 30, 350, 25, hWnd, (HMENU)3, Instance, 0); DefTextProc = (WNDPROC)GetWindowLong(hWndControl[2], GWL_WNDPROC); SetWindowLong(hWndControl[2], GWL_WNDPROC, (LONG)TextProc); break; case WM_PAINT: TextOutW(hDC, 30, 350, L"Варианты приоритета: -15 -2 -1 0 1 2 15", 46); // Вывод текста на экран. break; case WM_COMMAND: switch (LOWORD(wParam)) { case 0: // Создание потока: Threads[0].hThread = (HANDLE)_beginthreadex(NULL, 0, &FirstThreadFunc, NULL, 0, &Threads[0].Id); break; case 1: Threads[1].hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, &Threads[1].Id); break; case 3: SendMessage(hWndControl[2], WM_GETTEXT, TEXT_SIZE, (LPARAM)Text); break; default: break; } break; case WM_DESTROY: PostQuitMessage(0); return 0; default: break; } return DefWindowProc(hWnd, Message, wParam, lParam); } // Точка входа в приложение: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Определение необходимых переменных: WNDCLASSEX WindowClassEx; // Структура для хранения информации о создаваемом окне. HWND hWndMain; // Идентификатор основного окна. MSG Message; // Переменная для обработки сообщений. // Заполнение структуры WindowClassEx: WindowClassEx.cbSize = sizeof(WNDCLASSEX); WindowClassEx.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW; // Не напрягайтесь, это просто флаги. К лабораторной не имеют никакого отношения. WindowClassEx.lpfnWndProc = MainWinProc; // Указатель на функцию обработки сообщений ОС Windows. WindowClassEx.cbClsExtra = 0; WindowClassEx.cbWndExtra = 0; WindowClassEx.hInstance = hInstance; WindowClassEx.hIcon = NULL; // Иконка отсутствует. WindowClassEx.hCursor = LoadCursor(0, IDC_ARROW); WindowClassEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // Белый цвет окна. WindowClassEx.lpszMenuName = 0; // Меню отсутствует. WindowClassEx.lpszClassName = L"Laboratory"; // Имя класса. Используется операционной системой. WindowClassEx.hIconSm = LoadIcon(0, MAKEINTRESOURCE(32517)); // Какая-то иконка по умолчанию. RegisterClassEx(&WindowClassEx); // Регистрация класса окна, информация о котором берется из вышеописанной структуры. // Создание основного окна: hWndMain = CreateWindowEx(0, L"Laboratory", L"Лабораторная работа 13", WS_TILEDWINDOW, 50, 50, 640, 480, 0, 0, hInstance, 0); // Отображение всего созданного на экране: ShowWindow(hWndMain, SW_SHOWDEFAULT); UpdateWindow(hWndMain); // Получение контекста для рисования в окне: hDC = GetWindowDC(hWndMain); SendMessage(hWndMain, WM_PAINT, 0, 0); // Запуск основного цикла обработки сообщений: while (GetMessage(&Message, 0, 0, 0)) { TranslateMessage(&Message); DispatchMessage(&Message); } // Destroy the thread object. CloseHandle(Threads[0].hThread); CloseHandle(Threads[1].hThread); // Если из цикла вышли, значит пользователь (а может и не он вовсе) закрыл приложение: return (int) Message.wParam; }
31.721649
183
0.668996
virtualmode
e56470106e642884890ee85c08b837144a8feafb
7,624
hpp
C++
library/ATF/CD3DApplicationInfo.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/CD3DApplicationInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/CD3DApplicationInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CD3DApplication.hpp> START_ATF_NAMESPACE namespace Info { using CD3DApplicationAdjustWindowForChange1_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationAdjustWindowForChange1_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationAdjustWindowForChange1_ptr); using CD3DApplicationBuildDeviceList2_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationBuildDeviceList2_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationBuildDeviceList2_ptr); using CD3DApplicationctor_CD3DApplication3_ptr = int64_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationctor_CD3DApplication3_clbk = int64_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationctor_CD3DApplication3_ptr); using CD3DApplicationCleanup3DEnvironment4_ptr = void (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationCleanup3DEnvironment4_clbk = void (WINAPIV*)(struct CD3DApplication*, CD3DApplicationCleanup3DEnvironment4_ptr); using CD3DApplicationConfirmDevice5_ptr = int32_t (WINAPIV*)(struct CD3DApplication*, struct _D3DCAPS8*, uint32_t, _D3DFORMAT); using CD3DApplicationConfirmDevice5_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, struct _D3DCAPS8*, uint32_t, _D3DFORMAT, CD3DApplicationConfirmDevice5_ptr); using CD3DApplicationCreate6_ptr = int32_t (WINAPIV*)(struct CD3DApplication*, HINSTANCE); using CD3DApplicationCreate6_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, HINSTANCE, CD3DApplicationCreate6_ptr); using CD3DApplicationCreateDirect3D7_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationCreateDirect3D7_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationCreateDirect3D7_ptr); using CD3DApplicationDeleteDeviceObjects8_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationDeleteDeviceObjects8_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationDeleteDeviceObjects8_ptr); using CD3DApplicationDisplayErrorMsg9_ptr = int32_t (WINAPIV*)(struct CD3DApplication*, int32_t, uint32_t); using CD3DApplicationDisplayErrorMsg9_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, int32_t, uint32_t, CD3DApplicationDisplayErrorMsg9_ptr); using CD3DApplicationEndLoop10_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationEndLoop10_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationEndLoop10_ptr); using CD3DApplicationFinalCleanup11_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationFinalCleanup11_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationFinalCleanup11_ptr); using CD3DApplicationFindDepthStencilFormat12_ptr = int64_t (WINAPIV*)(struct CD3DApplication*, unsigned int, CD3DApplication::_D3DDEVTYPE, _D3DFORMAT, _D3DFORMAT*); using CD3DApplicationFindDepthStencilFormat12_clbk = int64_t (WINAPIV*)(struct CD3DApplication*, unsigned int, CD3DApplication::_D3DDEVTYPE, _D3DFORMAT, _D3DFORMAT*, CD3DApplicationFindDepthStencilFormat12_ptr); using CD3DApplicationForceWindowed13_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationForceWindowed13_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationForceWindowed13_ptr); using CD3DApplicationFrameMove14_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationFrameMove14_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationFrameMove14_ptr); using CD3DApplicationInitDeviceObjects15_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationInitDeviceObjects15_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationInitDeviceObjects15_ptr); using CD3DApplicationInitialize3DEnvironment16_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationInitialize3DEnvironment16_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationInitialize3DEnvironment16_ptr); using CD3DApplicationInvalidateDeviceObjects17_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationInvalidateDeviceObjects17_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationInvalidateDeviceObjects17_ptr); using CD3DApplicationMsgProc18_ptr = int64_t (WINAPIV*)(struct CD3DApplication*, HWND, UINT, WPARAM, LPARAM); using CD3DApplicationMsgProc18_clbk = int64_t (WINAPIV*)(struct CD3DApplication*, HWND, UINT, WPARAM, LPARAM, CD3DApplicationMsgProc18_ptr); using CD3DApplicationOneTimeSceneInit19_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationOneTimeSceneInit19_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationOneTimeSceneInit19_ptr); using CD3DApplicationPause20_ptr = void (WINAPIV*)(struct CD3DApplication*, int); using CD3DApplicationPause20_clbk = void (WINAPIV*)(struct CD3DApplication*, int, CD3DApplicationPause20_ptr); using CD3DApplicationPrepareLoop21_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationPrepareLoop21_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationPrepareLoop21_ptr); using CD3DApplicationRelease22_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRelease22_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRelease22_ptr); using CD3DApplicationRender23_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRender23_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRender23_ptr); using CD3DApplicationRender3DEnvironment24_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRender3DEnvironment24_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRender3DEnvironment24_ptr); using CD3DApplicationResize3DEnvironment25_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationResize3DEnvironment25_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationResize3DEnvironment25_ptr); using CD3DApplicationRestoreDeviceObjects26_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRestoreDeviceObjects26_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRestoreDeviceObjects26_ptr); using CD3DApplicationRun27_ptr = int64_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRun27_clbk = int64_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRun27_ptr); using CD3DApplicationSelectDeviceProc28_ptr = int64_t (WINAPIV*)(HWND__*, unsigned int, uint64_t, int64_t); using CD3DApplicationSelectDeviceProc28_clbk = int64_t (WINAPIV*)(HWND__*, unsigned int, uint64_t, int64_t, CD3DApplicationSelectDeviceProc28_ptr); using CD3DApplicationToggleFullscreen29_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationToggleFullscreen29_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationToggleFullscreen29_ptr); using CD3DApplicationUserSelectNewDevice30_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationUserSelectNewDevice30_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationUserSelectNewDevice30_ptr); }; // end namespace Info END_ATF_NAMESPACE
103.027027
219
0.797613
lemkova
e564c3e71bca048d54edb8b13dcfcd96bf76d6ea
3,315
hpp
C++
include/Mahi/Robo/Mechatronics/AtiSensor.hpp
mahilab/mahi-robo
8df76b7d0174feb3569182cbd65b0305d2a57a22
[ "MIT" ]
1
2020-05-07T13:40:28.000Z
2020-05-07T13:40:28.000Z
include/Mahi/Robo/Mechatronics/AtiSensor.hpp
mahilab/mahi-robo
8df76b7d0174feb3569182cbd65b0305d2a57a22
[ "MIT" ]
null
null
null
include/Mahi/Robo/Mechatronics/AtiSensor.hpp
mahilab/mahi-robo
8df76b7d0174feb3569182cbd65b0305d2a57a22
[ "MIT" ]
1
2020-12-21T09:44:36.000Z
2020-12-21T09:44:36.000Z
// MIT License // // Copyright (c) 2020 Mechatronics and Haptic Interfaces Lab - Rice University // // 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. // // Author(s): Evan Pezent (epezent@rice.edu) #pragma once #include <Mahi/Robo/Mechatronics/ForceSensor.hpp> #include <Mahi/Robo/Mechatronics/TorqueSensor.hpp> #include <array> #include <string> namespace mahi { namespace robo { /// Implements an ATI force/torque transducer class AtiSensor : public ForceSensor, public TorqueSensor { public: /// Calibration matrix data obtained from "UserAxis" elements /// in ATI supplied calibration file (e.g. "FTXXXXX.cal") struct Calibration { std::array<double, 6> Fx; std::array<double, 6> Fy; std::array<double, 6> Fz; std::array<double, 6> Tx; std::array<double, 6> Ty; std::array<double, 6> Tz; }; public: /// Constucts AtiSensor with unspecified channels and no calibration AtiSensor(); /// Constructs AtiSensor with specified channels and loads calibration from filepath AtiSensor(const double* ch0, const double* ch1, const double* ch2, const double* ch3, const double* ch4, const double* ch5, const std::string& filepath); /// Constructs AtiSensor from specified channels and manual calibration AtiSensor(const double* ch0, const double* ch1, const double* ch2, const double* ch3, const double* ch4, const double* ch5, Calibration calibration); /// Sets the voltages channels associated with this ATI sensor void set_channels(const double* ch0, const double* ch1, const double* ch2, const double* ch3, const double* ch4, const double* ch5); /// Loads calibration from ATI calibration file (e.g. "FTXXXXX.cal") bool load_calibration(const std::string& filepath); /// Allows for manually setting calibration void set_calibration(Calibration calibration); /// Returns force along specified axis double get_force(Axis axis) override; /// Returns forces along X, Z, and Z axes std::vector<double> get_forces() override; /// Returns torque along specifed axis double get_torque(Axis axis) override; /// Returns torque along X, Z, and Z axes std::vector<double> get_torques() override; /// Zeros all forces and torques at current preload void zero() override; private: /// Updates biased voltages void update_biased_voltages(); private: std::vector<const double*> channels_; ///< raw voltage channels Calibration calibration_; ///< calibration matrix std::array<double, 6> bias_; ///< bias vector std::array<double, 6> bSTG_; ///< biased strain gauge voltages }; } // namespace robo } // namespace mahi
41.4375
97
0.694419
mahilab
e567fe799a756faf5de1745546fc7f344992a2c7
10,116
cc
C++
thirdparty/aria2/src/DefaultBtMessageDispatcher.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
null
null
null
thirdparty/aria2/src/DefaultBtMessageDispatcher.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
2
2021-04-08T08:46:23.000Z
2021-04-08T08:57:58.000Z
thirdparty/aria2/src/DefaultBtMessageDispatcher.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
null
null
null
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * 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 * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "DefaultBtMessageDispatcher.h" #include <algorithm> #include "prefs.h" #include "BtAbortOutstandingRequestEvent.h" #include "BtCancelSendingPieceEvent.h" #include "BtChokingEvent.h" #include "BtMessageFactory.h" #include "message.h" #include "DownloadContext.h" #include "PeerStorage.h" #include "PieceStorage.h" #include "BtMessage.h" #include "Peer.h" #include "Piece.h" #include "LogFactory.h" #include "Logger.h" #include "a2functional.h" #include "a2algo.h" #include "RequestGroupMan.h" #include "RequestGroup.h" #include "util.h" #include "fmt.h" #include "PeerConnection.h" #include "BtCancelMessage.h" namespace aria2 { DefaultBtMessageDispatcher::DefaultBtMessageDispatcher() : cuid_{0}, downloadContext_{nullptr}, peerConnection_{nullptr}, messageFactory_{nullptr}, requestGroupMan_{nullptr}, requestTimeout_{0} { } DefaultBtMessageDispatcher::~DefaultBtMessageDispatcher() { A2_LOG_DEBUG("DefaultBtMessageDispatcher::deleted"); } void DefaultBtMessageDispatcher::addMessageToQueue( std::unique_ptr<BtMessage> btMessage) { btMessage->onQueued(); messageQueue_.push_back(std::move(btMessage)); } void DefaultBtMessageDispatcher::sendMessagesInternal() { auto tempQueue = std::vector<std::unique_ptr<BtMessage>>{}; while (!messageQueue_.empty()) { auto msg = std::move(messageQueue_.front()); messageQueue_.pop_front(); if (msg->isUploading()) { if (requestGroupMan_->doesOverallUploadSpeedExceed() || downloadContext_->getOwnerRequestGroup()->doesUploadSpeedExceed()) { tempQueue.push_back(std::move(msg)); continue; } } msg->send(); } if (!tempQueue.empty()) { messageQueue_.insert(std::begin(messageQueue_), std::make_move_iterator(std::begin(tempQueue)), std::make_move_iterator(std::end(tempQueue))); } } void DefaultBtMessageDispatcher::sendMessages() { if (peerConnection_->getBufferEntrySize() < A2_IOV_MAX) { sendMessagesInternal(); } peerConnection_->sendPendingData(); } namespace { std::vector<BtMessage*> toRawPointers(const std::deque<std::unique_ptr<BtMessage>>& v) { auto x = std::vector<BtMessage*>{}; x.reserve(v.size()); for (auto& i : v) { x.push_back(i.get()); } return x; } } // namespace // Cancel sending piece message to peer. void DefaultBtMessageDispatcher::doCancelSendingPieceAction(size_t index, int32_t begin, int32_t length) { BtCancelSendingPieceEvent event(index, begin, length); auto q = toRawPointers(messageQueue_); for (auto i : q) { i->onCancelSendingPieceEvent(event); } } // Cancel sending piece message to peer. // TODO Is this method really necessary? void DefaultBtMessageDispatcher::doCancelSendingPieceAction( const std::shared_ptr<Piece>& piece) { } namespace { void abortOutstandingRequest(const RequestSlot* slot, const std::shared_ptr<Piece>& piece, cuid_t cuid) { A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT, cuid, static_cast<unsigned long>(slot->getIndex()), slot->getBegin(), static_cast<unsigned long>(slot->getBlockIndex()))); piece->cancelBlock(slot->getBlockIndex()); } } // namespace // localhost cancels outstanding download requests to the peer. void DefaultBtMessageDispatcher::doAbortOutstandingRequestAction( const std::shared_ptr<Piece>& piece) { for (auto& slot : requestSlots_) { if (slot->getIndex() == piece->getIndex()) { abortOutstandingRequest(slot.get(), piece, cuid_); } } requestSlots_.erase( std::remove_if(std::begin(requestSlots_), std::end(requestSlots_), [&](const std::unique_ptr<RequestSlot>& slot) { return slot->getIndex() == piece->getIndex(); }), std::end(requestSlots_)); BtAbortOutstandingRequestEvent event(piece); auto tempQueue = toRawPointers(messageQueue_); for (auto i : tempQueue) { i->onAbortOutstandingRequestEvent(event); } } // localhost received choke message from the peer. void DefaultBtMessageDispatcher::doChokedAction() { for (auto& slot : requestSlots_) { if (!peer_->isInPeerAllowedIndexSet(slot->getIndex())) { A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_CHOKED, cuid_, static_cast<unsigned long>(slot->getIndex()), slot->getBegin(), static_cast<unsigned long>(slot->getBlockIndex()))); slot->getPiece()->cancelBlock(slot->getBlockIndex()); } } requestSlots_.erase( std::remove_if(std::begin(requestSlots_), std::end(requestSlots_), [&](const std::unique_ptr<RequestSlot>& slot) { return !peer_->isInPeerAllowedIndexSet(slot->getIndex()); }), std::end(requestSlots_)); } // localhost dispatched choke message to the peer. void DefaultBtMessageDispatcher::doChokingAction() { BtChokingEvent event; auto tempQueue = toRawPointers(messageQueue_); for (auto i : tempQueue) { i->onChokingEvent(event); } } void DefaultBtMessageDispatcher::checkRequestSlotAndDoNecessaryThing() { for (auto& slot : requestSlots_) { if (slot->isTimeout(requestTimeout_)) { A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_TIMEOUT, cuid_, static_cast<unsigned long>(slot->getIndex()), slot->getBegin(), static_cast<unsigned long>(slot->getBlockIndex()))); slot->getPiece()->cancelBlock(slot->getBlockIndex()); peer_->snubbing(true); } else if (slot->getPiece()->hasBlock(slot->getBlockIndex())) { A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_ACQUIRED, cuid_, static_cast<unsigned long>(slot->getIndex()), slot->getBegin(), static_cast<unsigned long>(slot->getBlockIndex()))); addMessageToQueue(messageFactory_->createCancelMessage( slot->getIndex(), slot->getBegin(), slot->getLength())); } } requestSlots_.erase( std::remove_if(std::begin(requestSlots_), std::end(requestSlots_), [&](const std::unique_ptr<RequestSlot>& slot) { return slot->isTimeout(requestTimeout_) || slot->getPiece()->hasBlock(slot->getBlockIndex()); }), std::end(requestSlots_)); } bool DefaultBtMessageDispatcher::isSendingInProgress() { return peerConnection_->getBufferEntrySize(); } bool DefaultBtMessageDispatcher::isOutstandingRequest(size_t index, size_t blockIndex) { for (auto& slot : requestSlots_) { if (slot->getIndex() == index && slot->getBlockIndex() == blockIndex) { return true; } } return false; } const RequestSlot* DefaultBtMessageDispatcher::getOutstandingRequest(size_t index, int32_t begin, int32_t length) { for (auto& slot : requestSlots_) { if (slot->getIndex() == index && slot->getBegin() == begin && slot->getLength() == length) { return slot.get(); } } return nullptr; } void DefaultBtMessageDispatcher::removeOutstandingRequest( const RequestSlot* slot) { for (auto i = std::begin(requestSlots_), eoi = std::end(requestSlots_); i != eoi; ++i) { if (*(*i) == *slot) { abortOutstandingRequest((*i).get(), (*i)->getPiece(), cuid_); requestSlots_.erase(i); break; } } } void DefaultBtMessageDispatcher::addOutstandingRequest( std::unique_ptr<RequestSlot> slot) { requestSlots_.push_back(std::move(slot)); } size_t DefaultBtMessageDispatcher::countOutstandingUpload() { return std::count_if(std::begin(messageQueue_), std::end(messageQueue_), std::mem_fn(&BtMessage::isUploading)); } void DefaultBtMessageDispatcher::setPeer(const std::shared_ptr<Peer>& peer) { peer_ = peer; } void DefaultBtMessageDispatcher::setDownloadContext( DownloadContext* downloadContext) { downloadContext_ = downloadContext; } void DefaultBtMessageDispatcher::setBtMessageFactory(BtMessageFactory* factory) { messageFactory_ = factory; } void DefaultBtMessageDispatcher::setRequestGroupMan(RequestGroupMan* rgman) { requestGroupMan_ = rgman; } } // namespace aria2
31.6125
80
0.666568
deltegic
e56b185395191bc7c313969043e419e2ad1b893d
4,119
cpp
C++
src/tests/functional/plugin/gpu/concurrency/gpu_concurrency_tests.cpp
ivkalgin/openvino
81685c8d212135dd9980da86a18db41fbf6d250a
[ "Apache-2.0" ]
null
null
null
src/tests/functional/plugin/gpu/concurrency/gpu_concurrency_tests.cpp
ivkalgin/openvino
81685c8d212135dd9980da86a18db41fbf6d250a
[ "Apache-2.0" ]
18
2022-01-21T08:42:58.000Z
2022-03-28T13:21:31.000Z
src/tests/functional/plugin/gpu/concurrency/gpu_concurrency_tests.cpp
ematroso/openvino
403339f8f470c90dee6f6d94ed58644b2787f66b
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <string> #include <utility> #include <vector> #include <memory> #include "openvino/runtime/core.hpp" #include <gpu/gpu_config.hpp> #include <common_test_utils/test_common.hpp> #include <functional_test_utils/plugin_cache.hpp> #include "ngraph_functions/subgraph_builders.hpp" #include "functional_test_utils/blob_utils.hpp" #include "openvino/core/preprocess/pre_post_process.hpp" #include "transformations/utils/utils.hpp" using namespace ::testing; using ConcurrencyTestParams = std::tuple<size_t, // number of streams size_t>; // number of requests class OVConcurrencyTest : public CommonTestUtils::TestsCommon, public testing::WithParamInterface<ConcurrencyTestParams> { void SetUp() override { std::tie(num_streams, num_requests) = this->GetParam(); fn_ptrs = {ngraph::builder::subgraph::makeSplitMultiConvConcat(), ngraph::builder::subgraph::makeMultiSingleConv()}; }; public: static std::string getTestCaseName(const testing::TestParamInfo<ConcurrencyTestParams>& obj) { size_t streams, requests; std::tie(streams, requests) = obj.param; return "_num_streams_" + std::to_string(streams) + "_num_req_" + std::to_string(requests); } protected: size_t num_streams; size_t num_requests; std::vector<std::shared_ptr<ngraph::Function>> fn_ptrs; }; TEST_P(OVConcurrencyTest, canInferTwoExecNets) { auto ie = ov::runtime::Core(); ov::ResultVector outputs; std::vector<ov::runtime::InferRequest> irs; std::vector<std::vector<uint8_t>> ref; std::vector<int> outElementsCount; for (size_t i = 0; i < fn_ptrs.size(); ++i) { auto fn = fn_ptrs[i]; auto exec_net = ie.compile_model(fn_ptrs[i], CommonTestUtils::DEVICE_GPU, {{ov::ie::PluginConfigParams::KEY_GPU_THROUGHPUT_STREAMS, std::to_string(num_streams)}}); auto input = fn_ptrs[i]->get_parameters().at(0); auto output = fn_ptrs[i]->get_results().at(0); for (int j = 0; j < num_streams * num_requests; j++) { outputs.push_back(output); auto inf_req = exec_net.create_infer_request(); irs.push_back(inf_req); auto tensor = FuncTestUtils::create_and_fill_tensor(input->get_element_type(), input->get_shape()); inf_req.set_tensor(input, tensor); outElementsCount.push_back(ov::shape_size(fn_ptrs[i]->get_output_shape(0))); const auto in_tensor = inf_req.get_tensor(input); const auto tensorSize = in_tensor.get_byte_size(); const auto inBlobBuf = static_cast<uint8_t*>(in_tensor.data()); std::vector<uint8_t> inData(inBlobBuf, inBlobBuf + tensorSize); auto reOutData = ngraph::helpers::interpreterFunction(fn_ptrs[i], {inData}).front().second; ref.push_back(reOutData); } } const int niter = 10; for (int i = 0; i < niter; i++) { for (auto ir : irs) { ir.start_async(); } for (auto ir : irs) { ir.wait(); } } auto thr = FuncTestUtils::GetComparisonThreshold(InferenceEngine::Precision::FP32); for (size_t i = 0; i < irs.size(); ++i) { const auto &refBuffer = ref[i].data(); ASSERT_EQ(outElementsCount[i], irs[i].get_tensor(outputs[i]).get_size()); FuncTestUtils::compareRawBuffers(irs[i].get_tensor(outputs[i]).data<float>(), reinterpret_cast<const float *>(refBuffer), outElementsCount[i], outElementsCount[i], thr); } } const std::vector<size_t> num_streams{ 1, 2 }; const std::vector<size_t> num_requests{ 1, 4 }; INSTANTIATE_TEST_SUITE_P(smoke_RemoteTensor, OVConcurrencyTest, ::testing::Combine(::testing::ValuesIn(num_streams), ::testing::ValuesIn(num_requests)), OVConcurrencyTest::getTestCaseName);
37.108108
130
0.636562
ivkalgin
e57059c1223fa766359d5c15c87c1a0537d43e5f
6,367
cpp
C++
src/gamebase/src/impl/ui/ScrollBar.cpp
TheMrButcher/opengl_lessons
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
1
2016-10-25T21:15:16.000Z
2016-10-25T21:15:16.000Z
src/gamebase/src/impl/ui/ScrollBar.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
375
2016-06-04T11:27:40.000Z
2019-04-14T17:11:09.000Z
src/gamebase/src/impl/ui/ScrollBar.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
null
null
null
/** * Copyright (c) 2018 Slavnejshev Filipp * This file is licensed under the terms of the MIT license. */ #include <stdafx.h> #include <gamebase/impl/ui/ScrollBar.h> #include <gamebase/impl/geom/PointGeometry.h> #include <gamebase/impl/geom/RectGeometry.h> #include <gamebase/impl/serial/ISerializer.h> #include <gamebase/impl/serial/IDeserializer.h> #include <gamebase/math/Math.h> namespace gamebase { namespace impl { class ScrollBar::DragBarMovement : public FloatValue { public: DragBarMovement(ScrollBar* scrollBar) : m_scrollBar(scrollBar) {} virtual float get() const override { THROW_EX() << "DragBarMovement::get() is unsupported"; } virtual void set(const float& value) override { if (!m_scrollBar->m_controlledValue) return; if (value == 0.0f) m_start = m_scrollBar->m_controlledValue->get(); else m_scrollBar->dragByPixels(m_start, value); } private: ScrollBar* m_scrollBar; float m_start; }; ScrollBar::ScrollBar( const std::shared_ptr<ScrollBarSkin>& skin, const std::shared_ptr<IRelativeOffset>& position) : OffsettedPosition(position) , Drawable(this) , m_skin(skin) , m_inited(false) , m_minVal(0) , m_maxVal(0) , m_visibleZoneSize(0) , m_dragBarOffset(std::make_shared<FixedOffset>()) , m_dragBarCallback(std::make_shared<DragBarMovement>(this)) , m_sizeFunc(m_skin->direction() == Direction::Horizontal ? &BoundingBox::width : &BoundingBox::height) { m_collection.setParentPosition(this); if (auto decButton = skin->createDecButton()) { decButton->setCallback([this]() { decrease(); }); m_collection.addObject(decButton); } if (auto incButton = skin->createIncButton()) { incButton->setCallback([this]() { increase(); }); m_collection.addObject(incButton); } if (m_dragBar = skin->createDragBar(m_dragBarOffset)) { if (m_skin->direction() == Direction::Horizontal) m_dragBar->setControlledHorizontal(m_dragBarCallback); else m_dragBar->setControlledVertical(m_dragBarCallback); m_collection.addObject(m_dragBar); } } void ScrollBar::move(float numOfSteps) { step(numOfSteps * m_skin->step()); } void ScrollBar::loadResources() { m_skin->loadResources(); m_collection.loadResources(); if (!m_inited) { m_inited = true; update(); m_collection.loadResources(); } } void ScrollBar::setBox(const BoundingBox& allowedBox) { m_skin->setBox(allowedBox); auto box = m_skin->box(); setPositionBoxes(allowedBox, box); m_collection.setBox(box); update(); } IScrollable* ScrollBar::findScrollableByPoint(const Vec2& point) { if (!isVisible()) return false; PointGeometry pointGeom(point); RectGeometry rectGeom(box()); if (!rectGeom.intersects(&pointGeom, position(), Transform2())) return nullptr; return this; } void ScrollBar::registerObject(PropertiesRegisterBuilder* builder) { builder->registerObject("skin", m_skin.get()); builder->registerObject("objects", &m_collection); } void ScrollBar::applyScroll(float scroll) { if (isVisible()) move(scroll); } void ScrollBar::serialize(Serializer& s) const { s << "minValue" << m_minVal << "maxValue" << m_maxVal << "visibleZone" << m_visibleZoneSize << "position" << m_offset << "skin" << m_skin; } std::unique_ptr<IObject> deserializeScrollBar(Deserializer& deserializer) { DESERIALIZE(std::shared_ptr<IRelativeOffset>, position); DESERIALIZE(std::shared_ptr<ScrollBarSkin>, skin); DESERIALIZE(float, minValue); DESERIALIZE(float, maxValue); DESERIALIZE(float, visibleZone); std::unique_ptr<ScrollBar> result(new ScrollBar(skin, position)); result->setRange(minValue, maxValue); result->setVisibleZoneSize(visibleZone); return std::move(result); } REGISTER_CLASS(ScrollBar); void ScrollBar::decrease() { move(-1); } void ScrollBar::increase() { move(+1); } void ScrollBar::update() { if (!m_inited) return; if (m_dragBar && box().isValid()) { auto dragBox = m_skin->dragBox(); if (m_visibleZoneSize >= m_maxVal - m_minVal) { if (!m_skin->alwaysShow()) { setVisible(false); } else { m_dragBar->setSelectionState(SelectionState::Disabled); } } else { setVisible(true); float boxSize = (dragBox.*m_sizeFunc)(); float dragBarSize = boxSize * m_visibleZoneSize / (m_maxVal - m_minVal); BoundingBox dragBarBox = m_skin->direction() == Direction::Horizontal ? BoundingBox( Vec2(-0.5f * dragBarSize, -0.5f * dragBox.height()), Vec2(0.5f * dragBarSize, 0.5f * dragBox.height())) : BoundingBox( Vec2(-0.5f * dragBox.width(), -0.5f * dragBarSize), Vec2(0.5f * dragBox.width(), 0.5f * dragBarSize)); m_dragBar->setBox(dragBarBox); m_dragBar->setSelectionState(SelectionState::None); } } step(0.0f); } void ScrollBar::dragByPixels(float startValue, float offsetInPixels) { float offset = offsetInPixels / (m_skin->dragBox().*m_sizeFunc)() * (m_maxVal - m_minVal); step(startValue + offset - m_controlledValue->get()); } void ScrollBar::step(float value) { if (!m_controlledValue) return; float curVal = m_controlledValue->get(); m_controlledValue->set(clamp( curVal + value, m_minVal, std::max(m_minVal, m_maxVal - m_visibleZoneSize))); if (m_dragBar && m_dragBar->selectionState() != SelectionState::Disabled && box().isValid()) { auto dragBox = m_skin->dragBox(); curVal = m_controlledValue->get(); float midRatio = (curVal + 0.5f * m_visibleZoneSize) / (m_maxVal - m_minVal); Vec2 offset = m_skin->direction() == Direction::Horizontal ? Vec2( dragBox.bottomLeft.x + midRatio * dragBox.width(), 0.5f * (dragBox.bottomLeft.y + dragBox.topRight.y)) : Vec2( 0.5f * (dragBox.bottomLeft.x + dragBox.topRight.x), dragBox.bottomLeft.y + midRatio * dragBox.height()); m_dragBarOffset->update(offset); } } } }
31.058537
98
0.639705
TheMrButcher
e5706f801da9659f49e9f9825e89e2ebdcb06b31
8,942
cpp
C++
src/autowiring/test/AutoPacketFactoryTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autowiring/test/AutoPacketFactoryTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autowiring/test/AutoPacketFactoryTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/CoreThread.h> #include CHRONO_HEADER #include THREAD_HEADER class AutoPacketFactoryTest: public testing::Test {}; TEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileNotStarted) { AutoRequired<AutoPacketFactory> factory; ASSERT_THROW(factory->NewPacket(), autowiring_error) << "Issuing a packet in a context that has not yet been started should throw an exception"; } TEST_F(AutoPacketFactoryTest, StopReallyStops) { AutoCurrentContext()->SignalShutdown(); AutoRequired<AutoPacketFactory> factory; ASSERT_TRUE(factory->ShouldStop()) << "Expected that an attempt to insert a packet factory to an already-stopped context would stop the packet factory"; } TEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileStopped) { AutoCurrentContext()->SignalShutdown(); AutoRequired<AutoPacketFactory> factory; ASSERT_THROW(factory->NewPacket(), autowiring_error) << "Issuing a packet in a context that has already been stopped should throw an exception"; } class IssuesPacketWaitsThenQuits: public CoreThread { public: IssuesPacketWaitsThenQuits(void) { // Note: Don't do this in practice. This only works because we only inject this type // into a context that's already running; normally, creating a packet from our ctor can // cause an exception if we are being injected before Initiate is called. AutoRequired<AutoPacketFactory> factory; m_packet = factory->NewPacket(); } bool m_hasQuit = false; std::shared_ptr<AutoPacket> m_packet; void Run(void) override { // Move shared pointer locally: std::shared_ptr<AutoPacket> packet; std::swap(packet, m_packet); // Just wait a bit, then return, just like we said we would this->ThreadSleep(std::chrono::milliseconds(50)); // Update our variable and then return out: m_hasQuit = true; } }; TEST_F(AutoPacketFactoryTest, WaitRunsDownAllPackets) { AutoCurrentContext()->Initiate(); // Create a factory in our context, factory had better be started: AutoRequired<AutoPacketFactory> factory; ASSERT_TRUE(factory->IsRunning()) << "Factory was not started even though it was a member of an initiated context"; // Make the thread create and hold a packet, and then return AutoRequired<IssuesPacketWaitsThenQuits> ipwtq; // Shutdown context AutoCurrentContext()->SignalShutdown(); // Now we're going to try to run down the factory: factory->Wait(); // Verify that the thread has quit: ASSERT_TRUE(ipwtq->m_hasQuit) << "AutoPacketFactory::Wait returned prematurely"; } class HoldsAutoPacketFactoryReference { public: AutoRequired<AutoPacketFactory> m_factory; int m_value = 0; // Just a dummy AutoFilter method so that this class is recognized as an AutoFilter void AutoFilter(int value) { m_value = value; } }; TEST_F(AutoPacketFactoryTest, AutoPacketFactoryCycle) { AutoCurrentContext()->Initiate(); std::weak_ptr<CoreContext> ctxtWeak; std::weak_ptr<HoldsAutoPacketFactoryReference> hapfrWeak; std::shared_ptr<AutoPacket> packet; { // Create a context, fill it up, kick it off: AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<HoldsAutoPacketFactoryReference> hapfr(ctxt); ctxt->Initiate(); // A weak pointer is used to detect object destruction ctxtWeak = ctxt; hapfrWeak = hapfr; // Trivial validation-of-reciept: AutoRequired<AutoPacketFactory> factory; { auto trivial = factory->NewPacket(); trivial->Decorate((int) 54); ASSERT_EQ(54, hapfr->m_value) << "A simple packet was not received as expected by an AutoFilter"; } // Create a packet which will force in a back-reference: packet = factory->NewPacket(); // Terminate the context: ctxt->SignalShutdown(); // Verify that we can still decorate the packet and also that the packet is delivered to the factory: packet->Decorate((int) 55); // Relock, verify the value was received by the hapfr: ASSERT_EQ(55, hapfr->m_value) << "AutoFilter did not receive a packet as expected"; } // The context cannot go out of socpe until all packets in the context are out of scope ASSERT_FALSE(ctxtWeak.expired()) << "Context went out of scope before all packets were finished being processed"; // Now we can release the packet and verify that everything gets cleaned up: packet.reset(); ASSERT_TRUE(ctxtWeak.expired()) << "AutoPacketFactory incorrectly held a cyclic reference even after the context was shut down"; ASSERT_TRUE(hapfrWeak.expired()) << "The last packet from a factory was released; this should have resulted in teardown, but it did not"; } class DelaysAutoPacketsOneMS { public: void AutoFilter(int value) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } }; TEST_F(AutoPacketFactoryTest, AutoPacketStatistics) { // Create a context, fill it up, kick it off: AutoCurrentContext ctxt; AutoRequired<DelaysAutoPacketsOneMS> dapoms; AutoRequired<AutoPacketFactory> factory; ctxt->Initiate(); int numPackets = 20; // Send 20 packets which should all be delayed 1ms for (int i = 0; i < numPackets; ++i) { auto packet = factory->NewPacket(); packet->Decorate(i); } // Shutdown our context, and rundown our factory ctxt->SignalShutdown(); factory->Wait(); // Ensure that the statistics are not too wrong // We delayed each packet by one ms, and our statistics are given in nanoseconds double packetDelay = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(1)).count(); ASSERT_EQ(numPackets, factory->GetTotalPacketCount()) << "The factory did not get enough packets"; ASSERT_LE(packetDelay, factory->GetMeanPacketLifetime()) << "The mean packet lifetime was less than the delay on each packet"; } TEST_F(AutoPacketFactoryTest, MultipleInstanceAddition) { AutoCurrentContext ctxt; AutoRequired<AutoPacketFactory> factory; ctxt->Initiate(); bool ary[2] = {}; for (size_t i = 0; i < 2; i++) *factory += [i, &ary] (int) { ary[i] = true; }; auto packet = factory->NewPacket(); packet->Decorate(101); ASSERT_TRUE(ary[0]) << "First of two identically typed AutoFilter lambdas was not called"; ASSERT_TRUE(ary[1]) << "Second of two identically typed AutoFilter lambdas was not called"; } TEST_F(AutoPacketFactoryTest, AddSubscriberTest) { AutoCurrentContext ctxt; AutoRequired<AutoPacketFactory> factory; ctxt->Initiate(); bool first_called = false; bool second_called = false; factory->AddSubscriber(AutoFilterDescriptor([&first_called](int) {first_called = true; })); { std::vector<AutoFilterDescriptor> descs; factory->AppendAutoFiltersTo(descs); ASSERT_EQ(1UL, descs.size()) << "Expected exactly one AutoFilters after call to AddSubscriber"; } *factory += [&second_called] (int v) { second_called = true; ASSERT_EQ(101, v) << "Decoration value mismatch"; }; { std::vector<AutoFilterDescriptor> descs; factory->AppendAutoFiltersTo(descs); ASSERT_EQ(2UL, descs.size()) << "Expected exactly two AutoFilters on this packet"; } auto packet = factory->NewPacket(); ASSERT_FALSE(first_called) << "Normal subscriber called too early"; ASSERT_FALSE(second_called) << "Subscriber added with operator+= called too early"; packet->DecorateImmediate(int(101)); ASSERT_TRUE(first_called) << "Normal subscriber never called"; ASSERT_TRUE(second_called) << "Subscriber added with operator+= never called"; } TEST_F(AutoPacketFactoryTest, CanRemoveAddedLambda) { AutoCurrentContext()->Initiate(); AutoRequired<AutoPacketFactory> factory; auto desc = *factory += [](int&){}; auto packet1 = factory->NewPacket(); *factory -= desc; auto packet2 = factory->NewPacket(); ASSERT_TRUE(packet1->Has<int>()) << "First packet did not posess expected decoration"; ASSERT_FALSE(packet2->Has<int>()) << "Decoration present even after all filters were removed from a factory"; } TEST_F(AutoPacketFactoryTest, CurrentPacket) { AutoCurrentContext()->Initiate(); AutoRequired<AutoPacketFactory> factory; ASSERT_EQ(nullptr, factory->CurrentPacket()) << "Current packet returned before any packets were issued"; auto packet = factory->NewPacket(); ASSERT_EQ(packet, factory->CurrentPacket()) << "Current packet was not reported correctly as being issued to the known current packet"; packet.reset(); ASSERT_EQ(nullptr, factory->CurrentPacket()) << "A current packet was reported after the current packet has expired"; } TEST_F(AutoPacketFactoryTest, IsRunningWhilePacketIssued) { AutoCurrentContext ctxt; ctxt->Initiate(); AutoRequired<AutoPacketFactory> factory; auto packet = factory->NewPacket(); ctxt->SignalShutdown(); ASSERT_TRUE(factory->IsRunning()) << "Factory should be considered to be running as long as packets are outstanding"; }
35.066667
154
0.733057
CaseyCarter
e5763e9b19aa0e988bd1b926a2cab8712d67d804
773
cpp
C++
NonLinearSimultaneousEquationsTest.cpp
Hiroshi-Nakamura/NonLinearSimultaneousEquations
a5afac2f151a3ff83b75ba46bb1d3317038d271d
[ "MIT" ]
null
null
null
NonLinearSimultaneousEquationsTest.cpp
Hiroshi-Nakamura/NonLinearSimultaneousEquations
a5afac2f151a3ff83b75ba46bb1d3317038d271d
[ "MIT" ]
null
null
null
NonLinearSimultaneousEquationsTest.cpp
Hiroshi-Nakamura/NonLinearSimultaneousEquations
a5afac2f151a3ff83b75ba46bb1d3317038d271d
[ "MIT" ]
null
null
null
#include "NonLinearSimultaneousEquations.hpp" #include <iostream> int main(int argc, char** argv){ /// prepair initial x Eigen::VectorXd x_val(2); x_val << 0.0, 0.5; /// solve NonLinearSimultaneousEquations::solve( { [](const std::vector<AutomaticDifferentiation::FuncPtr<double>> x) { return x[0]*x[0]+x[1]*x[1]-1.0; /// on unit circle }, [](const std::vector<AutomaticDifferentiation::FuncPtr<double>> x) { return (x[0]-1.0)*(x[0]-1.0)+(x[1]-1.0)*(x[1]-1.0)-1.0; /// on unit circle centered at (1.0,1.0) } }, /// equations x_val /// variables ); std::cout << "soluition x:" << std::endl << x_val <<std::endl; }
28.62963
112
0.518758
Hiroshi-Nakamura
ec77219258d453a0236d273a3cfdf01a71641a5c
23,036
hpp
C++
third_party/kangaru/container.hpp
kirillPshenychnyi/kangaru_di_sample
5e79860852d167b4b63185263edfb62c628741cc
[ "MIT" ]
2
2019-07-12T09:08:46.000Z
2020-09-01T13:12:45.000Z
third_party/kangaru/container.hpp
kirillPshenychnyi/kangaru_di_sample
5e79860852d167b4b63185263edfb62c628741cc
[ "MIT" ]
null
null
null
third_party/kangaru/container.hpp
kirillPshenychnyi/kangaru_di_sample
5e79860852d167b4b63185263edfb62c628741cc
[ "MIT" ]
null
null
null
#ifndef KGR_KANGARU_INCLUDE_KANGARU_CONTAINER_HPP #define KGR_KANGARU_INCLUDE_KANGARU_CONTAINER_HPP #include "detail/default_source.hpp" #include "detail/traits.hpp" #include "detail/validity_check.hpp" #include "detail/utils.hpp" #include "detail/override_range_service.hpp" #include "detail/container_service.hpp" #include "detail/autocall_traits.hpp" #include "detail/single.hpp" #include "detail/exception.hpp" #include "detail/service_storage.hpp" #include "detail/injected.hpp" #include "detail/error.hpp" #include "predicate.hpp" #include <unordered_map> #include <memory> #include <type_traits> #include "detail/define.hpp" namespace kgr { /** * The kangaru container class. * * This class will construct services and share single instances for a given definition. * It is the class that parses and manage dependency graphs and calls autocall functions. */ struct container : private detail::default_source { private: template<typename Condition, typename T = int> using enable_if = detail::enable_if_t<Condition::value, T>; template<typename Condition, typename T = int> using disable_if = detail::enable_if_t<!Condition::value, T>; template<typename T> using contained_service_t = typename std::conditional< detail::is_single<T>::value, detail::single_insertion_result_t<T>, T>::type; using unpack = int[]; auto source() const noexcept -> default_source const& { return static_cast<default_source const&>(*this); } auto source() noexcept -> default_source& { return static_cast<default_source&>(*this); } template<typename T> static auto static_unwrap_single(detail::single_insertion_result_t<T> single_result) -> T& { return *static_cast<T*>(std::get<0>(single_result).service); } explicit container(default_source&& source) : default_source{std::move(source)} {} public: explicit container() = default; container(container const&) = delete; container& operator=(container const&) = delete; container(container&&) = default; container& operator=(container&&) = default; /* * This function construct and save in place a service definition with the provided arguments. * The service is only constructed if it is not found. * It is usually used to instanciate supplied services. * It returns if the service has been constructed. * This function require the service to be single. */ template<typename T, typename... Args, enable_if<detail::is_emplace_valid<T, Args...>> = 0> bool emplace(Args&&... args) { // TODO: We're doing two search in the map: One before constructing the service and one to insert. We should do only one. return contains<T>() ? false : (autocall(static_unwrap_single<T>(make_service_instance<T>(std::forward<Args>(args)...))), true); } /* * The following two overloads are called in a case where the service is invalid, * or is called when provided arguments don't match the constructor. * In GCC, a diagnostic is provided. */ template<typename T, enable_if<std::is_default_constructible<detail::service_error<T>>> = 0> bool emplace(detail::service_error<T> = {}) = delete; template<typename T, typename... Args> bool emplace(detail::service_error<T, detail::identity_t<Args>...>, Args&&...) = delete; /* * This function construct and save in place a service definition with the provided arguments. * The inserted instance of the service will be used for now on. * It does not delete the old instance if any. * This function require the service to be single. */ template<typename T, typename... Args, enable_if<detail::is_emplace_valid<T, Args...>> = 0> void replace(Args&&... args) { autocall(static_unwrap_single<T>(make_service_instance<T>(std::forward<Args>(args)...))); } /* * The following two overloads are called in a case where the service is invalid, * or is called when provided arguments don't match the constructor. * In GCC, a diagnostic is provided. */ template<typename T, enable_if<std::is_default_constructible<detail::service_error<T>>> = 0> void replace(detail::service_error<T> = {}) = delete; template<typename T, typename... Args> void replace(detail::service_error<T, detail::identity_t<Args>...>, Args&&...) = delete; /* * This function returns the service given by service definition T. * T must be a valid service and must be constructible with arguments passed as parameters * In case of a non-single service, it takes additional arguments to be sent to the T::construct function. * T must not be a polymorphic type. */ template<typename T, typename... Args, enable_if<detail::is_service_valid<T, Args...>> = 0> auto service(Args&&... args) -> service_type<T> { return definition<T>(std::forward<Args>(args)...).forward(); } /* * The following two overloads are called in a case where the service is invalid, * or is called when provided arguments don't match the constructor. * In GCC, a diagnostic is provided. */ template<typename T, typename... Args> auto service(detail::service_error<T, detail::identity_t<Args>...>, Args&&...) -> detail::sink = delete; template<typename T, enable_if<std::is_default_constructible<detail::service_error<T>>> = 0> auto service(detail::service_error<T> = {}) -> detail::sink = delete; /* * This function returns the result of the callable object of type U. * Args are additional arguments to be sent to the function after services arguments. * This function will deduce arguments from the function signature. */ template<typename Map = map<>, typename U, typename... Args, enable_if<detail::is_map<Map>> = 0, enable_if<detail::is_invoke_valid<Map, detail::decay_t<U>, Args...>> = 0> auto invoke(Map, U&& function, Args&&... args) -> detail::invoke_function_result_t<Map, detail::decay_t<U>, Args...> { return invoke_helper<Map>( detail::tuple_seq_minus<detail::invoke_function_arguments_t<Map, detail::decay_t<U>, Args...>, sizeof...(Args)>{}, std::forward<U>(function), std::forward<Args>(args)... ); } /* * This function returns the result of the callable object of type U. * Args are additional arguments to be sent to the function after services arguments. * This function will deduce arguments from the function signature. */ template<typename Map = map<>, typename U, typename... Args, enable_if<detail::is_map<Map>> = 0, enable_if<detail::is_invoke_valid<Map, detail::decay_t<U>, Args...>> = 0> auto invoke(U&& function, Args&&... args) -> detail::invoke_function_result_t<Map, detail::decay_t<U>, Args...> { return invoke_helper<Map>( detail::tuple_seq_minus<detail::invoke_function_arguments_t<Map, detail::decay_t<U>, Args...>, sizeof...(Args)>{}, std::forward<U>(function), std::forward<Args>(args)... ); } /* * This function returns the result of the callable object of type U. * It will call the function with the sevices listed in the `Services` parameter pack. */ template<typename First, typename... Services, typename U, typename... Args, enable_if<detail::conjunction< detail::is_service_valid<First>, detail::is_service_valid<Services>...>> = 0> auto invoke(U&& function, Args&&... args) -> detail::call_result_t<U, service_type<First>, service_type<Services>..., Args...> { return std::forward<U>(function)(service<First>(), service<Services>()..., std::forward<Args>(args)...); } /* * This oveload is called when the function mannot be invoked. * It will provide diagnostic on GCC. */ template<typename... Services> auto invoke(detail::not_invokable_error = {}, ...) -> detail::sink = delete; /* * This function clears this container. * Every single services are invalidated after calling this function. */ inline void clear() { source().clear(); } /* * This function fork the container into a new container. * The new container will have the copied state of the first container. * Construction of new services within the new container will not affect the original one. * The new container must exist within the lifetime of the original container. * * It takes a predicate type as template argument. * The default predicate is kgr::all. * * This version of the function takes a predicate that is default constructible. * It will call fork() with a predicate as parameter. */ template<typename Predicate = all, detail::enable_if_t<std::is_default_constructible<Predicate>::value, int> = 0> auto fork() const -> container { return fork(Predicate{}); } /* * This function fork the container into a new container. * The new container will have the copied state of the first container. * Construction of new services within the new container will not affect the original one. * The new container must exist within the lifetime of the original container. * * It takes a predicate as argument. */ template<typename Predicate> auto fork(Predicate predicate) const -> container { return container{source().fork(predicate)}; } /* * This function merges a container with another. * The receiving container will prefer it's own instances in a case of conflicts. */ inline void merge(container&& other) { source().merge(std::move(other.source())); } /* * This function merges a container with another. * The receiving container will prefer it's own instances in a case of conflicts. * * This function consumes the container `other` */ inline void merge(container& other) { merge(std::move(other)); } /** * This function will add all services form the container sent as parameter into this one. * Note that the lifetime of the container sent as parameter must be at least as long as this one. * If the container you rebase from won't live long enough, consider using the merge function. * * It takes a predicate type as template argument. * The default predicate is kgr::all. * * This version of the function takes a predicate that is default constructible. * It will call rebase() with a predicate as parameter. */ template<typename Predicate = all, detail::enable_if_t<std::is_default_constructible<Predicate>::value, int> = 0> void rebase(const container& other) { rebase(other, Predicate{}); } /** * This function will add all services form the container sent as parameter into this one. * Note that the lifetime of the container sent as parameter must be at least as long as this one. * If the container you rebase from won't live long enough, consider using the merge function. * * It takes a predicate type as argument to filter. */ template<typename Predicate> void rebase(const container& other, Predicate predicate) { source().rebase(other.source(), predicate); } /* * This function return true if the container contains the service T. Returns false otherwise. * T nust be a single service. */ template<typename T, detail::enable_if_t<detail::is_service<T>::value && detail::is_single<T>::value, int> = 0> bool contains() const { return source().contains<T>(); } private: /////////////////////// // new service // /////////////////////// /* * This function will create a new instance and save it. * It also returns a reference to the constructed service. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, disable_if<detail::is_polymorphic<T>> = 0, disable_if<detail::is_supplied_service<T>> = 0, disable_if<detail::is_abstract_service<T>> = 0> auto configure_new_service(Args&&... args) -> T& { auto& service = static_unwrap_single<T>(make_service_instance<T>(std::forward<Args>(args)...)); autocall(service); return service; } /* * This function will create a new instance and save it. * It also returns a reference to the constructed service. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, enable_if<detail::is_polymorphic<T>> = 0, disable_if<detail::is_supplied_service<T>> = 0, disable_if<detail::is_abstract_service<T>> = 0> auto configure_new_service(Args&&... args) -> detail::typed_service_storage<T> { auto storage = make_service_instance<T>(std::forward<Args>(args)...); auto& service = static_unwrap_single<T>(storage); autocall(service); return std::get<0>(storage); } /* * This function is a specialization of configure_new_service for abstract classes. * Since you cannot construct an abstract class, this function always throw. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, enable_if<detail::is_abstract_service<T>> = 0, disable_if<detail::has_default<T>> = 0> auto configure_new_service(Args&&...) -> detail::typed_service_storage<T> { KGR_KANGARU_THROW(abstract_not_found{}); } /* * This function is a specialization of configure_new_service for abstract classes. * Since you cannot construct an abstract class, this function always throw. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, enable_if<detail::is_supplied_service<T>> = 0, disable_if<detail::is_abstract_service<T>> = 0> auto configure_new_service(Args&&...) -> detail::conditional_t<detail::is_polymorphic<T>::value, detail::typed_service_storage<T>, T&> { KGR_KANGARU_THROW(supplied_not_found{}); } /* * This function is a specialization of configure_new_service for abstract classes. * Since that abstract service has a default service specified, we can contruct that one. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, disable_if<detail::is_supplied_service<T>> = 0, enable_if<detail::is_abstract_service<T>> = 0, enable_if<detail::has_default<T>> = 0> auto configure_new_service(Args&&...) -> detail::typed_service_storage<T> { auto storage = make_service_instance<detail::default_type<T>>(); auto& service = *static_cast<detail::default_type<T>*>(std::get<0>(storage).service); using service_index = detail::meta_list_find<T, detail::parent_types<detail::default_type<T>>>; autocall(service); // The static assert is still required here, if other checks fails and allow // a call to this function where the default service don't overrides T, it would be UB. static_assert(detail::is_overriden_by<T, detail::default_type<T>>::value, "The default service type of an abstract service must override that abstract service." ); return std::get<service_index::value + 1>(storage); } /////////////////////// // make instance // /////////////////////// /* * This function creates an instance of a service. * It forward the work to make_service_instance_helper with an integer sequence. */ template<typename T, typename... Args> auto make_service_instance(Args&&... args) -> contained_service_t<T> { return make_service_instance_helper<T>( detail::construct_result_seq<T, Args...>{}, std::forward<Args>(args)... ); } /* * This function is the helper for make_service_instance. * It construct the service using the values returned by construct. * It forward it's work to make_contained_service. */ template<typename T, typename... Args, std::size_t... S> auto make_service_instance_helper(detail::seq<S...>, Args&&... args) -> contained_service_t<T> { auto construct_args = invoke_definition<detail::construct_function<T, Args...>>(std::forward<Args>(args)...); // This line is used to shut unused-variable warning, since S can be empty. static_cast<void>(construct_args); return make_contained_service<T>( detail::parent_types<T>{}, std::forward<detail::tuple_element_t<S, decltype(construct_args)>>(std::get<S>(construct_args))... ); } /* * This function create a service with the received arguments. * It creating it in the right type for the container to contain it in it's container. */ template<typename T, typename... Overrides, typename... Args, enable_if<detail::is_single<T>> = 0, enable_if<detail::is_someway_constructible<T, in_place_t, Args...>> = 0> auto make_contained_service(detail::meta_list<Overrides...>, Args&&... args) -> detail::single_insertion_result_t<T> { return source().emplace<T, Overrides...>(detail::in_place, std::forward<Args>(args)...); } /* * This function create a service with the received arguments. * It creating it in the right type for the container return it and inject it without overhead. */ template<typename T, typename... Args, disable_if<detail::is_single<T>> = 0, enable_if<detail::is_someway_constructible<T, in_place_t, Args...>> = 0> auto make_contained_service(detail::meta_list<>, Args&&... args) -> T { return T{detail::in_place, std::forward<Args>(args)...}; } /* * This function create a service with the received arguments. * It creating it in the right type for the container to contain it in it's container. * This version of the function is called when the service definition has no valid constructor. * It will try to call an emplace function that construct the service in a lazy way. */ template<typename T, typename... Overrides, typename... Args, enable_if<detail::is_single<T>> = 0, disable_if<detail::is_someway_constructible<T, in_place_t, Args...>> = 0, enable_if<detail::is_emplaceable<T, Args...>> = 0> auto make_contained_service(detail::meta_list<Overrides...>, Args&&... args) -> detail::single_insertion_result_t<T> { auto storage = source().emplace<T, Overrides...>(); auto& service = static_unwrap_single<T>(storage); service.emplace(std::forward<Args>(args)...); return storage; } /* * This function create a service with the received arguments. * It creating it in the right type for the container return it and inject it without overhead. * This version of the function is called when the service definition has no valid constructor. * It will try to call an emplace function that construct the service in a lazy way. */ template<typename T, typename... Args, disable_if<detail::is_single<T>> = 0, disable_if<detail::is_someway_constructible<T, in_place_t, Args...>> = 0, enable_if<detail::is_emplaceable<T, Args...>> = 0> auto make_contained_service(detail::meta_list<>, Args&&... args) -> T { T service; service.emplace(std::forward<Args>(args)...); return service; } /////////////////////// // service // /////////////////////// /* * This function call service using the service map. * This function is called when the service map `Map` is valid for a given `T` */ template<typename Map, typename T, enable_if<detail::is_complete_map<Map, T>> = 0, enable_if<detail::is_service_valid<detail::detected_t<mapped_service_t, T, Map>>> = 0> auto mapped_service() -> service_type<mapped_service_t<T, Map>> { return service<mapped_service_t<T, Map>>(); } /////////////////////// // definition // /////////////////////// /* * This function returns a service definition. * This version of this function create the service each time it is called. */ template<typename T, typename... Args, disable_if<detail::is_single<T>> = 0, disable_if<detail::is_container_service<T>> = 0, disable_if<detail::is_override_range_service<T>> = 0> auto definition(Args&&... args) -> detail::injected_wrapper<T> { auto service = make_service_instance<T>(std::forward<Args>(args)...); autocall(service); return detail::injected_wrapper<T>{std::move(service)}; } /* * This function returns a service definition. * This version of this function is specific to a container service. */ template<typename T, enable_if<detail::is_container_service<T>> = 0> auto definition() -> detail::injected_wrapper<T> { return detail::injected<container_service>{container_service{*this}}; } /* * This function returns a service definition. * This version of this function is specific to a container service. */ template<typename T, enable_if<detail::is_override_range_service<T>> = 0> auto definition() -> detail::injected_wrapper<T> { return detail::injected<T>{T{source().overrides<detail::override_range_service_type_t<T>>()}}; } /* * This function returns a service definition. * This version of this function create the service if it was not created before. * It is called when getting a service definition for a single, non virtual service */ template<typename T, enable_if<detail::is_single<T>> = 0> auto definition() -> detail::injected_wrapper<T> { return source().find<T>( [](detail::injected_wrapper<T>&& storage) { return storage; }, [this]{ return detail::injected_wrapper<T>{configure_new_service<T>()}; } ); } /////////////////////// // invoke // /////////////////////// /* * This function is an helper for the public invoke function. * It unpacks arguments of the function with an integer sequence. */ template<typename Map, typename U, typename... Args, std::size_t... S> auto invoke_helper(detail::seq<S...>, U&& function, Args&&... args) -> detail::invoke_function_result_t<Map, detail::decay_t<U>, Args...> { return std::forward<U>(function)( mapped_service<Map, detail::invoke_function_argument_t<S, Map, detail::decay_t<U>, Args...>>()..., std::forward<Args>(args)... ); } /* * This function is the same as invoke but it sends service definitions instead of the service itself. * It is called with some autocall function and the make_service_instance function. */ template<typename U, typename... Args, typename F = typename U::value_type> auto invoke_definition(Args&&... args) -> detail::function_result_t<F> { return invoke_definition_helper<U>( detail::tuple_seq_minus<detail::function_arguments_t<F>, sizeof...(Args)>{}, std::forward<Args>(args)... ); } /* * This function is an helper of the invoke_definition function. * It unpacks arguments of the function U with an integer sequence. */ template<typename U, typename... Args, std::size_t... S, typename F = typename U::value_type> auto invoke_definition_helper(detail::seq<S...>, Args&&... args) -> detail::function_result_t<F> { return U::value(definition<detail::injected_argument_t<S, F>>()..., std::forward<Args>(args)...); } /////////////////////// // autocall // /////////////////////// /* * This function starts the iteration (autocall_helper). */ template<typename T, enable_if<detail::has_autocall<T>> = 0> void autocall(T& service) { autocall(detail::tuple_seq<typename T::autocall_functions>{}, service); } /* * This function is the iteration for autocall. */ template<typename T, std::size_t... S, enable_if<detail::has_autocall<T>> = 0> void autocall(detail::seq<S...>, T& service) { (void)unpack{(void( invoke_definition<detail::autocall_nth_function<T, S>>(service) ), 0)..., 0}; } /* * This function is called when there is no autocall to do. */ template<typename T, disable_if<detail::has_autocall<T>> = 0> void autocall(T&) {} }; } // namespace kgr #include "detail/undef.hpp" #endif // KGR_KANGARU_INCLUDE_KANGARU_CONTAINER_HPP
38.076033
130
0.704332
kirillPshenychnyi
ec79d74f4860d465c34f6f3276879ca28a6062e7
1,791
cc
C++
horace/terminate_flag.cc
gdshaw/libholmes-horace
6a7d8365f01e165853fc967ce8eae45b82102fdf
[ "BSD-3-Clause" ]
null
null
null
horace/terminate_flag.cc
gdshaw/libholmes-horace
6a7d8365f01e165853fc967ce8eae45b82102fdf
[ "BSD-3-Clause" ]
null
null
null
horace/terminate_flag.cc
gdshaw/libholmes-horace
6a7d8365f01e165853fc967ce8eae45b82102fdf
[ "BSD-3-Clause" ]
null
null
null
// This file is part of libholmes. // Copyright 2019 Graham Shaw // Redistribution and modification are permitted within the terms of the // BSD-3-Clause licence as defined by v3.4 of the SPDX Licence List. #include <unistd.h> #include <fcntl.h> #include <poll.h> #include "horace/libc_error.h" #include "horace/terminate_flag.h" namespace horace { terminate_flag::terminate_flag(): _terminating(false) { if (pipe(_pipefd) == -1) { throw libc_error(); } _nonblock(_pipefd[0]); _nonblock(_pipefd[1]); } void terminate_flag::_nonblock(int fd) { int flags = ::fcntl(fd, F_GETFL, 0); if (flags == -1) { throw libc_error(); } flags |= O_NONBLOCK; if (fcntl(fd, F_SETFL, flags) == -1) { throw libc_error(); } } terminate_flag& terminate_flag::operator=(bool terminating) { bool changed = terminating != _terminating; _terminating = terminating; if (changed) { if (terminating) { size_t count = write(_pipefd[1], "", 1); } else { char buffer; while (read(_pipefd[0], &buffer, sizeof(buffer)) > 0) {} } } return *this; } int terminate_flag::poll(int fd, int events, int timeout) const { struct pollfd fds[2] = {{0}}; fds[0].fd = _pipefd[0]; fds[0].events = POLLIN; fds[1].fd = fd; fds[1].events = events; while (::poll(fds, 2, timeout) == -1) { if (errno != EINTR) { throw libc_error(); } } if (fds[0].revents & POLLIN) { throw terminate_exception(); } return fds[1].revents; } void terminate_flag::millisleep(int timeout) const { struct pollfd fds[1] = {{0}}; fds[0].fd = _pipefd[0]; fds[0].events = POLLIN; if (::poll(fds, 1, timeout) == -1) { if (errno != EINTR) { throw libc_error(); } } if (fds[0].revents & POLLIN) { throw terminate_exception(); } } terminate_flag terminating; } /* namespace horace */
20.352273
72
0.650475
gdshaw
ec8708c1cf6f3e2c019d92a9f0d1045135cdc18a
1,028
cpp
C++
core/src/ResourceManagement/Loaders/TextureLoader.cpp
tokongs/yage
14c9411d8efce08b89c0deb134b5c3023a32c577
[ "MIT" ]
null
null
null
core/src/ResourceManagement/Loaders/TextureLoader.cpp
tokongs/yage
14c9411d8efce08b89c0deb134b5c3023a32c577
[ "MIT" ]
null
null
null
core/src/ResourceManagement/Loaders/TextureLoader.cpp
tokongs/yage
14c9411d8efce08b89c0deb134b5c3023a32c577
[ "MIT" ]
null
null
null
#include "TextureLoader.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image/stb_image.h" namespace yage { TextureLoader::TextureLoader() { } TextureLoader::~TextureLoader() { } Resource *TextureLoader::load(std::string file_path) { std::string fileContent = mFileReader.readAsString(file_path); YAGE_INFO("Loading Material from {}", file_path); pugi::xml_document doc; pugi::xml_parse_result r = doc.load_string(fileContent.c_str()); if(!r){ YAGE_WARN("Failed to parse xml when loading material from {}", file_path); return nullptr; } pugi::xml_node root = doc.first_child(); std::string path = root.attribute("path").value(); int width, height, numChannels; unsigned char *data = stbi_load(path.c_str(), &width, &height, &numChannels, 0); Texture *result = new Texture(data, width, height, numChannels); stbi_image_free(data); return result; } } // namespace yage
30.235294
88
0.639105
tokongs
ec8cc8a89b0290455cf69cc837753cd28cfc6fb7
3,152
hxx
C++
src/interfaces/common/caller/ad3_caller.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
src/interfaces/common/caller/ad3_caller.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
src/interfaces/common/caller/ad3_caller.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#ifndef AD3_CALLER_HXX_ #define AD3_CALLER_HXX_ #include <opengm/opengm.hxx> #include <opengm/inference/external/ad3.hxx> #include "inference_caller_base.hxx" #include "../argument/argument.hxx" namespace opengm { namespace interface { template <class IO, class GM, class ACC> class Ad3Caller : public InferenceCallerBase<IO, GM, ACC, Ad3Caller<IO, GM, ACC> > { public: typedef external::AD3Inf<GM, ACC> Solver; typedef InferenceCallerBase<IO, GM, ACC, Ad3Caller<IO, GM, ACC> > BaseClass; typedef typename Solver::VerboseVisitorType VerboseVisitorType; typedef typename Solver::EmptyVisitorType EmptyVisitorType; typedef typename Solver::TimingVisitorType TimingVisitorType; const static std::string name_; Ad3Caller(IO& ioIn); virtual ~Ad3Caller(); protected: using BaseClass::addArgument; using BaseClass::io_; using BaseClass::infer; typedef typename BaseClass::OutputBase OutputBase; typename Solver::Parameter param_; std::string selectedSolverType_; virtual void runImpl(GM& model, OutputBase& output, const bool verbose); size_t steps_; }; template <class IO, class GM, class ACC> inline Ad3Caller<IO, GM, ACC>::Ad3Caller(IO& ioIn) : BaseClass(name_, "detailed description of Ad3Caller caller...", ioIn) { addArgument(DoubleArgument<>(param_.eta_, "", "eta", "eta.", double(param_.eta_))); addArgument(BoolArgument(param_.adaptEta_, "", "adaptEta", "adaptEta")); addArgument(Size_TArgument<>(steps_, "", "steps", "maximum steps", size_t(param_.steps_))); addArgument(DoubleArgument<>(param_.residualThreshold_, "", "residualThreshold", "residualThreshold", double(param_.residualThreshold_))); addArgument(IntArgument<>(param_.verbosity_, "", "verbosity", "verbosity", int(param_.verbosity_))); std::vector<std::string> possibleSolverType; possibleSolverType.push_back(std::string("AD3_LP")); possibleSolverType.push_back(std::string("AD3_ILP")); possibleSolverType.push_back(std::string("PSDD_LP")); addArgument(StringArgument<>(selectedSolverType_, "", "solverType", "selects the update rule", possibleSolverType.at(0), possibleSolverType)); } template <class IO, class GM, class ACC> inline Ad3Caller<IO, GM, ACC>::~Ad3Caller() { } template <class IO, class GM, class ACC> inline void Ad3Caller<IO, GM, ACC>::runImpl(GM& model, OutputBase& output, const bool verbose) { std::cout << "running Ad3Caller caller" << std::endl; if(selectedSolverType_ == std::string("AD3_LP")) { param_.solverType_= Solver::AD3_LP; } else if(selectedSolverType_ == std::string("AD3_ILP")) { param_.solverType_= Solver::AD3_ILP; } else if(selectedSolverType_ == std::string("PSDD_LP")) { param_.solverType_= Solver::PSDD_LP; } else { throw RuntimeError("Unknown solverType for ad3"); } param_.steps_=steps_; this-> template infer<Solver, TimingVisitorType, typename Solver::Parameter>(model, output, verbose, param_); } template <class IO, class GM, class ACC> const std::string Ad3Caller<IO, GM, ACC>::name_ = "AD3"; } // namespace interface } // namespace opengm #endif /* AD3_CALLER_HXX_ */
32.494845
145
0.722716
burcin
ec8ed91b4d4f555be82915746445d8ac0ad529af
1,566
cpp
C++
Source/Motor2D/Dissolve.cpp
Needlesslord/PaintWars_by_BrainDeadStudios
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
2
2020-03-06T11:32:40.000Z
2020-03-20T12:17:30.000Z
Source/Motor2D/Dissolve.cpp
Needlesslord/Heathen_Games
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
2
2020-03-03T09:56:57.000Z
2020-05-02T15:50:45.000Z
Source/Motor2D/Dissolve.cpp
Needlesslord/Heathen_Games
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
1
2020-03-17T18:50:53.000Z
2020-03-17T18:50:53.000Z
#include "Dissolve.h" #include "TransitionManager.h" Dissolve::Dissolve(SCENES next_scene, float step_duration) : Transition(next_scene, step_duration) , dissolving_alpha(0.0f) , condensing_alpha(0.0f) { InitDissolve(); } Dissolve::~Dissolve() { } void Dissolve::StepTransition() { switch (step) { case TRANSITION_STEP::ENTERING: Entering(); break; case TRANSITION_STEP::CHANGING: Changing(); break; case TRANSITION_STEP::EXITING: Exiting(); break; } ApplyDissolve(); } void Dissolve::Entering() { current_cutoff += GetCutoffRate(step_duration); if (current_cutoff <= MAX_CUTOFF) { current_cutoff = MAX_CUTOFF; step = TRANSITION_STEP::CHANGING; } } void Dissolve::Changing() { App->scenes->UnloadScene(App->scenes->current_scene); step = TRANSITION_STEP::EXITING; } void Dissolve::Exiting() { step = TRANSITION_STEP::NONE; App->transition_manager->DeleteActiveTransition(); } void Dissolve::ApplyDissolve() { dissolving_alpha += Lerp(MAX_ALPHA, MIN_ALPHA, dissolve_rate); // Decreasing alpha value. condensing_alpha += Lerp(MIN_ALPHA, MAX_ALPHA, dissolve_rate); // Increasing alpha value. SDL_SetTextureAlphaMod(App->scenes->current_scene->scene_texture, dissolving_alpha); SDL_SetTextureAlphaMod(App->scenes->next_scene->scene_texture, condensing_alpha); } void Dissolve::InitDissolve() { dissolve_rate = GetCutoffRate(step_duration); App->scenes->LoadScene(next_scene); SDL_SetTextureAlphaMod(App->scenes->next_scene->tileset_texture, 0.0f); step = TRANSITION_STEP::ENTERING; }
18.209302
98
0.736909
Needlesslord
ec8f41342830a6f2056500c0819252c425271da8
5,552
cpp
C++
qtlua/packages/qttorch/qttorch.cpp
elq/torch5
5965bd6410f8ca7e87c6bc9531aaf46e10ed281e
[ "BSD-3-Clause" ]
1
2016-05-09T05:34:15.000Z
2016-05-09T05:34:15.000Z
qtlua/packages/qttorch/qttorch.cpp
elq/torch5
5965bd6410f8ca7e87c6bc9531aaf46e10ed281e
[ "BSD-3-Clause" ]
null
null
null
qtlua/packages/qttorch/qttorch.cpp
elq/torch5
5965bd6410f8ca7e87c6bc9531aaf46e10ed281e
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- #include "qttorch.h" #include <QColor> #include <QDebug> #include <QImage> #include <QMetaType> #include "TH.h" #include "luaT.h" static const void* torch_Tensor_id; static int qttorch_qimage_fromtensor(lua_State *L) { THTensor *Tsrc = (THTensor*)luaT_checkudata(L,1,torch_Tensor_id); long depth = 1; if ( Tsrc->nDimension == 3) depth = Tsrc->size[2]; else if (Tsrc->nDimension != 2) luaL_error(L, "tensor must have 2 or 3 dimensions"); if (depth != 1 && depth != 3 && depth != 4) luaL_error(L, "tensor third dimension must be 1, 3, or 4."); // create image if (Tsrc->size[0] >= INT_MAX || Tsrc->size[1] >= INT_MAX) luaL_error(L, "image is too large"); int width = (int)(Tsrc->size[0]); int height = (int)(Tsrc->size[1]); QImage image(width, height, QImage::Format_ARGB32_Premultiplied); // fill image long s0 = Tsrc->stride[0]; long s1 = Tsrc->stride[1]; long s2 = (depth > 1) ? Tsrc->stride[2] : 0; double *tdata = THTensor_dataPtr(Tsrc); for(int j=0; j<height; j++) { QRgb *ip = (QRgb*)image.scanLine(j); double *tp = tdata + s1 * j; if (depth == 1) { for (int i=0; i<width; i++) { int g = (int)(tp[0] * 255.0) & 0xff; tp += s0; ip[i] = qRgb(g,g,g); } } else if (depth == 3) { for (int i=0; i<width; i++) { int r = (int)(tp[0] * 255.0) & 0xff; int g = (int)(tp[s2] * 255.0) & 0xff; int b = (int)(tp[s2+s2] * 255.0) & 0xff; tp += s0; ip[i] = qRgb(r,g,b); } } else if (depth == 4) { for (int i=0; i<width; i++) { int a = (int)(tp[s2+s2+s2] * 255.0) & 0xff; int r = (int)(tp[0] * a) & 0xff; int g = (int)(tp[s2] * a) & 0xff; int b = (int)(tp[s2+s2] * a) & 0xff; tp += s0; ip[i] = qRgba(r,g,b,a); } } } // return luaQ_pushqt(L, image); return 1; } static int qttorch_qimage_totensor(lua_State *L) { THTensor *Tdst = 0; QImage image = luaQ_checkqvariant<QImage>(L, 1); int width = image.width(); int height = image.height(); int depth = 1; int tpos = 0; // validate arguments if (lua_type(L, 2) == LUA_TUSERDATA) { tpos = 2; Tdst = (THTensor*)luaT_checkudata(L,2,torch_Tensor_id); if (Tdst->nDimension == 3) depth = Tdst->size[2]; else if (Tdst->nDimension != 2) luaL_error(L, "tensor must have 2 or 3 dimensions"); if (depth != 1 && depth != 3 && depth != 4) luaL_error(L, "tensor third dimension must be 1, 3, or 4."); if (width != Tdst->size[0] || height != Tdst->size[1]) luaL_error(L, "tensor dimensions must match the image size."); } else { depth = luaL_optinteger(L, 2, 3); if (depth != 1 && depth != 3 && depth != 4) luaL_error(L, "depth must be 1, 3, or 4."); if (depth == 1) Tdst = THTensor_newWithSize2d(width, height); else Tdst = THTensor_newWithSize3d(width, height, depth); } // convert image if (image.format() != QImage::Format_ARGB32) image = image.convertToFormat(QImage::Format_ARGB32); if (image.format() != QImage::Format_ARGB32) luaL_error(L, "Cannot convert image to format ARGB32"); // fill tensor long s0 = Tdst->stride[0]; long s1 = Tdst->stride[1]; long s2 = (depth > 1) ? Tdst->stride[2] : 0; double *tdata = THTensor_dataPtr(Tdst); for(int j=0; j<height; j++) { QRgb *ip = (QRgb*)image.scanLine(j); double *tp = tdata + s1 * j; if (depth == 1) { for (int i=0; i<width; i++) { QRgb v = ip[i]; tp[0] = (qreal)qGray(v) / 255.0; tp += s0; } } else if (depth == 3) { for (int i=0; i<width; i++) { QRgb v = ip[i]; tp[0] = (qreal)qRed(v) / 255.0; tp[s2] = (qreal)qGreen(v) / 255.0; tp[s2+s2] = (qreal)qBlue(v) / 255.0; tp += s0; } } else if (depth == 4) { for (int i=0; i<width; i++) { QRgb v = ip[i]; tp[0] = (qreal)qRed(v) / 255.0; tp[s2] = (qreal)qGreen(v) / 255.0; tp[s2+s2] = (qreal)qBlue(v) / 255.0; tp[s2+s2+s2] = (qreal)qAlpha(v) / 255.0; tp += s0; } } } // return if (tpos > 0) lua_pushvalue(L, tpos); else luaT_pushudata(L, (void*)Tdst, torch_Tensor_id); return 1; } struct luaL_Reg qttorch_qimage_lib[] = { {"fromTensor", qttorch_qimage_fromtensor}, {"toTensor", qttorch_qimage_totensor}, {0,0} }; int luaopen_libqttorch(lua_State *L) { // load module 'qt' if (luaL_dostring(L, "require 'qt'")) lua_error(L); // load modules 'torch' if (luaL_dostring(L, "require 'torch'")) lua_error(L); torch_Tensor_id = luaT_checktypename2id(L, "torch.Tensor"); // enrichs QImage luaQ_pushmeta(L, QMetaType::QImage); luaQ_getfield(L, -1, "__metatable"); luaL_register(L, 0, qttorch_qimage_lib); return 0; } /* ------------------------------------------------------------- Local Variables: c++-font-lock-extra-types: ("\\sw+_t" "\\(lua_\\)?[A-Z]\\sw*[a-z]\\sw*") End: ------------------------------------------------------------- */
26.821256
75
0.494597
elq
ec93d1181751399f8eb18c3ca34f9c2d13088cf5
2,112
hpp
C++
MyLib/ipcresponse.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
MyLib/ipcresponse.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
MyLib/ipcresponse.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
#ifndef IPCRESPONSE_HPP #define IPCRESPONSE_HPP #include <functional> #include <string> #include <unordered_map> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include "compression.hpp" #include "ipcprotocol.hpp" namespace MyLib { template<typename _ResponseStatusT, typename _ResponseStatusToStringT, typename _ResponseArgT, typename _ResponseArgToStringT> class BasicIPCResponse; class IPCResponse; } class MyLib::IPCResponse { public: typedef MyLib::BasicIPCResponse<MyLib::IPCProtocol::ResponseStatus::Common, MyLib::IPCProtocol::ResponseStatus::CommonToString_t, MyLib::IPCProtocol::ResponseArg::CommonHash_t, MyLib::IPCProtocol::ResponseArg::CommonToString_t> Common; typedef MyLib::BasicIPCResponse<MyLib::IPCProtocol::ResponseStatus::Common, MyLib::IPCProtocol::ResponseStatus::CommonToString_t, MyLib::IPCProtocol::ResponseArg::CommonHash_t, MyLib::IPCProtocol::ResponseArg::CommonToString_t> HandShake; }; template<typename _ResponseStatusT, typename _ResponseStatusToStringT, typename _ResponseArgT, typename _ResponseArgToStringT> class MyLib::BasicIPCResponse { private: std::string m_message; public: BasicIPCResponse(const _ResponseStatusT status, const _ResponseStatusToStringT &statusToString, const _ResponseArgT &args = _ResponseArgT(), const _ResponseArgToStringT &argsToStringT = _ResponseArgToStringT()) { boost::property_tree::ptree resTree; resTree.put("response.protocol.name", IPCProtocol::Name()); resTree.put("response.protocol.version", IPCProtocol::Version()); resTree.put("response.status", statusToString.at(status)); for (auto &arg : args) { resTree.put("response.args.key", argsToStringT.at(arg.first)); resTree.put("response.args.value", arg.second); } IPCProtocol::SetMessage(resTree, m_message); } public: const std::string &Message() const { return m_message; } }; #endif /* IPCRESPONSE_HPP */
30.608696
99
0.721117
NuLL3rr0r
ec9477e9408b79385b9b0df57aa2725c7c625653
589
hpp
C++
include/RED4ext/Scripting/Natives/Generated/audio/VoiceTriggerLimits.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/audio/VoiceTriggerLimits.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/audio/VoiceTriggerLimits.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> namespace RED4ext { namespace audio { struct VoiceTriggerLimits { static constexpr const char* NAME = "audioVoiceTriggerLimits"; static constexpr const char* ALIAS = NAME; float probability; // 00 float singleNpcMinRepeatTime; // 04 float allNpcsMinRepeatTime; // 08 float allNpcsSharingVoicesetMinRepeatTime; // 0C float combatVolume; // 10 }; RED4EXT_ASSERT_SIZE(VoiceTriggerLimits, 0x14); } // namespace audio } // namespace RED4ext
23.56
66
0.740238
jackhumbert
ec954d788768ad94ba2fd415232e4343a949df57
788
cpp
C++
src/Item.cpp
Miguel-EpicJS/state-rpg-tutorial
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
[ "MIT" ]
null
null
null
src/Item.cpp
Miguel-EpicJS/state-rpg-tutorial
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
[ "MIT" ]
null
null
null
src/Item.cpp
Miguel-EpicJS/state-rpg-tutorial
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
[ "MIT" ]
null
null
null
#include "../includes/Item.h" void Item::generate() { } Item::Item(std::string name, unsigned type, unsigned rarity, unsigned value) { this->name = name; this->type = type; this->rarity = rarity; this->value = value; } Item::~Item() { } const std::string& Item::getName() { return this->name; } const unsigned& Item::getType() { return this->type; } const unsigned& Item::getRarity() { return this->rarity; } const unsigned& Item::getValue() { return this->value; } const std::string Item::toString() const { std::stringstream ss; ss << " Name: " << this->name << " | Type: " << this->type << " | Rarity: " << this->rarity << " | Value: " << this->value << "\n"; return ss.str(); }
16.081633
76
0.549492
Miguel-EpicJS
ec9cedbad08ac278a4bf7ba84485bfcbb276b951
1,879
cpp
C++
hiro/cocoa/widget/frame.cpp
kirwinia/ares-emu-v121
722aa227caf943a4a64f1678c1bdd07b38b15caa
[ "0BSD" ]
2
2021-06-28T06:04:56.000Z
2021-06-28T11:30:20.000Z
cocoa/widget/frame.cpp
ProtoByter/hiro
89972942430f5cc9c931afdc115a0db253fa339a
[ "0BSD" ]
1
2022-02-16T02:46:39.000Z
2022-02-16T04:30:29.000Z
cocoa/widget/frame.cpp
ProtoByter/hiro
89972942430f5cc9c931afdc115a0db253fa339a
[ "0BSD" ]
1
2021-12-25T11:34:57.000Z
2021-12-25T11:34:57.000Z
#if defined(Hiro_Frame) @implementation CocoaFrame : NSBox -(id) initWith:(hiro::mFrame&)frameReference { if(self = [super initWithFrame:NSMakeRect(0, 0, 0, 0)]) { frame = &frameReference; [self setTitle:@""]; } return self; } @end namespace hiro { auto pFrame::construct() -> void { @autoreleasepool { cocoaView = cocoaFrame = [[CocoaFrame alloc] initWith:self()]; pWidget::construct(); setText(state().text); } } auto pFrame::destruct() -> void { @autoreleasepool { [cocoaView removeFromSuperview]; [cocoaView release]; } } auto pFrame::append(sSizable sizable) -> void { } auto pFrame::remove(sSizable sizable) -> void { } auto pFrame::setEnabled(bool enabled) -> void { pWidget::setEnabled(enabled); if(auto& sizable = state().sizable) sizable->setEnabled(enabled); } auto pFrame::setFont(const Font& font) -> void { @autoreleasepool { [cocoaView setTitleFont:pFont::create(font)]; } if(auto& sizable = state().sizable) sizable->setFont(font); } auto pFrame::setGeometry(Geometry geometry) -> void { bool empty = !state().text; Size size = pFont::size(self().font(true), state().text); pWidget::setGeometry({ geometry.x() - 3, geometry.y() - (empty ? size.height() - 2 : 1), geometry.width() + 6, geometry.height() + (empty ? size.height() + 2 : 5) }); if(auto& sizable = state().sizable) { sizable->setGeometry({ geometry.x() + 1, geometry.y() + (empty ? 1 : size.height() - 2), geometry.width() - 2, geometry.height() - (empty ? 1 : size.height() - 1) }); } } auto pFrame::setText(const string& text) -> void { @autoreleasepool { [cocoaView setTitle:[NSString stringWithUTF8String:text]]; } } auto pFrame::setVisible(bool visible) -> void { pWidget::setVisible(visible); if(auto& sizable = state().sizable) sizable->setVisible(visible); } } #endif
23.197531
79
0.645556
kirwinia
ec9e388ab9231c80f35ad42808eee70f32e3ab75
919
cpp
C++
src/renderer/shaders/shaders.cpp
fantasiorona/LRender
5fb6f29c323df53986e39b4350ee8494e4642452
[ "MIT" ]
5
2019-11-22T05:31:33.000Z
2021-11-18T19:15:21.000Z
src/renderer/shaders/shaders.cpp
fantasiorona/LRender
5fb6f29c323df53986e39b4350ee8494e4642452
[ "MIT" ]
7
2019-02-21T11:26:38.000Z
2019-03-29T10:28:58.000Z
src/renderer/shaders/shaders.cpp
fantasiorona/LRender
5fb6f29c323df53986e39b4350ee8494e4642452
[ "MIT" ]
1
2021-04-22T17:03:04.000Z
2021-04-22T17:03:04.000Z
#include "shaders.h" using namespace LRender; Shaders::Shaders() : branches( "LRender/glsl/vertexGeometry.glsl", "LRender/glsl/fragmentGeometry.glsl"), leaves( "LRender/glsl/vertexGeometry.glsl", "LRender/glsl/fragmentLeaf.glsl"), shadows( "LRender/glsl/vertexShadows.glsl", "LRender/glsl/fragmentShadows.glsl"){ } const Shader &Shaders::getBranches() const { return branches; } const Shader &Shaders::getLeaves() const { return leaves; } const Shader &Shaders::getShadows() const { return shadows; } const ShaderExposure &Shaders::getExposure() const { return exposure; } const ShaderImage &Shaders::getImage() const { return image; } const ShaderInteger &Shaders::getInteger() const { return integer; } const ShaderGeometryShadows& Shaders::getGeometryShadows() const { return geometryShadows; } const ShaderLeavesShadows& Shaders::getLeavesShadows() const { return leavesShadows; }
18.755102
66
0.747552
fantasiorona
ecad377c4bb33c02980b43d57dfb348c63412371
1,949
cpp
C++
algorithms/cpp/Problems 901-1000/_934_ShortestBridge.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
algorithms/cpp/Problems 901-1000/_934_ShortestBridge.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
algorithms/cpp/Problems 901-1000/_934_ShortestBridge.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
/* Source - https://leetcode.com/problems/shortest-bridge/ Author - Shivam Arora */ #include <bits/stdc++.h> using namespace std; struct Element { int x, y, d; Element(int a = -1, int b = -1, int c = -1) { x = a; y = b; d = c; } }; int xDir[4] = {1, 0, -1, 0}; int yDir[4] = {0, 1, 0, -1}; void dfs(int r, int c, vector<vector<int>>& A, queue<Element>& q) { A[r][c] = 2; q.push(Element(r, c, 0)); for(int k = 0; k < 4; k++) { int i = r + xDir[k], j = c + yDir[k]; if(i < 0 || i >= A.size() || j < 0 || j >= A.size() || A[i][j] != 1) continue; dfs(i, j, A, q); } } int shortestBridge(vector<vector<int>>& A) { int n = A.size(); queue<Element> q; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(A[i][j] == 1) { dfs(i, j, A, q); goto bfs; } } } bfs: while(!q.empty()) { Element front = q.front(); q.pop(); int r = front.x, c = front.y, flips = front.d; for(int k = 0; k < 4; k++) { int i = r + xDir[k], j = c + yDir[k]; if(i < 0 || i >= n || j < 0 || j >= n || A[i][j] == 2) continue; if(A[i][j] == 1) return flips; A[i][j] = 2; q.push(Element(i, j, flips + 1)); } } return 0; } int main() { int n; cout<<"Enter value of n (for array dimensions): "; cin>>n; vector<vector<int>> A(n, vector<int> (n)); cout<<"Enter values in array row-wise (0 or 1): "<<endl; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) cin>>A[i][j]; } cout<<"Smallest number of 0s to be flipped to connect the two islands: "<<shortestBridge(A)<<endl; }
22.402299
102
0.394048
shivamacs
ecb43180b299e99d49622cf7f5b54071e6629eea
1,778
cpp
C++
src/samt.cpp
danieldeutsch/thrax2
68c60bab9f12788e16750b15eba6be5ac9e7df36
[ "MIT" ]
null
null
null
src/samt.cpp
danieldeutsch/thrax2
68c60bab9f12788e16750b15eba6be5ac9e7df36
[ "MIT" ]
null
null
null
src/samt.cpp
danieldeutsch/thrax2
68c60bab9f12788e16750b15eba6be5ac9e7df36
[ "MIT" ]
null
null
null
#include <future> #include <iostream> #include <memory> #include <mutex> #include <sstream> #include <vector> #include "filters.h" #include "label.h" #include "phrasalrule.h" #include "sentence.h" #include "tree.h" namespace { int count = 0; std::mutex countLock, inputLock, outputLock; bool valid(const jhu::thrax::PhrasalRule& rule) { return !isNonlexicalXRule(rule) && !isAbstract(rule) && withinTokenLimit(rule) && !isSlashedRule(rule) && !isConcatRule(rule) && !hasAnyXNT(rule); } bool process() { std::string line; { std::lock_guard g(inputLock); if (!std::getline(std::cin, line)) { return false; } } try { auto asp = jhu::thrax::readAlignedSentencePair<false, true>(line); auto initial = jhu::thrax::allConsistentPairs(asp, 20); auto tree = jhu::thrax::readTree(jhu::thrax::fields(line)[1]); auto label = jhu::thrax::SAMTLabeler{std::move(tree)}; std::ostringstream out; for (auto& rule : jhu::thrax::extract(label, asp, std::move(initial))) { if (valid(rule)) { out << std::move(rule) << '\n'; } } std::lock_guard g(outputLock); std::cout << out.str(); } catch (std::exception& e) { std::cerr << e.what() << ' ' << line << '\n'; } { std::lock_guard g(countLock); count++; if (count % 10000 == 0) { std::lock_guard g(outputLock); std::cerr << count << std::endl; } } return true; } } // namespace int main(int argc, char** argv) { int threads = 1; if (argc > 1) { threads = std::atoi(argv[1]); } if (threads < 2) { while (process()) {} return 0; } std::vector<std::future<void>> workers(threads); for (auto& t : workers) { t = std::async([]() { while (process()) {} }); } }
22.506329
76
0.584364
danieldeutsch
ecb83560d96c0efc06a2b37a053f835fe101b67b
4,356
cc
C++
modules/control/tools/control_tester.cc
Shokoofeh/apollo
71d6ea753b4595eb38cc54d6650c8de677b173df
[ "Apache-2.0" ]
7
2017-07-07T07:56:13.000Z
2019-03-06T06:27:00.000Z
modules/control/tools/control_tester.cc
Shokoofeh/apollo
71d6ea753b4595eb38cc54d6650c8de677b173df
[ "Apache-2.0" ]
null
null
null
modules/control/tools/control_tester.cc
Shokoofeh/apollo
71d6ea753b4595eb38cc54d6650c8de677b173df
[ "Apache-2.0" ]
2
2017-07-07T07:56:15.000Z
2018-08-10T17:13:34.000Z
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "gflags/gflags.h" #include "cyber/cyber.h" #include "cyber/time/rate.h" #include "cyber/time/time.h" #include "cyber/common/log.h" #include "cyber/init.h" #include "modules/canbus/proto/chassis.pb.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/file.h" #include "modules/control/common/control_gflags.h" #include "modules/control/proto/pad_msg.pb.h" #include "modules/localization/proto/localization.pb.h" #include "modules/planning/proto/planning.pb.h" DEFINE_string( chassis_test_file, "/apollo/modules/control/testdata/control_tester/chassis.pb.txt", "Used for sending simulated Chassis content to the control node."); DEFINE_string( localization_test_file, "/apollo/modules/control/testdata/control_tester/localization.pb.txt", "Used for sending simulated localization to the control node."); DEFINE_string(pad_msg_test_file, "/apollo/modules/control/testdata/control_tester/pad_msg.pb.txt", "Used for sending simulated PadMsg content to the control node."); DEFINE_string( planning_test_file, "/apollo/modules/control/testdata/control_tester/planning.pb.txt", "Used for sending simulated Planning content to the control node."); DEFINE_int32(num_seconds, 10, "Length of execution."); DEFINE_int32(feed_frequency, 10, "Frequency with which protos are fed to control."); int main(int argc, char** argv) { using apollo::canbus::Chassis; using apollo::control::PadMessage; using apollo::cyber::Time; using apollo::localization::LocalizationEstimate; using apollo::planning::ADCTrajectory; using std::this_thread::sleep_for; google::ParseCommandLineFlags(&argc, &argv, true); apollo::cyber::Init(argv[0]); FLAGS_alsologtostderr = true; Chassis chassis; if (!apollo::common::util::GetProtoFromFile(FLAGS_chassis_test_file, &chassis)) { AERROR << "failed to load file: " << FLAGS_chassis_test_file; return -1; } LocalizationEstimate localization; if (!apollo::common::util::GetProtoFromFile(FLAGS_localization_test_file, &localization)) { AERROR << "failed to load file: " << FLAGS_localization_test_file; return -1; } PadMessage pad_msg; if (!apollo::common::util::GetProtoFromFile(FLAGS_pad_msg_test_file, &pad_msg)) { AERROR << "failed to load file: " << FLAGS_pad_msg_test_file; return -1; } ADCTrajectory trajectory; if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_test_file, &trajectory)) { AERROR << "failed to load file: " << FLAGS_planning_test_file; return -1; } std::shared_ptr<apollo::cyber::Node> node( apollo::cyber::CreateNode("control_tester")); auto chassis_writer = node->CreateWriter<Chassis>(FLAGS_chassis_topic); auto localization_writer = node->CreateWriter<LocalizationEstimate>(FLAGS_localization_topic); auto pad_msg_writer = node->CreateWriter<PadMessage>(FLAGS_pad_topic); auto planning_writer = node->CreateWriter<ADCTrajectory>(FLAGS_planning_trajectory_topic); for (int i = 0; i < FLAGS_num_seconds * FLAGS_feed_frequency; ++i) { chassis_writer->Write(chassis); localization_writer->Write(localization); pad_msg_writer->Write(pad_msg); planning_writer->Write(trajectory); sleep_for(std::chrono::milliseconds(1000 / FLAGS_feed_frequency)); } AINFO << "Successfully fed proto files."; return 0; }
39.243243
80
0.682277
Shokoofeh
ecb8702fc4f218e0507758661ae4eb67c37f8ca8
2,141
cpp
C++
modules/task_1/chuvashov_a_frequency_symbol/frequency_symbol.cpp
ImKonstant/pp_2020_autumn_engineer
c8ac69681201b63f5cf8b6c6cd790f48f037532a
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/chuvashov_a_frequency_symbol/frequency_symbol.cpp
ImKonstant/pp_2020_autumn_engineer
c8ac69681201b63f5cf8b6c6cd790f48f037532a
[ "BSD-3-Clause" ]
2
2020-11-14T18:00:55.000Z
2020-11-19T16:12:50.000Z
modules/task_1/chuvashov_a_frequency_symbol/frequency_symbol.cpp
ImKonstant/pp_2020_autumn_engineer
c8ac69681201b63f5cf8b6c6cd790f48f037532a
[ "BSD-3-Clause" ]
1
2020-10-10T09:54:14.000Z
2020-10-10T09:54:14.000Z
// Copyright 2020 Chuvashov Artem #include <mpi.h> #include <ctime> #include <random> #include <string> #include "../../../modules/task_1/chuvashov_a_frequency_symbol/frequency_symbol.h" std::string getString(int size) { std::mt19937 gen; gen.seed(static_cast<unsigned int>(time(0))); std::string str_res; str_res.resize(size); for (auto& smb : str_res) { smb = static_cast<char>(gen() % 100); } return str_res; } int parallelFrecSym(const std::string& general_str, char character, int size) { int frequency = 0; for (int j = 0; j < size; j++) { if (general_str[j] == character) { frequency++; } } return frequency; } int amountFrequencySymbol(const std::string& flow_str, char character, int Size) { int procsize, procrank; MPI_Comm_size(MPI_COMM_WORLD, &procsize); MPI_Comm_rank(MPI_COMM_WORLD, &procrank); if (Size < procsize) { if (procrank == 0) return parallelFrecSym(flow_str, character, Size); else return 0; } const int delta_ = Size / procsize; int Sizestr; if (procrank == procsize - 1) Sizestr = Size - (procsize - 1) * delta_; else Sizestr = delta_; if (procrank == 0 && procsize > 1) { for (int process = 1; process < procsize - 1; ++process) { MPI_Send(&flow_str[process * delta_], delta_, MPI_CHAR, process, 0, MPI_COMM_WORLD); } MPI_Send(&flow_str[(procsize - 1) * delta_], Size - (procsize - 1) * delta_, MPI_CHAR, procsize - 1, 0, MPI_COMM_WORLD); } int frequency_summa = 0; int local_summa = 0; std::string local_buf; local_buf.resize(delta_); if (procrank == 0) { local_summa = parallelFrecSym(flow_str, character, delta_); } else { MPI_Status status; MPI_Recv(&local_buf[0], Sizestr, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status); local_summa = parallelFrecSym(local_buf, character, Sizestr); } MPI_Reduce(&local_summa, &frequency_summa, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); return frequency_summa; }
30.15493
87
0.6156
ImKonstant
ecb9d9a556ffb3fd54b3cce5077b37052fd85bec
747
cpp
C++
Data Structures/Binary Tree/C++/Deletion of a node in a BST.cpp
sanchit2812/Data-Structures-Algorithms-Hacktoberfest-2K19
88bc29e924d6d15993db742ccaede4752c0083e8
[ "MIT" ]
null
null
null
Data Structures/Binary Tree/C++/Deletion of a node in a BST.cpp
sanchit2812/Data-Structures-Algorithms-Hacktoberfest-2K19
88bc29e924d6d15993db742ccaede4752c0083e8
[ "MIT" ]
null
null
null
Data Structures/Binary Tree/C++/Deletion of a node in a BST.cpp
sanchit2812/Data-Structures-Algorithms-Hacktoberfest-2K19
88bc29e924d6d15993db742ccaede4752c0083e8
[ "MIT" ]
null
null
null
node* del(node* root, int data){ if(root == NULL) return NULL; if(data > root->data) root->right = del(root->right, data); else if(data<root->data) root->left = del(root->left,data); else{ if (root->left == NULL){ node* temp =root->right; free(root); return temp; } else if(root->right==NULL){ node* temp = root->left; free(root); return temp; } node* temp = find_max(root->left); root->data = temp->data; root->left = del(root->left, root->data); } return root; } node* find_max(struct node* root){ while(root->right!=NULL) root = root->right; return root; }
27.666667
64
0.497992
sanchit2812