hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
908b760caceee96667e33459d10e09fa0cb5b640
501
cpp
C++
Versuch07/Add.cpp
marvinklimke/rwth-prit1
dc070a5caa3ebd6e7604345a2c4d898d6442be96
[ "MIT" ]
1
2021-07-12T10:01:50.000Z
2021-07-12T10:01:50.000Z
Versuch07/Add.cpp
marvinklimke/rwth-prit1
dc070a5caa3ebd6e7604345a2c4d898d6442be96
[ "MIT" ]
null
null
null
Versuch07/Add.cpp
marvinklimke/rwth-prit1
dc070a5caa3ebd6e7604345a2c4d898d6442be96
[ "MIT" ]
null
null
null
/* * Add.cpp * * Created on: 02.05.2016 * Author: mklimke */ /** * \file Add.cpp * \brief This file contains the method definitions for Add-class. */ #include "Add.h" Add::Add(Expression* summand1, Expression* summand2) : left(summand1), right(summand2) { } Add::~Add() { delete left; delete right; } double Add::evaluate() const { return left->evaluate() + right->evaluate(); } std::string Add::print() const { return ("( " + left->print() + " + " + right->print() + " )"); }
14.735294
86
0.60479
marvinklimke
908e482e4512c43e8cb68f893b57c508a9a6df1f
1,706
hpp
C++
include/boost/url/rfc/host_rule.hpp
vgrigoriu/url
8911d05c35123f978e90321fea863385b63525d4
[ "BSL-1.0" ]
null
null
null
include/boost/url/rfc/host_rule.hpp
vgrigoriu/url
8911d05c35123f978e90321fea863385b63525d4
[ "BSL-1.0" ]
2
2022-01-14T23:51:59.000Z
2022-02-19T19:28:35.000Z
include/boost/url/rfc/host_rule.hpp
vgrigoriu/url
8911d05c35123f978e90321fea863385b63525d4
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/CPPAlliance/url // #ifndef BOOST_URL_RFC_HOST_RULE_HPP #define BOOST_URL_RFC_HOST_RULE_HPP #include <boost/url/detail/config.hpp> #include <boost/url/error_code.hpp> #include <boost/url/host_type.hpp> #include <boost/url/pct_encoding_types.hpp> #include <boost/url/string_view.hpp> #include <boost/url/ipv4_address.hpp> #include <boost/url/ipv6_address.hpp> #include <boost/url/grammar/parse_tag.hpp> namespace boost { namespace urls { /** Rule for host @par BNF @code host = IP-literal / IPv4address / reg-name @endcode @par Specification @li <a href="https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2" >3.2.2. Host (rfc3986)</a> @see @ref host_type, @ref ipv4_address, @ref ipv6_address. */ struct host_rule { urls::host_type host_type = urls::host_type::none; pct_encoded_str name; ipv4_address ipv4; ipv6_address ipv6; string_view ipvfuture; string_view host_part; friend void tag_invoke( grammar::parse_tag const&, char const*& it, char const* const end, error_code& ec, host_rule& t) noexcept { return parse(it, end, ec, t); } private: BOOST_URL_DECL static void parse( char const*& it, char const* const end, error_code& ec, host_rule& t) noexcept; }; } // urls } // boost #endif
21.871795
79
0.654748
vgrigoriu
9095adbe4f61d9514c5a5658cdfd658e8ee8d613
7,407
cc
C++
ash/autotest_private_api_utils.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
ash/autotest_private_api_utils.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
ash/autotest_private_api_utils.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/public/cpp/autotest_private_api_utils.h" #include "ash/app_list/app_list_controller_impl.h" #include "ash/frame/non_client_frame_view_ash.h" #include "ash/shell.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/tablet_mode/scoped_skip_user_session_blocked_check.h" #include "base/callback_helpers.h" #include "base/optional.h" #include "base/scoped_observation.h" #include "ui/compositor/layer_animation_observer.h" namespace ash { namespace { class HomeLauncherStateWaiter { public: HomeLauncherStateWaiter(bool target_shown, base::OnceClosure closure) : target_shown_(target_shown), closure_(std::move(closure)) { Shell::Get() ->app_list_controller() ->SetHomeLauncherAnimationCallbackForTesting(base::BindRepeating( &HomeLauncherStateWaiter::OnHomeLauncherAnimationCompleted, base::Unretained(this))); } ~HomeLauncherStateWaiter() { Shell::Get() ->app_list_controller() ->SetHomeLauncherAnimationCallbackForTesting(base::NullCallback()); } private: // Passed to AppListControllerImpl as a callback to run when home launcher // transition animation is complete. void OnHomeLauncherAnimationCompleted(bool shown) { if (shown == target_shown_) { std::move(closure_).Run(); delete this; } } bool target_shown_; base::OnceClosure closure_; DISALLOW_COPY_AND_ASSIGN(HomeLauncherStateWaiter); }; // A waiter that waits until the animation ended with the target state, and // execute the callback. This self destruction upon completion. class LauncherStateWaiter { public: LauncherStateWaiter(ash::AppListViewState state, base::OnceClosure closure) : target_state_(state), closure_(std::move(closure)) { Shell::Get() ->app_list_controller() ->SetStateTransitionAnimationCallbackForTesting(base::BindRepeating( &LauncherStateWaiter::OnStateChanged, base::Unretained(this))); } ~LauncherStateWaiter() { Shell::Get() ->app_list_controller() ->SetStateTransitionAnimationCallbackForTesting(base::NullCallback()); } void OnStateChanged(ash::AppListViewState state) { if (target_state_ == state) { std::move(closure_).Run(); delete this; } } private: ash::AppListViewState target_state_; base::OnceClosure closure_; DISALLOW_COPY_AND_ASSIGN(LauncherStateWaiter); }; class LauncherAnimationWaiter : public ui::LayerAnimationObserver { public: LauncherAnimationWaiter(AppListView* view, base::OnceClosure closure) : closure_(std::move(closure)) { observation_.Observe(view->GetWidget()->GetLayer()->GetAnimator()); } ~LauncherAnimationWaiter() override = default; LauncherAnimationWaiter(const LauncherAnimationWaiter&) = delete; LauncherAnimationWaiter& operator=(const LauncherAnimationWaiter&) = delete; private: // ui::LayerAnimationObserver: void OnLayerAnimationEnded(ui::LayerAnimationSequence* sequence) override { std::move(closure_).Run(); delete this; } void OnLayerAnimationAborted(ui::LayerAnimationSequence* sequence) override { OnLayerAnimationEnded(sequence); } void OnLayerAnimationScheduled( ui::LayerAnimationSequence* sequence) override {} base::OnceClosure closure_; base::ScopedObservation<ui::LayerAnimator, ui::LayerAnimationObserver> observation_{this}; }; bool WaitForHomeLauncherState(bool target_visible, base::OnceClosure closure) { if (Shell::Get()->app_list_controller()->IsVisible( /*display_id=*/base::nullopt) == target_visible) { std::move(closure).Run(); return true; } new HomeLauncherStateWaiter(target_visible, std::move(closure)); return false; } bool WaitForLauncherAnimation(base::OnceClosure closure) { auto* app_list_view = Shell::Get()->app_list_controller()->presenter()->GetView(); if (!app_list_view) { std::move(closure).Run(); return true; } bool animating = app_list_view->GetWidget()->GetLayer()->GetAnimator()->is_animating(); if (!animating) { std::move(closure).Run(); return true; } new LauncherAnimationWaiter(app_list_view, std::move(closure)); return false; } } // namespace std::vector<aura::Window*> GetAppWindowList() { ScopedSkipUserSessionBlockedCheck skip_session_blocked; return Shell::Get()->mru_window_tracker()->BuildAppWindowList(kAllDesks); } bool WaitForLauncherState(AppListViewState target_state, base::OnceClosure closure) { const bool in_tablet_mode = Shell::Get()->tablet_mode_controller()->InTabletMode(); if (in_tablet_mode) { // App-list can't enter kPeeking or kHalf state in tablet mode. Thus // |target_state| should be either kClosed, kFullscreenAllApps or // kFullscreenSearch. DCHECK(target_state == AppListViewState::kClosed || target_state == AppListViewState::kFullscreenAllApps || target_state == AppListViewState::kFullscreenSearch); } // In the tablet mode, home launcher visibility state needs special handling, // as app list view visibility does not match home launcher visibility. The // app list view is always visible, but the home launcher may be obscured by // app windows. The waiter interprets waits for kClosed state as waits // "home launcher not visible" state - note that the app list view // is actually expected to be in a visible state. AppListViewState effective_target_state = in_tablet_mode && target_state == AppListViewState::kClosed ? AppListViewState::kFullscreenAllApps : target_state; base::Optional<bool> target_home_launcher_visibility; if (in_tablet_mode) target_home_launcher_visibility = target_state != AppListViewState::kClosed; // Don't wait if the launcher is already in the target state and not // animating. auto* app_list_view = Shell::Get()->app_list_controller()->presenter()->GetView(); bool animating = app_list_view && app_list_view->GetWidget()->GetLayer()->GetAnimator()->is_animating(); bool at_target_state = (!app_list_view && effective_target_state == AppListViewState::kClosed) || (app_list_view && app_list_view->app_list_state() == effective_target_state); if (at_target_state && !animating) { // In tablet mode, ensure that the home launcher is in the expected state. if (target_home_launcher_visibility.has_value()) { return WaitForHomeLauncherState(*target_home_launcher_visibility, std::move(closure)); } std::move(closure).Run(); return true; } // In tablet mode, ensure that the home launcher is in the expected state. base::OnceClosure callback = target_home_launcher_visibility.has_value() ? base::BindOnce(base::IgnoreResult(&WaitForHomeLauncherState), *target_home_launcher_visibility, std::move(closure)) : std::move(closure); if (at_target_state) return WaitForLauncherAnimation(std::move(callback)); new LauncherStateWaiter( target_state, base::BindOnce(base::IgnoreResult(&WaitForLauncherAnimation), std::move(callback))); return false; } } // namespace ash
35.104265
80
0.717024
iridium-browser
9095dddb129847e6a32ffdff5b625ebaf97fca09
9,139
cpp
C++
EVB-2/IS_EVB-2/src/main.cpp
ycdtosa/inertial-sense-sdk
4317aba8f3a87187125b44f1b2ccdd64e31ffeec
[ "MIT" ]
null
null
null
EVB-2/IS_EVB-2/src/main.cpp
ycdtosa/inertial-sense-sdk
4317aba8f3a87187125b44f1b2ccdd64e31ffeec
[ "MIT" ]
null
null
null
EVB-2/IS_EVB-2/src/main.cpp
ycdtosa/inertial-sense-sdk
4317aba8f3a87187125b44f1b2ccdd64e31ffeec
[ "MIT" ]
null
null
null
/* MIT LICENSE Copyright 2014-2019 Inertial Sense, Inc. - http://inertialsense.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT, IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <asf.h> #include <string> #include <stream_buffer.h> #include "sd_mmc_mem.h" #include "wifi.h" #include "xbee.h" #include "globals.h" #include "communications.h" #include "user_interface.h" #include "sd_card_logger.h" #include "control_law.h" #undef printf #define printf(...) #define printf_mutex(...) // RTOS Task Configuration #define TASK_COMM_PERIOD_MS 1 #define TASK_LOGGER_PERIOD_MS 1 #define TASK_WIFI_PERIOD_MS 10 #define TASK_MAINT_PERIOD_MS 10 #define TASK_MAINT_SLOW_SEC_PERIOD_MS 1000 // #define TASK_COMM_STACK_SIZE (4096/sizeof(portSTACK_TYPE)) #define TASK_COMM_STACK_SIZE (8192/sizeof(portSTACK_TYPE)) #define TASK_MAINT_STACK_SIZE (4096/sizeof(portSTACK_TYPE)) // #define TASK_LOGGER_STACK_SIZE (4096/sizeof(portSTACK_TYPE)) #define TASK_LOGGER_STACK_SIZE (8192/sizeof(portSTACK_TYPE)) #define TASK_WIFI_STACK_SIZE (2048/sizeof(portSTACK_TYPE)) #define TASK_COMM_PRIORITY (tskIDLE_PRIORITY + 4) // Highest #define TASK_LOGGER_PRIORITY (tskIDLE_PRIORITY + 3) #define TASK_WIFI_PRIORITY (tskIDLE_PRIORITY + 2) #define TASK_MAINT_PRIORITY (tskIDLE_PRIORITY + 1) #include "CAN.h" static void vTaskComm(void *pvParameters) { UNUSED(pvParameters); rtos_task_t *task = &g_rtos.task[EVB_TASK_COMMUNICATIONS]; static is_comm_instance_t comm; static uint8_t comm_buffer[PKT_BUF_SIZE]; is_comm_init(&comm, comm_buffer, PKT_BUF_SIZE); #ifdef CONF_BOARD_CAN_TEST //if(/*g_can_test == CAN_TEST_MASTER - or something like that*/ 1) //mcan_test_master(); if(/*g_can_test == CAN_TEST_SLAVE - or something like that*/ 1) mcan_test_slave(); #endif // Start USB CDC after everything is running #ifdef USB_PORT_NUM serInit(USB_PORT_NUM, 0, NULL, 0); #endif vTaskDelay(200); refresh_CFG_LED(); while(1) { vTaskDelay(task->periodMs); g_comm_time_ms = time_msec(); #ifdef ENABLE_WDT // Feed Watchdog to prevent reset wdt_restart(WDT); #endif // Turn off communications LEDs - first thing after vTaskDelay() LED_OFF(LED_INS_RXD_PIN); LED_OFF(LED_INS_TXD_PIN); // Forward data between communications ports step_com_bridge(comm); velocity_control(comm); // Read buttons and update LEDs step_user_interface(); ////////////////////////////////////////////////////////////////////////// // Suggested USER CODE Section // Update period: 1ms (Adjust by changing TASK_COMM_PERIOD_MS) // Priority: high // // Ensure code added here does not run longer than 1ms. Consider // adding code to vTaskMaint if it runs longer than 1ms and does not // require a high priority. // Add code here... ////////////////////////////////////////////////////////////////////////// } } /** * \brief RTOS logger task. */ static void vTaskLogger(void *pvParameters) { UNUSED(pvParameters); rtos_task_t *task = &g_rtos.task[EVB_TASK_LOGGER]; static is_comm_instance_t comm; static uint8_t comm_buffer[PKT_BUF_SIZE]; is_comm_init(&comm, comm_buffer, PKT_BUF_SIZE); uINS_stream_stop_all(comm); vTaskDelay(200); LED_LOG_OFF(); vTaskDelay(800); #if STREAM_INS_FOR_TIME_SYNC // Stream INS message on startup. Necessary to update EVB RTC for correct data log date and time. //uINS0_stream_stop_all(comm); //uINS0_stream_enable_std(comm); #endif cISLogger logger; for (;;) { vTaskDelay(task->periodMs); step_logger_control(logger, comm); // Ready uINS data from com task. Log to file. log_uINS_data(logger, comm); // Mount/unmount SD card sd_card_maintenance(); update_led_log(); } } /** * \brief RTOS maintenance task. */ static void vTaskMaint(void *pvParameters) { UNUSED(pvParameters); rtos_task_t *task = &g_rtos.task[EVB_TASK_MAINTENANCE]; uint32_t m2sPeriodMs = 0; for (;;) { vTaskDelay(task->periodMs); ////////////////////////////////////////////////////////////////////////// // Fast Maintenance - 10ms period ////////////////////////////////////////////////////////////////////////// // Suggested USER CODE Section // Update period: 10ms (Adjust by changing TASK_MAINT_PERIOD_MS) // Priority: low // // Consider adding code to vTaskComm if it needs to run faster than every // 10ms or requires a higher priority. // Add code here... ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Slow Maintenance - 1000ms period if ((m2sPeriodMs += TASK_MAINT_PERIOD_MS) < TASK_MAINT_SLOW_SEC_PERIOD_MS || g_loggerEnabled) { continue; } m2sPeriodMs = 0; // Sync local time from uINS time_sync_from_uINS(); nvr_slow_maintenance(); // Update RTOS stats if (g_enRtosStats) { rtos_monitor(EVB_RTOS_NUM_TASKS); } if (g_uInsBootloaderEnableTimeMs) { // uINS bootloader mode enabled if ( (g_comm_time_ms-g_uInsBootloaderEnableTimeMs) > 180000 ) { // Automatically disable uINS after 3 minutes g_uInsBootloaderEnableTimeMs = 0; } } ////////////////////////////////////////////////////////////////////////// // Suggested USER CODE Section // Update period: 1000ms (Adjust by changing TASK_MAINT_SUB_TASK_PERIOD_MS) // Priority: low // // Consider adding code to vTaskComm if it needs to run faster than every // 10ms or requires a higher priority. // Add code here... ////////////////////////////////////////////////////////////////////////// } } int main(void) { //XDMAC channel interrupt enables do not get cleared by a software reset. Clear them before they cause issues. XDMAC->XDMAC_GID = 0xFFFFFFFF; for(int i=0;i<XDMACCHID_NUMBER;i++) XDMAC->XDMAC_CHID[i].XDMAC_CID = 0xFFFFFFFF; // Force USB to disconnect. Helps to make sure the USB port starts up correctly when debugging. udc_stop(); // Initialize the SAM system board_init(); // Init globals and flash parameters globals_init(); nvr_init(); // Hold config while resetting if(!ioport_get_pin_level(BUTTON_CFG_PIN)) { g_flashCfg->cbPreset = EVB2_CB_PRESET_DEFAULT; } // Init hardware I/O, SD card logger, and communications board_IO_config(); init_control(); sd_card_logger_init(); communications_init(); // Create RTOS tasks createTask(EVB_TASK_COMMUNICATIONS, vTaskComm, "COMM", TASK_COMM_STACK_SIZE, NULL, TASK_COMM_PRIORITY, TASK_COMM_PERIOD_MS); createTask(EVB_TASK_LOGGER, vTaskLogger,"LOGGER", TASK_LOGGER_STACK_SIZE, NULL, TASK_LOGGER_PRIORITY, TASK_LOGGER_PERIOD_MS); #ifdef CONF_BOARD_SPI_ATWINC_WIFI // ATWINC WIFI createTask(EVB_TASK_WIFI, vTaskWiFi, "WIFI", TASK_WIFI_STACK_SIZE, NULL, TASK_WIFI_PRIORITY, TASK_WIFI_PERIOD_MS); #endif createTask(EVB_TASK_MAINTENANCE, vTaskMaint, "MAINT", TASK_MAINT_STACK_SIZE, NULL, TASK_MAINT_PRIORITY, TASK_MAINT_PERIOD_MS); strncpy(g_rtos.task[EVB_TASK_IDLE].name, "IDLE", MAX_TASK_NAME_LEN); strncpy(g_rtos.task[EVB_TASK_TIMER].name, "TIMER", MAX_TASK_NAME_LEN); strncpy(g_rtos.task[EVB_TASK_SPI_UINS_COM].name,"INSSPI", MAX_TASK_NAME_LEN); #ifdef ENABLE_WDT // Setup Watchdog uint32_t timeout_value = wdt_get_timeout_value(1000000, BOARD_FREQ_SLCK_XTAL); //Timeout in us, configured for 1 second. wdt_init(WDT, WDT_MR_WDRSTEN | WDT_MR_WDDBGHLT, timeout_value, timeout_value); #endif // Start the scheduler printf("Starting FreeRTOS\n\r"); vTaskStartScheduler((TaskHandle_t*)&g_rtos.task[EVB_TASK_IDLE].handle, (TaskHandle_t*)&g_rtos.task[EVB_TASK_TIMER].handle); // Will only get here if there was insufficient memory to create the idle task. return 0; }
32.99278
460
0.658387
ycdtosa
90960b1bf3754291437e7a15a3ecad2378ed7eb3
2,339
cpp
C++
VigenerFrequencyAnalysis.cpp
baa-lamb/Kritografia01-Vigener_Frequency_Analysis
28634658969892711be3d8e1187aa34aa6d1e9c1
[ "MIT" ]
null
null
null
VigenerFrequencyAnalysis.cpp
baa-lamb/Kritografia01-Vigener_Frequency_Analysis
28634658969892711be3d8e1187aa34aa6d1e9c1
[ "MIT" ]
null
null
null
VigenerFrequencyAnalysis.cpp
baa-lamb/Kritografia01-Vigener_Frequency_Analysis
28634658969892711be3d8e1187aa34aa6d1e9c1
[ "MIT" ]
null
null
null
#include "VigenerFrequencyAnalysis.h" VigenerFrequencyAnalysis::VigenerFrequencyAnalysis(std::string pathIn, std::string pathOut, std::string pathExample, int keySize) { finEncrypt_.open(pathIn); finExample_.open(pathExample); foutOutput_.open(pathOut); keySize_ = keySize; } VigenerFrequencyAnalysis::~VigenerFrequencyAnalysis() { finExample_.close(); finEncrypt_.close(); foutOutput_.close(); } int VigenerFrequencyAnalysis::getMax(std::map<unsigned char, double> statistic) { double max = -1.000; int symbol = 0; for (auto it = statistic.begin(); it != statistic.end(); it++) { if (max < it->second) { max = it->second; symbol = it->first; } } return symbol; } std::map<unsigned char, double> VigenerFrequencyAnalysis::getStatistics(std::ifstream &file, int start, int step) { file.clear(); file.seekg(0, std::ios::beg); std::map<unsigned char, double> statistics; int symbol = 0; int count = -1; while ((symbol = file.get()) != EOF) { count++; if (count != start) continue; start += step; if (statistics.find(symbol) == statistics.end()) statistics.insert(std::pair<unsigned char, double>(symbol, 1.000)); else statistics[symbol]++; } for (auto it = statistics.begin(); it != statistics.end(); ++it) it->second = ((it->second * 100.000) / (double) count); return statistics; } std::string VigenerFrequencyAnalysis::decipherByAnalisis() { if (!finExample_.is_open()) std::cout << "example file can't open" << std::endl; else { std::map<unsigned char, double> statisticExample = getStatistics(finExample_, 0, 1); int maxSymbolExamle = getMax(statisticExample); std::string key = ""; for (int i = 0; i < keySize_; i++) { std::map<unsigned char, double> statisticEncrypt = getStatistics(finEncrypt_, i, keySize_); int maxSymbolEncrypt = getMax(statisticEncrypt); int newSymbolInKey = (maxSymbolEncrypt - maxSymbolExamle - 32) % 223; while(newSymbolInKey < 0) newSymbolInKey += 223; key += (char) newSymbolInKey; } return key; } }
33.898551
115
0.598119
baa-lamb
909636dcae0e0a32d1cdf0ff3f84fc33c4e83185
3,794
cpp
C++
src/client/graphical/gui/gui_button.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
6
2018-05-11T23:16:02.000Z
2019-06-13T01:35:07.000Z
src/client/graphical/gui/gui_button.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
33
2018-05-11T14:12:22.000Z
2022-03-12T00:55:25.000Z
src/client/graphical/gui/gui_button.cpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
1
2018-12-06T23:39:55.000Z
2018-12-06T23:39:55.000Z
#include <chrono> #include <client/graphical/gui/gui_button.hpp> using namespace familyline::graphics::gui; using namespace familyline::input; Button::Button(unsigned width, unsigned height, std::string text) : width_(width), height_(height), label_(Label{1, 1, ""}) { // We set the text after we set the resize callback, so we can get the // text size correctly already when we build the button class label_.setResizeCallback([&](Control* c, size_t w, size_t h) { label_width_ = w; label_height_ = h; cairo_surface_destroy(l_canvas_); cairo_destroy(l_context_); l_canvas_ = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h); l_context_ = cairo_create(l_canvas_); }); ControlAppearance ca = label_.getAppearance(); ca.fontFace = "Arial"; ca.fontSize = 20; ca.foreground = {1.0, 1.0, 1.0, 1.0}; label_.setAppearance(ca); ca.background = {0.0, 0.0, 0.0, 0.5}; ca.borderColor = {0.0, 0.0, 0.0, 1.0}; appearance_ = ca; l_canvas_ = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); l_context_ = cairo_create(l_canvas_); label_.update(l_context_, l_canvas_); label_.setText(text); } bool Button::update(cairo_t* context, cairo_surface_t* canvas) { size_t label_x = width_ / 2 - label_width_ / 2; size_t label_y = height_ / 2 - label_height_ / 2; auto [br, bg, bb, ba] = this->appearance_.background; auto [bor, bog, bob, boa] = this->appearance_.borderColor; // draw the background if (clicked_ || std::chrono::steady_clock::now() - last_click_ < std::chrono::milliseconds(100)) { cairo_set_source_rgba(context, br, bg, bb, ba * 4); } else if (hovered_) { cairo_set_source_rgba(context, br, bg, bb, ba * 2); } else { cairo_set_source_rgba(context, br, bg, bb, ba); } cairo_set_operator(context, CAIRO_OPERATOR_SOURCE); cairo_paint(context); // draw a border cairo_set_line_width(context, 6); cairo_set_source_rgba(context, bor, bog, bob, boa); cairo_rectangle(context, 0, 0, width_, height_); cairo_stroke(context); label_.update(l_context_, l_canvas_); cairo_set_operator(context, CAIRO_OPERATOR_OVER); cairo_set_source_surface(context, l_canvas_, label_x, label_y); cairo_paint(context); return true; } std::tuple<int, int> Button::getNeededSize(cairo_t* parent_context) const { return std::tie(width_, height_); } void Button::receiveEvent(const familyline::input::HumanInputAction& ev, CallbackQueue& cq) { if (std::holds_alternative<ClickAction>(ev.type)) { auto ca = std::get<ClickAction>(ev.type); clicked_ = ca.isPressed; } if (clicked_) { click_active_ = true; this->enqueueCallback(cq, click_cb_); /// BUG: if the line below is uncommented, the game crashes, probably due to some /// cross-thread access. /// /// Maybe make the GUI run in its own thread, and run the callbacks on the main thread. // click_fut_ = std::async(this->click_cb_, this); clicked_ = false; } // Separating the click action (the clicked_ variable) from the "is clicked" question // allows us to set the last click only when the user releases the click. This is a better // and more reliable way than activating it on the button down event, or when the clicked_ // is false if (click_active_) { if (!clicked_) { last_click_ = std::chrono::steady_clock::now(); click_active_ = false; } } } void Button::setText(std::string v) { label_.setText(v); } Button::~Button() { cairo_surface_destroy(l_canvas_); cairo_destroy(l_context_); }
31.616667
95
0.653927
arthurmco
909752389e1656b7a63f577d4df90759c3bd825b
4,743
cc
C++
tensorflow/core/platform/file_system_helper.cc
Arushacked/tensorflow
9abd61ae0b2d239d3060cdd3d46b54a105159828
[ "Apache-2.0" ]
78
2020-08-04T12:36:25.000Z
2022-03-25T04:23:40.000Z
tensorflow/core/platform/file_system_helper.cc
Arushacked/tensorflow
9abd61ae0b2d239d3060cdd3d46b54a105159828
[ "Apache-2.0" ]
10
2021-08-03T08:42:38.000Z
2022-01-03T03:29:12.000Z
tensorflow/core/platform/file_system_helper.cc
Arushacked/tensorflow
9abd61ae0b2d239d3060cdd3d46b54a105159828
[ "Apache-2.0" ]
28
2020-02-10T07:03:06.000Z
2022-01-12T11:19:20.000Z
/* Copyright 2018 The TensorFlow 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 "tensorflow/core/platform/file_system_helper.h" #include <deque> #include <string> #include <vector> #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/file_system.h" #include "tensorflow/core/platform/path.h" #include "tensorflow/core/platform/platform.h" #include "tensorflow/core/platform/status.h" #include "tensorflow/core/platform/str_util.h" #include "tensorflow/core/platform/threadpool.h" namespace tensorflow { namespace internal { namespace { constexpr int kNumThreads = 8; // Run a function in parallel using a ThreadPool, but skip the ThreadPool // on the iOS platform due to its problems with more than a few threads. void ForEach(int first, int last, const std::function<void(int)>& f) { #if TARGET_OS_IPHONE for (int i = first; i < last; i++) { f(i); } #else int num_threads = std::min(kNumThreads, last - first); thread::ThreadPool threads(Env::Default(), "ForEach", num_threads); for (int i = first; i < last; i++) { threads.Schedule([f, i] { f(i); }); } #endif } } // namespace Status GetMatchingPaths(FileSystem* fs, Env* env, const string& pattern, std::vector<string>* results) { results->clear(); // Find the fixed prefix by looking for the first wildcard. string fixed_prefix = pattern.substr(0, pattern.find_first_of("*?[\\")); string eval_pattern = pattern; std::vector<string> all_files; string dir(io::Dirname(fixed_prefix)); // If dir is empty then we need to fix up fixed_prefix and eval_pattern to // include . as the top level directory. if (dir.empty()) { dir = "."; fixed_prefix = io::JoinPath(dir, fixed_prefix); eval_pattern = io::JoinPath(dir, pattern); } // Setup a BFS to explore everything under dir. std::deque<string> dir_q; dir_q.push_back(dir); Status ret; // Status to return. // children_dir_status holds is_dir status for children. It can have three // possible values: OK for true; FAILED_PRECONDITION for false; CANCELLED // if we don't calculate IsDirectory (we might do that because there isn't // any point in exploring that child path). std::vector<Status> children_dir_status; while (!dir_q.empty()) { string current_dir = dir_q.front(); dir_q.pop_front(); std::vector<string> children; Status s = fs->GetChildren(current_dir, &children); // In case PERMISSION_DENIED is encountered, we bail here. if (s.code() == tensorflow::error::PERMISSION_DENIED) { continue; } ret.Update(s); if (children.empty()) continue; // This IsDirectory call can be expensive for some FS. Parallelizing it. children_dir_status.resize(children.size()); ForEach(0, children.size(), [fs, &current_dir, &children, &fixed_prefix, &children_dir_status](int i) { const string child_path = io::JoinPath(current_dir, children[i]); // In case the child_path doesn't start with the fixed_prefix then // we don't need to explore this path. if (!absl::StartsWith(child_path, fixed_prefix)) { children_dir_status[i] = Status(tensorflow::error::CANCELLED, "Operation not needed"); } else { children_dir_status[i] = fs->IsDirectory(child_path); } }); for (size_t i = 0; i < children.size(); ++i) { const string child_path = io::JoinPath(current_dir, children[i]); // If the IsDirectory call was cancelled we bail. if (children_dir_status[i].code() == tensorflow::error::CANCELLED) { continue; } // If the child is a directory add it to the queue. if (children_dir_status[i].ok()) { dir_q.push_back(child_path); } all_files.push_back(child_path); } } // Match all obtained files to the input pattern. for (const auto& f : all_files) { if (fs->Match(f, eval_pattern)) { results->push_back(f); } } return ret; } } // namespace internal } // namespace tensorflow
36.206107
80
0.660131
Arushacked
90983a837d2b7730f7e5ed007ab2428911176269
377
cpp
C++
core/src/main/cpp/cv/Output.cpp
CJBuchel/NeuralNet
946ad04dacbd36ad2a7bd7489bc5d562897c06a1
[ "MIT" ]
1
2021-04-20T08:51:47.000Z
2021-04-20T08:51:47.000Z
core/src/main/cpp/cv/Output.cpp
CJBuchel/NeuralNet
946ad04dacbd36ad2a7bd7489bc5d562897c06a1
[ "MIT" ]
null
null
null
core/src/main/cpp/cv/Output.cpp
CJBuchel/NeuralNet
946ad04dacbd36ad2a7bd7489bc5d562897c06a1
[ "MIT" ]
null
null
null
#include "cv/Output.h" void Output::display(Image *image) { if (image->data.empty()) { std::cerr << "Display Error: Image empty" << std::endl; } else { // Temp (imshow doesn't work without GUI. << Coprocessor error) #ifdef COPROC // Use other means of displaying image. (Web Stream) #else cv::imshow(image->name, image->data); #endif } cv::waitKey(30); }
23.5625
66
0.639257
CJBuchel
90987ed250dfc06d8a845394343cb85ff058e03c
55,600
cpp
C++
src/game/server/tf/player_vs_environment/tf_populators.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
src/game/server/tf/player_vs_environment/tf_populators.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
src/game/server/tf/player_vs_environment/tf_populators.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
//========= Copyright � Valve LLC, All rights reserved. ======================= // // Purpose: // // $NoKeywords: $ //============================================================================= #include "cbase.h" #include "nav_mesh/tf_nav_mesh.h" #include "tf_team.h" #include "tf_obj_teleporter.h" #include "tf_obj_sentrygun.h" #include "tf_populators.h" #include "tf_population_manager.h" #include "eventqueue.h" #include "tier1/UtlSortVector.h" #include "tf_objective_resource.h" #include "tf_tank_boss.h" #include "tf_mann_vs_machine_stats.h" extern ConVar tf_populator_debug; extern ConVar tf_populator_active_buffer_range; ConVar tf_mvm_engineer_teleporter_uber_duration( "tf_mvm_engineer_teleporter_uber_duration", "5.0", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY ); ConVar tf_mvm_currency_bonus_ratio_min( "tf_mvm_currency_bonus_ratio_min", "0.95f", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "The minimum percentage of wave money players must collect in order to qualify for min bonus - 0.1 to 1.0. Half the bonus amount will be awarded when reaching min ratio, and half when reaching max.", true, 0.1, true, 1.0 ); ConVar tf_mvm_currency_bonus_ratio_max( "tf_mvm_currency_bonus_ratio_max", "1.f", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "The highest percentage of wave money players must collect in order to qualify for max bonus - 0.1 to 1.0. Half the bonus amount will be awarded when reaching min ratio, and half when reaching max.", true, 0.1, true, 1.0 ); static CHandle<CBaseEntity> s_lastTeleporter = NULL; static float s_flLastTeleportTime = -1; LINK_ENTITY_TO_CLASS( populator_internal_spawn_point, CPopulatorInternalSpawnPoint ); CHandle<CPopulatorInternalSpawnPoint> g_internalSpawnPoint = NULL; class CTFNavAreaIncursionLess { public: bool Less( const CTFNavArea *a, const CTFNavArea *b, void *pCtx ) { return a->GetIncursionDistance( TF_TEAM_BLUE ) < b->GetIncursionDistance( TF_TEAM_BLUE ); } }; //----------------------------------------------------------------------------- // Purpose: Fire off output events //----------------------------------------------------------------------------- void FireEvent( EventInfo *eventInfo, const char *eventName ) { if ( eventInfo ) { CBaseEntity *targetEntity = gEntList.FindEntityByName( NULL, eventInfo->m_target ); if ( !targetEntity ) { Warning( "WaveSpawnPopulator: Can't find target entity '%s' for %s\n", eventInfo->m_target.Access(), eventName ); } else { g_EventQueue.AddEvent( targetEntity, eventInfo->m_action, 0.0f, NULL, NULL ); } } } //----------------------------------------------------------------------------- // Purpose: Create output event pairings //----------------------------------------------------------------------------- EventInfo *ParseEvent( KeyValues *data ) { EventInfo *eventInfo = new EventInfo(); FOR_EACH_SUBKEY( data, pSubKey ) { const char *pszKey = pSubKey->GetName(); if ( !Q_stricmp( pszKey, "Target" ) ) { eventInfo->m_target.sprintf( "%s", pSubKey->GetString() ); } else if ( !Q_stricmp( pszKey, "Action" ) ) { eventInfo->m_action.sprintf( "%s", pSubKey->GetString() ); } else { Warning( "Unknown field '%s' in WaveSpawn event definition.\n", pSubKey->GetString() ); delete eventInfo; return NULL; } } return eventInfo; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- SpawnLocationResult DoTeleporterOverride( CBaseEntity *spawnEnt, Vector *vSpawnPosition, bool bClosestPointOnNav ) { CUtlVector<CBaseEntity *> activeTeleporters; FOR_EACH_VEC( IBaseObjectAutoList::AutoList(), i ) { CBaseObject *pObj = static_cast<CBaseObject *>( IBaseObjectAutoList::AutoList()[i] ); if ( pObj->GetType() != OBJ_TELEPORTER || pObj->GetTeamNumber() != TF_TEAM_MVM_BOTS ) continue; if ( pObj->IsBuilding() || pObj->HasSapper() || pObj->IsDisabled() ) continue; CObjectTeleporter *teleporter = assert_cast<CObjectTeleporter *>( pObj ); const CUtlStringList &teleportWhereNames = teleporter->m_TeleportWhere; const char *pszSpawnPointName = STRING( spawnEnt->GetEntityName() ); for ( int iTelePoints =0; iTelePoints < teleportWhereNames.Count(); ++iTelePoints ) { if ( !V_stricmp( teleportWhereNames[ iTelePoints ], pszSpawnPointName ) ) { activeTeleporters.AddToTail( teleporter ); break; } } } if ( activeTeleporters.Count() > 0 ) { int which = RandomInt( 0, activeTeleporters.Count() - 1 ); *vSpawnPosition = activeTeleporters[ which ]->WorldSpaceCenter(); s_lastTeleporter = activeTeleporters[ which ]; return SPAWN_LOCATION_TELEPORTER; } CTFNavArea *pArea = (CTFNavArea *)TheNavMesh->GetNearestNavArea( spawnEnt->WorldSpaceCenter() ); if ( pArea ) { if ( bClosestPointOnNav ) { pArea->GetClosestPointOnArea( spawnEnt->WorldSpaceCenter(), vSpawnPosition ); } else { *vSpawnPosition = pArea->GetCenter(); } return SPAWN_LOCATION_NORMAL; } return SPAWN_LOCATION_NOT_FOUND; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void OnBotTeleported( CTFBot *pBot ) { if ( gpGlobals->curtime - s_flLastTeleportTime > 0.1f ) { s_lastTeleporter->EmitSound( "MVM.Robot_Teleporter_Deliver" ); s_flLastTeleportTime = gpGlobals->curtime; } // force bot to face in the direction specified by the teleporter Vector vForward; AngleVectors( s_lastTeleporter->GetAbsAngles(), &vForward, NULL, NULL ); pBot->GetLocomotionInterface()->FaceTowards( pBot->GetAbsOrigin() + 50 * vForward ); // spy shouldn't get any effect from the teleporter if ( !pBot->IsPlayerClass( TF_CLASS_SPY ) ) { pBot->TeleportEffect(); // invading bots get uber while they leave their spawn so they don't drop their cash where players can't pick it up float flUberTime = tf_mvm_engineer_teleporter_uber_duration.GetFloat(); pBot->m_Shared.AddCond( TF_COND_INVULNERABLE, flUberTime ); pBot->m_Shared.AddCond( TF_COND_INVULNERABLE_WEARINGOFF, flUberTime ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CSpawnLocation::CSpawnLocation() { m_nRandomSeed = RandomInt( 0, 9999 ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CSpawnLocation::Parse( KeyValues *data ) { const char *pszKey = data->GetName(); const char *pszValue = data->GetString(); if ( !V_stricmp( pszKey, "Where" ) || !V_stricmp( pszKey, "ClosestPoint" ) ) { if ( !V_stricmp( pszValue, "Ahead" ) ) { m_eRelative = AHEAD; } else if ( !V_stricmp( pszValue, "Behind" ) ) { m_eRelative = BEHIND; } else if ( !V_stricmp( pszValue, "Anywhere" ) ) { m_eRelative = ANYWHERE; } else { m_bClosestPointOnNav = V_stricmp( pszKey, "ClosestPoint" ) == 0; // collect entities with given name bool bFound = false; for ( int i=0; i < ITFTeamSpawnAutoList::AutoList().Count(); ++i ) { CTFTeamSpawn *pTeamSpawn = static_cast<CTFTeamSpawn *>( ITFTeamSpawnAutoList::AutoList()[i] ); if ( !V_stricmp( STRING( pTeamSpawn->GetEntityName() ), pszValue ) ) { m_TeamSpawns.AddToTail( pTeamSpawn ); bFound = true; } } if ( !bFound ) { Warning( "Invalid Where argument '%s'\n", pszValue ); return false; } } return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- SpawnLocationResult CSpawnLocation::FindSpawnLocation( Vector *vSpawnPosition ) { CUtlVector< CHandle<CTFTeamSpawn> > activeSpawns; FOR_EACH_VEC( m_TeamSpawns, i ) { if ( m_TeamSpawns[i]->IsDisabled() ) continue; activeSpawns.AddToTail( m_TeamSpawns[i] ); } if ( m_nSpawnCount >= activeSpawns.Count() ) { m_nRandomSeed = RandomInt( 0, 9999 ); m_nSpawnCount = 0; } CUniformRandomStream randomSpawn; randomSpawn.SetSeed( m_nRandomSeed ); activeSpawns.Shuffle( &randomSpawn ); if ( activeSpawns.Count() > 0 ) { SpawnLocationResult result = DoTeleporterOverride( activeSpawns[ m_nSpawnCount ], vSpawnPosition, m_bClosestPointOnNav ); if ( result != SPAWN_LOCATION_NOT_FOUND ) { m_nSpawnCount++; return result; } } CTFNavArea *spawnArea = SelectSpawnArea(); if ( spawnArea ) { *vSpawnPosition = spawnArea->GetCenter(); return SPAWN_LOCATION_NORMAL; } return SPAWN_LOCATION_NOT_FOUND; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFNavArea *CSpawnLocation::SelectSpawnArea( void ) const { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( m_eRelative == UNDEFINED ) return nullptr; CUtlSortVector<CTFNavArea *, CTFNavAreaIncursionLess> theaterAreas; CUtlVector<INextBot *> bots; TheNextBots().CollectAllBots( &bots ); CTFNavArea::MakeNewTFMarker(); FOR_EACH_VEC( bots, i ) { CTFBot *pBot = ToTFBot( bots[i]->GetEntity() ); if ( pBot == nullptr ) continue; if ( !pBot->IsAlive() ) continue; if ( !pBot->GetLastKnownArea() ) continue; CUtlVector<CTFNavArea *> nearbyAreas; CollectSurroundingAreas( &nearbyAreas, pBot->GetLastKnownArea(), tf_populator_active_buffer_range.GetFloat() ); FOR_EACH_VEC( nearbyAreas, j ) { CTFNavArea *pArea = nearbyAreas[i]; if ( !pArea->IsTFMarked() ) { pArea->TFMark(); if ( pArea->IsPotentiallyVisibleToTeam( TF_TEAM_BLUE ) ) continue; if ( !pArea->IsValidForWanderingPopulation() ) continue; theaterAreas.Insert( pArea ); if ( tf_populator_debug.GetBool() ) TheNavMesh->AddToSelectedSet( pArea ); } } } if ( theaterAreas.Count() == 0 ) { if ( tf_populator_debug.GetBool() ) DevMsg( "%3.2f: SelectSpawnArea: Empty theater!\n", gpGlobals->curtime ); return nullptr; } for ( int i=0; i < 5; ++i ) { int which = 0; switch ( m_eRelative ) { case AHEAD: which = Max( RandomFloat( 0.0f, 1.0f ), RandomFloat( 0.0f, 1.0f ) ) * theaterAreas.Count(); break; case BEHIND: which = ( 1.0f - Max( RandomFloat( 0.0f, 1.0f ), RandomFloat( 0.0f, 1.0f ) ) ) * theaterAreas.Count(); break; case ANYWHERE: which = RandomFloat( 0.0f, 1.0f ) * theaterAreas.Count(); break; } if ( which >= theaterAreas.Count() ) which = theaterAreas.Count() - 1; return theaterAreas[which]; } return nullptr; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CMissionPopulator::CMissionPopulator( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CMissionPopulator::~CMissionPopulator() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CMissionPopulator::Parse( KeyValues *data ) { int nWaveDuration = 99999; FOR_EACH_SUBKEY( data, pSubKey ) { const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "Objective" ) ) { if ( !V_stricmp( pSubKey->GetString(), "DestroySentries" ) ) { m_eMission = CTFBot::MissionType::DESTROY_SENTRIES; } else if ( !V_stricmp( pSubKey->GetString(), "Sniper" ) ) { m_eMission = CTFBot::MissionType::SNIPER; } else if ( !V_stricmp( pSubKey->GetString(), "Spy" ) ) { m_eMission = CTFBot::MissionType::SPY; } else if ( !V_stricmp( pSubKey->GetString(), "Engineer" ) ) { m_eMission = CTFBot::MissionType::ENGINEER; } else if ( !V_stricmp( pSubKey->GetString(), "SeekAndDestroy" ) ) { m_eMission = CTFBot::MissionType::DESTROY_SENTRIES; } else { Warning( "Invalid mission '%s'\n", data->GetString() ); return false; } } else if ( !V_stricmp( pszKey, "InitialCooldown" ) ) { m_flInitialCooldown = data->GetFloat(); } else if ( !V_stricmp( pszKey, "CooldownTime" ) ) { m_flCooldownDuration = data->GetFloat(); } else if ( !V_stricmp( pszKey, "BeginAtWave" ) ) { m_nStartWave = data->GetInt() - 1; } else if ( !V_stricmp( pszKey, "RunForThisManyWaves" ) ) { nWaveDuration = data->GetInt(); } else if ( !V_stricmp( pszKey, "DesiredCount" ) ) { m_nDesiredCount = data->GetInt(); } else { m_pSpawner = IPopulationSpawner::ParseSpawner( this, pSubKey ); if ( m_pSpawner == NULL ) { Warning( "Unknown attribute '%s' in Mission definition.\n", pszKey ); } } } m_nEndWave = m_nStartWave + nWaveDuration; return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissionPopulator::Update( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( TFGameRules()->InSetup() || TFObjectiveResource()->GetMannVsMachineIsBetweenWaves() ) { m_eState = NOT_STARTED; return; } if ( m_pManager->m_nCurrentWaveIndex < m_nStartWave || m_pManager->m_nCurrentWaveIndex >= m_nEndWave ) { m_eState = NOT_STARTED; return; } if ( m_eState == NOT_STARTED ) { if ( m_flInitialCooldown > 0.0f ) { m_eState = INITIAL_COOLDOWN; m_cooldownTimer.Start( m_flInitialCooldown ); return; } m_eState = RUNNING; m_cooldownTimer.Invalidate(); } else if ( m_eState == INITIAL_COOLDOWN ) { if ( !m_cooldownTimer.IsElapsed() ) { return; } m_eState = RUNNING; m_cooldownTimer.Invalidate(); } if ( m_eMission == CTFBot::MissionType::DESTROY_SENTRIES ) { UpdateMissionDestroySentries(); } else if ( m_eMission >= CTFBot::MissionType::SNIPER && m_eMission <= CTFBot::MissionType::ENGINEER ) { UpdateMission( m_eMission ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMissionPopulator::UnpauseSpawning( void ) { m_cooldownTimer.Start( m_flCooldownDuration ); m_checkSentriesTimer.Start( RandomFloat( 5.0f, 10.0f ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CMissionPopulator::UpdateMission( CTFBot::MissionType mission ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); // TODO: Move away from depending on players CUtlVector<CTFPlayer *> bots; CollectPlayers( &bots, TF_TEAM_MVM_BOTS, true ); int nActiveMissions = 0; FOR_EACH_VEC( bots, i ) { CTFBot *pBot = ToTFBot( bots[i] ); if ( pBot ) { if ( pBot->HasMission( mission ) ) nActiveMissions++; } } if ( g_pPopulationManager->IsSpawningPaused() ) return false; if ( nActiveMissions > 0 ) { m_cooldownTimer.Start( m_flCooldownDuration ); return false; } if ( !m_cooldownTimer.IsElapsed() ) return false; int nCurrentBotCount = GetGlobalTeam( TF_TEAM_MVM_BOTS )->GetNumPlayers(); if ( nCurrentBotCount + m_nDesiredCount > k_nMvMBotTeamSize ) { if ( tf_populator_debug.GetBool() ) { DevMsg( "MANN VS MACHINE: %3.2f: Waiting for slots to spawn mission.\n", gpGlobals->curtime ); } return false; } if ( tf_populator_debug.GetBool() ) { DevMsg( "MANN VS MACHINE: %3.2f: <<<< Spawning Mission >>>>\n", gpGlobals->curtime ); } int nSniperCount = 0; FOR_EACH_VEC( bots, i ) { CTFBot *pBot = ToTFBot( bots[i] ); if ( pBot && pBot->IsPlayerClass( TF_CLASS_SNIPER ) ) nSniperCount++; } for ( int i=0; i < m_nDesiredCount; ++i ) { Vector vecSpawnPos; SpawnLocationResult spawnLocationResult = m_where.FindSpawnLocation( &vecSpawnPos ); if ( spawnLocationResult != SPAWN_LOCATION_NOT_FOUND ) { CUtlVector<EHANDLE> spawnedBots; if ( m_pSpawner && m_pSpawner->Spawn( vecSpawnPos, &spawnedBots ) ) { FOR_EACH_VEC( spawnedBots, j ) { CTFBot *pBot = ToTFBot( spawnedBots[j] ); if ( pBot == NULL ) continue; pBot->SetFlagTarget( NULL ); pBot->SetMission( mission ); if ( TFObjectiveResource() ) { unsigned int iFlags = MVM_CLASS_FLAG_MISSION; if ( pBot->IsMiniBoss() ) { iFlags |= MVM_CLASS_FLAG_MINIBOSS; } if ( pBot->HasAttribute( CTFBot::AttributeType::ALWAYSCRIT ) ) { iFlags |= MVM_CLASS_FLAG_ALWAYSCRIT; } TFObjectiveResource()->IncrementMannVsMachineWaveClassCount( m_pSpawner->GetClassIcon( j ), iFlags ); } if ( TFGameRules()->IsMannVsMachineMode() ) { if ( pBot->HasMission( CTFBot::MissionType::SNIPER ) ) { nSniperCount++; if ( nSniperCount == 1 ) TFGameRules()->HaveAllPlayersSpeakConceptIfAllowed( MP_CONCEPT_MVM_SNIPER_CALLOUT, TF_TEAM_MVM_BOTS ); } } if ( spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) OnBotTeleported( pBot ); } } } else if ( tf_populator_debug.GetBool() ) { Warning( "MissionPopulator: %3.2f: Skipped a member - can't find a place to spawn\n", gpGlobals->curtime ); } } m_cooldownTimer.Start( m_flCooldownDuration ); return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CMissionPopulator::UpdateMissionDestroySentries( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( !m_cooldownTimer.IsElapsed() || !m_checkSentriesTimer.IsElapsed() ) return false; if ( g_pPopulationManager->IsSpawningPaused() ) return false; m_checkSentriesTimer.Start( RandomFloat( 5.0f, 10.0f ) ); int nDmgLimit = 0; int nKillLimit = 0; m_pManager->GetSentryBusterDamageAndKillThreshold( nDmgLimit, nKillLimit ); CUtlVector<CObjectSentrygun *> dangerousSentries; FOR_EACH_VEC( IBaseObjectAutoList::AutoList(), i ) { CBaseObject *pObj = static_cast<CBaseObject *>( IBaseObjectAutoList::AutoList()[i] ); if ( pObj->ObjectType() != OBJ_SENTRYGUN ) continue; if ( pObj->IsDisposableBuilding() ) continue; if ( pObj->GetTeamNumber() != TF_TEAM_MVM_BOTS ) continue; CTFPlayer *pOwner = pObj->GetOwner(); if ( pOwner ) { int nDmgDone = pOwner->GetAccumulatedSentryGunDamageDealt(); int nKillsMade = pOwner->GetAccumulatedSentryGunKillCount(); if ( nDmgDone >= nDmgLimit || nKillsMade >= nKillLimit ) { dangerousSentries.AddToTail( static_cast<CObjectSentrygun *>( pObj ) ); } } } // TODO: Move away from depending on players CUtlVector<CTFPlayer *> bots; CollectPlayers( &bots, TF_TEAM_MVM_BOTS, true ); bool bSpawned = false; FOR_EACH_VEC( dangerousSentries, i ) { CObjectSentrygun *pSentry = dangerousSentries[i]; int nValidCount = 0; FOR_EACH_VEC( bots, j ) { CTFBot *pBot = ToTFBot( bots[j] ); if ( pBot ) { if ( pBot->HasMission( CTFBot::MissionType::DESTROY_SENTRIES ) && pBot->GetMissionTarget() == pSentry ) break; } nValidCount++; } if ( nValidCount < bots.Count() ) continue; Vector vecSpawnPos; SpawnLocationResult spawnLocationResult = m_where.FindSpawnLocation( &vecSpawnPos ); if ( spawnLocationResult != SPAWN_LOCATION_NOT_FOUND ) { CUtlVector<EHANDLE> spawnedBots; if ( m_pSpawner && m_pSpawner->Spawn( vecSpawnPos, &spawnedBots ) ) { if ( tf_populator_debug.GetBool() ) { DevMsg( "MANN VS MACHINE: %3.2f: <<<< Spawning Sentry Busting Mission >>>>\n", gpGlobals->curtime ); } FOR_EACH_VEC( spawnedBots, k ) { CTFBot *pBot = ToTFBot( spawnedBots[k] ); if ( pBot == NULL ) continue; bSpawned = true; pBot->SetMission( CTFBot::MissionType::DESTROY_SENTRIES ); pBot->SetMissionTarget( pSentry ); pBot->SetFlagTarget( NULL ); pBot->SetBloodColor( DONT_BLEED ); pBot->Update(); pBot->GetPlayerClass()->SetCustomModel( "models/bots/demo/bot_sentry_buster.mdl", true ); pBot->UpdateModel(); if ( TFObjectiveResource() ) { unsigned int iFlags = MVM_CLASS_FLAG_MISSION; if ( pBot->IsMiniBoss() ) iFlags |= MVM_CLASS_FLAG_MINIBOSS; if ( pBot->HasAttribute( CTFBot::AttributeType::ALWAYSCRIT ) ) iFlags |= MVM_CLASS_FLAG_ALWAYSCRIT; TFObjectiveResource()->IncrementMannVsMachineWaveClassCount( m_pSpawner->GetClassIcon( k ), iFlags ); } if ( TFGameRules() ) TFGameRules()->HaveAllPlayersSpeakConceptIfAllowed( MP_CONCEPT_MVM_SENTRY_BUSTER, TF_TEAM_MVM_BOTS ); if ( spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) OnBotTeleported( pBot ); } } } else if ( tf_populator_debug.GetBool() ) { Warning( "MissionPopulator: %3.2f: Can't find a place to spawn a sentry destroying squad\n", gpGlobals->curtime ); } } if ( bSpawned ) { float flCoolDown = m_flCooldownDuration; CWave *pWave = m_pManager->GetCurrentWave(); if ( pWave ) { pWave->m_nNumSentryBustersKilled++; if ( TFGameRules() ) { if ( pWave->m_nNumSentryBustersKilled > 1 ) { TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Sentry_Buster_Alert_Another" ); } else { TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Sentry_Buster_Alert" ); } } flCoolDown = m_flCooldownDuration + pWave->m_nNumSentryBustersKilled * m_flCooldownDuration; pWave->m_nNumSentryBustersKilled = 0;; } m_cooldownTimer.Start( flCoolDown ); } return bSpawned; } int CWaveSpawnPopulator::sm_reservedPlayerSlotCount = 0; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWaveSpawnPopulator::CWaveSpawnPopulator( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { m_iMaxActive = 999; m_nSpawnCount = 1; m_iTotalCurrency = -1; m_startWaveEvent = NULL; m_firstSpawnEvent = NULL; m_lastSpawnEvent = NULL; m_doneEvent = NULL; m_parentWave = NULL; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWaveSpawnPopulator::~CWaveSpawnPopulator() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } delete m_startWaveEvent; delete m_firstSpawnEvent; delete m_lastSpawnEvent; delete m_doneEvent; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWaveSpawnPopulator::Parse( KeyValues *data ) { KeyValues *pTemplate = data->FindKey( "Template" ); if ( pTemplate ) { KeyValues *pTemplateKV = m_pManager->GetTemplate( pTemplate->GetString() ); if ( pTemplateKV ) { if ( !Parse( pTemplateKV ) ) return false; } else { Warning( "Unknown Template '%s' in WaveSpawn definition\n", pTemplate->GetString() ); } } FOR_EACH_SUBKEY( data, pSubKey ) { if ( m_where.Parse( pSubKey ) ) continue; const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "TotalCount" ) ) { m_iTotalCount = data->GetInt(); } else if ( !V_stricmp( pszKey, "MaxActive" ) ) { m_iMaxActive = data->GetInt(); } else if ( !V_stricmp( pszKey, "SpawnCount" ) ) { m_nSpawnCount = data->GetInt(); } else if ( !V_stricmp( pszKey, "WaitBeforeStarting" ) ) { m_flWaitBeforeStarting = data->GetFloat(); } else if ( !V_stricmp( pszKey, "WaitBetweenSpawns" ) ) { if ( m_flWaitBetweenSpawns != 0 && m_bWaitBetweenSpawnsAfterDeath ) { Warning( "Already specified WaitBetweenSpawnsAfterDeath time, WaitBetweenSpawns won't be used\n" ); continue; } m_flWaitBetweenSpawns = data->GetFloat(); } else if ( !V_stricmp( pszKey, "WaitBetweenSpawnsAfterDeath" ) ) { if ( m_flWaitBetweenSpawns != 0 ) { Warning( "Already specified WaitBetweenSpawns time, WaitBetweenSpawnsAfterDeath won't be used\n" ); continue; } m_bWaitBetweenSpawnsAfterDeath = true; m_flWaitBetweenSpawns = data->GetFloat(); } else if ( !V_stricmp( pszKey, "StartWaveWarningSound" ) ) { m_startWaveWarningSound.sprintf( "%s", data->GetString() ); } else if ( !V_stricmp( pszKey, "StartWaveOutput" ) ) { m_startWaveEvent = ParseEvent( data ); } else if ( !V_stricmp( pszKey, "FirstSpawnWarningSound" ) ) { m_firstSpawnWarningSound.sprintf( "%s", data->GetString() ); } else if ( !V_stricmp( pszKey, "FirstSpawnOutput" ) ) { m_firstSpawnEvent = ParseEvent( data ); } else if ( !V_stricmp( pszKey, "LastSpawnWarningSound" ) ) { m_lastSpawnWarningSound.sprintf( "%s", data->GetString() ); } else if ( !V_stricmp( pszKey, "LastSpawnOutput" ) ) { m_lastSpawnEvent = ParseEvent( data ); } else if ( !V_stricmp( pszKey, "DoneWarningSound" ) ) { m_doneWarningSound.sprintf( "%s", data->GetString() ); } else if ( !V_stricmp( pszKey, "DoneOutput" ) ) { m_doneEvent = ParseEvent( data ); } else if ( !V_stricmp( pszKey, "TotalCurrency" ) ) { m_iTotalCurrency = data->GetInt(); } else if ( !V_stricmp( pszKey, "Name" ) ) { m_name = data->GetString(); } else if ( !V_stricmp( pszKey, "WaitForAllSpawned" ) ) { m_szWaitForAllSpawned = data->GetString(); } else if ( !V_stricmp( pszKey, "WaitForAllDead" ) ) { m_szWaitForAllDead = data->GetString(); } else if ( !V_stricmp( pszKey, "Support" ) ) { m_bLimitedSupport = !V_stricmp( data->GetString(), "Limited" ); m_bSupportWave = true; } else if ( !V_stricmp( pszKey, "RandomSpawn" ) ) { m_bRandomSpawn = data->GetBool(); } else { m_pSpawner = IPopulationSpawner::ParseSpawner( this, data ); if ( m_pSpawner == NULL ) { Warning( "Unknown attribute '%s' in WaveSpawn definition.\n", pszKey ); } } m_iRemainingCurrency = m_iTotalCurrency; m_iRemainingCount = m_iTotalCount; } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::Update( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); switch ( m_eState ) { case PENDING: { m_timer.Start( m_flWaitBeforeStarting ); SetState( PRE_SPAWN_DELAY ); sm_reservedPlayerSlotCount = 0; if ( m_startWaveWarningSound.Length() > 0 ) TFGameRules()->BroadcastSound( 255, m_startWaveWarningSound ); FireEvent( m_startWaveEvent, "StartWaveOutput" ); if ( tf_populator_debug.GetBool() ) { DevMsg( "%3.2f: WaveSpawn(%s) started PRE_SPAWN_DELAY\n", gpGlobals->curtime, m_name.IsEmpty() ? "" : m_name.Get() ); } } break; case PRE_SPAWN_DELAY: { if ( !m_timer.IsElapsed() ) return; m_nNumSpawnedSoFar = 0; m_nReservedPlayerSlots = 0; SetState( SPAWNING ); if ( m_firstSpawnWarningSound.Length() > 0 ) TFGameRules()->BroadcastSound( 255, m_firstSpawnWarningSound ); FireEvent( m_firstSpawnEvent, "FirstSpawnOutput" ); if ( tf_populator_debug.GetBool() ) { DevMsg( "%3.2f: WaveSpawn(%s) started SPAWNING\n", gpGlobals->curtime, m_name.IsEmpty() ? "" : m_name.Get() ); } } break; case SPAWNING: { if ( !m_timer.IsElapsed() || g_pPopulationManager->IsSpawningPaused() ) return; if ( !m_pSpawner ) { Warning( "Invalid spawner\n" ); SetState( DONE ); return; } int nNumActive = 0; FOR_EACH_VEC( m_activeSpawns, i ) { if ( m_activeSpawns[i] && m_activeSpawns[i]->IsAlive() ) nNumActive++; } if ( m_bWaitBetweenSpawnsAfterDeath ) { if ( nNumActive != 0 ) { return; } else { if ( m_spawnLocationResult ) { m_spawnLocationResult = SPAWN_LOCATION_NOT_FOUND; if ( m_flWaitBetweenSpawns > 0 ) m_timer.Start( m_flWaitBetweenSpawns ); return; } } } if ( nNumActive >= m_iMaxActive ) return; if ( m_nReservedPlayerSlots <= 0 ) { if ( nNumActive - m_iMaxActive < m_nSpawnCount ) return; int nTotalBotCount = GetGlobalTeam( TF_TEAM_MVM_BOTS )->GetNumPlayers(); if ( nTotalBotCount + m_nSpawnCount + sm_reservedPlayerSlotCount > k_nMvMBotTeamSize ) return; sm_reservedPlayerSlotCount += m_nSpawnCount; m_nReservedPlayerSlots = m_nSpawnCount; } Vector vecSpawnPos = vec3_origin; if ( m_pSpawner && m_pSpawner->IsWhereRequired() ) { if ( m_spawnLocationResult == SPAWN_LOCATION_NOT_FOUND || m_spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) { m_spawnLocationResult = m_where.FindSpawnLocation( &m_vecSpawnPosition ); if ( m_spawnLocationResult == SPAWN_LOCATION_NOT_FOUND ) return; } vecSpawnPos = m_vecSpawnPosition; if ( m_bRandomSpawn ) m_spawnLocationResult = SPAWN_LOCATION_NOT_FOUND; } CUtlVector<EHANDLE> spawnedBots; if ( m_pSpawner && m_pSpawner->Spawn( vecSpawnPos, &spawnedBots ) ) { FOR_EACH_VEC( spawnedBots, i ) { CTFBot *pBot = ToTFBot( spawnedBots[i] ); if ( pBot ) { pBot->SetCurrency( 0 ); pBot->m_pWaveSpawnPopulator = this; TFObjectiveResource()->SetMannVsMachineWaveClassActive( pBot->GetPlayerClass()->GetClassIconName() ); if ( m_bLimitedSupport ) pBot->m_bLimitedSupport = true; if ( m_spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) OnBotTeleported( pBot ); } else { CTFTankBoss *pTank = dynamic_cast<CTFTankBoss *>( spawnedBots[i].Get() ); if ( pTank ) { pTank->SetCurrencyValue( 0 ); pTank->SetWaveSpawnPopulator( this ); m_parentWave->m_nNumTanksSpawned++; } } } int nNumSpawned = spawnedBots.Count(); m_nNumSpawnedSoFar += nNumSpawned; int nNumSlotsToFree = ( nNumSpawned <= m_nReservedPlayerSlots ) ? nNumSpawned : m_nReservedPlayerSlots; m_nReservedPlayerSlots -= nNumSlotsToFree; sm_reservedPlayerSlotCount -= nNumSlotsToFree; FOR_EACH_VEC( spawnedBots, i ) { CBaseEntity *pEntity = spawnedBots[i]; FOR_EACH_VEC( m_activeSpawns, j ) { if ( m_activeSpawns[j] && m_activeSpawns[j]->entindex() == pEntity->entindex() ) { Warning( "WaveSpawn duplicate entry in active vector\n" ); continue; } } m_activeSpawns.AddToTail( pEntity ); } if ( IsFinishedSpawning() ) { SetState( WAIT_FOR_ALL_DEAD ); return; } if ( m_nReservedPlayerSlots <= 0 && !m_bWaitBetweenSpawnsAfterDeath ) { m_spawnLocationResult = SPAWN_LOCATION_NOT_FOUND; if ( m_flWaitBetweenSpawns > 0 ) m_timer.Start( m_flWaitBetweenSpawns ); } return; } m_timer.Start( 1.0f ); } break; case WAIT_FOR_ALL_DEAD: { FOR_EACH_VEC( m_activeSpawns, i ) { if ( m_activeSpawns[i] && m_activeSpawns[i]->IsAlive() ) return; } SetState( DONE ); } break; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::OnPlayerKilled( CTFPlayer *pPlayer ) { m_activeSpawns.FindAndFastRemove( pPlayer ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::ForceFinish( void ) { if ( m_eState < WAIT_FOR_ALL_DEAD ) { SetState( WAIT_FOR_ALL_DEAD ); } else if ( m_eState != WAIT_FOR_ALL_DEAD ) { SetState( DONE ); } FOR_EACH_VEC( m_activeSpawns, i ) { CTFBot *pBot = ToTFBot( m_activeSpawns[i] ); if ( pBot ) { pBot->ChangeTeam( TEAM_SPECTATOR, false, true ); } else { m_activeSpawns[i]->Remove(); } } m_activeSpawns.Purge(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CWaveSpawnPopulator::GetCurrencyAmountPerDeath( void ) { int nCurrency = 0; if ( m_bSupportWave ) { if ( m_eState == WAIT_FOR_ALL_DEAD ) m_iRemainingCount = m_activeSpawns.Count(); } if ( m_iRemainingCurrency > 0 ) { m_iRemainingCount = m_iRemainingCount <= 0 ? 1 : m_iRemainingCount; nCurrency = m_iRemainingCurrency / m_iRemainingCount--; m_iRemainingCurrency -= nCurrency; } return nCurrency; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWaveSpawnPopulator::IsFinishedSpawning( void ) { if ( m_bSupportWave && !m_bLimitedSupport ) return false; return ( m_nNumSpawnedSoFar >= m_iTotalCount ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::OnNonSupportWavesDone( void ) { if ( m_bSupportWave ) { switch ( m_eState ) { case PENDING: case PRE_SPAWN_DELAY: SetState( DONE ); break; case SPAWNING: case WAIT_FOR_ALL_DEAD: if ( TFGameRules() && ( m_iRemainingCurrency > 0 ) ) { TFGameRules()->DistributeCurrencyAmount( m_iRemainingCurrency, NULL, true, true ); m_iRemainingCurrency = 0; } SetState( WAIT_FOR_ALL_DEAD ); break; } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWaveSpawnPopulator::SetState( InternalStateType eState ) { m_eState = eState; if ( eState == WAIT_FOR_ALL_DEAD ) { if ( m_lastSpawnWarningSound.Length() > 0 ) { TFGameRules()->BroadcastSound( 255, m_lastSpawnWarningSound ); } FireEvent( m_lastSpawnEvent, "LastSpawnOutput" ); if ( tf_populator_debug.GetBool() ) { DevMsg( "%3.2f: WaveSpawn(%s) started WAIT_FOR_ALL_DEAD\n", gpGlobals->curtime, m_name.IsEmpty() ? "" : m_name.Get() ); } } else if ( eState == DONE ) { if ( m_doneWarningSound.Length() > 0 ) { TFGameRules()->BroadcastSound( 255, m_doneWarningSound ); } FireEvent( m_doneEvent, "DoneOutput" ); if ( tf_populator_debug.GetBool() ) { DevMsg( "%3.2f: WaveSpawn(%s) DONE\n", gpGlobals->curtime, m_name.IsEmpty() ? "" : m_name.Get() ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CPeriodicSpawnPopulator::CPeriodicSpawnPopulator( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { m_flMinInterval = 30.0f; m_flMaxInterval = 30.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CPeriodicSpawnPopulator::~CPeriodicSpawnPopulator() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CPeriodicSpawnPopulator::Parse( KeyValues *data ) { FOR_EACH_SUBKEY( data, pSubKey ) { if ( m_where.Parse( pSubKey ) ) continue; const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "When" ) ) { if ( pSubKey->GetFirstSubKey() ) { FOR_EACH_SUBKEY( pSubKey, pWhenSubKey ) { if ( !V_stricmp( pWhenSubKey->GetName(), "MinInterval" ) ) { m_flMinInterval = pWhenSubKey->GetFloat(); } else if ( !V_stricmp( pWhenSubKey->GetName(), "MaxInterval" ) ) { m_flMaxInterval = pWhenSubKey->GetFloat(); } else { Warning( "Invalid field '%s' encountered in When\n", pWhenSubKey->GetName() ); return false; } } } else { m_flMinInterval = pSubKey->GetFloat(); m_flMaxInterval = m_flMinInterval; } } else { m_pSpawner = IPopulationSpawner::ParseSpawner( this, pSubKey ); if ( m_pSpawner == NULL ) { Warning( "Unknown attribute '%s' in PeriodicSpawn definition.\n", pszKey ); } } } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPeriodicSpawnPopulator::PostInitialize( void ) { m_timer.Start( RandomFloat( m_flMinInterval, m_flMaxInterval ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPeriodicSpawnPopulator::Update( void ) { if ( !m_timer.IsElapsed() || g_pPopulationManager->IsSpawningPaused() ) return; Vector vecSpawnPos; SpawnLocationResult spawnLocationResult = m_where.FindSpawnLocation( &vecSpawnPos ); if ( spawnLocationResult != SPAWN_LOCATION_NOT_FOUND ) { CUtlVector<EHANDLE> spawnedBots; if ( m_pSpawner && m_pSpawner->Spawn( vecSpawnPos, &spawnedBots ) ) { m_timer.Start( RandomFloat( m_flMinInterval, m_flMaxInterval ) ); FOR_EACH_VEC( spawnedBots, k ) { CTFBot *pBot = ToTFBot( spawnedBots[k] ); if ( pBot && spawnLocationResult == SPAWN_LOCATION_TELEPORTER ) OnBotTeleported( pBot ); } return; } } m_timer.Start( 2.0f ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPeriodicSpawnPopulator::UnpauseSpawning( void ) { m_timer.Start( RandomFloat( m_flMinInterval, m_flMaxInterval ) ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CRandomPlacementPopulator::CRandomPlacementPopulator( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CRandomPlacementPopulator::~CRandomPlacementPopulator() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CRandomPlacementPopulator::Parse( KeyValues *data ) { FOR_EACH_SUBKEY( data, pSubKey ) { const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "Count" ) ) { m_iCount = pSubKey->GetInt(); } else if ( !V_stricmp( pszKey, "MinimumSeparation" ) ) { m_flMinSeparation = pSubKey->GetFloat(); } else if ( !V_stricmp( pszKey, "NavAreaFilter" ) ) { if ( !V_stricmp( pSubKey->GetString(), "SENTRY_SPOT" ) ) { m_nNavAreaFilter = TF_NAV_SENTRY_SPOT; } else if ( !V_stricmp( pSubKey->GetString(), "SNIPER_SPOT" ) ) { m_nNavAreaFilter = TF_NAV_SNIPER_SPOT; } else { Warning( "Unknown NavAreaFilter value '%s'\n", pSubKey->GetString() ); } } else { m_pSpawner = IPopulationSpawner::ParseSpawner( this, pSubKey ); if ( m_pSpawner == NULL ) { Warning( "Unknown attribute '%s' in RandomPlacement definition.\n", pszKey ); } } } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CRandomPlacementPopulator::PostInitialize( void ) { CUtlVector<CTFNavArea *> markedAreas;; FOR_EACH_VEC( TheNavAreas, i ) { CTFNavArea *pArea = (CTFNavArea *)TheNavAreas[i]; if ( pArea->HasTFAttributes( m_nNavAreaFilter ) ) markedAreas.AddToTail( pArea ); } CUtlVector<CTFNavArea *> selectedAreas; SelectSeparatedShuffleSet< CTFNavArea >( m_iCount, m_flMinSeparation, markedAreas, &selectedAreas ); if ( m_pSpawner ) { FOR_EACH_VEC( selectedAreas, i ) { m_pSpawner->Spawn( selectedAreas[i]->GetCenter() ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWave::CWave( CPopulationManager *pManager ) : m_pManager( pManager ), m_pSpawner( NULL ) { m_startWaveEvent = NULL; m_doneEvent = NULL; m_initWaveEvent = NULL; m_bCheckBonusCreditsMin = true; m_bCheckBonusCreditsMax = true; m_doneTimer.Invalidate(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWave::~CWave() { if ( m_pSpawner ) { delete m_pSpawner; m_pSpawner = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWave::Parse( KeyValues *data ) { FOR_EACH_SUBKEY( data, pSubKey ) { const char *pszKey = pSubKey->GetName(); if ( !V_stricmp( pszKey, "WaveSpawn" ) ) { CWaveSpawnPopulator *pWavePopulator = new CWaveSpawnPopulator( m_pManager ); if ( !pWavePopulator->Parse( pSubKey ) ) { Warning( "Error reading WaveSpawn definition\n" ); return false; } if ( !pWavePopulator->m_bSupportWave ) m_nTotalEnemyCount += pWavePopulator->m_iTotalCount; m_iTotalCurrency += pWavePopulator->m_iTotalCurrency; pWavePopulator->m_parentWave = this; m_WaveSpawns.AddToTail( pWavePopulator ); if ( pWavePopulator->GetSpawner() ) { if ( pWavePopulator->GetSpawner()->IsVarious() ) { for ( int i = 0; i < pWavePopulator->m_iTotalCount; ++i ) { unsigned int iFlags = pWavePopulator->m_bSupportWave ? MVM_CLASS_FLAG_SUPPORT : MVM_CLASS_FLAG_NORMAL; if ( pWavePopulator->GetSpawner()->IsMiniBoss( i ) ) iFlags |= MVM_CLASS_FLAG_MINIBOSS; if ( pWavePopulator->GetSpawner()->HasAttribute( CTFBot::AttributeType::ALWAYSCRIT, i ) ) iFlags |= MVM_CLASS_FLAG_ALWAYSCRIT; if ( pWavePopulator->m_bLimitedSupport ) iFlags |= MVM_CLASS_FLAG_SUPPORT_LIMITED; AddClassType( pWavePopulator->GetSpawner()->GetClassIcon( i ), 1, iFlags ); } } else { unsigned int iFlags = pWavePopulator->m_bSupportWave ? MVM_CLASS_FLAG_SUPPORT : MVM_CLASS_FLAG_NORMAL; if ( pWavePopulator->GetSpawner()->IsMiniBoss() ) iFlags |= MVM_CLASS_FLAG_MINIBOSS; if ( pWavePopulator->GetSpawner()->HasAttribute( CTFBot::AttributeType::ALWAYSCRIT ) ) iFlags |= MVM_CLASS_FLAG_ALWAYSCRIT; if ( pWavePopulator->m_bLimitedSupport ) iFlags |= MVM_CLASS_FLAG_SUPPORT_LIMITED; AddClassType( pWavePopulator->GetSpawner()->GetClassIcon(), pWavePopulator->m_iTotalCount, iFlags ); } } } else if ( !V_stricmp( pszKey, "Sound" ) ) { m_soundName.sprintf( "%s", pSubKey->GetString() ); } else if ( !V_stricmp( pszKey, "Description" ) ) { m_description.sprintf( "%s", pSubKey->GetString() ); } else if ( !V_stricmp( pszKey, "WaitWhenDone" ) ) { m_flWaitWhenDone = pSubKey->GetFloat(); } else if ( !V_stricmp( pszKey, "Checkpoint" ) ) { } else if ( !V_stricmp( pszKey, "StartWaveOutput" ) ) { m_startWaveEvent = ParseEvent( pSubKey ); } else if ( !V_stricmp( pszKey, "DoneOutput" ) ) { m_doneEvent = ParseEvent( pSubKey ); } else if ( !V_stricmp( pszKey, "InitWaveOutput" ) ) { m_initWaveEvent = ParseEvent( pSubKey ); } else { Warning( "Unknown attribute '%s' in Wave definition.\n", pszKey ); } } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::Update( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( TFGameRules()->State_Get() == GR_STATE_RND_RUNNING ) { ActiveWaveUpdate(); } else if ( TFGameRules()->State_Get() == GR_STATE_BETWEEN_RNDS || TFGameRules()->State_Get() == GR_STATE_TEAM_WIN ) { WaveIntermissionUpdate(); } if ( m_bEveryWaveSpawnDone && TFGameRules()->State_Get() == GR_STATE_RND_RUNNING ) { if ( m_pManager->byte58A ) { if ( m_pManager->ehandle58C && m_pManager->ehandle58C->IsAlive() ) return; } WaveCompleteUpdate(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::OnPlayerKilled( CTFPlayer *pPlayer ) { FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->OnPlayerKilled( pPlayer ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWave::HasEventChangeAttributes( const char *pszEventName ) const { bool bHasEventChangeAttributes = false; FOR_EACH_VEC( m_WaveSpawns, i ) { bHasEventChangeAttributes |= m_WaveSpawns[i]->HasEventChangeAttributes( pszEventName ); } return bHasEventChangeAttributes; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::AddClassType( string_t iszClassIconName, int nCount, unsigned int iFlags ) { int nIndex = -1; FOR_EACH_VEC( m_WaveClassCounts, i ) { WaveClassCount_t const &count = m_WaveClassCounts[i]; if ( ( count.iszClassIconName == iszClassIconName ) && ( count.iFlags & iFlags ) ) { nIndex = i; break; } } if ( nIndex == -1 ) { nIndex = m_WaveClassCounts.AddToTail( {0, iszClassIconName, MVM_CLASS_FLAG_NONE} ); } m_WaveClassCounts[ nIndex ].nClassCount += nCount; m_WaveClassCounts[ nIndex ].iFlags |= iFlags; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWaveSpawnPopulator *CWave::FindWaveSpawnPopulator( const char *name ) { FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *pPopulator = m_WaveSpawns[i]; if ( !V_stricmp( pPopulator->m_name, name ) ) return pPopulator; } return nullptr; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::ForceFinish() { FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->ForceFinish(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::ForceReset() { m_bStarted = false; m_bFiredInitWaveOutput = false; m_bEveryWaveSpawnDone = false; m_flStartTime = 0; m_doneTimer.Invalidate(); FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->m_iRemainingCurrency = m_WaveSpawns[i]->m_iTotalCurrency; m_WaveSpawns[i]->m_iRemainingCount = m_WaveSpawns[i]->m_iTotalCount; m_WaveSpawns[i]->m_eState = CWaveSpawnPopulator::PENDING; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWave::IsDoneWithNonSupportWaves( void ) { FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *pPopulator = m_WaveSpawns[i]; if ( pPopulator->m_bSupportWave && pPopulator->m_eState != CWaveSpawnPopulator::DONE ) return false; } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::ActiveWaveUpdate( void ) { VPROF_BUDGET( __FUNCTION__, "NextBot" ); if ( !m_bStarted ) { if ( m_pManager->IsInEndlessWaves() && m_flStartTime > gpGlobals->curtime ) return; m_bStarted = true; FireEvent( m_startWaveEvent, "StartWaveOutput" ); if ( m_soundName.Length() > 0 ) TFGameRules()->BroadcastSound( 255, m_soundName ); m_pManager->AdjustMinPlayerSpawnTime(); } m_bEveryWaveSpawnDone = true; FOR_EACH_VEC( m_WaveSpawns, i ) { CWaveSpawnPopulator *pPopulator = m_WaveSpawns[i]; bool bWaiting = false; if ( !pPopulator->m_szWaitForAllSpawned.IsEmpty() ) { FOR_EACH_VEC( m_WaveSpawns, j ) { CWaveSpawnPopulator *pWaitingPopulator = m_WaveSpawns[j]; if ( pWaitingPopulator == NULL ) continue; if ( V_stricmp( pWaitingPopulator->m_name, pPopulator->m_szWaitForAllSpawned ) ) continue; if ( pWaitingPopulator->m_eState <= CWaveSpawnPopulator::SPAWNING ) { bWaiting = true; break; } } } if ( !bWaiting && !pPopulator->m_szWaitForAllDead.IsEmpty() ) { FOR_EACH_VEC( m_WaveSpawns, j ) { CWaveSpawnPopulator *pWaitingPopulator = m_WaveSpawns[j]; if ( pWaitingPopulator == NULL ) continue; if ( V_stricmp( pWaitingPopulator->m_name, pPopulator->m_szWaitForAllSpawned ) ) continue; if ( pWaitingPopulator->m_eState != CWaveSpawnPopulator::DONE ) { bWaiting = true; break; } } } if ( bWaiting ) continue; pPopulator->Update(); m_bEveryWaveSpawnDone &= ( pPopulator->m_eState == CWaveSpawnPopulator::DONE ); } if ( IsDoneWithNonSupportWaves() ) { FOR_EACH_VEC( m_WaveSpawns, i ) { m_WaveSpawns[i]->OnNonSupportWavesDone(); } for ( int i = 0; i <= gpGlobals->maxClients; ++i ) { CTFPlayer *pPlayer = ToTFPlayer( UTIL_PlayerByIndex( i ) ); if ( !pPlayer || !pPlayer->IsAlive() ) continue; if ( pPlayer->GetTeamNumber() != TF_TEAM_MVM_BOTS ) continue; pPlayer->CommitSuicide( true ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::WaveCompleteUpdate( void ) { FireEvent( m_doneEvent, "DoneOutput" ); bool bAdvancedPopfile = ( g_pPopulationManager ? g_pPopulationManager->IsAdvanced() : false ); IGameEvent *event = gameeventmanager->CreateEvent( "mvm_wave_complete" ); if ( event ) { event->SetBool( "advanced", bAdvancedPopfile ); gameeventmanager->FireEvent( event ); } if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() && bAdvancedPopfile ) { CTeamControlPointMaster *pMaster = g_hControlPointMasters.Count() ? g_hControlPointMasters[0] : NULL; if ( pMaster && ( pMaster->GetNumPoints() > 0 ) ) { if ( pMaster->GetNumPointsOwnedByTeam( TF_TEAM_MVM_BOTS ) == pMaster->GetNumPoints() ) { IGameEvent *event = gameeventmanager->CreateEvent( "mvm_adv_wave_complete_no_gates" ); if ( event ) { event->SetInt( "index", m_pManager->m_nCurrentWaveIndex ); gameeventmanager->FireEvent( event ); } } } } if ( ( m_pManager->m_nCurrentWaveIndex + 1 ) >= m_pManager->m_Waves.Count() && !m_pManager->IsInEndlessWaves() ) { m_pManager->MvMVictory(); if ( TFGameRules() ) { /*if ( GTFGCClientSystem()->dword3B8 && GTFGCClientSystem()->dword3B8->dword10 == 1 ) TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Manned_Up_Wave_End" ); else*/ TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Final_Wave_End" ); TFGameRules()->BroadcastSound( 255, "music.mvm_end_last_wave" ); } event = gameeventmanager->CreateEvent( "mvm_mission_complete" ); if ( event ) { event->SetString( "mission", m_pManager->GetPopulationFilename() ); gameeventmanager->FireEvent( event ); } } else { if ( TFGameRules() ) { TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Wave_End" ); if ( m_nNumTanksSpawned >= 1 ) TFGameRules()->BroadcastSound( 255, "music.mvm_end_tank_wave" ); else if ( ( m_pManager->m_nCurrentWaveIndex + 1 ) >= ( m_pManager->m_Waves.Count() / 2 ) ) TFGameRules()->BroadcastSound( 255, "music.mvm_end_mid_wave" ); else TFGameRules()->BroadcastSound( 255, "music.mvm_end_wave" ); } } CReliableBroadcastRecipientFilter filter; UserMessageBegin( filter, "MVMAnnouncement" ); WRITE_CHAR( MVM_ANNOUNCEMENT_WAVE_COMPLETE ); WRITE_CHAR( m_pManager->m_nCurrentWaveIndex ); MessageEnd(); // Why does this care about the resource? if ( TFObjectiveResource() ) { CUtlVector<CTFPlayer *> players; CollectPlayers( &players, TF_TEAM_MVM_PLAYERS ); FOR_EACH_VEC( players, i ) { if ( !players[i]->IsAlive() ) players[i]->ForceRespawn(); players[i]->m_nAccumulatedSentryGunDamageDealt = 0; players[i]->m_nAccumulatedSentryGunKillCount = 0; } } m_pManager->WaveEnd( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWave::WaveIntermissionUpdate( void ) { if ( !m_bFiredInitWaveOutput ) { FireEvent( m_initWaveEvent, "InitWaveOutput" ); m_bFiredInitWaveOutput = true; } if ( m_upgradeAlertTimer.HasStarted() && m_upgradeAlertTimer.IsElapsed() ) { if ( ( m_bCheckBonusCreditsMin || m_bCheckBonusCreditsMax ) && gpGlobals->curtime > m_flBonusCreditsTime ) { int nWaveNum = m_pManager->m_nCurrentWaveIndex - 1; int nDropped = MannVsMachineStats_GetDroppedCredits( nWaveNum ); int nAcquired = MannVsMachineStats_GetAcquiredCredits( nWaveNum, false ); float flRatioCollected = clamp( ( (float)nAcquired / (float)nDropped ), 0.1f, 1.f ); float flMinBonus = tf_mvm_currency_bonus_ratio_min.GetFloat(); float flMaxBonus = tf_mvm_currency_bonus_ratio_max.GetFloat(); if ( m_bCheckBonusCreditsMax && nDropped > 0 && flRatioCollected >= flMaxBonus ) { int nAmount = TFGameRules()->CalculateCurrencyAmount_ByType( CURRENCY_WAVE_COLLECTION_BONUS ); TFGameRules()->DistributeCurrencyAmount( (float)nAmount * 0.5f, NULL, true, false, true ); TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Bonus" ); IGameEvent *event = gameeventmanager->CreateEvent( "mvm_creditbonus_wave" ); if ( event ) { gameeventmanager->FireEvent( event ); } m_bCheckBonusCreditsMax = false; m_upgradeAlertTimer.Reset(); } if ( m_bCheckBonusCreditsMin && nDropped > 0 && flRatioCollected >= fminf( flMinBonus, flMaxBonus ) ) { int nAmount = TFGameRules()->CalculateCurrencyAmount_ByType( CURRENCY_WAVE_COLLECTION_BONUS ); TFGameRules()->DistributeCurrencyAmount( (float)nAmount * 0.5f, NULL, true, false, true ); TFGameRules()->BroadcastSound( 255, "Announcer.MVM_Bonus" ); IGameEvent *event = gameeventmanager->CreateEvent( "mvm_creditbonus_wave" ); if ( event ) { gameeventmanager->FireEvent( event ); } m_bCheckBonusCreditsMin = false; } m_flBonusCreditsTime = gpGlobals->curtime + 0.25f; } } if ( m_doneTimer.HasStarted() && m_doneTimer.IsElapsed() ) { m_doneTimer.Invalidate(); m_pManager->StartCurrentWave(); } }
27.228208
345
0.581691
TF2V
90988967ffcba91de30826913ed51391104c44d4
1,437
cc
C++
lib/dfuds-trie.cc
rockeet/taiju
90f152d5e66b1741d35b9d871f7a5db68699d48d
[ "BSD-3-Clause" ]
null
null
null
lib/dfuds-trie.cc
rockeet/taiju
90f152d5e66b1741d35b9d871f7a5db68699d48d
[ "BSD-3-Clause" ]
null
null
null
lib/dfuds-trie.cc
rockeet/taiju
90f152d5e66b1741d35b9d871f7a5db68699d48d
[ "BSD-3-Clause" ]
null
null
null
#include <taiju/dfuds-trie.h> namespace taiju { UInt64 DfudsTrie::size() const { return sizeof(TrieType) + sizeof(UInt64) + dfuds_.size() + labels_.size() + is_terminals_.size(); } void DfudsTrie::clear() { num_keys_ = 0; dfuds_.clear(); labels_.clear(); is_terminals_.clear(); } void DfudsTrie::swap(DfudsTrie *target) { std::swap(num_keys_, target->num_keys_); dfuds_.swap(&target->dfuds_); labels_.swap(&target->labels_); is_terminals_.swap(&target->is_terminals_); } const void *DfudsTrie::map(Mapper mapper, bool checks_type) { DfudsTrie temp; if (checks_type) { if (*mapper.map<TrieType>() != type()) TAIJU_THROW("failed to map DfudsTrie: wrong TrieType"); } temp.num_keys_ = *mapper.map<UInt64>(); mapper = temp.dfuds_.map(mapper); mapper = temp.labels_.map(mapper); mapper = temp.is_terminals_.map(mapper); swap(&temp); return mapper.address(); } void DfudsTrie::read(Reader reader, bool checks_type) { DfudsTrie temp; if (checks_type) { TrieType trie_type; reader.read(&trie_type); if (trie_type != type()) TAIJU_THROW("failed to read DfudsTrie: wrong TrieType"); } reader.read(&temp.num_keys_); temp.dfuds_.read(reader); temp.labels_.read(reader); temp.is_terminals_.read(reader); swap(&temp); } void DfudsTrie::write(Writer writer) const { writer.write(num_keys_); dfuds_.write(writer); labels_.write(writer); is_terminals_.write(writer); } } // namespace taiju
18.907895
59
0.707029
rockeet
9098f2d6d40bea864601fdade28d0b3dff6376f9
8,082
cpp
C++
src/Map/MapMainCharacter.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
279
2015-05-06T19:04:07.000Z
2022-03-21T21:33:38.000Z
src/Map/MapMainCharacter.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
222
2016-10-26T15:56:25.000Z
2021-10-03T15:30:18.000Z
src/Map/MapMainCharacter.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
49
2015-10-01T21:23:03.000Z
2022-03-19T20:11:31.000Z
#include "Map/MapMainCharacter.h" #include "Map/DynamicTiles/DoorMapTile.h" #include "Screens/MapScreen.h" MapMainCharacter::MapMainCharacter(Map* map, Screen* screen) : MapMovableGameObject(map) { m_screen = screen; load(); m_isAlwaysUpdate = true; } MapMainCharacter::~MapMainCharacter() { } void MapMainCharacter::setCharacterCore(CharacterCore* core) { m_core = core; setPosition(m_core->getData().currentMapPosition); } void MapMainCharacter::update(const sf::Time& frameTime) { m_previousFramePosition = getPosition(); handleInput(); sf::Vector2f nextPosition; calculateNextPosition(frameTime, nextPosition); checkCollisions(nextPosition); MovableGameObject::update(frameTime); updateAnimation(frameTime); handleInteraction(); } void MapMainCharacter::checkCollisions(const sf::Vector2f& nextPosition) { const sf::FloatRect& bb = *getBoundingBox(); sf::FloatRect nextBoundingBoxX(nextPosition.x, bb.top, bb.width, bb.height); sf::FloatRect nextBoundingBoxY(bb.left, nextPosition.y, bb.width, bb.height); WorldCollisionQueryRecord rec; auto const isMovingY = nextPosition.y != bb.top; auto const isMovingX = nextPosition.x != bb.left; auto const isMovingRight = nextPosition.x > bb.left; auto const isMovingDown = nextPosition.y > bb.top; if (!isMovingX && !isMovingY) return; // should we use strategy 2: try y direction first, then x direction? auto tryYfirst = false; rec.boundingBox = nextBoundingBoxX; rec.collisionDirection = isMovingRight ? CollisionDirection::Right : CollisionDirection::Left; if (m_map->collides(rec)) { if (std::abs(nextPosition.x - rec.safeLeft) > 5.f) { tryYfirst = true; } } if (!tryYfirst) { // check for collision on x axis rec.boundingBox = nextBoundingBoxX; rec.collisionDirection = isMovingRight ? CollisionDirection::Right : CollisionDirection::Left; if (isMovingX && m_map->collides(rec)) { setAccelerationX(0.f); setVelocityX(0.f); if (!rec.noSafePos) { setPositionX(rec.safeLeft); nextBoundingBoxY.left = rec.safeLeft; } } else { nextBoundingBoxY.left = nextPosition.x; } // check for collision on y axis rec.boundingBox = nextBoundingBoxY; rec.collisionDirection = isMovingDown ? CollisionDirection::Down : CollisionDirection::Up; if (isMovingY && m_map->collides(rec)) { setAccelerationY(0.f); setVelocityY(0.f); if (!rec.noSafePos) { setPositionY(rec.safeTop); } } } else { // check for collision on y axis rec.boundingBox = nextBoundingBoxY; rec.collisionDirection = isMovingDown ? CollisionDirection::Down : CollisionDirection::Up; if (isMovingY && m_map->collides(rec)) { setAccelerationY(0.f); setVelocityY(0.f); if (!rec.noSafePos) { setPositionY(rec.safeTop); nextBoundingBoxX.top = rec.safeTop; } } else { nextBoundingBoxX.top = nextPosition.y; } // check for collision on x axis rec.boundingBox = nextBoundingBoxX; rec.collisionDirection = isMovingRight ? CollisionDirection::Right : CollisionDirection::Left; if (isMovingX & m_map->collides(rec)) { setAccelerationX(0.f); setVelocityX(0.f); if (!rec.noSafePos) { setPositionX(rec.safeLeft); } } } } void MapMainCharacter::render(sf::RenderTarget& target) { MapMovableGameObject::render(target); dynamic_cast<MapScreen*>(m_screen)->renderEquipment(target); } void MapMainCharacter::handleInput() { sf::Vector2f currentAcceleration; if (g_inputController->isDown()) { currentAcceleration += sf::Vector2f(0.f, 1.f); } if (g_inputController->isUp()) { currentAcceleration += sf::Vector2f(0.f, -1.f); } if (g_inputController->isLeft()) { currentAcceleration += sf::Vector2f(-1.f, 0.f); } if (g_inputController->isRight()) { currentAcceleration += sf::Vector2f(1.f, 0.f); } currentAcceleration *= WALK_ACCELERATION; setAcceleration(currentAcceleration); } void MapMainCharacter::load() { g_resourceManager->loadTexture(getSpritePath(), ResourceType::Map); const sf::Texture* tex = g_resourceManager->getTexture(getSpritePath()); setBoundingBox(sf::FloatRect(0.f, 0.f, 18.f, 15.f)); setSpriteOffset(sf::Vector2f(-16.f, -35.f)); Animation* walkingAnimationDown = new Animation(sf::seconds(0.15f)); walkingAnimationDown->setSpriteSheet(tex); walkingAnimationDown->addFrame(sf::IntRect(0, 0, 50, 50)); walkingAnimationDown->addFrame(sf::IntRect(50, 0, 50, 50)); walkingAnimationDown->addFrame(sf::IntRect(100, 0, 50, 50)); walkingAnimationDown->addFrame(sf::IntRect(50, 0, 50, 50)); addAnimation(GameObjectState::Walking_down, walkingAnimationDown); Animation* walkingAnimationLeft = new Animation(sf::seconds(0.15f)); walkingAnimationLeft->setSpriteSheet(tex); walkingAnimationLeft->addFrame(sf::IntRect(0, 50, 50, 50)); walkingAnimationLeft->addFrame(sf::IntRect(50, 50, 50, 50)); walkingAnimationLeft->addFrame(sf::IntRect(100, 50, 50, 50)); walkingAnimationLeft->addFrame(sf::IntRect(50, 50, 50, 50)); addAnimation(GameObjectState::Walking_left, walkingAnimationLeft); Animation* walkingAnimationRight = new Animation(sf::seconds(0.15f)); walkingAnimationRight->setSpriteSheet(tex); walkingAnimationRight->addFrame(sf::IntRect(0, 100, 50, 50)); walkingAnimationRight->addFrame(sf::IntRect(50, 100, 50, 50)); walkingAnimationRight->addFrame(sf::IntRect(100, 100, 50, 50)); walkingAnimationRight->addFrame(sf::IntRect(50, 100, 50, 50)); addAnimation(GameObjectState::Walking_right, walkingAnimationRight); Animation* walkingAnimationUp = new Animation(sf::seconds(0.15f)); walkingAnimationUp->setSpriteSheet(tex); walkingAnimationUp->addFrame(sf::IntRect(0, 150, 50, 50)); walkingAnimationUp->addFrame(sf::IntRect(50, 150, 50, 50)); walkingAnimationUp->addFrame(sf::IntRect(100, 150, 50, 50)); walkingAnimationUp->addFrame(sf::IntRect(50, 150, 50, 50)); addAnimation(GameObjectState::Walking_up, walkingAnimationUp); Animation* idleAnimationDown = new Animation(); idleAnimationDown->setSpriteSheet(tex); idleAnimationDown->addFrame(sf::IntRect(50, 0, 50, 50)); addAnimation(GameObjectState::Idle_down, idleAnimationDown); Animation* idleAnimationLeft = new Animation(); idleAnimationLeft->setSpriteSheet(tex); idleAnimationLeft->addFrame(sf::IntRect(50, 50, 50, 50)); addAnimation(GameObjectState::Idle_left, idleAnimationLeft); Animation* idleAnimationRight = new Animation(); idleAnimationRight->setSpriteSheet(tex); idleAnimationRight->addFrame(sf::IntRect(50, 100, 50, 50)); addAnimation(GameObjectState::Idle_right, idleAnimationRight); Animation* idleAnimationUp = new Animation(); idleAnimationUp->setSpriteSheet(tex); idleAnimationUp->addFrame(sf::IntRect(50, 150, 50, 50)); addAnimation(GameObjectState::Idle_up, idleAnimationUp); setDebugBoundingBox(COLOR_WHITE); // initial values m_state = GameObjectState::Idle_down; setCurrentAnimation(getAnimation(m_state), false); playCurrentAnimation(true); } void MapMainCharacter::calculateUnboundedVelocity(const sf::Time& frameTime, sf::Vector2f& nextVel) const { if (getAcceleration().x == 0.f) { nextVel.x = 0.f; } else { nextVel.x = (getVelocity().x + getAcceleration().x * frameTime.asSeconds()); } if (getAcceleration().y == 0.f) { nextVel.y = 0.f; } else { nextVel.y = (getVelocity().y + getAcceleration().y * frameTime.asSeconds()); } } void MapMainCharacter::boundVelocity(sf::Vector2f& vel) const { // check bounds if (std::abs(vel.x) > getConfiguredMaxVelocityX() || std::abs(vel.y) > getConfiguredMaxVelocityX()) { normalize(vel); vel *= getConfiguredMaxVelocityX(); } } const sf::Vector2f& MapMainCharacter::getPreviousPosition() const { return m_previousFramePosition; } float MapMainCharacter::getConfiguredMaxVelocityX() const { return 200.f; } GameObjectType MapMainCharacter::getConfiguredType() const { return _MapMovableGameObject; } std::string MapMainCharacter::getSpritePath() const { if (!m_screen->getCharacterCore()->isConditionFulfilled("boss", "BossVelius")) { return "res/texture/cendric/spritesheet_cendric_map.png"; } return "res/texture/cendric/spritesheet_cendric_map_end.png"; }
31.694118
107
0.740906
tizian
909a52dc3448ecd463564363e92672b248dde74e
17,478
cpp
C++
B2G/gecko/widget/xpwidgets/nsTransferable.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/widget/xpwidgets/nsTransferable.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/widget/xpwidgets/nsTransferable.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Notes to self: - at some point, strings will be accessible from JS, so we won't have to wrap flavors in an nsISupportsCString. Until then, we're kinda stuck with this crappy API of nsISupportsArrays. */ #include "nsTransferable.h" #include "nsString.h" #include "nsReadableUtils.h" #include "nsTArray.h" #include "nsIFormatConverter.h" #include "nsIComponentManager.h" #include "nsCOMPtr.h" #include "nsXPCOM.h" #include "nsISupportsPrimitives.h" #include "nsMemory.h" #include "nsPrimitiveHelpers.h" #include "nsXPIDLString.h" #include "nsDirectoryServiceDefs.h" #include "nsDirectoryService.h" #include "nsCRT.h" #include "nsNetUtil.h" #include "nsIOutputStream.h" #include "nsIInputStream.h" #include "nsIFile.h" #include "nsILoadContext.h" #include "nsAutoPtr.h" NS_IMPL_ISUPPORTS1(nsTransferable, nsITransferable) uint32_t GetDataForFlavor (const nsTArray<DataStruct>& aArray, const char* aDataFlavor) { for (uint32_t i = 0 ; i < aArray.Length () ; ++i) { if (aArray[i].GetFlavor().Equals (aDataFlavor)) return i; } return aArray.NoIndex; } //------------------------------------------------------------------------- DataStruct::~DataStruct() { if (mCacheFileName) nsCRT::free(mCacheFileName); //nsIFileSpec * cacheFile = GetFileSpec(mCacheFileName); //cacheFile->Remove(); } //------------------------------------------------------------------------- void DataStruct::SetData ( nsISupports* aData, uint32_t aDataLen ) { // Now, check to see if we consider the data to be "too large" if (aDataLen > kLargeDatasetSize) { // if so, cache it to disk instead of memory if ( NS_SUCCEEDED(WriteCache(aData, aDataLen)) ) return; else NS_WARNING("Oh no, couldn't write data to the cache file"); } mData = aData; mDataLen = aDataLen; } //------------------------------------------------------------------------- void DataStruct::GetData ( nsISupports** aData, uint32_t *aDataLen ) { // check here to see if the data is cached on disk if ( !mData && mCacheFileName ) { // if so, read it in and pass it back // ReadCache creates memory and copies the data into it. if ( NS_SUCCEEDED(ReadCache(aData, aDataLen)) ) return; else { // oh shit, something went horribly wrong here. NS_WARNING("Oh no, couldn't read data in from the cache file"); *aData = nullptr; *aDataLen = 0; return; } } *aData = mData; if ( mData ) NS_ADDREF(*aData); *aDataLen = mDataLen; } //------------------------------------------------------------------------- nsIFile* DataStruct::GetFileSpec(const char * aFileName) { nsIFile* cacheFile; NS_GetSpecialDirectory(NS_OS_TEMP_DIR, &cacheFile); if (cacheFile == nullptr) return nullptr; // if the param aFileName contains a name we should use that // because the file probably already exists // otherwise create a unique name if (!aFileName) { cacheFile->AppendNative(NS_LITERAL_CSTRING("clipboardcache")); cacheFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600); } else { cacheFile->AppendNative(nsDependentCString(aFileName)); } return cacheFile; } //------------------------------------------------------------------------- nsresult DataStruct::WriteCache(nsISupports* aData, uint32_t aDataLen) { // Get a new path and file to the temp directory nsCOMPtr<nsIFile> cacheFile ( getter_AddRefs(GetFileSpec(mCacheFileName)) ); if (cacheFile) { // remember the file name if (!mCacheFileName) { nsXPIDLCString fName; cacheFile->GetNativeLeafName(fName); mCacheFileName = nsCRT::strdup(fName); } // write out the contents of the clipboard // to the file //uint32_t bytes; nsCOMPtr<nsIOutputStream> outStr; NS_NewLocalFileOutputStream(getter_AddRefs(outStr), cacheFile); if (!outStr) return NS_ERROR_FAILURE; void* buff = nullptr; nsPrimitiveHelpers::CreateDataFromPrimitive ( mFlavor.get(), aData, &buff, aDataLen ); if ( buff ) { uint32_t ignored; outStr->Write(reinterpret_cast<char*>(buff), aDataLen, &ignored); nsMemory::Free(buff); return NS_OK; } } return NS_ERROR_FAILURE; } //------------------------------------------------------------------------- nsresult DataStruct::ReadCache(nsISupports** aData, uint32_t* aDataLen) { // if we don't have a cache filename we are out of luck if (!mCacheFileName) return NS_ERROR_FAILURE; // get the path and file name nsCOMPtr<nsIFile> cacheFile ( getter_AddRefs(GetFileSpec(mCacheFileName)) ); bool exists; if ( cacheFile && NS_SUCCEEDED(cacheFile->Exists(&exists)) && exists ) { // get the size of the file int64_t fileSize; int64_t max32(LL_INIT(0, 0xFFFFFFFF)); cacheFile->GetFileSize(&fileSize); if (fileSize > max32) return NS_ERROR_OUT_OF_MEMORY; uint32_t size; LL_L2UI(size, fileSize); // create new memory for the large clipboard data nsAutoArrayPtr<char> data(new char[size]); if ( !data ) return NS_ERROR_OUT_OF_MEMORY; // now read it all in nsCOMPtr<nsIInputStream> inStr; NS_NewLocalFileInputStream( getter_AddRefs(inStr), cacheFile); if (!cacheFile) return NS_ERROR_FAILURE; nsresult rv = inStr->Read(data, fileSize, aDataLen); // make sure we got all the data ok if (NS_SUCCEEDED(rv) && *aDataLen == size) { nsPrimitiveHelpers::CreatePrimitiveForData ( mFlavor.get(), data, fileSize, aData ); return *aData ? NS_OK : NS_ERROR_FAILURE; } // zero the return params *aData = nullptr; *aDataLen = 0; } return NS_ERROR_FAILURE; } //------------------------------------------------------------------------- // // Transferable constructor // //------------------------------------------------------------------------- nsTransferable::nsTransferable() : mPrivateData(false) #ifdef DEBUG , mInitialized(false) #endif { } //------------------------------------------------------------------------- // // Transferable destructor // //------------------------------------------------------------------------- nsTransferable::~nsTransferable() { } NS_IMETHODIMP nsTransferable::Init(nsILoadContext* aContext) { MOZ_ASSERT(!mInitialized); if (aContext) { mPrivateData = aContext->UsePrivateBrowsing(); } #ifdef DEBUG mInitialized = true; #endif return NS_OK; } // // GetTransferDataFlavors // // Returns a copy of the internal list of flavors. This does NOT take into // account any converter that may be registered. This list consists of // nsISupportsCString objects so that the flavor list can be accessed from JS. // nsresult nsTransferable::GetTransferDataFlavors(nsISupportsArray ** aDataFlavorList) { MOZ_ASSERT(mInitialized); nsresult rv = NS_NewISupportsArray ( aDataFlavorList ); if (NS_FAILED(rv)) return rv; for ( uint32_t i=0; i<mDataArray.Length(); ++i ) { DataStruct& data = mDataArray.ElementAt(i); nsCOMPtr<nsISupportsCString> flavorWrapper = do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID); if ( flavorWrapper ) { flavorWrapper->SetData ( data.GetFlavor() ); nsCOMPtr<nsISupports> genericWrapper ( do_QueryInterface(flavorWrapper) ); (*aDataFlavorList)->AppendElement( genericWrapper ); } } return NS_OK; } // // GetTransferData // // Returns the data of the requested flavor, obtained from either having the data on hand or // using a converter to get it. The data is wrapped in a nsISupports primitive so that it is // accessible from JS. // NS_IMETHODIMP nsTransferable::GetTransferData(const char *aFlavor, nsISupports **aData, uint32_t *aDataLen) { MOZ_ASSERT(mInitialized); NS_ENSURE_ARG_POINTER(aFlavor && aData && aDataLen); nsresult rv = NS_OK; nsCOMPtr<nsISupports> savedData; // first look and see if the data is present in one of the intrinsic flavors uint32_t i; for (i = 0; i < mDataArray.Length(); ++i ) { DataStruct& data = mDataArray.ElementAt(i); if ( data.GetFlavor().Equals(aFlavor) ) { nsCOMPtr<nsISupports> dataBytes; uint32_t len; data.GetData(getter_AddRefs(dataBytes), &len); if (len == kFlavorHasDataProvider && dataBytes) { // do we have a data provider? nsCOMPtr<nsIFlavorDataProvider> dataProvider = do_QueryInterface(dataBytes); if (dataProvider) { rv = dataProvider->GetFlavorData(this, aFlavor, getter_AddRefs(dataBytes), &len); if (NS_FAILED(rv)) break; // the provider failed. fall into the converter code below. } } if (dataBytes && len > 0) { // XXXmats why is zero length not ok? *aDataLen = len; dataBytes.forget(aData); return NS_OK; } savedData = dataBytes; // return this if format converter fails break; } } bool found = false; // if not, try using a format converter to get the requested flavor if ( mFormatConv ) { for (i = 0; i < mDataArray.Length(); ++i) { DataStruct& data = mDataArray.ElementAt(i); bool canConvert = false; mFormatConv->CanConvert(data.GetFlavor().get(), aFlavor, &canConvert); if ( canConvert ) { nsCOMPtr<nsISupports> dataBytes; uint32_t len; data.GetData(getter_AddRefs(dataBytes), &len); if (len == kFlavorHasDataProvider && dataBytes) { // do we have a data provider? nsCOMPtr<nsIFlavorDataProvider> dataProvider = do_QueryInterface(dataBytes); if (dataProvider) { rv = dataProvider->GetFlavorData(this, aFlavor, getter_AddRefs(dataBytes), &len); if (NS_FAILED(rv)) break; // give up } } mFormatConv->Convert(data.GetFlavor().get(), dataBytes, len, aFlavor, aData, aDataLen); found = true; break; } } } // for backward compatibility if (!found) { savedData.forget(aData); *aDataLen = 0; } return found ? NS_OK : NS_ERROR_FAILURE; } // // GetAnyTransferData // // Returns the data of the first flavor found. Caller is responsible for deleting the // flavor string. // NS_IMETHODIMP nsTransferable::GetAnyTransferData(char **aFlavor, nsISupports **aData, uint32_t *aDataLen) { MOZ_ASSERT(mInitialized); NS_ENSURE_ARG_POINTER(aFlavor && aData && aDataLen); for ( uint32_t i=0; i < mDataArray.Length(); ++i ) { DataStruct& data = mDataArray.ElementAt(i); if (data.IsDataAvailable()) { *aFlavor = ToNewCString(data.GetFlavor()); data.GetData(aData, aDataLen); return NS_OK; } } return NS_ERROR_FAILURE; } // // SetTransferData // // // NS_IMETHODIMP nsTransferable::SetTransferData(const char *aFlavor, nsISupports *aData, uint32_t aDataLen) { MOZ_ASSERT(mInitialized); NS_ENSURE_ARG(aFlavor); // first check our intrinsic flavors to see if one has been registered. uint32_t i = 0; for (i = 0; i < mDataArray.Length(); ++i) { DataStruct& data = mDataArray.ElementAt(i); if ( data.GetFlavor().Equals(aFlavor) ) { data.SetData ( aData, aDataLen ); return NS_OK; } } // if not, try using a format converter to find a flavor to put the data in if ( mFormatConv ) { for (i = 0; i < mDataArray.Length(); ++i) { DataStruct& data = mDataArray.ElementAt(i); bool canConvert = false; mFormatConv->CanConvert(aFlavor, data.GetFlavor().get(), &canConvert); if ( canConvert ) { nsCOMPtr<nsISupports> ConvertedData; uint32_t ConvertedLen; mFormatConv->Convert(aFlavor, aData, aDataLen, data.GetFlavor().get(), getter_AddRefs(ConvertedData), &ConvertedLen); data.SetData(ConvertedData, ConvertedLen); return NS_OK; } } } // Can't set data neither directly nor through converter. Just add this flavor and try again nsresult result = NS_ERROR_FAILURE; if ( NS_SUCCEEDED(AddDataFlavor(aFlavor)) ) result = SetTransferData (aFlavor, aData, aDataLen); return result; } // // AddDataFlavor // // Adds a data flavor to our list with no data. Error if it already exists. // NS_IMETHODIMP nsTransferable::AddDataFlavor(const char *aDataFlavor) { MOZ_ASSERT(mInitialized); if (GetDataForFlavor (mDataArray, aDataFlavor) != mDataArray.NoIndex) return NS_ERROR_FAILURE; // Create a new "slot" for the data mDataArray.AppendElement(DataStruct ( aDataFlavor )); return NS_OK; } // // RemoveDataFlavor // // Removes a data flavor (and causes the data to be destroyed). Error if // the requested flavor is not present. // NS_IMETHODIMP nsTransferable::RemoveDataFlavor(const char *aDataFlavor) { MOZ_ASSERT(mInitialized); uint32_t idx; if ((idx = GetDataForFlavor(mDataArray, aDataFlavor)) != mDataArray.NoIndex) { mDataArray.RemoveElementAt (idx); return NS_OK; } return NS_ERROR_FAILURE; } /** * * */ NS_IMETHODIMP nsTransferable::IsLargeDataSet(bool *_retval) { MOZ_ASSERT(mInitialized); NS_ENSURE_ARG_POINTER(_retval); *_retval = false; return NS_OK; } /** * * */ NS_IMETHODIMP nsTransferable::SetConverter(nsIFormatConverter * aConverter) { MOZ_ASSERT(mInitialized); mFormatConv = aConverter; return NS_OK; } /** * * */ NS_IMETHODIMP nsTransferable::GetConverter(nsIFormatConverter * *aConverter) { MOZ_ASSERT(mInitialized); NS_ENSURE_ARG_POINTER(aConverter); *aConverter = mFormatConv; NS_IF_ADDREF(*aConverter); return NS_OK; } // // FlavorsTransferableCanImport // // Computes a list of flavors that the transferable can accept into it, either through // intrinsic knowledge or input data converters. // NS_IMETHODIMP nsTransferable::FlavorsTransferableCanImport(nsISupportsArray **_retval) { MOZ_ASSERT(mInitialized); NS_ENSURE_ARG_POINTER(_retval); // Get the flavor list, and on to the end of it, append the list of flavors we // can also get to through a converter. This is so that we can just walk the list // in one go, looking for the desired flavor. GetTransferDataFlavors(_retval); // addrefs nsCOMPtr<nsIFormatConverter> converter; GetConverter(getter_AddRefs(converter)); if ( converter ) { nsCOMPtr<nsISupportsArray> convertedList; converter->GetInputDataFlavors(getter_AddRefs(convertedList)); if ( convertedList ) { uint32_t importListLen; convertedList->Count(&importListLen); for ( uint32_t i=0; i < importListLen; ++i ) { nsCOMPtr<nsISupports> genericFlavor; convertedList->GetElementAt ( i, getter_AddRefs(genericFlavor) ); nsCOMPtr<nsISupportsCString> flavorWrapper ( do_QueryInterface (genericFlavor) ); nsAutoCString flavorStr; flavorWrapper->GetData( flavorStr ); if (GetDataForFlavor (mDataArray, flavorStr.get()) == mDataArray.NoIndex) // Don't append if already in intrinsic list (*_retval)->AppendElement (genericFlavor); } // foreach flavor that can be converted to } } // if a converter exists return NS_OK; } // FlavorsTransferableCanImport // // FlavorsTransferableCanExport // // Computes a list of flavors that the transferable can export, either through // intrinsic knowledge or output data converters. // NS_IMETHODIMP nsTransferable::FlavorsTransferableCanExport(nsISupportsArray **_retval) { MOZ_ASSERT(mInitialized); NS_ENSURE_ARG_POINTER(_retval); // Get the flavor list, and on to the end of it, append the list of flavors we // can also get to through a converter. This is so that we can just walk the list // in one go, looking for the desired flavor. GetTransferDataFlavors(_retval); // addrefs nsCOMPtr<nsIFormatConverter> converter; GetConverter(getter_AddRefs(converter)); if ( converter ) { nsCOMPtr<nsISupportsArray> convertedList; converter->GetOutputDataFlavors(getter_AddRefs(convertedList)); if ( convertedList ) { uint32_t importListLen; convertedList->Count(&importListLen); for ( uint32_t i=0; i < importListLen; ++i ) { nsCOMPtr<nsISupports> genericFlavor; convertedList->GetElementAt ( i, getter_AddRefs(genericFlavor) ); nsCOMPtr<nsISupportsCString> flavorWrapper ( do_QueryInterface (genericFlavor) ); nsAutoCString flavorStr; flavorWrapper->GetData( flavorStr ); if (GetDataForFlavor (mDataArray, flavorStr.get()) == mDataArray.NoIndex) // Don't append if already in intrinsic list (*_retval)->AppendElement (genericFlavor); } // foreach flavor that can be converted to } } // if a converter exists return NS_OK; } // FlavorsTransferableCanExport NS_IMETHODIMP nsTransferable::GetIsPrivateData(bool *aIsPrivateData) { MOZ_ASSERT(mInitialized); NS_ENSURE_ARG_POINTER(aIsPrivateData); *aIsPrivateData = mPrivateData; return NS_OK; } NS_IMETHODIMP nsTransferable::SetIsPrivateData(bool aIsPrivateData) { MOZ_ASSERT(mInitialized); mPrivateData = aIsPrivateData; return NS_OK; }
27.524409
125
0.653164
wilebeast
909b277e2c4083b785b27724de54c5568c0e2345
1,433
cpp
C++
src/victoryconnect/cpp/packet.cpp
victoryforphil/VictoryConnect-ClientCPP
6ad06edcd6339df933af337f2fa9d111c83d6e2d
[ "MIT" ]
null
null
null
src/victoryconnect/cpp/packet.cpp
victoryforphil/VictoryConnect-ClientCPP
6ad06edcd6339df933af337f2fa9d111c83d6e2d
[ "MIT" ]
null
null
null
src/victoryconnect/cpp/packet.cpp
victoryforphil/VictoryConnect-ClientCPP
6ad06edcd6339df933af337f2fa9d111c83d6e2d
[ "MIT" ]
null
null
null
#include "packet.hpp" #include "utils.hpp" using namespace VictoryConnect; Packet::Packet(PacketType type, std::string path){ mPacketType = type; mPath = path; } Packet::Packet(PacketType type, std::string path, std::vector<std::string> data){ mPacketType = type; mPath = path; mData = data; } void Packet::addData(std::string dataToAdd){ mData.push_back(dataToAdd); } void Packet::setProtocol(std::string protocol){ mProtocol = protocol; } void Packet::setRaw(std::string raw){ mRaw = raw; } void Packet::setPath(std::string path){ mPath = path; } void Packet::setType(PacketType type){ mPacketType = type; } // Get Functions std::string Packet::getString(){ std::string final = std::to_string(mPacketType); final += " " + mPath + " " + "{"; final += Utils::vectorJoin(mData, ";"); final += "}~\n"; return final; } std::string Packet::toString(){ std::string final = getProtocol() + "->"; final += std::to_string(mPacketType); final += " " + mPath + " " + "{"; final += Utils::vectorJoin(mData, ";"); final += "}~\n"; return final; } std::string Packet::getPath(){ return mPath; } std::string Packet::getRaw(){ return mRaw; } std::string Packet::getProtocol(){ return mProtocol; } std::vector<std::string> Packet::getData(){ return mData; } PacketType Packet::getType(){ return mPacketType; }
19.630137
81
0.620377
victoryforphil
90a0153d9cd3a22ac72408efb5db7ab486547fb5
1,308
cpp
C++
NeoMathEngine/src/CrtAllocatedObject.cpp
AlinaKalyakina/neoml
328eac0d23e45faedb07a336ebfaf36288bb0db9
[ "ECL-2.0", "Apache-2.0" ]
1
2020-12-25T08:04:55.000Z
2020-12-25T08:04:55.000Z
NeoMathEngine/src/CrtAllocatedObject.cpp
AlinaKalyakina/neoml
328eac0d23e45faedb07a336ebfaf36288bb0db9
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NeoMathEngine/src/CrtAllocatedObject.cpp
AlinaKalyakina/neoml
328eac0d23e45faedb07a336ebfaf36288bb0db9
[ "ECL-2.0", "Apache-2.0" ]
1
2020-11-05T06:46:19.000Z
2020-11-05T06:46:19.000Z
/* Copyright © 2017-2020 ABBYY Production LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------------------------------------------------*/ #include <common.h> #pragma hdrstop #include <stdlib.h> #include <NeoMathEngine/CrtAllocatedObject.h> #include <MathEngineCommon.h> namespace NeoML { void* CCrtAllocatedObject::operator new(size_t size) { void* result = malloc(size); if( result == 0 ) { THROW_MEMORY_EXCEPTION; } return result; } void CCrtAllocatedObject::operator delete(void* ptr) { free(ptr); } void* CCrtAllocatedObject::operator new[](size_t size) { void* result = malloc(size); if( result == 0 ) { THROW_MEMORY_EXCEPTION; } return result; } void CCrtAllocatedObject::operator delete[](void* ptr) { free(ptr); } } // namespace NeoML
24.222222
112
0.687309
AlinaKalyakina
90a5e7866bce854daf6b25ebc55b246a382d1e89
7,506
cpp
C++
Source/WebKit/UIProcess/API/glib/WebKitPrivate.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebKit/UIProcess/API/glib/WebKitPrivate.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebKit/UIProcess/API/glib/WebKitPrivate.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2012 Igalia S.L. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "WebKitPrivate.h" #include "APIError.h" #include "WebEvent.h" #include "WebKitError.h" #if PLATFORM(GTK) #include <WebCore/GtkVersioning.h> #elif PLATFORM(WPE) #include <wpe/wpe.h> #endif #if PLATFORM(GTK) unsigned toPlatformModifiers(OptionSet<WebKit::WebEvent::Modifier> wkModifiers) { unsigned modifiers = 0; if (wkModifiers.contains(WebKit::WebEvent::Modifier::ShiftKey)) modifiers |= GDK_SHIFT_MASK; if (wkModifiers.contains(WebKit::WebEvent::Modifier::ControlKey)) modifiers |= GDK_CONTROL_MASK; if (wkModifiers.contains(WebKit::WebEvent::Modifier::AltKey)) modifiers |= GDK_MOD1_MASK; if (wkModifiers.contains(WebKit::WebEvent::Modifier::MetaKey)) modifiers |= GDK_META_MASK; if (wkModifiers.contains(WebKit::WebEvent::Modifier::CapsLockKey)) modifiers |= GDK_LOCK_MASK; return modifiers; } #elif PLATFORM(WPE) unsigned toPlatformModifiers(OptionSet<WebKit::WebEvent::Modifier> wkModifiers) { unsigned modifiers = 0; if (wkModifiers.contains(WebKit::WebEvent::Modifier::ShiftKey)) modifiers |= wpe_input_keyboard_modifier_shift; if (wkModifiers.contains(WebKit::WebEvent::Modifier::ControlKey)) modifiers |= wpe_input_keyboard_modifier_control; if (wkModifiers.contains(WebKit::WebEvent::Modifier::AltKey)) modifiers |= wpe_input_keyboard_modifier_alt; if (wkModifiers.contains(WebKit::WebEvent::Modifier::MetaKey)) modifiers |= wpe_input_keyboard_modifier_meta; return modifiers; } #endif WebKitNavigationType toWebKitNavigationType(WebCore::NavigationType type) { switch (type) { case WebCore::NavigationType::LinkClicked: return WEBKIT_NAVIGATION_TYPE_LINK_CLICKED; case WebCore::NavigationType::FormSubmitted: return WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED; case WebCore::NavigationType::BackForward: return WEBKIT_NAVIGATION_TYPE_BACK_FORWARD; case WebCore::NavigationType::Reload: return WEBKIT_NAVIGATION_TYPE_RELOAD; case WebCore::NavigationType::FormResubmitted: return WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED; case WebCore::NavigationType::Other: return WEBKIT_NAVIGATION_TYPE_OTHER; default: ASSERT_NOT_REACHED(); return WEBKIT_NAVIGATION_TYPE_OTHER; } } unsigned toWebKitMouseButton(WebKit::WebMouseEvent::Button button) { switch (button) { case WebKit::WebMouseEvent::Button::NoButton: return 0; case WebKit::WebMouseEvent::Button::LeftButton: return 1; case WebKit::WebMouseEvent::Button::MiddleButton: return 2; case WebKit::WebMouseEvent::Button::RightButton: return 3; } ASSERT_NOT_REACHED(); return 0; } unsigned toWebKitError(unsigned webCoreError) { switch (webCoreError) { case API::Error::Network::Cancelled: return WEBKIT_NETWORK_ERROR_CANCELLED; case API::Error::Network::FileDoesNotExist: return WEBKIT_NETWORK_ERROR_FILE_DOES_NOT_EXIST; case API::Error::Policy::CannotShowMIMEType: return WEBKIT_POLICY_ERROR_CANNOT_SHOW_MIME_TYPE; case API::Error::Policy::CannotShowURL: return WEBKIT_POLICY_ERROR_CANNOT_SHOW_URI; case API::Error::Policy::FrameLoadInterruptedByPolicyChange: return WEBKIT_POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE; case API::Error::Policy::CannotUseRestrictedPort: return WEBKIT_POLICY_ERROR_CANNOT_USE_RESTRICTED_PORT; case API::Error::Plugin::CannotFindPlugIn: return WEBKIT_PLUGIN_ERROR_CANNOT_FIND_PLUGIN; case API::Error::Plugin::CannotLoadPlugIn: return WEBKIT_PLUGIN_ERROR_CANNOT_LOAD_PLUGIN; case API::Error::Plugin::JavaUnavailable: return WEBKIT_PLUGIN_ERROR_JAVA_UNAVAILABLE; case API::Error::Plugin::PlugInCancelledConnection: return WEBKIT_PLUGIN_ERROR_CONNECTION_CANCELLED; case API::Error::Plugin::PlugInWillHandleLoad: return WEBKIT_PLUGIN_ERROR_WILL_HANDLE_LOAD; case API::Error::Download::Transport: return WEBKIT_DOWNLOAD_ERROR_NETWORK; case API::Error::Download::CancelledByUser: return WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER; case API::Error::Download::Destination: return WEBKIT_DOWNLOAD_ERROR_DESTINATION; #if PLATFORM(GTK) case API::Error::Print::Generic: return WEBKIT_PRINT_ERROR_GENERAL; case API::Error::Print::PrinterNotFound: return WEBKIT_PRINT_ERROR_PRINTER_NOT_FOUND; case API::Error::Print::InvalidPageRange: return WEBKIT_PRINT_ERROR_INVALID_PAGE_RANGE; #endif default: // This may be a user app defined error, which needs to be passed as-is. return webCoreError; } } unsigned toWebCoreError(unsigned webKitError) { switch (webKitError) { case WEBKIT_NETWORK_ERROR_CANCELLED: return API::Error::Network::Cancelled; case WEBKIT_NETWORK_ERROR_FILE_DOES_NOT_EXIST: return API::Error::Network::FileDoesNotExist; case WEBKIT_POLICY_ERROR_CANNOT_SHOW_MIME_TYPE: return API::Error::Policy::CannotShowMIMEType; case WEBKIT_POLICY_ERROR_CANNOT_SHOW_URI: return API::Error::Policy::CannotShowURL; case WEBKIT_POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE: return API::Error::Policy::FrameLoadInterruptedByPolicyChange; case WEBKIT_POLICY_ERROR_CANNOT_USE_RESTRICTED_PORT: return API::Error::Policy::CannotUseRestrictedPort; case WEBKIT_PLUGIN_ERROR_CANNOT_FIND_PLUGIN: return API::Error::Plugin::CannotFindPlugIn; case WEBKIT_PLUGIN_ERROR_CANNOT_LOAD_PLUGIN: return API::Error::Plugin::CannotLoadPlugIn; case WEBKIT_PLUGIN_ERROR_JAVA_UNAVAILABLE: return API::Error::Plugin::JavaUnavailable; case WEBKIT_PLUGIN_ERROR_CONNECTION_CANCELLED: return API::Error::Plugin::PlugInCancelledConnection; case WEBKIT_PLUGIN_ERROR_WILL_HANDLE_LOAD: return API::Error::Plugin::PlugInWillHandleLoad; case WEBKIT_DOWNLOAD_ERROR_NETWORK: return API::Error::Download::Transport; case WEBKIT_DOWNLOAD_ERROR_CANCELLED_BY_USER: return API::Error::Download::CancelledByUser; case WEBKIT_DOWNLOAD_ERROR_DESTINATION: return API::Error::Download::Destination; #if PLATFORM(GTK) case WEBKIT_PRINT_ERROR_GENERAL: return API::Error::Print::Generic; case WEBKIT_PRINT_ERROR_PRINTER_NOT_FOUND: return API::Error::Print::PrinterNotFound; case WEBKIT_PRINT_ERROR_INVALID_PAGE_RANGE: return API::Error::Print::InvalidPageRange; #endif default: // This may be a user app defined error, which needs to be passed as-is. return webKitError; } }
39.298429
80
0.743272
jacadcaps
90aa99070b3b780ed42ca93899745dd707f6d3a7
427
cpp
C++
src/main/cpp/binarysearch/bounded_square_sums.cpp
jo3-l/cp-practice
d1db0c8e9269c8720b31013068dff948b33f57fd
[ "MIT" ]
5
2022-01-05T20:15:47.000Z
2022-02-15T22:40:44.000Z
src/main/cpp/binarysearch/bounded_square_sums.cpp
jo3-l/ccc-java
7a77f365e52496967e5265ecefb34f3b7db5fae8
[ "MIT" ]
3
2022-01-06T01:34:42.000Z
2022-01-20T23:46:53.000Z
src/main/cpp/binarysearch/bounded_square_sums.cpp
jo3-l/ccc-java
7a77f365e52496967e5265ecefb34f3b7db5fae8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int solve(vector<int> &a, vector<int> &b, int lower, int upper) { transform(b.begin(), b.end(), b.begin(), [](int v) { return v * v; }); sort(b.begin(), b.end()); int n = 0; for (int v : a) { v *= v; int lp = lower_bound(b.begin(), b.end(), lower - v) - b.begin(); int up = upper_bound(b.begin(), b.end(), upper - v) - b.begin(); n += max(up - lp, 0); } return n; }
26.6875
71
0.550351
jo3-l
90ab2bfb36bcb316f23c07b6b04d3afa55a5a3fa
12,909
cpp
C++
openstudiocore/src/model/AirLoopHVACSupplyPlenum.cpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
4
2015-05-02T21:04:15.000Z
2015-10-28T09:47:22.000Z
openstudiocore/src/model/AirLoopHVACSupplyPlenum.cpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
11
2015-05-05T16:16:33.000Z
2017-08-10T08:15:50.000Z
openstudiocore/src/model/AirLoopHVACSupplyPlenum.cpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
1
2017-09-23T12:51:13.000Z
2017-09-23T12:51:13.000Z
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "AirLoopHVAC.hpp" #include "AirLoopHVAC_Impl.hpp" #include "AirLoopHVACZoneSplitter.hpp" #include "AirLoopHVACZoneSplitter_Impl.hpp" #include "AirLoopHVACSupplyPlenum.hpp" #include "AirLoopHVACSupplyPlenum_Impl.hpp" #include "AirLoopHVACReturnPlenum.hpp" #include "AirLoopHVACReturnPlenum_Impl.hpp" #include "AirLoopHVACZoneMixer.hpp" #include "AirLoopHVACZoneMixer_Impl.hpp" #include "ThermalZone.hpp" #include "ThermalZone_Impl.hpp" #include "Model.hpp" #include "Model_Impl.hpp" #include "Node.hpp" #include "Node_Impl.hpp" #include "AirTerminalSingleDuctUncontrolled.hpp" #include "AirTerminalSingleDuctUncontrolled_Impl.hpp" #include <utilities/idd/OS_AirLoopHVAC_SupplyPlenum_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> namespace openstudio { namespace model { namespace detail { AirLoopHVACSupplyPlenum_Impl::AirLoopHVACSupplyPlenum_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : Splitter_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == AirLoopHVACSupplyPlenum::iddObjectType()); } AirLoopHVACSupplyPlenum_Impl::AirLoopHVACSupplyPlenum_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : Splitter_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == AirLoopHVACSupplyPlenum::iddObjectType()); } AirLoopHVACSupplyPlenum_Impl::AirLoopHVACSupplyPlenum_Impl(const AirLoopHVACSupplyPlenum_Impl& other, Model_Impl* model, bool keepHandle) : Splitter_Impl(other,model,keepHandle) {} const std::vector<std::string>& AirLoopHVACSupplyPlenum_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType AirLoopHVACSupplyPlenum_Impl::iddObjectType() const { return AirLoopHVACSupplyPlenum::iddObjectType(); } boost::optional<ThermalZone> AirLoopHVACSupplyPlenum_Impl::thermalZone() const { return getObject<ModelObject>().getModelObjectTarget<ThermalZone>(OS_AirLoopHVAC_SupplyPlenumFields::ThermalZone); } bool AirLoopHVACSupplyPlenum_Impl::setThermalZone(const boost::optional<ThermalZone>& thermalZone) { bool result(false); if( ! thermalZone ) { resetThermalZone(); result = true; } else if( (! thermalZone->getImpl<ThermalZone_Impl>()->airLoopHVACSupplyPlenum()) && (! thermalZone->getImpl<ThermalZone_Impl>()->airLoopHVACReturnPlenum()) && (thermalZone->equipment().size() == 0) && (! thermalZone->useIdealAirLoads()) ) { result = setPointer(OS_AirLoopHVAC_SupplyPlenumFields::ThermalZone, thermalZone.get().handle()); } return result; } void AirLoopHVACSupplyPlenum_Impl::resetThermalZone() { bool result = setString(OS_AirLoopHVAC_SupplyPlenumFields::ThermalZone, ""); OS_ASSERT(result); } unsigned AirLoopHVACSupplyPlenum_Impl::inletPort() { return OS_AirLoopHVAC_SupplyPlenumFields::InletNode; } unsigned AirLoopHVACSupplyPlenum_Impl::outletPort(unsigned branchIndex) { unsigned result; result = numNonextensibleFields(); result = result + branchIndex; return result; } unsigned AirLoopHVACSupplyPlenum_Impl::nextOutletPort() { return outletPort( this->nextBranchIndex() ); } bool AirLoopHVACSupplyPlenum_Impl::addToNode(Node & node) { bool result = true; Model _model = model(); // Is the node in this model if( node.model() != _model ) { result = false; } // Is the node part of an air loop boost::optional<AirLoopHVAC> nodeAirLoop = node.airLoopHVAC(); if( ! nodeAirLoop ) { result = false; } // Is this plenum already connected to a different air loop boost::optional<AirLoopHVAC> currentAirLoopHVAC = airLoopHVAC(); if( currentAirLoopHVAC && (currentAirLoopHVAC.get() != nodeAirLoop) ) { result = false; } boost::optional<ModelObject> inletObj = node.inletModelObject(); boost::optional<ModelObject> outletObj = node.outletModelObject(); boost::optional<AirTerminalSingleDuctUncontrolled> directAirModelObject; boost::optional<ModelObject> directAirInletModelObject; if( inletObj && inletObj->optionalCast<AirTerminalSingleDuctUncontrolled>() ) { directAirModelObject = inletObj->cast<AirTerminalSingleDuctUncontrolled>(); directAirInletModelObject = directAirModelObject->inletModelObject(); } // Is the immediate upstream object to the node a splitter // or a direct air terminal (special case since this guy oddly does not have an inlet node) boost::optional<AirLoopHVACZoneSplitter> splitter; if( result ) { splitter = nodeAirLoop->zoneSplitter(); if( directAirInletModelObject ) { if( ! (splitter && ( directAirInletModelObject.get() == splitter.get() )) ) { result = false; } } else if( ! (inletObj && splitter && ( inletObj.get() == splitter.get() )) ) { result = false; } } // Is there a zone on this branch if( result ) { Mixer mixer = nodeAirLoop->zoneMixer(); if( nodeAirLoop->demandComponents(node,mixer,ThermalZone::iddObjectType()).empty() ) { result = false; } } unsigned oldOutletObjectPort; unsigned oldInletObjectPort; boost::optional<ModelObject> oldInletModelObject; boost::optional<ModelObject> oldOutletModelObject; // Record the old port connections if( result ) { oldInletModelObject = splitter; if( directAirModelObject ) { oldOutletModelObject = directAirModelObject; oldOutletObjectPort = directAirModelObject->inletPort(); oldInletObjectPort = directAirModelObject->connectedObjectPort(directAirModelObject->inletPort()).get(); } else { oldOutletModelObject = node; oldOutletObjectPort = node.inletPort(); oldInletObjectPort = node.connectedObjectPort(node.inletPort()).get(); } } // Create a new node and connect the plenum if( result ) { AirLoopHVACSupplyPlenum thisObject = getObject<AirLoopHVACSupplyPlenum>(); if( currentAirLoopHVAC ) { splitter->removePortForBranch(splitter->branchIndexForOutletModelObject(oldOutletModelObject.get())); _model.connect(thisObject,thisObject.nextOutletPort(),oldOutletModelObject.get(),oldOutletObjectPort); } else { Node plenumInletNode(_model); plenumInletNode.createName(); _model.connect(oldInletModelObject.get(),oldInletObjectPort,plenumInletNode,plenumInletNode.inletPort()); _model.connect(plenumInletNode,plenumInletNode.outletPort(),thisObject,thisObject.inletPort()); _model.connect(thisObject,thisObject.nextOutletPort(),oldOutletModelObject.get(),oldOutletObjectPort); } } return result; } bool AirLoopHVACSupplyPlenum_Impl::addBranchForZone(openstudio::model::ThermalZone & thermalZone, StraightComponent & terminal) { boost::optional<StraightComponent> t_terminal = terminal; return AirLoopHVACSupplyPlenum_Impl::addBranchForZoneImpl(thermalZone,t_terminal); } bool AirLoopHVACSupplyPlenum_Impl::addBranchForZone(openstudio::model::ThermalZone & thermalZone) { boost::optional<StraightComponent> t_terminal; return AirLoopHVACSupplyPlenum_Impl::addBranchForZoneImpl(thermalZone,t_terminal); } bool AirLoopHVACSupplyPlenum_Impl::addBranchForZoneImpl(openstudio::model::ThermalZone & thermalZone, boost::optional<StraightComponent> & terminal) { boost::optional<Splitter> splitter = getObject<AirLoopHVACSupplyPlenum>(); boost::optional<Mixer> mixer; boost::optional<AirLoopHVAC> t_airLoopHVAC = airLoopHVAC(); if( ! t_airLoopHVAC ) { return false; } std::vector<ModelObject> returnPlenums; returnPlenums = t_airLoopHVAC->demandComponents(splitter.get(), t_airLoopHVAC->demandOutletNode(), AirLoopHVACReturnPlenum::iddObjectType()); if( returnPlenums.size() == 1u ) { mixer = returnPlenums.front().cast<Mixer>(); } else { mixer = t_airLoopHVAC->zoneMixer(); } OS_ASSERT(splitter); OS_ASSERT(mixer); return AirLoopHVAC_Impl::addBranchForZoneImpl(thermalZone,t_airLoopHVAC.get(),splitter.get(),mixer.get(),terminal); } std::vector<IdfObject> AirLoopHVACSupplyPlenum_Impl::remove() { Model t_model = model(); if( boost::optional<AirLoopHVAC> t_airLoopHVAC = airLoopHVAC() ) { AirLoopHVACZoneSplitter zoneSplitter= t_airLoopHVAC->zoneSplitter(); std::vector<ModelObject> t_outletModelObjects = outletModelObjects(); for( auto it = t_outletModelObjects.rbegin(); it != t_outletModelObjects.rend(); ++it ) { unsigned branchIndex = branchIndexForOutletModelObject(*it); unsigned t_outletPort = outletPort(branchIndex); unsigned connectedObjectInletPort = connectedObjectPort(t_outletPort).get(); t_model.connect(zoneSplitter,zoneSplitter.nextOutletPort(),*it,connectedObjectInletPort); } boost::optional<ModelObject> mo = inletModelObject(); OS_ASSERT(mo); boost::optional<Node> node = mo->optionalCast<Node>(); OS_ASSERT(node); zoneSplitter.removePortForBranch(zoneSplitter.branchIndexForOutletModelObject(node.get())); node->remove(); } return Splitter_Impl::remove(); } } // detail AirLoopHVACSupplyPlenum::AirLoopHVACSupplyPlenum(const Model& model) : Splitter(AirLoopHVACSupplyPlenum::iddObjectType(),model) { OS_ASSERT(getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()); } IddObjectType AirLoopHVACSupplyPlenum::iddObjectType() { return IddObjectType(IddObjectType::OS_AirLoopHVAC_SupplyPlenum); } boost::optional<ThermalZone> AirLoopHVACSupplyPlenum::thermalZone() const { return getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->thermalZone(); } bool AirLoopHVACSupplyPlenum::setThermalZone(const ThermalZone& thermalZone) { return getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->setThermalZone(thermalZone); } void AirLoopHVACSupplyPlenum::resetThermalZone() { getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->resetThermalZone(); } unsigned AirLoopHVACSupplyPlenum::inletPort() { return getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->inletPort(); } unsigned AirLoopHVACSupplyPlenum::outletPort(unsigned branchIndex) { return getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->outletPort(branchIndex); } unsigned AirLoopHVACSupplyPlenum::nextOutletPort() { return getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->nextOutletPort(); } bool AirLoopHVACSupplyPlenum::addToNode(Node & node) { return getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->addToNode(node); } bool AirLoopHVACSupplyPlenum::addBranchForZone(openstudio::model::ThermalZone & thermalZone) { return getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->addBranchForZone(thermalZone); } bool AirLoopHVACSupplyPlenum::addBranchForZone(openstudio::model::ThermalZone & thermalZone, StraightComponent & terminal) { return getImpl<detail::AirLoopHVACSupplyPlenum_Impl>()->addBranchForZone(thermalZone,terminal); } /// @cond AirLoopHVACSupplyPlenum::AirLoopHVACSupplyPlenum(std::shared_ptr<detail::AirLoopHVACSupplyPlenum_Impl> impl) : Splitter(impl) {} /// @endcond } // model } // openstudio
33.52987
150
0.69347
pepsi7959
90ace3edcc12858a6ac7a6733bbe33a075efbcc0
1,766
cpp
C++
02_estructuras_selectivas/20_pizzeria.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
1
2021-12-03T03:37:04.000Z
2021-12-03T03:37:04.000Z
02_estructuras_selectivas/20_pizzeria.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
null
null
null
02_estructuras_selectivas/20_pizzeria.cpp
gemboedu/ejercicios-basicos-c-
648e2abe4c8e7f51bbfb1d21032eeeee3f5b9343
[ "MIT" ]
null
null
null
/* 20. La pizzería Bella Rita ofrece pizzas vegetarianas y no vegetarianas a sus clientes. Los ingredientes para cada tipo de pizza aparecen a continuación. • Ingredientes vegetarianos: Pimiento y tofu. • Ingredientes no vegetarianos: Peperoni, Jamón y Salmón. Escribir un programa que pregunte al usuario si quiere una pizza vegetariana o no, y en función de su respuesta le muestre un menú con los ingredientes disponibles para que elija. Solo se puede eligir un ingrediente además de la mozzarella y el tomate que están en todas las pizzas. Al final se debe mostrar por pantalla si la pizza elegida es vegetariana o no y todos los ingredientes que lleva. */ #include <iostream> using namespace std; int main() { int tipo, ingrediente; cout << "Bienvenido a la pizzeria Bella Rita.\nTipos de pizza\n\t1- Vegetariana\n\t2- No vegetariana\n" << endl; cout << "Introduce el numero correspondiente al tipo de pizza que quieres: "; cin >> tipo; if (tipo == 1) { cout << "Ingredientes de pizzas vegetarianas\n\t1- Pimiento\n\t2- Tofu\n" << endl; cout << "Introduce el ingrediente que deseas: "; cin >> ingrediente; cout << "Pizza vegetariana con mozzarella, tomate y "; ingrediente == 1 ? cout << "pimiento" : cout << "tofu\n\n"; } else { cout << "Ingredientes de pizzas no vegetarianas\n\t1- Peperoni\n\t2- Jamon\n\t3- Salmon\n"; cout << "Introduce el ingrediente que deseas: "; cin >> ingrediente; cout << "Pizza no vegetarina con mozarrella, tomate y "; ingrediente == 1 ? cout << "peperoni" : ingrediente == 2 ? cout << "jamon" : cout << "salmon\n\n"; } return 0; }
51.941176
396
0.651755
gemboedu
90aef4fe828941f0414be1af66fcaac5e6c71cd0
4,124
cpp
C++
SQLEditor/SQLCodeEditor/CodeEditor/syntaxhighlighter.cpp
stephen-pinto/POC-CPP
6aaabeeb4b35251b853b8be368dcdabb096bca65
[ "MIT" ]
null
null
null
SQLEditor/SQLCodeEditor/CodeEditor/syntaxhighlighter.cpp
stephen-pinto/POC-CPP
6aaabeeb4b35251b853b8be368dcdabb096bca65
[ "MIT" ]
null
null
null
SQLEditor/SQLCodeEditor/CodeEditor/syntaxhighlighter.cpp
stephen-pinto/POC-CPP
6aaabeeb4b35251b853b8be368dcdabb096bca65
[ "MIT" ]
null
null
null
#include "syntaxhighlighter.h" #include <QTextDocument> SyntaxHighlighter::SyntaxHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { addDefualtRules(); } void SyntaxHighlighter::addDefualtRules() { HighlightingRule rule; QFont boldFont(this->document()->defaultFont()); boldFont.setBold(true); QStringList keywordPatterns; keywordPatterns << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b" << "\\bdouble\\b" << "\\benum\\b" << "\\bexplicit\\b" << "\\bfriend\\b" << "\\binline\\b" << "\\bint\\b" << "\\blong\\b" << "\\bnamespace\\b" << "\\boperator\\b" << "\\bprivate\\b" << "\\bprotected\\b" << "\\bpublic\\b" << "\\bshort\\b" << "\\bsignals\\b" << "\\bsigned\\b" << "\\bslots\\b" << "\\bstatic\\b" << "\\bstruct\\b" << "\\btemplate\\b" << "\\btypedef\\b" << "\\btypename\\b" << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvirtual\\b" << "\\bvoid\\b" << "\\bvolatile\\b" << "\\bbool\\b"; foreach (const QString &pattern, keywordPatterns) setRule(QRegularExpression(pattern), QColor(0, 0, 255), boldFont); multiLineCommentFormat.setForeground(Qt::red); setRule(QRegularExpression("\\bQ[A-Za-z]+\\b"), QColor(139,0,139), boldFont); //classes setRule(QRegularExpression("//[^\n]*"), QColor(255, 0, 0)); //single line comments setRule(QRegularExpression("\".*\""), QColor(0, 100, 0)); //quotes setRule(QRegularExpression("\\b[A-Za-z0-9_]+(?=\\()"), QColor(0, 0, 255)); //functions commentStartExpression = QRegularExpression("/\\*"); commentEndExpression = QRegularExpression("\\*/"); } void SyntaxHighlighter::setRule(QRegularExpression matchExprn, QBrush brushForeground) { static HighlightingRule rule; QTextCharFormat format; format.setForeground(brushForeground); rule.format = format; //Set match expression for the rule rule.pattern = matchExprn; //Add new rule highlightingRules.append(rule); } void SyntaxHighlighter::setRule(QRegularExpression matchExprn, QBrush brushForeground, QFont font) { static HighlightingRule rule; QTextCharFormat format; format.setFontWeight(font.weight()); format.setFontItalic(font.italic()); format.setFontCapitalization(font.capitalization()); format.setFontOverline(font.overline()); format.setFontUnderline(font.underline()); format.setFontLetterSpacing(font.letterSpacing()); format.setFontWordSpacing(font.wordSpacing()); format.setFontStretch(font.stretch()); format.setFontStrikeOut(font.strikeOut()); format.setForeground(brushForeground); rule.format = format; //Set match expression for the rule rule.pattern = matchExprn; //Add new rule highlightingRules.append(rule); } void SyntaxHighlighter::highlightBlock(const QString &text) { foreach (const HighlightingRule &rule, highlightingRules) { QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text); while (matchIterator.hasNext()) { QRegularExpressionMatch match = matchIterator.next(); setFormat(match.capturedStart(), match.capturedLength(), rule.format); } } setCurrentBlockState(0); int startIndex = 0; if (previousBlockState() != 1) startIndex = text.indexOf(commentStartExpression); while (startIndex >= 0) { QRegularExpressionMatch match = commentEndExpression.match(text, startIndex); int endIndex = match.capturedStart(); int commentLength = 0; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + match.capturedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); startIndex = text.indexOf(commentStartExpression, startIndex + commentLength); } }
34.366667
98
0.622696
stephen-pinto
90b01b0d728e3bd8671d8c7b7c7442cdb07da9b6
1,583
cpp
C++
codeforce3/505C. Mr. Kitayuta, the Treasure Hunter.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/505C. Mr. Kitayuta, the Treasure Hunter.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce3/505C. Mr. Kitayuta, the Treasure Hunter.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
/* Idea: - Dynamic Programming. - The regular DP using NxN time and memory complexity does not work. It is give correct solutions, but it does not fit the time and memory limits. - To change this solution to accepted one we need to reduce the size of our DP, we need the index where we are now, but the distance we want to jump we can always write it as d + offset, where d is the original d from the question and offset if some value maybe negative or positive. Now we can take the offset with us in the DP and leave d, but what is the lower and upper limits for offset? - To calculate this imagine that we always take the +1 step, so in the first step we are add d then add d + 1, d + 2, ..., d + x. - x value equals to ~245, why? because (d + (d + 1) + (d + 2) + ... + (d + 245)) = 30135 > 30001 (d = 1), so we can take the offset in the DP array and solve the problem. */ #include <bits/stdc++.h> using namespace std; int const N = 3e4 + 10; int n, d, a[N], dp[N][600]; int rec(int cur, int off) { if(cur >= N) return 0; int &ret = dp[cur][300 + off]; if(ret != -1) return ret; ret = 0; if(cur + d + off - 1 > cur) ret = max(ret, rec(cur + (d + off - 1), off - 1) + a[cur]); ret = max(ret, rec(cur + d + off, off) + a[cur]); ret = max(ret, rec(cur + (d + off + 1), off + 1) + a[cur]); return ret; } int main() { scanf("%d %d", &n, &d); for(int i = 0, tmp; i < n; ++i) { scanf("%d", &tmp); ++a[tmp]; } memset(dp, -1, sizeof dp); printf("%d\n", rec(d, 0)); return 0; }
31.039216
135
0.588756
khaled-farouk
ff96d791f1f830a2f1b60d637fc390d4b0c34c17
598
hpp
C++
engine/calculators/include/BlindedCalculator.hpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/calculators/include/BlindedCalculator.hpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/calculators/include/BlindedCalculator.hpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#pragma once #include "StatusEffectCalculator.hpp" #include "Creature.hpp" // Class used to determine whether a creature is blinded (typically by // the smoke from a flaming attack), and if so, for how long. class BlindedCalculator : public StatusEffectCalculator { public: int calculate_pct_chance_effect(CreaturePtr creature) const override; int calculate_duration_in_minutes(CreaturePtr creature) const override; protected: static const int BASE_BLINDED_DURATION_MEAN; static const int BASE_BLINDED_PCT_CHANCE; static const int BASE_BLINDED_CHANCE_HEALTH_MODIFIER; };
31.473684
75
0.795987
sidav
ff977a89d025b5e486659bc33b39ad4fd3cf31db
4,259
cpp
C++
hydra_api/SystemWin.cpp
Ray-Tracing-Systems/HydraAPI
17e812d5026b7d09df7e419658cf3a781162df55
[ "MIT" ]
18
2018-01-08T17:55:09.000Z
2021-08-02T11:22:30.000Z
hydra_api/SystemWin.cpp
Ray-Tracing-Systems/HydraAPI
17e812d5026b7d09df7e419658cf3a781162df55
[ "MIT" ]
null
null
null
hydra_api/SystemWin.cpp
Ray-Tracing-Systems/HydraAPI
17e812d5026b7d09df7e419658cf3a781162df55
[ "MIT" ]
6
2018-10-07T13:46:22.000Z
2019-07-04T09:13:14.000Z
#include "HydraAPI.h" #include "HydraInternal.h" #include <memory> #include <vector> #include <string> #include <sstream> #include <map> #ifdef WIN32 #include <direct.h> #else #endif int hr_mkdir(const char* a_folder) { return _mkdir(a_folder); } int hr_mkdir(const wchar_t* a_folder) { return _wmkdir(a_folder); } int hr_cleardir(const char* a_folder) { std::string tempFolder = std::string(a_folder) + "/"; std::string tempName = tempFolder + "*"; WIN32_FIND_DATAA fd; HANDLE hFind = ::FindFirstFileA(tempName.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { std::string tempName2 = tempFolder + fd.cFileName; DeleteFileA(tempName2.c_str()); } while (::FindNextFileA(hFind, &fd)); ::FindClose(hFind); } return 0; } int hr_cleardir(const wchar_t* a_folder) { std::wstring tempFolder = std::wstring(a_folder) + L"/"; std::wstring tempName = tempFolder + L"*"; WIN32_FIND_DATAW fd; HANDLE hFind = ::FindFirstFileW(tempName.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { std::wstring tempName2 = tempFolder + fd.cFileName; DeleteFileW(tempName2.c_str()); } while (::FindNextFileW(hFind, &fd)); ::FindClose(hFind); } return 0; } std::vector<std::wstring> hr_listfiles(const wchar_t* a_folder, bool excludeFolders) { std::vector<std::wstring> result; std::wstring tempFolder = std::wstring(a_folder) + L"/"; std::wstring tempName = tempFolder + L"*"; WIN32_FIND_DATAW fd; HANDLE hFind = ::FindFirstFileW(tempName.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { std::wstring tempName2 = tempFolder + fd.cFileName; result.push_back(tempName2); } while (::FindNextFileW(hFind, &fd)); ::FindClose(hFind); } return result; } std::vector<std::string> hr_listfiles(const char* a_folder, bool excludeFolders) { std::vector<std::string> result; std::string tempFolder = std::string(a_folder) + "/"; std::string tempName = tempFolder + "*"; WIN32_FIND_DATAA fd; HANDLE hFind = ::FindFirstFileA(tempName.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { do { std::string tempName2 = tempFolder + fd.cFileName; result.push_back(tempName2); } while (::FindNextFileA(hFind, &fd)); ::FindClose(hFind); } return result; } void hr_copy_file(const char* a_file1, const char* a_file2) { CopyFileA(a_file1, a_file2, FALSE); } void hr_copy_file(const wchar_t* a_file1, const wchar_t* a_file2) { CopyFileW(a_file1, a_file2, FALSE); } void hr_deletefile(const wchar_t* a_file) { DeleteFileW(a_file); } void hr_deletefile(const char* a_file) { DeleteFileA(a_file); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct HRSystemMutex { HANDLE mutex; std::string name; bool owner; }; HRSystemMutex* hr_create_system_mutex(const char* a_mutexName) { HRSystemMutex* a_mutex = new HRSystemMutex; a_mutex->mutex = OpenMutexA(MUTEX_ALL_ACCESS, FALSE, a_mutexName); if (a_mutex->mutex == NULL || a_mutex->mutex == INVALID_HANDLE_VALUE) a_mutex->mutex = CreateMutexA(NULL, FALSE, a_mutexName); return a_mutex; } void hr_free_system_mutex(HRSystemMutex*& a_mutex) // logic of this function is not strictly correct, but its ok for our usage case. { if(a_mutex == nullptr) return; if (a_mutex->mutex != INVALID_HANDLE_VALUE && a_mutex->mutex != NULL) { CloseHandle(a_mutex->mutex); a_mutex->mutex = NULL; } delete a_mutex; a_mutex = nullptr; } bool hr_lock_system_mutex(HRSystemMutex* a_mutex, int a_msToWait) { if (a_mutex == nullptr) return false; const DWORD res = WaitForSingleObject(a_mutex->mutex, a_msToWait); if (res == WAIT_TIMEOUT || res == WAIT_FAILED) return false; else return true; } void hr_unlock_system_mutex(HRSystemMutex* a_mutex) { if (a_mutex == nullptr) return; ReleaseMutex(a_mutex->mutex); } #include <fstream> void hr_ifstream_open(std::ifstream& a_stream, const wchar_t* a_fileName) { a_stream.open(a_fileName, std::ios::binary); } void hr_ofstream_open(std::ofstream& a_stream, const wchar_t* a_fileName) { a_stream.open(a_fileName, std::ios::binary); }
20.980296
132
0.666354
Ray-Tracing-Systems
ff994351a95e16eeab1981dfe1b9a1d1431d0686
2,140
cpp
C++
dev/velocities_sidecar/generate_velocities_sidecar_main.cpp
nyue/SegmentedInterpolativeMotionBlurAlembic
1f02ff5516b6e114410b5977885133bb4b5bb490
[ "Apache-2.0" ]
1
2020-12-28T23:33:00.000Z
2020-12-28T23:33:00.000Z
dev/velocities_sidecar/generate_velocities_sidecar_main.cpp
nyue/SegmentedInterpolativeMotionBlurAlembic
1f02ff5516b6e114410b5977885133bb4b5bb490
[ "Apache-2.0" ]
null
null
null
dev/velocities_sidecar/generate_velocities_sidecar_main.cpp
nyue/SegmentedInterpolativeMotionBlurAlembic
1f02ff5516b6e114410b5977885133bb4b5bb490
[ "Apache-2.0" ]
1
2018-10-10T11:49:02.000Z
2018-10-10T11:49:02.000Z
#include <Alembic/Util/All.h> #include <Alembic/AbcCoreAbstract/All.h> #include <Alembic/AbcCoreOgawa/All.h> #ifdef SIMBA_ENABLE_ALEMBIC_HDF5 #include <Alembic/AbcCoreHDF5/All.h> #endif // SIMBA_ENABLE_ALEMBIC_HDF5 #include <Alembic/Abc/All.h> #include <Alembic/AbcCoreFactory/All.h> #include <Alembic/AbcGeom/All.h> #include <Alembic/AbcCollection/All.h> #include <Alembic/AbcMaterial/All.h> #include <vector> #include <boost/format.hpp> #include <boost/program_options.hpp> #include <OpenEXR/ImathVec.h> #include "VelocitySideCar.h" namespace po = boost::program_options; Alembic::AbcGeom::OXform addXform(Alembic::Abc::OObject parent, std::string name) { Alembic::AbcGeom::OXform xform(parent, name.c_str()); return xform; } void write_velocities_sidecar(const std::string& i_filename, const VelocitySideCar& i_vsc) { Alembic::Abc::OArchive archive(Alembic::Abc::CreateArchiveWithInfo(Alembic::AbcCoreHDF5::WriteArchive(), std::string(i_filename.c_str()), std::string("Procedural Insight"), std::string("SIMBA Velocity Sidecar"), Alembic::Abc::ErrorHandler::kThrowPolicy)); Alembic::AbcGeom::OXform xform = addXform(archive.getTop(),"Xform"); } int main(int argc, char** argv) { try { std::string alembic_file; std::string velocity_file; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("abc", po::value<std::string>(&alembic_file), "name of alembic file") ("vsc", po::value<std::string>(&velocity_file), "name of velocity file") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help") || alembic_file.empty() || velocity_file.empty()) { std::cout << desc << "\n"; return 1; } // std::string sha; // get_sha(alembic_file, sha); // std::cout << boost::format("sha = '%1%'") % sha << std::endl; VelocitySideCar vsc; vsc.compute(alembic_file); } catch(std::exception& e) { std::cerr << "error: " << e.what() << "\n"; return 1; } catch(...) { std::cerr << "Exception of unknown type!\n"; } return 0; }
26.097561
105
0.683645
nyue
ff9e8a84e79f46e7e4016ee7940334ea11585f37
10,107
cpp
C++
Alien Engine/Alien Engine/ComponentPhysics.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
7
2020-02-20T15:11:11.000Z
2020-05-19T00:29:04.000Z
Alien Engine/Alien Engine/ComponentPhysics.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
125
2020-02-29T17:17:31.000Z
2020-05-06T19:50:01.000Z
Alien Engine/Alien Engine/ComponentPhysics.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
1
2020-05-19T00:29:06.000Z
2020-05-19T00:29:06.000Z
#include "Application.h" #include "ComponentCharacterController.h" #include "ComponentTransform.h" #include "ComponentPhysics.h" #include "ComponentCollider.h" #include "ComponentRigidBody.h" #include "ComponentScript.h" #include "ImGuizmos/ImGuizmo.h" #include "CollisionLayers.h" #include "GameObject.h" #include "Alien.h" #include "Event.h" #include "Time.h" #include "RandomHelper.h" ComponentPhysics::ComponentPhysics(GameObject* go) : Component(go) { this->go = go; serialize = false; // Not save & load ID = (PxU32)Random::GetRandom32ID(); transform = go->GetComponent<ComponentTransform>(); state = PhysicState::DISABLED; layers = &App->physx->layers; scale = GetValidPhysicScale(); std::vector<ComponentScript*> found_script = go->GetComponents<ComponentScript>(); for (ComponentScript* script : found_script) if (script->need_alien == true) scripts.push_back(script); } ComponentPhysics::~ComponentPhysics() { if (actor) // Dettach and Delete Actor { PxU32 num_shapes = actor->getNbShapes(); PxShape* shapes[10]; actor->getShapes(shapes, num_shapes); for (PxU32 i = 0; i < num_shapes; ++i) actor->detachShape(*shapes[i]); App->physx->RemoveBody(actor); actor = nullptr; } rigid_body = nullptr; } ComponentRigidBody* ComponentPhysics::GetRigidBody() { return (rigid_body && IsDynamic()) ? rigid_body : nullptr; } void ComponentPhysics::OnEnable() { if (CheckChangeState()) UpdateBody(); } void ComponentPhysics::OnDisable() { if (CheckChangeState()) UpdateBody(); } void ComponentPhysics::Update() { GizmoManipulation(); // Check if gizmo is selected UpdatePositioning(); // Move body or gameobject } void ComponentPhysics::PostUpdate() { float3 current_scale = GetValidPhysicScale(); if (!scale.Equals(current_scale)) { scale = current_scale; go->SendAlientEventThis(this, AlienEventType::PHYSICS_SCALE_CHANGED); } } void ComponentPhysics::HandleAlienEvent(const AlienEvent& e) { switch (e.type) { case AlienEventType::SCRIPT_ADDED: { ComponentScript* script = (ComponentScript*)e.object; if (script->game_object_attached == game_object_attached && script->need_alien == true) scripts.push_back(script); break; } case AlienEventType::SCRIPT_DELETED: { ComponentScript* script = (ComponentScript*)e.object; if (script->game_object_attached == game_object_attached && script->need_alien == true) scripts.remove(script); break; } case AlienEventType::COLLIDER_DELETED: { ComponentCollider* object = (ComponentCollider*)e.object; RemoveCollider(object); break; } case AlienEventType::RIGIDBODY_DELETED: { ComponentRigidBody* object = (ComponentRigidBody*)e.object; RemoveRigidBody(object); break; } case AlienEventType::CHARACTER_CTRL_DELETED: { ComponentCharacterController* object = (ComponentCharacterController*)e.object; RemoveController(object); break; } } } bool ComponentPhysics::AddRigidBody(ComponentRigidBody* rb) { if (CheckRigidBody(rb)) { rigid_body = rb; if (CheckChangeState()) UpdateBody(); return true; } return true; } bool ComponentPhysics::RemoveRigidBody(ComponentRigidBody* rb) { if (rb == rigid_body) { rigid_body = nullptr; if (CheckChangeState()) UpdateBody(); return true; } return true; } void ComponentPhysics::SwitchedRigidBody(ComponentRigidBody* rb) { if (rb == rigid_body) if (CheckChangeState()) UpdateBody(); } void ComponentPhysics::AttachCollider(ComponentCollider* collider, bool only_update) { bool do_attach = false; if (!only_update && CheckCollider(collider) && collider->IsEnabled()) { if (CheckChangeState()) UpdateBody(); else do_attach = true; } if (actor && (do_attach || only_update)) { if (!ShapeAttached(collider->shape)) actor->attachShape(*collider->shape); WakeUp(); } } void ComponentPhysics::DettachCollider(ComponentCollider* collider, bool only_update) { bool do_dettach = false; if (!only_update && CheckCollider(collider) && !collider->IsEnabled()) { if (CheckChangeState()) UpdateBody(); else do_dettach = true; } if (actor && (do_dettach || only_update)) { if (ShapeAttached(collider->shape)) actor->detachShape(*collider->shape); WakeUp(); } } // Add Collider from Phisic System bool ComponentPhysics::AddCollider(ComponentCollider* collider) { if (CheckCollider(collider)) { if (!FindCollider(collider)) // Add Collider if is not found colliders.push_back(collider); if (CheckChangeState()) // Check if added collider change state UpdateBody(); else // Else only attach { AttachCollider(collider, true); } return true; } return false; } // Remove Collider from Phisic System bool ComponentPhysics::RemoveCollider(ComponentCollider* collider) { if (FindCollider(collider)) { colliders.remove(collider); if (CheckChangeState()) UpdateBody(); else { DettachCollider(collider, true); } return true; } return false; } bool ComponentPhysics::FindCollider(ComponentCollider* collider) { return (std::find(colliders.begin(), colliders.end(), collider) != colliders.end()); } bool ComponentPhysics::CheckCollider(ComponentCollider* collider) { return (collider != nullptr && collider->game_object_attached == game_object_attached); } bool ComponentPhysics::CheckRigidBody(ComponentRigidBody* rb) { return (rb != nullptr && rb->game_object_attached == game_object_attached); } // Controller Logic ------------------------------- bool ComponentPhysics::AddController(ComponentCharacterController* ctrl) { if (CheckController(ctrl)) // TODO: review this { character_ctrl = ctrl; return true; } return false; } bool ComponentPhysics::RemoveController(ComponentCharacterController* ctrl) { if (ctrl == character_ctrl) // TODO: review this { character_ctrl = nullptr; if (CheckChangeState()) UpdateBody(); return true; } return false; } bool ComponentPhysics::CheckController(ComponentCharacterController* ctrl) { return (ctrl != nullptr && ctrl->game_object_attached == game_object_attached); } bool ComponentPhysics::CheckChangeState() { if ( !character_ctrl && !rigid_body && colliders.empty()) { // Delete if not has physic components Destroy(); state = PhysicState::DISABLED; return true; } PhysicState new_state = PhysicState::DISABLED; if (!go->IsEnabled()) { new_state = PhysicState::DISABLED; } else if (rigid_body /*&& rigid_body->IsEnabled()*/) { new_state = PhysicState::DYNAMIC; } else if (HasEnabledColliders()) { new_state = PhysicState::STATIC; } if (new_state != state) { // If state is different state = new_state; return true; } return false; } void ComponentPhysics::UpdateBody() { if (actor) // Dettach and Delete Actor { PxU32 num_shapes = actor->getNbShapes(); PxShape* shapes[10]; // Buffer Shapes actor->getShapes(shapes, num_shapes); for (PxU32 i = 0; i < num_shapes; ++i) actor->detachShape(*shapes[i]); App->physx->RemoveBody(actor); actor = nullptr; } if (state == PhysicState::STATIC || state == PhysicState::DYNAMIC) { actor = App->physx->CreateBody(transform->GetGlobalMatrix(), IsDynamic()); if (actor == nullptr) { LOG_ENGINE("PhyX Rigid Actor Created at Infinite Transform (Scale x,y,z = 0 ? )"); state == PhysicState::INVALID_TRANS; return; } for (ComponentCollider* collider : colliders) if (collider->enabled && collider->shape) // TODO: check this actor->attachShape(*collider->shape); if (IsDynamic()) rigid_body->SetBodyProperties(); } } float3 ComponentPhysics::GetValidPhysicScale() { float3 scale = transform->GetGlobalScale(); for (int i = 0; i < 3; ++i) if (scale[i] == 0.f) scale[i] = 0.01f; return scale; } void ComponentPhysics::GizmoManipulation() { bool is_using_gizmo = ImGuizmo::IsUsing() && game_object_attached->IsSelected(); if (gizmo_selected) { if (!is_using_gizmo) { WakeUp(); gizmo_selected = false; } else PutToSleep(); } else if (is_using_gizmo) gizmo_selected = true; } void ComponentPhysics::UpdateActorTransform() { PxTransform trans; if (!F4X4_TO_PXTRANS(transform->GetGlobalMatrix(), trans)) { LOG_ENGINE("Error! GameObject %s transform is NaN or Infinite -> Physics Can't be updated "); return; } actor->setGlobalPose(trans); } void ComponentPhysics::UpdatePositioning() { if (IsDisabled()) return; if (character_ctrl && character_ctrl->IsEnabled()) { UpdateActorTransform(); PutToSleep(); return; } if ( !Time::IsPlaying() || gizmo_selected) { UpdateActorTransform(); } else { if (IsDynamic()) { PxTransform trans = actor->getGlobalPose(); // Get Controller Position transform->SetGlobalPosition(PXVEC3_TO_F3(trans.p)); transform->SetGlobalRotation(PXQUAT_TO_QUAT(trans.q)); } else { PxTransform trans; if (!F4X4_TO_PXTRANS(transform->GetGlobalMatrix(), trans)) { LOG_ENGINE("Error! GameObject %s transform is NaN or Infinite -> Physics Can't be updated "); return; } actor->setGlobalPose(trans); } } } void ComponentPhysics::WakeUp() { if (IsDynamic() && !IsKinematic()) actor->is<PxRigidDynamic>()->wakeUp(); } void ComponentPhysics::PutToSleep() { if (IsDynamic() && !IsKinematic()) actor->is<PxRigidDynamic>()->putToSleep(); } void ComponentPhysics::ChangedFilters() { if (IsDisabled()) return; //App->physx->px_scene->resetFiltering(*actor); } bool ComponentPhysics::HasEnabledColliders() { for (ComponentCollider* collider : colliders) if (collider->enabled) return true; return false; } bool ComponentPhysics::ShapeAttached(PxShape* shape) { bool ret = false; PxU32 num_shapes = actor->getNbShapes(); PxShape* shapes[10]; // Buffer Shapes actor->getShapes(shapes, num_shapes); for (PxU32 i = 0; i < num_shapes; i++) if (shapes[i] == shape) { ret = true; break; } return ret; } bool ComponentPhysics::IsDynamic() { return state == PhysicState::DYNAMIC; } bool ComponentPhysics::IsKinematic() { return state == PhysicState::DYNAMIC && rigid_body->is_kinematic; } bool ComponentPhysics::IsDisabled() { return state == PhysicState::DISABLED; }
22.661435
106
0.708519
OverPowered-Team
ff9eabb1f38c0c1d8b78ac9284894dbaabf43a6c
710
cpp
C++
gamelib/src/engine/GameTimer.cpp
alexBraidwood/my_first_game_engine
7a2d87fdef841e633ca40eae38536fd7d2b70032
[ "Zlib", "MIT" ]
null
null
null
gamelib/src/engine/GameTimer.cpp
alexBraidwood/my_first_game_engine
7a2d87fdef841e633ca40eae38536fd7d2b70032
[ "Zlib", "MIT" ]
null
null
null
gamelib/src/engine/GameTimer.cpp
alexBraidwood/my_first_game_engine
7a2d87fdef841e633ca40eae38536fd7d2b70032
[ "Zlib", "MIT" ]
null
null
null
// // Created by alex on 12/12/15. // #include <GameTimer.h> #include <chrono> using namespace engine::sdl2; using namespace std::chrono; auto Game_timer::start() -> void { is_running = true; start_time = high_resolution_clock::now(); last_dt = start_time; } auto Game_timer::stop() -> void { is_running = false; stop_time = start_time; start_time = timestamp(); } auto Game_timer::delta_time() -> float { auto current_dt = high_resolution_clock::now(); auto diff = duration_cast<nanoseconds>(current_dt - last_dt); last_dt = current_dt; float dt = diff.count() / 1000000000.f; return dt; } auto Game_timer::stopped() const -> bool { return !is_running; };
19.189189
65
0.669014
alexBraidwood
ff9f68afc3080fac603b390fbce70d02ad9b62ec
1,455
cpp
C++
qt5/group.cpp
kristjanbb/libui
e381e6b45fc421daeea6f1ed5c29a84aad13271b
[ "MIT" ]
3
2016-07-12T12:06:15.000Z
2021-05-24T22:06:45.000Z
qt5/group.cpp
kristjanbb/libui
e381e6b45fc421daeea6f1ed5c29a84aad13271b
[ "MIT" ]
null
null
null
qt5/group.cpp
kristjanbb/libui
e381e6b45fc421daeea6f1ed5c29a84aad13271b
[ "MIT" ]
null
null
null
#include "uipriv_qt5.hpp" #include <QGroupBox> #include <QVBoxLayout> struct uiGroup : public uiQt5Control {}; char *uiGroupTitle(uiGroup *g) { if (auto groupBox = uiValidateAndCastObjTo<QGroupBox>(g)) { return uiQt5StrdupQString(groupBox->title()); } return nullptr; } void uiGroupSetTitle(uiGroup *g, const char *text) { if (auto groupBox = uiValidateAndCastObjTo<QGroupBox>(g)) { groupBox->setTitle(QString::fromUtf8(text)); } } void uiGroupSetChild(uiGroup *g, uiControl *child) { if (auto groupBox = uiValidateAndCastObjTo<QGroupBox>(g)) { auto obj = uiValidateAndCastObjTo<QObject>(child); if (groupBox->layout()) { groupBox->layout()->deleteLater(); } if (auto layout = qobject_cast<QLayout*>(obj)) { groupBox->setLayout(layout); } else if (auto widget = qobject_cast<QWidget*>(obj)) { auto layout = new QVBoxLayout; layout->setMargin(0); // ? layout->addWidget(widget); groupBox->setLayout(layout); } else { qWarning("object is neither layout nor widget"); } } } int uiGroupMargined(uiGroup *g) { qWarning("TODO: %p", (void*)g); return 0; } void uiGroupSetMargined(uiGroup *g, int margined) { qWarning("TODO: %p, %d", (void*)g, margined); } uiGroup *uiNewGroup(const char *text) { auto groupBox = new QGroupBox(QString::fromUtf8(text)); // note styling is being set in main.cpp -> styleSheet return uiAllocQt5ControlType(uiGroup,groupBox,uiQt5Control::DeleteControlOnQObjectFree); }
22.734375
89
0.706529
kristjanbb
ffa088e80959e36dea0fc2b365cb86413e4f88fa
1,866
cpp
C++
HDP_HSMM/internals/cpp_eigen_code/hsmm_intnegbinvariant_sample_forwards.cpp
GUZHIXIANG/DAA_taguchi
5c77f0a326b53e0cc908cf08714fd470870877ec
[ "MIT" ]
null
null
null
HDP_HSMM/internals/cpp_eigen_code/hsmm_intnegbinvariant_sample_forwards.cpp
GUZHIXIANG/DAA_taguchi
5c77f0a326b53e0cc908cf08714fd470870877ec
[ "MIT" ]
null
null
null
HDP_HSMM/internals/cpp_eigen_code/hsmm_intnegbinvariant_sample_forwards.cpp
GUZHIXIANG/DAA_taguchi
5c77f0a326b53e0cc908cf08714fd470870877ec
[ "MIT" ]
null
null
null
using namespace Eigen; using namespace std; // inputs Map<ArrayXXd> eAT(A,M,M); Map<ArrayXXd> eaBl(aBl,M,T); Map<ArrayXXd> ebetal(betal,rtot,T); Map<ArrayXXd> esuperbetal(superbetal,M,T); // locals int t, state, substate, end; double total, pi; ArrayXd logdomain(M); ArrayXd nextstate_unsmoothed(M); ArrayXd nextstate_distr(M); ArrayXd pair(2); // code! // sample first state // logdomain = esuperbetal.col(0) + eaBl.col(0); // nextstate_distr = (logdomain - logdomain.maxCoeff()).exp() * epi0; // total = nextstate_distr.sum() * (((double)random())/((double)RAND_MAX)); // for (state=0; (total -= nextstate_distr(state)) > 0; state++) ; // stateseq[0] = state; t = 0; state = initial_superstate; substate = initial_substate; pi = ps[state]; end = end_indices[state]; while (t < T) { // loop inside the substates while ((substate < end) && (t < T)) { pair = eaBl(state,t) + ebetal.col(t).segment(substate,2); pair = (pair - pair.maxCoeff()).exp(); total = (1.0-pi)*pair(1) / ((1.0-pi)*pair(1) + pi*pair(0)); substate += (((double)random())/((double)RAND_MAX)) < total; stateseq[t] = state; t += 1; } // sample the 'end' row just like a regular HMM transition nextstate_unsmoothed = eAT.col(state); int current_state = state; while ((state == current_state) && (t < T)) { logdomain = esuperbetal.col(t) + eaBl.col(t); logdomain(state) = ebetal(end,t) + eaBl(state,t); nextstate_distr = (logdomain - logdomain.maxCoeff()).exp() * nextstate_unsmoothed; total = nextstate_distr.sum() * (((double)random())/((double)RAND_MAX)); for (state=0; (total -= nextstate_distr(state)) > 0; state++) ; stateseq[t] = current_state; t += 1; } substate = start_indices[state]; end = end_indices[state]; pi = ps[state]; }
27.441176
90
0.617363
GUZHIXIANG
ffa0e449b12fb8dae6e7a8384dce1979e101047f
1,323
cpp
C++
util/image_loader.cpp
Seviel/rinvid
0b8fbb1c0a6a5180acd9846cbf953126c05756a4
[ "BSD-2-Clause" ]
1
2020-12-31T13:36:56.000Z
2020-12-31T13:36:56.000Z
util/image_loader.cpp
Seviel/rinvid
0b8fbb1c0a6a5180acd9846cbf953126c05756a4
[ "BSD-2-Clause" ]
3
2020-11-12T21:37:03.000Z
2021-03-28T13:07:40.000Z
util/image_loader.cpp
Seviel/rinvid
0b8fbb1c0a6a5180acd9846cbf953126c05756a4
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************** * Copyright (c) 2021, Filip Vasiljevic * All rights reserved. * * This file is subject to the terms and conditions of the BSD 2-Clause * License. See the file LICENSE in the root directory of the Rinvid * repository for more details. **********************************************************************/ #include <cstdint> #include <iostream> #include <string> #include <vector> #include "extern/include/stb_image.h" #include "util/include/error_handler.h" #include "util/include/image_loader.h" namespace rinvid { bool load_image(const char* file_name, std::vector<std::uint8_t>& image_data, std::int32_t& width, std::int32_t& height) { std::int32_t number_of_channels; std::uint8_t* data = stbi_load(file_name, &width, &height, &number_of_channels, STBI_rgb_alpha); if (data == NULL) { std::string error_description = "STBI: Image loading failed because: "; error_description += stbi_failure_reason(); rinvid::errors::put_error_to_log(error_description); return false; } for (std::int32_t i{0}; i < width * height * STBI_rgb_alpha; ++i) { image_data.push_back(data[i]); } stbi_image_free(data); return true; } } // namespace rinvid
27
100
0.606954
Seviel
ffa0fc1c564a22420d9afd4f97803aa000ce9171
298
cpp
C++
src/parameters.cpp
antoinewdg/inpainting-detection
24c758e3fc1e15563e134137a64ec4fc51930f3a
[ "MIT" ]
4
2019-09-17T03:17:39.000Z
2022-02-15T01:30:13.000Z
src/parameters.cpp
antoinewdg/inpainting-detection
24c758e3fc1e15563e134137a64ec4fc51930f3a
[ "MIT" ]
null
null
null
src/parameters.cpp
antoinewdg/inpainting-detection
24c758e3fc1e15563e134137a64ec4fc51930f3a
[ "MIT" ]
2
2016-12-13T05:26:51.000Z
2021-02-10T07:22:11.000Z
#include "parameters.h" const float A_MIN = 100; const float A_HUGE = 500; const float ALPHA = 1.3f; const float R_MIN = 5.f; const int N_DOMINANT = 20; const bool SAVE_PATCH_MATCH = false; const int MIN_PATCH_OFFSET = 20; const int RELEVANT_OFFSET_NORM = 25; const float VARIANCE_THRESHOLD = 2.f;
27.090909
37
0.758389
antoinewdg
ffa25e8758d5c9b5e23f5a4e89d10d8ead8cebca
711
cpp
C++
app/text/j.cpp
Na6ezh6a/rymanceva-testings-lab2
ce2433d3cdd2946fcc38730b5d9a7cfa721425f2
[ "MIT" ]
null
null
null
app/text/j.cpp
Na6ezh6a/rymanceva-testings-lab2
ce2433d3cdd2946fcc38730b5d9a7cfa721425f2
[ "MIT" ]
null
null
null
app/text/j.cpp
Na6ezh6a/rymanceva-testings-lab2
ce2433d3cdd2946fcc38730b5d9a7cfa721425f2
[ "MIT" ]
null
null
null
#include "_text.h" int j(text txt) { std::list<std::string>::iterator cursor_line = txt->cursor->line; std::list<std::string>::iterator cursor_next = txt->cursor->line; cursor_next++; /* Проверка на последнюю строку */ if (cursor_next == txt->lines->end()) { printf ("Невозможно. Текущая строка последняя\n"); return -1; } // /* Присоединяем следующую строку */ // strcat(cursor_line->contents, cursor_next->contents); if (cursor_next != txt->lines->end()) { /*Запоминаем указатель на следующую строку для последующего очищения */ *cursor_line += *cursor_next; txt->lines->erase(cursor_next); } return 0; }
23.7
79
0.609001
Na6ezh6a
ffa3ee71529be322cc74d9c80026c6f88988a012
901
hpp
C++
cpp/RoverBot/Localizer/include/Localizer.hpp
bo-rc/Rover
0a82ae2fd6583cb526543ff2af9810f221e18698
[ "MIT" ]
null
null
null
cpp/RoverBot/Localizer/include/Localizer.hpp
bo-rc/Rover
0a82ae2fd6583cb526543ff2af9810f221e18698
[ "MIT" ]
null
null
null
cpp/RoverBot/Localizer/include/Localizer.hpp
bo-rc/Rover
0a82ae2fd6583cb526543ff2af9810f221e18698
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <librealsense2/rs.hpp> #include <iostream> #include <memory> #include "Types.hpp" #include "NavPose2d_Pub.hpp" #include "Position3d_Pub.hpp" #include "Velocity3d_Pub.hpp" class Localizer { public: Localizer(); ~Localizer(); // TODO: refactor as virtual sensor interface void step(); private: void setNavPose2d(NavPose2d& gNavPose) const; void setPose3d(Position3d& pose) const; void setVel3d(Velocity3d& vel) const; void setState3d(NavPose2d& gNavPose, VehicleState& gState) const; // not used std::unique_ptr<rs2::pipeline> m_pipe = nullptr; rs2_pose m_pose = {0}; NavPose2d_Pub::NavPose2d_Pub m_NavPose2d_PubNode; Position3d_Pub::Position3d_Pub m_Position3d_PubNode; Velocity3d_Pub::Velocity3d_Pub m_Velocity3d_PubNode; };
26.5
85
0.673696
bo-rc
ffa4df1e653c3200b5ca0febd08e1496988c1e7d
478
hpp
C++
include/Input/Actuator.hpp
InDieTasten/IDT.EXP
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
null
null
null
include/Input/Actuator.hpp
InDieTasten/IDT.EXP
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
56
2015-04-04T00:09:38.000Z
2015-08-02T23:39:13.000Z
include/Input/Actuator.hpp
InDieTasten-Legacy/--EXP-old-
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
1
2015-05-08T19:23:51.000Z
2015-05-08T19:23:51.000Z
#ifndef _Actuator_hpp_ #define _Actuator_hpp_ #include <Utilities\Logger.hpp> #include <Utilities\Conversion.hpp> class Actuator { protected: sf::Mutex confmtx; private: virtual float getRawVector() = 0; float multiplier; float adjustment; public: Actuator(); ~Actuator(); float getControlVector(); void setMultiplier(float); void setAdjustment(float); float getMultiplier(); float getAdjustment(); }; #endif // !_Actuator_hpp_
15.419355
36
0.698745
InDieTasten
ffa8cd86cca52a7c40d86c0ae13cb3551512e426
498
cpp
C++
src/luogu/P1055/9547070_ac_100_0ms_1667k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/P1055/9547070_ac_100_0ms_1667k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/P1055/9547070_ac_100_0ms_1667k_noO2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
#include<cstdio> using namespace std; int main(){ char a[13]; int n,b[13]; for (int i=0;i<13;i++){ a[i]=getchar(); } for (int i=0;i<13;i++){ b[i]=a[i]-48; } n=(b[0]*1+b[2]*2+b[3]*3+b[4]*4+b[6]*5+b[7]*6+b[8]*7+b[9]*8+b[10]*9)%11; if (n==10){ if (a[12]=='X') printf("Right"); else { for (int i=0;i<12;i++) printf("%c",a[i]); printf("X"); } } else { if (b[12]==n) printf("Right"); else { for (int i=0;i<12;i++) printf("%c",a[i]); printf("%d",n); } } return 0; }
17.785714
72
0.473896
lnkkerst
ffaf0c5b42e75c192e2d820737f4a0432e602b9f
2,297
cpp
C++
Graphs/FordFulkerson.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
687
2015-02-23T17:31:00.000Z
2022-03-27T02:57:23.000Z
Graphs/FordFulkerson.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
9
2018-08-27T06:41:24.000Z
2020-12-17T13:39:07.000Z
Graphs/FordFulkerson.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
253
2015-03-16T00:42:18.000Z
2022-03-23T06:01:36.000Z
/******************************************************************************** MaxFlow Ford-Fulkerson algorithm. O(M|f|), |f| - maxflow value Based on problem 2783 from informatics.mccme.ru http://informatics.mccme.ru/mod/statements/view3.php?chapterid=2783#1 ********************************************************************************/ #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <cstdlib> #include <cstdio> #include <string> #include <cstring> #include <cassert> #include <utility> #include <iomanip> using namespace std; const int MAXN = 1050; const int INF = (int) 1e9; struct edge { int from, to, f, cap; }; int n, m; vector <edge> e; vector <int> g[MAXN]; bool used[MAXN]; int s, t; int ans; void addEdge(int from, int to, int cap) { edge ed; ed.from = from; ed.to = to; ed.f = 0; ed.cap = cap; e.push_back(ed); g[from].push_back((int) e.size() - 1); ed.from = to; ed.to = from; ed.f = cap; ed.cap = cap; e.push_back(ed); g[to].push_back((int) e.size() - 1); } int pushFlow(int v, int flow = INF) { used[v] = true; if (v == t) return flow; for (int i = 0; i < (int) g[v].size(); i++) { int ind = g[v][i]; int to = e[ind].to; int f = e[ind].f; int cap = e[ind].cap; if (used[to] || cap - f == 0) continue; int pushed = pushFlow(to, min(flow, cap - f)); if (pushed > 0) { e[ind].f += pushed; e[ind ^ 1].f -= pushed; return pushed; } } return 0; } int main() { //assert(freopen("input.txt","r",stdin)); //assert(freopen("output.txt","w",stdout)); scanf("%d %d", &n, &m); s = 1; t = n; for (int i = 1; i <= m; i++) { int from, to, cap; scanf("%d %d %d", &from, &to, &cap); addEdge(from, to, cap); } while (true) { memset(used, 0, sizeof(used)); int add = pushFlow(s); if (add == 0) break; ans += add; } printf("%d\n", ans); return 0; }
21.87619
82
0.462342
mayukhsen1301
ffafe770a92b6aec62c6a1ba2819fb2ff5a60d78
936
cpp
C++
src/ArgParser.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
src/ArgParser.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
src/ArgParser.cpp
canzarlab/fortuna
62109f879a640d7154bda66ee21d9396c0d637ea
[ "BSD-2-Clause" ]
null
null
null
#include <map> #include <string> #include <iostream> typedef std::map<std::string, std::string>::const_iterator it_type; class ArgParser { public: ArgParser(const int argc, char* const argv[]) { for (int i = 0; i < argc; i++) { std::string str = argv[i]; if (str[0] != '-') continue; if (str[1] == '-') index[str.substr(2, str.length() - 2)] = " "; else if (i < argc - 1) index[str.substr(1, str.length() - 1)] = argv[++i]; } } std::string operator()(const std::string key) { if (exists(key)) return index[key]; return ""; } bool exists(const std::string key) { return index.count(key); } private: std::map<std::string, std::string> index; friend std::ostream& operator<<(std::ostream& os, const ArgParser& ap) { for(auto& it : ap.index) { os << it.first << " " << it.second << std::endl; } return os; } ArgParser() { } };
17.333333
71
0.553419
canzarlab
ffb35e1631da0109c21f6dc0a8b638156b33cd3c
4,631
cc
C++
sling/task/dashboard.cc
anysql/sling
d521b27f1537608ddf3d8b4281edd585ffd90545
[ "Apache-2.0" ]
97
2020-03-11T07:44:05.000Z
2022-03-27T14:24:15.000Z
sling/task/dashboard.cc
anysql/sling
d521b27f1537608ddf3d8b4281edd585ffd90545
[ "Apache-2.0" ]
11
2020-10-23T09:26:26.000Z
2021-08-25T09:31:28.000Z
sling/task/dashboard.cc
anysql/sling
d521b27f1537608ddf3d8b4281edd585ffd90545
[ "Apache-2.0" ]
8
2018-06-11T07:59:18.000Z
2021-06-09T09:19:05.000Z
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "sling/task/dashboard.h" #include <time.h> #include <unistd.h> #include <sstream> #include "sling/base/perf.h" namespace sling { namespace task { Dashboard::Dashboard() { start_time_ = time(0); } Dashboard::~Dashboard() { for (auto *j : jobs_) delete j; } void Dashboard::Register(HTTPServer *http) { http->Register("/status", this, &Dashboard::HandleStatus); common_.Register(http); app_.Register(http); } string Dashboard::GetStatus() { MutexLock lock(&mu_); std::stringstream out; // Output current time and status. bool running = (status_ < FINAL); out << "{\"time\":" << (running ? time(0) : end_time_); out << ",\"started\":" << start_time_; out << ",\"finished\":" << (running ? 0 : 1); // Output jobs. out << ",\"jobs\":["; bool first_job = true; for (JobStatus *status : jobs_) { if (!first_job) out << ","; first_job = false; out << "{\"name\":\"" << status->name << "\""; out << ",\"started\":" << status->started; if (status->ended != 0) out << ",\"ended\":" << status->ended; if (status->job != nullptr) { // Output stages for running job. out << ",\"stages\":["; bool first_stage = true; for (Stage *stage : status->job->stages()) { if (!first_stage) out << ","; first_stage = false; out << "{\"tasks\":" << stage->num_tasks() << ",\"done\":" << stage->num_completed_tasks() << "}"; } out << "],"; // Output counters for running job. out << "\"counters\":{"; bool first_counter = true; status->job->IterateCounters( [&out, &first_counter](const string &name, Counter *counter) { if (!first_counter) out << ","; first_counter = false; out << "\"" << name << "\":" << counter->value(); } ); out << "}"; } else { // Output counters for completed job. out << ",\"counters\":{"; bool first_counter = true; for (auto &counter : status->counters) { if (!first_counter) out << ","; first_counter = false; out << "\"" << counter.first << "\":" << counter.second; } out << "}"; } out << "}"; } out << "]"; // Output resource usage. Perf perf; perf.Sample(); out << ",\"utime\":" << perf.utime(); out << ",\"stime\":" << perf.stime(); out << ",\"mem\":" << (running ? perf.memory() : Perf::peak_memory_usage()); out << ",\"ioread\":" << perf.ioread(); out << ",\"iowrite\":" << perf.iowrite(); out << ",\"flops\":" << perf.flops(); out << ",\"temperature\":" << (running ? perf.cputemp() : Perf::peak_cpu_temperature()); out << "}"; return out.str(); } void Dashboard::HandleStatus(HTTPRequest *request, HTTPResponse *response) { response->set_content_type("text/json; charset=utf-8"); response->Append(GetStatus()); if (status_ == IDLE) status_ = MONITORED; if (status_ == FINAL) status_ = SYNCHED; } void Dashboard::OnJobStart(Job *job) { MutexLock lock(&mu_); // Add job to job list. JobStatus *status = new JobStatus(job); jobs_.push_back(status); status->name = job->name(); status->started = time(0); active_jobs_[job] = status; } void Dashboard::OnJobDone(Job *job) { MutexLock lock(&mu_); // Get job status. JobStatus *status = active_jobs_[job]; CHECK(status != nullptr); // Record job completion time. status->ended = time(0); // Update final counter values. job->IterateCounters([status](const string &name, Counter *counter) { status->counters.emplace_back(name, counter->value()); }); // Remove job from active job list. active_jobs_.erase(job); status->job = nullptr; } void Dashboard::Finalize(int timeout) { if (status_ == MONITORED) { // Signal that all jobs are done. end_time_ = time(0); status_ = FINAL; // Wait until final status has been sent back. for (int wait = 0; wait < timeout && status_ != SYNCHED; ++wait) sleep(1); } status_ = TERMINAL; } } // namespace task } // namespace sling
27.730539
78
0.593392
anysql
ffbaf092363092b9cff8f77ac40cda9f51042fdb
877
cxx
C++
test/nick4.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
10
2018-03-26T07:41:44.000Z
2021-11-06T08:33:24.000Z
test/nick4.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
null
null
null
test/nick4.cxx
paulwratt/cin-5.34.00
036a8202f11a4a0e29ccb10d3c02f304584cda95
[ "MIT" ]
1
2020-11-17T03:17:00.000Z
2020-11-17T03:17:00.000Z
/* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch) * * For the licensing terms see the file COPYING * ************************************************************************/ #include <stdio.h> class A { int a; public: A() { a=123; } #ifdef DEST ~A() { printf("~A() %d\n",a); } #endif int get() {return a;} }; class B { A **ppa; public: B() { #ifndef DEST ppa = NULL; #endif } void test() { ppa = new A*[3]; for(int i=0;i<3;i++) { ppa[i] = new A[i+1]; } } void disp() { for(int i=0;i<3;i++) { for(int j=0;j<i+1;j++) printf("%d\n",ppa[i][j].get()); } } ~B() { for(int i=0;i<3;i++) { delete[] ppa[i]; } delete[] ppa; } }; int main() { B b; b.test(); b.disp(); return 0; }
15.945455
74
0.380844
paulwratt
ffbb5fbcfe6fc522126c653eb4e7752067d9ad0d
2,095
cpp
C++
source/bxdf/GlossySpecular.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
source/bxdf/GlossySpecular.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
source/bxdf/GlossySpecular.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
#include "raytracing/bxdf/GlossySpecular.h" #include "raytracing/utilities/ShadeRec.h" #include "raytracing/sampler/MultiJittered.h" namespace rt { GlossySpecular::GlossySpecular() : m_cs(1, 1, 1) { } // ----------------------------------------------------------------------------------- f // no sampling here: just use the Phong formula // this is used for direct illumination only // explained on page 284 RGBColor GlossySpecular::f(const ShadeRec& sr, const Vector3D& wo, const Vector3D& wi) const { RGBColor L; float ndotwi = static_cast<float>(sr.normal * wi); Vector3D r(-wi + 2.0f * sr.normal * ndotwi); // mirror reflection direction float rdotwo = static_cast<float>(r * wo); if (rdotwo > 0.0) L = m_ks * m_cs * pow(rdotwo, m_exp); return (L); } RGBColor GlossySpecular::rho(const ShadeRec& sr, const Vector3D& wo) const { return BLACK; } RGBColor GlossySpecular::sample_f(const ShadeRec& sr, const Vector3D& wo, Vector3D& wi, float& pdf) const { float ndotwo = static_cast<float>(sr.normal * wo); Vector3D r = -wo + 2.0f * sr.normal * ndotwo; // direction of mirror reflection Vector3D w = r; Vector3D u = Vector3D(0.00424, 1, 0.00764) ^ w; u.Normalize(); Vector3D v = u ^ w; Point3D sp = m_sampler->SampleHemisphere(); wi = sp.x * u + sp.y * v + sp.z * w; // reflected ray direction if (sr.normal * wi < 0.0) // reflected ray is below tangent plane wi = -sp.x * u - sp.y * v + sp.z * w; float phong_lobe = pow((float)(r * wi), (float)m_exp); pdf = static_cast<float>(phong_lobe * (sr.normal * wi)); return (m_ks * m_cs * phong_lobe); } void GlossySpecular::SetKs(float ks) { m_ks = ks; } void GlossySpecular::SetExp(float e) { m_exp = e; } void GlossySpecular::SetCs(const RGBColor& c) { m_cs = c; } void GlossySpecular::SetSamples(int num_samples, float exp) { m_sampler = std::make_shared<MultiJittered>(num_samples); m_sampler->MapSamplesToHemisphere(exp); } void GlossySpecular::SetSampler(const std::shared_ptr<Sampler>& sampler, float exp) { m_sampler = sampler; m_sampler->MapSamplesToHemisphere(exp); } }
24.940476
105
0.661098
xzrunner
ffbb82c0bec6acfa9413fab175657befae97f379
3,596
cpp
C++
debug/atomics/ATLAS-TDAQ/ScilabSampler.cpp
jorexe/haikunet
dd1697fdc4590de8d687816ec470e40193619b8f
[ "MIT" ]
2
2021-05-05T18:22:19.000Z
2022-01-21T13:50:27.000Z
debug/atomics/ATLAS-TDAQ/ScilabSampler.cpp
jorexe/haikunet
dd1697fdc4590de8d687816ec470e40193619b8f
[ "MIT" ]
null
null
null
debug/atomics/ATLAS-TDAQ/ScilabSampler.cpp
jorexe/haikunet
dd1697fdc4590de8d687816ec470e40193619b8f
[ "MIT" ]
1
2021-05-05T18:05:11.000Z
2021-05-05T18:05:11.000Z
#include "ScilabSampler.h" void ScilabSampler::init(double t, ...) { BaseSimulator::init(t); //The 'parameters' variable contains the parameters transferred from the editor. va_list parameters; va_start(parameters, t); printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s: Init: \n", t, this->getName()); char *fvar; fvar = va_arg(parameters, char*); samplePeriod = readDefaultParameterValue<double>(fvar); printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s: samplePeriod: %f \n", t, this->getName(), samplePeriod); sigma = samplePeriod; // reset resetCounters(); this->logger->initSignals({"max", "avg", "min", "count", "sentBytes", "discards"}); return; } void ScilabSampler::resetCounters(){ eventCounter = 0; weightedSumCounter = 0; maxCounter = lastQueueSize; minCounter = lastQueueSize; discardsCounter = 0; sentBytesCounter = 0; } void ScilabSampler::dint(double t) { sigma = samplePeriod; if(samplePeriod < 0){ // use samplePeriod=-1 to log everything sigma = INF; } } void ScilabSampler::dext(Event x, double t) { printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s_ext: Packet arrived to port %u \n", t, this->getName(), x.port); auto value = (std::static_pointer_cast<double> (x.valuePtr)).get(); double newQueueSize = value[0]; double discard = value[1]; printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s_ext: value[0]=%f value[1]=%f \n", t, this->getName(), newQueueSize, discard); discardsCounter += discard; eventCounter++; // record sent packets if(newQueueSize < lastQueueSize){ // a packet was dequeued sentBytesCounter += lastQueueSize - newQueueSize; } if(lastT != -1 && lastT != t){ // If more than one value arrive in the same T, only sample the last one for that T printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s_ext: Enter counters calculation \n", t, this->getName()); weightedSumCounter += lastQueueSize * (t - lastT); maxCounter = std::max(maxCounter, lastQueueSize); minCounter = std::min(minCounter, lastQueueSize); } lastT = t; lastQueueSize = newQueueSize; sigma = sigma - e; // continue as before if(samplePeriod < 0){ // use samplePeriod=-1 to log everything sigma = 0; } printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s_ext: Counters: events=%i; discards=%i; sentBytes=%i; weightedSum=%f; max=%i; min=%i; \n", t, this->getName(), eventCounter, discardsCounter, sentBytesCounter, weightedSumCounter, maxCounter, minCounter); printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s_ext: lastT=%f, lastQueueSize=%i \n", t, this->getName(), lastT, lastQueueSize); return; } Event ScilabSampler::lambda(double t) { printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s_ext: Sampling now ... \n",t, this->getName()); // record sample for last value if(lastT != -1 && lastT != t){ weightedSumCounter += lastQueueSize * (t - lastT); maxCounter = std::max(maxCounter, lastQueueSize); minCounter = std::min(minCounter, lastQueueSize); } double avg = samplePeriod>0? weightedSumCounter / samplePeriod : weightedSumCounter; printLog(LOG_LEVEL_FULL_LOGGING, "[%f] %s_ext: Counters: events=%i; discards=%i; sentBytes=%i; sum=%f; max=%i; min=%i; avg=%f \n", t, this->getName(), eventCounter, discardsCounter, sentBytesCounter, weightedSumCounter, maxCounter, minCounter,avg); // log to scilab logger->logSignal(t,maxCounter,"max"); logger->logSignal(t,minCounter,"min"); logger->logSignal(t,avg,"avg"); logger->logSignal(t,eventCounter,"count"); logger->logSignal(t,discardsCounter,"discards"); logger->logSignal(t,sentBytesCounter,"sentBytes"); // reset resetCounters(); lastT = t; return Event(); // no output, just log to scilab }
33.296296
250
0.703281
jorexe
ffbcac18fe91c8b1262c48270b66f2b73ad1ac92
3,062
cc
C++
src/trap-handler/handler-outside-posix.cc
xtuc/v8
86894d98bfe79f46c51e27b0699f7bfcc07fe0b2
[ "BSD-3-Clause" ]
1
2019-05-21T13:21:59.000Z
2019-05-21T13:21:59.000Z
src/trap-handler/handler-outside-posix.cc
xtuc/v8
86894d98bfe79f46c51e27b0699f7bfcc07fe0b2
[ "BSD-3-Clause" ]
null
null
null
src/trap-handler/handler-outside-posix.cc
xtuc/v8
86894d98bfe79f46c51e27b0699f7bfcc07fe0b2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // PLEASE READ BEFORE CHANGING THIS FILE! // // This file implements the support code for the out of bounds signal handler. // Nothing in here actually runs in the signal handler, but the code here // manipulates data structures used by the signal handler so we still need to be // careful. In order to minimize this risk, here are some rules to follow. // // 1. Avoid introducing new external dependencies. The files in src/trap-handler // should be as self-contained as possible to make it easy to audit the code. // // 2. Any changes must be reviewed by someone from the crash reporting // or security team. Se OWNERS for suggested reviewers. // // For more information, see https://goo.gl/yMeyUY. // // For the code that runs in the signal handler itself, see handler-inside.cc. #include <signal.h> #include "src/trap-handler/handler-inside-posix.h" #include "src/trap-handler/trap-handler-internal.h" namespace v8 { namespace internal { namespace trap_handler { #if V8_TRAP_HANDLER_SUPPORTED namespace { struct sigaction g_old_handler; // When using the default signal handler, we save the old one to restore in case // V8 chooses not to handle the signal. bool g_is_default_signal_handler_registered; } // namespace bool RegisterDefaultTrapHandler() { CHECK(!g_is_default_signal_handler_registered); struct sigaction action; action.sa_sigaction = HandleSignal; action.sa_flags = SA_SIGINFO; sigemptyset(&action.sa_mask); // {sigaction} installs a new custom segfault handler. On success, it returns // 0. If we get a nonzero value, we report an error to the caller by returning // false. if (sigaction(SIGSEGV, &action, &g_old_handler) != 0) { return false; } // Sanitizers often prevent us from installing our own signal handler. Attempt // to detect this and if so, refuse to enable trap handling. // // TODO(chromium:830894): Remove this once all bots support custom signal // handlers. #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) || \ defined(UNDEFINED_SANITIZER) struct sigaction installed_handler; CHECK_EQ(sigaction(SIGSEGV, NULL, &installed_handler), 0); // If the installed handler does not point to HandleSignal, then // allow_user_segv_handler is 0. if (installed_handler.sa_sigaction != HandleSignal) { printf( "WARNING: sanitizers are preventing signal handler installation. " "Trap handlers are disabled.\n"); return false; } #endif g_is_default_signal_handler_registered = true; return true; } void RemoveTrapHandler() { if (g_is_default_signal_handler_registered) { if (sigaction(SIGSEGV, &g_old_handler, nullptr) == 0) { g_is_default_signal_handler_registered = false; } } } #endif // V8_TRAP_HANDLER_SUPPORTED } // namespace trap_handler } // namespace internal } // namespace v8
33.648352
80
0.743305
xtuc
ffc4a530dedd6b539b37018ee68a8e942c3a4c0e
4,809
hpp
C++
src/setup/info.hpp
kennethmyhra/innoextract
6e6d9559b500a6ddeb918a019d794b67396f1c82
[ "Zlib" ]
8
2018-04-04T06:44:51.000Z
2020-02-27T01:51:41.000Z
src/setup/info.hpp
hanul93/innoextract
6cc1708445d9848d4e88a65ef1c0df084bff31d5
[ "Zlib" ]
null
null
null
src/setup/info.hpp
hanul93/innoextract
6cc1708445d9848d4e88a65ef1c0df084bff31d5
[ "Zlib" ]
1
2018-05-02T18:10:42.000Z
2018-05-02T18:10:42.000Z
/* * Copyright (C) 2011-2014 Daniel Scharrer * * This software is provided 'as-is', without any express or implied * warranty. In no event will the author(s) 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. */ /*! * \file * * Central point to load all the different headers in the correct order. */ #ifndef INNOEXTRACT_SETUP_INFO_HPP #define INNOEXTRACT_SETUP_INFO_HPP #include <vector> #include <iosfwd> #include "setup/header.hpp" #include "setup/version.hpp" #include "util/flags.hpp" namespace setup { struct component_entry; struct data_entry; struct delete_entry; struct directory_entry; struct file_entry; struct icon_entry; struct ini_entry; struct language_entry; struct message_entry; struct permission_entry; struct registry_entry; struct run_entry; struct task_entry; struct type_entry; /*! * Class used to hold and load the various \ref setup headers. */ struct info { info(); ~info(); FLAGS(entry_types, Components, DataEntries, DeleteEntries, UninstallDeleteEntries, Directories, Files, Icons, IniEntries, Languages, Messages, Permissions, RegistryEntries, RunEntries, UninstallRunEntries, Tasks, Types, WizardImages, DecompressorDll, DecryptDll, NoSkip ); setup::version version; setup::header header; std::vector<component_entry> components; //! \c Components std::vector<data_entry> data_entries; //! \c DataEntries std::vector<delete_entry> delete_entries; //! \c DeleteEntries std::vector<delete_entry> uninstall_delete_entries; //! \c UninstallDeleteEntries std::vector<directory_entry> directories; //! \c Directories std::vector<file_entry> files; //! \c Files std::vector<icon_entry> icons; //! \c Icons std::vector<ini_entry> ini_entries; //! \c IniEntries std::vector<language_entry> languages; //! \c Languages std::vector<message_entry> messages; //! \c Messages std::vector<permission_entry> permissions; //! \c Permissions std::vector<registry_entry> registry_entries; //! \c RegistryEntries std::vector<run_entry> run_entries; //! \c RunEntries std::vector<run_entry> uninstall_run_entries; //! \c UninstallRunEntries std::vector<task_entry> tasks; //! \c Tasks std::vector<type_entry> types; //! \c Types //! Images displayed in the installer UI. //! Loading enabled by \c WizardImages std::string wizard_image; std::string wizard_image_small; //! Contents of the helper DLL used to decompress setup data in some versions. //! Loading enabled by \c DecompressorDll std::string decompressor_dll; //! Contents of the helper DLL used to decrypt setup data. //! Loading enabled by \c DecryptDll std::string decrypt_dll; /*! * Load setup headers. * * \param is The input stream to load the setup headers from. * It must already be positioned at start of \ref setup::version * identifier whose position is given by * \ref loader::offsets::header_offset. * \param entries What kinds of entries to load. */ void load(std::istream & is, entry_types entries); /*! * Load setup headers for a specific version. * * \param is The input stream to load the setup headers from. * It must already be positioned at start of the compressed headers. * The compressed headers start directly after the \ref setup::version * identifier whose position is given by * \ref loader::offsets::header_offset. * \param entries What kinds of entries to load. * \param version The setup data version of the headers. * * This function does not set the \ref version member. */ void load(std::istream & is, entry_types entries, const setup::version & version); }; } // namespace setup FLAGS_OVERLOADS(setup::info::entry_types) #endif // INNOEXTRACT_SETUP_INFO_HPP
31.847682
86
0.678519
kennethmyhra
ffc52c354efa906f952ebe3e0ef549ef25305455
861
cpp
C++
OwNetClient/cache/gdsfclock.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
2
2016-09-28T02:23:07.000Z
2019-07-13T15:53:47.000Z
OwNetClient/cache/gdsfclock.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
OwNetClient/cache/gdsfclock.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
#include "gdsfclock.h" #include "qmath.h" #include "databasesettings.h" #include <QVariant> GDSFClock::GDSFClock(QObject *parent) : QObject(parent), m_lastClock(0) { m_lastClock = DatabaseSettings().value("cache_clean_clock", QString::number(0.0)).toDouble(); } double GDSFClock::getGDSFPriority(int accessCount, long size) { return lastClock() + accessCount * (100 / qLn(size + 1.1)); } double GDSFClock::lastClock() { int clock = 0; m_lastClockMutex.lock(); clock = m_lastClock; m_lastClockMutex.unlock(); return clock; } void GDSFClock::setLastClock(double clock) { m_lastClockMutex.lock(); if (clock < m_lastClock) { m_lastClockMutex.unlock(); return; } m_lastClock = clock; m_lastClockMutex.unlock(); DatabaseSettings().setValue("cache_clean_clock", QString::number(clock)); }
21.525
97
0.682927
OwNet
ffc93b5b68d086bca47d521cfa186a32fed7a5c5
242
cpp
C++
data-structures/trees/tree-height-of-a-binary-tree/Solution.cpp
marcos-sb/hacker-rank
566c8426264c944edf6b63bfbfbb9b78b710fce7
[ "Apache-2.0" ]
null
null
null
data-structures/trees/tree-height-of-a-binary-tree/Solution.cpp
marcos-sb/hacker-rank
566c8426264c944edf6b63bfbfbb9b78b710fce7
[ "Apache-2.0" ]
null
null
null
data-structures/trees/tree-height-of-a-binary-tree/Solution.cpp
marcos-sb/hacker-rank
566c8426264c944edf6b63bfbfbb9b78b710fce7
[ "Apache-2.0" ]
null
null
null
/*The tree node has data, left child and right child struct node { int data; node* left; node* right; }; */ int height(node * root) { if(root == NULL) return 0; return max(height(root->left), height(root->right)) + 1; }
15.125
60
0.607438
marcos-sb
ffca57ec7206d38743126876fd8c527cbef53e12
7,579
cpp
C++
modules/ti.UI/gtk/gtk_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
3
2016-03-15T23:50:35.000Z
2016-05-09T09:36:10.000Z
modules/ti.UI/gtk/gtk_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
null
null
null
modules/ti.UI/gtk/gtk_menu_item_impl.cpp
pjunior/titanium
2d5846849fb33291afd73d79c117ea990b54db77
[ "Apache-2.0" ]
null
null
null
/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include "../ui_module.h" namespace ti { void menu_callback(gpointer data); GtkMenuItemImpl::GtkMenuItemImpl() : parent(NULL) { } void GtkMenuItemImpl::SetParent(GtkMenuItemImpl* parent) { this->parent = parent; } GtkMenuItemImpl* GtkMenuItemImpl::GetParent() { return this->parent; } SharedValue GtkMenuItemImpl::AddSeparator() { GtkMenuItemImpl* item = new GtkMenuItemImpl(); item->MakeSeparator(); return this->AppendItem(item); } SharedValue GtkMenuItemImpl::AddItem(SharedValue label, SharedValue callback, SharedValue icon_url) { GtkMenuItemImpl* item = new GtkMenuItemImpl(); item->MakeItem(label, callback, icon_url); return this->AppendItem(item); } SharedValue GtkMenuItemImpl::AddSubMenu(SharedValue label, SharedValue icon_url) { GtkMenuItemImpl* item = new GtkMenuItemImpl(); item->MakeSubMenu(label, icon_url); return this->AppendItem(item); } SharedValue GtkMenuItemImpl::AppendItem(GtkMenuItemImpl* item) { item->SetParent(this); this->children.push_back(item); /* Realize the new item and add it to all existing instances */ std::vector<MenuPieces*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { MenuPieces *pieces = item->Realize(false); gtk_menu_shell_append(GTK_MENU_SHELL((*i)->menu), pieces->item); gtk_widget_show(pieces->item); i++; } return MenuItem::AddToListModel(item); } GtkWidget* GtkMenuItemImpl::GetMenu() { if (this->parent == NULL) // top-level { MenuPieces* pieces = this->Realize(false); return pieces->menu; } else { // For now we do not support using a submenu as a menu, // as that makes determining parent-child relationships // really hard, so just return NULL and check above. return NULL; } } GtkWidget* GtkMenuItemImpl::GetMenuBar() { if (this->parent == NULL) // top level { MenuPieces* pieces = this->Realize(true); return pieces->menu; } else { // For now we do not support using a submenu as a menu, // as that makes determining parent-child relationships // really hard, so just return NULL and check above. return NULL; } } void GtkMenuItemImpl::AddChildrenTo(GtkWidget* menu) { std::vector<GtkMenuItemImpl*>::iterator c; for (c = this->children.begin(); c != this->children.end(); c++) { MenuPieces* pieces = new MenuPieces(); (*c)->MakeMenuPieces(*pieces); gtk_menu_shell_append(GTK_MENU_SHELL(menu), pieces->item); gtk_widget_show(pieces->item); if (this->IsSubMenu() || this->parent == NULL) { (*c)->AddChildrenTo(pieces->menu); } delete pieces; } } void GtkMenuItemImpl::ClearRealization(GtkWidget *parent_menu) { std::vector<MenuPieces*>::iterator i; std::vector<GtkMenuItemImpl*>::iterator c; // Find the instance which is contained in parent_menu or, // if we are the root, find the instance which uses this // menu to contain it's children. for (i = this->instances.begin(); i != this->instances.end(); i++) { if ((*i)->parent_menu == parent_menu || (this->parent == NULL && (*i)->menu == parent_menu)) break; } // Could not find an instance which uses the menu. if (i == this->instances.end()) return; // Erase all children which use // the sub-menu as their parent. for (c = this->children.begin(); c != this->children.end(); c++) { (*c)->ClearRealization((*i)->menu); } this->instances.erase(i); // Erase the instance } GtkMenuItemImpl::MenuPieces* GtkMenuItemImpl::Realize(bool is_menu_bar) { MenuPieces* pieces = new MenuPieces(); if (this->parent == NULL) // top-level { if (is_menu_bar) pieces->menu = gtk_menu_bar_new(); else pieces->menu = gtk_menu_new(); } else { this->MakeMenuPieces(*pieces); } /* Realize this widget's children */ if (this->IsSubMenu() || this->parent == NULL) { std::vector<GtkMenuItemImpl*>::iterator i = this->children.begin(); while (i != this->children.end()) { MenuPieces* child_pieces = (*i)->Realize(false); child_pieces->parent_menu = pieces->menu; gtk_menu_shell_append( GTK_MENU_SHELL(pieces->menu), child_pieces->item); gtk_widget_show(child_pieces->item); i++; } } this->instances.push_back(pieces); return pieces; } void GtkMenuItemImpl::MakeMenuPieces(MenuPieces& pieces) { const char* label = this->GetLabel(); const char* icon_url = this->GetIconURL(); SharedString icon_path = UIModule::GetResourcePath(icon_url); SharedValue callback_val = this->RawGet("callback"); if (this->IsSeparator()) { pieces.item = gtk_separator_menu_item_new(); } else if (icon_path.isNull()) { pieces.item = gtk_menu_item_new_with_label(label); } else { pieces.item = gtk_image_menu_item_new_with_label(label); GtkWidget* image = gtk_image_new_from_file(icon_path->c_str()); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(pieces.item), image); } if (callback_val->IsMethod()) { // The callback is stored as a property of this MenuItem // so we do not need to worry about the pointer being freed // out from under us. At some point, in threaded code we will // have to protect it with a mutex though, in the case that // the callback is fired after it has been reassigned. BoundMethod* cb = callback_val->ToMethod().get(); g_signal_connect_swapped( G_OBJECT (pieces.item), "activate", G_CALLBACK(menu_callback), (gpointer) cb); } if (this->IsSubMenu()) { pieces.menu = gtk_menu_new(); gtk_menu_item_set_submenu(GTK_MENU_ITEM(pieces.item), pieces.menu); } } /* Crazy mutations below */ void GtkMenuItemImpl::Enable() { std::vector<MenuPieces*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { GtkWidget *w = (*i)->item; if (w != NULL) gtk_widget_set_sensitive(w, TRUE); i++; } } void GtkMenuItemImpl::Disable() { std::vector<MenuPieces*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { GtkWidget *w = (*i)->item; if (w != NULL) gtk_widget_set_sensitive(w, FALSE); i++; } } void GtkMenuItemImpl::SetLabel(std::string label) { std::vector<MenuPieces*>::iterator i = this->instances.begin(); while (i != this->instances.end()) { GtkWidget *w = (*i)->item; if (w != NULL) { GtkWidget *menu_label = gtk_bin_get_child(GTK_BIN(w)); gtk_label_set_text(GTK_LABEL(menu_label), label.c_str()); } i++; } } void GtkMenuItemImpl::SetIcon(std::string icon_url) { std::vector<MenuPieces*>::iterator i = this->instances.begin(); SharedString icon_path = UIModule::GetResourcePath(icon_url.c_str()); while (i != this->instances.end()) { GtkWidget *w = (*i)->item; if (w != NULL && G_TYPE_FROM_INSTANCE(w) == GTK_TYPE_IMAGE_MENU_ITEM) { GtkWidget* image = gtk_image_new_from_file(icon_path->c_str()); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(w), image); } i++; } } /* Le callback */ void menu_callback(gpointer data) { BoundMethod* cb = (BoundMethod*) data; // TODO: Handle exceptions in some way try { ValueList args; cb->Call(args); } catch(...) { std::cerr << "Menu callback failed" << std::endl; } } }
24.291667
74
0.660773
pjunior
ffcbb6c4ba1cf30efb861161a4c4a6fed66727ea
1,096
cpp
C++
src/Sound.cpp
ChrisFadden/PartyTowers
b16f822130c27b0b7eaef10626fc99f5010f6591
[ "MIT" ]
1
2015-09-26T16:36:29.000Z
2015-09-26T16:36:29.000Z
src/Sound.cpp
ChrisFadden/PartyTowers
b16f822130c27b0b7eaef10626fc99f5010f6591
[ "MIT" ]
null
null
null
src/Sound.cpp
ChrisFadden/PartyTowers
b16f822130c27b0b7eaef10626fc99f5010f6591
[ "MIT" ]
null
null
null
#include <iostream> #include "Sound.h" GameSound::GameSound() { int audio_rate = 22050; Uint16 audio_format = AUDIO_S16SYS; int audio_channels = 2; int audio_buffers = 4096; if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) { printf("Unable to initialize audio: %s\n", Mix_GetError()); } } void GameSound::PlaySound(char* songName) { Mix_Chunk* sound = NULL; int channel; sound = Mix_LoadWAV(songName); if (sound == NULL) { printf("Unable to load WAV file: %s\n", Mix_GetError()); } channel = Mix_PlayChannel(-1, sound, 0); if (channel == -1) { printf("Unable to play WAV file: %s\n", Mix_GetError()); } MixChunkVec.push_back(sound); channelVec.push_back(channel); return; } bool GameSound::IsPlaying(){ for(auto &i : channelVec) { if(Mix_Playing(i) != 0) return true; } return false; } GameSound::~GameSound(){ for(auto &i : MixChunkVec) { Mix_FreeChunk(i); } Mix_CloseAudio(); }
21.490196
67
0.594891
ChrisFadden
ffcd26bd9d12082c22a10c023f9d81cbbbcd2070
2,216
cpp
C++
CmnIP/sample/sample_draw_map2d.cpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
CmnIP/sample/sample_draw_map2d.cpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
CmnIP/sample/sample_draw_map2d.cpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
/** * @file sample_drawing_map2d.cpp * @brief Example of the visualization of the chart radar type. * * @section LICENSE * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR/AUTHORS 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. * * @author Alessandro Moro <alessandromoro.italy@gmail.com> * @bug No known bugs. * @version 1.0.0.1 * */ #include <iostream> #include "container/inc/container/container_headers.hpp" #include "draw/inc/draw/draw_headers.hpp" namespace { /** @brief Test function. */ void test() { CmnIP::draw::Map2D map; map.set_natural_size(512, 512); map.set_range(-3000, -3000, 3000, 3000); map.reset_paint(); float x = 0, y = 0; map.original2scaled(1239, 738, x, y); cv::circle(map.image(), cv::Point(x, y), 2, cv::Scalar::all(255)); float xin = 0, yin = 0; map.scaled2original(x, y, xin, yin); std::vector<cv::Point2f> points; map.scaled_marker(500, 350, 1.8, 100, points); cv::line(map.image(), points[0], points[1], cv::Scalar(0,255)); cv::line(map.image(), points[2], points[3], cv::Scalar(0,255)); map.scaled_marker(2400, 1350, 2.6, 100, points); cv::line(map.image(), points[0], points[1], cv::Scalar(0,0,255)); cv::line(map.image(), points[2], points[3], cv::Scalar(0,0,255)); std::cout << xin << " " << yin << std::endl; cv::imshow("map", map.image()); cv::waitKey(); } } // namespace #ifdef CmnLib cmnLIBRARY_TEST_MAIN(&test, "data\\MemoryLeakCPP.txt", "data\\MemoryLeakC.txt"); #else /** main */ int main(int argc, char *argv[]) { std::cout << "Test chart radar" << std::endl; test(); return 0; } #endif
29.546667
80
0.698105
Khoronus
ffcd49e8a0796b2e3bf1b808247467055f4ece88
414
cpp
C++
game/MakeWythoffTable.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
game/MakeWythoffTable.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
game/MakeWythoffTable.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
//n is the length of the array that required //if table[i] < i,then i means a,and table[i] means b.Else,i means b,ans table[i] means a. int* MakeWythoffTable(int n) { int k; int* table = new int[n]; int a; for(k = 0; k < n; k++) { a = k * mul; if(a >= n) break; table[a] = a + k; if(a + k < n) table[a+k] = a; } return table; }
19.714286
90
0.471014
searchstar2017
ffd60057506f98a6d836d619d11b011d88351a0e
1,050
cpp
C++
cds/variable_length_vector/elias_fano_codes.cpp
echizentm/CompactDataStructures
f7a7ab95f7353440dc4b66caeb07448b35b743fe
[ "Apache-2.0" ]
2
2017-01-29T16:06:48.000Z
2017-04-11T07:58:08.000Z
cds/variable_length_vector/elias_fano_codes.cpp
echizentm/CompactDataStructures
f7a7ab95f7353440dc4b66caeb07448b35b743fe
[ "Apache-2.0" ]
null
null
null
cds/variable_length_vector/elias_fano_codes.cpp
echizentm/CompactDataStructures
f7a7ab95f7353440dc4b66caeb07448b35b743fe
[ "Apache-2.0" ]
null
null
null
#include "elias_fano_codes.h" namespace cds { elias_fano_codes::elias_fano_codes() : marker(1) { this->size = 0; this->marker.resize(1); this->marker.write(0, 1); } uint64_t elias_fano_codes::vector_size() const { return this->bv.vector_size() + this->marker.vector_size(); } uint64_t elias_fano_codes::read(uint64_t index) const { uint64_t begin = this->marker.search(index + 1); uint64_t end = this->marker.search(index + 2); uint64_t value = this->bv.bits_read(begin, end); return (value | (1LL << (end - begin))) - 2; } void elias_fano_codes::push_back(uint64_t value) { this->size++; value += 2; uint64_t length = bits_length(value) - 1; value &= ((1LL << length) - 1); this->bv.resize(this->bv.size + length); this->marker.resize(this->marker.size + length); this->bv.bits_write(this->bv.size - length, this->bv.size, value); this->marker.write(this->marker.size - 1, 1); } }
29.166667
74
0.589524
echizentm
ffd61173debcf45f034afb348acf31d4d286352b
3,642
cc
C++
kv/server/raft_server.cc
yunxiao3/eraft
d68d5dbe7007c4d9cac3238af4e6e78e48d9cb5f
[ "MIT" ]
58
2021-05-20T12:56:54.000Z
2022-03-28T03:45:25.000Z
kv/server/raft_server.cc
yunxiao3/eraft
d68d5dbe7007c4d9cac3238af4e6e78e48d9cb5f
[ "MIT" ]
1
2022-01-25T04:40:20.000Z
2022-01-28T05:43:30.000Z
kv/server/raft_server.cc
yunxiao3/eraft
d68d5dbe7007c4d9cac3238af4e6e78e48d9cb5f
[ "MIT" ]
15
2021-05-20T12:56:57.000Z
2022-03-14T20:35:58.000Z
// MIT License // Copyright (c) 2021 eraft dev group // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <kv/engines.h> #include <kv/raft_server.h> #include <kv/utils.h> #include <spdlog/spdlog.h> #include <cassert> namespace kvserver { RaftStorage::RaftStorage(std::shared_ptr<Config> conf) : conf_(conf) { this->engs_ = std::make_shared<Engines>(conf->dbPath_ + "_raft", conf->dbPath_ + "_kv"); } RaftStorage::~RaftStorage() {} bool RaftStorage::CheckResponse(raft_cmdpb::RaftCmdResponse* resp, int reqCount) {} bool RaftStorage::Write(const kvrpcpb::Context& ctx, const kvrpcpb::RawPutRequest* put) { std::shared_ptr<raft_serverpb::RaftMessage> sendMsg = std::make_shared<raft_serverpb::RaftMessage>(); // send raft message sendMsg->set_data(put->SerializeAsString()); sendMsg->set_region_id(ctx.region_id()); sendMsg->set_raft_msg_type(raft_serverpb::RaftMsgClientCmd); return this->Raft(sendMsg.get()); } StorageReader* RaftStorage::Reader(const kvrpcpb::Context& ctx) { metapb::Region region; RegionReader* regionReader = new RegionReader(this->engs_, region); this->regionReader_ = regionReader; return regionReader; } bool RaftStorage::Raft(const raft_serverpb::RaftMessage* msg) { return this->raftRouter_->SendRaftMessage(msg); } bool RaftStorage::SnapShot(raft_serverpb::RaftSnapshotData* snap) {} bool RaftStorage::Start() { // raft system init this->raftSystem_ = std::make_shared<RaftStore>(this->conf_); // router init this->raftRouter_ = this->raftSystem_->raftRouter_; // raft client init std::shared_ptr<RaftClient> raftClient = std::make_shared<RaftClient>(this->conf_); this->node_ = std::make_shared<Node>(this->raftSystem_, this->conf_); // server transport init std::shared_ptr<ServerTransport> trans = std::make_shared<ServerTransport>(raftClient, raftRouter_); if (this->node_->Start(this->engs_, trans)) { SPDLOG_INFO("raft storage start succeed!"); } else { SPDLOG_INFO("raft storage start error!"); } } RegionReader::RegionReader(std::shared_ptr<Engines> engs, metapb::Region region) { this->engs_ = engs; this->region_ = region; } RegionReader::~RegionReader() {} std::string RegionReader::GetFromCF(std::string cf, std::string key) { return Assistant::GetInstance()->GetCF(this->engs_->kvDB_, cf, key); } rocksdb::Iterator* RegionReader::IterCF(std::string cf) { return Assistant::GetInstance()->NewCFIterator(this->engs_->kvDB_, cf); } void RegionReader::Close() {} } // namespace kvserver
33.412844
80
0.720483
yunxiao3
ffd77d12d0dcfaf5739ac24d223036312d9f574f
9,215
cpp
C++
src/kvstore/RocksEngine.cpp
0xflotus/nebula
10faa87c83f66b62e0db493f958492afe8b569c8
[ "Apache-2.0" ]
1
2019-05-24T02:41:17.000Z
2019-05-24T02:41:17.000Z
src/kvstore/RocksEngine.cpp
steppenwolfyuetong/vgraph
b0d817fd151758d5ef788b2a26bc3e48a3fa4e18
[ "Apache-2.0" ]
null
null
null
src/kvstore/RocksEngine.cpp
steppenwolfyuetong/vgraph
b0d817fd151758d5ef788b2a26bc3e48a3fa4e18
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "base/Base.h" #include "kvstore/RocksEngine.h" #include <folly/String.h> #include "fs/FileUtils.h" #include "kvstore/KVStore.h" #include "kvstore/RocksEngineConfig.h" namespace nebula { namespace kvstore { using fs::FileUtils; using fs::FileType; const char* kSystemParts = "__system__parts__"; RocksEngine::RocksEngine(GraphSpaceID spaceId, const std::string& dataPath, std::shared_ptr<rocksdb::MergeOperator> mergeOp, std::shared_ptr<rocksdb::CompactionFilterFactory> cfFactory) : KVEngine(spaceId) , dataPath_(dataPath) { LOG(INFO) << "open rocksdb on " << dataPath; if (FileUtils::fileType(dataPath.c_str()) == FileType::NOTEXIST) { FileUtils::makeDir(dataPath); } rocksdb::Options options; rocksdb::DB* db = nullptr; rocksdb::Status status = initRocksdbOptions(options); CHECK(status.ok()); if (mergeOp != nullptr) { options.merge_operator = mergeOp; } if (cfFactory != nullptr) { options.compaction_filter_factory = cfFactory; } status = rocksdb::DB::Open(options, dataPath_, &db); CHECK(status.ok()); db_.reset(db); partsNum_ = allParts().size(); } RocksEngine::~RocksEngine() { } ResultCode RocksEngine::get(const std::string& key, std::string* value) { rocksdb::ReadOptions options; rocksdb::Status status = db_->Get(options, rocksdb::Slice(key), value); if (status.ok()) { return ResultCode::SUCCEEDED; } else if (status.IsNotFound()) { VLOG(3) << "Get: " << key << " Not Found"; return ResultCode::ERR_KEY_NOT_FOUND; } else { VLOG(3) << "Get Failed: " << key << " " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::multiGet(const std::vector<std::string>& keys, std::vector<std::string>* values) { rocksdb::ReadOptions options; std::vector<rocksdb::Slice> slices; for (unsigned int index = 0 ; index < keys.size() ; index++) { slices.emplace_back(keys[index]); } std::vector<rocksdb::Status> status = db_->MultiGet(options, slices, values); auto code = std::all_of(status.begin(), status.end(), [](rocksdb::Status s) { return s.ok(); }); if (code) { return ResultCode::SUCCEEDED; } else { return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::put(std::string key, std::string value) { rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; rocksdb::Status status = db_->Put(options, key, value); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "Put Failed: " << key << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::multiPut(std::vector<KV> keyValues) { rocksdb::WriteBatch updates(FLAGS_batch_reserved_bytes); for (size_t i = 0; i < keyValues.size(); i++) { updates.Put(keyValues[i].first, keyValues[i].second); } rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; rocksdb::Status status = db_->Write(options, &updates); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "MultiPut Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::range(const std::string& start, const std::string& end, std::unique_ptr<KVIterator>* storageIter) { rocksdb::ReadOptions options; rocksdb::Iterator* iter = db_->NewIterator(options); if (iter) { iter->Seek(rocksdb::Slice(start)); } storageIter->reset(new RocksRangeIter(iter, start, end)); return ResultCode::SUCCEEDED; } ResultCode RocksEngine::prefix(const std::string& prefix, std::unique_ptr<KVIterator>* storageIter) { rocksdb::ReadOptions options; rocksdb::Iterator* iter = db_->NewIterator(options); if (iter) { iter->Seek(rocksdb::Slice(prefix)); } storageIter->reset(new RocksPrefixIter(iter, prefix)); return ResultCode::SUCCEEDED; } ResultCode RocksEngine::remove(const std::string& key) { rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; auto status = db_->Delete(options, key); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "Remove Failed: " << key << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::multiRemove(std::vector<std::string> keys) { rocksdb::WriteBatch deletes(FLAGS_batch_reserved_bytes); for (size_t i = 0; i < keys.size(); i++) { deletes.Delete(keys[i]); } rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; rocksdb::Status status = db_->Write(options, &deletes); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "MultiRemove Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::removeRange(const std::string& start, const std::string& end) { rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; auto status = db_->DeleteRange(options, db_->DefaultColumnFamily(), start, end); if (status.ok()) { return ResultCode::SUCCEEDED; } else { VLOG(3) << "RemoveRange Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } std::string RocksEngine::partKey(PartitionID partId) { std::string key; static const size_t prefixLen = ::strlen(kSystemParts); key.reserve(prefixLen + sizeof(PartitionID)); key.append(kSystemParts, prefixLen); key.append(reinterpret_cast<const char*>(&partId), sizeof(PartitionID)); return key; } void RocksEngine::addPart(PartitionID partId) { auto ret = put(partKey(partId), ""); if (ret == ResultCode::SUCCEEDED) { partsNum_++; CHECK_GE(partsNum_, 0); } } void RocksEngine::removePart(PartitionID partId) { rocksdb::WriteOptions options; options.disableWAL = FLAGS_rocksdb_disable_wal; auto status = db_->Delete(options, partKey(partId)); if (status.ok()) { partsNum_--; CHECK_GE(partsNum_, 0); } } std::vector<PartitionID> RocksEngine::allParts() { std::unique_ptr<KVIterator> iter; static const size_t prefixLen = ::strlen(kSystemParts); static const std::string prefixStr(kSystemParts, prefixLen); CHECK_EQ(ResultCode::SUCCEEDED, this->prefix(prefixStr, &iter)); std::vector<PartitionID> parts; while (iter->valid()) { auto key = iter->key(); CHECK_EQ(key.size(), prefixLen + sizeof(PartitionID)); parts.emplace_back( *reinterpret_cast<const PartitionID*>(key.data() + key.size() - sizeof(PartitionID))); iter->next(); } return parts; } int32_t RocksEngine::totalPartsNum() { return partsNum_; } ResultCode RocksEngine::ingest(const std::vector<std::string>& files) { rocksdb::IngestExternalFileOptions options; rocksdb::Status status = db_->IngestExternalFile(files, options); if (status.ok()) { return ResultCode::SUCCEEDED; } else { LOG(ERROR) << "Ingest Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } ResultCode RocksEngine::setOption(const std::string& configKey, const std::string& configValue) { std::unordered_map<std::string, std::string> configOptions = { {configKey, configValue} }; rocksdb::Status status = db_->SetOptions(configOptions); if (status.ok()) { return ResultCode::SUCCEEDED; } else { LOG(ERROR) << "SetOption Failed: " << configKey << ":" << configValue; return ResultCode::ERR_INVALID_ARGUMENT; } } ResultCode RocksEngine::setDBOption(const std::string& configKey, const std::string& configValue) { std::unordered_map<std::string, std::string> configOptions = { {configKey, configValue} }; rocksdb::Status status = db_->SetDBOptions(configOptions); if (status.ok()) { return ResultCode::SUCCEEDED; } else { LOG(ERROR) << "SetDBOption Failed: " << configKey << ":" << configValue; return ResultCode::ERR_INVALID_ARGUMENT; } } ResultCode RocksEngine::compactAll() { rocksdb::CompactRangeOptions options; rocksdb::Status status = db_->CompactRange(options, nullptr, nullptr); if (status.ok()) { return ResultCode::SUCCEEDED; } else { LOG(ERROR) << "CompactAll Failed: " << status.ToString(); return ResultCode::ERR_UNKNOWN; } } } // namespace kvstore } // namespace nebula
31.343537
97
0.627564
0xflotus
ffd8796be2556eaf9b7ac8bb25ba0e7659ec1f61
16,703
cpp
C++
helpers/OriWidgets.cpp
Qt-Widgets/orion-qt
2df2b9687f637800bcd2a9f64f4cabafa8773f03
[ "MIT" ]
null
null
null
helpers/OriWidgets.cpp
Qt-Widgets/orion-qt
2df2b9687f637800bcd2a9f64f4cabafa8773f03
[ "MIT" ]
null
null
null
helpers/OriWidgets.cpp
Qt-Widgets/orion-qt
2df2b9687f637800bcd2a9f64f4cabafa8773f03
[ "MIT" ]
1
2022-01-15T08:54:38.000Z
2022-01-15T08:54:38.000Z
#include "OriWidgets.h" #include <QAction> #include <QActionGroup> #include <QApplication> #include <QBoxLayout> #include <QComboBox> #include <QDebug> #include <QGroupBox> #include <QHeaderView> #include <QLabel> #include <QMenu> #include <QObject> #include <QPushButton> #include <QStyle> #include <QSpinBox> #include <QSplitter> #include <QTableView> #include <QTextBrowser> #include <QToolBar> #include <QToolButton> #include <QTreeWidget> #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) #define qintptr std::intptr_t #endif namespace Ori { namespace Gui { //-------------------------------------------------------------------------------------------------- void adjustFont(QWidget *w) { #ifdef Q_OS_WIN QFont f = w->font(); if (f.pointSize() < 10) { f.setPointSize(10); w->setFont(f); } #else Q_UNUSED(w) #endif } void setFontSizePt(QWidget *w, int sizePt) { QFont f = w->font(); f.setPointSize(sizePt); w->setFont(f); } void setFontMonospace(QWidget *w, int sizePt) { QFont f = w->font(); #if defined(Q_OS_WIN) f.setFamily("Consolas"); f.setPointSize(10); #elif defined(Q_OS_MAC) f.setFamily("Monaco"); f.setPointSize(13); #else f.setFamily("monospace"); f.setPointSize(11); #endif if (sizePt > 0) f.setPointSize(sizePt); w->setFont(f); } //-------------------------------------------------------------------------------------------------- QSplitter* splitter(Qt::Orientation orientation, QWidget *w1, QWidget *w2, QList<int> sizes) { auto splitter = new QSplitter(orientation); splitter->addWidget(w1); splitter->addWidget(w2); if (!sizes.isEmpty()) splitter->setSizes(sizes); return splitter; } QSplitter* splitterH(QWidget *w1, QWidget *w2) { return splitter(Qt::Horizontal, w1, w2, {}); } QSplitter* splitterV(QWidget *w1, QWidget *w2) { return splitter(Qt::Vertical, w1, w2, {}); } QSplitter* splitterH(QWidget *w1, QWidget *w2, int size1, int size2) { return splitter(Qt::Horizontal, w1, w2, {size1, size2}); } QSplitter* splitterV(QWidget *w1, QWidget *w2, int size1, int size2) { return splitter(Qt::Vertical, w1, w2, {size1, size2}); } //-------------------------------------------------------------------------------------------------- QToolButton* textToolButton(QAction* action) { auto button = new QToolButton; button->setDefaultAction(action); button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); return button; } QToolButton* menuToolButton(QMenu* menu, QAction* action) { auto button = new QToolButton; button->setDefaultAction(action); button->setPopupMode(QToolButton::MenuButtonPopup); button->setMenu(menu); return button; } QToolButton* iconToolButton(const QString& tooltip, const QString& iconPath, QObject* receiver, const char* slot) { auto button = new QToolButton; button->setToolTip(tooltip); button->setIcon(QIcon(iconPath)); button->connect(button, SIGNAL(clicked()), receiver, slot); return button; } QToolButton* iconToolButton(const QString& tooltip, const QString& iconPath, int iconSize, QObject* receiver, const char* slot) { auto button = new QToolButton; button->setToolTip(tooltip); button->setIconSize(QSize(iconSize, iconSize)); button->setIcon(QIcon(iconPath)); button->connect(button, SIGNAL(clicked()), receiver, slot); return button; } //-------------------------------------------------------------------------------------------------- QMenu* menu(std::initializer_list<QObject*> items) { return menu(QString(), nullptr, items); } QMenu* menu(QWidget *parent, std::initializer_list<QObject*> items) { return menu(QString(), parent, items); } QMenu* menu(const QString& title, std::initializer_list<QObject*> items) { return menu(title, nullptr, items); } QMenu* menu(const QString& title, QWidget *parent, std::initializer_list<QObject*> items) { return populate(new QMenu(title, parent), items); } QMenu* populate(QMenu* menu, std::initializer_list<QObject*> items) { if (!menu) return nullptr; menu->clear(); for (auto item: items) append(menu, item); return menu; } void append(QMenu* menu, QObject* item) { if (!item) { menu->addSeparator(); return; } auto action = qobject_cast<QAction*>(item); if (action) { menu->addAction(action); return; } auto submenu = qobject_cast<QMenu*>(item); if (submenu) { menu->addMenu(submenu); return; } } QMenu* makeToggleWidgetsMenu(QMenu* parent, const QString& title, std::initializer_list<QWidget*> widgets) { QMenu* menu = parent->addMenu(title); QVector<QPair<QAction*, QWidget*> > actions; for (QWidget* widget : widgets) { QAction *action = menu->addAction(widget->windowTitle(), [widget](){ toggleWidget(widget); }); action->setCheckable(true); actions.push_back(QPair<QAction*, QWidget*>(action, widget)); } qApp->connect(menu, &QMenu::aboutToShow, [actions](){ for (const QPair<QAction*, QWidget*>& pair : actions) pair.first->setChecked(pair.second->isVisible()); }); return menu; } //-------------------------------------------------------------------------------------------------- QToolBar* toolbar(std::initializer_list<QObject*> items) { return populate(new QToolBar, items); } QToolBar* populate(QToolBar* toolbar, std::initializer_list<QObject*> items) { if (!toolbar) return nullptr; toolbar->clear(); for (auto item : items) append(toolbar, item); return toolbar; } void append(QToolBar* toolbar, QObject* item) { if (!item) { toolbar->addSeparator(); return; } auto action = qobject_cast<QAction*>(item); if (action) { toolbar->addAction(action); return; } auto group = qobject_cast<QActionGroup*>(item); if (group) { for (auto action : group->actions()) toolbar->addAction(action); return; } auto widget = qobject_cast<QWidget*>(item); if (widget) { toolbar->addWidget(widget); return; } } //-------------------------------------------------------------------------------------------------- QBoxLayout* layoutH(const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return populate(new QHBoxLayout, items); } QBoxLayout* layoutV(const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return populate(new QVBoxLayout, items); } QBoxLayout* layoutH(QWidget* parent, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return populate(new QHBoxLayout(parent), items); } QBoxLayout* layoutV(QWidget* parent, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return populate(new QVBoxLayout(parent), items); } QBoxLayout* initGeometry(QBoxLayout* layout, int margin, int spacing) { if (margin >= 0) layout->setContentsMargins(margin, margin, margin, margin); if (spacing >= 0) layout->setSpacing(spacing); return layout; } QBoxLayout* layoutH(QWidget* parent, int margin, int spacing, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return initGeometry(layoutH(parent, items), margin, spacing); } QBoxLayout* layoutV(QWidget* parent, int margin, int spacing, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return initGeometry(layoutV(parent, items), margin, spacing); } QBoxLayout* layoutH(int margin, int spacing, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return initGeometry(layoutH(items), margin, spacing); } QBoxLayout* layoutV(int margin, int spacing, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return initGeometry(layoutV(items), margin, spacing); } QBoxLayout* populate(QBoxLayout* layout, const std::initializer_list<QObject*>& items) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; if (!layout) return nullptr; for (auto item: items) append(layout, item); return layout; } void append(QBoxLayout* layout, QObject* item) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; if (!item) { layout->addStretch(); return; } if (qintptr(item) < 100) { layout->addSpacing(int(qintptr(item))); return; } auto widget = qobject_cast<QWidget*>(item); if (widget) { layout->addWidget(widget); return; } auto sublayout = qobject_cast<QLayout*>(item); if (sublayout) { layout->addLayout(sublayout); return; } } QObject* spacing(int size) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return (QObject*)qintptr(size); } QObject* defaultSpacing(int factor) { qDebug() << "This function is obsolete and should be removed. Please use stuff from OriLayout.h instead."; return spacing(factor * layoutSpacing()); } //-------------------------------------------------------------------------------------------------- QLabel* stretchedLabel(const QString& text) { auto label = new QLabel(text); label->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); return label; } //-------------------------------------------------------------------------------------------------- int layoutSpacing() { int spacing = qApp->style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing); // MacOS's style "macintosh" has spacing -1, sic! // It is not what we want adjusting widgets using layoutSpacing() // Fusion style gets 6 and it's most reasonable style in Qt if (spacing < 0) spacing = 6; return spacing; } int borderWidth() { return qApp->style()->pixelMetric(QStyle::PM_DefaultFrameWidth); } //-------------------------------------------------------------------------------------------------- QGroupBox* group(const QString& title, QLayout *layout) { auto group = new QGroupBox(title); group->setLayout(layout); return group; } QGroupBox* groupV(const QString& title, const std::initializer_list<QObject*>& items) { return group(title, layoutV(items)); } QGroupBox* groupH(const QString& title, const std::initializer_list<QObject*>& items) { return group(title, layoutH(items)); } //-------------------------------------------------------------------------------------------------- QWidget* widget(QBoxLayout* layout) { auto widget = new QWidget; widget->setLayout(layout); return widget; } QWidget* widgetV(const std::initializer_list<QObject*>& items) { return widget(layoutV(items)); } QWidget* widgetH(const std::initializer_list<QObject*>& items) { return widget(layoutH(items)); } //-------------------------------------------------------------------------------------------------- QPushButton* button(const QString& title, QObject *receiver, const char* slot) { auto button = new QPushButton(title); button->connect(button, SIGNAL(clicked(bool)), receiver, slot); return button; } QPushButton* iconButton(const QString& tooltip, const QString& iconPath, QObject* receiver, const char* slot, bool flat) { auto button = new QPushButton; button->setIcon(QIcon(iconPath)); button->setToolTip(tooltip); button->connect(button, SIGNAL(clicked(bool)), receiver, slot); button->setFlat(flat); return button; } //-------------------------------------------------------------------------------------------------- void setSelectedId(QComboBox *combo, int id) { for (int i = 0; i < combo->count(); i++) if (combo->itemData(i).toInt() == id) { combo->setCurrentIndex(i); return; } combo->setCurrentIndex(-1); } int getSelectedId(const QComboBox *combo, int def) { QVariant data = combo->itemData(combo->currentIndex()); if (!data.isValid()) return def; bool ok; int id = data.toInt(&ok); return ok? id: def; } //-------------------------------------------------------------------------------------------------- // Guesses a descriptive text suited for the menu entry. // This is equivalent to QAction's internal qt_strippedText(). static QString strippedActionTitle(QString s) { s.remove(QString::fromLatin1("...")); for (int i = 0; i < s.size(); ++i) if (s.at(i) == QLatin1Char('&')) s.remove(i, 1); return s.trimmed(); } // Adds shortcut information to the action's tooltip. // Here is more complete solution supporting custom tooltips // https://stackoverflow.com/questions/42607554/show-shortcut-in-tooltip-of-qtoolbar static void setActionShortcut(QAction* action, const QKeySequence& shortcut) { action->setShortcut(shortcut); action->setToolTip(QStringLiteral("<p style='white-space:pre'>%1&nbsp;&nbsp;(<code>%2</code>)</p>") .arg(strippedActionTitle(action->text()), shortcut.toString(QKeySequence::NativeText))); } QAction* action(const QString& title, QObject* receiver, const char* slot, const char* icon, const QKeySequence& shortcut) { auto action = new QAction(title, receiver); if (!shortcut.isEmpty()) setActionShortcut(action, shortcut); if (icon) action->setIcon(QIcon(icon)); qApp->connect(action, SIGNAL(triggered()), receiver, slot); return action; } QAction* toggledAction(const QString& title, QObject* receiver, const char* slot, const char* icon, const QKeySequence& shortcut) { auto action = new QAction(title, receiver); action->setCheckable(true); if (!shortcut.isEmpty()) setActionShortcut(action, shortcut); if (icon) action->setIcon(QIcon(icon)); if (slot) qApp->connect(action, SIGNAL(toggled(bool)), receiver, slot); return action; } //-------------------------------------------------------------------------------------------------- QTreeWidget* twoColumnTree(const QString& title1, const QString& title2) { auto tree = new QTreeWidget; tree->setColumnCount(2); tree->setAlternatingRowColors(true); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) tree->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); tree->header()->setSectionResizeMode(1, QHeaderView::Stretch); #else tree->header()->setResizeMode(0, QHeaderView::ResizeToContents); tree->header()->setResizeMode(1, QHeaderView::Stretch); #endif auto header = new QTreeWidgetItem(); header->setText(0, title1); header->setText(1, title2); tree->setHeaderItem(header); return tree; } //-------------------------------------------------------------------------------------------------- void stretchColumn(QTableView *table, int col) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) table->horizontalHeader()->setSectionResizeMode(col, QHeaderView::Stretch); #else table->horizontalHeader()->setResizeMode(col, QHeaderView::Stretch); #endif } void resizeColumnToContent(QTableView *table, int col) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) table->horizontalHeader()->setSectionResizeMode(col, QHeaderView::ResizeToContents); #else table->horizontalHeader()->setResizeMode(col, QHeaderView::ResizeToContents); #endif } //-------------------------------------------------------------------------------------------------- void toggleWidget(QWidget* panel) { if (panel->isVisible()) panel->hide(); else panel->show(); } //-------------------------------------------------------------------------------------------------- QSpinBox* spinBox(int min, int max, int value) { auto sb = new QSpinBox; sb->setMinimum(min); sb->setMaximum(max); if (value != 0) sb->setValue(value); return sb; } } // namespace Gui } // namespace Ori
28.998264
129
0.607136
Qt-Widgets
ffda0fe56d537ad66935f32afb7cb41aed0a6644
86
hpp
C++
Framework/Interface/Include/Interface.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
3
2021-03-30T09:02:56.000Z
2022-03-16T05:43:21.000Z
Framework/Interface/Include/Interface.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
null
null
null
Framework/Interface/Include/Interface.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
null
null
null
#pragma once #include "Common.hpp" #define Interface class #define implements public
14.333333
25
0.790698
Quanwei1992
ffdd3b4ee63371d21d5c4d1eb5f1ffb057f2d091
10,330
cpp
C++
src/ui_objectives.cpp
libtcod/pyromancer
ae4d4ad36246c0273fdc6e871e1f1bc72605dee4
[ "MIT" ]
null
null
null
src/ui_objectives.cpp
libtcod/pyromancer
ae4d4ad36246c0273fdc6e871e1f1bc72605dee4
[ "MIT" ]
null
null
null
src/ui_objectives.cpp
libtcod/pyromancer
ae4d4ad36246c0273fdc6e871e1f1bc72605dee4
[ "MIT" ]
null
null
null
/* * Copyright (c) 2010 Jice * 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. * * The name of Jice may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Jice ``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 Jice BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "main.hpp" #define OBJ_WIDTH (CON_W-4) #define OBJ_HEIGHT 40 Objective::Objective(const char *title, const char *description, const char *enableScript, const char *successScript, bool mainObjective) : title(title),description(description), enableScript(enableScript), successScript(successScript), onEnable(NULL), onSuccess(NULL), mainObjective(mainObjective) { if (enableScript) { onEnable = new Script(); onEnable->parse(enableScript); } if (successScript) { onSuccess = new Script(); onSuccess->parse(successScript); } } #define UPDATE_DELAY 3.0f Objectives::Objectives() : timer(0.0f),showWindow(false),firstObj(true) { saveGame.registerListener(OBJE_CHUNK_ID,PHASE_START,this); rect = UmbraRect(2,5,OBJ_WIDTH,OBJ_HEIGHT); con = new TCODConsole(OBJ_WIDTH,OBJ_HEIGHT); con->setDefaultBackground(guiBackground); guiTabs.addTab("Active"); guiTabs.addTab("Success"); guiTabs.addTab("Failure"); flags=DIALOG_CLOSABLE_NODISABLE; currentList=&active; scroller = new Scroller(this,OBJ_WIDTH/2-1,OBJ_HEIGHT-2); selected=0; } bool Objectives::executeObjScript(Objective *obj, Script *script) { currentObjective = obj; bool ret=script->execute(); currentObjective = NULL; return ret; } void Objectives::activateCurrent() { gameEngine->gui.log.warn("New objective : %s",currentObjective->title); if ( firstObj ) { gameEngine->gui.log.info("Press 'o' to open the objectives screen"); firstObj=false; } toActivate.push(currentObjective); } void Objectives::activateObjective(const char *title) { for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { if ( strcmp(title,(*it)->title) == 0 ) { gameEngine->gui.log.warn("New objective : %s",title); toActivate.push(*it); break; } } } void Objectives::closeCurrent(bool success) { gameEngine->gui.log.warn("Objective completed : %s (%s)",currentObjective->title, success ? "success":"failure"); if ( success ) { toSuccess.push(currentObjective); if ( currentObjective->mainObjective ) gameEngine->win=true; } else toFailure.push(currentObjective); } void Objectives::addStep(const char *msg, Objective *obj) { if (! obj ) obj = currentObjective; if (! toSuccess.contains( obj ) ) gameEngine->gui.log.warn("Objective updated : %s",obj->title); obj->steps.push(strdup(msg)); } void Objectives::render() { if (! showWindow ) return; con->clear(); con->setDefaultForeground(guiText); con->vline(OBJ_WIDTH/2,2,OBJ_HEIGHT-3); guiTabs.render(con,0,0); scroller->render(con,0,2); scroller->renderScrollbar(con,0,2); if ( currentList && selected < currentList->size() ) { con->setDefaultForeground(guiText); int y=2; Objective *objective=currentList->get(selected); y+=con->printRect(OBJ_WIDTH/2+2,y,OBJ_WIDTH/2-3,0,objective->description); for ( const char **step=objective->steps.begin(); step != objective->steps.end(); step ++ ) { y++; y+=con->printRect(OBJ_WIDTH/2+2,y,OBJ_WIDTH/2-3,0,*step); } } blitSemiTransparent(con,0,0,OBJ_WIDTH,OBJ_HEIGHT,TCODConsole::root,rect.x,rect.y,0.8f,1.0f); renderFrame(1.0f,"Objectives"); } int Objectives::getScrollTotalSize() { return currentList->size(); } const char *Objectives::getScrollText(int idx) { return currentList->get(idx)->title; } void Objectives::getScrollColor(int idx, TCODColor *fore, TCODColor *back) { *fore = idx == selected ? guiHighlightedText : guiText; *back = guiBackground; } bool Objectives::update(float elapsed, TCOD_key_t &k, TCOD_mouse_t &mouse) { if ( showWindow ) { flags |= DIALOG_MODAL; guiTabs.update(elapsed,k,mouse,rect.x,rect.y); scroller->update(elapsed,k,mouse,rect.x,rect.y+2); if ( mouse.cx >= rect.x && mouse.cx < rect.x+rect.w/2 && mouse.cy >= rect.y+2 && mouse.cy < rect.y+rect.h) { int newSelected = mouse.cy-rect.y-2; if ( currentList && newSelected < currentList->size() ) selected=newSelected; } switch(guiTabs.curTab) { case 0 : currentList = &active; break; case 1 : currentList = &success; break; case 2 : currentList = &failed; break; } if (closeButton.mouseHover && mouse.lbutton_pressed) { gameEngine->gui.setMode(GUI_NONE); } if ( (k.vk == TCODK_ESCAPE && ! k.pressed) ) { gameEngine->gui.setMode(GUI_NONE); } } else if ( wasShowingWindow) { flags &= ~DIALOG_MODAL; if ( gameEngine->gui.mode == GUI_NONE && gameEngine->isGamePaused() ) { gameEngine->resumeGame(); } } timer += elapsed; if ( timer < UPDATE_DELAY ) return true; timer = 0.0f; // check end conditions for active objectives for (Objective **it=active.begin(); it != active.end(); it++) { if (! (*it)->onSuccess ) toSuccess.push(*it); else if ( !executeObjScript(*it,(*it)->onSuccess) ) { // script execution failed. junk the objective failed.push(*it); it = active.removeFast(it); } } // check if new objectives are enabled for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { if ( ! (*it)->onEnable ) { toActivate.push(*it); gameEngine->gui.log.warn("New objective : %s",(*it)->title); if ( firstObj ) { gameEngine->gui.log.info("Press 'o' to open the objectives screen"); firstObj=false; } } else if ( !executeObjScript(*it,(*it)->onEnable) ) { // script execution failed. junk the objective failed.push(*it); it = sleeping.removeFast(it); } } for (Objective **it=toActivate.begin(); it != toActivate.end(); it++) { sleeping.removeFast(*it); active.push(*it); } toActivate.clear(); for (Objective **it=toSuccess.begin(); it != toSuccess.end(); it++) { active.removeFast(*it); success.push(*it); } toSuccess.clear(); for (Objective **it=toFailure.begin(); it != toFailure.end(); it++) { active.removeFast(*it); failed.push(*it); } toFailure.clear(); wasShowingWindow = showWindow; return true; } void Objectives::addObjective(Objective *obj) { sleeping.push(obj); } #define OBJE_CHUNK_VERSION 1 bool Objectives::loadData(uint32 chunkId, uint32 chunkVersion, TCODZip *zip) { if ( chunkVersion != OBJE_CHUNK_VERSION ) return false; showWindow = (zip->getChar()==1); firstObj = (zip->getChar()==1); int nbSleeping=zip->getInt(); while ( nbSleeping > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); const char *enableScript=zip->getString(); if (enableScript) enableScript=strdup(enableScript); const char *successScript=zip->getString(); if (successScript) successScript=strdup(successScript); Objective *obj = new Objective(title,description,enableScript,successScript); sleeping.push(obj); nbSleeping--; } int nbActive=zip->getInt(); while ( nbActive > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); const char *enableScript=zip->getString(); if (enableScript) enableScript=strdup(enableScript); const char *successScript=zip->getString(); if (successScript) successScript=strdup(successScript); Objective *obj = new Objective(title,description,enableScript,successScript); active.push(obj); nbActive--; } int nbSuccess=zip->getInt(); while ( nbSuccess > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); Objective *obj = new Objective(title,description); success.push(obj); nbSuccess--; } int nbFailed=zip->getInt(); while ( nbFailed > 0 ) { const char *title=strdup(zip->getString()); const char *description=strdup(zip->getString()); Objective *obj = new Objective(title,description); failed.push(obj); nbFailed--; } return true; } void Objectives::saveData(uint32 chunkId, TCODZip *zip) { saveGame.saveChunk(OBJE_CHUNK_ID,OBJE_CHUNK_VERSION); zip->putChar(showWindow ? 1:0); zip->putChar(firstObj ? 1:0); zip->putInt(sleeping.size()); for (Objective **it=sleeping.begin(); it != sleeping.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); zip->putString((*it)->enableScript); zip->putString((*it)->successScript); } zip->putInt(active.size()); for (Objective **it=active.begin(); it != active.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); zip->putString((*it)->enableScript); zip->putString((*it)->successScript); } zip->putInt(success.size()); for (Objective **it=success.begin(); it != success.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); } zip->putInt(failed.size()); for (Objective **it=failed.begin(); it != failed.end(); it++) { zip->putString((*it)->title); zip->putString((*it)->description); } }
34.318937
115
0.677735
libtcod
ffdf383dfac20dc2c8a34fd5e1d0258ad524b780
4,143
cpp
C++
3dc/avp/support/console_batch.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/support/console_batch.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/support/console_batch.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************* * * DESCRIPTION: consbtch.cpp * * AUTHOR: David Malcolm * * HISTORY: Created 8/4/98 * *******************************************************************/ /* Includes ********************************************************/ #include "3dc.h" #include "console_batch.hpp" #include "reflist.hpp" #define UseLocalAssert TRUE #include "ourasert.h" /* Version settings ************************************************/ /* Constants *******************************************************/ enum { MaxBatchFileLineLength=300, MaxBatchFileLineSize=(MaxBatchFileLineLength+1) }; /* Macros **********************************************************/ /* Imported function prototypes ************************************/ /* Imported data ***************************************************/ /* Exported globals ************************************************/ /* Internal type definitions ***************************************/ /* Internal function prototypes ************************************/ /* Internal globals ************************************************/ /* Exported function definitions ***********************************/ // class BatchFileProcessing // public: // static bool BatchFileProcessing :: Run(char* Filename) { // Tries to find the file, if it finds it it reads it, // adds the non-comment lines to the pending list, and returns TRUE // If it can't find the file, it returns FALSE // LOCALISEME // This code makes several uses of the assumption that char is type-equal // to ProjChar RefList<SCString> PendingList; { FILE *pFile = avp_open_userfile(Filename, "r"); if (NULL==pFile) { return FALSE; } // Read the file, line by line. { // We impose a maximum length on lines that will be valid: char LineBuffer[MaxBatchFileLineSize]; int CharsReadInLine = 0; while (1) { int Char = fgetc(pFile); if (Char==EOF) { break; } else { if ( Char=='\n' ) { // Flush the buffer into the pending queue: GLOBALASSERT(CharsReadInLine<=MaxBatchFileLineLength); LineBuffer[CharsReadInLine] = '\0'; SCString* pSCString_Line = new SCString(&LineBuffer[0]); PendingList . AddToEnd ( *pSCString_Line ); pSCString_Line -> R_Release(); CharsReadInLine = 0; } else { // Add to buffer; silently reject characters beyond the length limit if ( CharsReadInLine < MaxBatchFileLineLength ) { LineBuffer[CharsReadInLine++]=toupper((char)Char); } } } } // Flush anything still in the buffer into the pending queue: { GLOBALASSERT(CharsReadInLine<=MaxBatchFileLineLength); LineBuffer[CharsReadInLine] = '\0'; SCString* pSCString_Line = new SCString(&LineBuffer[0]); PendingList . AddToEnd ( *pSCString_Line ); pSCString_Line -> R_Release(); } } fclose(pFile); } // Feedback: { SCString* pSCString_1 = new SCString("EXECUTING BATCH FILE "); // LOCALISEME SCString* pSCString_2 = new SCString(Filename); SCString* pSCString_Feedback = new SCString ( pSCString_1, pSCString_2 ); pSCString_Feedback -> SendToScreen(); pSCString_Feedback -> R_Release(); pSCString_2 -> R_Release(); pSCString_1 -> R_Release(); } // Now process the pending queue: { // Iterate through the pending list, destructively reading the // "references" from the front: { SCString* pSCString; // The assignment in this boolean expression is deliberate: while ( NULL != (pSCString = PendingList . GetYourFirst()) ) { if (pSCString->pProjCh()[0] != '#') { // lines beginning with hash are comments if (bEcho) { pSCString -> SendToScreen(); } pSCString -> ProcessAnyCheatCodes(); } pSCString -> R_Release(); } } } return TRUE; } // public: // static int BatchFileProcessing :: bEcho = FALSE; /* Internal function definitions ***********************************/
21.691099
74
0.529809
Melanikus
ffdf398463e352be548f436b75d0ea6319815de1
1,679
hpp
C++
include/Nazara/VulkanRenderer/VulkanBuffer.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/VulkanRenderer/VulkanBuffer.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/VulkanRenderer/VulkanBuffer.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Vulkan Renderer" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_VULKANRENDERER_BUFFER_HPP #define NAZARA_VULKANRENDERER_BUFFER_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Utility/AbstractBuffer.hpp> #include <Nazara/VulkanRenderer/Config.hpp> #include <Nazara/VulkanRenderer/Wrapper/Buffer.hpp> #include <Nazara/VulkanRenderer/Wrapper/DeviceMemory.hpp> #include <Nazara/VulkanRenderer/Wrapper/Fence.hpp> #include <memory> #include <vector> namespace Nz { class NAZARA_VULKANRENDERER_API VulkanBuffer : public AbstractBuffer { public: inline VulkanBuffer(Vk::Device& device, BufferType type); VulkanBuffer(const VulkanBuffer&) = delete; VulkanBuffer(VulkanBuffer&&) = delete; ///TODO virtual ~VulkanBuffer(); bool Fill(const void* data, UInt64 offset, UInt64 size) override; bool Initialize(UInt64 size, BufferUsageFlags usage) override; inline VkBuffer GetBuffer(); UInt64 GetSize() const override; DataStorage GetStorage() const override; void* Map(BufferAccess access, UInt64 offset, UInt64 size) override; bool Unmap() override; VulkanBuffer& operator=(const VulkanBuffer&) = delete; VulkanBuffer& operator=(VulkanBuffer&&) = delete; ///TODO private: BufferType m_type; BufferUsageFlags m_usage; UInt64 m_size; VkBuffer m_buffer; VkBuffer m_stagingBuffer; VmaAllocation m_allocation; VmaAllocation m_stagingAllocation; Vk::Device& m_device; }; } #include <Nazara/VulkanRenderer/VulkanBuffer.inl> #endif // NAZARA_VULKANRENDERER_BUFFER_HPP
28.948276
77
0.767719
waruqi
ffe224c76c681907ddc262ae12752c359f23b872
3,600
hpp
C++
include/logi/memory/memory_allocator_impl.hpp
PrimozLavric/VulkanRenderer
6d95b8ec4b0133ce46b4b4e550d20ef17f77b2c4
[ "BSD-2-Clause" ]
6
2021-04-06T02:37:55.000Z
2021-11-24T06:14:04.000Z
include/logi/memory/memory_allocator_impl.hpp
PrimozLavric/Logi
6d95b8ec4b0133ce46b4b4e550d20ef17f77b2c4
[ "BSD-2-Clause" ]
null
null
null
include/logi/memory/memory_allocator_impl.hpp
PrimozLavric/Logi
6d95b8ec4b0133ce46b4b4e550d20ef17f77b2c4
[ "BSD-2-Clause" ]
null
null
null
/** * Project Logi source code * Copyright (C) 2019 Primoz Lavric * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #ifndef LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP #define LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP #include <optional> #include <vk_mem_alloc.h> #include "logi/base/common.hpp" #include "logi/base/vulkan_object.hpp" namespace logi { class VulkanInstanceImpl; class PhysicalDeviceImpl; class LogicalDeviceImpl; class VMABufferImpl; class VMAImageImpl; class VMAAccelerationStructureNVImpl; class MemoryAllocatorImpl : public VulkanObject, public std::enable_shared_from_this<MemoryAllocatorImpl>, public VulkanObjectComposite<VMABufferImpl>, public VulkanObjectComposite<VMAImageImpl>, public VulkanObjectComposite<VMAAccelerationStructureNVImpl> { public: explicit MemoryAllocatorImpl(LogicalDeviceImpl& logicalDevice, vk::DeviceSize preferredLargeHeapBlockSize = 0u, uint32_t frameInUseCount = 0u, const std::vector<vk::DeviceSize>& heapSizeLimits = {}, const std::optional<vk::AllocationCallbacks>& allocator = {}); // region Sub handles const std::shared_ptr<VMABufferImpl>& createBuffer(const vk::BufferCreateInfo& bufferCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator); void destroyBuffer(size_t id); const std::shared_ptr<VMAImageImpl>& createImage(const vk::ImageCreateInfo& imageCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator = {}); void destroyImage(size_t id); const std::shared_ptr<VMAAccelerationStructureNVImpl>& createAccelerationStructureNV(const vk::AccelerationStructureCreateInfoNV& accelerationStructureCreateInfo, const VmaAllocationCreateInfo& allocationCreateInfo, const std::optional<vk::AllocationCallbacks>& allocator = {}); void destroyAccelerationStructureNV(size_t id); // endregion // region Logi Declarations VulkanInstanceImpl& getInstance() const; PhysicalDeviceImpl& getPhysicalDevice() const; LogicalDeviceImpl& getLogicalDevice() const; const vk::DispatchLoaderDynamic& getDispatcher() const; operator const VmaAllocator&() const; void destroy() const; protected: void free() override; // endregion private: LogicalDeviceImpl& logicalDevice_; std::optional<vk::AllocationCallbacks> allocator_; VmaAllocator vma_; }; } // namespace logi #endif // LOGI_MEMORY_MEMORY_ALLOCATOR_IMPL_HPP
37.113402
118
0.6725
PrimozLavric
ffe228198955a3e4838e783ead228d2d5c36ebfe
3,471
hpp
C++
include/shadertoy/buffers/gl_buffer.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
2
2020-02-23T09:33:07.000Z
2021-11-15T18:23:13.000Z
include/shadertoy/buffers/gl_buffer.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
2
2019-08-09T15:48:07.000Z
2020-11-16T13:51:56.000Z
include/shadertoy/buffers/gl_buffer.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
3
2019-12-12T09:42:34.000Z
2020-12-14T03:56:30.000Z
#ifndef _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ #define _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ #include "shadertoy/pre.hpp" #include "shadertoy/buffers/basic_buffer.hpp" #include "shadertoy/gl/framebuffer.hpp" #include "shadertoy/gl/renderbuffer.hpp" namespace shadertoy { namespace buffers { /** * @brief Represents a buffer in a swap chain. Rendering is done using a framebuffer. * * This class instantiates a framebuffer and a renderbuffer which are bound * before rendering the contents of this buffer. */ class gl_buffer : public basic_buffer { /// Target framebuffer gl::framebuffer target_fbo_; /// Target renderbuffer gl::renderbuffer target_rbo_; protected: /** * @brief Initialize a new gl_buffer * * @param[in] id Identifier for this buffer */ gl_buffer(const std::string &id); /** * @brief Initialize the contents of the buffer for rendering. * * @param[in] context Rendering context to use for shared objects * @param[in] io IO resource object */ void init_contents(const render_context &context, const io_resource &io) override; /** * @brief Initialize the renderbuffer object for the new specified size. * * @param[in] context Rendering context to use for shared objects * @param[in] io IO resource object */ void allocate_contents(const render_context &context, const io_resource &io) override; /** * @brief Render the contents of this buffer. This methods binds the * framebuffer and renderbuffer to the appropriate texture for * rendering, and then calls render_gl_contents as defined by * the derived class. * * @param[in] context Rendering context to use for rendering this buffer * @param[in] io IO resource object * @param[in] member Current swap-chain member */ void render_contents(const render_context &context, const io_resource &io, const members::buffer_member &member) final; /** * @brief Render the contents of this buffer to the currently bound * framebuffer and renderbuffer. This method must be implemented * by derived classes as part of their rendering routine. * * @param[in] context Rendering context to use for rendering this buffer * @param[in] io IO resource object */ virtual void render_gl_contents(const render_context &context, const io_resource &io) = 0; /** * @brief Binds the given texture to the target framebuffer object * for rendering. This method may be overridden by derived classes * in order to control the binding process. The default behavior is * to bind the first layer of the texture object to the first color attachment. * * @param[in] target_fbo Target framebuffer bound object * @param[in] io IO resource object containing the target textures to bind */ virtual void attach_framebuffer_outputs(const gl::bind_guard<gl::framebuffer, GLint> &target_fbo, const io_resource &io); public: /** * @brief Obtain this buffer's GL framebuffer object * * @return Reference to the framebuffer object */ inline const gl::framebuffer &target_fbo() const { return target_fbo_; } /** * @brief Obtain this buffer's GL renderbuffer object * * @return Reference to the renderbuffer object */ inline const gl::renderbuffer &target_rbo() const { return target_rbo_; } }; } } #endif /* _SHADERTOY_BUFFERS_BUFFER_BASE_HPP_ */
31.554545
98
0.706425
vtavernier
ffe45838ae7f55a986ad5fce27c0ffff3ae7ab0c
2,017
cpp
C++
hackerrank/Algorithms/ArraysAndSorting/BoardCutting/BoardCutting.cpp
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
null
null
null
hackerrank/Algorithms/ArraysAndSorting/BoardCutting/BoardCutting.cpp
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
null
null
null
hackerrank/Algorithms/ArraysAndSorting/BoardCutting/BoardCutting.cpp
everyevery/programming_study
ff35e97e13953e4d7a26591f7cdb301d3e8e36c6
[ "MIT" ]
1
2017-04-01T21:34:23.000Z
2017-04-01T21:34:23.000Z
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int T; cin >> T; while (T--) { int M, N; int m = 1, n=1; long long input, output=0; vector<long long> MS, NS; cin >> M >> N; M--; N--; while (M--) { cin >> input; MS.push_back(input); } while (N--) { cin >> input; NS.push_back(input); } sort(MS.begin(), MS.end(), [] (long long x, long long y) {return x>y;}); sort(NS.begin(), NS.end(), [] (long long x, long long y) {return x>y;}); vector<long long>::iterator mi = MS.begin(), ni = NS.begin(); while (true) { if (mi == MS.end() && ni == NS.end()) { //cerr << "<END>" << endl; output %= 1000000007; break; } else if (mi == MS.end()) { output += ((*ni * m) % 1000000007); //cerr << "<ONLY N> ni:" << *ni << ", m:" << m << ", output:" << output << endl; ni++; n++; } else if (ni == NS.end()) { output += ((*mi * n) % 1000000007); //cerr << "<ONLY M> *mi:" << *mi << ", n:" << n << ", output:" << output << endl; mi++; m++; } else if (*mi >= *ni) { //cerr << "<M>=N> *mi:" << *mi << ", *ni:" << *ni << "n:" << n << ", output:" << output << endl; output += ((*mi * n) % 1000000007); mi++; m++; } else { //cerr << "<M<N> *mi:" << *mi << ", *ni:" << *ni << ", m:" << m << ", output:" << output << endl; output += ((*ni * m) % 1000000007); ni++; n++; } } cout << output << endl; } return 0; }
29.231884
113
0.337134
everyevery
ffe4c7d2f4624d5ceae6c76c5f196d9b46632646
3,686
cpp
C++
graphic_lite/ui/animator_posix/src/animator_test.cpp
chaoyangcui/xts_acts
3ea7c32929c9260f081cda97f6630ac9b14ab3fd
[ "Apache-2.0" ]
null
null
null
graphic_lite/ui/animator_posix/src/animator_test.cpp
chaoyangcui/xts_acts
3ea7c32929c9260f081cda97f6630ac9b14ab3fd
[ "Apache-2.0" ]
null
null
null
graphic_lite/ui/animator_posix/src/animator_test.cpp
chaoyangcui/xts_acts
3ea7c32929c9260f081cda97f6630ac9b14ab3fd
[ "Apache-2.0" ]
1
2021-09-13T12:04:33.000Z
2021-09-13T12:04:33.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "animator/animator.h" #include <climits> #include <gtest/gtest.h> using namespace std; using namespace testing::ext; namespace OHOS { class AnimatorTest : public testing::Test { public: static void SetUpTestCase(void) { if (animator == nullptr) { animator = new Animator(); } } static void TearDownTestCase(void) { if (animator != nullptr) { delete animator; animator = nullptr; } } static Animator* animator; }; Animator* AnimatorTest::animator = nullptr; /** * @tc.number SUB_GRAPHIC_ANIMATOR_START_0100 * @tc.name test animator start api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_Start_0100, Function | MediumTest | Level0) { animator->Start(); EXPECT_EQ(animator->GetState(), Animator::START); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_STOP_0200 * @tc.name test animator stop api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_Stop_0200, Function | MediumTest | Level0) { animator->Stop(); EXPECT_EQ(animator->GetState(), Animator::STOP); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_PAUSE_0300 * @tc.name test animator pause api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_Pause_0300, Function | MediumTest | Level0) { animator->Pause(); EXPECT_EQ(animator->GetState(), Animator::PAUSE); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_RESUME_0400 * @tc.name test animator resume api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_Resume_0400, Function | MediumTest | Level0) { animator->Resume(); EXPECT_EQ(animator->GetState(), Animator::START); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_SETSTATE_0500 * @tc.name test animator set-state api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_SetState_0500, Function | MediumTest | Level0) { animator->SetState(Animator::START); EXPECT_EQ(animator->GetState(), Animator::START); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_SETTIME_0600 * @tc.name test animator set-time api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_SetTime_0600, Function | MediumTest | Level0) { uint16_t time = 300; animator->SetTime(time); EXPECT_EQ(animator->GetTime(), time); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_SETRUNTIME_0700 * @tc.name test animator set-runtime api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_SetRunTime_0700, Function | MediumTest | Level0) { uint16_t time = 300; animator->SetRunTime(time); EXPECT_EQ(animator->GetRunTime(), time); } /** * @tc.number SUB_GRAPHIC_ANIMATOR_ISRPEAT_0800 * @tc.name test animator if-repeat api * @tc.desc [C- SOFTWARE -0200] */ HWTEST_F(AnimatorTest, Graphic_Animator_Test_IsRepeat_0800, Function | MediumTest | Level0) { EXPECT_EQ(animator->IsRepeat(), false); } } // namespace OHOS
28.137405
93
0.692892
chaoyangcui
ffe909a24d7d0210f35e0c656492d31145d7a02e
17,525
cpp
C++
core/src/command/mgcmdmgr.cpp
rhcad/touchvg-v0.6
8b349ecd66b2363eec96e20873267aad9ed67ff1
[ "RSA-MD" ]
1
2016-06-14T06:22:50.000Z
2016-06-14T06:22:50.000Z
core/src/command/mgcmdmgr.cpp
rhcad/touchvg-v0.6
8b349ecd66b2363eec96e20873267aad9ed67ff1
[ "RSA-MD" ]
null
null
null
core/src/command/mgcmdmgr.cpp
rhcad/touchvg-v0.6
8b349ecd66b2363eec96e20873267aad9ed67ff1
[ "RSA-MD" ]
null
null
null
// mgcmdmgr.cpp: 实现命令管理器类 // Copyright (c) 2004-2012, Zhang Yungui // License: LGPL, https://github.com/rhcad/touchvg #include "mgcmdmgr.h" #include "mgcmdselect.h" #include <mggrid.h> MgCommand* mgCreateCoreCommand(const char* name); float mgDisplayMmToModel(float mm, GiGraphics* gs); float mgDisplayMmToModel(float mm, const MgMotion* sender); typedef std::map<std::string, MgCommand* (*)()> Factories; static Factories _factories; static MgCmdManagerImpl* s_manager = NULL; static MgCmdManagerImpl s_tmpmgr(true); void mgRegisterCommand(const char* name, MgCommand* (*factory)()) { if (!factory) { _factories.erase(name); } else { _factories[name] = factory; } } MgCommandManager* mgGetCommandManager() { return s_manager ? s_manager : &s_tmpmgr; } MgCmdManagerImpl::MgCmdManagerImpl(bool tmpobj) { if (!s_manager && !tmpobj) s_manager = this; } MgCmdManagerImpl::~MgCmdManagerImpl() { unloadCommands(); if (s_manager == this) s_manager = NULL; } void MgCmdManagerImpl::unloadCommands() { for (CMDS::iterator it = _cmds.begin(); it != _cmds.end(); ++it) it->second->release(); _cmds.clear(); _cmdname = ""; } const char* MgCmdManagerImpl::getCommandName() { MgCommand* cmd = getCommand(); return cmd ? cmd->getName() : ""; } MgCommand* MgCmdManagerImpl::getCommand() { CMDS::iterator it = _cmds.find(_cmdname); return it != _cmds.end() ? it->second : NULL; } MgCommand* MgCmdManagerImpl::findCommand(const char* name) { CMDS::iterator it = _cmds.find(name); if (it == _cmds.end() && *name) { MgCommand* cmd = NULL; Factories::iterator itf = _factories.find(name); if (itf != _factories.end()) { cmd = itf->second ? (itf->second)() : NULL; } if (!cmd) { cmd = mgCreateCoreCommand(name); } if (cmd) { _cmds[name] = cmd; it = _cmds.find(name); } } return it != _cmds.end() ? it->second : NULL; } bool MgCmdManagerImpl::setCommand(const MgMotion* sender, const char* name) { if (strcmp(name, "erase") == 0) { MgSelection *sel = getSelection(sender->view); if (sel && sel->deleteSelection(sender->view)) return false; } cancel(sender); if (strcmp(name, "@draw") == 0) { name = _drawcmd.empty() ? "splines" : _drawcmd.c_str(); } MgCommand* cmd = findCommand(name); bool ret = false; if (cmd) { std::string oldname(_cmdname); _cmdname = cmd->getName(); ret = cmd->initialize(sender); if (!ret) { _cmdname = oldname; } else if (cmd->isDrawingCommand()) { _drawcmd = _cmdname; } } else { if (strcmp(name, "erasewnd") == 0) { eraseWnd(sender); } else { _cmdname = ""; } } return ret; } bool MgCmdManagerImpl::cancel(const MgMotion* sender) { clearSnap(); CMDS::iterator it = _cmds.find(_cmdname); if (it != _cmds.end()) { return it->second->cancel(sender); } return false; } int MgCmdManagerImpl::getSelection(MgView* view, int count, MgShape** shapes, bool forChange) { if (_cmdname == MgCmdSelect::Name() && view) { MgCmdSelect* sel = (MgCmdSelect*)getCommand(); return sel ? sel->getSelection(view, count, shapes, forChange) : 0; } return 0; } bool MgCmdManagerImpl::dynamicChangeEnded(MgView* view, bool apply) { bool changed = false; if (_cmdname == MgCmdSelect::Name() && view) { MgCmdSelect* sel = (MgCmdSelect*)getCommand(); changed = sel && sel->dynamicChangeEnded(view, apply); } return changed; } MgSelection* MgCmdManagerImpl::getSelection(MgView*) { return (MgCmdSelect*)findCommand(MgCmdSelect::Name()); } MgActionDispatcher* MgCmdManagerImpl::getActionDispatcher() { return this; } void MgCmdManagerImpl::doContextAction(const MgMotion* sender, int action) { doAction(sender, action); } MgSnap* MgCmdManagerImpl::getSnap() { return this; } class SnapItem { public: Point2d pt; // 捕捉到的坐标 Point2d base; // 参考线基准点、原始点 float dist; // 捕捉距离 int type; // 特征点类型 int shapeid; // 捕捉到的图形 int handleIndex; // 捕捉到图形上的控制点序号 int handleIndexSrc; // 待确定位置的源图形上的控制点序号,与handleIndex点匹配 SnapItem() {} SnapItem(const Point2d& _pt, const Point2d& _base, float _dist, int _type = 0, int _shapeid = 0, int _handleIndex = -1, int _handleIndexSrc = -1) : pt(_pt), base(_base), dist(_dist), type(_type), shapeid(_shapeid) , handleIndex(_handleIndex), handleIndexSrc(_handleIndexSrc) {} }; static int snapHV(const Point2d& basePt, Point2d& newPt, SnapItem arr[3]) { int ret = 0; float diff; diff = arr[1].dist - fabsf(newPt.x - basePt.x); if (diff > _MGZERO || (diff > - _MGZERO && fabsf(newPt.y - basePt.y) < fabsf(newPt.y - arr[1].base.y))) { arr[1].dist = fabsf(newPt.x - basePt.x); arr[1].base = basePt; newPt.x = basePt.x; arr[1].pt = newPt; arr[1].type = kSnapSameX; ret |= 1; } diff = arr[2].dist - fabsf(newPt.y - basePt.y); if (diff > _MGZERO || (diff > - _MGZERO && fabsf(newPt.x - basePt.x) < fabsf(newPt.x - arr[2].base.x))) { arr[2].dist = fabsf(newPt.y - basePt.y); arr[2].base = basePt; newPt.y = basePt.y; arr[2].pt = newPt; arr[2].type = kSnapSameY; ret |= 2; } return ret; } static void snapPoints(const MgMotion* sender, const MgShape* shape, int ignoreHandle, const int* ignoreids, SnapItem arr[3], Point2d* matchpt) { Box2d snapbox(sender->pointM, 2 * arr[0].dist, 0); // 捕捉容差框 GiTransform* xf = sender->view->xform(); Box2d wndbox(xf->getWndRectW() * xf->worldToModel()); // 视图模型坐标范围 void* it = NULL; for (const MgShape* sp = sender->view->shapes()->getFirstShape(it); sp; sp = sender->view->shapes()->getNextShape(it)) { bool skip = false; for (int t = 0; ignoreids[t] != 0 && !skip; t++) { skip = (ignoreids[t] == sp->getID()); // 跳过当前图形 } if (skip) continue; Box2d extent(sp->shapec()->getExtent()); if (extent.width() < xf->displayToModel(2, true) && extent.height() < xf->displayToModel(2, true)) { // 图形太小就跳过 continue; } bool allOnBox = extent.isIntersect(snapbox); // 不是整体拖动图形 if (allOnBox || extent.isIntersect(wndbox)) { // 或者在视图内可能单向捕捉 int n = sp->shapec()->getHandleCount(); bool curve = sp->shapec()->isKindOf(MgSplines::Type()); bool dragHandle = (!shape || shape->getID() == 0 || sender->pointM == shape->shapec()->getHandlePoint(ignoreHandle)); for (int i = 0; i < n; i++) { // 循环每一个控制点 if (curve && ((i > 0 && i + 1 < n) || sp->shapec()->isClosed())) { continue; // 对于开放曲线只捕捉端点 } Point2d pnt(sp->shapec()->getHandlePoint(i)); // 已有图形的一个顶点 if (allOnBox) { float dist = pnt.distanceTo(sender->pointM); // 触点与顶点匹配 if (arr[0].dist > dist) { arr[0].dist = dist; arr[0].base = sender->pointM; arr[0].pt = pnt; arr[0].type = kSnapPoint; arr[0].shapeid = sp->getID(); arr[0].handleIndex = i; arr[0].handleIndexSrc = dragHandle ? ignoreHandle : -1; } } if (!matchpt && !curve && wndbox.contains(pnt)) { // 在视图可见范围内捕捉X或Y Point2d newPt (sender->pointM); snapHV(pnt, newPt, arr); } int d = matchpt && shape ? (int)shape->shapec()->getHandleCount() - 1 : -1; for (; d >= 0; d--) { // 整体移动图形,顶点匹配 if (d == ignoreHandle || shape->shapec()->isHandleFixed(d)) continue; Point2d ptd (shape->shapec()->getHandlePoint(d)); float dist = pnt.distanceTo(ptd); // 当前图形与其他图形顶点匹配 if (arr[0].dist > dist - _MGZERO) { arr[0].dist = dist; arr[0].base = ptd; arr[0].pt = pnt; arr[0].type = kSnapPoint; arr[0].shapeid = sp->getID(); arr[0].handleIndex = i; arr[0].handleIndexSrc = d; // 因为对当前图形先从startM移到pointM,然后再从pointM移到matchpt *matchpt = sender->pointM + (pnt - ptd); // 所以最后差量为(pnt-ptd) } } } if (allOnBox && sp->shapec()->isKindOf(MgGrid::Type())) { Point2d newPt (sender->pointM); const MgGrid* grid = (const MgGrid*)(sp->shapec()); int type = grid->snap(newPt, arr[1].dist, arr[2].dist); if (type & 1) { arr[1].base = newPt; arr[1].pt = newPt; arr[1].type = kSnapGridX; } if (type & 2) { arr[2].base = newPt; arr[2].pt = newPt; arr[2].type = kSnapGridY; } int d = matchpt && shape ? (int)shape->shapec()->getHandleCount() - 1 : -1; for (; d >= 0; d--) { if (d == ignoreHandle || shape->shapec()->isHandleFixed(d)) continue; Point2d ptd (shape->shapec()->getHandlePoint(d)); float distx = mgMin(arr[0].dist, arr[1].dist); float disty = mgMin(arr[0].dist, arr[2].dist); newPt = ptd; type = grid->snap(newPt, distx, disty); float dist = newPt.distanceTo(ptd); if ((type & 3) == 3 && arr[0].dist > dist - _MGZERO) { arr[0].dist = dist; arr[0].base = ptd; arr[0].pt = newPt; arr[0].type = kSnapPoint; arr[0].shapeid = sp->getID(); arr[0].handleIndex = -1; arr[0].handleIndexSrc = d; // 因为对当前图形先从startM移到pointM,然后再从pointM移到matchpt *matchpt = sender->pointM + (newPt - ptd); // 所以最后差量为(pnt-ptd) } } } } } sender->view->shapes()->freeIterator(it); } // hotHandle: 绘新图时,起始步骤为-1,后续步骤>0;拖动一个或多个整体图形时为-1,拖动顶点时>=0 Point2d MgCmdManagerImpl::snapPoint(const MgMotion* sender, const MgShape* shape, int hotHandle, int ignoreHandle, const int* ignoreids) { int ignoreids_tmp[2] = { shape ? shape->getID() : 0, 0 }; if (!ignoreids) ignoreids = ignoreids_tmp; if (!shape || hotHandle >= (int)shape->shapec()->getHandleCount()) { hotHandle = -1; // 对hotHandle进行越界检查 } _ptSnap = sender->pointM; // 默认结果为当前触点位置 SnapItem arr[3] = { // 设置捕捉容差和捕捉初值 SnapItem(_ptSnap, _ptSnap, mgDisplayMmToModel(3.f, sender)), // XY点捕捉 SnapItem(_ptSnap, _ptSnap, mgDisplayMmToModel(2.f, sender)), // X分量捕捉,竖直线 SnapItem(_ptSnap, _ptSnap, mgDisplayMmToModel(2.f, sender)), // Y分量捕捉,水平线 }; if (shape && shape->getID() == 0 && hotHandle > 0 // 绘图命令中的临时图形 && !shape->shapec()->isKindOf(MgBaseRect::Type())) { // 不是矩形或椭圆 Point2d pt (sender->pointM); if (0 == snapHV(shape->shapec()->getPoint(hotHandle - 1), pt, arr)) { // 和上一个点对齐 float dist = pt.distanceTo(shape->shapec()->getPoint(0)); if (arr[0].dist > dist) { arr[0].dist = dist; arr[0].type = kSnapPoint; arr[0].pt = shape->shapec()->getPoint(0); } } } Point2d pnt(-1e10f, -1e10f); // 当前图形的某一个顶点匹配到其他顶点pnt bool matchpt = (shape && shape->getID() != 0 // 拖动整个图形 && (hotHandle < 0 || (ignoreHandle >= 0 && ignoreHandle != hotHandle))); snapPoints(sender, shape, ignoreHandle, ignoreids, arr, matchpt ? &pnt : NULL); // 在所有图形中捕捉 if (arr[0].type > 0) { // X和Y方向同时捕捉到一个点 _ptSnap = arr[0].pt; // 结果点 _snapBase[0] = arr[0].base; // 原始点 _snapType[0] = arr[0].type; _snapShapeId = arr[0].shapeid; _snapHandle = arr[0].handleIndex; _snapHandleSrc = arr[0].handleIndexSrc; } else { _snapShapeId = 0; _snapHandle = -1; _snapHandleSrc = -1; _snapType[0] = arr[1].type; // 竖直方向捕捉到一个点 if (arr[1].type > 0) { _ptSnap.x = arr[1].pt.x; _snapBase[0] = arr[1].base; } _snapType[1] = arr[2].type; // 水平方向捕捉到一个点 if (arr[2].type > 0) { _ptSnap.y = arr[2].pt.y; _snapBase[1] = arr[2].base; } } return matchpt && pnt.x > -1e8f ? pnt : _ptSnap; // 顶点匹配优先于用触点捕捉结果 } int MgCmdManagerImpl::getSnappedType() { if (_snapType[0] >= kSnapPoint) return _snapType[0]; return (_snapType[0] == kSnapGridX && _snapType[1] == kSnapGridY) ? kSnapPoint : 0; } int MgCmdManagerImpl::getSnappedPoint(Point2d& fromPt, Point2d& toPt) { fromPt = _snapBase[0]; toPt = _ptSnap; return getSnappedType(); } bool MgCmdManagerImpl::getSnappedHandle(int& shapeid, int& handleIndex, int& handleIndexSrc) { shapeid = _snapShapeId; handleIndex = _snapHandle; handleIndexSrc = _snapHandleSrc; return shapeid != 0; } void MgCmdManagerImpl::clearSnap() { _snapType[0] = 0; _snapType[1] = 0; } bool MgCmdManagerImpl::drawSnap(const MgMotion* sender, GiGraphics* gs) { bool ret = false; if (sender->dragging || !sender->view->useFinger()) { if (_snapType[0] >= kSnapPoint) { GiContext ctx(-2, GiColor(0, 255, 0, 200), kGiLineDash, GiColor(0, 255, 0, 64)); ret = gs->drawEllipse(&ctx, _ptSnap, mgDisplayMmToModel(6.f, gs)); } else { GiContext ctx(0, GiColor(0, 255, 0, 200), kGiLineDash, GiColor(0, 255, 0, 64)); GiContext ctxcross(-2, GiColor(0, 255, 0, 200)); if (_snapType[0] > 0) { if (_snapBase[0] == _ptSnap) { if (_snapType[0] == kSnapGridX) { Vector2d vec(0, mgDisplayMmToModel(15.f, gs)); ret = gs->drawLine(&ctxcross, _ptSnap - vec, _ptSnap + vec); gs->drawEllipse(&ctx, _snapBase[0], mgDisplayMmToModel(4.f, gs)); } } else { // kSnapSameX ret = gs->drawLine(&ctx, _snapBase[0], _ptSnap); gs->drawEllipse(&ctx, _snapBase[0], mgDisplayMmToModel(2.5f, gs)); } } if (_snapType[1] > 0) { if (_snapBase[1] == _ptSnap) { if (_snapType[1] == kSnapGridY) { Vector2d vec(mgDisplayMmToModel(15.f, gs), 0); ret = gs->drawLine(&ctxcross, _ptSnap - vec, _ptSnap + vec); gs->drawEllipse(&ctx, _snapBase[1], mgDisplayMmToModel(4.f, gs)); } } else { // kSnapSameY ret = gs->drawLine(&ctx, _snapBase[1], _ptSnap); gs->drawEllipse(&ctx, _snapBase[1], mgDisplayMmToModel(2.5f, gs)); } } } } return ret; } void MgCmdManagerImpl::eraseWnd(const MgMotion* sender) { Box2d snap(sender->view->xform()->getWndRectW() * sender->view->xform()->worldToModel()); std::vector<int> delIds; void *it = NULL; MgShapes* s = sender->view->shapes(); for (MgShape* shape = s->getFirstShape(it); shape; shape = s->getNextShape(it)) { if (shape->shape()->hitTestBox(snap)) { delIds.push_back(shape->getID()); } } s->freeIterator(it); if (!delIds.empty() && sender->view->shapeWillDeleted(s->findShape(delIds.front()))) { MgShapesLock locker(sender->view->doc(), MgShapesLock::Remove); for (std::vector<int>::iterator i = delIds.begin(); i != delIds.end(); ++i) { MgShape* shape = s->findShape(*i); if (shape && sender->view->removeShape(shape)) { shape->release(); } } sender->view->regen(); } }
34.095331
93
0.501227
rhcad
ffe96e028921f63424cde35edfe0a0cf2b4a093f
7,019
cxx
C++
src/Cxx/Utilities/SaveSceneToFile.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/Utilities/SaveSceneToFile.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/Utilities/SaveSceneToFile.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkActor.h> #include <vtkBYUReader.h> #include <vtkCamera.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkOBJReader.h> #include <vtkPLYReader.h> #include <vtkPolyDataMapper.h> #include <vtkPolyDataReader.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkSTLReader.h> #include <vtkSmartPointer.h> #include <vtkSphereSource.h> #include <vtkTimerLog.h> #include <vtkXMLPolyDataReader.h> #include <vtksys/RegularExpression.hxx> #include <vtksys/SystemTools.hxx> namespace { vtkSmartPointer<vtkPolyData> ReadPolyData(const char* fileName); } #include <vtkActor.h> #include <vtkCamera.h> namespace { void SaveSceneToFile(std::string fileName, vtkActor* actor, vtkCamera* camera); } #include <vtkActor.h> #include <vtkCamera.h> namespace { void RestoreSceneFromFile(std::string fileName, vtkActor* actor, vtkCamera* camera); } int main(int argc, char* argv[]) { auto polyData = ReadPolyData(argc > 1 ? argv[1] : ""); // Visualize vtkNew<vtkNamedColors> colors; vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputData(polyData); vtkNew<vtkActor> actor; actor->SetMapper(mapper); actor->GetProperty()->SetDiffuseColor( colors->GetColor3d("Crimson").GetData()); actor->GetProperty()->SetSpecular(.6); actor->GetProperty()->SetSpecularPower(30); ; vtkNew<vtkRenderer> renderer; vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); vtkNew<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(actor); renderer->SetBackground(colors->GetColor3d("Silver").GetData()); // Interact to change camera renderWindow->Render(); renderWindowInteractor->Start(); // After the interaction is done, save the scene SaveSceneToFile(argv[2], actor, renderer->GetActiveCamera()); renderWindow->Render(); renderWindowInteractor->Start(); // After interaction , restore the scene RestoreSceneFromFile(argv[2], actor, renderer->GetActiveCamera()); renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } namespace { #include <fstream> void SaveSceneToFile(std::string fileName, vtkActor* /* actor */, vtkCamera* camera) { // Actor // Position, orientation, origin, scale, usrmatrix, usertransform // Camera // FocalPoint, Position, ViewUp, ViewAngle, ClippingRange std::ofstream saveFile(fileName, std::ofstream::out); double vector[3]; double scalar; camera->GetFocalPoint(vector); saveFile << "Camera:FocalPoint " << vector[0] << ", " << vector[1] << ", " << vector[2] << std::endl; camera->GetPosition(vector); saveFile << "Camera:Position " << vector[0] << ", " << vector[1] << ", " << vector[2] << std::endl; camera->GetViewUp(vector); saveFile << "Camera:ViewUp " << vector[0] << ", " << vector[1] << ", " << vector[2] << std::endl; scalar = camera->GetViewAngle(); saveFile << "Camera:ViewAngle " << scalar << std::endl; camera->GetClippingRange(vector); saveFile << "Camera:ClippingRange " << vector[0] << ", " << vector[1] << std::endl; saveFile.close(); } } // namespace namespace { #include <fstream> void RestoreSceneFromFile(std::string fileName, vtkActor* /* actor */, vtkCamera* camera) { std::ifstream saveFile(fileName); std::string line; vtksys::RegularExpression reCP("^Camera:Position"); vtksys::RegularExpression reCFP("^Camera:FocalPoint"); vtksys::RegularExpression reCVU("^Camera:ViewUp"); vtksys::RegularExpression reCVA("^Camera:ViewAngle"); vtksys::RegularExpression reCCR("^Camera:ClippingRange"); vtksys::RegularExpression floatNumber( "[^0-9\\.\\-]*([0-9e\\.\\-]*[^,])[^0-9\\.\\-]*([0-9e\\.\\-]*[^,])[^0-9\\." "\\-]*([0-9e\\.\\-]*[^,])"); vtksys::RegularExpression floatScalar("[^0-9\\.\\-]*([0-9\\.\\-e]*[^,])"); while (std::getline(saveFile, line) && !saveFile.eof()) { if (reCFP.find(line)) { std::string rest(line, reCFP.end()); if (floatNumber.find(rest)) { camera->SetFocalPoint(atof(floatNumber.match(1).c_str()), atof(floatNumber.match(2).c_str()), atof(floatNumber.match(3).c_str())); } } else if (reCP.find(line)) { std::string rest(line, reCP.end()); if (floatNumber.find(rest)) { camera->SetPosition(atof(floatNumber.match(1).c_str()), atof(floatNumber.match(2).c_str()), atof(floatNumber.match(3).c_str())); } } else if (reCVU.find(line)) { std::string rest(line, reCVU.end()); if (floatNumber.find(rest)) { camera->SetViewUp(atof(floatNumber.match(1).c_str()), atof(floatNumber.match(2).c_str()), atof(floatNumber.match(3).c_str())); } } else if (reCVA.find(line)) { std::string rest(line, reCVA.end()); if (floatScalar.find(rest)) { camera->SetViewAngle(atof(floatScalar.match(1).c_str())); } } else if (reCCR.find(line)) { std::string rest(line, reCCR.end()); if (floatNumber.find(rest)) { camera->SetClippingRange(atof(floatNumber.match(1).c_str()), atof(floatNumber.match(2).c_str())); } } else { std::cout << "Unrecognized line: " << line << std::endl; } } saveFile.close(); } } // namespace namespace { vtkSmartPointer<vtkPolyData> ReadPolyData(const char* fileName) { vtkSmartPointer<vtkPolyData> polyData; std::string extension = vtksys::SystemTools::GetFilenameExtension(std::string(fileName)); if (extension == ".ply") { vtkNew<vtkPLYReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".vtp") { vtkNew<vtkXMLPolyDataReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".obj") { vtkNew<vtkOBJReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".stl") { vtkNew<vtkSTLReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".vtk") { vtkNew<vtkPolyDataReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".g") { vtkNew<vtkBYUReader> reader; reader->SetGeometryFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else { vtkNew<vtkSphereSource> source; source->Update(); polyData = source->GetOutput(); } return polyData; } } // namespace
29.004132
80
0.629862
ajpmaclean
fff173ac174f2ffa44cee0c44438318ab1b6e290
6,428
cpp
C++
test/dbi/test_dbi.cpp
webosce/umediaserver
988605735c1e35937fbfb7ac28422dee678d70d6
[ "Apache-2.0" ]
8
2018-03-17T22:28:05.000Z
2021-11-16T15:29:06.000Z
test/dbi/test_dbi.cpp
webosce/umediaserver
988605735c1e35937fbfb7ac28422dee678d70d6
[ "Apache-2.0" ]
1
2021-05-21T22:51:00.000Z
2021-05-21T22:51:00.000Z
test/dbi/test_dbi.cpp
webosce/umediaserver
988605735c1e35937fbfb7ac28422dee678d70d6
[ "Apache-2.0" ]
4
2018-03-22T18:48:22.000Z
2021-11-16T15:29:08.000Z
#define BOOST_TEST_MODULE TestDBI #include <boost/test/included/unit_test.hpp> #include <list> #include <dbi.h> using namespace uMediaServer::DBI; typedef SQLiteDBI sql_t; const std::string db_init = R"__( drop table if exists books; create table books ( id varchar primary key, author varchar, title varchar, pages integer, weight float, instock integer); insert into books values('kobzar', 'Taras Shevchenko', 'Kobzar', 452, 1.5, 1); insert into books values('mdick', 'Herman Melville', 'Moby-Dick', 927, 3.2, 0); )__"; const std::string db_uri = ":memory:"; struct DbiFixture { DbiFixture() : sql(db_uri) { sql << db_init; } sql_t sql; }; namespace test { struct book { std::string id; std::string author; std::string title; size_t pages; float weight; bool instock; }; } void report_error(std::ostream & s, const uMediaServer::DBI::Exception & e) { using namespace uMediaServer::DBI; s << *boost::get_error_info<boost::throw_file>(e) << "(" << *boost::get_error_info<boost::throw_line>(e) << "): " << "<" << *boost::get_error_info<boost::throw_function>(e) << ">: "; if (auto * info_ptr = boost::get_error_info<throw_db_error>(e)) s << *info_ptr << " "; if (auto * info_ptr = boost::get_error_info<throw_db_uri>(e)) s << "{" << *info_ptr << "} "; if (auto * info_ptr = boost::get_error_info<throw_typeid>(e)) s << "{" << *info_ptr << "} "; s << std::endl; } BOOST_FIXTURE_TEST_CASE(dbi_exceptions, DbiFixture) { // wrong database uri using namespace uMediaServer::DBI; BOOST_CHECK_THROW(sql_t("/fake_dir/fake_file"), OpenError); // sql syntax error BOOST_CHECK_THROW(sql << "select some hiking boots from books;" << "drop table 'books';", ExecError); // wrong table name BOOST_CHECK_THROW(sql << "select * from 'book';", ExecError); // into type mismatch std::list<int> titles; BOOST_CHECK_THROW((sql << "select title from 'books';", into(titles)), ConvError); // binding type mismatch // FIXME: sqlite silently accepts type mismatch while binding // int id = 10; std::string title; // BOOST_CHECK_THROW((sql << "select title from 'books' where id=?;", // from(id), into(title)), ConvError); // not enough storage provided std::string id("kobzar"), title, author; BOOST_CHECK_THROW((sql << "select title, author, weight from 'books' where id=?;", from(id), into(author), into(title)), RangeError); id = "CAD"; author = "Ian Cain"; title = "Corporate America for Dummies"; BOOST_CHECK_THROW((sql << "insert into 'books' values(?, ?, ?, ?, ?, ?);", from(id), from(author), from(title)), RangeError); // error reporting try { sql << "errorneus sql query;"; } catch (const Exception & e) { report_error(std::cerr, e); } try { int title; sql << "select title from 'books' where id='kobzar';", into(title); } catch (const Exception & e) { report_error(std::cerr, e); } try { std::string data; sql << "select title, author from 'books' where id='kobzar';", into(data); } catch (const Exception & e) { report_error(std::cerr, e); } } BOOST_FIXTURE_TEST_CASE(select_trivial_types, DbiFixture) { float weight; std::string author, title; size_t pages; bool instock; sql << "select author, title, pages, weight, instock from books where id='kobzar';", into(author), into(title), into(pages), into(weight), into(instock); BOOST_CHECK_EQUAL(author, "Taras Shevchenko"); BOOST_CHECK_EQUAL(title, "Kobzar"); BOOST_CHECK_EQUAL(pages, 452); BOOST_CHECK_EQUAL(weight, 1.5); BOOST_CHECK_EQUAL(instock, true); } BOOST_FIXTURE_TEST_CASE(insert_trivial_types, DbiFixture) { double weight = 0.8; std::string id("c++"), author("Bjarne Stroustrup"), title("A Tour of C++"); size_t pages = 192; bool instock = false; sql << "insert into books values(?, ?, ?, ?, ?, ?);", from(id), from(author), from(title), from(pages), from(weight), from(instock); weight = 0.0; id.clear(); author.clear(); title.clear(); pages = 0; instock = true; sql << "select author, title, pages, weight, instock from books where id='c++';", into(author), into(title), into(pages), into(weight), into(instock); BOOST_CHECK_EQUAL(author, "Bjarne Stroustrup"); BOOST_CHECK_EQUAL(title, "A Tour of C++"); BOOST_CHECK_EQUAL(pages, 192); BOOST_CHECK_EQUAL(weight, 0.8); BOOST_CHECK_EQUAL(instock, false); } #include <boost/fusion/adapted.hpp> BOOST_FUSION_ADAPT_STRUCT ( test::book, (std::string, id) (std::string, author) (std::string, title) (size_t, pages) (float, weight) (bool, instock)) BOOST_FIXTURE_TEST_CASE(composite_types, DbiFixture) { test::book book; test::book expected{"CAD", "Ian Cain", "Corporate America for Dummies", 235, 1.3, true}; size_t row_count; sql << "insert into books values(?, ?, ?, ?, ?, ?);", from(expected); sql << "select count(*) from books;", into(row_count); BOOST_CHECK_EQUAL(row_count, 3); sql << "select * from books where id=?;", from(expected), into(book); BOOST_CHECK(boost::fusion::equal_to(book, expected)); sql << "delete from books where id=?;", from(book); sql << "select count(*) from books;", into(row_count); BOOST_CHECK_EQUAL(row_count, 2); } BOOST_FIXTURE_TEST_CASE(list_select, DbiFixture) { std::list<std::string> strings; std::list<std::string> expected{"kobzar", "Taras Shevchenko", "Kobzar"}; sql << "select id, author, title from books where id=?;", from(expected.front()), into(strings); BOOST_CHECK_EQUAL_COLLECTIONS(strings.begin(), strings.end(), expected.begin(), expected.end()); strings.clear(); expected = {"Kobzar", "Moby-Dick"}; sql << "select title from books;", into(strings); BOOST_CHECK_EQUAL_COLLECTIONS(strings.begin(), strings.end(), expected.begin(), expected.end()); std::list<test::book> books; std::list<test::book> expected_books{ {"kobzar", "Taras Shevchenko", "Kobzar", 452, 1.5, true}, {"mdick", "Herman Melville", "Moby-Dick", 927, 3.2, false} }; sql << "select * from books;", into(books); BOOST_CHECK_EQUAL(books.size(), expected_books.size()); auto it = books.begin(); auto eit = expected_books.begin(); for (; it != books.end(); ++it, ++eit) BOOST_CHECK(boost::fusion::equal_to(*it, *eit)); // assure empty list books.clear(); std::string non_existent("unknown"); sql << "select * from books where id=?;", from(non_existent), into(books); BOOST_CHECK(books.empty()); }
30.903846
89
0.665215
webosce
fff2c71393a47f7ddc2a65c2bd77f1fa6fcbe020
2,947
inl
C++
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/ModularInteger.inl
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/ModularInteger.inl
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/ModularInteger.inl
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
#ifndef RS_MODULARINTEGER_INL #define RS_MODULARINTEGER_INL #include "ModularInteger.h" // why is this include needed? maybe it's not using namespace RSLib; // construction/destruction: template<class T> rsModularInteger<T>::rsModularInteger(rsUint64 initialValue, rsUint64 modulusToUse) { modulus = modulusToUse; value = initialValue; rsAssert( value >= T(0) && value < modulus ); } template<class T> rsModularInteger<T>::rsModularInteger(const rsModularInteger<T>& other) { modulus = other.modulus; value = other.value; } // operators: template<class T> rsModularInteger<T> rsModularInteger<T>::operator-() const { if( value == 0 ) return *this; else return rsModularInteger<T>(modulus-value, modulus); } template<class T> bool rsModularInteger<T>::operator==(const rsModularInteger<T>& other) const { return value == other.value && modulus == other.modulus; } template<class T> bool rsModularInteger<T>::operator!=(const rsModularInteger<T>& other) const { return !(*this == other); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator+(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r = this->value + other.value; if( r >= modulus ) r -= modulus; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator-(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r; if( other.value > this->value ) r = modulus + this->value - other.value; else r = this->value - other.value; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator*(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); T r = (this->value * other.value) % modulus; return rsModularInteger<T>(r, modulus); } template<class T> rsModularInteger<T> rsModularInteger<T>::operator/(const rsModularInteger<T> &other) { rsAssert( modulus == other.modulus ); return *this * rsModularInverse(other.value, modulus); } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator+=(const rsModularInteger<T> &other) { *this = *this + other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator-=(const rsModularInteger<T> &other) { *this = *this - other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator*=(const rsModularInteger<T> &other) { *this = *this * other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator/=(const rsModularInteger<T> &other) { *this = *this / other; return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator++() { *this = *this + rsModularInteger<T>(1, modulus); return *this; } template<class T> rsModularInteger<T>& rsModularInteger<T>::operator--() { *this = *this - rsModularInteger<T>(1, modulus); return *this; } #endif
24.155738
86
0.709874
RobinSchmidt
fff596ba478f512384eb607b6be214f12d50b052
4,712
cpp
C++
windows/appcompat/shims/specific/kingsquestmask.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/appcompat/shims/specific/kingsquestmask.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/appcompat/shims/specific/kingsquestmask.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 2000 Microsoft Corporation Module Name: KingsQuestMask.cpp Abstract: The app calls UnmapViewOfFile with a bogus address - an address that wasn't obtained from MapViewOfFile. We validate the address before calling UnmapViewOfFile. History: 11/20/2000 maonis Created --*/ #include "precomp.h" typedef BOOL (WINAPI *_pfn_UnmapViewOfFile)(LPCVOID lpBaseAddress); IMPLEMENT_SHIM_BEGIN(KingsQuestMask) #include "ShimHookMacro.h" APIHOOK_ENUM_BEGIN APIHOOK_ENUM_ENTRY(MapViewOfFile) APIHOOK_ENUM_ENTRY(UnmapViewOfFile) APIHOOK_ENUM_END // Link list of base addresses struct MAPADDRESS { MAPADDRESS *next; LPCVOID pBaseAddress; }; MAPADDRESS *g_pBaseAddressList; /*++ Function Description: Add a base address to the linked list of addresses. Does not add if the address is NULL or a duplicate. Arguments: IN pBaseAddress - base address returned by MapViewOfFile. Return Value: None History: 11/20/2000 maonis Created --*/ VOID AddBaseAddress( IN LPCVOID pBaseAddress ) { if (pBaseAddress) { MAPADDRESS *pMapAddress = g_pBaseAddressList; while (pMapAddress) { if (pMapAddress->pBaseAddress == pBaseAddress) { return; } pMapAddress = pMapAddress->next; } pMapAddress = (MAPADDRESS *) malloc(sizeof MAPADDRESS); pMapAddress->pBaseAddress = pBaseAddress; pMapAddress->next = g_pBaseAddressList; g_pBaseAddressList = pMapAddress; } } /*++ Function Description: Remove a base address if it can be found in the linked list of addresses. Arguments: IN pBaseAddress - the base address to remove. Return Value: TRUE if the address is found. FALSE if the address is not found. History: 11/20/2000 maonis Created --*/ BOOL RemoveBaseAddress( IN LPCVOID pBaseAddress ) { MAPADDRESS *pMapAddress = g_pBaseAddressList; MAPADDRESS *last = NULL; while (pMapAddress) { if (pMapAddress->pBaseAddress == pBaseAddress) { if (last) { last->next = pMapAddress->next; } else { g_pBaseAddressList = pMapAddress->next; } free(pMapAddress); return TRUE; } last = pMapAddress; pMapAddress = pMapAddress->next; } return FALSE; } /*++ Add the base address to our list. --*/ LPVOID APIHOOK(MapViewOfFile)( HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap ) { LPVOID pRet = ORIGINAL_API(MapViewOfFile)( hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap); AddBaseAddress(pRet); DPFN( eDbgLevelInfo, "MapViewOfFile: added base address = 0x%x\n", pRet); return pRet; } /*++ Remove the address from our list if it can be found; otherwise do nothing. --*/ BOOL APIHOOK(UnmapViewOfFile)( LPCVOID lpBaseAddress ) { BOOL bRet; if (RemoveBaseAddress(lpBaseAddress)) { bRet = ORIGINAL_API(UnmapViewOfFile)(lpBaseAddress); if (bRet) { DPFN( eDbgLevelInfo, "UnmapViewOfFile unmapped address 0x%x\n", lpBaseAddress); } return bRet; } else { DPFN( eDbgLevelError,"UnmapViewOfFile was passed an invalid address 0x%x\n", lpBaseAddress); return FALSE; } } /*++ Free the list. --*/ BOOL NOTIFY_FUNCTION( DWORD fdwReason) { if (fdwReason == DLL_PROCESS_DETACH) { DWORD dwCount = 0; MAPADDRESS *pMapAddress = g_pBaseAddressList; while (pMapAddress) { g_pBaseAddressList = pMapAddress->next; ORIGINAL_API(UnmapViewOfFile)(pMapAddress->pBaseAddress); free(pMapAddress); pMapAddress = g_pBaseAddressList; dwCount++; } if (dwCount > 0) { DPFN( eDbgLevelInfo,"%d addresses not unmapped.", dwCount); } } return TRUE; } /*++ Register hooked functions --*/ HOOK_BEGIN APIHOOK_ENTRY(KERNEL32.DLL, MapViewOfFile) APIHOOK_ENTRY(KERNEL32.DLL, UnmapViewOfFile) CALL_NOTIFY_FUNCTION HOOK_END IMPLEMENT_SHIM_END
19.232653
101
0.593591
npocmaka
fff61daaf471b518d075a646c8d5ccfc952aab7c
28,480
cpp
C++
CvGameCoreDLL/CyPlot.cpp
macaurther/DOCUSA
40586727c351d1b1130c05c2d4648cca3a8bacf5
[ "MIT" ]
1
2017-08-17T02:49:22.000Z
2017-08-17T02:49:22.000Z
CvGameCoreDLL/CyPlot.cpp
macaurther/DOCUSA
40586727c351d1b1130c05c2d4648cca3a8bacf5
[ "MIT" ]
null
null
null
CvGameCoreDLL/CyPlot.cpp
macaurther/DOCUSA
40586727c351d1b1130c05c2d4648cca3a8bacf5
[ "MIT" ]
1
2021-03-17T23:58:03.000Z
2021-03-17T23:58:03.000Z
// // Python wrapper class for CvPlot // // #include "CvGameCoreDLL.h" #include "CyPlot.h" #include "CyCity.h" #include "CyArea.h" #include "CyUnit.h" #include "CvPlot.h" CyPlot::CyPlot(CvPlot* pPlot) : m_pPlot(pPlot) { } CyPlot::CyPlot() : m_pPlot(NULL) { } void CyPlot::erase() { if (m_pPlot) m_pPlot->erase(); } //Rhye - start void CyPlot::eraseAIDevelopment() { if (m_pPlot) m_pPlot->eraseAIDevelopment(); } //Rhye - end NiPoint3 CyPlot::getPoint() { return m_pPlot ? m_pPlot->getPoint() : NiPoint3(0,0,0); } int CyPlot::getTeam() { return m_pPlot ? m_pPlot->getTeam() : -1; } void CyPlot::nukeExplosion(int iRange, CyUnit* pNukeUnit) { if (m_pPlot) m_pPlot->nukeExplosion(iRange, pNukeUnit->getUnit()); } bool CyPlot::isConnectedTo(CyCity* pCity) { return m_pPlot ? m_pPlot->isConnectedTo(pCity->getCity()) : false; } bool CyPlot::isConnectedToCapital(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->isConnectedToCapital((PlayerTypes) ePlayer): false; } int CyPlot::getPlotGroupConnectedBonus(int /*PlayerTypes*/ ePlayer, int /*BonusTypes*/ eBonus) { return m_pPlot ? m_pPlot->getPlotGroupConnectedBonus((PlayerTypes) ePlayer, (BonusTypes) eBonus) : -1; } bool CyPlot::isPlotGroupConnectedBonus(int /*PlayerTypes*/ ePlayer, int /*BonusTypes*/ eBonus) { return m_pPlot ? m_pPlot->isPlotGroupConnectedBonus((PlayerTypes) ePlayer, (BonusTypes) eBonus) : false; } bool CyPlot::isAdjacentPlotGroupConnectedBonus(int /*PlayerTypes*/ ePlayer, int /*BonusTypes*/ eBonus) { return m_pPlot ? m_pPlot->isAdjacentPlotGroupConnectedBonus((PlayerTypes) ePlayer, (BonusTypes) eBonus) : false; } void CyPlot::updateVisibility() { if (m_pPlot) { m_pPlot->updateVisibility(); } } bool CyPlot::isAdjacentToArea(CyArea* pArea) { return m_pPlot ? m_pPlot->isAdjacentToArea(pArea->getArea()) : false; } bool CyPlot::shareAdjacentArea(CyPlot* pPlot) { return m_pPlot ? m_pPlot->shareAdjacentArea(pPlot->getPlot()) : false; } bool CyPlot::isAdjacentToLand() { return m_pPlot ? m_pPlot->isAdjacentToLand() : false; } bool CyPlot::isCoastalLand() { return m_pPlot ? m_pPlot->isCoastalLand() : false; } bool CyPlot::isWithinTeamCityRadius(int /*TeamTypes*/ eTeam, int /*PlayerTypes*/ eIgnorePlayer) { return m_pPlot ? m_pPlot->isWithinTeamCityRadius((TeamTypes) eTeam, (PlayerTypes) eIgnorePlayer) : false; } bool CyPlot::isLake() { return m_pPlot ? m_pPlot->isLake() : false; } bool CyPlot::isFreshWater() { return m_pPlot ? m_pPlot->isFreshWater() : false; } bool CyPlot::isPotentialIrrigation() { return m_pPlot ? m_pPlot->isPotentialIrrigation() : false; } bool CyPlot::canHavePotentialIrrigation() { return m_pPlot ? m_pPlot->canHavePotentialIrrigation() : false; } bool CyPlot::isIrrigationAvailable(bool bIgnoreSelf) { return m_pPlot ? m_pPlot->isIrrigationAvailable(bIgnoreSelf) : false; } bool CyPlot::isRiverSide() { return m_pPlot ? m_pPlot->isRiverSide() : false; } bool CyPlot::isRiver() { return m_pPlot ? m_pPlot->isRiver() : false; } bool CyPlot::isRiverConnection(int /*DirectionTypes*/ eDirection) { return m_pPlot ? m_pPlot->isRiverConnection((DirectionTypes) eDirection) : false; } int CyPlot::getNearestLandArea() { return m_pPlot ? m_pPlot->getNearestLandArea() : -1; } CyPlot* CyPlot::getNearestLandPlot() { return m_pPlot ? new CyPlot(m_pPlot->getNearestLandPlot()) : NULL; } int CyPlot::seeFromLevel(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->seeFromLevel((TeamTypes)eTeam) : -1; } int CyPlot::seeThroughLevel() { return m_pPlot ? m_pPlot->seeThroughLevel() : -1; } bool CyPlot::canHaveBonus(int /*BonusTypes*/ eBonus, bool bIgnoreLatitude) { return m_pPlot ? m_pPlot->canHaveBonus((BonusTypes)eBonus, bIgnoreLatitude) : false; } bool CyPlot::canHaveImprovement(int /* ImprovementTypes */ eImprovement, int /*TeamTypes*/ eTeam, bool bPotential) { return m_pPlot ? m_pPlot->canHaveImprovement(((ImprovementTypes)eImprovement), ((TeamTypes)eTeam), bPotential) : false; } bool CyPlot::canBuild(int /*BuildTypes*/ eBuild, int /*PlayerTypes*/ ePlayer, bool bTestVisible) { return m_pPlot ? m_pPlot->canBuild((BuildTypes) eBuild, (PlayerTypes) ePlayer, bTestVisible) : false; } int CyPlot::getBuildTime(int /* BuildTypes */ eBuild) { return m_pPlot ? m_pPlot->getBuildTime((BuildTypes)eBuild) : -1; } int CyPlot::getBuildTurnsLeft(int /*BuildTypes*/ eBuild, int iNowExtra, int iThenExtra) { return m_pPlot ? m_pPlot->getBuildTurnsLeft((BuildTypes) eBuild, iNowExtra, iThenExtra) : -1; } int CyPlot::getFeatureProduction(int /*BuildTypes*/ eBuild, int /*TeamTypes*/ eTeam, CyCity* ppCity) { CvCity* tempCity = ppCity->getCity(); return m_pPlot ? m_pPlot->getFeatureProduction((BuildTypes) eBuild, (TeamTypes) eTeam, &tempCity) : -1; } CyUnit* CyPlot::getBestDefender(int /*PlayerTypes*/ eOwner, int /*PlayerTypes*/ eAttackingPlayer, CyUnit* pAttacker, bool bTestAtWar, bool bTestPotentialEnemy, bool bTestCanMove) { return m_pPlot ? new CyUnit(m_pPlot->getBestDefender((PlayerTypes) eOwner, (PlayerTypes) eAttackingPlayer, pAttacker->getUnit(), bTestAtWar, bTestPotentialEnemy, bTestCanMove)) : NULL; } CyUnit* CyPlot::getSelectedUnit() { return m_pPlot ? new CyUnit(m_pPlot->getSelectedUnit()) : NULL; } int CyPlot::getUnitPower(int /* PlayerTypes */ eOwner) { return m_pPlot ? m_pPlot->getUnitPower((PlayerTypes)eOwner) : -1; } int CyPlot::movementCost(CyUnit* pUnit, CyPlot* pFromPlot) { return m_pPlot ? m_pPlot->movementCost(pUnit->getUnit(), pFromPlot->getPlot()) : -1; } int CyPlot::defenseModifier(int iDefendTeam, bool bIgnoreBuilding, bool bHelp) { return m_pPlot ? m_pPlot->defenseModifier((TeamTypes)iDefendTeam, bIgnoreBuilding, bHelp) : -1; } int CyPlot::getExtraMovePathCost() { return m_pPlot ? m_pPlot->getExtraMovePathCost() : -1; } void CyPlot::changeExtraMovePathCost(int iChange) { if (m_pPlot) m_pPlot->changeExtraMovePathCost(iChange); } bool CyPlot::isAdjacentOwned() { return m_pPlot ? m_pPlot->isAdjacentOwned() : false; } bool CyPlot::isAdjacentPlayer(int /*PlayerTypes*/ ePlayer, bool bLandOnly) { return m_pPlot ? m_pPlot->isAdjacentPlayer((PlayerTypes)ePlayer, bLandOnly) : false; } bool CyPlot::isAdjacentTeam(int /*TeamTypes*/ ePlayer, bool bLandOnly) { return m_pPlot ? m_pPlot->isAdjacentTeam((TeamTypes)ePlayer, bLandOnly) : false; } bool CyPlot::isWithinCultureRange(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->isWithinCultureRange((PlayerTypes)ePlayer) : false; } int CyPlot::getNumCultureRangeCities(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->getNumCultureRangeCities((PlayerTypes)ePlayer) : -1; } int /*PlayerTypes*/ CyPlot::calculateCulturalOwner() { return m_pPlot ? m_pPlot->calculateCulturalOwner() : -1; } bool CyPlot::isOwned() { return m_pPlot ? m_pPlot->isOwned() : false; } bool CyPlot::isBarbarian() { return m_pPlot ? m_pPlot->isBarbarian() : false; } bool CyPlot::isRevealedBarbarian() { return m_pPlot ? m_pPlot->isRevealedBarbarian() : false; } bool CyPlot::isVisible(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->isVisible((TeamTypes)eTeam, bDebug) : false; } bool CyPlot::isActiveVisible(bool bDebug) { return m_pPlot ? m_pPlot->isActiveVisible(bDebug) : false; } bool CyPlot::isVisibleToWatchingHuman() { return m_pPlot ? m_pPlot->isVisibleToWatchingHuman() : false; } bool CyPlot::isAdjacentVisible(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->isAdjacentVisible((TeamTypes) eTeam, bDebug) : false; } bool CyPlot::isAdjacentNonvisible(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isAdjacentNonvisible((TeamTypes) eTeam) : false; } bool CyPlot::isAdjacentRevealed(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isAdjacentRevealed((TeamTypes) eTeam) : false; } bool CyPlot::isAdjacentNonrevealed(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isAdjacentNonrevealed((TeamTypes) eTeam) : false; } void CyPlot::removeGoody() { if (m_pPlot) { m_pPlot->removeGoody(); } } bool CyPlot::isGoody() { return m_pPlot ? m_pPlot->isGoody() : false; } bool CyPlot::isRevealedGoody(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isRevealedGoody((TeamTypes) eTeam) : false; } bool CyPlot::isCity() { return m_pPlot ? m_pPlot->isCity() : false; } bool CyPlot::isFriendlyCity(CyUnit* pUnit, bool bCheckImprovement) { return m_pPlot ? m_pPlot->isFriendlyCity(*(pUnit->getUnit()), bCheckImprovement) : false; } bool CyPlot::isEnemyCity(CyUnit* pUnit) { return m_pPlot ? m_pPlot->isEnemyCity(*(pUnit->getUnit())) : false; } bool CyPlot::isOccupation() { return m_pPlot ? m_pPlot->isOccupation() : false; } bool CyPlot::isBeingWorked() { return m_pPlot ? m_pPlot->isBeingWorked() : false; } bool CyPlot::isUnit() { return m_pPlot ? m_pPlot->isUnit() : false; } bool CyPlot::isInvestigate(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isInvestigate((TeamTypes) eTeam) : false; } bool CyPlot::isVisibleEnemyDefender(CyUnit* pUnit) { return m_pPlot ? m_pPlot->isVisibleEnemyDefender(pUnit->getUnit()) : false; } int CyPlot::getNumDefenders(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->getNumDefenders((PlayerTypes) ePlayer) : -1; } int CyPlot::getNumVisibleEnemyDefenders(CyUnit* pUnit) { return m_pPlot ? m_pPlot->getNumVisibleEnemyDefenders(pUnit->getUnit()) : -1; } int CyPlot::getNumVisiblePotentialEnemyDefenders(CyUnit* pUnit) { return m_pPlot ? m_pPlot->getNumVisiblePotentialEnemyDefenders(pUnit->getUnit()) : -1; } bool CyPlot::isVisibleEnemyUnit(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->isVisibleEnemyUnit((PlayerTypes) ePlayer) : false; } bool CyPlot::isVisibleOtherUnit(int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->isVisibleOtherUnit((PlayerTypes) ePlayer) : false; } bool CyPlot::isFighting() { return m_pPlot ? m_pPlot->isFighting() : false; } bool CyPlot::canHaveFeature(int /*FeatureTypes*/ eFeature) { return m_pPlot ? m_pPlot->canHaveFeature((FeatureTypes)eFeature) : false; } bool CyPlot::isRoute() { return m_pPlot ? m_pPlot->isRoute() : false; } bool CyPlot::isNetworkTerrain(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isNetworkTerrain((TeamTypes) eTeam) : false; } bool CyPlot::isBonusNetwork(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isBonusNetwork((TeamTypes) eTeam) : false; } bool CyPlot::isTradeNetworkImpassable(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isTradeNetworkImpassable((TeamTypes) eTeam) : false; } bool CyPlot::isTradeNetwork(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isTradeNetwork((TeamTypes)eTeam) : false; } bool CyPlot::isTradeNetworkConnected(CyPlot* pPlot, int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->isTradeNetworkConnected(pPlot->getPlot(), (TeamTypes)eTeam) : false; } bool CyPlot::isValidDomainForLocation(CyUnit* pUnit) const { return (m_pPlot && pUnit && pUnit->getUnit()) ? m_pPlot->isValidDomainForLocation(*(pUnit->getUnit())) : false; } bool CyPlot::isValidDomainForAction(CyUnit* pUnit) const { return (m_pPlot && pUnit && pUnit->getUnit()) ? m_pPlot->isValidDomainForAction(*(pUnit->getUnit())) : false; } bool CyPlot::isImpassable() { return m_pPlot ? m_pPlot->isImpassable() : false; } int CyPlot::getX() { return m_pPlot ? m_pPlot->getX_INLINE() : -1; } int CyPlot::getY() { return m_pPlot ? m_pPlot->getY_INLINE() : -1; } bool CyPlot::at(int iX, int iY) { return m_pPlot ? m_pPlot->at(iX, iY) : false; } int CyPlot::getLatitude() { return m_pPlot ? m_pPlot->getLatitude() : -1; } CyArea* CyPlot::area() { return m_pPlot ? new CyArea(m_pPlot->area()) : NULL; } CyArea* CyPlot::waterArea() { return m_pPlot ? new CyArea(m_pPlot->waterArea()) : NULL; } int CyPlot::getArea() { return m_pPlot ? m_pPlot->getArea() : -1; } //Rhye - start void CyPlot::setArea(int iNewValue) { if (m_pPlot) m_pPlot->setArea(iNewValue); } //Rhye - end int CyPlot::getUpgradeProgress() { return m_pPlot ? m_pPlot->getUpgradeProgress() : -1; } int CyPlot::getUpgradeTimeLeft(int /*ImprovementTypes*/ eImprovement, int /*PlayerTypes*/ ePlayer) { return m_pPlot ? m_pPlot->getUpgradeTimeLeft((ImprovementTypes) eImprovement, (PlayerTypes) ePlayer) : -1; } void CyPlot::setUpgradeProgress(int iNewValue) { if (m_pPlot) m_pPlot->setUpgradeProgress(iNewValue); } void CyPlot::changeUpgradeProgress(int iChange) { if (m_pPlot) m_pPlot->changeUpgradeProgress(iChange); } int CyPlot::getForceUnownedTimer() { return m_pPlot ? m_pPlot->getForceUnownedTimer() : -1; } bool CyPlot::isForceUnowned() { return m_pPlot ? m_pPlot->isForceUnowned() : false; } void CyPlot::setForceUnownedTimer(int iNewValue) { if (m_pPlot) m_pPlot->setForceUnownedTimer(iNewValue); } void CyPlot::changeForceUnownedTimer(int iChange) { if (m_pPlot) m_pPlot->changeForceUnownedTimer(iChange); } int CyPlot::getCityRadiusCount() { return m_pPlot ? m_pPlot->getCityRadiusCount() : -1; } int CyPlot::isCityRadius() { return m_pPlot ? m_pPlot->isCityRadius() : -1; } bool CyPlot::isStartingPlot() { return m_pPlot ? m_pPlot->isStartingPlot() : false; } void CyPlot::setStartingPlot(bool bNewValue) { if (m_pPlot) m_pPlot->setStartingPlot(bNewValue); } bool CyPlot::isNOfRiver() { return m_pPlot ? m_pPlot->isNOfRiver() : false; } void CyPlot::setNOfRiver(bool bNewValue, CardinalDirectionTypes eRiverDir) { if (m_pPlot) { m_pPlot->setNOfRiver(bNewValue, eRiverDir); } } bool CyPlot::isWOfRiver() { return m_pPlot ? m_pPlot->isWOfRiver() : false; } void CyPlot::setWOfRiver(bool bNewValue, CardinalDirectionTypes eRiverDir) { if (m_pPlot) { m_pPlot->setWOfRiver(bNewValue, eRiverDir); } } CardinalDirectionTypes CyPlot::getRiverWEDirection() { return m_pPlot->getRiverWEDirection(); } CardinalDirectionTypes CyPlot::getRiverNSDirection() { return m_pPlot->getRiverNSDirection(); } bool CyPlot::isIrrigated() { return m_pPlot ? m_pPlot->isIrrigated() : false; } bool CyPlot::isPotentialCityWork() { return m_pPlot ? m_pPlot->isPotentialCityWork() : false; } bool CyPlot::isPotentialCityWorkForArea(CyArea* pArea) { return m_pPlot ? m_pPlot->isPotentialCityWorkForArea(pArea->getArea()) : false; } bool CyPlot::isFlagDirty() { return m_pPlot ? m_pPlot->isFlagDirty() : false; } void CyPlot::setFlagDirty(bool bNewValue) { if (m_pPlot) { m_pPlot->setFlagDirty(bNewValue); } } int CyPlot::getOwner() { return m_pPlot ? m_pPlot->getOwnerINLINE() : -1; } void CyPlot::setOwner(int /*PlayerTypes*/ eNewValue) { if (m_pPlot) m_pPlot->setOwner((PlayerTypes) eNewValue, true, true); } void CyPlot::setOwnerNoUnitCheck(int /*PlayerTypes*/ eNewValue) { if (m_pPlot) m_pPlot->setOwner((PlayerTypes) eNewValue, false, true); } PlotTypes CyPlot::getPlotType() { return m_pPlot ? m_pPlot->getPlotType() : NO_PLOT; } bool CyPlot::isWater() { return m_pPlot ? m_pPlot->isWater() : false; } bool CyPlot::isFlatlands() { return m_pPlot ? m_pPlot->isFlatlands() : false; } bool CyPlot::isHills() { return m_pPlot ? m_pPlot->isHills() : false; } bool CyPlot::isPeak() { return m_pPlot ? m_pPlot->isPeak() : false; } void CyPlot::setPlotType(PlotTypes eNewValue, bool bRecalculate, bool bRebuildGraphics) { if (m_pPlot) m_pPlot->setPlotType(eNewValue, bRecalculate, bRebuildGraphics); } int /*TerrainTypes*/ CyPlot::getTerrainType() { return m_pPlot ? m_pPlot->getTerrainType() : -1; } void CyPlot::setTerrainType(int /*TerrainTypes*/ eNewValue, bool bRecalculate, bool bRebuildGraphics) { if (m_pPlot) m_pPlot->setTerrainType((TerrainTypes)eNewValue, bRecalculate, bRebuildGraphics); } int /*FeatureTypes*/ CyPlot::getFeatureType() { return m_pPlot ? m_pPlot->getFeatureType() : -1; } void CyPlot::setFeatureType(int /*FeatureTypes*/ eNewValue, int iVariety) { if (m_pPlot) m_pPlot->setFeatureType((FeatureTypes)eNewValue, iVariety); } void CyPlot::setFeatureDummyVisibility(std::string dummyTag, bool show) { if(m_pPlot) m_pPlot->setFeatureDummyVisibility(dummyTag.c_str(), show); } void CyPlot::addFeatureDummyModel(std::string dummyTag, std::string modelTag) { if(m_pPlot) m_pPlot->addFeatureDummyModel(dummyTag.c_str(), modelTag.c_str()); } void CyPlot::setFeatureDummyTexture(std::string dummyTag, std::string textureTag) { if(m_pPlot) m_pPlot->setFeatureDummyTexture(dummyTag.c_str(), textureTag.c_str()); } std::string CyPlot::pickFeatureDummyTag(int mouseX, int mouseY) { if(m_pPlot) return m_pPlot->pickFeatureDummyTag(mouseX, mouseY); else return ""; } void CyPlot::resetFeatureModel() { if(m_pPlot) m_pPlot->resetFeatureModel(); } int CyPlot::getFeatureVariety() { return m_pPlot ? m_pPlot->getFeatureVariety() : -1; } int CyPlot::getOwnershipDuration() { return m_pPlot ? m_pPlot->getOwnershipDuration() : -1; } bool CyPlot::isOwnershipScore() { return m_pPlot ? m_pPlot->isOwnershipScore() : false; } void CyPlot::setOwnershipDuration(int iNewValue) { if (m_pPlot) m_pPlot->setOwnershipDuration(iNewValue); } void CyPlot::changeOwnershipDuration(int iChange) { if (m_pPlot) m_pPlot->changeOwnershipDuration(iChange); } int CyPlot::getImprovementDuration() { return m_pPlot ? m_pPlot->getImprovementDuration() : -1; } void CyPlot::setImprovementDuration(int iNewValue) { if (m_pPlot) m_pPlot->setImprovementDuration(iNewValue); } void CyPlot::changeImprovementDuration(int iChange) { if (m_pPlot) m_pPlot->changeImprovementDuration(iChange); } int /* BonusTypes */ CyPlot::getBonusType(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->getBonusType((TeamTypes)eTeam) : -1; } int /* BonusTypes */ CyPlot::getNonObsoleteBonusType(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->getNonObsoleteBonusType((TeamTypes)eTeam) : -1; } void CyPlot::setBonusType(int /* BonusTypes */ eNewValue) { if (m_pPlot) m_pPlot->setBonusType((BonusTypes)eNewValue); } int /* ImprovementTypes */ CyPlot::getImprovementType() { return m_pPlot ? m_pPlot->getImprovementType() : -1; } void CyPlot::setImprovementType(int /* ImprovementTypes */ eNewValue) { if (m_pPlot) m_pPlot->setImprovementType((ImprovementTypes)eNewValue); } int /* RouteTypes */ CyPlot::getRouteType() { return m_pPlot ? m_pPlot->getRouteType() : -1; } void CyPlot::setRouteType(int /*RouteTypes*/ eNewValue) { if (m_pPlot) m_pPlot->setRouteType((RouteTypes) eNewValue, true); } CyCity* CyPlot::getPlotCity() { return m_pPlot ? new CyCity(m_pPlot->getPlotCity()) : NULL; } CyCity* CyPlot::getWorkingCity() { return m_pPlot ? new CyCity(m_pPlot->getWorkingCity()) : NULL; } CyCity* CyPlot::getWorkingCityOverride() { return m_pPlot ? new CyCity(m_pPlot->getWorkingCityOverride()) : NULL; } int CyPlot::getRiverID() const { return m_pPlot ? m_pPlot->getRiverID() : -1; } void CyPlot::setRiverID(int iNewValue) { if (m_pPlot) m_pPlot->setRiverID(iNewValue); } int CyPlot::getMinOriginalStartDist() { return m_pPlot ? m_pPlot->getMinOriginalStartDist() : -1; } int CyPlot::getReconCount() { return m_pPlot ? m_pPlot->getReconCount() : -1; } int CyPlot::getRiverCrossingCount() { return m_pPlot ? m_pPlot->getRiverCrossingCount() : -1; } int CyPlot::getYield(YieldTypes eIndex) { return m_pPlot ? m_pPlot->getYield(eIndex) : -1; } int CyPlot::calculateNatureYield(YieldTypes eIndex, TeamTypes eTeam, bool bIgnoreFeature) { return m_pPlot ? m_pPlot->calculateNatureYield(eIndex, eTeam, bIgnoreFeature) : -1; } int CyPlot::calculateBestNatureYield(YieldTypes eIndex, TeamTypes eTeam) { return m_pPlot ? m_pPlot->calculateBestNatureYield(eIndex, eTeam) : -1; } int CyPlot::calculateTotalBestNatureYield(TeamTypes eTeam) { return m_pPlot ? m_pPlot->calculateTotalBestNatureYield(eTeam) : -1; } int CyPlot::calculateImprovementYieldChange(int /*ImprovementTypes*/ eImprovement, YieldTypes eYield, int /*PlayerTypes*/ ePlayer, bool bOptimal) { return m_pPlot ? m_pPlot->calculateImprovementYieldChange((ImprovementTypes) eImprovement, eYield, (PlayerTypes) ePlayer, bOptimal) : -1; } int CyPlot::calculateYield(YieldTypes eIndex, bool bDisplay) { return m_pPlot ? m_pPlot->calculateYield(eIndex, bDisplay) : -1; } bool CyPlot::hasYield() { return m_pPlot ? m_pPlot->hasYield() : false; } int CyPlot::getCulture(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->getCulture((PlayerTypes)eIndex) : -1; } int CyPlot::countTotalCulture() { return m_pPlot ? m_pPlot->countTotalCulture() : -1; } int /*TeamTypes*/ CyPlot::findHighestCultureTeam() { return m_pPlot ? m_pPlot->findHighestCultureTeam() : -1; } int CyPlot::calculateCulturePercent(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->calculateCulturePercent((PlayerTypes)eIndex) : -1; } int CyPlot::calculateTeamCulturePercent(int /*TeamTypes*/ eIndex) { return m_pPlot ? m_pPlot->calculateTeamCulturePercent((TeamTypes)eIndex) : -1; } void CyPlot::setCulture(int /*PlayerTypes*/ eIndex, int iChange, bool bUpdate) { if (m_pPlot) m_pPlot->setCulture((PlayerTypes)eIndex, iChange, bUpdate, true); } void CyPlot::changeCulture(int /*PlayerTypes*/ eIndex, int iChange, bool bUpdate) { if (m_pPlot) m_pPlot->changeCulture((PlayerTypes)eIndex, iChange, bUpdate); } int CyPlot::countNumAirUnits(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->countNumAirUnits((TeamTypes)eTeam) : -1; } int CyPlot::getFoundValue(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->getFoundValue((PlayerTypes)eIndex) : -1; } bool CyPlot::isBestAdjacentFound(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->isBestAdjacentFound((PlayerTypes)eIndex) : false; } int CyPlot::getPlayerCityRadiusCount(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->getPlayerCityRadiusCount((PlayerTypes)eIndex) : -1; } bool CyPlot::isPlayerCityRadius(int /*PlayerTypes*/ eIndex) { return m_pPlot ? m_pPlot->isPlayerCityRadius((PlayerTypes)eIndex) : false; } int CyPlot::getVisibilityCount(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->getVisibilityCount((TeamTypes)eTeam) : -1; } void CyPlot::changeVisibilityCount(int /*TeamTypes*/ eTeam, int iChange, int /*InvisibleTypes*/ eSeeInvisible) { if (m_pPlot) m_pPlot->changeVisibilityCount((TeamTypes) eTeam, iChange, (InvisibleTypes) eSeeInvisible, true); } int CyPlot::getStolenVisibilityCount(int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->getStolenVisibilityCount((TeamTypes)eTeam) : -1; } int /*PlayerTypes*/ CyPlot::getRevealedOwner(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->getRevealedOwner((TeamTypes)eTeam, bDebug) : -1; } int /*TeamTypes*/ CyPlot::getRevealedTeam(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->getRevealedTeam((TeamTypes)eTeam, bDebug) : -1; } bool CyPlot::isRiverCrossing(DirectionTypes eIndex) { return m_pPlot ? m_pPlot->isRiverCrossing(eIndex) : false; } bool CyPlot::isRevealed(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->isRevealed((TeamTypes)eTeam, bDebug) : false; } void CyPlot::setRevealed(int /*TeamTypes*/ eTeam, bool bNewValue, bool bTerrainOnly, int /*TeamTypes*/ eFromTeam) { if (m_pPlot) m_pPlot->setRevealed((TeamTypes)eTeam, bNewValue, bTerrainOnly, (TeamTypes)eFromTeam, true); } int /* ImprovementTypes */ CyPlot::getRevealedImprovementType(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->getRevealedImprovementType((TeamTypes)eTeam, bDebug) : -1; } int /* RouteTypes */ CyPlot::getRevealedRouteType(int /*TeamTypes*/ eTeam, bool bDebug) { return m_pPlot ? m_pPlot->getRevealedRouteType((TeamTypes)eTeam, bDebug) : -1; } int CyPlot::getBuildProgress(int /*BuildTypes*/ eBuild) { return m_pPlot ? m_pPlot->getBuildProgress((BuildTypes)eBuild) : -1; } bool CyPlot::changeBuildProgress(int /*BuildTypes*/ eBuild, int iChange, int /*TeamTypes*/ eTeam) { return m_pPlot ? m_pPlot->changeBuildProgress((BuildTypes)eBuild, iChange, (TeamTypes)eTeam) : false; } int CyPlot::getCultureRangeCities(int /*PlayerTypes*/ eOwnerIndex, int iRangeIndex) { return m_pPlot ? m_pPlot->getCultureRangeCities((PlayerTypes) eOwnerIndex, iRangeIndex) : -1; } bool CyPlot::isCultureRangeCity(int /*PlayerTypes*/ eOwnerIndex, int iRangeIndex) { return m_pPlot ? m_pPlot->isCultureRangeCity((PlayerTypes) eOwnerIndex, iRangeIndex) : false; } int CyPlot::getInvisibleVisibilityCount(int /*TeamTypes*/ eTeam, int /*InvisibleTypes*/ eInvisible) { return m_pPlot ? m_pPlot->getInvisibleVisibilityCount((TeamTypes) eTeam, (InvisibleTypes) eInvisible) : -1; } bool CyPlot::isInvisibleVisible(int /*TeamTypes*/ eTeam, int /*InvisibleTypes*/ eInvisible) { return m_pPlot ? m_pPlot->isInvisibleVisible((TeamTypes) eTeam, (InvisibleTypes) eInvisible) : -1; } void CyPlot::changeInvisibleVisibilityCount(int /*TeamTypes*/ eTeam, int /*InvisibleTypes*/ eInvisible, int iChange) { if (m_pPlot) m_pPlot->changeInvisibleVisibilityCount((TeamTypes) eTeam, (InvisibleTypes) eInvisible, iChange); } int CyPlot::getNumUnits() { return m_pPlot ? m_pPlot->getNumUnits() : -1; } CyUnit* CyPlot::getUnit(int iIndex) { return m_pPlot ? new CyUnit(m_pPlot->getUnitByIndex(iIndex)) : NULL; } std::string CyPlot::getScriptData() const { return m_pPlot ? m_pPlot->getScriptData() : ""; } void CyPlot::setScriptData(std::string szNewValue) { if (m_pPlot) m_pPlot->setScriptData(szNewValue.c_str()); } //Leoreth int CyPlot::getRegionID() { return m_pPlot ? m_pPlot->getRegionID() : -1; } void CyPlot::setRegionID(int iNewValue) { if (m_pPlot) m_pPlot->setRegionID(iNewValue); } bool CyPlot::isCore(int ePlayer) { return m_pPlot ? m_pPlot->isCore((PlayerTypes)ePlayer) : -1; } void CyPlot::setCore(int ePlayer, bool bNewValue) { if (m_pPlot) m_pPlot->setCore((PlayerTypes)ePlayer, bNewValue); } int CyPlot::getSettlerValue(int ePlayer) { return m_pPlot ? m_pPlot->getSettlerValue((PlayerTypes)ePlayer) : -1; } void CyPlot::setSettlerValue(int ePlayer, int iNewValue) { if (m_pPlot) m_pPlot->setSettlerValue((PlayerTypes)ePlayer, iNewValue); } int CyPlot::getWarValue(int ePlayer) { return m_pPlot ? m_pPlot->getWarValue((PlayerTypes)ePlayer) : -1; } void CyPlot::setWarValue(int ePlayer, int iNewValue) { if (m_pPlot) m_pPlot->setWarValue((PlayerTypes)ePlayer, iNewValue); } int CyPlot::getSpreadFactor(int eReligion) { return m_pPlot ? m_pPlot->getSpreadFactor((ReligionTypes)eReligion) : -1; } void CyPlot::setSpreadFactor(int eReligion, int iNewValue) { if (m_pPlot) m_pPlot->setSpreadFactor((ReligionTypes)eReligion, iNewValue); } bool CyPlot::isWithinGreatWall() { return m_pPlot ? m_pPlot->isWithinGreatWall() : -1; } void CyPlot::setWithinGreatWall(bool bNewValue) { if (m_pPlot) m_pPlot->setWithinGreatWall(bNewValue); } void CyPlot::cameraLookAt() { if (m_pPlot) m_pPlot->cameraLookAt(); } int CyPlot::calculateOverallCulturePercent(int ePlayer) { return m_pPlot ? m_pPlot->calculateOverallCulturePercent((PlayerTypes)ePlayer) : 0; } void CyPlot::updateCulture() { if (m_pPlot) m_pPlot->updateCulture(true, true); } void CyPlot::setCultureConversion(int ePlayer, int iRate) { if (m_pPlot) m_pPlot->setCultureConversion((PlayerTypes)ePlayer, iRate); } void CyPlot::resetCultureConversion() { if (m_pPlot) m_pPlot->resetCultureConversion(); } int CyPlot::getCultureConversionPlayer() { return m_pPlot ? m_pPlot->getCultureConversionPlayer() : -1; } int CyPlot::getActualCulture(int ePlayer) { return m_pPlot ? m_pPlot->getActualCulture((PlayerTypes)ePlayer) : -1; }
24.658009
186
0.710042
macaurther
fff7edbfc2e8b6db2b65bf0176e06139546971cb
1,428
cpp
C++
Chapter04/SmartPointers/unique_ptr/main.cpp
ibiscum/Mastering-Cpp-Programming
313caae6b9d77e97b0ada93fc37511d55bfad699
[ "MIT" ]
25
2017-09-15T22:54:57.000Z
2022-02-07T06:52:06.000Z
Chapter04/SmartPointers/unique_ptr/main.cpp
ibiscum/Mastering-Cpp-Programming
313caae6b9d77e97b0ada93fc37511d55bfad699
[ "MIT" ]
1
2021-07-08T07:54:36.000Z
2021-07-08T07:54:36.000Z
Chapter04/SmartPointers/unique_ptr/main.cpp
ibiscum/Mastering-Cpp-Programming
313caae6b9d77e97b0ada93fc37511d55bfad699
[ "MIT" ]
19
2017-09-19T14:50:37.000Z
2021-12-04T15:34:48.000Z
#include <iostream> #include <string> #include <memory> #include <sstream> using namespace std; class MyClass { private: static int count; string name; public: MyClass() { ostringstream stringStream(ostringstream::ate); stringStream << "Object"; stringStream << ++count; name = stringStream.str(); cout << "\nMyClass Default constructor - " << name << endl; } ~MyClass() { cout << "\nMyClass destructor - " << name << endl; } MyClass ( const MyClass &objectBeingCopied ) { cout << "\nMyClass copy constructor" << endl; } MyClass& operator = ( const MyClass &objectBeingAssigned ) { cout << "\nMyClass assignment operator" << endl; } void sayHello() { cout << "Hello from MyClass " << name << endl; } }; int MyClass::count = 0; int main ( ) { unique_ptr<MyClass> ptr1( new MyClass() ); unique_ptr<MyClass> ptr2( new MyClass() ); ptr1->sayHello(); ptr2->sayHello(); //At this point the below stuffs happen //1. ptr2 smart pointer has given up ownership of MyClass Object 2 //2. MyClass Object 2 will be destructed as ptr2 has given up its ownership on Object 2 //3. Ownership of Object 1 will be transferred to ptr2 ptr2 = move(ptr1); //The line below if uncommented will result in core dump as ptr1 has given up its ownership //on Object 1 and the ownership of Object 1 is transferred to ptr2. ptr1->sayHello(); ptr2->sayHello(); return 0; }
22.3125
92
0.668768
ibiscum
fff9b871a32d5bc265eb6d9a098f3fc3f487137c
2,320
cpp
C++
Interview Bit/Max Non Negative Subarray.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
51
2020-02-24T11:14:00.000Z
2022-03-24T09:32:18.000Z
Interview Bit/Max Non Negative Subarray.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
3
2020-10-02T08:16:09.000Z
2021-04-17T16:32:38.000Z
Interview Bit/Max Non Negative Subarray.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
18
2020-04-24T15:33:36.000Z
2022-03-24T09:32:20.000Z
/* Interview Bit */ /* Title - Max Non Negative Subarray */ /* Created By - Akash Modak */ /* Date - 26/06/2020 */ // Given an array of integers, A of length N, find out the maximum sum sub-array of non negative numbers from A. // The sub-array should be contiguous i.e., a sub-array created by choosing the second and fourth element and skipping the third element is invalid. // Maximum sub-array is defined in terms of the sum of the elements in the sub-array. // Find and return the required subarray. // NOTE: // If there is a tie, then compare with segment's length and return segment which has maximum length. // If there is still a tie, then return the segment with minimum starting index. // Problem Constraints // 1 <= N <= 105 // -109 <= A[i] <= 109 // Input Format // The first and the only argument of input contains an integer array A, of length N. // Output Format // Return an array of integers, that is a subarray of A that satisfies the given conditions. // Example Input // Input 1: // A = [1, 2, 5, -7, 2, 3] // Input 2: // A = [10, -1, 2, 3, -4, 100] // Example Output // Output 1: // [1, 2, 5] // Output 2: // [100] // Example Explanation // Explanation 1: // The two sub-arrays are [1, 2, 5] [2, 3]. // The answer is [1, 2, 5] as its sum is larger than [2, 3]. // Explanation 2: // The three sub-arrays are [10], [2, 3], [100]. // The answer is [100] as its sum is larger than the other two. vector<int> Solution::maxset(vector<int> &A) { int n=A.size(); int i=0,maxm=0,count=0,start=0,end=-1; int fstart=-1,fend=-1; long long int sum=0,maxsum=0; vector<int> res; while(i<n){ if(A[i]>=0){ sum+=A[i]; count++; end++; } if(sum>maxsum){ maxsum=sum; fstart=start; fend=end; } else if(sum==maxsum&&count>maxm){ maxm=count; fstart=start; fend=end; } if(A[i]<0){ count=0; start=i+1;end=i; sum=0; } i++; } if(fstart!=-1&&fend!=-1){ for(int i=fstart;i<=fend;i++) res.push_back(A[i]); } return res; }
23.434343
149
0.54569
Shubhrmcf07
fffab5150cd082aa6df93e8b19553a00955046c4
735
cpp
C++
Contests/Codeforces/CF1011/D.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Contests/Codeforces/CF1011/D.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Contests/Codeforces/CF1011/D.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=40; const int inf=2147483647; int Opt[maxN]; int main() { int n,m,ans; scanf("%d%d",&m,&n); for (int i=1;i<=n;i++){ printf("1\n");fflush(stdout);scanf("%d",&ans); if (ans==0) exit(0); if (ans==1) Opt[i]=-1; else Opt[i]=1; } int L=1,R=m,outp=0,cnt=0; do { cnt++; if (cnt>n) cnt=1; int mid=(L+R)>>1; printf("%d\n",mid);fflush(stdout);scanf("%d",&ans); if (ans==0) exit(0); ans*=Opt[cnt]; if (ans==1) R=mid-1; else L=mid+1; } while (L<=R); printf("%d\n",L);fflush(stdout);scanf("%d",&ans); return 0; }
16.333333
53
0.589116
SYCstudio
08017ef8acdfa07563dacfb68cbf8d31337470e9
4,080
cc
C++
src/xapian/weight/inl2weight.cc
Kronuz/Xapiand
a71570859dcfc9f48090d845053f359b07f4f78c
[ "MIT" ]
370
2016-03-14T12:19:08.000Z
2022-03-25T02:07:29.000Z
src/xapian/weight/inl2weight.cc
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
34
2015-11-30T19:06:40.000Z
2022-02-26T03:46:58.000Z
src/xapian/weight/inl2weight.cc
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
31
2015-02-13T22:27:34.000Z
2022-03-25T02:07:34.000Z
/** @file inl2weight.cc * @brief Xapian::InL2Weight class - the InL2 weighting scheme of the DFR framework. */ /* Copyright (C) 2013,2014 Aarsh Shah * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "xapian/weight.h" #include "xapian/common/log2.h" #include "xapian/weight/weightinternal.h" #include "xapian/common/serialise-double.h" #include "xapian/error.h" using namespace std; namespace Xapian { InL2Weight::InL2Weight(double c) : param_c(c) { if (param_c <= 0) throw Xapian::InvalidArgumentError("Parameter c is invalid."); need_stat(AVERAGE_LENGTH); need_stat(DOC_LENGTH); need_stat(DOC_LENGTH_MIN); need_stat(COLLECTION_SIZE); need_stat(WDF); need_stat(WDF_MAX); need_stat(WQF); need_stat(TERMFREQ); } InL2Weight * InL2Weight::clone() const { return new InL2Weight(param_c); } void InL2Weight::init(double factor) { if (factor == 0.0) { // This object is for the term-independent contribution, and that's // always zero for this scheme. return; } double wdfn_upper = get_wdf_upper_bound(); if (wdfn_upper == 0) { upper_bound = 0.0; return; } double termfrequency = get_termfreq(); double N = get_collection_size(); wdfn_upper *= log2(1 + (param_c * get_average_length()) / get_doclength_lower_bound()); // wdfn * L = wdfn / (wdfn + 1) = 1 / (1 + 1 / wdfn). // To maximize the product, we need to minimize the denominator and so we use wdfn_upper in (1 / wdfn). double maximum_wdfn_product_L = wdfn_upper / (wdfn_upper + 1.0); // This term is constant for all documents. double idf_max = log2((N + 1) / (termfrequency + 0.5)); /* Calculate constant values to be used in get_sumpart() upfront. */ wqf_product_idf = get_wqf() * idf_max * factor; c_product_avlen = param_c * get_average_length(); upper_bound = wqf_product_idf * maximum_wdfn_product_L * factor; } string InL2Weight::name() const { return "Xapian::InL2Weight"; } string InL2Weight::short_name() const { return "inl2"; } string InL2Weight::serialise() const { return serialise_double(param_c); } InL2Weight * InL2Weight::unserialise(const string & s) const { const char *ptr = s.data(); const char *end = ptr + s.size(); double c = unserialise_double(&ptr, end); if (rare(ptr != end)) throw Xapian::SerialisationError("Extra data in InL2Weight::unserialise()"); return new InL2Weight(c); } double InL2Weight::get_sumpart(Xapian::termcount wdf, Xapian::termcount len, Xapian::termcount) const { if (wdf == 0) return 0.0; double wdfn = wdf; wdfn *= log2(1 + c_product_avlen / len); double wdfn_product_L = wdfn / (wdfn + 1.0); return (wqf_product_idf * wdfn_product_L); } double InL2Weight::get_maxpart() const { return upper_bound; } double InL2Weight::get_sumextra(Xapian::termcount, Xapian::termcount) const { return 0; } double InL2Weight::get_maxextra() const { return 0; } InL2Weight * InL2Weight::create_from_parameters(const char * p) const { if (*p == '\0') return new Xapian::InL2Weight(); double k = 1.0; if (!Xapian::Weight::Internal::double_param(&p, &k)) Xapian::Weight::Internal::parameter_error("Parameter is invalid", "inl2"); if (*p) Xapian::Weight::Internal::parameter_error("Extra data after parameter", "inl2"); return new Xapian::InL2Weight(k); } }
24.578313
107
0.692157
Kronuz
0801aa77f7f4d45276733c53ee7cd875cc7f10ce
506
hh
C++
include/simlib/defer.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
null
null
null
include/simlib/defer.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T17:50:32.000Z
2017-01-05T17:50:32.000Z
include/simlib/defer.hh
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T15:26:48.000Z
2017-01-05T15:26:48.000Z
#pragma once #include <utility> template <class Func> class Defer { Func func_; public: // NOLINTNEXTLINE(google-explicit-constructor) Defer(Func func) try : func_(std::move(func)) { } catch (...) { func(); throw; } Defer(const Defer&) = delete; Defer(Defer&&) = delete; Defer& operator=(const Defer&) = delete; Defer& operator=(Defer&&) = delete; ~Defer() { try { func_(); } catch (...) { } } };
16.322581
50
0.511858
varqox
0802ea0905ca05761dc8f06f6ae9c4390cef4d40
704
cpp
C++
zoe/src/zoe/display/Physics/AxisAlignedBox.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
7
2019-12-16T20:23:39.000Z
2020-10-26T08:46:12.000Z
zoe/src/zoe/display/Physics/AxisAlignedBox.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
13
2020-01-13T20:19:06.000Z
2021-09-10T21:23:52.000Z
zoe/src/zoe/display/Physics/AxisAlignedBox.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
7
2019-12-29T22:46:23.000Z
2020-07-15T19:56:32.000Z
// // Created by Florian on 20.12.2020. // #include "AxisAlignedBox.h" #include "cmath" namespace Zoe{ AxisAlignedBox::AxisAlignedBox(const vec3& lower, const vec3& higher) { AxisAlignedBox::lower = vec3(std::min(lower.x, higher.x), std::min(lower.y, higher.y), std::min(lower.z, higher.z)); AxisAlignedBox::higher = vec3(std::max(lower.x, higher.x), std::max(lower.y, higher.y), std::max(lower.z, higher.z)); } AxisAlignedBox::AxisAlignedBox(double x1, double y1, double z1, double x2, double y2, double z2) { AxisAlignedBox::lower = vec3(std::min(x1, x2), std::min(y1, y2), std::min(z1, z2)); AxisAlignedBox::higher = vec3(std::max(x1, x2), std::max(y1, y2), std::max(z1, z2)); } }
35.2
121
0.671875
NudelErde
08040c4e9fff3bdfc50d838bb796914dc14ba2cc
15,503
inl
C++
ThirdParty/Havok/include/Geometry/Internal/Algorithms/RayCast/hkcdRayCastCapsule.inl
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
11
2016-08-02T03:40:36.000Z
2022-03-15T13:41:29.000Z
ThirdParty/Havok/include/Geometry/Internal/Algorithms/RayCast/hkcdRayCastCapsule.inl
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
null
null
null
ThirdParty/Havok/include/Geometry/Internal/Algorithms/RayCast/hkcdRayCastCapsule.inl
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
8
2017-03-17T05:59:25.000Z
2021-02-27T08:51:46.000Z
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #include <Geometry/Internal/Types/hkcdRay.h> #include <Geometry/Internal/Algorithms/Distance/hkcdDistancePointLine.h> #include <Geometry/Internal/Algorithms/ClosestPoint/hkcdClosestPointLineLine.h> #include <Geometry/Internal/Algorithms/RayCast/hkcdRayCastSphere.h> HK_FORCE_INLINE hkcdRayCastResult hkcdRayCastCapsule( const hkcdRay& rayIn, hkVector4Parameter vertex0, hkVector4Parameter vertex1, hkSimdRealParameter radius, hkSimdReal* HK_RESTRICT fractionInOut, hkVector4* HK_RESTRICT normalOut, hkcdRayCastCapsuleHitType* HK_RESTRICT hitTypeOut, hkFlags<hkcdRayQueryFlags::Enum,hkUint32> flags ) { hkVector4Comparison insideHits; hkcdRayQueryFlags::isFlagSet(flags, hkcdRayQueryFlags::ENABLE_INSIDE_HITS, insideHits); hkcdRay ray = rayIn; const hkVector4& dA = ray.getDirection(); // Catch the case where the ray has length zero. if (HK_VERY_UNLIKELY(dA.equalZero().allAreSet<hkVector4ComparisonMask::MASK_XYZ>())) { return hkcdRayCastResult::NO_HIT; } hkVector4 dB; dB.setSub( vertex1, vertex0 ); hkSimdReal radiusSq = radius * radius; hkSimdReal fraction = *fractionInOut; hkVector4Comparison isInverseRay; isInverseRay.set<hkVector4ComparisonMask::MASK_NONE>(); hkSimdReal invScale = hkSimdReal_1; hkVector4Comparison isInsideComparison; hkcdRayCastResult success = hkcdRayCastResult::FRONT_FACE_HIT; { hkSimdReal sToCylDistSq = hkcdPointSegmentDistanceSquared( ray.m_origin, vertex0, vertex1 ); isInsideComparison = sToCylDistSq.less(radiusSq); if( HK_VERY_UNLIKELY( isInsideComparison.allAreSet() ) ) { success = hkcdRayCastResult(hkcdRayCastResult::BACK_FACE_HIT | hkcdRayCastResult::INSIDE_HIT); // origin inside the cylinder if ( HK_VERY_LIKELY( !insideHits.allAreSet() ) ) { return hkcdRayCastResult::NO_HIT; } else { // The origin is inside, so we invert the ray to get inside hits. // Inverting a ray that is extremely long might get us into accuracy issues, // so we conservatively resize the inverse ray to handle the issue: // We can setup an inverse ray ending at the inside point and starting outside the capsule. // To find the starting point outside the capsule, we can safely move from the inside point // along the ray's inverse direction by a distance that is the radius of a sphere englobing // the capsule (plus some padding = 2*radius ), capped by the size of the original ray. // We use 'invScale' to correct the final hitFraction later on. hkVector4 endPoint; endPoint.setAddMul( ray.m_origin, ray.m_direction, *fractionInOut ); hkSimdReal sToCylDistSq2 = hkcdPointSegmentDistanceSquared( endPoint, vertex0, vertex1 ); isInverseRay.set<hkVector4ComparisonMask::MASK_XYZW>(); hkSimdReal inRaySize = ray.getDirection().length<3>(); hkSimdReal invRayMaxSize = dB.length<3>() + hkSimdReal_4 * radius; hkSimdReal invRaySize; invRaySize.setMin( invRayMaxSize, inRaySize * ( *fractionInOut ) ); invScale.setDiv<HK_ACC_RAYCAST, HK_DIV_SET_ZERO>( invRaySize, inRaySize ); ray.m_direction.setMul( rayIn.m_direction, invScale ); ray.m_direction.setNeg<3>( ray.m_direction ); ray.m_origin.setSub( rayIn.m_origin, ray.m_direction ); // ray.m_invDirection is not used fraction = hkSimdReal_1; // Both ray points are inside the capsule. // Also safely catches the case where the ray has zero length. if( HK_VERY_UNLIKELY( sToCylDistSq2 < radiusSq ) ) { return hkcdRayCastResult::NO_HIT; } } } } // Work out closest points to cylinder hkSimdReal infInfDistSquared; hkSimdReal t, u; // Get distance between inf lines + parametric description (t, u) of closest points, { hkcdClosestPointLineLine(ray.m_origin, dA, vertex0, dB, t, u); hkVector4 p,q; p.setAddMul(ray.m_origin, dA, t); q.setAddMul(vertex0, dB, u); hkVector4 diff; diff.setSub(p, q); infInfDistSquared = diff.lengthSquared<3>(); if( infInfDistSquared > (radius*radius) ) { return hkcdRayCastResult::NO_HIT; // Infinite ray is outside radius of infinite cylinder } } hkSimdReal axisLength; hkVector4 axis; hkSimdReal ipT; { axis = dB; // Check for zero axis { hkSimdReal axisLengthSqrd = axis.lengthSquared<3>(); hkVector4Comparison mask = axisLengthSqrd.greater( hkSimdReal_Eps ); axisLength = axis.normalizeWithLength<3,HK_ACC_RAYCAST,HK_SQRT_IGNORE>(); axisLength.zeroIfFalse(mask); axis.zeroIfFalse(mask); } hkSimdReal component = dA.dot<3>(axis); // Flatdir is now a ray firing in the "plane" of the cylinder. hkVector4 flatDir; flatDir.setAddMul(dA, axis, -component); // Convert d to a parameterization instead of absolute distance along ray. hkSimdReal flatDirLengthSquared3 = flatDir.lengthSquared<3>(); // If flatDir is zero, the ray is parallel to the cylinder axis. In this case we set ipT to a // negative value to bypass the cylinder intersection test and go straight to the cap tests. hkVector4Comparison mask = flatDirLengthSquared3.equalZero(); hkSimdReal d = (radius * radius - infInfDistSquared) / flatDirLengthSquared3; ipT.setSelect(mask, hkSimdReal_Minus1, t - d.sqrt()); } // Intersection parameterization with infinite cylinder is outside length of ray // or is greater than a previous hit fraction if (ipT >= fraction ) { return hkcdRayCastResult::NO_HIT; } hkSimdReal ptHeight; hkSimdReal pointAProj = vertex0.dot<3>(axis); // Find intersection point of actual ray with infinite cylinder hkVector4 intersectPt; intersectPt.setAddMul( ray.m_origin, ray.getDirection(), ipT ); // Test height of intersection point w.r.t. cylinder axis // to determine hit against actual cylinder // Intersection point projected against cylinder hkSimdReal ptProj = intersectPt.dot<3>(axis); ptHeight = ptProj - pointAProj; if ( ipT.isGreaterEqualZero() ) // Actual ray (not infinite ray) must intersect with infinite cylinder { if ( ptHeight.isGreaterZero() && ptHeight.isLess(axisLength) ) // Report hit against cylinder part { // Calculate normal hkVector4 projPtOnAxis; projPtOnAxis.setInterpolate( vertex0, vertex1, ptHeight / axisLength ); hkVector4 normal; normal.setSub( intersectPt, projPtOnAxis ); normal.normalize<3>(); *normalOut = normal; hkSimdReal invIpT; invIpT.setSub( hkSimdReal_1, ipT ); invIpT.setMul( invIpT, invScale ); fractionInOut->setSelect( isInverseRay, invIpT, ipT ); *hitTypeOut = HK_CD_RAY_CAPSULE_BODY; return success; } } // Cap tests { // Check whether start point is inside infinite cylinder or not hkSimdReal fromLocalProj = ray.m_origin.dot<3>(axis); hkSimdReal projParam = fromLocalProj - pointAProj; hkVector4 fromPtProjAxis; fromPtProjAxis.setInterpolate( vertex0, vertex1, projParam / axisLength ); hkVector4 axisToRayStart; axisToRayStart.setSub( ray.m_origin, fromPtProjAxis); if ( ipT.isLessZero() && axisToRayStart.lengthSquared<3>().isGreater(radius * radius) ) { // Ray starts outside infinite cylinder and points away... must be no hit return hkcdRayCastResult::NO_HIT; } // Ray can only hit 1 cap... Use intersection point // to determine which sphere to test against (NB: this only works because // we have discarded cases where ray starts inside) hkVector4 capEnd; hkVector4Comparison mask = ptHeight.lessEqualZero(); capEnd.setSelect( mask, vertex0, vertex1 ); capEnd.setW( radius ); if( hkcdRayCastSphere( ray, capEnd, &fraction, normalOut, hkcdRayQueryFlags::NO_FLAGS).isHit() ) { hkSimdReal invFraction; invFraction.setSub( hkSimdReal_1, fraction ); invFraction.setMul( invFraction, invScale ); fractionInOut->setSelect( isInverseRay, invFraction, fraction ); *hitTypeOut = mask.anyIsSet() ? HK_CD_RAY_CAPSULE_CAP0 : HK_CD_RAY_CAPSULE_CAP1; return success; } return hkcdRayCastResult::NO_HIT; } } HK_FORCE_INLINE hkVector4Comparison hkcdRayBundleCapsuleIntersect( const hkcdRayBundle& rayBundle, hkVector4Parameter vertex0, hkVector4Parameter vertex1, hkSimdRealParameter radius, hkVector4& fractionsInOut, hkFourTransposedPoints& normalsOut ) { hkVector4 sToCylDistSq = hkcdPointSegmentDistanceSquared( rayBundle.m_start, vertex0, vertex1 ); hkVector4 radiusSqr; radiusSqr.setAll(radius * radius); hkVector4Comparison activeMask = rayBundle.m_activeRays; hkVector4Comparison rayStartOutside = sToCylDistSq.greaterEqual( radiusSqr ); activeMask.setAnd(activeMask, rayStartOutside); if ( !activeMask.anyIsSet() ) { return activeMask; } // Work out closest points to cylinder hkVector4 infInfDistSquared; //infInfDistSquared.setConstant<HK_QUADREAL_MAX>(); hkVector4 t, u; hkFourTransposedPoints dA; dA.setSub(rayBundle.m_end, rayBundle.m_start); hkVector4 dB; dB.setSub( vertex1, vertex0 ); // Get distance between inf lines + parametric description (t, u) of closest points, { hkcdClosestPointLineLine(rayBundle.m_start, dA, vertex0, dB, t, u); hkFourTransposedPoints p,q; p.setAddMulT(rayBundle.m_start, dA, t); hkFourTransposedPoints B4; B4.setAll(vertex0); hkFourTransposedPoints dB4; dB4.setAll(dB); q.setAddMulT(B4, dB4, u); hkFourTransposedPoints diff; diff.setSub(p, q); diff.dot3(diff, infInfDistSquared); } // Is infinite ray within radius of infinite cylinder? hkVector4Comparison isInfRayWithinCylinder = infInfDistSquared.lessEqual( radiusSqr ); activeMask.setAnd(activeMask, isInfRayWithinCylinder); if ( !activeMask.anyIsSet() ) { return activeMask; } hkSimdReal axisLength; hkVector4 axis; hkVector4 ipT; { axis = dB; // Check for zero axis hkSimdReal axisLengthSqrd = axis.lengthSquared<3>(); hkVector4Comparison mask = axisLengthSqrd.greater( hkSimdReal_Eps ); axisLength = axis.normalizeWithLength<3,HK_ACC_RAYCAST,HK_SQRT_IGNORE>(); axisLength.zeroIfFalse(mask); axis.zeroIfFalse(mask); hkVector4 component; dA.dot3(axis, component); component.setNeg<4>(component); hkFourTransposedPoints flatDir; hkFourTransposedPoints axis4; axis4.setAll(axis); flatDir.setAddMulT(dA, axis4, component); // Flatdir is now a ray firing in the "plane" of the cylinder. // Convert d to a parameterization instead of absolute distance along ray. // Avoid division by zero in case of ray parallel to infinite cylinder. hkVector4 flatDirLengthSquared3; flatDir.dot3(flatDir, flatDirLengthSquared3); hkVector4 d; d.setSub(radiusSqr, infInfDistSquared); d.div(flatDirLengthSquared3); d.setSqrt(d); d.setSub(t, d); mask = flatDirLengthSquared3.equalZero(); const hkVector4 minusOne = hkVector4::getConstant<HK_QUADREAL_MINUS1>(); ipT.setSelect(mask, minusOne, d); } // Intersection parameterization with infinite cylinder is outside length of ray // or is greater than a previous hit fraction hkVector4Comparison isFractionOk = ipT.less( fractionsInOut ); activeMask.setAnd(activeMask, isFractionOk); if( !activeMask.anyIsSet() ) { return activeMask; } hkVector4 ptHeight; const hkSimdReal pointAProj = vertex0.dot<3>(axis); // Find intersection point of actual ray with infinite cylinder hkFourTransposedPoints intersectPt; intersectPt.setAddMulT( rayBundle.m_start, dA, ipT ); // Test height of intersection point w.r.t. cylinder axis // to determine hit against actual cylinder // Intersection point projected against cylinder hkVector4 ptProj; intersectPt.dot3(axis, ptProj); ptHeight.setSub(ptProj, pointAProj); hkVector4 axisLengthVector; axisLengthVector.setAll(axisLength); hkFourTransposedPoints vertex0x4; vertex0x4.setAll(vertex0); hkFourTransposedPoints vertex1x4; vertex1x4.setAll(vertex1); hkFourTransposedPoints dBx4; dBx4.setAll(dB); hkVector4Comparison isRayWithinCylinder = ipT.greaterEqualZero(); hkVector4Comparison gtZero = ptHeight.greaterZero(); hkVector4Comparison ltAxisLength = ptHeight.less(axisLengthVector); hkVector4Comparison hitBodyMask; hitBodyMask.setAnd(gtZero, ltAxisLength); hitBodyMask.setAnd(hitBodyMask, isRayWithinCylinder); if ( hitBodyMask.anyIsSet() ) // Actual ray (not infinite ray) must intersect with infinite cylinder { // Calculate normal hkVector4 ratio; ratio.setDiv(ptHeight, axisLengthVector); hkFourTransposedPoints projPtOnAxis; projPtOnAxis.setAddMulT( vertex0x4, dBx4, ratio ); hkFourTransposedPoints normals; normals.setSub( intersectPt, projPtOnAxis ); normals.normalize(); normalsOut.setSelect(hitBodyMask, normals, normalsOut); // Output fraction fractionsInOut.setSelect(hitBodyMask, ipT, fractionsInOut); // This is a parameterization along the ray } hitBodyMask.setAndNot(activeMask, hitBodyMask); if (!hitBodyMask.anyIsSet()) { return activeMask; } // Cap tests { // Check whether start point is inside infinite cylinder or not hkVector4 fromLocalProj; rayBundle.m_start.dot3(axis, fromLocalProj); hkVector4 projParam; projParam.setSub(fromLocalProj, pointAProj); hkVector4 ratio; ratio.setDiv(projParam, axisLengthVector); hkFourTransposedPoints fromPtProjAxis; fromPtProjAxis.setAddMulT( vertex0x4, dBx4, ratio ); hkFourTransposedPoints axisToRayStart; axisToRayStart.setSub( rayBundle.m_start, fromPtProjAxis ); hkVector4 axisToRayStartLenSq; axisToRayStart.dot3(axisToRayStart, axisToRayStartLenSq); hkVector4Comparison gteZero = ipT.greaterEqualZero(); hkVector4Comparison lteRadiusSqr = axisToRayStartLenSq.lessEqual(radiusSqr); hkVector4Comparison maskOr; maskOr.setOr(gteZero, lteRadiusSqr); activeMask.setAnd(activeMask, maskOr); if ( !activeMask.anyIsSet() ) { // Ray starts outside infinite cylinder and points away... must be no hit return activeMask; } // Ray can only hit 1 cap... Use intersection point // to determine which sphere to test against (NB: this only works because // we have discarded cases where ray starts inside) hkFourTransposedPoints extra; hkVector4Comparison mask = ptHeight.lessEqualZero(); extra.setSelect( mask, vertex0x4, vertex1x4 ); hkcdRayBundle raySphere; raySphere.m_start.setSub(rayBundle.m_start, extra); raySphere.m_end.setSub(rayBundle.m_end, extra); raySphere.m_activeRays = hitBodyMask; hkVector4Comparison sphereMask = hkcdRayBundleSphereIntersect( raySphere, radius, fractionsInOut, normalsOut); activeMask.setSelect(hitBodyMask, sphereMask, activeMask); } return activeMask; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
35.63908
251
0.761014
wobbier
0804d8f097c1773304affe64b89d049d7f0a8b9d
751
cpp
C++
contest-1005-496/c-v2-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
1
2018-12-03T02:06:05.000Z
2018-12-03T02:06:05.000Z
contest-1005-496/c-v2-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
null
null
null
contest-1005-496/c-v2-cpp/main.cpp
easimonenko/solution-problems-from-codeforces
64251e0ba2c2ba619b0daf67f89f29b6dff8fd9f
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; int main() { int n; cin >> n; vector<long long> a(n); map<long long,int> v; for (int i = 0; i < n; i++) { cin >> a[i]; v[a[i]]++; } vector<long long> d; d.push_back(1); for (int i = 1; i < 32; i++) { d.push_back(d[i-1] << 1); } int ans = 0; for_each(a.begin(), a.end(), [&ans,d,&v](auto elem) { bool no = true; for (int k = 0; k < d.size(); k++) { long long r = d[k] - elem; if (r == elem && v[elem] == 1) { continue; } if (r > 0 && v.find(r) != v.end()) { no = false; break; } } if (no) { ans++; } //v.insert(elem); }); cout << ans << endl; return 0; }
16.326087
55
0.464714
easimonenko
08051db556842246b2d6309f0a26274fe72109e2
3,186
cpp
C++
Chapter5/PlayState.cpp
sgeos/book_sdl_game_development
a37466bfe916313216f332cbcff07dc6b3800908
[ "BSD-3-Clause" ]
5
2020-08-01T21:18:55.000Z
2021-11-30T12:12:37.000Z
Chapter5/PlayState.cpp
sgeos/book_sdl_game_development
a37466bfe916313216f332cbcff07dc6b3800908
[ "BSD-3-Clause" ]
null
null
null
Chapter5/PlayState.cpp
sgeos/book_sdl_game_development
a37466bfe916313216f332cbcff07dc6b3800908
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include "Constants.h" #include "DemoBackground.h" #include "Enemy.h" #include "Game.h" #include "GameOverState.h" #include "InputHandler.h" #include "PlayState.h" #include "PauseState.h" #include "Vector2D.h" const std::string PlayState::sStateId = "PLAY"; void PlayState::update(void) { for (std::vector<GameObject *>::size_type i = 0; i < mGameObjectList.size(); i++) { mGameObjectList[i]->update(); } int joypadId = 0; if (checkCollision(dynamic_cast<SdlGameObject *>(mGameObjectList[1]), dynamic_cast<SdlGameObject *>(mGameObjectList[2]))) { Game::Instance()->getStateMachine()->changeState(new GameOverState()); } else if (InputHandler::Instance()->isButtonDown(joypadId, 5) || InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE)) { Game::Instance()->getStateMachine()->pushState(new PauseState()); } } void PlayState::render(void) { for (std::vector<GameObject *>::size_type i = 0; i < mGameObjectList.size(); i++) { mGameObjectList[i]->draw(); } } bool PlayState::onEnter(void) { const std::string resourcePath = Constants::ResourcePath(""); bool success = TextureManager::Instance()->load("player", resourcePath + "helicopter0.png"); success = success && TextureManager::Instance()->load("enemy", resourcePath + "helicopter1.png"); success = success && TextureManager::Instance()->load("play_background", resourcePath + "background.png"); if (success) { int tileWidth, tileHeight; TextureManager::Instance()->queryTexture("play_background", nullptr, nullptr, &tileWidth, &tileHeight); mGameObjectList.push_back(new DemoBackground(new LoaderParams("play_background", 0, 0, tileWidth, tileHeight))); int x, y, w, h; TextureManager::Instance()->queryTexture("player", nullptr, nullptr, &w, &h); w /= 5; x = (Constants::WindowWidth() - w) / 2; y = (Constants::WindowHeight() - h) / 2 - 200; mGameObjectList.push_back(new Enemy(new LoaderParams("enemy", x, y, w, h))); y = (Constants::WindowHeight() - h) / 2; mGameObjectList.push_back(new Player(new LoaderParams("player", x, y, w, h))); std::cout << "Entering PlayState \"" << sStateId << "\"." << std::endl; } return true; } bool PlayState::onExit(void) { while (false == mGameObjectList.empty()) { delete mGameObjectList.back(); mGameObjectList.pop_back(); } TextureManager::Instance()->unload("player"); TextureManager::Instance()->unload("enemy"); TextureManager::Instance()->unload("play_background"); std::cout << "Exiting PlayState \"" << sStateId << "\"." << std::endl; return true; } bool PlayState::checkCollision(SdlGameObject *pObjectA, SdlGameObject *pObjectB) { int leftA, rightA, topA, bottomA; int leftB, rightB, topB, bottomB; leftA = pObjectA->getPosition().getX(); rightA = leftA + pObjectA->getWidth(); topA = pObjectA->getPosition().getY(); bottomA = topA + pObjectA->getHeight(); leftB = pObjectB->getPosition().getX(); rightB = leftB + pObjectB->getWidth(); topB = pObjectB->getPosition().getY(); bottomB = topB + pObjectB->getHeight(); return topA < bottomB && topB < bottomA && leftA < rightB && leftB < rightA; }
37.928571
127
0.680791
sgeos
0808fb3d8784296c96b3ba7d6e54a1309f55d33f
1,946
cpp
C++
encoder/vaapicodedbuffer.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
89
2015-01-09T10:31:13.000Z
2018-01-18T12:48:21.000Z
encoder/vaapicodedbuffer.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
626
2015-01-12T00:01:26.000Z
2018-01-23T18:58:58.000Z
encoder/vaapicodedbuffer.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
104
2015-01-12T04:02:09.000Z
2017-12-28T08:27:42.000Z
/* * Copyright (C) 2014 Intel Corporation. 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vaapicodedbuffer.h" #include "vaapi/vaapicontext.h" #include <string.h> namespace YamiMediaCodec{ CodedBufferPtr VaapiCodedBuffer::create(const ContextPtr& context, uint32_t bufSize) { CodedBufferPtr coded; BufObjectPtr buf = VaapiBuffer::create(context, VAEncCodedBufferType, bufSize); if (buf) coded.reset(new VaapiCodedBuffer(buf)); return coded; } bool VaapiCodedBuffer::map() { if (!m_segments) m_segments = static_cast<VACodedBufferSegment*>(m_buf->map()); return m_segments != NULL; } uint32_t VaapiCodedBuffer::size() { if (!map()) return 0; uint32_t size = 0; VACodedBufferSegment* segment = m_segments; while (segment != NULL) { size += segment->size; segment = static_cast<VACodedBufferSegment*>(segment->next); } return size; } bool VaapiCodedBuffer::copyInto(void* data) { if (!data) return false; if (!map()) return false; uint8_t* dest = static_cast<uint8_t*>(data); VACodedBufferSegment* segment = m_segments; while (segment != NULL) { memcpy(dest, segment->buf, segment->size); dest += segment->size; segment = static_cast<VACodedBufferSegment*>(segment->next); } return true; } }
27.027778
84
0.686536
genisysram
080b961151465ead797fe5492414d7af7a76d943
25,920
cpp
C++
examples/IBFE/explicit/ex6/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
2
2017-12-06T06:16:36.000Z
2021-03-13T12:28:08.000Z
examples/IBFE/explicit/ex6/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
examples/IBFE/explicit/ex6/main.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2002-2013, Boyce Griffith // 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 New York University nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // Config files #include <IBAMR_prefix_config.h> #include <IBTK_prefix_config.h> #include <SAMRAI_config.h> // Headers for basic PETSc functions #include <petscsys.h> // Headers for basic SAMRAI objects #include <BergerRigoutsos.h> #include <CartesianGridGeometry.h> #include <LoadBalancer.h> #include <StandardTagAndInitialize.h> // Headers for basic libMesh objects #include <libmesh/boundary_info.h> #include <libmesh/equation_systems.h> #include <libmesh/exodusII_io.h> #include <libmesh/mesh.h> #include <libmesh/mesh_function.h> #include <libmesh/mesh_generation.h> // Headers for application-specific algorithm/data structure objects #include <ibamr/IBExplicitHierarchyIntegrator.h> #include <ibamr/IBFEMethod.h> #include <ibamr/INSCollocatedHierarchyIntegrator.h> #include <ibamr/INSStaggeredHierarchyIntegrator.h> #include <ibamr/app_namespaces.h> #include <ibtk/AppInitializer.h> #include <ibtk/libmesh_utilities.h> #include <ibtk/muParserCartGridFunction.h> #include <ibtk/muParserRobinBcCoefs.h> // Elasticity model data. namespace ModelData { static double kappa_s = 1.0e6; // Tether (penalty) force function for the solid block. void block_tether_force_function( VectorValue<double>& F, const TensorValue<double>& /*FF*/, const Point& X, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { F = kappa_s*(s-X); return; }// block_tether_force_function // Tether (penalty) force function for the thin beam. void beam_tether_force_function( VectorValue<double>& F, const TensorValue<double>& /*FF*/, const Point& X, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { const double r = sqrt((s(0) - 0.2)*(s(0) - 0.2) + (s(1) - 0.2)*(s(1) - 0.2)); if (r <= 0.05) { F = kappa_s*(s-X); } else { F.zero(); } return; }// beam_tether_force_function // Stress tensor function for the thin beam. static double mu_s, lambda_s; void beam_PK1_stress_function( TensorValue<double>& PP, const TensorValue<double>& FF, const Point& /*X*/, const Point& s, Elem* const /*elem*/, NumericVector<double>& /*X_vec*/, const vector<NumericVector<double>*>& /*system_data*/, double /*time*/, void* /*ctx*/) { const double r = sqrt((s(0) - 0.2)*(s(0) - 0.2) + (s(1) - 0.2)*(s(1) - 0.2)); if (r > 0.05) { static const TensorValue<double> II(1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0); const TensorValue<double> CC = FF.transpose()*FF; const TensorValue<double> EE = 0.5*(CC - II); const TensorValue<double> SS = lambda_s*EE.tr()*II + 2.0*mu_s*EE; PP = FF*SS; } else { PP.zero(); } return; }// beam_PK1_stress_function } using namespace ModelData; // Function prototypes static ofstream drag_stream, lift_stream, A_x_posn_stream, A_y_posn_stream; void postprocess_data( Pointer<PatchHierarchy<NDIM> > patch_hierarchy, Pointer<INSHierarchyIntegrator> navier_stokes_integrator, Mesh& beam_mesh, EquationSystems* beam_equation_systems, Mesh& block_mesh, EquationSystems* block_equation_systems, const int iteration_num, const double loop_time, const string& data_dump_dirname); /******************************************************************************* * For each run, the input filename and restart information (if needed) must * * be given on the command line. For non-restarted case, command line is: * * * * executable <input file name> * * * * For restarted run, command line is: * * * * executable <input file name> <restart directory> <restart number> * * * *******************************************************************************/ int main( int argc, char* argv[]) { // Initialize libMesh, PETSc, MPI, and SAMRAI. LibMeshInit init(argc, argv); SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD); SAMRAI_MPI::setCallAbortInSerialInsteadOfExit(); SAMRAIManager::startup(); {// cleanup dynamically allocated objects prior to shutdown // Parse command line options, set some standard options from the input // file, initialize the restart database (if this is a restarted run), // and enable file logging. Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "IB.log"); Pointer<Database> input_db = app_initializer->getInputDatabase(); // Get various standard options set in the input file. const bool dump_viz_data = app_initializer->dumpVizData(); const int viz_dump_interval = app_initializer->getVizDumpInterval(); const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter(); const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty(); const string block_exodus_filename = app_initializer->getExodusIIFilename("block"); const string beam_exodus_filename = app_initializer->getExodusIIFilename("beam" ); const bool dump_restart_data = app_initializer->dumpRestartData(); const int restart_dump_interval = app_initializer->getRestartDumpInterval(); const string restart_dump_dirname = app_initializer->getRestartDumpDirectory(); const bool dump_postproc_data = app_initializer->dumpPostProcessingData(); const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval(); const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory(); if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty()) { Utilities::recursiveMkdir(postproc_data_dump_dirname); } const bool dump_timer_data = app_initializer->dumpTimerData(); const int timer_dump_interval = app_initializer->getTimerDumpInterval(); // Create a simple FE mesh. const double dx = input_db->getDouble("DX"); const double ds = input_db->getDouble("MFAC")*dx; Mesh block_mesh(NDIM); string block_elem_type = input_db->getString("BLOCK_ELEM_TYPE"); const double R = 0.05; if (block_elem_type == "TRI3" || block_elem_type == "TRI6") { const int num_circum_nodes = ceil(2.0*M_PI*R/ds); for (int k = 0; k < num_circum_nodes; ++k) { const double theta = 2.0*M_PI*static_cast<double>(k)/static_cast<double>(num_circum_nodes); block_mesh.add_point(Point(R*cos(theta), R*sin(theta))); } TriangleInterface triangle(block_mesh); triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL; triangle.elem_type() = Utility::string_to_enum<ElemType>(block_elem_type); triangle.desired_area() = sqrt(3.0)/4.0*ds*ds; triangle.insert_extra_points() = true; triangle.smooth_after_generating() = true; triangle.triangulate(); block_mesh.prepare_for_use(); } else { // NOTE: number of segments along boundary is 4*2^r. const double num_circum_segments = ceil(2.0*M_PI*R/ds); const int r = log2(0.25*num_circum_segments); MeshTools::Generation::build_sphere(block_mesh, R, r, Utility::string_to_enum<ElemType>(block_elem_type)); } for (MeshBase::node_iterator n_it = block_mesh.nodes_begin(); n_it != block_mesh.nodes_end(); ++n_it) { Node& n = **n_it; n(0) += 0.2; n(1) += 0.2; } Mesh beam_mesh(NDIM); string beam_elem_type = input_db->getString("BEAM_ELEM_TYPE"); MeshTools::Generation::build_square(beam_mesh, ceil(0.4/ds), ceil(0.02/ds), 0.2, 0.6, 0.19, 0.21, Utility::string_to_enum<ElemType>(beam_elem_type)); beam_mesh.prepare_for_use(); vector<Mesh*> meshes(2); meshes[0] = &block_mesh; meshes[1] = & beam_mesh; mu_s = input_db->getDouble("MU_S"); lambda_s = input_db->getDouble("LAMBDA_S"); kappa_s = input_db->getDouble("KAPPA_S"); // Create major algorithm and data objects that comprise the // application. These objects are configured from the input database // and, if this is a restarted run, from the restart database. Pointer<INSHierarchyIntegrator> navier_stokes_integrator; const string solver_type = app_initializer->getComponentDatabase("Main")->getString("solver_type"); if (solver_type == "STAGGERED") { navier_stokes_integrator = new INSStaggeredHierarchyIntegrator( "INSStaggeredHierarchyIntegrator", app_initializer->getComponentDatabase("INSStaggeredHierarchyIntegrator")); } else if (solver_type == "COLLOCATED") { navier_stokes_integrator = new INSCollocatedHierarchyIntegrator( "INSCollocatedHierarchyIntegrator", app_initializer->getComponentDatabase("INSCollocatedHierarchyIntegrator")); } else { TBOX_ERROR("Unsupported solver type: " << solver_type << "\n" << "Valid options are: COLLOCATED, STAGGERED"); } Pointer<IBFEMethod> ib_method_ops = new IBFEMethod( "IBFEMethod", app_initializer->getComponentDatabase("IBFEMethod"), meshes, app_initializer->getComponentDatabase("GriddingAlgorithm")->getInteger("max_levels")); Pointer<IBHierarchyIntegrator> time_integrator = new IBExplicitHierarchyIntegrator( "IBHierarchyIntegrator", app_initializer->getComponentDatabase("IBHierarchyIntegrator"), ib_method_ops, navier_stokes_integrator); Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>( "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry")); Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>( "PatchHierarchy", grid_geometry); Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>( "StandardTagAndInitialize", time_integrator, app_initializer->getComponentDatabase("StandardTagAndInitialize")); Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>(); Pointer<LoadBalancer<NDIM> > load_balancer = new LoadBalancer<NDIM>( "LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer")); Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm = new GriddingAlgorithm<NDIM>( "GriddingAlgorithm", app_initializer->getComponentDatabase("GriddingAlgorithm"), error_detector, box_generator, load_balancer); // Configure the IBFE solver. ib_method_ops->registerLagBodyForceFunction(&block_tether_force_function, std::vector<unsigned int>(), NULL, 0); ib_method_ops->registerLagBodyForceFunction( &beam_tether_force_function, std::vector<unsigned int>(), NULL, 1); ib_method_ops->registerPK1StressTensorFunction(&beam_PK1_stress_function, std::vector<unsigned int>(), NULL, 1); EquationSystems* block_equation_systems = ib_method_ops->getFEDataManager(0)->getEquationSystems(); EquationSystems* beam_equation_systems = ib_method_ops->getFEDataManager(1)->getEquationSystems(); // Create Eulerian initial condition specification objects. if (input_db->keyExists("VelocityInitialConditions")) { Pointer<CartGridFunction> u_init = new muParserCartGridFunction( "u_init", app_initializer->getComponentDatabase("VelocityInitialConditions"), grid_geometry); navier_stokes_integrator->registerVelocityInitialConditions(u_init); } if (input_db->keyExists("PressureInitialConditions")) { Pointer<CartGridFunction> p_init = new muParserCartGridFunction( "p_init", app_initializer->getComponentDatabase("PressureInitialConditions"), grid_geometry); navier_stokes_integrator->registerPressureInitialConditions(p_init); } // Create Eulerian boundary condition specification objects (when necessary). const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift(); vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM); if (periodic_shift.min() > 0) { for (unsigned int d = 0; d < NDIM; ++d) { u_bc_coefs[d] = NULL; } } else { for (unsigned int d = 0; d < NDIM; ++d) { ostringstream bc_coefs_name_stream; bc_coefs_name_stream << "u_bc_coefs_" << d; const string bc_coefs_name = bc_coefs_name_stream.str(); ostringstream bc_coefs_db_name_stream; bc_coefs_db_name_stream << "VelocityBcCoefs_" << d; const string bc_coefs_db_name = bc_coefs_db_name_stream.str(); u_bc_coefs[d] = new muParserRobinBcCoefs( bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry); } navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs); } // Create Eulerian body force function specification objects. if (input_db->keyExists("ForcingFunction")) { Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction( "f_fcn", app_initializer->getComponentDatabase("ForcingFunction"), grid_geometry); time_integrator->registerBodyForceFunction(f_fcn); } // Set up visualization plot file writers. Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter(); if (uses_visit) { time_integrator->registerVisItDataWriter(visit_data_writer); } AutoPtr<ExodusII_IO> block_exodus_io(uses_exodus ? new ExodusII_IO(block_mesh) : NULL); AutoPtr<ExodusII_IO> beam_exodus_io(uses_exodus ? new ExodusII_IO( beam_mesh) : NULL); // Initialize hierarchy configuration and data on all patches. ib_method_ops->initializeFEData(); time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm); // Deallocate initialization objects. app_initializer.setNull(); // Print the input database contents to the log file. plog << "Input database:\n"; input_db->printClassData(plog); // Write out initial visualization data. int iteration_num = time_integrator->getIntegratorStep(); double loop_time = time_integrator->getIntegratorTime(); if (dump_viz_data) { pout << "\n\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { block_exodus_io->write_timestep(block_exodus_filename, *block_equation_systems, iteration_num/viz_dump_interval+1, loop_time); beam_exodus_io ->write_timestep( beam_exodus_filename, * beam_equation_systems, iteration_num/viz_dump_interval+1, loop_time); } } // Open streams to save lift and drag coefficients. if (SAMRAI_MPI::getRank() == 0) { drag_stream.open("C_D.curve", ios_base::out | ios_base::trunc); lift_stream.open("C_L.curve", ios_base::out | ios_base::trunc); A_x_posn_stream.open("A_x.curve", ios_base::out | ios_base::trunc); A_y_posn_stream.open("A_y.curve", ios_base::out | ios_base::trunc); } // Main time step loop. double loop_time_end = time_integrator->getEndTime(); double dt = 0.0; while (!MathUtilities<double>::equalEps(loop_time,loop_time_end) && time_integrator->stepsRemaining()) { iteration_num = time_integrator->getIntegratorStep(); loop_time = time_integrator->getIntegratorTime(); pout << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "At beginning of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; dt = time_integrator->getMaximumTimeStepSize(); time_integrator->advanceHierarchy(dt); loop_time += dt; pout << "\n"; pout << "At end of timestep # " << iteration_num << "\n"; pout << "Simulation time is " << loop_time << "\n"; pout << "+++++++++++++++++++++++++++++++++++++++++++++++++++\n"; pout << "\n"; // At specified intervals, write visualization and restart files, // print out timer data, and store hierarchy data for post // processing. iteration_num += 1; const bool last_step = !time_integrator->stepsRemaining(); if (dump_viz_data && (iteration_num%viz_dump_interval == 0 || last_step)) { pout << "\nWriting visualization files...\n\n"; if (uses_visit) { time_integrator->setupPlotData(); visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time); } if (uses_exodus) { block_exodus_io->write_timestep(block_exodus_filename, *block_equation_systems, iteration_num/viz_dump_interval+1, loop_time); beam_exodus_io ->write_timestep( beam_exodus_filename, * beam_equation_systems, iteration_num/viz_dump_interval+1, loop_time); } } if (dump_restart_data && (iteration_num%restart_dump_interval == 0 || last_step)) { pout << "\nWriting restart files...\n\n"; RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num); } if (dump_timer_data && (iteration_num%timer_dump_interval == 0 || last_step)) { pout << "\nWriting timer data...\n\n"; TimerManager::getManager()->print(plog); } if (dump_postproc_data && (iteration_num%postproc_data_dump_interval == 0 || last_step)) { pout << "\nWriting state data...\n\n"; postprocess_data(patch_hierarchy, navier_stokes_integrator, beam_mesh, beam_equation_systems, block_mesh, block_equation_systems, iteration_num, loop_time, postproc_data_dump_dirname); } } // Close the logging streams. if (SAMRAI_MPI::getRank() == 0) { drag_stream.close(); lift_stream.close(); A_x_posn_stream.close(); A_y_posn_stream.close(); } // Cleanup Eulerian boundary condition specification objects (when // necessary). for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d]; }// cleanup dynamically allocated objects prior to shutdown SAMRAIManager::shutdown(); return 0; }// main void postprocess_data( Pointer<PatchHierarchy<NDIM> > /*patch_hierarchy*/, Pointer<INSHierarchyIntegrator> /*navier_stokes_integrator*/, Mesh& beam_mesh, EquationSystems* beam_equation_systems, Mesh& block_mesh, EquationSystems* block_equation_systems, const int /*iteration_num*/, const double loop_time, const string& /*data_dump_dirname*/) { double F_integral[NDIM]; for (unsigned int d = 0; d < NDIM; ++d) F_integral[d] = 0.0; Mesh* mesh[2] = {&beam_mesh , &block_mesh}; EquationSystems* equation_systems[2] = {beam_equation_systems , block_equation_systems}; for (unsigned int k = 0; k < 2; ++k) { System& F_system = equation_systems[k]->get_system<System>(IBFEMethod::FORCE_SYSTEM_NAME); NumericVector<double>* F_vec = F_system.solution.get(); NumericVector<double>* F_ghost_vec = F_system.current_local_solution.get(); F_vec->localize(*F_ghost_vec); DofMap& F_dof_map = F_system.get_dof_map(); blitz::Array<std::vector<unsigned int>,1> F_dof_indices(NDIM); AutoPtr<FEBase> fe(FEBase::build(NDIM, F_dof_map.variable_type(0))); AutoPtr<QBase> qrule = QBase::build(QGAUSS, NDIM, FIFTH); fe->attach_quadrature_rule(qrule.get()); const std::vector<std::vector<double> >& phi = fe->get_phi(); const std::vector<double>& JxW = fe->get_JxW(); blitz::Array<double,2> F_node; const MeshBase::const_element_iterator el_begin = mesh[k]->active_local_elements_begin(); const MeshBase::const_element_iterator el_end = mesh[k]->active_local_elements_end(); for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it) { Elem* const elem = *el_it; fe->reinit(elem); for (unsigned int d = 0; d < NDIM; ++d) { F_dof_map.dof_indices(elem, F_dof_indices(d), d); } const int n_qp = qrule->n_points(); const int n_basis = F_dof_indices(0).size(); get_values_for_interpolation(F_node, *F_ghost_vec, F_dof_indices); for (int qp = 0; qp < n_qp; ++qp) { for (int k = 0; k < n_basis; ++k) { for (int d = 0; d < NDIM; ++d) { F_integral[d] += F_node(k,d)*phi[k][qp]*JxW[qp]; } } } } } SAMRAI_MPI::sumReduction(F_integral,NDIM); if (SAMRAI_MPI::getRank() == 0) { drag_stream.precision(12); drag_stream.setf(ios::fixed,ios::floatfield); drag_stream << loop_time << " " << -F_integral[0] << endl; lift_stream.precision(12); lift_stream.setf(ios::fixed,ios::floatfield); lift_stream << loop_time << " " << -F_integral[1] << endl; } System& X_system = beam_equation_systems->get_system<System>(IBFEMethod::COORDS_SYSTEM_NAME); NumericVector<double>* X_vec = X_system.solution.get(); AutoPtr<NumericVector<Number> > X_serial_vec = NumericVector<Number>::build(); X_serial_vec->init(X_vec->size(), true, SERIAL); X_vec->localize(*X_serial_vec); DofMap& X_dof_map = X_system.get_dof_map(); vector<unsigned int> vars(2); vars[0] = 0; vars[1] = 1; MeshFunction X_fcn(*beam_equation_systems, *X_serial_vec, X_dof_map, vars); X_fcn.init(); DenseVector<double> X_A(2); X_fcn(Point(0.6,0.2,0), 0.0, X_A); if (SAMRAI_MPI::getRank() == 0) { A_x_posn_stream.precision(12); A_x_posn_stream.setf(ios::fixed,ios::floatfield); A_x_posn_stream << loop_time << " " << X_A(0) << endl; A_y_posn_stream.precision(12); A_y_posn_stream.setf(ios::fixed,ios::floatfield); A_y_posn_stream << loop_time << " " << X_A(1) << endl; } return; }// postprocess_data
45
173
0.621952
MSV-Project
080e711d0461bcc65eeee7ceeff7aa9d626a0570
4,195
hpp
C++
SDK/ARKSurvivalEvolved_Jugbug_Character_BaseBP_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Jugbug_Character_BaseBP_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Jugbug_Character_BaseBP_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Jugbug_Character_BaseBP_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Jugbug_Character_BaseBP.Jugbug_Character_BaseBP_C // 0x0048 (0x22B0 - 0x2268) class AJugbug_Character_BaseBP_C : public AInsect_Character_Base_C { public: class UDinoCharacterStatusComponent_BP_JugBug_C* DinoCharacterStatus_BP_JugBug_C1; // 0x2268(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UAudioComponent* LivingAudio; // 0x2270(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) float ResourceAmount; // 0x2278(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData) TEnumAsByte<EJugbugType> JugbugType; // 0x227C(0x0001) (Edit, BlueprintVisible, ZeroConstructor, SaveGame, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x227D(0x0003) MISSED OFFSET float MaxResourceAmount; // 0x2280(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float ResourceAmountFillTime; // 0x2284(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float MinSpeed; // 0x2288(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) int MaxItemsToGive; // 0x228C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) class UClass* PrimalItemToGive; // 0x2290(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) double LastUpdateTime; // 0x2298(0x0008) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) float MaxJugbugWaterGiveAmount; // 0x22A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x4]; // 0x22A4(0x0004) MISSED OFFSET double LastGiveResourcesTime; // 0x22A8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Jugbug_Character_BaseBP.Jugbug_Character_BaseBP_C"); return ptr; } void BPTimerNonDedicated(); void BPTimerServer(); bool BlueprintCanAttack(int* AttackIndex, float* Distance, float* attackRangeOffset, class AActor** OtherTarget); TArray<struct FMultiUseEntry> STATIC_BPGetMultiUseEntries(class APlayerController** ForPC, TArray<struct FMultiUseEntry>* MultiUseEntries); void AddResource(float amount, float* NewResourceAmount, float* AddedResourceAmount); bool BPTryMultiUse(class APlayerController** ForPC, int* UseIndex); void RefreshResourceAmount(); void BlueprintDrawFloatingHUD(class AShooterHUD** HUD, float* CenterX, float* CenterY, float* DrawScale); void UserConstructionScript(); void ExecuteUbergraph_Jugbug_Character_BaseBP(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
67.66129
223
0.579023
2bite
080fb35dcf54903da9cb5c65214501b380c3a870
6,248
cpp
C++
src/utility/RTC8563_Class.cpp
mayopan/M5Unified
d5473378016c98e3932a83fcfbb54e644c4aab7a
[ "MIT" ]
38
2021-10-10T14:37:44.000Z
2022-03-20T10:45:41.000Z
src/utility/RTC8563_Class.cpp
mayopan/M5Unified
d5473378016c98e3932a83fcfbb54e644c4aab7a
[ "MIT" ]
15
2021-11-01T05:52:07.000Z
2022-03-05T23:02:34.000Z
src/utility/RTC8563_Class.cpp
mayopan/M5Unified
d5473378016c98e3932a83fcfbb54e644c4aab7a
[ "MIT" ]
9
2021-10-10T15:53:05.000Z
2022-03-06T16:24:19.000Z
// Copyright (c) M5Stack. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "RTC8563_Class.hpp" #include <sys/time.h> namespace m5 { static std::uint8_t bcd2ToByte(std::uint8_t value) { return ((value >> 4) * 10) + (value & 0x0F); } static std::uint8_t byteToBcd2(std::uint8_t value) { std::uint_fast8_t bcdhigh = value / 10; return (bcdhigh << 4) | (value - (bcdhigh * 10)); } bool RTC8563_Class::begin(I2C_Class* i2c) { if (i2c) { _i2c = i2c; i2c->begin(); } /// TimerCameraの内蔵RTCが初期化に失敗することがあったため、最初に空打ちする; writeRegister8(0x00, 0x00); _init = writeRegister8(0x00, 0x00) && writeRegister8(0x0E, 0x03); return _init; } bool RTC8563_Class::getVoltLow(void) { return readRegister8(0x02) & 0x80; // RTCC_VLSEC_MASK } bool RTC8563_Class::getDateTime(rtc_datetime_t* datetime) const { std::uint8_t buf[7] = { 0 }; if (!isEnabled() || !readRegister(0x02, buf, 7)) { return false; } datetime->time.seconds = bcd2ToByte(buf[0] & 0x7f); datetime->time.minutes = bcd2ToByte(buf[1] & 0x7f); datetime->time.hours = bcd2ToByte(buf[2] & 0x3f); datetime->date.date = bcd2ToByte(buf[3] & 0x3f); datetime->date.weekDay = bcd2ToByte(buf[4] & 0x07); datetime->date.month = bcd2ToByte(buf[5] & 0x1f); datetime->date.year = bcd2ToByte(buf[6] & 0xff) + ((0x80 & buf[5]) ? 1900 : 2000); return true; } bool RTC8563_Class::getTime(rtc_time_t* time) const { std::uint8_t buf[3] = { 0 }; if (!isEnabled() || !readRegister(0x02, buf, 3)) { return false; } time->seconds = bcd2ToByte(buf[0] & 0x7f); time->minutes = bcd2ToByte(buf[1] & 0x7f); time->hours = bcd2ToByte(buf[2] & 0x3f); return true; } void RTC8563_Class::setTime(const rtc_time_t& time) { std::uint8_t buf[] = { byteToBcd2(time.seconds) , byteToBcd2(time.minutes) , byteToBcd2(time.hours) }; writeRegister(0x02, buf, sizeof(buf)); } bool RTC8563_Class::getDate(rtc_date_t* date) const { std::uint8_t buf[4] = {0}; if (!readRegister(0x05, buf, 4)) { return false; } date->date = bcd2ToByte(buf[0] & 0x3f); date->weekDay = bcd2ToByte(buf[1] & 0x07); date->month = bcd2ToByte(buf[2] & 0x1f); date->year = bcd2ToByte(buf[3] & 0xff) + ((0x80 & buf[2]) ? 1900 : 2000); return true; } void RTC8563_Class::setDate(const rtc_date_t& date) { std::uint8_t w = date.weekDay; if (w > 6 && date.year >= 1900 && ((std::size_t)(date.month - 1)) < 12) { /// weekDay auto adjust std::int_fast16_t y = date.year / 100; w = (date.year + (date.year >> 2) - y + (y >> 2) + (13 * date.month + 8) / 5 + date.date) % 7; } std::uint8_t buf[] = { byteToBcd2(date.date) , w , (std::uint8_t)(byteToBcd2(date.month) + (date.year < 2000 ? 0x80 : 0)) , byteToBcd2(date.year % 100) }; writeRegister(0x05, buf, sizeof(buf)); } int RTC8563_Class::setAlarmIRQ(int afterSeconds) { std::uint8_t reg_value = readRegister8(0x01) & ~0x0C; if (afterSeconds < 0) { // disable timer writeRegister8(0x01, reg_value & ~0x01); writeRegister8(0x0E, 0x03); return -1; } std::size_t div = 1; std::uint8_t type_value = 0x82; if (afterSeconds < 270) { if (afterSeconds > 255) { afterSeconds = 255; } } else { div = 60; afterSeconds = (afterSeconds + 30) / div; if (afterSeconds > 255) { afterSeconds = 255; } type_value = 0x83; } writeRegister8(0x0E, type_value); writeRegister8(0x0F, afterSeconds); writeRegister8(0x01, (reg_value | 0x01) & ~0x80); return afterSeconds * div; } int RTC8563_Class::setAlarmIRQ(const rtc_time_t &time) { union { std::uint32_t raw = ~0; std::uint8_t buf[4]; }; bool irq_enable = false; if (time.minutes >= 0) { irq_enable = true; buf[0] = byteToBcd2(time.minutes) & 0x7f; } if (time.hours >= 0) { irq_enable = true; buf[1] = byteToBcd2(time.hours) & 0x3f; } writeRegister(0x09, buf, 4); if (irq_enable) { bitOn(0x01, 0x02); } else { bitOff(0x01, 0x02); } return irq_enable; } int RTC8563_Class::setAlarmIRQ(const rtc_date_t &date, const rtc_time_t &time) { union { std::uint32_t raw = ~0; std::uint8_t buf[4]; }; bool irq_enable = false; if (time.minutes >= 0) { irq_enable = true; buf[0] = byteToBcd2(time.minutes) & 0x7f; } if (time.hours >= 0) { irq_enable = true; buf[1] = byteToBcd2(time.hours) & 0x3f; } if (date.date >= 0) { irq_enable = true; buf[2] = byteToBcd2(date.date) & 0x3f; } if (date.weekDay >= 0) { irq_enable = true; buf[3] = byteToBcd2(date.weekDay) & 0x07; } writeRegister(0x09, buf, 4); if (irq_enable) { bitOn(0x01, 1 << 1); } else { bitOff(0x01, 1 << 1); } return irq_enable; } bool RTC8563_Class::getIRQstatus(void) { return _init && (0x0C & readRegister8(0x01)); } void RTC8563_Class::clearIRQ(void) { if (!_init) { return; } bitOff(0x01, 0x0C); } void RTC8563_Class::disableIRQ(void) { if (!_init) { return; } // disable alerm (bit7:1=disabled) std::uint8_t buf[4] = { 0x80, 0x80, 0x80, 0x80 }; writeRegister(0x09, buf, 4); // disable timer (bit7:0=disabled) writeRegister8(0x0E, 0); // clear flag and INT enable bits writeRegister8(0x01, 0x00); } void RTC8563_Class::setSystemTimeFromRtc(void) { rtc_datetime_t dt; if (getDateTime(&dt)) { tm t_st; t_st.tm_isdst = -1; t_st.tm_year = dt.date.year - 1900; t_st.tm_mon = dt.date.month - 1; t_st.tm_mday = dt.date.date; t_st.tm_hour = dt.time.hours; t_st.tm_min = dt.time.minutes; t_st.tm_sec = dt.time.seconds; timeval now; now.tv_sec = mktime(&t_st); now.tv_usec = 0; settimeofday(&now, nullptr); } } }
23.226766
101
0.579706
mayopan
08111f5cfdab849b74ce81849b788bde66f7f895
1,673
cpp
C++
src/State/IntroState.cpp
trew/TDP005
f604b7e3f3bc10dd4f0cad354f7fccc5d9797a5b
[ "MIT" ]
null
null
null
src/State/IntroState.cpp
trew/TDP005
f604b7e3f3bc10dd4f0cad354f7fccc5d9797a5b
[ "MIT" ]
null
null
null
src/State/IntroState.cpp
trew/TDP005
f604b7e3f3bc10dd4f0cad354f7fccc5d9797a5b
[ "MIT" ]
null
null
null
#include <State/IntroState.h> #include <Core/Define.h> #include <SDL2_gfxPrimitives.h> #include <Core/GameEngine.h> bool IntroState::init() { internalState = DEVSCREEN; devScreen = new Sprite(game, "./gfx/intro/devscreen.png", 0, 0, WWIDTH, WHEIGHT); introScreen = new Sprite(game, "./gfx/intro/introscreen.png", 0, 0, WWIDTH, WHEIGHT); startTime = SDL_GetTicks(); return true; } void IntroState::cleanup() { delete devScreen; delete introScreen; } bool IntroState::handleEvent(const SDL_Event &ev) { if (ev.type == SDL_QUIT) { game->getEngine()->exit(); return true; } else if (ev.type == SDL_KEYDOWN) { if (ev.key.keysym.sym == SDLK_ESCAPE || ev.key.keysym.sym == SDLK_SPACE) { if (internalState == INTROSCREEN) { game->getEngine()->setState((State*)game->mainMenuState); } else { internalState = INTROSCREEN; } return true; } } return false; } void IntroState::update(const float &timeStep) { if (SDL_GetTicks() > (startTime + 6000) && internalState == DEVSCREEN) internalState = INTROSCREEN; } void IntroState::render(SDL_Renderer* const renderer) { if (internalState == DEVSCREEN) { unsigned int initial_delay = 1000; unsigned int fadeout_time = 3000; int alpha_level = 255 - ((SDL_GetTicks() - initial_delay) / 5); if (alpha_level < 0) alpha_level = 0; if (SDL_GetTicks() > initial_delay && SDL_GetTicks() <= fadeout_time) { devScreen->draw(renderer); boxRGBA(renderer, 0, 0, WWIDTH, WHEIGHT, 0, 0, 0, alpha_level); } else if (SDL_GetTicks() > initial_delay) devScreen->draw(renderer); } else if (internalState == INTROSCREEN) { introScreen->draw(renderer); } }
20.402439
86
0.676629
trew
08136e19c5e71985be23ecc203603009025ac121
1,307
hpp
C++
AST/JSONStruct.hpp
germago119/C__IDE
2fb9950e2c67932eb69806094c65fcd9ae9ca220
[ "MIT" ]
null
null
null
AST/JSONStruct.hpp
germago119/C__IDE
2fb9950e2c67932eb69806094c65fcd9ae9ca220
[ "MIT" ]
null
null
null
AST/JSONStruct.hpp
germago119/C__IDE
2fb9950e2c67932eb69806094c65fcd9ae9ca220
[ "MIT" ]
1
2020-02-07T17:41:56.000Z
2020-02-07T17:41:56.000Z
// // Created by Roger Valderrama on 4/10/18. // /** * @file JSONStruct.hpp * @version 1.0 * @date 4/10/18 * @author Roger Valderrama * @title JSON for Structs * @brief JSON Class for saving structs with its variables. */ #ifndef C_IDE_JSONSTRUCT_HPP #define C_IDE_JSONSTRUCT_HPP #include "JSONVar.hpp" #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> class JSONStruct { /** * @brief An array oj Json for the variables of the line of code. */ QJsonArray *variables = new QJsonArray; /** * @brief json that represent the JsonObject that will be modified. */ QJsonObject *json = new QJsonObject; public: /** * @brief It add all variables to a Json and it prints it and add it to the log file. */ void submit(); /** * @brief Converts the JSON into a char so it can be added to the log file. */ const char *toLog(); /** * @brief Converts the JSON into a string. */ std::string toString(); /** * @brief It adds Variables to the JSON for struct. * @param jsonVar each json variable it will add. */ void add(JSONVar *jsonVar); /** * @brief It inserts to the JSON each key with its value. */ void put(std::string, std::string); }; #endif //C_IDE_JSONSTRUCT_HPP
20.107692
88
0.633512
germago119
0813a661d4d3fdbd66f5829b0064d23e999e0450
1,721
hpp
C++
include/cynodelic/tesela/detail/tdouble_ops.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
include/cynodelic/tesela/detail/tdouble_ops.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
include/cynodelic/tesela/detail/tdouble_ops.hpp
cynodelic/tesela
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt /** * @file tdouble_ops.hpp * * @brief Macros for defining `tdouble` operators. */ #ifndef CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP #define CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP #include <cynodelic/tesela/config.hpp> #define CYNODELIC_TESELA_TDOUBLE_DEFINE_ARITHMETIC_OPERATOR(op) \ constexpr friend tdouble operator op(const tdouble& lhs,const tdouble& rhs) \ { \ return tdouble(lhs.data op rhs.data); \ } \ constexpr friend tdouble operator op(const tdouble& lhs,const value_type& rhs) \ { \ return tdouble(lhs.data op tdouble(rhs).data); \ } \ constexpr friend tdouble operator op(const value_type& lhs,const tdouble& rhs) \ { \ return tdouble(tdouble(lhs).data op rhs.data); \ } #define CYNODELIC_TESELA_TDOUBLE_DEFINE_COMPARISON_OPERATOR(op) \ constexpr friend bool operator op(const tdouble& lhs,const tdouble& rhs) \ { \ return lhs.data op rhs.data; \ } \ constexpr friend bool operator op(const tdouble& lhs,const value_type& rhs) \ { \ return lhs.data op rhs; \ } \ constexpr friend bool operator op(const value_type& lhs,const tdouble& rhs) \ { \ return lhs op rhs.data; \ } #define CYNODELIC_TESELA_TDOUBLE_DEFINE_COMPOUND_OPERATOR(cmp_op,op) \ template <typename T> \ tdouble& operator cmp_op(const T& rhs) \ { \ data = quantize(data op quantize(rhs)); \ return *this; \ } \ tdouble& operator cmp_op(const tdouble& rhs) \ { \ data = quantize(data op rhs.data); \ return *this; \ } #endif // CYNODELIC_TESELA_DETAIL_TDOUBLE_OPS_HPP
27.31746
82
0.715863
cynodelic
0814f2a81b75fe973444bad545cb414d902d4397
9,524
hpp
C++
src/functions/functions.hpp
Hotege/irafl
1154bb69650e98998b28aed688f424cfb94413f9
[ "MIT" ]
null
null
null
src/functions/functions.hpp
Hotege/irafl
1154bb69650e98998b28aed688f424cfb94413f9
[ "MIT" ]
null
null
null
src/functions/functions.hpp
Hotege/irafl
1154bb69650e98998b28aed688f424cfb94413f9
[ "MIT" ]
null
null
null
#if !defined(_FUNCTIONS_FUNCTIONS_HPP_) #define _FUNCTIONS_FUNCTIONS_HPP_ #include <irafldef.h> #include <cmath> namespace IRAFLFunc { static double PI = atan(1.0) * 4; static double ColorNormal[256] = { 0.0, 0.00392156862745098, 0.00784313725490196, 0.011764705882352941, 0.01568627450980392, 0.0196078431372549, 0.023529411764705882, 0.027450980392156862, 0.03137254901960784, 0.03529411764705882, 0.0392156862745098, 0.043137254901960784, 0.047058823529411764, 0.050980392156862744, 0.054901960784313725, 0.058823529411764705, 0.06274509803921569, 0.06666666666666667, 0.07058823529411765, 0.07450980392156863, 0.0784313725490196, 0.08235294117647059, 0.08627450980392157, 0.09019607843137255, 0.09411764705882353, 0.09803921568627451, 0.10196078431372549, 0.10588235294117647, 0.10980392156862745, 0.11372549019607843, 0.11764705882352941, 0.12156862745098039, 0.12549019607843137, 0.12941176470588237, 0.13333333333333333, 0.13725490196078433, 0.1411764705882353, 0.1450980392156863, 0.14901960784313725, 0.15294117647058825, 0.1568627450980392, 0.1607843137254902, 0.16470588235294117, 0.16862745098039217, 0.17254901960784313, 0.17647058823529413, 0.1803921568627451, 0.1843137254901961, 0.18823529411764706, 0.19215686274509805, 0.19607843137254902, 0.2, 0.20392156862745098, 0.20784313725490197, 0.21176470588235294, 0.21568627450980393, 0.2196078431372549, 0.2235294117647059, 0.22745098039215686, 0.23137254901960785, 0.23529411764705882, 0.23921568627450981, 0.24313725490196078, 0.24705882352941178, 0.25098039215686274, 0.2549019607843137, 0.25882352941176473, 0.2627450980392157, 0.26666666666666666, 0.27058823529411763, 0.27450980392156865, 0.2784313725490196, 0.2823529411764706, 0.28627450980392155, 0.2901960784313726, 0.29411764705882354, 0.2980392156862745, 0.30196078431372547, 0.3058823529411765, 0.30980392156862746, 0.3137254901960784, 0.3176470588235294, 0.3215686274509804, 0.3254901960784314, 0.32941176470588235, 0.3333333333333333, 0.33725490196078434, 0.3411764705882353, 0.34509803921568627, 0.34901960784313724, 0.35294117647058826, 0.3568627450980392, 0.3607843137254902, 0.36470588235294116, 0.3686274509803922, 0.37254901960784315, 0.3764705882352941, 0.3803921568627451, 0.3843137254901961, 0.38823529411764707, 0.39215686274509803, 0.396078431372549, 0.4, 0.403921568627451, 0.40784313725490196, 0.4117647058823529, 0.41568627450980394, 0.4196078431372549, 0.4235294117647059, 0.42745098039215684, 0.43137254901960786, 0.43529411764705883, 0.4392156862745098, 0.44313725490196076, 0.4470588235294118, 0.45098039215686275, 0.4549019607843137, 0.4588235294117647, 0.4627450980392157, 0.4666666666666667, 0.47058823529411764, 0.4745098039215686, 0.47843137254901963, 0.4823529411764706, 0.48627450980392156, 0.49019607843137253, 0.49411764705882355, 0.4980392156862745, 0.5019607843137255, 0.5058823529411764, 0.5098039215686274, 0.5137254901960784, 0.5176470588235295, 0.5215686274509804, 0.5254901960784314, 0.5294117647058824, 0.5333333333333333, 0.5372549019607843, 0.5411764705882353, 0.5450980392156862, 0.5490196078431373, 0.5529411764705883, 0.5568627450980392, 0.5607843137254902, 0.5647058823529412, 0.5686274509803921, 0.5725490196078431, 0.5764705882352941, 0.5803921568627451, 0.5843137254901961, 0.5882352941176471, 0.592156862745098, 0.596078431372549, 0.6, 0.6039215686274509, 0.6078431372549019, 0.611764705882353, 0.615686274509804, 0.6196078431372549, 0.6235294117647059, 0.6274509803921569, 0.6313725490196078, 0.6352941176470588, 0.6392156862745098, 0.6431372549019608, 0.6470588235294118, 0.6509803921568628, 0.6549019607843137, 0.6588235294117647, 0.6627450980392157, 0.6666666666666666, 0.6705882352941176, 0.6745098039215687, 0.6784313725490196, 0.6823529411764706, 0.6862745098039216, 0.6901960784313725, 0.6941176470588235, 0.6980392156862745, 0.7019607843137254, 0.7058823529411765, 0.7098039215686275, 0.7137254901960784, 0.7176470588235294, 0.7215686274509804, 0.7254901960784313, 0.7294117647058823, 0.7333333333333333, 0.7372549019607844, 0.7411764705882353, 0.7450980392156863, 0.7490196078431373, 0.7529411764705882, 0.7568627450980392, 0.7607843137254902, 0.7647058823529411, 0.7686274509803922, 0.7725490196078432, 0.7764705882352941, 0.7803921568627451, 0.7843137254901961, 0.788235294117647, 0.792156862745098, 0.796078431372549, 0.8, 0.803921568627451, 0.807843137254902, 0.8117647058823529, 0.8156862745098039, 0.8196078431372549, 0.8235294117647058, 0.8274509803921568, 0.8313725490196079, 0.8352941176470589, 0.8392156862745098, 0.8431372549019608, 0.8470588235294118, 0.8509803921568627, 0.8549019607843137, 0.8588235294117647, 0.8627450980392157, 0.8666666666666667, 0.8705882352941177, 0.8745098039215686, 0.8784313725490196, 0.8823529411764706, 0.8862745098039215, 0.8901960784313725, 0.8941176470588236, 0.8980392156862745, 0.9019607843137255, 0.9058823529411765, 0.9098039215686274, 0.9137254901960784, 0.9176470588235294, 0.9215686274509803, 0.9254901960784314, 0.9294117647058824, 0.9333333333333333, 0.9372549019607843, 0.9411764705882353, 0.9450980392156862, 0.9490196078431372, 0.9529411764705882, 0.9568627450980393, 0.9607843137254902, 0.9647058823529412, 0.9686274509803922, 0.9725490196078431, 0.9764705882352941, 0.9803921568627451, 0.984313725490196, 0.9882352941176471, 0.9921568627450981, 0.996078431372549, 1.0, }; static const unsigned int crc32tab[] = { 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL }; uint32_t CRC32Get(const void* vbuf, unsigned int size) { const unsigned char* buf = (const unsigned char*)vbuf; unsigned int i, crc; crc = 0xFFFFFFFF; for (i = 0; i < size; i++) crc = crc32tab[(crc ^ buf[i]) & 0xff] ^ (crc >> 8); return crc ^ 0xFFFFFFFF; } } #endif
90.704762
343
0.789164
Hotege
0818cff8fe62ef46802eb2f857c29fa5927985c2
320
cpp
C++
list10_2/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
list10_2/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
list10_2/main.cpp
rimever/SuraSuraCPlus
acbc6e1d0d0bb9bf07e28ab02c30ac021b1f6899
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; template<class T> T getMin(T a, T b) { return a < b ? a : b; } int main() { int a, b, c; a = 123; b = 456; c = getMin(a, b); cout << c << endl; double x, y, z; x = 1.23; y = 4.56; z = getMin(x, y); cout << z << endl; return 0; }
14.545455
25
0.4625
rimever
081beac538b3aa47e226bdca458c9ca2bff952d8
161
cpp
C++
instrumentation/src/utils/fastint.cpp
shdnx/MooCoverage
59c313d8fb16090c14aeaa3320b39913f6b5dfa9
[ "MIT" ]
6
2015-09-22T21:11:32.000Z
2021-12-29T15:33:16.000Z
instrumentation/src/utils/fastint.cpp
shdnx/MooCoverage
59c313d8fb16090c14aeaa3320b39913f6b5dfa9
[ "MIT" ]
null
null
null
instrumentation/src/utils/fastint.cpp
shdnx/MooCoverage
59c313d8fb16090c14aeaa3320b39913f6b5dfa9
[ "MIT" ]
1
2021-12-29T15:33:18.000Z
2021-12-29T15:33:18.000Z
#include "moocov/utils/fastint.h" namespace moocov { namespace utils { const FastIntWriterManip fastInt{}; } // end namespace utils } // end namespace moocov
16.1
35
0.745342
shdnx
081c4245ceb6cbaeac26985d17f422d974faf423
6,961
cpp
C++
Pyext/src/ExportSuiteAndFamily.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Pyext/src/ExportSuiteAndFamily.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Pyext/src/ExportSuiteAndFamily.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // Name : // Author : Avi // Revision : $Revision: #85 $ // // Copyright 2009- ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // file deepcode ignore CppConstantBinaryExpression: <comment the reason here> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/python/raw_function.hpp> #include <boost/core/noncopyable.hpp> #include "Defs.hpp" #include "Suite.hpp" #include "Family.hpp" #include "Task.hpp" #include "BoostPythonUtil.hpp" #include "DefsDoc.hpp" #include "NodeUtil.hpp" using namespace ecf; using namespace boost::python; using namespace std; namespace bp = boost::python; // See: http://wiki.python.org/moin/boost.python/HowTo#boost.function_objects /// Since we don't pass in a child pos, the nodes are added to the end family_ptr add_family(NodeContainer* self,family_ptr f){ self->addFamily(f); return f; } task_ptr add_task(NodeContainer* self,task_ptr t){ self->addTask(t); return t;} suite_ptr add_clock(suite_ptr self, const ClockAttr& clk) { self->addClock(clk); return self;} suite_ptr add_end_clock(suite_ptr self, const ClockAttr& clk) { self->add_end_clock(clk); return self;} // Sized and Container protocol size_t family_len(family_ptr self) { return self->nodeVec().size();} size_t suite_len(suite_ptr self) { return self->nodeVec().size();} bool family_container(family_ptr self, const std::string& name){size_t pos; return (self->findImmediateChild(name,pos)) ? true: false;} bool suite_container(suite_ptr self, const std::string& name) {size_t pos; return (self->findImmediateChild(name,pos)) ? true: false;} // Context management, Only used to provide indentation suite_ptr suite_enter(suite_ptr self) { return self;} bool suite_exit(suite_ptr self,const bp::object& type,const bp::object& value,const bp::object& traceback){return false;} family_ptr family_enter(family_ptr self) { return self;} bool family_exit(family_ptr self,const bp::object& type,const bp::object& value,const bp::object& traceback){return false;} family_ptr family_init(const std::string& name, bp::list the_list, bp::dict kw) { //cout << "family_init : " << name << " the_list: " << len(the_list) << " dict: " << len(kw) << endl; family_ptr node = Family::create(name); (void)NodeUtil::add_variable_dict(node,kw); (void)NodeUtil::node_iadd(node,the_list); return node; } suite_ptr suite_init(const std::string& name, bp::list the_list, bp::dict kw) { //cout << "suite_init : " << name << " the_list: " << len(the_list) << " dict: " << len(kw) << endl; suite_ptr node = Suite::create(name); (void)NodeUtil::add_variable_dict(node,kw); (void)NodeUtil::node_iadd(node,the_list); return node; } void export_SuiteAndFamily() { // Turn off proxies by passing true as the NoProxy template parameter. // shared_ptrs don't need proxies because calls on one a copy of the // shared_ptr will affect all of them (duh!). class_<std::vector<family_ptr> >("FamilyVec","Hold a list of `family`_ nodes") .def(vector_indexing_suite<std::vector<family_ptr>, true >()) ; class_<std::vector<suite_ptr> >("SuiteVec","Hold a list of `suite`_ nodes's") .def(vector_indexing_suite<std::vector<suite_ptr>, true >()); // choose the correct overload class_<NodeContainer, bases<Node>, boost::noncopyable >("NodeContainer",DefsDoc::node_container_doc(), no_init) .def("__iter__",bp::range(&NodeContainer::node_begin,&NodeContainer::node_end)) .def("add_family",&NodeContainer::add_family ,DefsDoc::add_family_doc()) .def("add_family",add_family ) .def("add_task", &NodeContainer::add_task , DefsDoc::add_task_doc()) .def("add_task", add_task ) .def("find_node", &NodeContainer::find_by_name, "Find immediate child node given a name") .def("find_task", &NodeContainer::findTask , "Find a task given a name") .def("find_family", &NodeContainer::findFamily , "Find a family given a name") .add_property("nodes",bp::range( &NodeContainer::node_begin,&NodeContainer::node_end),"Returns a list of Node's") ; class_<Family, bases<NodeContainer>, family_ptr>("Family",DefsDoc::family_doc()) .def("__init__",raw_function(&NodeUtil::node_raw_constructor,1)) // will call -> family_init .def("__init__",make_constructor(&family_init), DefsDoc::family_doc()) .def("__init__",make_constructor(&Family::create_me), DefsDoc::family_doc()) .def(self == self ) // __eq__ .def("__str__", &Family::to_string) // __str__ .def("__copy__", copyObject<Family>) // __copy__ uses copy constructor .def("__enter__", &family_enter) // allow with statement, hence indentation support .def("__exit__", &family_exit) // allow with statement, hence indentation support .def("__len__", &family_len) // Implement sized protocol for immediate children .def("__contains__",&family_container) // Implement container protocol for immediate children ; #if ECF_ENABLE_PYTHON_PTR_REGISTER bp::register_ptr_to_python<family_ptr>(); // needed for mac and boost 1.6 #endif class_<Suite, bases<NodeContainer>, suite_ptr>("Suite",DefsDoc::suite_doc()) .def("__init__",raw_function(&NodeUtil::node_raw_constructor,1)) // will call -> suite_init .def("__init__",make_constructor(&suite_init), DefsDoc::suite_doc()) .def("__init__",make_constructor(&Suite::create_me), DefsDoc::suite_doc()) .def(self == self ) // __eq__ .def("__str__", &Suite::to_string) // __str__ .def("__copy__", copyObject<Suite>) // __copy__ uses copy constructor .def("__enter__", &suite_enter) // allow with statement, hence indentation support .def("__exit__", &suite_exit) // allow with statement, hence indentation support .def("__len__", &suite_len) // Implement sized protocol for immediate children .def("__contains__",&suite_container) // Implement container protocol for immediate children .def("add_clock", &add_clock) .def("get_clock", &Suite::clockAttr,"Returns the `suite`_ `clock`_") .def("add_end_clock", &add_end_clock,"End clock, used to mark end of simulation") .def("get_end_clock", &Suite::clock_end_attr,"Return the suite's end clock. Can be NULL") .def("begun", &Suite::begun, "Returns true if the `suite`_ has begun, false otherwise") ; #if ECF_ENABLE_PYTHON_PTR_REGISTER bp::register_ptr_to_python<suite_ptr>(); // needed for mac and boost 1.6 #endif }
50.810219
135
0.699899
mpartio
081d4fe97337f2c5b388ad6eff4f849d47929eb0
969
cpp
C++
tests/insert_id.cpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
2
2018-01-16T18:05:21.000Z
2021-02-02T05:04:51.000Z
tests/insert_id.cpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
null
null
null
tests/insert_id.cpp
Wassasin/librusql
207919e5da1e9e49d4c575c81699fcb1d8cd6204
[ "BSD-3-Clause" ]
null
null
null
#include <rusql/rusql.hpp> #include "test.hpp" #include "database_test.hpp" #include <cstdlib> int main(int argc, char *argv[]) { auto db = get_database(argc, argv); test_init(4); test_start_try(4); try { db->execute("CREATE TABLE rusqltest (`id` INTEGER(10) PRIMARY KEY AUTO_INCREMENT, `value` INT(2) NOT NULL)"); auto statement = db->prepare("INSERT INTO rusqltest (`value`) VALUES (67)"); statement.execute(); uint64_t insert_id = statement.insert_id(); auto st2 = db->prepare("SELECT id FROM rusqltest WHERE value=67"); st2.execute(); uint64_t real_insert_id = 0xdeadbeef; st2.bind_results(real_insert_id); test(st2.fetch(), "one result"); test(real_insert_id != 0xdeadbeef, "real_insert_id was changed"); test(real_insert_id == insert_id, "last_insert_id() returned correctly"); test(!st2.fetch(), "one result only"); } catch(std::exception &e) { diag(e); } test_finish_try(); db->execute("DROP TABLE rusqltest"); return 0; }
30.28125
111
0.701754
Wassasin
082335effc7cbf2e3ba41b00bc9080c25dc0fd0b
5,633
cpp
C++
source/glbinding/source/gl/functions_l.cpp
cpp-pm/glbinding
663e19cf1ae6a5fa1acfb1bd952fc43f647ca79c
[ "MIT" ]
632
2015-07-01T18:03:24.000Z
2022-03-17T08:25:51.000Z
source/glbinding/source/gl/functions_l.cpp
cpp-pm/glbinding
663e19cf1ae6a5fa1acfb1bd952fc43f647ca79c
[ "MIT" ]
191
2015-07-01T16:11:32.000Z
2022-02-10T22:04:09.000Z
source/glbinding/source/gl/functions_l.cpp
cpp-pm/glbinding
663e19cf1ae6a5fa1acfb1bd952fc43f647ca79c
[ "MIT" ]
89
2015-10-26T11:18:07.000Z
2022-03-31T16:22:50.000Z
#include "../Binding_pch.h" #include <glbinding/gl/functions.h> namespace gl { void glLabelObjectEXT(GLenum type, GLuint object, GLsizei length, const GLchar * label) { return glbinding::Binding::LabelObjectEXT(type, object, length, label); } void glLGPUCopyImageSubDataNVX(GLuint sourceGpu, GLbitfield destinationGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srxY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth) { return glbinding::Binding::LGPUCopyImageSubDataNVX(sourceGpu, destinationGpuMask, srcName, srcTarget, srcLevel, srcX, srxY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, width, height, depth); } void glLGPUInterlockNVX() { return glbinding::Binding::LGPUInterlockNVX(); } void glLGPUNamedBufferSubDataNVX(GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const void * data) { return glbinding::Binding::LGPUNamedBufferSubDataNVX(gpuMask, buffer, offset, size, data); } void glLightEnviSGIX(GLenum pname, GLint param) { return glbinding::Binding::LightEnviSGIX(pname, param); } void glLightf(GLenum light, GLenum pname, GLfloat param) { return glbinding::Binding::Lightf(light, pname, param); } void glLightfv(GLenum light, GLenum pname, const GLfloat * params) { return glbinding::Binding::Lightfv(light, pname, params); } void glLighti(GLenum light, GLenum pname, GLint param) { return glbinding::Binding::Lighti(light, pname, param); } void glLightiv(GLenum light, GLenum pname, const GLint * params) { return glbinding::Binding::Lightiv(light, pname, params); } void glLightModelf(GLenum pname, GLfloat param) { return glbinding::Binding::LightModelf(pname, param); } void glLightModelfv(GLenum pname, const GLfloat * params) { return glbinding::Binding::LightModelfv(pname, params); } void glLightModeli(GLenum pname, GLint param) { return glbinding::Binding::LightModeli(pname, param); } void glLightModeliv(GLenum pname, const GLint * params) { return glbinding::Binding::LightModeliv(pname, params); } void glLightModelxOES(GLenum pname, GLfixed param) { return glbinding::Binding::LightModelxOES(pname, param); } void glLightModelxvOES(GLenum pname, const GLfixed * param) { return glbinding::Binding::LightModelxvOES(pname, param); } void glLightxOES(GLenum light, GLenum pname, GLfixed param) { return glbinding::Binding::LightxOES(light, pname, param); } void glLightxvOES(GLenum light, GLenum pname, const GLfixed * params) { return glbinding::Binding::LightxvOES(light, pname, params); } void glLineStipple(GLint factor, GLushort pattern) { return glbinding::Binding::LineStipple(factor, pattern); } void glLineWidth(GLfloat width) { return glbinding::Binding::LineWidth(width); } void glLineWidthxOES(GLfixed width) { return glbinding::Binding::LineWidthxOES(width); } void glLinkProgram(GLuint program) { return glbinding::Binding::LinkProgram(program); } void glLinkProgramARB(GLhandleARB programObj) { return glbinding::Binding::LinkProgramARB(programObj); } void glListBase(GLuint base) { return glbinding::Binding::ListBase(base); } void glListDrawCommandsStatesClientNV(GLuint list, GLuint segment, const void ** indirects, const GLsizei * sizes, const GLuint * states, const GLuint * fbos, GLuint count) { return glbinding::Binding::ListDrawCommandsStatesClientNV(list, segment, indirects, sizes, states, fbos, count); } void glListParameterfSGIX(GLuint list, GLenum pname, GLfloat param) { return glbinding::Binding::ListParameterfSGIX(list, pname, param); } void glListParameterfvSGIX(GLuint list, GLenum pname, const GLfloat * params) { return glbinding::Binding::ListParameterfvSGIX(list, pname, params); } void glListParameteriSGIX(GLuint list, GLenum pname, GLint param) { return glbinding::Binding::ListParameteriSGIX(list, pname, param); } void glListParameterivSGIX(GLuint list, GLenum pname, const GLint * params) { return glbinding::Binding::ListParameterivSGIX(list, pname, params); } void glLoadIdentity() { return glbinding::Binding::LoadIdentity(); } void glLoadIdentityDeformationMapSGIX(FfdMaskSGIX mask) { return glbinding::Binding::LoadIdentityDeformationMapSGIX(mask); } void glLoadMatrixd(const GLdouble * m) { return glbinding::Binding::LoadMatrixd(m); } void glLoadMatrixf(const GLfloat * m) { return glbinding::Binding::LoadMatrixf(m); } void glLoadMatrixxOES(const GLfixed * m) { return glbinding::Binding::LoadMatrixxOES(m); } void glLoadName(GLuint name) { return glbinding::Binding::LoadName(name); } void glLoadProgramNV(GLenum target, GLuint id, GLsizei len, const GLubyte * program) { return glbinding::Binding::LoadProgramNV(target, id, len, program); } void glLoadTransposeMatrixd(const GLdouble * m) { return glbinding::Binding::LoadTransposeMatrixd(m); } void glLoadTransposeMatrixdARB(const GLdouble * m) { return glbinding::Binding::LoadTransposeMatrixdARB(m); } void glLoadTransposeMatrixf(const GLfloat * m) { return glbinding::Binding::LoadTransposeMatrixf(m); } void glLoadTransposeMatrixfARB(const GLfloat * m) { return glbinding::Binding::LoadTransposeMatrixfARB(m); } void glLoadTransposeMatrixxOES(const GLfixed * m) { return glbinding::Binding::LoadTransposeMatrixxOES(m); } void glLockArraysEXT(GLint first, GLsizei count) { return glbinding::Binding::LockArraysEXT(first, count); } void glLogicOp(GLenum opcode) { return glbinding::Binding::LogicOp(opcode); } } // namespace gl
25.373874
297
0.756258
cpp-pm
0823f63cb7a139e1a779ed1bbc1630279460107f
776
cpp
C++
plugins/opengl/src/clear/depth_buffer.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/src/clear/depth_buffer.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/src/clear/depth_buffer.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/opengl/call.hpp> #include <sge/opengl/check_state.hpp> #include <sge/opengl/common.hpp> #include <sge/opengl/clear/depth_buffer.hpp> #include <sge/renderer/exception.hpp> #include <sge/renderer/clear/depth_buffer_value.hpp> #include <fcppt/text.hpp> #include <fcppt/cast/size.hpp> void sge::opengl::clear::depth_buffer(sge::renderer::clear::depth_buffer_value const &_value) { sge::opengl::call(::glClearDepth, fcppt::cast::size<GLdouble>(_value)); SGE_OPENGL_CHECK_STATE(FCPPT_TEXT("glClearDepth failed"), sge::renderer::exception) }
36.952381
93
0.742268
cpreh
08247b67a6036ea9f500344de36b0117965d8d98
989
cpp
C++
src/components/oscilloscope.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
17
2021-03-22T14:17:16.000Z
2022-02-22T20:58:27.000Z
src/components/oscilloscope.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
null
null
null
src/components/oscilloscope.cpp
jan-van-bergen/Synth
cc6fee6376974a3cc2e86899ab2859a5f1fb7e33
[ "MIT" ]
1
2021-11-17T18:00:55.000Z
2021-11-17T18:00:55.000Z
#include "oscilloscope.h" #include <ImGui/implot.h> void OscilloscopeComponent::update(Synth const & synth) { memset(samples, 0, sizeof(samples)); for (auto const & [other, weight] : inputs[0].others) { for (int i = 0; i < BLOCK_SIZE; i++) { samples[i] += weight * other->get_sample(i).left; } } } void OscilloscopeComponent::render(Synth const & synth) { auto avail = ImGui::GetContentRegionAvail(); auto space = ImVec2(avail.x, std::max( ImGui::GetTextLineHeightWithSpacing(), avail.y - (inputs.size() + outputs.size()) * ImGui::GetTextLineHeightWithSpacing() )); ImPlot::SetNextPlotLimits(0.0, BLOCK_SIZE, -1.0, 1.0, ImGuiCond_Always); if (ImPlot::BeginPlot("Osciloscope", nullptr, nullptr, space, ImPlotFlags_CanvasOnly, ImPlotAxisFlags_NoDecorations)) { ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f); ImPlot::PlotShaded("", samples, BLOCK_SIZE); ImPlot::PlotLine ("", samples, BLOCK_SIZE); ImPlot::PopStyleVar(); ImPlot::EndPlot(); } }
29.088235
120
0.703741
jan-van-bergen
0825dbf0b27b6e909c310aee51fa262b25af0d91
211,173
cpp
C++
3rdparty/openmm/plugins/amoeba/platforms/cuda/src/AmoebaCudaKernels.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
5
2020-07-31T17:33:03.000Z
2022-01-01T19:24:37.000Z
3rdparty/openmm/plugins/amoeba/platforms/cuda/src/AmoebaCudaKernels.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
11
2020-06-16T05:05:42.000Z
2022-03-30T09:59:14.000Z
3rdparty/openmm/plugins/amoeba/platforms/cuda/src/AmoebaCudaKernels.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
9
2020-01-24T12:02:37.000Z
2020-10-16T06:23:56.000Z
/* -------------------------------------------------------------------------- * * OpenMMAmoeba * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2008-2018 Stanford University and the Authors. * * Authors: Peter Eastman, Mark Friedrichs * * Contributors: * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as published * * by the Free Software Foundation, either version 3 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 Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * -------------------------------------------------------------------------- */ #ifdef WIN32 #define _USE_MATH_DEFINES // Needed to get M_PI #endif #include "AmoebaCudaKernels.h" #include "CudaAmoebaKernelSources.h" #include "openmm/internal/ContextImpl.h" #include "openmm/internal/AmoebaGeneralizedKirkwoodForceImpl.h" #include "openmm/internal/AmoebaMultipoleForceImpl.h" #include "openmm/internal/AmoebaWcaDispersionForceImpl.h" #include "openmm/internal/AmoebaTorsionTorsionForceImpl.h" #include "openmm/internal/AmoebaVdwForceImpl.h" #include "openmm/internal/NonbondedForceImpl.h" #include "CudaBondedUtilities.h" #include "CudaFFT3D.h" #include "CudaForceInfo.h" #include "CudaKernelSources.h" #include "jama_lu.h" #include <algorithm> #include <cmath> #ifdef _MSC_VER #include <windows.h> #endif using namespace OpenMM; using namespace std; #define CHECK_RESULT(result, prefix) \ if (result != CUDA_SUCCESS) { \ std::stringstream m; \ m<<prefix<<": "<<cu.getErrorString(result)<<" ("<<result<<")"<<" at "<<__FILE__<<":"<<__LINE__; \ throw OpenMMException(m.str());\ } /* -------------------------------------------------------------------------- * * AmoebaBondForce * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaBondForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaBondForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumBonds(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2; double length, k; force.getBondParameters(index, particle1, particle2, length, k); particles.resize(2); particles[0] = particle1; particles[1] = particle2; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2; double length1, length2, k1, k2; force.getBondParameters(group1, particle1, particle2, length1, k1); force.getBondParameters(group2, particle1, particle2, length2, k2); return (length1 == length2 && k1 == k2); } private: const AmoebaBondForce& force; }; CudaCalcAmoebaBondForceKernel::CudaCalcAmoebaBondForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaBondForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaBondForceKernel::initialize(const System& system, const AmoebaBondForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumBonds()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumBonds()/numContexts; numBonds = endIndex-startIndex; if (numBonds == 0) return; vector<vector<int> > atoms(numBonds, vector<int>(2)); params.initialize<float2>(cu, numBonds, "bondParams"); vector<float2> paramVector(numBonds); for (int i = 0; i < numBonds; i++) { double length, k; force.getBondParameters(startIndex+i, atoms[i][0], atoms[i][1], length, k); paramVector[i] = make_float2((float) length, (float) k); } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["COMPUTE_FORCE"] = CudaAmoebaKernelSources::amoebaBondForce; replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2"); replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalBondCubic()); replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalBondQuartic()); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaKernelSources::bondForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaBondForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaBondForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaBondForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumBonds()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumBonds()/numContexts; if (numBonds != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of bonds has changed"); if (numBonds == 0) return; // Record the per-bond parameters. vector<float2> paramVector(numBonds); for (int i = 0; i < numBonds; i++) { int atom1, atom2; double length, k; force.getBondParameters(startIndex+i, atom1, atom2, length, k); paramVector[i] = make_float2((float) length, (float) k); } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaAngleForce * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaAngleForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaAngleForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumAngles(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3; double angle, k; force.getAngleParameters(index, particle1, particle2, particle3, angle, k); particles.resize(3); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3; double angle1, angle2, k1, k2; force.getAngleParameters(group1, particle1, particle2, particle3, angle1, k1); force.getAngleParameters(group2, particle1, particle2, particle3, angle2, k2); return (angle1 == angle2 && k1 == k2); } private: const AmoebaAngleForce& force; }; CudaCalcAmoebaAngleForceKernel::CudaCalcAmoebaAngleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaAngleForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaAngleForceKernel::initialize(const System& system, const AmoebaAngleForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts; numAngles = endIndex-startIndex; if (numAngles == 0) return; vector<vector<int> > atoms(numAngles, vector<int>(3)); params.initialize<float2>(cu, numAngles, "angleParams"); vector<float2> paramVector(numAngles); for (int i = 0; i < numAngles; i++) { double angle, k; force.getAngleParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], angle, k); paramVector[i] = make_float2((float) angle, (float) k); } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["COMPUTE_FORCE"] = CudaAmoebaKernelSources::amoebaAngleForce; replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2"); replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleCubic()); replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleQuartic()); replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAnglePentic()); replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleSextic()); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaKernelSources::angleForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaAngleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaAngleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaAngleForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts; if (numAngles != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of angles has changed"); if (numAngles == 0) return; // Record the per-angle parameters. vector<float2> paramVector(numAngles); for (int i = 0; i < numAngles; i++) { int atom1, atom2, atom3; double angle, k; force.getAngleParameters(startIndex+i, atom1, atom2, atom3, angle, k); paramVector[i] = make_float2((float) angle, (float) k); } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaInPlaneAngleForce * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaInPlaneAngleForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaInPlaneAngleForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumAngles(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3, particle4; double angle, k; force.getAngleParameters(index, particle1, particle2, particle3, particle4, angle, k); particles.resize(4); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; particles[3] = particle4; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3, particle4; double angle1, angle2, k1, k2; force.getAngleParameters(group1, particle1, particle2, particle3, particle4, angle1, k1); force.getAngleParameters(group2, particle1, particle2, particle3, particle4, angle2, k2); return (angle1 == angle2 && k1 == k2); } private: const AmoebaInPlaneAngleForce& force; }; CudaCalcAmoebaInPlaneAngleForceKernel::CudaCalcAmoebaInPlaneAngleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaInPlaneAngleForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaInPlaneAngleForceKernel::initialize(const System& system, const AmoebaInPlaneAngleForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts; numAngles = endIndex-startIndex; if (numAngles == 0) return; vector<vector<int> > atoms(numAngles, vector<int>(4)); params.initialize<float2>(cu, numAngles, "angleParams"); vector<float2> paramVector(numAngles); for (int i = 0; i < numAngles; i++) { double angle, k; force.getAngleParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], angle, k); paramVector[i] = make_float2((float) angle, (float) k); } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2"); replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleCubic()); replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleQuartic()); replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAnglePentic()); replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleSextic()); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaInPlaneForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaInPlaneAngleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaInPlaneAngleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaInPlaneAngleForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts; if (numAngles != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of in-plane angles has changed"); if (numAngles == 0) return; // Record the per-angle parameters. vector<float2> paramVector(numAngles); for (int i = 0; i < numAngles; i++) { int atom1, atom2, atom3, atom4; double angle, k; force.getAngleParameters(startIndex+i, atom1, atom2, atom3, atom4, angle, k); paramVector[i] = make_float2((float) angle, (float) k); } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaPiTorsion * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaPiTorsionForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaPiTorsionForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumPiTorsions(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3, particle4, particle5, particle6; double k; force.getPiTorsionParameters(index, particle1, particle2, particle3, particle4, particle5, particle6, k); particles.resize(6); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; particles[3] = particle4; particles[4] = particle5; particles[5] = particle6; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3, particle4, particle5, particle6; double k1, k2; force.getPiTorsionParameters(group1, particle1, particle2, particle3, particle4, particle5, particle6, k1); force.getPiTorsionParameters(group2, particle1, particle2, particle3, particle4, particle5, particle6, k2); return (k1 == k2); } private: const AmoebaPiTorsionForce& force; }; CudaCalcAmoebaPiTorsionForceKernel::CudaCalcAmoebaPiTorsionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaPiTorsionForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaPiTorsionForceKernel::initialize(const System& system, const AmoebaPiTorsionForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumPiTorsions()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumPiTorsions()/numContexts; numPiTorsions = endIndex-startIndex; if (numPiTorsions == 0) return; vector<vector<int> > atoms(numPiTorsions, vector<int>(6)); params.initialize<float>(cu, numPiTorsions, "piTorsionParams"); vector<float> paramVector(numPiTorsions); for (int i = 0; i < numPiTorsions; i++) { double k; force.getPiTorsionParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], atoms[i][4], atoms[i][5], k); paramVector[i] = (float) k; } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float"); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaPiTorsionForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaPiTorsionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaPiTorsionForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaPiTorsionForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumPiTorsions()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumPiTorsions()/numContexts; if (numPiTorsions != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of torsions has changed"); if (numPiTorsions == 0) return; // Record the per-torsion parameters. vector<float> paramVector(numPiTorsions); for (int i = 0; i < numPiTorsions; i++) { int atom1, atom2, atom3, atom4, atom5, atom6; double k; force.getPiTorsionParameters(startIndex+i, atom1, atom2, atom3, atom4, atom5, atom6, k); paramVector[i] = (float) k; } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaStretchBend * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaStretchBendForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaStretchBendForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumStretchBends(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3; double lengthAB, lengthCB, angle, k1, k2; force.getStretchBendParameters(index, particle1, particle2, particle3, lengthAB, lengthCB, angle, k1, k2); particles.resize(3); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3; double lengthAB1, lengthAB2, lengthCB1, lengthCB2, angle1, angle2, k11, k12, k21, k22; force.getStretchBendParameters(group1, particle1, particle2, particle3, lengthAB1, lengthCB1, angle1, k11, k12); force.getStretchBendParameters(group2, particle1, particle2, particle3, lengthAB2, lengthCB2, angle2, k21, k22); return (lengthAB1 == lengthAB2 && lengthCB1 == lengthCB2 && angle1 == angle2 && k11 == k21 && k12 == k22); } private: const AmoebaStretchBendForce& force; }; CudaCalcAmoebaStretchBendForceKernel::CudaCalcAmoebaStretchBendForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaStretchBendForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaStretchBendForceKernel::initialize(const System& system, const AmoebaStretchBendForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumStretchBends()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumStretchBends()/numContexts; numStretchBends = endIndex-startIndex; if (numStretchBends == 0) return; vector<vector<int> > atoms(numStretchBends, vector<int>(3)); params1.initialize<float3>(cu, numStretchBends, "stretchBendParams"); params2.initialize<float2>(cu, numStretchBends, "stretchBendForceConstants"); vector<float3> paramVector(numStretchBends); vector<float2> paramVectorK(numStretchBends); for (int i = 0; i < numStretchBends; i++) { double lengthAB, lengthCB, angle, k1, k2; force.getStretchBendParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], lengthAB, lengthCB, angle, k1, k2); paramVector[i] = make_float3((float) lengthAB, (float) lengthCB, (float) angle); paramVectorK[i] = make_float2((float) k1, (float) k2); } params1.upload(paramVector); params2.upload(paramVectorK); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params1.getDevicePointer(), "float3"); replacements["FORCE_CONSTANTS"] = cu.getBondedUtilities().addArgument(params2.getDevicePointer(), "float2"); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaStretchBendForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaStretchBendForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaStretchBendForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaStretchBendForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumStretchBends()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumStretchBends()/numContexts; if (numStretchBends != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of bend-stretch terms has changed"); if (numStretchBends == 0) return; // Record the per-stretch-bend parameters. vector<float3> paramVector(numStretchBends); vector<float2> paramVector1(numStretchBends); for (int i = 0; i < numStretchBends; i++) { int atom1, atom2, atom3; double lengthAB, lengthCB, angle, k1, k2; force.getStretchBendParameters(startIndex+i, atom1, atom2, atom3, lengthAB, lengthCB, angle, k1, k2); paramVector[i] = make_float3((float) lengthAB, (float) lengthCB, (float) angle); paramVector1[i] = make_float2((float) k1, (float) k2); } params1.upload(paramVector); params2.upload(paramVector1); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaOutOfPlaneBend * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaOutOfPlaneBendForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaOutOfPlaneBendForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumOutOfPlaneBends(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3, particle4; double k; force.getOutOfPlaneBendParameters(index, particle1, particle2, particle3, particle4, k); particles.resize(4); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; particles[3] = particle4; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3, particle4; double k1, k2; force.getOutOfPlaneBendParameters(group1, particle1, particle2, particle3, particle4, k1); force.getOutOfPlaneBendParameters(group2, particle1, particle2, particle3, particle4, k2); return (k1 == k2); } private: const AmoebaOutOfPlaneBendForce& force; }; CudaCalcAmoebaOutOfPlaneBendForceKernel::CudaCalcAmoebaOutOfPlaneBendForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaOutOfPlaneBendForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaOutOfPlaneBendForceKernel::initialize(const System& system, const AmoebaOutOfPlaneBendForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumOutOfPlaneBends()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumOutOfPlaneBends()/numContexts; numOutOfPlaneBends = endIndex-startIndex; if (numOutOfPlaneBends == 0) return; vector<vector<int> > atoms(numOutOfPlaneBends, vector<int>(4)); params.initialize<float>(cu, numOutOfPlaneBends, "outOfPlaneParams"); vector<float> paramVector(numOutOfPlaneBends); for (int i = 0; i < numOutOfPlaneBends; i++) { double k; force.getOutOfPlaneBendParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], k); paramVector[i] = (float) k; } params.upload(paramVector); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float"); replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendCubic()); replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendQuartic()); replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendPentic()); replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendSextic()); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaOutOfPlaneBendForce, replacements), force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaOutOfPlaneBendForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } void CudaCalcAmoebaOutOfPlaneBendForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaOutOfPlaneBendForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumOutOfPlaneBends()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumOutOfPlaneBends()/numContexts; if (numOutOfPlaneBends != endIndex-startIndex) throw OpenMMException("updateParametersInContext: The number of out-of-plane bends has changed"); if (numOutOfPlaneBends == 0) return; // Record the per-bend parameters. vector<float> paramVector(numOutOfPlaneBends); for (int i = 0; i < numOutOfPlaneBends; i++) { int atom1, atom2, atom3, atom4; double k; force.getOutOfPlaneBendParameters(startIndex+i, atom1, atom2, atom3, atom4, k); paramVector[i] = (float) k; } params.upload(paramVector); // Mark that the current reordering may be invalid. cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaTorsionTorsion * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaTorsionTorsionForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaTorsionTorsionForce& force) : force(force) { } int getNumParticleGroups() { return force.getNumTorsionTorsions(); } void getParticlesInGroup(int index, std::vector<int>& particles) { int particle1, particle2, particle3, particle4, particle5, chiralCheckAtomIndex, gridIndex; force.getTorsionTorsionParameters(index, particle1, particle2, particle3, particle4, particle5, chiralCheckAtomIndex, gridIndex); particles.resize(5); particles[0] = particle1; particles[1] = particle2; particles[2] = particle3; particles[3] = particle4; particles[4] = particle5; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2, particle3, particle4, particle5; int chiral1, chiral2, grid1, grid2; force.getTorsionTorsionParameters(group1, particle1, particle2, particle3, particle4, particle5, chiral1, grid1); force.getTorsionTorsionParameters(group2, particle1, particle2, particle3, particle4, particle5, chiral2, grid2); return (grid1 == grid2); } private: const AmoebaTorsionTorsionForce& force; }; CudaCalcAmoebaTorsionTorsionForceKernel::CudaCalcAmoebaTorsionTorsionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaTorsionTorsionForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaTorsionTorsionForceKernel::initialize(const System& system, const AmoebaTorsionTorsionForce& force) { cu.setAsCurrent(); int numContexts = cu.getPlatformData().contexts.size(); int startIndex = cu.getContextIndex()*force.getNumTorsionTorsions()/numContexts; int endIndex = (cu.getContextIndex()+1)*force.getNumTorsionTorsions()/numContexts; numTorsionTorsions = endIndex-startIndex; if (numTorsionTorsions == 0) return; // Record torsion parameters. vector<vector<int> > atoms(numTorsionTorsions, vector<int>(5)); vector<int2> torsionParamsVec(numTorsionTorsions); torsionParams.initialize<int2>(cu, numTorsionTorsions, "torsionTorsionParams"); for (int i = 0; i < numTorsionTorsions; i++) force.getTorsionTorsionParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], atoms[i][4], torsionParamsVec[i].x, torsionParamsVec[i].y); torsionParams.upload(torsionParamsVec); // Record the grids. vector<float4> gridValuesVec; vector<float4> gridParamsVec; for (int i = 0; i < force.getNumTorsionTorsionGrids(); i++) { const TorsionTorsionGrid& initialGrid = force.getTorsionTorsionGrid(i); // check if grid needs to be reordered: x-angle should be 'slow' index bool reordered = false; TorsionTorsionGrid reorderedGrid; if (initialGrid[0][0][0] != initialGrid[0][1][0]) { AmoebaTorsionTorsionForceImpl::reorderGrid(initialGrid, reorderedGrid); reordered = true; } const TorsionTorsionGrid& grid = (reordered ? reorderedGrid : initialGrid); float range = grid[0][grid[0].size()-1][1] - grid[0][0][1]; gridParamsVec.push_back(make_float4(gridValuesVec.size(), grid[0][0][0], range/(grid.size()-1), grid.size())); for (int j = 0; j < grid.size(); j++) for (int k = 0; k < grid[j].size(); k++) gridValuesVec.push_back(make_float4((float) grid[j][k][2], (float) grid[j][k][3], (float) grid[j][k][4], (float) grid[j][k][5])); } gridValues.initialize<float4>(cu, gridValuesVec.size(), "torsionTorsionGridValues"); gridParams.initialize<float4>(cu, gridParamsVec.size(), "torsionTorsionGridParams"); gridValues.upload(gridValuesVec); gridParams.upload(gridParamsVec); map<string, string> replacements; replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0"); replacements["GRID_VALUES"] = cu.getBondedUtilities().addArgument(gridValues.getDevicePointer(), "float4"); replacements["GRID_PARAMS"] = cu.getBondedUtilities().addArgument(gridParams.getDevicePointer(), "float4"); replacements["TORSION_PARAMS"] = cu.getBondedUtilities().addArgument(torsionParams.getDevicePointer(), "int2"); replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI); cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaTorsionTorsionForce, replacements), force.getForceGroup()); cu.getBondedUtilities().addPrefixCode(CudaAmoebaKernelSources::bicubic); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaTorsionTorsionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { return 0.0; } /* -------------------------------------------------------------------------- * * AmoebaMultipole * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaMultipoleForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaMultipoleForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double charge1, charge2, thole1, thole2, damping1, damping2, polarity1, polarity2; int axis1, axis2, multipole11, multipole12, multipole21, multipole22, multipole31, multipole32; vector<double> dipole1, dipole2, quadrupole1, quadrupole2; force.getMultipoleParameters(particle1, charge1, dipole1, quadrupole1, axis1, multipole11, multipole21, multipole31, thole1, damping1, polarity1); force.getMultipoleParameters(particle2, charge2, dipole2, quadrupole2, axis2, multipole12, multipole22, multipole32, thole2, damping2, polarity2); if (charge1 != charge2 || thole1 != thole2 || damping1 != damping2 || polarity1 != polarity2 || axis1 != axis2) { return false; } for (int i = 0; i < (int) dipole1.size(); ++i) { if (dipole1[i] != dipole2[i]) { return false; } } for (int i = 0; i < (int) quadrupole1.size(); ++i) { if (quadrupole1[i] != quadrupole2[i]) { return false; } } return true; } int getNumParticleGroups() { return 7*force.getNumMultipoles(); } void getParticlesInGroup(int index, vector<int>& particles) { int particle = index/7; int type = index-7*particle; force.getCovalentMap(particle, AmoebaMultipoleForce::CovalentType(type), particles); } bool areGroupsIdentical(int group1, int group2) { return ((group1%7) == (group2%7)); } private: const AmoebaMultipoleForce& force; }; CudaCalcAmoebaMultipoleForceKernel::CudaCalcAmoebaMultipoleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaMultipoleForceKernel(name, platform), cu(cu), system(system), hasInitializedScaleFactors(false), hasInitializedFFT(false), multipolesAreValid(false), hasCreatedEvent(false), gkKernel(NULL) { } CudaCalcAmoebaMultipoleForceKernel::~CudaCalcAmoebaMultipoleForceKernel() { cu.setAsCurrent(); if (hasInitializedFFT) cufftDestroy(fft); if (hasCreatedEvent) cuEventDestroy(syncEvent); } void CudaCalcAmoebaMultipoleForceKernel::initialize(const System& system, const AmoebaMultipoleForce& force) { cu.setAsCurrent(); // Initialize multipole parameters. numMultipoles = force.getNumMultipoles(); CudaArray& posq = cu.getPosq(); vector<double4> temp(posq.getSize()); float4* posqf = (float4*) &temp[0]; double4* posqd = (double4*) &temp[0]; vector<float2> dampingAndTholeVec; vector<float> polarizabilityVec; vector<float> molecularDipolesVec; vector<float> molecularQuadrupolesVec; vector<int4> multipoleParticlesVec; for (int i = 0; i < numMultipoles; i++) { double charge, thole, damping, polarity; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; force.getMultipoleParameters(i, charge, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity); if (cu.getUseDoublePrecision()) posqd[i] = make_double4(0, 0, 0, charge); else posqf[i] = make_float4(0, 0, 0, (float) charge); dampingAndTholeVec.push_back(make_float2((float) damping, (float) thole)); polarizabilityVec.push_back((float) polarity); multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType)); for (int j = 0; j < 3; j++) molecularDipolesVec.push_back((float) dipole[j]); molecularQuadrupolesVec.push_back((float) quadrupole[0]); molecularQuadrupolesVec.push_back((float) quadrupole[1]); molecularQuadrupolesVec.push_back((float) quadrupole[2]); molecularQuadrupolesVec.push_back((float) quadrupole[4]); molecularQuadrupolesVec.push_back((float) quadrupole[5]); } hasQuadrupoles = false; for (auto q : molecularQuadrupolesVec) if (q != 0.0) hasQuadrupoles = true; int paddedNumAtoms = cu.getPaddedNumAtoms(); for (int i = numMultipoles; i < paddedNumAtoms; i++) { dampingAndTholeVec.push_back(make_float2(0, 0)); polarizabilityVec.push_back(0); multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0)); for (int j = 0; j < 3; j++) molecularDipolesVec.push_back(0); for (int j = 0; j < 5; j++) molecularQuadrupolesVec.push_back(0); } dampingAndThole.initialize<float2>(cu, paddedNumAtoms, "dampingAndThole"); polarizability.initialize<float>(cu, paddedNumAtoms, "polarizability"); multipoleParticles.initialize<int4>(cu, paddedNumAtoms, "multipoleParticles"); molecularDipoles.initialize<float>(cu, 3*paddedNumAtoms, "molecularDipoles"); molecularQuadrupoles.initialize<float>(cu, 5*paddedNumAtoms, "molecularQuadrupoles"); lastPositions.initialize(cu, cu.getPosq().getSize(), cu.getPosq().getElementSize(), "lastPositions"); dampingAndThole.upload(dampingAndTholeVec); polarizability.upload(polarizabilityVec); multipoleParticles.upload(multipoleParticlesVec); molecularDipoles.upload(molecularDipolesVec); molecularQuadrupoles.upload(molecularQuadrupolesVec); posq.upload(&temp[0]); // Create workspace arrays. polarizationType = force.getPolarizationType(); int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); labFrameDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "labFrameDipoles"); labFrameQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "labFrameQuadrupoles"); sphericalDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "sphericalDipoles"); sphericalQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "sphericalQuadrupoles"); fracDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "fracDipoles"); fracQuadrupoles.initialize(cu, 6*paddedNumAtoms, elementSize, "fracQuadrupoles"); field.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "field"); fieldPolar.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "fieldPolar"); torque.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "torque"); inducedDipole.initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipole"); inducedDipolePolar.initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipolePolar"); if (polarizationType == AmoebaMultipoleForce::Mutual) { inducedDipoleErrors.initialize(cu, cu.getNumThreadBlocks(), sizeof(float2), "inducedDipoleErrors"); prevDipoles.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipoles"); prevDipolesPolar.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesPolar"); prevErrors.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevErrors"); diisMatrix.initialize(cu, MaxPrevDIISDipoles*MaxPrevDIISDipoles, elementSize, "diisMatrix"); diisCoefficients.initialize(cu, MaxPrevDIISDipoles+1, sizeof(float), "diisMatrix"); CHECK_RESULT(cuEventCreate(&syncEvent, CU_EVENT_DISABLE_TIMING), "Error creating event for AmoebaMultipoleForce"); hasCreatedEvent = true; } else if (polarizationType == AmoebaMultipoleForce::Extrapolated) { int numOrders = force.getExtrapolationCoefficients().size(); extrapolatedDipole.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipole"); extrapolatedDipolePolar.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipolePolar"); inducedDipoleFieldGradient.initialize(cu, 6*paddedNumAtoms, sizeof(long long), "inducedDipoleFieldGradient"); inducedDipoleFieldGradientPolar.initialize(cu, 6*paddedNumAtoms, sizeof(long long), "inducedDipoleFieldGradientPolar"); extrapolatedDipoleFieldGradient.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradient"); extrapolatedDipoleFieldGradientPolar.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientPolar"); } cu.addAutoclearBuffer(field); cu.addAutoclearBuffer(fieldPolar); cu.addAutoclearBuffer(torque); // Record which atoms should be flagged as exclusions based on covalent groups, and determine // the values for the covalent group flags. vector<vector<int> > exclusions(numMultipoles); for (int i = 0; i < numMultipoles; i++) { vector<int> atoms; set<int> allAtoms; allAtoms.insert(i); force.getCovalentMap(i, AmoebaMultipoleForce::Covalent12, atoms); allAtoms.insert(atoms.begin(), atoms.end()); force.getCovalentMap(i, AmoebaMultipoleForce::Covalent13, atoms); allAtoms.insert(atoms.begin(), atoms.end()); for (int atom : allAtoms) covalentFlagValues.push_back(make_int3(i, atom, 0)); force.getCovalentMap(i, AmoebaMultipoleForce::Covalent14, atoms); allAtoms.insert(atoms.begin(), atoms.end()); for (int atom : atoms) covalentFlagValues.push_back(make_int3(i, atom, 1)); force.getCovalentMap(i, AmoebaMultipoleForce::Covalent15, atoms); for (int atom : atoms) covalentFlagValues.push_back(make_int3(i, atom, 2)); allAtoms.insert(atoms.begin(), atoms.end()); force.getCovalentMap(i, AmoebaMultipoleForce::PolarizationCovalent11, atoms); allAtoms.insert(atoms.begin(), atoms.end()); exclusions[i].insert(exclusions[i].end(), allAtoms.begin(), allAtoms.end()); // Workaround for bug in TINKER: if an atom is listed in both the PolarizationCovalent11 // and PolarizationCovalent12 maps, the latter takes precedence. vector<int> atoms12; force.getCovalentMap(i, AmoebaMultipoleForce::PolarizationCovalent12, atoms12); for (int atom : atoms) if (find(atoms12.begin(), atoms12.end(), atom) == atoms12.end()) polarizationFlagValues.push_back(make_int2(i, atom)); } set<pair<int, int> > tilesWithExclusions; for (int atom1 = 0; atom1 < (int) exclusions.size(); ++atom1) { int x = atom1/CudaContext::TileSize; for (int atom2 : exclusions[atom1]) { int y = atom2/CudaContext::TileSize; tilesWithExclusions.insert(make_pair(max(x, y), min(x, y))); } } // Record other options. if (polarizationType == AmoebaMultipoleForce::Mutual) { maxInducedIterations = force.getMutualInducedMaxIterations(); inducedEpsilon = force.getMutualInducedTargetEpsilon(); } else maxInducedIterations = 0; if (polarizationType != AmoebaMultipoleForce::Direct) { inducedField.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedField"); inducedFieldPolar.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedFieldPolar"); } usePME = (force.getNonbondedMethod() == AmoebaMultipoleForce::PME); // See whether there's an AmoebaGeneralizedKirkwoodForce in the System. const AmoebaGeneralizedKirkwoodForce* gk = NULL; for (int i = 0; i < system.getNumForces() && gk == NULL; i++) gk = dynamic_cast<const AmoebaGeneralizedKirkwoodForce*>(&system.getForce(i)); double innerDielectric = (gk == NULL ? 1.0 : gk->getSoluteDielectric()); // Create the kernels. bool useShuffle = (cu.getComputeCapability() >= 3.0 && !cu.getUseDoublePrecision()); double fixedThreadMemory = 19*elementSize+2*sizeof(float)+3*sizeof(int)/(double) cu.TileSize; double inducedThreadMemory = 15*elementSize+2*sizeof(float); if (polarizationType == AmoebaMultipoleForce::Extrapolated) inducedThreadMemory += 12*elementSize; double electrostaticsThreadMemory = 0; if (!useShuffle) fixedThreadMemory += 3*elementSize; map<string, string> defines; defines["NUM_ATOMS"] = cu.intToString(numMultipoles); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456/innerDielectric); if (polarizationType == AmoebaMultipoleForce::Direct) defines["DIRECT_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Mutual) defines["MUTUAL_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Extrapolated) defines["EXTRAPOLATED_POLARIZATION"] = ""; if (useShuffle) defines["USE_SHUFFLE"] = ""; if (hasQuadrupoles) defines["INCLUDE_QUADRUPOLES"] = ""; defines["TILE_SIZE"] = cu.intToString(CudaContext::TileSize); int numExclusionTiles = tilesWithExclusions.size(); defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(numExclusionTiles); int numContexts = cu.getPlatformData().contexts.size(); int startExclusionIndex = cu.getContextIndex()*numExclusionTiles/numContexts; int endExclusionIndex = (cu.getContextIndex()+1)*numExclusionTiles/numContexts; defines["FIRST_EXCLUSION_TILE"] = cu.intToString(startExclusionIndex); defines["LAST_EXCLUSION_TILE"] = cu.intToString(endExclusionIndex); maxExtrapolationOrder = force.getExtrapolationCoefficients().size(); defines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder); stringstream coefficients; for (int i = 0; i < maxExtrapolationOrder; i++) { if (i > 0) coefficients << ","; double sum = 0; for (int j = i; j < maxExtrapolationOrder; j++) sum += force.getExtrapolationCoefficients()[j]; coefficients << cu.doubleToString(sum); } defines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str(); if (usePME) { int nx, ny, nz; force.getPMEParameters(alpha, nx, ny, nz); if (nx == 0 || alpha == 0.0) { NonbondedForce nb; nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance()); nb.setCutoffDistance(force.getCutoffDistance()); NonbondedForceImpl::calcPMEParameters(system, nb, alpha, gridSizeX, gridSizeY, gridSizeZ, false); gridSizeX = CudaFFT3D::findLegalDimension(gridSizeX); gridSizeY = CudaFFT3D::findLegalDimension(gridSizeY); gridSizeZ = CudaFFT3D::findLegalDimension(gridSizeZ); } else { gridSizeX = CudaFFT3D::findLegalDimension(nx); gridSizeY = CudaFFT3D::findLegalDimension(ny); gridSizeZ = CudaFFT3D::findLegalDimension(nz); } defines["EWALD_ALPHA"] = cu.doubleToString(alpha); defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); defines["USE_EWALD"] = ""; defines["USE_CUTOFF"] = ""; defines["USE_PERIODIC"] = ""; defines["CUTOFF_SQUARED"] = cu.doubleToString(force.getCutoffDistance()*force.getCutoffDistance()); } if (gk != NULL) { defines["USE_GK"] = ""; defines["GK_C"] = cu.doubleToString(2.455); double solventDielectric = gk->getSolventDielectric(); defines["GK_FC"] = cu.doubleToString(1*(1-solventDielectric)/(0+1*solventDielectric)); defines["GK_FD"] = cu.doubleToString(2*(1-solventDielectric)/(1+2*solventDielectric)); defines["GK_FQ"] = cu.doubleToString(3*(1-solventDielectric)/(2+3*solventDielectric)); fixedThreadMemory += 4*elementSize; inducedThreadMemory += 13*elementSize; if (polarizationType == AmoebaMultipoleForce::Mutual) { prevDipolesGk.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesGk"); prevDipolesGkPolar.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesGkPolar"); } else if (polarizationType == AmoebaMultipoleForce::Extrapolated) { inducedThreadMemory += 12*elementSize; int numOrders = force.getExtrapolationCoefficients().size(); extrapolatedDipoleGk.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipoleGk"); extrapolatedDipoleGkPolar.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipoleGkPolar"); inducedDipoleFieldGradientGk.initialize(cu, 6*numMultipoles, elementSize, "inducedDipoleFieldGradientGk"); inducedDipoleFieldGradientGkPolar.initialize(cu, 6*numMultipoles, elementSize, "inducedDipoleFieldGradientGkPolar"); extrapolatedDipoleFieldGradientGk.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientGk"); extrapolatedDipoleFieldGradientGkPolar.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientGkPolar"); } } int maxThreads = cu.getNonbondedUtilities().getForceThreadBlockSize(); fixedFieldThreads = min(maxThreads, cu.computeThreadBlockSize(fixedThreadMemory)); inducedFieldThreads = min(maxThreads, cu.computeThreadBlockSize(inducedThreadMemory)); CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoles, defines); computeMomentsKernel = cu.getKernel(module, "computeLabFrameMoments"); recordInducedDipolesKernel = cu.getKernel(module, "recordInducedDipoles"); mapTorqueKernel = cu.getKernel(module, "mapTorqueToForce"); computePotentialKernel = cu.getKernel(module, "computePotentialAtPoints"); defines["THREAD_BLOCK_SIZE"] = cu.intToString(fixedFieldThreads); module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleFixedField, defines); computeFixedFieldKernel = cu.getKernel(module, "computeFixedField"); if (polarizationType != AmoebaMultipoleForce::Direct) { defines["THREAD_BLOCK_SIZE"] = cu.intToString(inducedFieldThreads); defines["MAX_PREV_DIIS_DIPOLES"] = cu.intToString(MaxPrevDIISDipoles); module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleInducedField, defines); computeInducedFieldKernel = cu.getKernel(module, "computeInducedField"); updateInducedFieldKernel = cu.getKernel(module, "updateInducedFieldByDIIS"); recordDIISDipolesKernel = cu.getKernel(module, "recordInducedDipolesForDIIS"); buildMatrixKernel = cu.getKernel(module, "computeDIISMatrix"); solveMatrixKernel = cu.getKernel(module, "solveDIISMatrix"); initExtrapolatedKernel = cu.getKernel(module, "initExtrapolatedDipoles"); iterateExtrapolatedKernel = cu.getKernel(module, "iterateExtrapolatedDipoles"); computeExtrapolatedKernel = cu.getKernel(module, "computeExtrapolatedDipoles"); addExtrapolatedGradientKernel = cu.getKernel(module, "addExtrapolatedFieldGradientToForce"); } stringstream electrostaticsSource; electrostaticsSource << CudaKernelSources::vectorOps; electrostaticsSource << CudaAmoebaKernelSources::sphericalMultipoles; if (usePME) electrostaticsSource << CudaAmoebaKernelSources::pmeMultipoleElectrostatics; else electrostaticsSource << CudaAmoebaKernelSources::multipoleElectrostatics; electrostaticsThreadMemory = 24*elementSize+3*sizeof(float)+3*sizeof(int)/(double) cu.TileSize; electrostaticsThreads = min(maxThreads, cu.computeThreadBlockSize(electrostaticsThreadMemory)); defines["THREAD_BLOCK_SIZE"] = cu.intToString(electrostaticsThreads); module = cu.createModule(electrostaticsSource.str(), defines); electrostaticsKernel = cu.getKernel(module, "computeElectrostatics"); // Set up PME. if (usePME) { // Create the PME kernels. map<string, string> pmeDefines; pmeDefines["EWALD_ALPHA"] = cu.doubleToString(alpha); pmeDefines["PME_ORDER"] = cu.intToString(PmeOrder); pmeDefines["NUM_ATOMS"] = cu.intToString(numMultipoles); pmeDefines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); pmeDefines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456); pmeDefines["GRID_SIZE_X"] = cu.intToString(gridSizeX); pmeDefines["GRID_SIZE_Y"] = cu.intToString(gridSizeY); pmeDefines["GRID_SIZE_Z"] = cu.intToString(gridSizeZ); pmeDefines["M_PI"] = cu.doubleToString(M_PI); pmeDefines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); if (polarizationType == AmoebaMultipoleForce::Direct) pmeDefines["DIRECT_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Mutual) pmeDefines["MUTUAL_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Extrapolated) pmeDefines["EXTRAPOLATED_POLARIZATION"] = ""; CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipolePme, pmeDefines); pmeTransformMultipolesKernel = cu.getKernel(module, "transformMultipolesToFractionalCoordinates"); pmeTransformPotentialKernel = cu.getKernel(module, "transformPotentialToCartesianCoordinates"); pmeSpreadFixedMultipolesKernel = cu.getKernel(module, "gridSpreadFixedMultipoles"); pmeSpreadInducedDipolesKernel = cu.getKernel(module, "gridSpreadInducedDipoles"); pmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge"); pmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution"); pmeFixedPotentialKernel = cu.getKernel(module, "computeFixedPotentialFromGrid"); pmeInducedPotentialKernel = cu.getKernel(module, "computeInducedPotentialFromGrid"); pmeFixedForceKernel = cu.getKernel(module, "computeFixedMultipoleForceAndEnergy"); pmeInducedForceKernel = cu.getKernel(module, "computeInducedDipoleForceAndEnergy"); pmeRecordInducedFieldDipolesKernel = cu.getKernel(module, "recordInducedFieldDipoles"); cuFuncSetCacheConfig(pmeSpreadFixedMultipolesKernel, CU_FUNC_CACHE_PREFER_L1); cuFuncSetCacheConfig(pmeSpreadInducedDipolesKernel, CU_FUNC_CACHE_PREFER_L1); cuFuncSetCacheConfig(pmeFixedPotentialKernel, CU_FUNC_CACHE_PREFER_L1); cuFuncSetCacheConfig(pmeInducedPotentialKernel, CU_FUNC_CACHE_PREFER_L1); // Create required data structures. int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); pmeGrid.initialize(cu, gridSizeX*gridSizeY*gridSizeZ, 2*elementSize, "pmeGrid"); cu.addAutoclearBuffer(pmeGrid); pmeBsplineModuliX.initialize(cu, gridSizeX, elementSize, "pmeBsplineModuliX"); pmeBsplineModuliY.initialize(cu, gridSizeY, elementSize, "pmeBsplineModuliY"); pmeBsplineModuliZ.initialize(cu, gridSizeZ, elementSize, "pmeBsplineModuliZ"); pmePhi.initialize(cu, 20*numMultipoles, elementSize, "pmePhi"); pmePhid.initialize(cu, 10*numMultipoles, elementSize, "pmePhid"); pmePhip.initialize(cu, 10*numMultipoles, elementSize, "pmePhip"); pmePhidp.initialize(cu, 20*numMultipoles, elementSize, "pmePhidp"); pmeCphi.initialize(cu, 10*numMultipoles, elementSize, "pmeCphi"); cufftResult result = cufftPlan3d(&fft, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2Z : CUFFT_C2C); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); hasInitializedFFT = true; // Initialize the b-spline moduli. double data[PmeOrder]; double x = 0.0; data[0] = 1.0 - x; data[1] = x; for (int i = 2; i < PmeOrder; i++) { double denom = 1.0/i; data[i] = x*data[i-1]*denom; for (int j = 1; j < i; j++) data[i-j] = ((x+j)*data[i-j-1] + ((i-j+1)-x)*data[i-j])*denom; data[0] = (1.0-x)*data[0]*denom; } int maxSize = max(max(gridSizeX, gridSizeY), gridSizeZ); vector<double> bsplines_data(maxSize+1, 0.0); for (int i = 2; i <= PmeOrder+1; i++) bsplines_data[i] = data[i-2]; for (int dim = 0; dim < 3; dim++) { int ndata = (dim == 0 ? gridSizeX : dim == 1 ? gridSizeY : gridSizeZ); vector<double> moduli(ndata); // get the modulus of the discrete Fourier transform double factor = 2.0*M_PI/ndata; for (int i = 0; i < ndata; i++) { double sc = 0.0; double ss = 0.0; for (int j = 1; j <= ndata; j++) { double arg = factor*i*(j-1); sc += bsplines_data[j]*cos(arg); ss += bsplines_data[j]*sin(arg); } moduli[i] = sc*sc+ss*ss; } // Fix for exponential Euler spline interpolation failure. double eps = 1.0e-7; if (moduli[0] < eps) moduli[0] = 0.9*moduli[1]; for (int i = 1; i < ndata-1; i++) if (moduli[i] < eps) moduli[i] = 0.9*(moduli[i-1]+moduli[i+1]); if (moduli[ndata-1] < eps) moduli[ndata-1] = 0.9*moduli[ndata-2]; // Compute and apply the optimal zeta coefficient. int jcut = 50; for (int i = 1; i <= ndata; i++) { int k = i - 1; if (i > ndata/2) k = k - ndata; double zeta; if (k == 0) zeta = 1.0; else { double sum1 = 1.0; double sum2 = 1.0; factor = M_PI*k/ndata; for (int j = 1; j <= jcut; j++) { double arg = factor/(factor+M_PI*j); sum1 += pow(arg, PmeOrder); sum2 += pow(arg, 2*PmeOrder); } for (int j = 1; j <= jcut; j++) { double arg = factor/(factor-M_PI*j); sum1 += pow(arg, PmeOrder); sum2 += pow(arg, 2*PmeOrder); } zeta = sum2/sum1; } moduli[i-1] = moduli[i-1]*zeta*zeta; } if (cu.getUseDoublePrecision()) { if (dim == 0) pmeBsplineModuliX.upload(moduli); else if (dim == 1) pmeBsplineModuliY.upload(moduli); else pmeBsplineModuliZ.upload(moduli); } else { vector<float> modulif(ndata); for (int i = 0; i < ndata; i++) modulif[i] = (float) moduli[i]; if (dim == 0) pmeBsplineModuliX.upload(modulif); else if (dim == 1) pmeBsplineModuliY.upload(modulif); else pmeBsplineModuliZ.upload(modulif); } } } // Add an interaction to the default nonbonded kernel. This doesn't actually do any calculations. It's // just so that CudaNonbondedUtilities will build the exclusion flags and maintain the neighbor list. cu.getNonbondedUtilities().addInteraction(usePME, usePME, true, force.getCutoffDistance(), exclusions, "", force.getForceGroup()); cu.getNonbondedUtilities().setUsePadding(false); cu.addForce(new ForceInfo(force)); } void CudaCalcAmoebaMultipoleForceKernel::initializeScaleFactors() { hasInitializedScaleFactors = true; CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); // Figure out the covalent flag values to use for each atom pair. vector<ushort2> exclusionTiles; nb.getExclusionTiles().download(exclusionTiles); map<pair<int, int>, int> exclusionTileMap; for (int i = 0; i < (int) exclusionTiles.size(); i++) { ushort2 tile = exclusionTiles[i]; exclusionTileMap[make_pair(tile.x, tile.y)] = i; } covalentFlags.initialize<uint2>(cu, nb.getExclusions().getSize(), "covalentFlags"); vector<uint2> covalentFlagsVec(nb.getExclusions().getSize(), make_uint2(0, 0)); for (int3 values : covalentFlagValues) { int atom1 = values.x; int atom2 = values.y; int value = values.z; int x = atom1/CudaContext::TileSize; int offset1 = atom1-x*CudaContext::TileSize; int y = atom2/CudaContext::TileSize; int offset2 = atom2-y*CudaContext::TileSize; int f1 = (value == 0 || value == 1 ? 1 : 0); int f2 = (value == 0 || value == 2 ? 1 : 0); if (x == y) { int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize; covalentFlagsVec[index+offset1].x |= f1<<offset2; covalentFlagsVec[index+offset1].y |= f2<<offset2; covalentFlagsVec[index+offset2].x |= f1<<offset1; covalentFlagsVec[index+offset2].y |= f2<<offset1; } else if (x > y) { int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize; covalentFlagsVec[index+offset1].x |= f1<<offset2; covalentFlagsVec[index+offset1].y |= f2<<offset2; } else { int index = exclusionTileMap[make_pair(y, x)]*CudaContext::TileSize; covalentFlagsVec[index+offset2].x |= f1<<offset1; covalentFlagsVec[index+offset2].y |= f2<<offset1; } } covalentFlags.upload(covalentFlagsVec); // Do the same for the polarization flags. polarizationGroupFlags.initialize<unsigned int>(cu, nb.getExclusions().getSize(), "polarizationGroupFlags"); vector<unsigned int> polarizationGroupFlagsVec(nb.getExclusions().getSize(), 0); for (int2 values : polarizationFlagValues) { int atom1 = values.x; int atom2 = values.y; int x = atom1/CudaContext::TileSize; int offset1 = atom1-x*CudaContext::TileSize; int y = atom2/CudaContext::TileSize; int offset2 = atom2-y*CudaContext::TileSize; if (x == y) { int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize; polarizationGroupFlagsVec[index+offset1] |= 1<<offset2; polarizationGroupFlagsVec[index+offset2] |= 1<<offset1; } else if (x > y) { int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize; polarizationGroupFlagsVec[index+offset1] |= 1<<offset2; } else { int index = exclusionTileMap[make_pair(y, x)]*CudaContext::TileSize; polarizationGroupFlagsVec[index+offset2] |= 1<<offset1; } } polarizationGroupFlags.upload(polarizationGroupFlagsVec); } double CudaCalcAmoebaMultipoleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { if (!hasInitializedScaleFactors) { initializeScaleFactors(); for (auto impl : context.getForceImpls()) { AmoebaGeneralizedKirkwoodForceImpl* gkImpl = dynamic_cast<AmoebaGeneralizedKirkwoodForceImpl*>(impl); if (gkImpl != NULL) { gkKernel = dynamic_cast<CudaCalcAmoebaGeneralizedKirkwoodForceKernel*>(&gkImpl->getKernel().getImpl()); break; } } } CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); // Compute the lab frame moments. void* computeMomentsArgs[] = {&cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer(), &molecularDipoles.getDevicePointer(), &molecularQuadrupoles.getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer()}; cu.executeKernel(computeMomentsKernel, computeMomentsArgs, cu.getNumAtoms()); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); if (!pmeGrid.isInitialized()) { // Compute induced dipoles. if (gkKernel == NULL) { void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads); void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms()); } else { gkKernel->computeBornRadii(); void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &gkKernel->getBornRadii().getDevicePointer(), &gkKernel->getField().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads); void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &gkKernel->getField().getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms()); } // Iterate until the dipoles converge. if (polarizationType == AmoebaMultipoleForce::Extrapolated) computeExtrapolatedDipoles(NULL); for (int i = 0; i < maxInducedIterations; i++) { computeInducedField(NULL); bool converged = iterateDipolesByDIIS(i); if (converged) break; } // Compute electrostatic force. void* electrostaticsArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(electrostaticsKernel, electrostaticsArgs, numForceThreadBlocks*electrostaticsThreads, electrostaticsThreads); if (gkKernel != NULL) gkKernel->finishComputation(torque, labFrameDipoles, labFrameQuadrupoles, inducedDipole, inducedDipolePolar, dampingAndThole, covalentFlags, polarizationGroupFlags); } else { // Compute reciprocal box vectors. Vec3 boxVectors[3]; cu.getPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]); double determinant = boxVectors[0][0]*boxVectors[1][1]*boxVectors[2][2]; double scale = 1.0/determinant; double3 recipBoxVectors[3]; recipBoxVectors[0] = make_double3(boxVectors[1][1]*boxVectors[2][2]*scale, 0, 0); recipBoxVectors[1] = make_double3(-boxVectors[1][0]*boxVectors[2][2]*scale, boxVectors[0][0]*boxVectors[2][2]*scale, 0); recipBoxVectors[2] = make_double3((boxVectors[1][0]*boxVectors[2][1]-boxVectors[1][1]*boxVectors[2][0])*scale, -boxVectors[0][0]*boxVectors[2][1]*scale, boxVectors[0][0]*boxVectors[1][1]*scale); float3 recipBoxVectorsFloat[3]; void* recipBoxVectorPointer[3]; if (cu.getUseDoublePrecision()) { recipBoxVectorPointer[0] = &recipBoxVectors[0]; recipBoxVectorPointer[1] = &recipBoxVectors[1]; recipBoxVectorPointer[2] = &recipBoxVectors[2]; } else { recipBoxVectorsFloat[0] = make_float3((float) recipBoxVectors[0].x, 0, 0); recipBoxVectorsFloat[1] = make_float3((float) recipBoxVectors[1].x, (float) recipBoxVectors[1].y, 0); recipBoxVectorsFloat[2] = make_float3((float) recipBoxVectors[2].x, (float) recipBoxVectors[2].y, (float) recipBoxVectors[2].z); recipBoxVectorPointer[0] = &recipBoxVectorsFloat[0]; recipBoxVectorPointer[1] = &recipBoxVectorsFloat[1]; recipBoxVectorPointer[2] = &recipBoxVectorsFloat[2]; } // Reciprocal space calculation. unsigned int maxTiles = nb.getInteractingTiles().getSize(); void* pmeTransformMultipolesArgs[] = {&labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformMultipolesKernel, pmeTransformMultipolesArgs, cu.getNumAtoms()); void* pmeSpreadFixedMultipolesArgs[] = {&cu.getPosq().getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadFixedMultipolesKernel, pmeSpreadFixedMultipolesArgs, cu.getNumAtoms()); void* finishSpreadArgs[] = {&pmeGrid.getDevicePointer()}; if (cu.getUseDoublePrecision()) { cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize()); cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); } else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); void* pmeConvolutionArgs[] = {&pmeGrid.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(), &pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); void* pmeFixedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhi.getDevicePointer(), &field.getDevicePointer(), &fieldPolar .getDevicePointer(), &cu.getPosq().getDevicePointer(), &labFrameDipoles.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeFixedPotentialKernel, pmeFixedPotentialArgs, cu.getNumAtoms()); void* pmeTransformFixedPotentialArgs[] = {&pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformPotentialKernel, pmeTransformFixedPotentialArgs, cu.getNumAtoms()); void* pmeFixedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeFixedForceKernel, pmeFixedForceArgs, cu.getNumAtoms()); // Direct space calculation. void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &nb.getInteractingTiles().getDevicePointer(), &nb.getInteractionCount().getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), &maxTiles, &nb.getBlockCenters().getDevicePointer(), &nb.getInteractingAtoms().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads); void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms()); // Reciprocal space calculation for the induced dipoles. cu.clearBuffer(pmeGrid); void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms()); if (cu.getUseDoublePrecision()) { cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize()); cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); } else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); void* pmeInducedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms()); // Iterate until the dipoles converge. if (polarizationType == AmoebaMultipoleForce::Extrapolated) computeExtrapolatedDipoles(recipBoxVectorPointer); for (int i = 0; i < maxInducedIterations; i++) { computeInducedField(recipBoxVectorPointer); bool converged = iterateDipolesByDIIS(i); if (converged) break; } // Compute electrostatic force. void* electrostaticsArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &nb.getInteractingTiles().getDevicePointer(), &nb.getInteractionCount().getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), &maxTiles, &nb.getBlockCenters().getDevicePointer(), &nb.getInteractingAtoms().getDevicePointer(), &sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(electrostaticsKernel, electrostaticsArgs, numForceThreadBlocks*electrostaticsThreads, electrostaticsThreads); void* pmeTransformInducedPotentialArgs[] = {&pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformPotentialKernel, pmeTransformInducedPotentialArgs, cu.getNumAtoms()); void* pmeInducedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &pmePhi.getDevicePointer(), &pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedForceKernel, pmeInducedForceArgs, cu.getNumAtoms()); } // If using extrapolated polarization, add in force contributions from µ(m) T µ(n). if (polarizationType == AmoebaMultipoleForce::Extrapolated) { if (gkKernel == NULL) { void* extrapolatedArgs[] = {&cu.getForce().getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer()}; cu.executeKernel(addExtrapolatedGradientKernel, extrapolatedArgs, numMultipoles); } else { void* extrapolatedArgs[] = {&cu.getForce().getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer(), &extrapolatedDipoleFieldGradientGk.getDevicePointer(), &extrapolatedDipoleFieldGradientGkPolar.getDevicePointer()}; cu.executeKernel(addExtrapolatedGradientKernel, extrapolatedArgs, numMultipoles); } } // Map torques to force. void* mapTorqueArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer()}; cu.executeKernel(mapTorqueKernel, mapTorqueArgs, cu.getNumAtoms()); // Record the current atom positions so we can tell later if they have changed. cu.getPosq().copyTo(lastPositions); multipolesAreValid = true; return 0.0; } void CudaCalcAmoebaMultipoleForceKernel::computeInducedField(void** recipBoxVectorPointer) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); unsigned int maxTiles = 0; vector<void*> computeInducedFieldArgs; computeInducedFieldArgs.push_back(&inducedField.getDevicePointer()); computeInducedFieldArgs.push_back(&inducedFieldPolar.getDevicePointer()); computeInducedFieldArgs.push_back(&cu.getPosq().getDevicePointer()); computeInducedFieldArgs.push_back(&nb.getExclusionTiles().getDevicePointer()); computeInducedFieldArgs.push_back(&inducedDipole.getDevicePointer()); computeInducedFieldArgs.push_back(&inducedDipolePolar.getDevicePointer()); computeInducedFieldArgs.push_back(&startTileIndex); computeInducedFieldArgs.push_back(&numTileIndices); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { computeInducedFieldArgs.push_back(&inducedDipoleFieldGradient.getDevicePointer()); computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientPolar.getDevicePointer()); } if (pmeGrid.isInitialized()) { computeInducedFieldArgs.push_back(&nb.getInteractingTiles().getDevicePointer()); computeInducedFieldArgs.push_back(&nb.getInteractionCount().getDevicePointer()); computeInducedFieldArgs.push_back(cu.getPeriodicBoxSizePointer()); computeInducedFieldArgs.push_back(cu.getInvPeriodicBoxSizePointer()); computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecXPointer()); computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecYPointer()); computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecZPointer()); computeInducedFieldArgs.push_back(&maxTiles); computeInducedFieldArgs.push_back(&nb.getBlockCenters().getDevicePointer()); computeInducedFieldArgs.push_back(&nb.getInteractingAtoms().getDevicePointer()); } if (gkKernel != NULL) { computeInducedFieldArgs.push_back(&gkKernel->getInducedField().getDevicePointer()); computeInducedFieldArgs.push_back(&gkKernel->getInducedFieldPolar().getDevicePointer()); computeInducedFieldArgs.push_back(&gkKernel->getInducedDipoles().getDevicePointer()); computeInducedFieldArgs.push_back(&gkKernel->getInducedDipolesPolar().getDevicePointer()); computeInducedFieldArgs.push_back(&gkKernel->getBornRadii().getDevicePointer()); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientGk.getDevicePointer()); computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientGkPolar.getDevicePointer()); } } computeInducedFieldArgs.push_back(&dampingAndThole.getDevicePointer()); cu.clearBuffer(inducedField); cu.clearBuffer(inducedFieldPolar); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { cu.clearBuffer(inducedDipoleFieldGradient); cu.clearBuffer(inducedDipoleFieldGradientPolar); } if (gkKernel != NULL) { cu.clearBuffer(gkKernel->getInducedField()); cu.clearBuffer(gkKernel->getInducedFieldPolar()); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { cu.clearBuffer(inducedDipoleFieldGradientGk); cu.clearBuffer(inducedDipoleFieldGradientGkPolar); } } if (!pmeGrid.isInitialized()) cu.executeKernel(computeInducedFieldKernel, &computeInducedFieldArgs[0], numForceThreadBlocks*inducedFieldThreads, inducedFieldThreads); else { maxTiles = nb.getInteractingTiles().getSize(); cu.executeKernel(computeInducedFieldKernel, &computeInducedFieldArgs[0], numForceThreadBlocks*inducedFieldThreads, inducedFieldThreads); cu.clearBuffer(pmeGrid); void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms()); if (cu.getUseDoublePrecision()) { void* finishSpreadArgs[] = {&pmeGrid.getDevicePointer()}; cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize()); cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); } else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD); void* pmeConvolutionArgs[] = {&pmeGrid.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(), &pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); else cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE); void* pmeInducedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms()); if (polarizationType == AmoebaMultipoleForce::Extrapolated) { void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &inducedField.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms()); } else { void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(), &inducedField.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms()); } } } bool CudaCalcAmoebaMultipoleForceKernel::iterateDipolesByDIIS(int iteration) { void* npt = NULL; bool trueValue = true, falseValue = false; int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); // Record the dipoles and errors into the lists of previous dipoles. if (gkKernel != NULL) { void* recordDIISDipolesGkArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &gkKernel->getField().getDevicePointer(), &gkKernel->getInducedField().getDevicePointer(), &gkKernel->getInducedFieldPolar().getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &polarizability.getDevicePointer(), &inducedDipoleErrors.getDevicePointer(), &prevDipolesGk.getDevicePointer(), &prevDipolesGkPolar.getDevicePointer(), &prevErrors.getDevicePointer(), &iteration, &falseValue, &diisMatrix.getDevicePointer()}; cu.executeKernel(recordDIISDipolesKernel, recordDIISDipolesGkArgs, cu.getNumThreadBlocks()*cu.ThreadBlockSize, cu.ThreadBlockSize, cu.ThreadBlockSize*elementSize*2); } void* recordDIISDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &npt, &inducedField.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer(), &inducedDipoleErrors.getDevicePointer(), &prevDipoles.getDevicePointer(), &prevDipolesPolar.getDevicePointer(), &prevErrors.getDevicePointer(), &iteration, &trueValue, &diisMatrix.getDevicePointer()}; cu.executeKernel(recordDIISDipolesKernel, recordDIISDipolesArgs, cu.getNumThreadBlocks()*cu.ThreadBlockSize, cu.ThreadBlockSize, cu.ThreadBlockSize*elementSize*2); float2* errors = (float2*) cu.getPinnedBuffer(); inducedDipoleErrors.download(errors, false); cuEventRecord(syncEvent, cu.getCurrentStream()); // Build the DIIS matrix. int numPrev = (iteration+1 < MaxPrevDIISDipoles ? iteration+1 : MaxPrevDIISDipoles); void* buildMatrixArgs[] = {&prevErrors.getDevicePointer(), &iteration, &diisMatrix.getDevicePointer()}; int threadBlocks = min(numPrev, cu.getNumThreadBlocks()); int blockSize = 512; cu.executeKernel(buildMatrixKernel, buildMatrixArgs, threadBlocks*blockSize, blockSize, blockSize*elementSize); // Solve the matrix. void* solveMatrixArgs[] = {&iteration, &diisMatrix.getDevicePointer(), &diisCoefficients.getDevicePointer()}; cu.executeKernel(solveMatrixKernel, solveMatrixArgs, 32, 32); // Determine whether the iteration has converged. cuEventSynchronize(syncEvent); double total1 = 0.0, total2 = 0.0; for (int j = 0; j < inducedDipoleErrors.getSize(); j++) { total1 += errors[j].x; total2 += errors[j].y; } if (48.033324*sqrt(max(total1, total2)/cu.getNumAtoms()) < inducedEpsilon) return true; // Compute the dipoles. void* updateInducedFieldArgs[] = {&inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &prevDipoles.getDevicePointer(), &prevDipolesPolar.getDevicePointer(), &diisCoefficients.getDevicePointer(), &numPrev}; cu.executeKernel(updateInducedFieldKernel, updateInducedFieldArgs, 3*cu.getNumAtoms(), 256); if (gkKernel != NULL) { void* updateInducedFieldGkArgs[] = {&gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &prevDipolesGk.getDevicePointer(), &prevDipolesGkPolar.getDevicePointer(), &diisCoefficients.getDevicePointer(), &numPrev}; cu.executeKernel(updateInducedFieldKernel, updateInducedFieldGkArgs, 3*cu.getNumAtoms(), 256); } return false; } void CudaCalcAmoebaMultipoleForceKernel::computeExtrapolatedDipoles(void** recipBoxVectorPointer) { // Start by storing the direct dipoles as PT0 if (gkKernel == NULL) { void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer()}; cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize()); } else { void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer(), &inducedDipoleFieldGradientGk.getDevicePointer(), &inducedDipoleFieldGradientGkPolar.getDevicePointer()}; cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize()); } // Recursively apply alpha.Tau to the µ_(n) components to generate µ_(n+1), and store the result for (int order = 1; order < maxExtrapolationOrder; ++order) { computeInducedField(recipBoxVectorPointer); if (gkKernel == NULL) { void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize()); } else { void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer(), &inducedDipoleFieldGradientGk.getDevicePointer(), &inducedDipoleFieldGradientGkPolar.getDevicePointer(), &gkKernel->getInducedField().getDevicePointer(), &gkKernel->getInducedFieldPolar().getDevicePointer(), &extrapolatedDipoleFieldGradientGk.getDevicePointer(), &extrapolatedDipoleFieldGradientGkPolar.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize()); } } // Take a linear combination of the µ_(n) components to form the total dipole if (gkKernel == NULL) { void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer()}; cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize()); } else { void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer()}; cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize()); } computeInducedField(recipBoxVectorPointer); } void CudaCalcAmoebaMultipoleForceKernel::ensureMultipolesValid(ContextImpl& context) { if (multipolesAreValid) { int numParticles = cu.getNumAtoms(); if (cu.getUseDoublePrecision()) { vector<double4> pos1, pos2; cu.getPosq().download(pos1); lastPositions.download(pos2); for (int i = 0; i < numParticles; i++) if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) { multipolesAreValid = false; break; } } else { vector<float4> pos1, pos2; cu.getPosq().download(pos1); lastPositions.download(pos2); for (int i = 0; i < numParticles; i++) if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) { multipolesAreValid = false; break; } } } if (!multipolesAreValid) context.calcForcesAndEnergy(false, false, -1); } void CudaCalcAmoebaMultipoleForceKernel::getLabFramePermanentDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double> labDipoleVec; labFrameDipoles.download(labDipoleVec); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(labDipoleVec[3*i], labDipoleVec[3*i+1], labDipoleVec[3*i+2]); } else { vector<float> labDipoleVec; labFrameDipoles.download(labDipoleVec); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(labDipoleVec[3*i], labDipoleVec[3*i+1], labDipoleVec[3*i+2]); } } void CudaCalcAmoebaMultipoleForceKernel::getInducedDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double> d; inducedDipole.download(d); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(d[3*i], d[3*i+1], d[3*i+2]); } else { vector<float> d; inducedDipole.download(d); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(d[3*i], d[3*i+1], d[3*i+2]); } } void CudaCalcAmoebaMultipoleForceKernel::getTotalDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double4> posqVec; vector<double> labDipoleVec; vector<double> inducedDipoleVec; double totalDipoleVecX; double totalDipoleVecY; double totalDipoleVecZ; inducedDipole.download(inducedDipoleVec); labFrameDipoles.download(labDipoleVec); cu.getPosq().download(posqVec); for (int i = 0; i < numParticles; i++) { totalDipoleVecX = labDipoleVec[3*i] + inducedDipoleVec[3*i]; totalDipoleVecY = labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1]; totalDipoleVecZ = labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2]; dipoles[order[i]] = Vec3(totalDipoleVecX, totalDipoleVecY, totalDipoleVecZ); } } else { vector<float4> posqVec; vector<float> labDipoleVec; vector<float> inducedDipoleVec; float totalDipoleVecX; float totalDipoleVecY; float totalDipoleVecZ; inducedDipole.download(inducedDipoleVec); labFrameDipoles.download(labDipoleVec); cu.getPosq().download(posqVec); for (int i = 0; i < numParticles; i++) { totalDipoleVecX = labDipoleVec[3*i] + inducedDipoleVec[3*i]; totalDipoleVecY = labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1]; totalDipoleVecZ = labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2]; dipoles[order[i]] = Vec3(totalDipoleVecX, totalDipoleVecY, totalDipoleVecZ); } } } void CudaCalcAmoebaMultipoleForceKernel::getElectrostaticPotential(ContextImpl& context, const vector<Vec3>& inputGrid, vector<double>& outputElectrostaticPotential) { ensureMultipolesValid(context); int numPoints = inputGrid.size(); int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); CudaArray points(cu, numPoints, 4*elementSize, "points"); CudaArray potential(cu, numPoints, elementSize, "potential"); // Copy the grid points to the GPU. if (cu.getUseDoublePrecision()) { vector<double4> p(numPoints); for (int i = 0; i < numPoints; i++) p[i] = make_double4(inputGrid[i][0], inputGrid[i][1], inputGrid[i][2], 0); points.upload(p); } else { vector<float4> p(numPoints); for (int i = 0; i < numPoints; i++) p[i] = make_float4((float) inputGrid[i][0], (float) inputGrid[i][1], (float) inputGrid[i][2], 0); points.upload(p); } // Compute the potential. void* computePotentialArgs[] = {&cu.getPosq().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &points.getDevicePointer(), &potential.getDevicePointer(), &numPoints, cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer()}; int blockSize = 128; cu.executeKernel(computePotentialKernel, computePotentialArgs, numPoints, blockSize, blockSize*15*elementSize); outputElectrostaticPotential.resize(numPoints); if (cu.getUseDoublePrecision()) potential.download(outputElectrostaticPotential); else { vector<float> p(numPoints); potential.download(p); for (int i = 0; i < numPoints; i++) outputElectrostaticPotential[i] = p[i]; } } template <class T, class T4, class M4> void CudaCalcAmoebaMultipoleForceKernel::computeSystemMultipoleMoments(ContextImpl& context, vector<double>& outputMultipoleMoments) { // Compute the local coordinates relative to the center of mass. int numAtoms = cu.getNumAtoms(); vector<T4> posq; vector<M4> velm; cu.getPosq().download(posq); cu.getVelm().download(velm); double totalMass = 0.0; Vec3 centerOfMass(0, 0, 0); for (int i = 0; i < numAtoms; i++) { double mass = (velm[i].w > 0 ? 1.0/velm[i].w : 0.0); totalMass += mass; centerOfMass[0] += mass*posq[i].x; centerOfMass[1] += mass*posq[i].y; centerOfMass[2] += mass*posq[i].z; } if (totalMass > 0.0) { centerOfMass[0] /= totalMass; centerOfMass[1] /= totalMass; centerOfMass[2] /= totalMass; } vector<double4> posqLocal(numAtoms); for (int i = 0; i < numAtoms; i++) { posqLocal[i].x = posq[i].x - centerOfMass[0]; posqLocal[i].y = posq[i].y - centerOfMass[1]; posqLocal[i].z = posq[i].z - centerOfMass[2]; posqLocal[i].w = posq[i].w; } // Compute the multipole moments. double totalCharge = 0.0; double xdpl = 0.0; double ydpl = 0.0; double zdpl = 0.0; double xxqdp = 0.0; double xyqdp = 0.0; double xzqdp = 0.0; double yxqdp = 0.0; double yyqdp = 0.0; double yzqdp = 0.0; double zxqdp = 0.0; double zyqdp = 0.0; double zzqdp = 0.0; vector<T> labDipoleVec, inducedDipoleVec, quadrupoleVec; labFrameDipoles.download(labDipoleVec); inducedDipole.download(inducedDipoleVec); labFrameQuadrupoles.download(quadrupoleVec); for (int i = 0; i < numAtoms; i++) { totalCharge += posqLocal[i].w; double netDipoleX = (labDipoleVec[3*i] + inducedDipoleVec[3*i]); double netDipoleY = (labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1]); double netDipoleZ = (labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2]); xdpl += posqLocal[i].x*posqLocal[i].w + netDipoleX; ydpl += posqLocal[i].y*posqLocal[i].w + netDipoleY; zdpl += posqLocal[i].z*posqLocal[i].w + netDipoleZ; xxqdp += posqLocal[i].x*posqLocal[i].x*posqLocal[i].w + 2*posqLocal[i].x*netDipoleX; xyqdp += posqLocal[i].x*posqLocal[i].y*posqLocal[i].w + posqLocal[i].x*netDipoleY + posqLocal[i].y*netDipoleX; xzqdp += posqLocal[i].x*posqLocal[i].z*posqLocal[i].w + posqLocal[i].x*netDipoleZ + posqLocal[i].z*netDipoleX; yxqdp += posqLocal[i].y*posqLocal[i].x*posqLocal[i].w + posqLocal[i].y*netDipoleX + posqLocal[i].x*netDipoleY; yyqdp += posqLocal[i].y*posqLocal[i].y*posqLocal[i].w + 2*posqLocal[i].y*netDipoleY; yzqdp += posqLocal[i].y*posqLocal[i].z*posqLocal[i].w + posqLocal[i].y*netDipoleZ + posqLocal[i].z*netDipoleY; zxqdp += posqLocal[i].z*posqLocal[i].x*posqLocal[i].w + posqLocal[i].z*netDipoleX + posqLocal[i].x*netDipoleZ; zyqdp += posqLocal[i].z*posqLocal[i].y*posqLocal[i].w + posqLocal[i].z*netDipoleY + posqLocal[i].y*netDipoleZ; zzqdp += posqLocal[i].z*posqLocal[i].z*posqLocal[i].w + 2*posqLocal[i].z*netDipoleZ; } // Convert the quadrupole from traced to traceless form. double qave = (xxqdp + yyqdp + zzqdp)/3; xxqdp = 1.5*(xxqdp-qave); xyqdp = 1.5*xyqdp; xzqdp = 1.5*xzqdp; yxqdp = 1.5*yxqdp; yyqdp = 1.5*(yyqdp-qave); yzqdp = 1.5*yzqdp; zxqdp = 1.5*zxqdp; zyqdp = 1.5*zyqdp; zzqdp = 1.5*(zzqdp-qave); // Add the traceless atomic quadrupoles to the total quadrupole moment. for (int i = 0; i < numAtoms; i++) { xxqdp = xxqdp + 3*quadrupoleVec[5*i]; xyqdp = xyqdp + 3*quadrupoleVec[5*i+1]; xzqdp = xzqdp + 3*quadrupoleVec[5*i+2]; yxqdp = yxqdp + 3*quadrupoleVec[5*i+1]; yyqdp = yyqdp + 3*quadrupoleVec[5*i+3]; yzqdp = yzqdp + 3*quadrupoleVec[5*i+4]; zxqdp = zxqdp + 3*quadrupoleVec[5*i+2]; zyqdp = zyqdp + 3*quadrupoleVec[5*i+4]; zzqdp = zzqdp + -3*(quadrupoleVec[5*i]+quadrupoleVec[5*i+3]); } double debye = 4.80321; outputMultipoleMoments.resize(13); outputMultipoleMoments[0] = totalCharge; outputMultipoleMoments[1] = 10.0*xdpl*debye; outputMultipoleMoments[2] = 10.0*ydpl*debye; outputMultipoleMoments[3] = 10.0*zdpl*debye; outputMultipoleMoments[4] = 100.0*xxqdp*debye; outputMultipoleMoments[5] = 100.0*xyqdp*debye; outputMultipoleMoments[6] = 100.0*xzqdp*debye; outputMultipoleMoments[7] = 100.0*yxqdp*debye; outputMultipoleMoments[8] = 100.0*yyqdp*debye; outputMultipoleMoments[9] = 100.0*yzqdp*debye; outputMultipoleMoments[10] = 100.0*zxqdp*debye; outputMultipoleMoments[11] = 100.0*zyqdp*debye; outputMultipoleMoments[12] = 100.0*zzqdp*debye; } void CudaCalcAmoebaMultipoleForceKernel::getSystemMultipoleMoments(ContextImpl& context, vector<double>& outputMultipoleMoments) { ensureMultipolesValid(context); if (cu.getUseDoublePrecision()) computeSystemMultipoleMoments<double, double4, double4>(context, outputMultipoleMoments); else if (cu.getUseMixedPrecision()) computeSystemMultipoleMoments<float, float4, double4>(context, outputMultipoleMoments); else computeSystemMultipoleMoments<float, float4, float4>(context, outputMultipoleMoments); } void CudaCalcAmoebaMultipoleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaMultipoleForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumMultipoles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of multipoles has changed"); // Record the per-multipole parameters. cu.getPosq().download(cu.getPinnedBuffer()); float4* posqf = (float4*) cu.getPinnedBuffer(); double4* posqd = (double4*) cu.getPinnedBuffer(); vector<float2> dampingAndTholeVec; vector<float> polarizabilityVec; vector<float> molecularDipolesVec; vector<float> molecularQuadrupolesVec; vector<int4> multipoleParticlesVec; for (int i = 0; i < force.getNumMultipoles(); i++) { double charge, thole, damping, polarity; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; force.getMultipoleParameters(i, charge, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity); if (cu.getUseDoublePrecision()) posqd[i].w = charge; else posqf[i].w = (float) charge; dampingAndTholeVec.push_back(make_float2((float) damping, (float) thole)); polarizabilityVec.push_back((float) polarity); multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType)); for (int j = 0; j < 3; j++) molecularDipolesVec.push_back((float) dipole[j]); molecularQuadrupolesVec.push_back((float) quadrupole[0]); molecularQuadrupolesVec.push_back((float) quadrupole[1]); molecularQuadrupolesVec.push_back((float) quadrupole[2]); molecularQuadrupolesVec.push_back((float) quadrupole[4]); molecularQuadrupolesVec.push_back((float) quadrupole[5]); } if (!hasQuadrupoles) { for (auto q : molecularQuadrupolesVec) if (q != 0.0) throw OpenMMException("updateParametersInContext: Cannot set a non-zero quadrupole moment, because quadrupoles were excluded from the kernel"); } for (int i = force.getNumMultipoles(); i < cu.getPaddedNumAtoms(); i++) { dampingAndTholeVec.push_back(make_float2(0, 0)); polarizabilityVec.push_back(0); multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0)); for (int j = 0; j < 3; j++) molecularDipolesVec.push_back(0); for (int j = 0; j < 5; j++) molecularQuadrupolesVec.push_back(0); } dampingAndThole.upload(dampingAndTholeVec); polarizability.upload(polarizabilityVec); multipoleParticles.upload(multipoleParticlesVec); molecularDipoles.upload(molecularDipolesVec); molecularQuadrupoles.upload(molecularQuadrupolesVec); cu.getPosq().upload(cu.getPinnedBuffer()); cu.invalidateMolecules(); multipolesAreValid = false; } void CudaCalcAmoebaMultipoleForceKernel::getPMEParameters(double& alpha, int& nx, int& ny, int& nz) const { if (!usePME) throw OpenMMException("getPMEParametersInContext: This Context is not using PME"); alpha = this->alpha; nx = gridSizeX; ny = gridSizeY; nz = gridSizeZ; } /* -------------------------------------------------------------------------- * * AmoebaGeneralizedKirkwood * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaGeneralizedKirkwoodForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaGeneralizedKirkwoodForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double charge1, charge2, radius1, radius2, scale1, scale2; force.getParticleParameters(particle1, charge1, radius1, scale1); force.getParticleParameters(particle2, charge2, radius2, scale2); return (charge1 == charge2 && radius1 == radius2 && scale1 == scale2); } private: const AmoebaGeneralizedKirkwoodForce& force; }; CudaCalcAmoebaGeneralizedKirkwoodForceKernel::CudaCalcAmoebaGeneralizedKirkwoodForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaGeneralizedKirkwoodForceKernel(name, platform), cu(cu), system(system), hasInitializedKernels(false) { } void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::initialize(const System& system, const AmoebaGeneralizedKirkwoodForce& force) { cu.setAsCurrent(); if (cu.getPlatformData().contexts.size() > 1) throw OpenMMException("AmoebaGeneralizedKirkwoodForce does not support using multiple CUDA devices"); const AmoebaMultipoleForce* multipoles = NULL; for (int i = 0; i < system.getNumForces() && multipoles == NULL; i++) multipoles = dynamic_cast<const AmoebaMultipoleForce*>(&system.getForce(i)); if (multipoles == NULL) throw OpenMMException("AmoebaGeneralizedKirkwoodForce requires the System to also contain an AmoebaMultipoleForce"); CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int paddedNumAtoms = cu.getPaddedNumAtoms(); int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); params.initialize<float2>(cu, paddedNumAtoms, "amoebaGkParams"); bornRadii .initialize(cu, paddedNumAtoms, elementSize, "bornRadii"); field .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkField"); bornSum.initialize<long long>(cu, paddedNumAtoms, "bornSum"); bornForce.initialize<long long>(cu, paddedNumAtoms, "bornForce"); inducedDipoleS .initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipoleS"); inducedDipolePolarS .initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipolePolarS"); polarizationType = multipoles->getPolarizationType(); if (polarizationType != AmoebaMultipoleForce::Direct) { inducedField .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkInducedField"); inducedFieldPolar .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkInducedFieldPolar"); } cu.addAutoclearBuffer(field); cu.addAutoclearBuffer(bornSum); cu.addAutoclearBuffer(bornForce); vector<float2> paramsVector(paddedNumAtoms); for (int i = 0; i < force.getNumParticles(); i++) { double charge, radius, scalingFactor; force.getParticleParameters(i, charge, radius, scalingFactor); paramsVector[i] = make_float2((float) radius, (float) (scalingFactor*radius)); // Make sure the charge matches the one specified by the AmoebaMultipoleForce. double charge2, thole, damping, polarity; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; multipoles->getMultipoleParameters(i, charge2, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity); if (charge != charge2) throw OpenMMException("AmoebaGeneralizedKirkwoodForce and AmoebaMultipoleForce must specify the same charge for every atom"); } params.upload(paramsVector); // Select the number of threads for each kernel. double computeBornSumThreadMemory = 4*elementSize+3*sizeof(float); double gkForceThreadMemory = 24*elementSize; double chainRuleThreadMemory = 10*elementSize; double ediffThreadMemory = 28*elementSize+2*sizeof(float)+3*sizeof(int)/(double) cu.TileSize; int maxThreads = cu.getNonbondedUtilities().getForceThreadBlockSize(); computeBornSumThreads = min(maxThreads, cu.computeThreadBlockSize(computeBornSumThreadMemory)); gkForceThreads = min(maxThreads, cu.computeThreadBlockSize(gkForceThreadMemory)); chainRuleThreads = min(maxThreads, cu.computeThreadBlockSize(chainRuleThreadMemory)); ediffThreads = min(maxThreads, cu.computeThreadBlockSize(ediffThreadMemory)); // Set preprocessor macros we will use when we create the kernels. defines["NUM_ATOMS"] = cu.intToString(cu.getNumAtoms()); defines["PADDED_NUM_ATOMS"] = cu.intToString(paddedNumAtoms); defines["BORN_SUM_THREAD_BLOCK_SIZE"] = cu.intToString(computeBornSumThreads); defines["GK_FORCE_THREAD_BLOCK_SIZE"] = cu.intToString(gkForceThreads); defines["CHAIN_RULE_THREAD_BLOCK_SIZE"] = cu.intToString(chainRuleThreads); defines["EDIFF_THREAD_BLOCK_SIZE"] = cu.intToString(ediffThreads); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["GK_C"] = cu.doubleToString(2.455); double solventDielectric = force.getSolventDielectric(); defines["GK_FC"] = cu.doubleToString(1*(1-solventDielectric)/(0+1*solventDielectric)); defines["GK_FD"] = cu.doubleToString(2*(1-solventDielectric)/(1+2*solventDielectric)); defines["GK_FQ"] = cu.doubleToString(3*(1-solventDielectric)/(2+3*solventDielectric)); defines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456); defines["M_PI"] = cu.doubleToString(M_PI); defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456/force.getSoluteDielectric()); if (polarizationType == AmoebaMultipoleForce::Direct) defines["DIRECT_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Mutual) defines["MUTUAL_POLARIZATION"] = ""; else if (polarizationType == AmoebaMultipoleForce::Extrapolated) defines["EXTRAPOLATED_POLARIZATION"] = ""; includeSurfaceArea = force.getIncludeCavityTerm(); if (includeSurfaceArea) { defines["SURFACE_AREA_FACTOR"] = cu.doubleToString(force.getSurfaceAreaFactor()); defines["PROBE_RADIUS"] = cu.doubleToString(force.getProbeRadius()); defines["DIELECTRIC_OFFSET"] = cu.doubleToString(0.009); } cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaGeneralizedKirkwoodForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { // Since GK is so tightly entwined with the electrostatics, this method does nothing, and the force calculation // is driven by AmoebaMultipoleForce. return 0.0; } void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::computeBornRadii() { if (!hasInitializedKernels) { hasInitializedKernels = true; // Create the kernels. int numExclusionTiles = cu.getNonbondedUtilities().getExclusionTiles().getSize(); defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(numExclusionTiles); int numContexts = cu.getPlatformData().contexts.size(); int startExclusionIndex = cu.getContextIndex()*numExclusionTiles/numContexts; int endExclusionIndex = (cu.getContextIndex()+1)*numExclusionTiles/numContexts; defines["FIRST_EXCLUSION_TILE"] = cu.intToString(startExclusionIndex); defines["LAST_EXCLUSION_TILE"] = cu.intToString(endExclusionIndex); stringstream forceSource; forceSource << CudaKernelSources::vectorOps; forceSource << CudaAmoebaKernelSources::amoebaGk; forceSource << "#define F1\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; forceSource << CudaAmoebaKernelSources::gkEDiffPairForce; forceSource << "#undef F1\n"; forceSource << "#define F2\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; forceSource << "#undef F2\n"; forceSource << "#define T1\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; forceSource << CudaAmoebaKernelSources::gkEDiffPairForce; forceSource << "#undef T1\n"; forceSource << "#define T2\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; forceSource << "#undef T2\n"; forceSource << "#define T3\n"; forceSource << CudaAmoebaKernelSources::gkEDiffPairForce; forceSource << "#undef T3\n"; forceSource << "#define B1\n"; forceSource << "#define B2\n"; forceSource << CudaAmoebaKernelSources::gkPairForce1; forceSource << CudaAmoebaKernelSources::gkPairForce2; CUmodule module = cu.createModule(forceSource.str(), defines); computeBornSumKernel = cu.getKernel(module, "computeBornSum"); reduceBornSumKernel = cu.getKernel(module, "reduceBornSum"); gkForceKernel = cu.getKernel(module, "computeGKForces"); chainRuleKernel = cu.getKernel(module, "computeChainRuleForce"); ediffKernel = cu.getKernel(module, "computeEDiffForce"); if (includeSurfaceArea) surfaceAreaKernel = cu.getKernel(module, "computeSurfaceAreaForce"); } CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int numTiles = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); void* computeBornSumArgs[] = {&bornSum.getDevicePointer(), &cu.getPosq().getDevicePointer(), &params.getDevicePointer(), &numTiles}; cu.executeKernel(computeBornSumKernel, computeBornSumArgs, numForceThreadBlocks*computeBornSumThreads, computeBornSumThreads); void* reduceBornSumArgs[] = {&bornSum.getDevicePointer(), &params.getDevicePointer(), &bornRadii.getDevicePointer()}; cu.executeKernel(reduceBornSumKernel, reduceBornSumArgs, cu.getNumAtoms()); } void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::finishComputation(CudaArray& torque, CudaArray& labFrameDipoles, CudaArray& labFrameQuadrupoles, CudaArray& inducedDipole, CudaArray& inducedDipolePolar, CudaArray& dampingAndThole, CudaArray& covalentFlags, CudaArray& polarizationGroupFlags) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); // Compute the GK force. void* gkForceArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices, &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &inducedDipoleS.getDevicePointer(), &inducedDipolePolarS.getDevicePointer(), &bornRadii.getDevicePointer(), &bornForce.getDevicePointer()}; cu.executeKernel(gkForceKernel, gkForceArgs, numForceThreadBlocks*gkForceThreads, gkForceThreads); // Compute the surface area force. if (includeSurfaceArea) { void* surfaceAreaArgs[] = {&bornForce.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &params.getDevicePointer(), &bornRadii.getDevicePointer()}; cu.executeKernel(surfaceAreaKernel, surfaceAreaArgs, cu.getNumAtoms()); } // Apply the remaining terms. void* chainRuleArgs[] = {&cu.getForce().getDevicePointer(), &cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices, &params.getDevicePointer(), &bornRadii.getDevicePointer(), &bornForce.getDevicePointer()}; cu.executeKernel(chainRuleKernel, chainRuleArgs, numForceThreadBlocks*chainRuleThreads, chainRuleThreads); void* ediffArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices, &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &inducedDipoleS.getDevicePointer(), &inducedDipolePolarS.getDevicePointer(), &dampingAndThole.getDevicePointer()}; cu.executeKernel(ediffKernel, ediffArgs, numForceThreadBlocks*ediffThreads, ediffThreads); } void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaGeneralizedKirkwoodForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumParticles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of particles has changed"); // Record the per-particle parameters. vector<float2> paramsVector(cu.getPaddedNumAtoms()); for (int i = 0; i < force.getNumParticles(); i++) { double charge, radius, scalingFactor; force.getParticleParameters(i, charge, radius, scalingFactor); paramsVector[i] = make_float2((float) radius, (float) (scalingFactor*radius)); } params.upload(paramsVector); cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaVdw * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaVdwForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaVdwForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { int iv1, iv2; double sigma1, sigma2, epsilon1, epsilon2, reduction1, reduction2; bool isAlchemical1, isAlchemical2; force.getParticleParameters(particle1, iv1, sigma1, epsilon1, reduction1, isAlchemical1); force.getParticleParameters(particle2, iv2, sigma2, epsilon2, reduction2, isAlchemical2); return (sigma1 == sigma2 && epsilon1 == epsilon2 && reduction1 == reduction2 && isAlchemical1 == isAlchemical2); } private: const AmoebaVdwForce& force; }; CudaCalcAmoebaVdwForceKernel::CudaCalcAmoebaVdwForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaVdwForceKernel(name, platform), cu(cu), system(system), hasInitializedNonbonded(false), nonbonded(NULL), vdwLambdaPinnedBuffer(NULL) { } CudaCalcAmoebaVdwForceKernel::~CudaCalcAmoebaVdwForceKernel() { cu.setAsCurrent(); if (nonbonded != NULL) delete nonbonded; if (vdwLambdaPinnedBuffer != NULL) cuMemFreeHost(vdwLambdaPinnedBuffer); } void CudaCalcAmoebaVdwForceKernel::initialize(const System& system, const AmoebaVdwForce& force) { cu.setAsCurrent(); sigmaEpsilon.initialize<float2>(cu, cu.getPaddedNumAtoms(), "sigmaEpsilon"); bondReductionAtoms.initialize<int>(cu, cu.getPaddedNumAtoms(), "bondReductionAtoms"); bondReductionFactors.initialize<float>(cu, cu.getPaddedNumAtoms(), "bondReductionFactors"); tempPosq.initialize(cu, cu.getPaddedNumAtoms(), cu.getUseDoublePrecision() ? sizeof(double4) : sizeof(float4), "tempPosq"); tempForces.initialize<long long>(cu, 3*cu.getPaddedNumAtoms(), "tempForces"); // Record atom parameters. vector<float2> sigmaEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 1)); vector<float> isAlchemicalVec(cu.getPaddedNumAtoms(), 0); vector<int> bondReductionAtomsVec(cu.getPaddedNumAtoms(), 0); vector<float> bondReductionFactorsVec(cu.getPaddedNumAtoms(), 0); vector<vector<int> > exclusions(cu.getNumAtoms()); // Handle Alchemical parameters. hasAlchemical = force.getAlchemicalMethod() != AmoebaVdwForce::None; if (hasAlchemical) { isAlchemical.initialize<float>(cu, cu.getPaddedNumAtoms(), "isAlchemical"); vdwLambda.initialize<float>(cu, 1, "vdwLambda"); CHECK_RESULT(cuMemHostAlloc(&vdwLambdaPinnedBuffer, sizeof(float), 0), "Error allocating vdwLambda pinned buffer"); } for (int i = 0; i < force.getNumParticles(); i++) { int ivIndex; double sigma, epsilon, reductionFactor; bool alchemical; force.getParticleParameters(i, ivIndex, sigma, epsilon, reductionFactor, alchemical); sigmaEpsilonVec[i] = make_float2((float) sigma, (float) epsilon); isAlchemicalVec[i] = (alchemical) ? 1.0f : 0.0f; bondReductionAtomsVec[i] = ivIndex; bondReductionFactorsVec[i] = (float) reductionFactor; force.getParticleExclusions(i, exclusions[i]); exclusions[i].push_back(i); } sigmaEpsilon.upload(sigmaEpsilonVec); bondReductionAtoms.upload(bondReductionAtomsVec); bondReductionFactors.upload(bondReductionFactorsVec); if (force.getUseDispersionCorrection()) dispersionCoefficient = AmoebaVdwForceImpl::calcDispersionCorrection(system, force); else dispersionCoefficient = 0.0; // This force is applied based on modified atom positions, where hydrogens have been moved slightly // closer to their parent atoms. We therefore create a separate CudaNonbondedUtilities just for // this force, so it will have its own neighbor list and interaction kernel. nonbonded = new CudaNonbondedUtilities(cu); nonbonded->addParameter(CudaNonbondedUtilities::ParameterInfo("sigmaEpsilon", "float", 2, sizeof(float2), sigmaEpsilon.getDevicePointer())); if (hasAlchemical) { isAlchemical.upload(isAlchemicalVec); ((float*) vdwLambdaPinnedBuffer)[0] = 1.0f; currentVdwLambda = 1.0f; vdwLambda.upload(vdwLambdaPinnedBuffer, false); nonbonded->addParameter(CudaNonbondedUtilities::ParameterInfo("isAlchemical", "float", 1, sizeof(float), isAlchemical.getDevicePointer())); nonbonded->addArgument(CudaNonbondedUtilities::ParameterInfo("vdwLambda", "float", 1, sizeof(float), vdwLambda.getDevicePointer())); } // Create the interaction kernel. map<string, string> replacements; string sigmaCombiningRule = force.getSigmaCombiningRule(); if (sigmaCombiningRule == "ARITHMETIC") replacements["SIGMA_COMBINING_RULE"] = "1"; else if (sigmaCombiningRule == "GEOMETRIC") replacements["SIGMA_COMBINING_RULE"] = "2"; else if (sigmaCombiningRule == "CUBIC-MEAN") replacements["SIGMA_COMBINING_RULE"] = "3"; else throw OpenMMException("Illegal combining rule for sigma: "+sigmaCombiningRule); string epsilonCombiningRule = force.getEpsilonCombiningRule(); if (epsilonCombiningRule == "ARITHMETIC") replacements["EPSILON_COMBINING_RULE"] = "1"; else if (epsilonCombiningRule == "GEOMETRIC") replacements["EPSILON_COMBINING_RULE"] = "2"; else if (epsilonCombiningRule =="HARMONIC") replacements["EPSILON_COMBINING_RULE"] = "3"; else if (epsilonCombiningRule == "W-H") replacements["EPSILON_COMBINING_RULE"] = "4"; else if (epsilonCombiningRule == "HHG") replacements["EPSILON_COMBINING_RULE"] = "5"; else throw OpenMMException("Illegal combining rule for sigma: "+sigmaCombiningRule); replacements["VDW_ALCHEMICAL_METHOD"] = cu.intToString(force.getAlchemicalMethod()); replacements["VDW_SOFTCORE_POWER"] = cu.intToString(force.getSoftcorePower()); replacements["VDW_SOFTCORE_ALPHA"] = cu.doubleToString(force.getSoftcoreAlpha()); double cutoff = force.getCutoffDistance(); double taperCutoff = cutoff*0.9; replacements["CUTOFF_DISTANCE"] = cu.doubleToString(force.getCutoffDistance()); replacements["TAPER_CUTOFF"] = cu.doubleToString(taperCutoff); replacements["TAPER_C3"] = cu.doubleToString(10/pow(taperCutoff-cutoff, 3.0)); replacements["TAPER_C4"] = cu.doubleToString(15/pow(taperCutoff-cutoff, 4.0)); replacements["TAPER_C5"] = cu.doubleToString(6/pow(taperCutoff-cutoff, 5.0)); bool useCutoff = (force.getNonbondedMethod() != AmoebaVdwForce::NoCutoff); nonbonded->addInteraction(useCutoff, useCutoff, true, force.getCutoffDistance(), exclusions, cu.replaceStrings(CudaAmoebaKernelSources::amoebaVdwForce2, replacements), 0); // Create the other kernels. map<string, string> defines; defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); CUmodule module = cu.createModule(CudaAmoebaKernelSources::amoebaVdwForce1, defines); prepareKernel = cu.getKernel(module, "prepareToComputeForce"); spreadKernel = cu.getKernel(module, "spreadForces"); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaVdwForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { if (!hasInitializedNonbonded) { hasInitializedNonbonded = true; nonbonded->initialize(system); } if (hasAlchemical) { float contextLambda = context.getParameter(AmoebaVdwForce::Lambda()); if (contextLambda != currentVdwLambda) { // Non-blocking copy of vdwLambda to device memory ((float*) vdwLambdaPinnedBuffer)[0] = contextLambda; vdwLambda.upload(vdwLambdaPinnedBuffer, false); currentVdwLambda = contextLambda; } } cu.getPosq().copyTo(tempPosq); cu.getForce().copyTo(tempForces); void* prepareArgs[] = {&cu.getForce().getDevicePointer(), &cu.getPosq().getDevicePointer(), &tempPosq.getDevicePointer(), &bondReductionAtoms.getDevicePointer(), &bondReductionFactors.getDevicePointer()}; cu.executeKernel(prepareKernel, prepareArgs, cu.getPaddedNumAtoms()); nonbonded->prepareInteractions(1); nonbonded->computeInteractions(1, includeForces, includeEnergy); void* spreadArgs[] = {&cu.getForce().getDevicePointer(), &tempForces.getDevicePointer(), &bondReductionAtoms.getDevicePointer(), &bondReductionFactors.getDevicePointer()}; cu.executeKernel(spreadKernel, spreadArgs, cu.getPaddedNumAtoms()); tempPosq.copyTo(cu.getPosq()); tempForces.copyTo(cu.getForce()); double4 box = cu.getPeriodicBoxSize(); return dispersionCoefficient/(box.x*box.y*box.z); } void CudaCalcAmoebaVdwForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaVdwForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumParticles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of particles has changed"); // Record the per-particle parameters. vector<float2> sigmaEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 1)); vector<float> isAlchemicalVec(cu.getPaddedNumAtoms(), 0); vector<int> bondReductionAtomsVec(cu.getPaddedNumAtoms(), 0); vector<float> bondReductionFactorsVec(cu.getPaddedNumAtoms(), 0); for (int i = 0; i < force.getNumParticles(); i++) { int ivIndex; double sigma, epsilon, reductionFactor; bool alchemical; force.getParticleParameters(i, ivIndex, sigma, epsilon, reductionFactor, alchemical); sigmaEpsilonVec[i] = make_float2((float) sigma, (float) epsilon); isAlchemicalVec[i] = (alchemical) ? 1.0f : 0.0f; bondReductionAtomsVec[i] = ivIndex; bondReductionFactorsVec[i] = (float) reductionFactor; } sigmaEpsilon.upload(sigmaEpsilonVec); if (hasAlchemical) isAlchemical.upload(isAlchemicalVec); bondReductionAtoms.upload(bondReductionAtomsVec); bondReductionFactors.upload(bondReductionFactorsVec); if (force.getUseDispersionCorrection()) dispersionCoefficient = AmoebaVdwForceImpl::calcDispersionCorrection(system, force); else dispersionCoefficient = 0.0; cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * AmoebaWcaDispersion * * -------------------------------------------------------------------------- */ class CudaCalcAmoebaWcaDispersionForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const AmoebaWcaDispersionForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double radius1, radius2, epsilon1, epsilon2; force.getParticleParameters(particle1, radius1, epsilon1); force.getParticleParameters(particle2, radius2, epsilon2); return (radius1 == radius2 && epsilon1 == epsilon2); } private: const AmoebaWcaDispersionForce& force; }; CudaCalcAmoebaWcaDispersionForceKernel::CudaCalcAmoebaWcaDispersionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcAmoebaWcaDispersionForceKernel(name, platform), cu(cu), system(system) { } void CudaCalcAmoebaWcaDispersionForceKernel::initialize(const System& system, const AmoebaWcaDispersionForce& force) { int numParticles = system.getNumParticles(); int paddedNumAtoms = cu.getPaddedNumAtoms(); // Record parameters. vector<float2> radiusEpsilonVec(paddedNumAtoms, make_float2(0, 0)); for (int i = 0; i < numParticles; i++) { double radius, epsilon; force.getParticleParameters(i, radius, epsilon); radiusEpsilonVec[i] = make_float2((float) radius, (float) epsilon); } radiusEpsilon.initialize<float2>(cu, paddedNumAtoms, "radiusEpsilon"); radiusEpsilon.upload(radiusEpsilonVec); // Create the kernel. map<string, string> defines; defines["NUM_ATOMS"] = cu.intToString(numParticles); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["THREAD_BLOCK_SIZE"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize()); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["EPSO"] = cu.doubleToString(force.getEpso()); defines["EPSH"] = cu.doubleToString(force.getEpsh()); defines["RMINO"] = cu.doubleToString(force.getRmino()); defines["RMINH"] = cu.doubleToString(force.getRminh()); defines["AWATER"] = cu.doubleToString(force.getAwater()); defines["SHCTD"] = cu.doubleToString(force.getShctd()); defines["M_PI"] = cu.doubleToString(M_PI); CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::amoebaWcaForce, defines); forceKernel = cu.getKernel(module, "computeWCAForce"); totalMaximumDispersionEnergy = AmoebaWcaDispersionForceImpl::getTotalMaximumDispersionEnergy(force); // Add an interaction to the default nonbonded kernel. This doesn't actually do any calculations. It's // just so that CudaNonbondedUtilities will keep track of the tiles. vector<vector<int> > exclusions; cu.getNonbondedUtilities().addInteraction(false, false, false, 1.0, exclusions, "", force.getForceGroup()); cu.addForce(new ForceInfo(force)); } double CudaCalcAmoebaWcaDispersionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); int startTileIndex = nb.getStartTileIndex(); int numTileIndices = nb.getNumTiles(); int numForceThreadBlocks = nb.getNumForceThreadBlocks(); int forceThreadBlockSize = nb.getForceThreadBlockSize(); void* forceArgs[] = {&cu.getForce().getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices, &radiusEpsilon.getDevicePointer()}; cu.executeKernel(forceKernel, forceArgs, numForceThreadBlocks*forceThreadBlockSize, forceThreadBlockSize); return totalMaximumDispersionEnergy; } void CudaCalcAmoebaWcaDispersionForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaWcaDispersionForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumParticles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of particles has changed"); // Record the per-particle parameters. vector<float2> radiusEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 0)); for (int i = 0; i < cu.getNumAtoms(); i++) { double radius, epsilon; force.getParticleParameters(i, radius, epsilon); radiusEpsilonVec[i] = make_float2((float) radius, (float) epsilon); } radiusEpsilon.upload(radiusEpsilonVec); totalMaximumDispersionEnergy = AmoebaWcaDispersionForceImpl::getTotalMaximumDispersionEnergy(force); cu.invalidateMolecules(); } /* -------------------------------------------------------------------------- * * HippoNonbondedForce * * -------------------------------------------------------------------------- */ class CudaCalcHippoNonbondedForceKernel::ForceInfo : public CudaForceInfo { public: ForceInfo(const HippoNonbondedForce& force) : force(force) { } bool areParticlesIdentical(int particle1, int particle2) { double charge1, coreCharge1, alpha1, epsilon1, damping1, c61, pauliK1, pauliQ1, pauliAlpha1, polarizability1; double charge2, coreCharge2, alpha2, epsilon2, damping2, c62, pauliK2, pauliQ2, pauliAlpha2, polarizability2; int axisType1, multipoleZ1, multipoleX1, multipoleY1; int axisType2, multipoleZ2, multipoleX2, multipoleY2; vector<double> dipole1, dipole2, quadrupole1, quadrupole2; force.getParticleParameters(particle1, charge1, dipole1, quadrupole1, coreCharge1, alpha1, epsilon1, damping1, c61, pauliK1, pauliQ1, pauliAlpha1, polarizability1, axisType1, multipoleZ1, multipoleX1, multipoleY1); force.getParticleParameters(particle2, charge2, dipole2, quadrupole2, coreCharge2, alpha2, epsilon2, damping2, c62, pauliK2, pauliQ2, pauliAlpha2, polarizability2, axisType2, multipoleZ2, multipoleX2, multipoleY2); if (charge1 != charge2 || coreCharge1 != coreCharge2 || alpha1 != alpha2 || epsilon1 != epsilon1 || damping1 != damping2 || c61 != c62 || pauliK1 != pauliK2 || pauliQ1 != pauliQ2 || pauliAlpha1 != pauliAlpha2 || polarizability1 != polarizability2 || axisType1 != axisType2) { return false; } for (int i = 0; i < dipole1.size(); ++i) if (dipole1[i] != dipole2[i]) return false; for (int i = 0; i < quadrupole1.size(); ++i) if (quadrupole1[i] != quadrupole2[i]) return false; return true; } int getNumParticleGroups() { return force.getNumExceptions(); } void getParticlesInGroup(int index, vector<int>& particles) { int particle1, particle2; double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale; force.getExceptionParameters(index, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale); particles.resize(2); particles[0] = particle1; particles[1] = particle2; } bool areGroupsIdentical(int group1, int group2) { int particle1, particle2; double multipoleMultipoleScale1, dipoleMultipoleScale1, dipoleDipoleScale1, dispersionScale1, repulsionScale1, chargeTransferScale1; double multipoleMultipoleScale2, dipoleMultipoleScale2, dipoleDipoleScale2, dispersionScale2, repulsionScale2, chargeTransferScale2; force.getExceptionParameters(group1, particle1, particle2, multipoleMultipoleScale1, dipoleMultipoleScale1, dipoleDipoleScale1, dispersionScale1, repulsionScale1, chargeTransferScale1); force.getExceptionParameters(group2, particle1, particle2, multipoleMultipoleScale2, dipoleMultipoleScale2, dipoleDipoleScale2, dispersionScale2, repulsionScale2, chargeTransferScale2); return (multipoleMultipoleScale1 == multipoleMultipoleScale2 && dipoleMultipoleScale1 == dipoleMultipoleScale2 && dipoleDipoleScale1 == dipoleDipoleScale2 && dispersionScale1 == dispersionScale2 && repulsionScale1 == repulsionScale2 && chargeTransferScale1 == chargeTransferScale2); } private: const HippoNonbondedForce& force; }; class CudaCalcHippoNonbondedForceKernel::TorquePostComputation : public CudaContext::ForcePostComputation { public: TorquePostComputation(CudaCalcHippoNonbondedForceKernel& owner) : owner(owner) { } double computeForceAndEnergy(bool includeForces, bool includeEnergy, int groups) { owner.addTorquesToForces(); return 0.0; } private: CudaCalcHippoNonbondedForceKernel& owner; }; CudaCalcHippoNonbondedForceKernel::CudaCalcHippoNonbondedForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) : CalcHippoNonbondedForceKernel(name, platform), cu(cu), system(system), sort(NULL), hasInitializedKernels(false), hasInitializedFFT(false), multipolesAreValid(false) { } CudaCalcHippoNonbondedForceKernel::~CudaCalcHippoNonbondedForceKernel() { cu.setAsCurrent(); if (sort != NULL) delete sort; if (hasInitializedFFT) { cufftDestroy(fftForward); cufftDestroy(fftBackward); cufftDestroy(dfftForward); cufftDestroy(dfftBackward); } } void CudaCalcHippoNonbondedForceKernel::initialize(const System& system, const HippoNonbondedForce& force) { cu.setAsCurrent(); extrapolationCoefficients = force.getExtrapolationCoefficients(); usePME = (force.getNonbondedMethod() == HippoNonbondedForce::PME); // Initialize particle parameters. numParticles = force.getNumParticles(); vector<double> coreChargeVec, valenceChargeVec, alphaVec, epsilonVec, dampingVec, c6Vec, pauliKVec, pauliQVec, pauliAlphaVec, polarizabilityVec; vector<double> localDipolesVec, localQuadrupolesVec; vector<int4> multipoleParticlesVec; vector<vector<int> > exclusions(numParticles); for (int i = 0; i < numParticles; i++) { double charge, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; force.getParticleParameters(i, charge, dipole, quadrupole, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability, axisType, atomZ, atomX, atomY); coreChargeVec.push_back(coreCharge); valenceChargeVec.push_back(charge-coreCharge); alphaVec.push_back(alpha); epsilonVec.push_back(epsilon); dampingVec.push_back(damping); c6Vec.push_back(c6); pauliKVec.push_back(pauliK); pauliQVec.push_back(pauliQ); pauliAlphaVec.push_back(pauliAlpha); polarizabilityVec.push_back(polarizability); multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType)); for (int j = 0; j < 3; j++) localDipolesVec.push_back(dipole[j]); localQuadrupolesVec.push_back(quadrupole[0]); localQuadrupolesVec.push_back(quadrupole[1]); localQuadrupolesVec.push_back(quadrupole[2]); localQuadrupolesVec.push_back(quadrupole[4]); localQuadrupolesVec.push_back(quadrupole[5]); exclusions[i].push_back(i); } int paddedNumAtoms = cu.getPaddedNumAtoms(); for (int i = numParticles; i < paddedNumAtoms; i++) { coreChargeVec.push_back(0); valenceChargeVec.push_back(0); alphaVec.push_back(0); epsilonVec.push_back(0); dampingVec.push_back(0); c6Vec.push_back(0); pauliKVec.push_back(0); pauliQVec.push_back(0); pauliAlphaVec.push_back(0); polarizabilityVec.push_back(0); multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0)); for (int j = 0; j < 3; j++) localDipolesVec.push_back(0); for (int j = 0; j < 5; j++) localQuadrupolesVec.push_back(0); } int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float)); coreCharge.initialize(cu, paddedNumAtoms, elementSize, "coreCharge"); valenceCharge.initialize(cu, paddedNumAtoms, elementSize, "valenceCharge"); alpha.initialize(cu, paddedNumAtoms, elementSize, "alpha"); epsilon.initialize(cu, paddedNumAtoms, elementSize, "epsilon"); damping.initialize(cu, paddedNumAtoms, elementSize, "damping"); c6.initialize(cu, paddedNumAtoms, elementSize, "c6"); pauliK.initialize(cu, paddedNumAtoms, elementSize, "pauliK"); pauliQ.initialize(cu, paddedNumAtoms, elementSize, "pauliQ"); pauliAlpha.initialize(cu, paddedNumAtoms, elementSize, "pauliAlpha"); polarizability.initialize(cu, paddedNumAtoms, elementSize, "polarizability"); multipoleParticles.initialize<int4>(cu, paddedNumAtoms, "multipoleParticles"); localDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "localDipoles"); localQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "localQuadrupoles"); lastPositions.initialize(cu, cu.getPosq().getSize(), cu.getPosq().getElementSize(), "lastPositions"); coreCharge.upload(coreChargeVec, true); valenceCharge.upload(valenceChargeVec, true); alpha.upload(alphaVec, true); epsilon.upload(epsilonVec, true); damping.upload(dampingVec, true); c6.upload(c6Vec, true); pauliK.upload(pauliKVec, true); pauliQ.upload(pauliQVec, true); pauliAlpha.upload(pauliAlphaVec, true); polarizability.upload(polarizabilityVec, true); multipoleParticles.upload(multipoleParticlesVec); localDipoles.upload(localDipolesVec, true); localQuadrupoles.upload(localQuadrupolesVec, true); // Create workspace arrays. labDipoles.initialize(cu, paddedNumAtoms, 3*elementSize, "dipole"); labQuadrupoles[0].initialize(cu, paddedNumAtoms, elementSize, "qXX"); labQuadrupoles[1].initialize(cu, paddedNumAtoms, elementSize, "qXY"); labQuadrupoles[2].initialize(cu, paddedNumAtoms, elementSize, "qXZ"); labQuadrupoles[3].initialize(cu, paddedNumAtoms, elementSize, "qYY"); labQuadrupoles[4].initialize(cu, paddedNumAtoms, elementSize, "qYZ"); fracDipoles.initialize(cu, paddedNumAtoms, 3*elementSize, "fracDipoles"); fracQuadrupoles.initialize(cu, 6*paddedNumAtoms, elementSize, "fracQuadrupoles"); field.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "field"); inducedField.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedField"); torque.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "torque"); inducedDipole.initialize(cu, paddedNumAtoms, 3*elementSize, "inducedDipole"); int numOrders = extrapolationCoefficients.size(); extrapolatedDipole.initialize(cu, 3*numParticles*numOrders, elementSize, "extrapolatedDipole"); extrapolatedPhi.initialize(cu, 10*numParticles*numOrders, elementSize, "extrapolatedPhi"); cu.addAutoclearBuffer(field); cu.addAutoclearBuffer(torque); // Record exceptions and exclusions. vector<double> exceptionScaleVec[6]; vector<int2> exceptionAtomsVec; for (int i = 0; i < force.getNumExceptions(); i++) { int particle1, particle2; double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale; force.getExceptionParameters(i, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale); exclusions[particle1].push_back(particle2); exclusions[particle2].push_back(particle1); if (usePME || multipoleMultipoleScale != 0 || dipoleMultipoleScale != 0 || dipoleDipoleScale != 0 || dispersionScale != 0 || repulsionScale != 0 || chargeTransferScale != 0) { exceptionAtomsVec.push_back(make_int2(particle1, particle2)); exceptionScaleVec[0].push_back(multipoleMultipoleScale); exceptionScaleVec[1].push_back(dipoleMultipoleScale); exceptionScaleVec[2].push_back(dipoleDipoleScale); exceptionScaleVec[3].push_back(dispersionScale); exceptionScaleVec[4].push_back(repulsionScale); exceptionScaleVec[5].push_back(chargeTransferScale); } } if (exceptionAtomsVec.size() > 0) { exceptionAtoms.initialize<int2>(cu, exceptionAtomsVec.size(), "exceptionAtoms"); exceptionAtoms.upload(exceptionAtomsVec); for (int i = 0; i < 6; i++) { exceptionScales[i].initialize(cu, exceptionAtomsVec.size(), elementSize, "exceptionScales"); exceptionScales[i].upload(exceptionScaleVec[i], true); } } // Create the kernels. bool useShuffle = (cu.getComputeCapability() >= 3.0 && !cu.getUseDoublePrecision()); map<string, string> defines; defines["HIPPO"] = "1"; defines["NUM_ATOMS"] = cu.intToString(numParticles); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456); if (useShuffle) defines["USE_SHUFFLE"] = ""; maxExtrapolationOrder = extrapolationCoefficients.size(); defines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder); stringstream coefficients; for (int i = 0; i < maxExtrapolationOrder; i++) { if (i > 0) coefficients << ","; double sum = 0; for (int j = i; j < maxExtrapolationOrder; j++) sum += extrapolationCoefficients[j]; coefficients << cu.doubleToString(sum); } defines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str(); cutoff = force.getCutoffDistance(); if (usePME) { int nx, ny, nz; force.getPMEParameters(pmeAlpha, nx, ny, nz); if (nx == 0 || pmeAlpha == 0) { NonbondedForce nb; nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance()); nb.setCutoffDistance(force.getCutoffDistance()); NonbondedForceImpl::calcPMEParameters(system, nb, pmeAlpha, gridSizeX, gridSizeY, gridSizeZ, false); gridSizeX = CudaFFT3D::findLegalDimension(gridSizeX); gridSizeY = CudaFFT3D::findLegalDimension(gridSizeY); gridSizeZ = CudaFFT3D::findLegalDimension(gridSizeZ); } else { gridSizeX = CudaFFT3D::findLegalDimension(nx); gridSizeY = CudaFFT3D::findLegalDimension(ny); gridSizeZ = CudaFFT3D::findLegalDimension(nz); } force.getDPMEParameters(dpmeAlpha, nx, ny, nz); if (nx == 0 || dpmeAlpha == 0) { NonbondedForce nb; nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance()); nb.setCutoffDistance(force.getCutoffDistance()); NonbondedForceImpl::calcPMEParameters(system, nb, dpmeAlpha, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, true); dispersionGridSizeX = CudaFFT3D::findLegalDimension(dispersionGridSizeX); dispersionGridSizeY = CudaFFT3D::findLegalDimension(dispersionGridSizeY); dispersionGridSizeZ = CudaFFT3D::findLegalDimension(dispersionGridSizeZ); } else { dispersionGridSizeX = CudaFFT3D::findLegalDimension(nx); dispersionGridSizeY = CudaFFT3D::findLegalDimension(ny); dispersionGridSizeZ = CudaFFT3D::findLegalDimension(nz); } defines["EWALD_ALPHA"] = cu.doubleToString(pmeAlpha); defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); defines["USE_EWALD"] = ""; defines["USE_CUTOFF"] = ""; defines["USE_PERIODIC"] = ""; defines["CUTOFF_SQUARED"] = cu.doubleToString(force.getCutoffDistance()*force.getCutoffDistance()); } CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::hippoMultipoles, defines); computeMomentsKernel = cu.getKernel(module, "computeLabFrameMoments"); recordInducedDipolesKernel = cu.getKernel(module, "recordInducedDipoles"); mapTorqueKernel = cu.getKernel(module, "mapTorqueToForce"); module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleInducedField, defines); initExtrapolatedKernel = cu.getKernel(module, "initExtrapolatedDipoles"); iterateExtrapolatedKernel = cu.getKernel(module, "iterateExtrapolatedDipoles"); computeExtrapolatedKernel = cu.getKernel(module, "computeExtrapolatedDipoles"); polarizationEnergyKernel = cu.getKernel(module, "computePolarizationEnergy"); // Set up PME. if (usePME) { // Create the PME kernels. map<string, string> pmeDefines; pmeDefines["HIPPO"] = "1"; pmeDefines["EWALD_ALPHA"] = cu.doubleToString(pmeAlpha); pmeDefines["DISPERSION_EWALD_ALPHA"] = cu.doubleToString(dpmeAlpha); pmeDefines["PME_ORDER"] = cu.intToString(PmeOrder); pmeDefines["NUM_ATOMS"] = cu.intToString(numParticles); pmeDefines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); pmeDefines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456); pmeDefines["GRID_SIZE_X"] = cu.intToString(gridSizeX); pmeDefines["GRID_SIZE_Y"] = cu.intToString(gridSizeY); pmeDefines["GRID_SIZE_Z"] = cu.intToString(gridSizeZ); pmeDefines["M_PI"] = cu.doubleToString(M_PI); pmeDefines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); pmeDefines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str(); pmeDefines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder); CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipolePme, pmeDefines); pmeTransformMultipolesKernel = cu.getKernel(module, "transformMultipolesToFractionalCoordinates"); pmeTransformPotentialKernel = cu.getKernel(module, "transformPotentialToCartesianCoordinates"); pmeSpreadFixedMultipolesKernel = cu.getKernel(module, "gridSpreadFixedMultipoles"); pmeSpreadInducedDipolesKernel = cu.getKernel(module, "gridSpreadInducedDipoles"); pmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge"); pmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution"); pmeFixedPotentialKernel = cu.getKernel(module, "computeFixedPotentialFromGrid"); pmeInducedPotentialKernel = cu.getKernel(module, "computeInducedPotentialFromGrid"); pmeFixedForceKernel = cu.getKernel(module, "computeFixedMultipoleForceAndEnergy"); pmeInducedForceKernel = cu.getKernel(module, "computeInducedDipoleForceAndEnergy"); pmeRecordInducedFieldDipolesKernel = cu.getKernel(module, "recordInducedFieldDipoles"); pmeSelfEnergyKernel = cu.getKernel(module, "calculateSelfEnergyAndTorque"); // Create the dispersion PME kernels. pmeDefines["EWALD_ALPHA"] = cu.doubleToString(dpmeAlpha); pmeDefines["EPSILON_FACTOR"] = "1"; pmeDefines["GRID_SIZE_X"] = cu.intToString(dispersionGridSizeX); pmeDefines["GRID_SIZE_Y"] = cu.intToString(dispersionGridSizeY); pmeDefines["GRID_SIZE_Z"] = cu.intToString(dispersionGridSizeZ); pmeDefines["RECIP_EXP_FACTOR"] = cu.doubleToString(M_PI*M_PI/(dpmeAlpha*dpmeAlpha)); pmeDefines["CHARGE"] = "charges[atom]"; pmeDefines["USE_LJPME"] = "1"; module = cu.createModule(CudaKernelSources::vectorOps+CudaKernelSources::pme, pmeDefines); dpmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge"); dpmeGridIndexKernel = cu.getKernel(module, "findAtomGridIndex"); dpmeSpreadChargeKernel = cu.getKernel(module, "gridSpreadCharge"); dpmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution"); dpmeEvalEnergyKernel = cu.getKernel(module, "gridEvaluateEnergy"); dpmeInterpolateForceKernel = cu.getKernel(module, "gridInterpolateForce"); // Create required data structures. int roundedZSize = PmeOrder*(int) ceil(gridSizeZ/(double) PmeOrder); int gridElements = gridSizeX*gridSizeY*roundedZSize; roundedZSize = PmeOrder*(int) ceil(dispersionGridSizeZ/(double) PmeOrder); gridElements = max(gridElements, dispersionGridSizeX*dispersionGridSizeY*roundedZSize); pmeGrid1.initialize(cu, gridElements, elementSize, "pmeGrid1"); pmeGrid2.initialize(cu, gridElements, 2*elementSize, "pmeGrid2"); cu.addAutoclearBuffer(pmeGrid1); pmeBsplineModuliX.initialize(cu, gridSizeX, elementSize, "pmeBsplineModuliX"); pmeBsplineModuliY.initialize(cu, gridSizeY, elementSize, "pmeBsplineModuliY"); pmeBsplineModuliZ.initialize(cu, gridSizeZ, elementSize, "pmeBsplineModuliZ"); dpmeBsplineModuliX.initialize(cu, dispersionGridSizeX, elementSize, "dpmeBsplineModuliX"); dpmeBsplineModuliY.initialize(cu, dispersionGridSizeY, elementSize, "dpmeBsplineModuliY"); dpmeBsplineModuliZ.initialize(cu, dispersionGridSizeZ, elementSize, "dpmeBsplineModuliZ"); pmePhi.initialize(cu, 20*numParticles, elementSize, "pmePhi"); pmePhidp.initialize(cu, 20*numParticles, elementSize, "pmePhidp"); pmeCphi.initialize(cu, 10*numParticles, elementSize, "pmeCphi"); pmeAtomGridIndex.initialize<int2>(cu, numParticles, "pmeAtomGridIndex"); sort = new CudaSort(cu, new SortTrait(), cu.getNumAtoms()); cufftResult result = cufftPlan3d(&fftForward, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_D2Z : CUFFT_R2C); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); result = cufftPlan3d(&fftBackward, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2D : CUFFT_C2R); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); result = cufftPlan3d(&dfftForward, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, cu.getUseDoublePrecision() ? CUFFT_D2Z : CUFFT_R2C); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); result = cufftPlan3d(&dfftBackward, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2D : CUFFT_C2R); if (result != CUFFT_SUCCESS) throw OpenMMException("Error initializing FFT: "+cu.intToString(result)); hasInitializedFFT = true; // Initialize the B-spline moduli. double data[PmeOrder]; double x = 0.0; data[0] = 1.0 - x; data[1] = x; for (int i = 2; i < PmeOrder; i++) { double denom = 1.0/i; data[i] = x*data[i-1]*denom; for (int j = 1; j < i; j++) data[i-j] = ((x+j)*data[i-j-1] + ((i-j+1)-x)*data[i-j])*denom; data[0] = (1.0-x)*data[0]*denom; } int maxSize = max(max(gridSizeX, gridSizeY), gridSizeZ); vector<double> bsplines_data(maxSize+1, 0.0); for (int i = 2; i <= PmeOrder+1; i++) bsplines_data[i] = data[i-2]; for (int dim = 0; dim < 3; dim++) { int ndata = (dim == 0 ? gridSizeX : dim == 1 ? gridSizeY : gridSizeZ); vector<double> moduli(ndata); // get the modulus of the discrete Fourier transform double factor = 2.0*M_PI/ndata; for (int i = 0; i < ndata; i++) { double sc = 0.0; double ss = 0.0; for (int j = 1; j <= ndata; j++) { double arg = factor*i*(j-1); sc += bsplines_data[j]*cos(arg); ss += bsplines_data[j]*sin(arg); } moduli[i] = sc*sc+ss*ss; } // Fix for exponential Euler spline interpolation failure. double eps = 1.0e-7; if (moduli[0] < eps) moduli[0] = 0.9*moduli[1]; for (int i = 1; i < ndata-1; i++) if (moduli[i] < eps) moduli[i] = 0.9*(moduli[i-1]+moduli[i+1]); if (moduli[ndata-1] < eps) moduli[ndata-1] = 0.9*moduli[ndata-2]; // Compute and apply the optimal zeta coefficient. int jcut = 50; for (int i = 1; i <= ndata; i++) { int k = i - 1; if (i > ndata/2) k = k - ndata; double zeta; if (k == 0) zeta = 1.0; else { double sum1 = 1.0; double sum2 = 1.0; factor = M_PI*k/ndata; for (int j = 1; j <= jcut; j++) { double arg = factor/(factor+M_PI*j); sum1 += pow(arg, PmeOrder); sum2 += pow(arg, 2*PmeOrder); } for (int j = 1; j <= jcut; j++) { double arg = factor/(factor-M_PI*j); sum1 += pow(arg, PmeOrder); sum2 += pow(arg, 2*PmeOrder); } zeta = sum2/sum1; } moduli[i-1] = moduli[i-1]*zeta*zeta; } if (cu.getUseDoublePrecision()) { if (dim == 0) pmeBsplineModuliX.upload(moduli); else if (dim == 1) pmeBsplineModuliY.upload(moduli); else pmeBsplineModuliZ.upload(moduli); } else { vector<float> modulif(ndata); for (int i = 0; i < ndata; i++) modulif[i] = (float) moduli[i]; if (dim == 0) pmeBsplineModuliX.upload(modulif); else if (dim == 1) pmeBsplineModuliY.upload(modulif); else pmeBsplineModuliZ.upload(modulif); } } // Initialize the b-spline moduli for dispersion PME. maxSize = max(max(dispersionGridSizeX, dispersionGridSizeY), dispersionGridSizeZ); vector<double> ddata(PmeOrder); bsplines_data.resize(maxSize); data[PmeOrder-1] = 0.0; data[1] = 0.0; data[0] = 1.0; for (int i = 3; i < PmeOrder; i++) { double div = 1.0/(i-1.0); data[i-1] = 0.0; for (int j = 1; j < (i-1); j++) data[i-j-1] = div*(j*data[i-j-2]+(i-j)*data[i-j-1]); data[0] = div*data[0]; } // Differentiate. ddata[0] = -data[0]; for (int i = 1; i < PmeOrder; i++) ddata[i] = data[i-1]-data[i]; double div = 1.0/(PmeOrder-1); data[PmeOrder-1] = 0.0; for (int i = 1; i < (PmeOrder-1); i++) data[PmeOrder-i-1] = div*(i*data[PmeOrder-i-2]+(PmeOrder-i)*data[PmeOrder-i-1]); data[0] = div*data[0]; for (int i = 0; i < maxSize; i++) bsplines_data[i] = 0.0; for (int i = 1; i <= PmeOrder; i++) bsplines_data[i] = data[i-1]; // Evaluate the actual bspline moduli for X/Y/Z. for(int dim = 0; dim < 3; dim++) { int ndata = (dim == 0 ? dispersionGridSizeX : dim == 1 ? dispersionGridSizeY : dispersionGridSizeZ); vector<double> moduli(ndata); for (int i = 0; i < ndata; i++) { double sc = 0.0; double ss = 0.0; for (int j = 0; j < ndata; j++) { double arg = (2.0*M_PI*i*j)/ndata; sc += bsplines_data[j]*cos(arg); ss += bsplines_data[j]*sin(arg); } moduli[i] = sc*sc+ss*ss; } for (int i = 0; i < ndata; i++) if (moduli[i] < 1.0e-7) moduli[i] = (moduli[i-1]+moduli[i+1])*0.5; if (dim == 0) dpmeBsplineModuliX.upload(moduli, true); else if (dim == 1) dpmeBsplineModuliY.upload(moduli, true); else dpmeBsplineModuliZ.upload(moduli, true); } } // Add the interaction to the default nonbonded kernel. CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); nb.setKernelSource(CudaAmoebaKernelSources::hippoInteractionHeader+CudaAmoebaKernelSources::hippoNonbonded); nb.addArgument(CudaNonbondedUtilities::ParameterInfo("torqueBuffers", "unsigned long long", 1, torque.getElementSize(), torque.getDevicePointer(), false)); nb.addArgument(CudaNonbondedUtilities::ParameterInfo("extrapolatedDipole", "real3", 1, extrapolatedDipole.getElementSize(), extrapolatedDipole.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("coreCharge", "real", 1, coreCharge.getElementSize(), coreCharge.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("valenceCharge", "real", 1, valenceCharge.getElementSize(), valenceCharge.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("alpha", "real", 1, alpha.getElementSize(), alpha.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("epsilon", "real", 1, epsilon.getElementSize(), epsilon.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("damping", "real", 1, damping.getElementSize(), damping.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("c6", "real", 1, c6.getElementSize(), c6.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliK", "real", 1, pauliK.getElementSize(), pauliK.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliQ", "real", 1, pauliQ.getElementSize(), pauliQ.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliAlpha", "real", 1, pauliAlpha.getElementSize(), pauliAlpha.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("dipole", "real", 3, labDipoles.getElementSize(), labDipoles.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("inducedDipole", "real", 3, inducedDipole.getElementSize(), inducedDipole.getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXX", "real", 1, labQuadrupoles[0].getElementSize(), labQuadrupoles[0].getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXY", "real", 1, labQuadrupoles[1].getElementSize(), labQuadrupoles[1].getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXZ", "real", 1, labQuadrupoles[2].getElementSize(), labQuadrupoles[2].getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qYY", "real", 1, labQuadrupoles[3].getElementSize(), labQuadrupoles[3].getDevicePointer())); nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qYZ", "real", 1, labQuadrupoles[4].getElementSize(), labQuadrupoles[4].getDevicePointer())); map<string, string> replacements; replacements["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456); replacements["SWITCH_CUTOFF"] = cu.doubleToString(force.getSwitchingDistance()); replacements["SWITCH_C3"] = cu.doubleToString(10/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 3.0)); replacements["SWITCH_C4"] = cu.doubleToString(15/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 4.0)); replacements["SWITCH_C5"] = cu.doubleToString(6/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 5.0)); replacements["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder); replacements["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str(); replacements["USE_EWALD"] = (usePME ? "1" : "0"); replacements["PME_ALPHA"] = (usePME ? cu.doubleToString(pmeAlpha) : "0"); replacements["DPME_ALPHA"] = (usePME ? cu.doubleToString(dpmeAlpha) : "0"); replacements["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); string interactionSource = cu.replaceStrings(CudaAmoebaKernelSources::hippoInteraction, replacements); nb.addInteraction(usePME, usePME, true, force.getCutoffDistance(), exclusions, interactionSource, force.getForceGroup()); nb.setUsePadding(false); // Create the kernel for computing exceptions. if (exceptionAtoms.isInitialized()) { replacements["COMPUTE_INTERACTION"] = interactionSource; string exceptionsSrc = CudaKernelSources::vectorOps+CudaAmoebaKernelSources::hippoInteractionHeader+CudaAmoebaKernelSources::hippoNonbondedExceptions; exceptionsSrc = cu.replaceStrings(exceptionsSrc, replacements); defines["NUM_EXCEPTIONS"] = cu.intToString(exceptionAtoms.getSize()); module = cu.createModule(exceptionsSrc, defines); computeExceptionsKernel = cu.getKernel(module, "computeNonbondedExceptions"); } cu.addForce(new ForceInfo(force)); cu.addPostComputation(new TorquePostComputation(*this)); } void CudaCalcHippoNonbondedForceKernel::createFieldKernel(const string& interactionSrc, vector<CudaArray*> params, CudaArray& fieldBuffer, CUfunction& kernel, vector<void*>& args, CUfunction& exceptionKernel, vector<void*>& exceptionArgs, CudaArray& exceptionScale) { // Create the kernel source. map<string, string> replacements; replacements["COMPUTE_FIELD"] = interactionSrc; stringstream extraArgs, atomParams, loadLocal1, loadLocal2, load1, load2, load3; for (auto param : params) { string name = param->getName(); string type = (param->getElementSize() == 4 || param->getElementSize() == 8 ? "real" : "real3"); extraArgs << ", const " << type << "* __restrict__ " << name; atomParams << type << " " << name << ";\n"; loadLocal1 << "localData[localAtomIndex]." << name << " = " << name << "1;\n"; loadLocal2 << "localData[localAtomIndex]." << name << " = " << name << "[j];\n"; load1 << type << " " << name << "1 = " << name << "[atom1];\n"; load2 << type << " " << name << "2 = localData[atom2]." << name << ";\n"; load3 << type << " " << name << "2 = " << name << "[atom2];\n"; } replacements["PARAMETER_ARGUMENTS"] = extraArgs.str(); replacements["ATOM_PARAMETER_DATA"] = atomParams.str(); replacements["LOAD_LOCAL_PARAMETERS_FROM_1"] = loadLocal1.str(); replacements["LOAD_LOCAL_PARAMETERS_FROM_GLOBAL"] = loadLocal2.str(); replacements["LOAD_ATOM1_PARAMETERS"] = load1.str(); replacements["LOAD_ATOM2_PARAMETERS"] = load2.str(); replacements["LOAD_ATOM2_PARAMETERS_FROM_GLOBAL"] = load3.str(); string src = cu.replaceStrings(CudaAmoebaKernelSources::hippoComputeField, replacements); // Set defines and create the kernel. map<string, string> defines; if (usePME) { defines["USE_CUTOFF"] = "1"; defines["USE_PERIODIC"] = "1"; defines["USE_EWALD"] = "1"; defines["PME_ALPHA"] = cu.doubleToString(pmeAlpha); defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI)); } defines["WARPS_PER_GROUP"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize()/CudaContext::TileSize); defines["THREAD_BLOCK_SIZE"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize()); defines["CUTOFF"] = cu.doubleToString(cutoff); defines["CUTOFF_SQUARED"] = cu.doubleToString(cutoff*cutoff); defines["NUM_ATOMS"] = cu.intToString(cu.getNumAtoms()); defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms()); defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks()); defines["TILE_SIZE"] = cu.intToString(CudaContext::TileSize); defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(cu.getNonbondedUtilities().getExclusionTiles().getSize()); defines["NUM_EXCEPTIONS"] = cu.intToString(exceptionAtoms.isInitialized() ? exceptionAtoms.getSize() : 0); CUmodule module = cu.createModule(CudaKernelSources::vectorOps+src, defines); kernel = cu.getKernel(module, "computeField"); // Build the list of arguments. CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); args.push_back(&cu.getPosq().getDevicePointer()); args.push_back(&cu.getNonbondedUtilities().getExclusions().getDevicePointer()); args.push_back(&cu.getNonbondedUtilities().getExclusionTiles().getDevicePointer()); args.push_back(&fieldBuffer.getDevicePointer()); if (nb.getUseCutoff()) { args.push_back(&nb.getInteractingTiles().getDevicePointer()); args.push_back(&nb.getInteractionCount().getDevicePointer()); args.push_back(cu.getPeriodicBoxSizePointer()); args.push_back(cu.getInvPeriodicBoxSizePointer()); args.push_back(cu.getPeriodicBoxVecXPointer()); args.push_back(cu.getPeriodicBoxVecYPointer()); args.push_back(cu.getPeriodicBoxVecZPointer()); args.push_back(&maxTiles); args.push_back(&nb.getBlockCenters().getDevicePointer()); args.push_back(&nb.getBlockBoundingBoxes().getDevicePointer()); args.push_back(&nb.getInteractingAtoms().getDevicePointer()); } else args.push_back(&maxTiles); for (auto param : params) args.push_back(&param->getDevicePointer()); // If there are any exceptions, build the kernel and arguments to compute them. if (exceptionAtoms.isInitialized()) { exceptionKernel = cu.getKernel(module, "computeFieldExceptions"); exceptionArgs.push_back(&cu.getPosq().getDevicePointer()); exceptionArgs.push_back(&fieldBuffer.getDevicePointer()); exceptionArgs.push_back(&exceptionAtoms.getDevicePointer()); exceptionArgs.push_back(&exceptionScale.getDevicePointer()); if (nb.getUseCutoff()) { exceptionArgs.push_back(cu.getPeriodicBoxSizePointer()); exceptionArgs.push_back(cu.getInvPeriodicBoxSizePointer()); exceptionArgs.push_back(cu.getPeriodicBoxVecXPointer()); exceptionArgs.push_back(cu.getPeriodicBoxVecYPointer()); exceptionArgs.push_back(cu.getPeriodicBoxVecZPointer()); } for (auto param : params) exceptionArgs.push_back(&param->getDevicePointer()); } } double CudaCalcHippoNonbondedForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); if (!hasInitializedKernels) { hasInitializedKernels = true; // These kernels can't be compiled in initialize(), because the nonbonded utilities object // has not yet been initialized then. maxTiles = (nb.getUseCutoff() ? nb.getInteractingTiles().getSize() : cu.getNumAtomBlocks()*(cu.getNumAtomBlocks()+1)/2); createFieldKernel(CudaAmoebaKernelSources::hippoFixedField, {&coreCharge, &valenceCharge, &alpha, &labDipoles, &labQuadrupoles[0], &labQuadrupoles[1], &labQuadrupoles[2], &labQuadrupoles[3], &labQuadrupoles[4]}, field, fixedFieldKernel, fixedFieldArgs, fixedFieldExceptionKernel, fixedFieldExceptionArgs, exceptionScales[1]); createFieldKernel(CudaAmoebaKernelSources::hippoMutualField, {&alpha, &inducedDipole}, inducedField, mutualFieldKernel, mutualFieldArgs, mutualFieldExceptionKernel, mutualFieldExceptionArgs, exceptionScales[2]); if (exceptionAtoms.isInitialized()) { computeExceptionsArgs.push_back(&cu.getForce().getDevicePointer()); computeExceptionsArgs.push_back(&cu.getEnergyBuffer().getDevicePointer()); computeExceptionsArgs.push_back(&torque.getDevicePointer()); computeExceptionsArgs.push_back(&cu.getPosq().getDevicePointer()); computeExceptionsArgs.push_back(&extrapolatedDipole.getDevicePointer()); computeExceptionsArgs.push_back(&exceptionAtoms.getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[0].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[1].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[2].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[3].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[4].getDevicePointer()); computeExceptionsArgs.push_back(&exceptionScales[5].getDevicePointer()); computeExceptionsArgs.push_back(&coreCharge.getDevicePointer()); computeExceptionsArgs.push_back(&valenceCharge.getDevicePointer()); computeExceptionsArgs.push_back(&alpha.getDevicePointer()); computeExceptionsArgs.push_back(&epsilon.getDevicePointer()); computeExceptionsArgs.push_back(&damping.getDevicePointer()); computeExceptionsArgs.push_back(&c6.getDevicePointer()); computeExceptionsArgs.push_back(&pauliK.getDevicePointer()); computeExceptionsArgs.push_back(&pauliQ.getDevicePointer()); computeExceptionsArgs.push_back(&pauliAlpha.getDevicePointer()); computeExceptionsArgs.push_back(&labDipoles.getDevicePointer()); computeExceptionsArgs.push_back(&inducedDipole.getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[0].getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[1].getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[2].getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[3].getDevicePointer()); computeExceptionsArgs.push_back(&labQuadrupoles[4].getDevicePointer()); computeExceptionsArgs.push_back(&extrapolatedDipole.getDevicePointer()); if (nb.getUseCutoff()) { computeExceptionsArgs.push_back(cu.getPeriodicBoxSizePointer()); computeExceptionsArgs.push_back(cu.getInvPeriodicBoxSizePointer()); computeExceptionsArgs.push_back(cu.getPeriodicBoxVecXPointer()); computeExceptionsArgs.push_back(cu.getPeriodicBoxVecYPointer()); computeExceptionsArgs.push_back(cu.getPeriodicBoxVecZPointer()); } } } // Make sure the arrays for the neighbor list haven't been recreated. if (nb.getUseCutoff()) { if (maxTiles < nb.getInteractingTiles().getSize()) { maxTiles = nb.getInteractingTiles().getSize(); fixedFieldArgs[4] = &nb.getInteractingTiles().getDevicePointer(); fixedFieldArgs[14] = &nb.getInteractingAtoms().getDevicePointer(); mutualFieldArgs[4] = &nb.getInteractingTiles().getDevicePointer(); mutualFieldArgs[14] = &nb.getInteractingAtoms().getDevicePointer(); } } // Compute the lab frame moments. void* computeMomentsArgs[] = {&cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer(), &localDipoles.getDevicePointer(), &localQuadrupoles.getDevicePointer(), &labDipoles.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer()}; cu.executeKernel(computeMomentsKernel, computeMomentsArgs, cu.getNumAtoms()); void* recipBoxVectorPointer[3]; if (usePME) { // Compute reciprocal box vectors. Vec3 boxVectors[3]; cu.getPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]); double determinant = boxVectors[0][0]*boxVectors[1][1]*boxVectors[2][2]; double scale = 1.0/determinant; double3 recipBoxVectors[3]; recipBoxVectors[0] = make_double3(boxVectors[1][1]*boxVectors[2][2]*scale, 0, 0); recipBoxVectors[1] = make_double3(-boxVectors[1][0]*boxVectors[2][2]*scale, boxVectors[0][0]*boxVectors[2][2]*scale, 0); recipBoxVectors[2] = make_double3((boxVectors[1][0]*boxVectors[2][1]-boxVectors[1][1]*boxVectors[2][0])*scale, -boxVectors[0][0]*boxVectors[2][1]*scale, boxVectors[0][0]*boxVectors[1][1]*scale); float3 recipBoxVectorsFloat[3]; if (cu.getUseDoublePrecision()) { recipBoxVectorPointer[0] = &recipBoxVectors[0]; recipBoxVectorPointer[1] = &recipBoxVectors[1]; recipBoxVectorPointer[2] = &recipBoxVectors[2]; } else { recipBoxVectorsFloat[0] = make_float3((float) recipBoxVectors[0].x, 0, 0); recipBoxVectorsFloat[1] = make_float3((float) recipBoxVectors[1].x, (float) recipBoxVectors[1].y, 0); recipBoxVectorsFloat[2] = make_float3((float) recipBoxVectors[2].x, (float) recipBoxVectors[2].y, (float) recipBoxVectors[2].z); recipBoxVectorPointer[0] = &recipBoxVectorsFloat[0]; recipBoxVectorPointer[1] = &recipBoxVectorsFloat[1]; recipBoxVectorPointer[2] = &recipBoxVectorsFloat[2]; } // Reciprocal space calculation for electrostatics. void* pmeTransformMultipolesArgs[] = {&labDipoles.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformMultipolesKernel, pmeTransformMultipolesArgs, cu.getNumAtoms()); void* pmeSpreadFixedMultipolesArgs[] = {&cu.getPosq().getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmeGrid1.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadFixedMultipolesKernel, pmeSpreadFixedMultipolesArgs, cu.getNumAtoms()); if (cu.getUseDoublePrecision()) { void* finishSpreadArgs[] = {&pmeGrid1.getDevicePointer()}; cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid1.getSize()); cufftExecD2Z(fftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer()); } else cufftExecR2C(fftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer()); void* pmeConvolutionArgs[] = {&pmeGrid2.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(), &pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2D(fftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer()); else cufftExecC2R(fftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer()); void* pmeFixedPotentialArgs[] = {&pmeGrid1.getDevicePointer(), &pmePhi.getDevicePointer(), &field.getDevicePointer(), &cu.getPosq().getDevicePointer(), &labDipoles.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeFixedPotentialKernel, pmeFixedPotentialArgs, cu.getNumAtoms()); void* pmeTransformFixedPotentialArgs[] = {&pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformPotentialKernel, pmeTransformFixedPotentialArgs, cu.getNumAtoms()); void* pmeFixedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeFixedForceKernel, pmeFixedForceArgs, cu.getNumAtoms()); // Reciprocal space calculation for dispersion. void* gridIndexArgs[] = {&cu.getPosq().getDevicePointer(), &pmeAtomGridIndex.getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(dpmeGridIndexKernel, gridIndexArgs, cu.getNumAtoms()); sort->sort(pmeAtomGridIndex); cu.clearBuffer(pmeGrid2); void* spreadArgs[] = {&cu.getPosq().getDevicePointer(), &pmeGrid2.getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2], &pmeAtomGridIndex.getDevicePointer(), &c6.getDevicePointer()}; cu.executeKernel(dpmeSpreadChargeKernel, spreadArgs, cu.getNumAtoms(), 128); void* finishSpreadArgs[] = {&pmeGrid2.getDevicePointer(), &pmeGrid1.getDevicePointer()}; cu.executeKernel(dpmeFinishSpreadChargeKernel, finishSpreadArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecD2Z(dfftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer()); else cufftExecR2C(dfftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer()); if (includeEnergy) { void* computeEnergyArgs[] = {&pmeGrid2.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &dpmeBsplineModuliX.getDevicePointer(), &dpmeBsplineModuliY.getDevicePointer(), &dpmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(dpmeEvalEnergyKernel, computeEnergyArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ); } void* convolutionArgs[] = {&pmeGrid2.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &dpmeBsplineModuliX.getDevicePointer(), &dpmeBsplineModuliY.getDevicePointer(), &dpmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(dpmeConvolutionKernel, convolutionArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2D(dfftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer()); else cufftExecC2R(dfftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer()); void* interpolateArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &pmeGrid1.getDevicePointer(), cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2], &pmeAtomGridIndex.getDevicePointer(), &c6.getDevicePointer()}; cu.executeKernel(dpmeInterpolateForceKernel, interpolateArgs, cu.getNumAtoms(), 128); } // Compute the field from fixed multipoles. cu.executeKernel(fixedFieldKernel, &fixedFieldArgs[0], nb.getNumForceThreadBlocks()*nb.getForceThreadBlockSize(), nb.getForceThreadBlockSize()); if (fixedFieldExceptionArgs.size() > 0) cu.executeKernel(fixedFieldExceptionKernel, &fixedFieldExceptionArgs[0], exceptionAtoms.getSize()); // Iterate the induced dipoles. computeExtrapolatedDipoles(recipBoxVectorPointer); // Add the polarization energy. if (includeEnergy) { void* polarizationEnergyArgs[] = {&cu.getEnergyBuffer().getDevicePointer(), &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(polarizationEnergyKernel, polarizationEnergyArgs, cu.getNumAtoms()); } // Compute the forces due to the reciprocal space PME calculation for induced dipoles. if (usePME) { void* pmeTransformInducedPotentialArgs[] = {&pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeTransformPotentialKernel, pmeTransformInducedPotentialArgs, cu.getNumAtoms()); void* pmeInducedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &extrapolatedPhi.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &pmePhi.getDevicePointer(), &pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedForceKernel, pmeInducedForceArgs, cu.getNumAtoms()); void* pmeSelfEnergyArgs[] = {&torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), &labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), &c6.getDevicePointer(), &inducedDipole.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer()}; cu.executeKernel(pmeSelfEnergyKernel, pmeSelfEnergyArgs, cu.getNumAtoms()); } // Compute nonbonded exceptions. if (exceptionAtoms.isInitialized()) cu.executeKernel(computeExceptionsKernel, &computeExceptionsArgs[0], exceptionAtoms.getSize()); // Record the current atom positions so we can tell later if they have changed. cu.getPosq().copyTo(lastPositions); multipolesAreValid = true; return 0.0; } void CudaCalcHippoNonbondedForceKernel::computeInducedField(void** recipBoxVectorPointer, int optOrder) { CudaNonbondedUtilities& nb = cu.getNonbondedUtilities(); cu.clearBuffer(inducedField); cu.executeKernel(mutualFieldKernel, &mutualFieldArgs[0], nb.getNumForceThreadBlocks()*nb.getForceThreadBlockSize(), nb.getForceThreadBlockSize()); if (mutualFieldExceptionArgs.size() > 0) cu.executeKernel(mutualFieldExceptionKernel, &mutualFieldExceptionArgs[0], exceptionAtoms.getSize()); if (usePME) { cu.clearBuffer(pmeGrid1); void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(), &pmeGrid1.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms()); if (cu.getUseDoublePrecision()) { void* finishSpreadArgs[] = {&pmeGrid1.getDevicePointer()}; cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid1.getSize()); cufftExecD2Z(fftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer()); } else cufftExecR2C(fftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer()); void* pmeConvolutionArgs[] = {&pmeGrid2.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(), &pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256); if (cu.getUseDoublePrecision()) cufftExecZ2D(fftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer()); else cufftExecC2R(fftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer()); void* pmeInducedPotentialArgs[] = {&pmeGrid1.getDevicePointer(), &extrapolatedPhi.getDevicePointer(), &optOrder, &pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms()); void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhidp.getDevicePointer(), &inducedField.getDevicePointer(), &inducedDipole.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]}; cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms()); } } void CudaCalcHippoNonbondedForceKernel::computeExtrapolatedDipoles(void** recipBoxVectorPointer) { // Start by storing the direct dipoles as PT0 void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &inducedDipole.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms()); void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer()}; cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize()); // Recursively apply alpha.Tau to the µ_(n) components to generate µ_(n+1), and store the result for (int order = 1; order < maxExtrapolationOrder; ++order) { computeInducedField(recipBoxVectorPointer, order-1); void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(), &polarizability.getDevicePointer()}; cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize()); } // Take a linear combination of the µ_(n) components to form the total dipole void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer()}; cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize()); computeInducedField(recipBoxVectorPointer, maxExtrapolationOrder-1); } void CudaCalcHippoNonbondedForceKernel::addTorquesToForces() { void* mapTorqueArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer()}; cu.executeKernel(mapTorqueKernel, mapTorqueArgs, cu.getNumAtoms()); } void CudaCalcHippoNonbondedForceKernel::getInducedDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double3> d; inducedDipole.download(d); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(d[i].x, d[i].y, d[i].z); } else { vector<float3> d; inducedDipole.download(d); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(d[i].x, d[i].y, d[i].z); } } void CudaCalcHippoNonbondedForceKernel::ensureMultipolesValid(ContextImpl& context) { if (multipolesAreValid) { int numParticles = cu.getNumAtoms(); if (cu.getUseDoublePrecision()) { vector<double4> pos1, pos2; cu.getPosq().download(pos1); lastPositions.download(pos2); for (int i = 0; i < numParticles; i++) if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) { multipolesAreValid = false; break; } } else { vector<float4> pos1, pos2; cu.getPosq().download(pos1); lastPositions.download(pos2); for (int i = 0; i < numParticles; i++) if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) { multipolesAreValid = false; break; } } } if (!multipolesAreValid) context.calcForcesAndEnergy(false, false, -1); } void CudaCalcHippoNonbondedForceKernel::getLabFramePermanentDipoles(ContextImpl& context, vector<Vec3>& dipoles) { ensureMultipolesValid(context); int numParticles = cu.getNumAtoms(); dipoles.resize(numParticles); const vector<int>& order = cu.getAtomIndex(); if (cu.getUseDoublePrecision()) { vector<double3> labDipoleVec; labDipoles.download(labDipoleVec); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(labDipoleVec[i].x, labDipoleVec[i].y, labDipoleVec[i].z); } else { vector<float3> labDipoleVec; labDipoles.download(labDipoleVec); for (int i = 0; i < numParticles; i++) dipoles[order[i]] = Vec3(labDipoleVec[i].x, labDipoleVec[i].y, labDipoleVec[i].z); } } void CudaCalcHippoNonbondedForceKernel::copyParametersToContext(ContextImpl& context, const HippoNonbondedForce& force) { // Make sure the new parameters are acceptable. cu.setAsCurrent(); if (force.getNumParticles() != cu.getNumAtoms()) throw OpenMMException("updateParametersInContext: The number of particles has changed"); // Record the per-particle parameters. vector<double> coreChargeVec, valenceChargeVec, alphaVec, epsilonVec, dampingVec, c6Vec, pauliKVec, pauliQVec, pauliAlphaVec, polarizabilityVec; vector<double> localDipolesVec, localQuadrupolesVec; vector<int4> multipoleParticlesVec; for (int i = 0; i < numParticles; i++) { double charge, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability; int axisType, atomX, atomY, atomZ; vector<double> dipole, quadrupole; force.getParticleParameters(i, charge, dipole, quadrupole, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability, axisType, atomZ, atomX, atomY); coreChargeVec.push_back(coreCharge); valenceChargeVec.push_back(charge-coreCharge); alphaVec.push_back(alpha); epsilonVec.push_back(epsilon); dampingVec.push_back(damping); c6Vec.push_back(c6); pauliKVec.push_back(pauliK); pauliQVec.push_back(pauliQ); pauliAlphaVec.push_back(pauliAlpha); polarizabilityVec.push_back(polarizability); multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType)); for (int j = 0; j < 3; j++) localDipolesVec.push_back(dipole[j]); localQuadrupolesVec.push_back(quadrupole[0]); localQuadrupolesVec.push_back(quadrupole[1]); localQuadrupolesVec.push_back(quadrupole[2]); localQuadrupolesVec.push_back(quadrupole[4]); localQuadrupolesVec.push_back(quadrupole[5]); } int paddedNumAtoms = cu.getPaddedNumAtoms(); for (int i = numParticles; i < paddedNumAtoms; i++) { coreChargeVec.push_back(0); valenceChargeVec.push_back(0); alphaVec.push_back(0); epsilonVec.push_back(0); dampingVec.push_back(0); c6Vec.push_back(0); pauliKVec.push_back(0); pauliQVec.push_back(0); pauliAlphaVec.push_back(0); polarizabilityVec.push_back(0); multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0)); for (int j = 0; j < 3; j++) localDipolesVec.push_back(0); for (int j = 0; j < 5; j++) localQuadrupolesVec.push_back(0); } coreCharge.upload(coreChargeVec, true); valenceCharge.upload(valenceChargeVec, true); alpha.upload(alphaVec, true); epsilon.upload(epsilonVec, true); damping.upload(dampingVec, true); c6.upload(c6Vec, true); pauliK.upload(pauliKVec, true); pauliQ.upload(pauliQVec, true); pauliAlpha.upload(pauliAlphaVec, true); polarizability.upload(polarizabilityVec, true); multipoleParticles.upload(multipoleParticlesVec); localDipoles.upload(localDipolesVec, true); localQuadrupoles.upload(localQuadrupolesVec, true); // Record the per-exception parameters. vector<double> exceptionScaleVec[6]; vector<int2> exceptionAtomsVec; for (int i = 0; i < force.getNumExceptions(); i++) { int particle1, particle2; double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale; force.getExceptionParameters(i, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale); if (usePME || multipoleMultipoleScale != 0 || dipoleMultipoleScale != 0 || dipoleDipoleScale != 0 || dispersionScale != 0 || repulsionScale != 0 || chargeTransferScale != 0) { exceptionAtomsVec.push_back(make_int2(particle1, particle2)); exceptionScaleVec[0].push_back(multipoleMultipoleScale); exceptionScaleVec[1].push_back(dipoleMultipoleScale); exceptionScaleVec[2].push_back(dipoleDipoleScale); exceptionScaleVec[3].push_back(dispersionScale); exceptionScaleVec[4].push_back(repulsionScale); exceptionScaleVec[5].push_back(chargeTransferScale); } } if (exceptionAtomsVec.size() > 0) { if (!exceptionAtoms.isInitialized() || exceptionAtoms.getSize() != exceptionAtomsVec.size()) throw OpenMMException("updateParametersInContext: The number of exceptions has changed"); exceptionAtoms.upload(exceptionAtomsVec); for (int i = 0; i < 6; i++) exceptionScales[i].upload(exceptionScaleVec[i], true); } else if (exceptionAtoms.isInitialized()) throw OpenMMException("updateParametersInContext: The number of exceptions has changed"); cu.invalidateMolecules(); multipolesAreValid = false; } void CudaCalcHippoNonbondedForceKernel::getPMEParameters(double& alpha, int& nx, int& ny, int& nz) const { alpha = pmeAlpha; nx = gridSizeX; ny = gridSizeY; nz = gridSizeZ; } void CudaCalcHippoNonbondedForceKernel::getDPMEParameters(double& alpha, int& nx, int& ny, int& nz) const { alpha = dpmeAlpha; nx = dispersionGridSizeX; ny = dispersionGridSizeY; nz = dispersionGridSizeZ; }
55.747888
202
0.683459
merkys
0825fce6f420b678bc45bde2f99f310fb9efe8d2
2,344
cpp
C++
test/test-v3.cpp
TheodoreDavis/simple-ray-tracer
db0ebbea4f70efb70c67729c0b737de458bce8bd
[ "Apache-2.0" ]
null
null
null
test/test-v3.cpp
TheodoreDavis/simple-ray-tracer
db0ebbea4f70efb70c67729c0b737de458bce8bd
[ "Apache-2.0" ]
1
2021-09-17T02:24:36.000Z
2021-09-17T02:24:36.000Z
test/test-v3.cpp
TheodoreDavis/simple-ray-tracer
db0ebbea4f70efb70c67729c0b737de458bce8bd
[ "Apache-2.0" ]
null
null
null
#include <inc/v3.h> using namespace std; int main() { v3 a = v3(1,2,3); // Test Accessers cout << "Testing Accessors" << endl; cout << a[0] << a[1] << a[2]; cout << " -- Should be 123" << endl; a[0] = 5, a[1] = 5, a[2] = 5; cout << a[0] << a[1] << a[2]; cout << " -- Should be 555" << endl << endl; a[0] = 1, a[1] = 2, a[2] = 3; // Test ostream cout << "Testing ostream" << endl; cout << a; cout << " -- Should be {1,2,3}" << endl << endl; // Test unary operators cout << "Testing Unary Operators" << endl; cout << +a; cout << " -- Should be {1,2,3}" << endl; cout << -a; cout << " -- Should be {-1,-2,-3}" << endl << endl; // Test assignments cout << "Testing Assignments" << endl; a += v3(1,1,1); cout << a; cout << " -- Should be {2,3,4}" << endl; a -= v3(1,2,1); cout << a; cout << " -- Should be {1,1,3}" << endl; a *= v3(1,2,4); cout << a; cout << " -- Should be {1,2,12}" << endl; a /= v3(1,1,4); cout << a; cout << " -- Should be {1,2,3}" << endl; a *= 5; cout << a; cout << " -- Should be {5,10,15}" << endl; a /= 5; cout << a; cout << " -- Should be {1,2,3}" << endl << endl; // Operations cout << "Testing Operations" << endl; cout << a + v3(1,1,1); cout << " -- Should be {2,3,4}" << endl; cout << a - v3(1,2,1); cout << " -- Should be {0,0,2}" << endl; cout << a * v3(1,2,4); cout << " -- Should be {1,4,12}" << endl; cout << a / v3(1,1,4); cout << " -- Should be {1,2,0.75}" << endl; cout << a * 5; cout << " -- Should be {5,10,15}" << endl; cout << a / 5; cout << " -- Should be {0.2,0.4,0.6}" << endl << endl; // Vector Operations cout << "Testing Vector Operations" << endl; v3 b = v3(7,8,9); cout << a.crossProduct(b); cout << " -- Should be {-6,12,-6}" << endl; cout << a.dotProduct(b); cout << " -- Should be 50" << endl; cout << a.magnitude(); cout << " -- Should be 3.7417" << endl; cout << a.magnitudeSquared(); cout << " -- Should be 14" << endl; cout << a.unitVector(); cout << " -- Should be {0.27,0.53,0.80}" << endl << endl; }
24.416667
63
0.426621
TheodoreDavis
0826719ee4014a46f1db0a7b379920f8fb320ed2
6,726
hpp
C++
src/include/index/kmeans.hpp
xinyandai/similarity-search
75dc71abdd7f79094475db734fe55d04358363fc
[ "MIT" ]
16
2018-11-17T00:51:26.000Z
2022-03-10T22:51:56.000Z
src/include/index/kmeans.hpp
xinyandai/similarity-search
75dc71abdd7f79094475db734fe55d04358363fc
[ "MIT" ]
null
null
null
src/include/index/kmeans.hpp
xinyandai/similarity-search
75dc71abdd7f79094475db734fe55d04358363fc
[ "MIT" ]
9
2018-11-14T08:08:32.000Z
2022-01-08T02:42:58.000Z
//////////////////////////////////////////////////////////////////////////////// /// Copyright 2018-present Xinyan DAI<xinyan.dai@outlook.com> /// /// permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to /// deal in the Software without restriction, including without limitation the /// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or /// sell copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions ofthe 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. /// @version 0.1 /// @author Xinyan DAI /// @contact xinyan.dai@outlook.com ////////////////////////////////////////////////////////////////////////////// #pragma once #include <utility> #include <vector> #include <random> #include <unordered_map> #include <boost/progress.hpp> #include "../index.hpp" namespace ss { using std::vector; template<class DataType> class KMeansIndex : public Index<DataType> { protected: /// _center[i] means the i'th center's coordinate vector<vector<DataType > > _centers; /// _points[i] means all points' indexes belong to i'th center /// _points[i][j] means the j'th point's index belongs to i'th center vector<vector<int > > _points; public: explicit KMeansIndex(const parameter& para) : Index<DataType >(para), _centers(para.kmeans_centers), _points(para.kmeans_centers) {} const vector<vector<DataType > > & get_centers() const { return _centers; } const vector<vector<int > > & get_points() const { return _points; } void reset(int num_centers) { this->_centers = vector<vector<DataType > >(num_centers); this->_points = vector<vector<int > >(num_centers); } void set_centers(const vector<vector<DataType > >& centers) { _centers = centers; } void Train(const Matrix<DataType > & data) override { Iterate(Visitor<DataType >(data, 0, data.getDim())); } void Add(const Matrix<DataType > & data) override { Assign(Visitor<DataType >(data, 0, data.getDim())); } void Search(const DataType *query, const std::function<void (int)>& prober) override { const vector<int>& idx = _points[NearestCenter(query, _centers[0].size())]; for (int id : idx) { prober(id); } } const vector<int>& Search(const DataType *query) { return _points[NearestCenter(query, _centers[0].size())]; } /*** * iteratively update centers and re-assign points * @param data */ void Iterate(const Visitor<DataType> & data) { /// initialize centers /// TODO(Xinyan): should initialized randomly for(int i=0; i<_centers.size(); i++) { _centers[i] = vector<DataType >(data[i], data[i]+data.getDim()); } boost::progress_display progress(this->_para.iteration); for (int iter = 0; iter < this->_para.iteration; ++iter, ++progress) { /// Assignment Assign(data); /// UpdateCenter Update(data); /// clear points in each centers for (int c = 0; c<_points.size(); c++) { _points[c].clear(); } } } /** * re-calculate center by averaging points' coordinate */ void Update(const Visitor<DataType> & data) { for (int c = 0; c < _centers.size(); ++c) { vector<DataType > sum(data.getDim(), 0.0f); for (int p = 0; p < _points[c].size(); ++p) { for (int d = 0; d < data.getDim(); ++d) { sum[d] += data[_points[c][p]][d]; /// add up } } for (int d = 0; d < data.getDim(); ++d) { _centers[c][d] = sum[d] / _points[c].size(); /// average } } } /** * assign each point in {@link data} to nearest center */ void Assign(const Visitor<DataType> & data) { vector<int > codes(data.getSize()); #pragma omp parallel for for (int i = 0; i < data.getSize(); ++i) { codes[i] = NearestCenter(data[i], data.getDim()); } for (int i=0; i<data.getSize(); ++i) { _points[codes[i]].push_back(i); } } int NearestCenter(const DataType * vector, int dimension) { DataType min_distance = ss::EuclidDistance(vector, _centers[0].data(), dimension); int nearest_center = 0; for (int c = 1; c < _centers.size(); c++) { DataType distance = Distance(vector, dimension, c); if (distance < min_distance) { min_distance = distance; nearest_center = c; } } return nearest_center; } /** * calculate distances from {@link vector} to each center * @return distances within a vector of pair<distance, center> */ std::vector<std::pair<float, int > > ClusterDistance(const DataType *vector, int dimension) { std::vector<std::pair<float, int>> dist_centers(this->_centers.size()); for (int center = 0; center < (this->_centers.size()); ++center) { DataType distance = Distance(vector, dimension, center); dist_centers[center] = std::make_pair(distance, center); } return dist_centers; } inline DataType Distance(const DataType * vector, int dimension, int center) { return ss::EuclidDistance(vector, _centers[center].data(), dimension); } }; } // namespace ss
36.356757
101
0.545941
xinyandai
082873125198dab2730ad219bcdb9f7f2d9a36c9
2,675
cpp
C++
examples/linux/socket/wind2rrd.cpp
rkuris/n2klib
e465a8f591d135d2e632186309d69a28ff7c9c4e
[ "MIT" ]
null
null
null
examples/linux/socket/wind2rrd.cpp
rkuris/n2klib
e465a8f591d135d2e632186309d69a28ff7c9c4e
[ "MIT" ]
null
null
null
examples/linux/socket/wind2rrd.cpp
rkuris/n2klib
e465a8f591d135d2e632186309d69a28ff7c9c4e
[ "MIT" ]
null
null
null
#include "n2k.h" #include "n2ksocket.h" #include "generated/windData.cc" #include "generated/waterDepth.cc" #include "generated/vesselHeading.cc" #include "pipe.h" #include <stdio.h> #include <signal.h> #include <bits/stdc++.h> void handleWind(const n2k::Message & m); void handleDepth(const n2k::Message & m); void handleHeading(const n2k::Message & m); std::ostream* out = &std::cout; int main(int argc, char *argv[]) { // if you pass any argument, you skip writing to rrdtool if (argc <= 1) { out = new opipestream("rrdtool - >/dev/null"); } signal(SIGINT, exit); n2k::SocketCanReceiver r("can0"); int callbackCount = 0; if (access("wind.rrd", W_OK) || argc > 1) { n2k::Callback cb( n2k::WindData::PGN, n2k::WindData::Type, handleWind); r.addCallback(cb); callbackCount++; } if (access("depth.rrd", W_OK) || argc > 1) { n2k::Callback cb2( n2k::WaterDepth::PGN, n2k::WaterDepth::Type, handleDepth); r.addCallback(cb2); callbackCount++; } if (access("heading.rrd", W_OK) || argc > 1) { n2k::Callback cb3( n2k::VesselHeading::PGN, n2k::VesselHeading::Type, handleHeading); r.addCallback(cb3); callbackCount++; } if (callbackCount == 0) { std::cerr << "No writeable rrd files!\n"; exit(1); } r.applyKernelFilter(); r.run(); } void handleWind(const n2k::Message & m) { static n2k::WindData last; static int repeatCount; const int kRepeatLimit = 10; const n2k::WindData &w = static_cast<const n2k::WindData&>(m); if ((repeatCount++ < kRepeatLimit) && (w.getWindSpeedKnots() == last.getWindSpeedKnots()) && (w.getWindAngleDegrees() == last.getWindAngleDegrees())) { return; } last = w; repeatCount = 0; *out << "update wind.rrd N:" << std::setprecision(2) << w.getWindSpeedKnots() << ":" << w.getWindAngleDegrees() << "\n"; } void handleDepth(const n2k::Message & m) { const n2k::WaterDepth &d = static_cast<const n2k::WindData&>(m); *out << "update depth.rrd N:" << std::setprecision(2) << d.getDepthFeet() << "\n"; } void handleHeading(const n2k::Message & m) { static double last; static int repeatCount; const int kRepeatLimit = 10; const n2k::VesselHeading &h = static_cast<const n2k::WindData&>(m); auto diff = last - h.getHeadingDegrees(); if ((repeatCount++ < kRepeatLimit) && (diff < .1 && diff > -.1)) { return; } last = h.getHeadingDegrees(); repeatCount = 0; *out << "update heading.rrd N:" << std::setprecision(2) << h.getHeadingDegrees() << "\n"; }
26.22549
72
0.603738
rkuris
08288a49dbd45c0cab516ec703b2330289d414a5
184
cpp
C++
NonMoveableSprite.cpp
Loathed94/2D-Game-Engine
1ac8582dabeba02767b44a5db92275c3142486a9
[ "MIT" ]
null
null
null
NonMoveableSprite.cpp
Loathed94/2D-Game-Engine
1ac8582dabeba02767b44a5db92275c3142486a9
[ "MIT" ]
null
null
null
NonMoveableSprite.cpp
Loathed94/2D-Game-Engine
1ac8582dabeba02767b44a5db92275c3142486a9
[ "MIT" ]
null
null
null
//Code written by Christian Neij #include "NonMoveableSprite.h" namespace minMotor { NonMoveableSprite::NonMoveableSprite(int x, int y, int w, int h) :Sprite(x, y, w, h) { } }
26.285714
88
0.695652
Loathed94
082c53a9a1aaffd8593069ae5ec8d82b02a72da8
6,854
cc
C++
src/box/lua/session.cc
Mons/tarantool
35daf23419c88e12758d49c7c60d2cc5f8a00ad1
[ "BSD-2-Clause" ]
null
null
null
src/box/lua/session.cc
Mons/tarantool
35daf23419c88e12758d49c7c60d2cc5f8a00ad1
[ "BSD-2-Clause" ]
null
null
null
src/box/lua/session.cc
Mons/tarantool
35daf23419c88e12758d49c7c60d2cc5f8a00ad1
[ "BSD-2-Clause" ]
null
null
null
/* * 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 <COPYRIGHT HOLDER> ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "session.h" #include "lua/utils.h" #include "lua/trigger.h" #include "box/user.h" #include "scoped_guard.h" extern "C" { #include <lua.h> #include <lauxlib.h> #include <lualib.h> } #include <fiber.h> #include <sio.h> #include "box/session.h" static const char *sessionlib_name = "box.session"; /** * Return a unique monotonic session * identifier. The identifier can be used * to check whether or not a session is alive. * 0 means there is no session (e.g. * a procedure is running in a detached * fiber). */ static int lbox_session_id(struct lua_State *L) { lua_pushnumber(L, current_session()->id); return 1; } /** * Return the id of currently executed request. * Many requests share the same session so this is only * valid at session start. 0 for non-iproto sessions. */ static int lbox_session_sync(struct lua_State *L) { lua_pushnumber(L, current_session()->sync); return 1; } /** * Session user id. * Note: effective user id (current_user()->uid) * may be different in a setuid function. */ static int lbox_session_uid(struct lua_State *L) { /* * Sic: push session user, not the current user, * which may differ inside a setuid function. */ lua_pushnumber(L, current_session()->credentials.uid); return 1; } /** * Session user name. * Note: effective user name may be different in * a setuid function. */ static int lbox_session_user(struct lua_State *L) { struct user *user = user_by_id(current_session()->credentials.uid); if (user) lua_pushstring(L, user->name); else lua_pushnil(L); return 1; } /** Session user id. */ static int lbox_session_su(struct lua_State *L) { int top = lua_gettop(L); if (top < 1) luaL_error(L, "session.su(): bad arguments"); struct session *session = current_session(); if (session == NULL) luaL_error(L, "session.su(): session does not exit"); struct user *user; if (lua_type(L, 1) == LUA_TSTRING) { size_t len; const char *name = lua_tolstring(L, 1, &len); user = user_cache_find_by_name(name, len); } else { user = user_cache_find(lua_tointeger(L, 1)); } struct credentials orig_cr; credentials_copy(&orig_cr, &session->credentials); credentials_init(&session->credentials, user); if (top == 1) return 0; /* su */ /* sudo */ auto scoped_guard = make_scoped_guard([&] { credentials_copy(&session->credentials, &orig_cr); }); lua_call(L, top - 2, LUA_MULTRET); return lua_gettop(L) - 1; } /** * Check whether or not a session exists. */ static int lbox_session_exists(struct lua_State *L) { if (lua_gettop(L) != 1) luaL_error(L, "session.exists(sid): bad arguments"); uint32_t sid = luaL_checkint(L, -1); lua_pushboolean(L, session_find(sid) != NULL); return 1; } /** * Check whether or not a session exists. */ static int lbox_session_fd(struct lua_State *L) { if (lua_gettop(L) != 1) luaL_error(L, "session.fd(sid): bad arguments"); uint32_t sid = luaL_checkint(L, -1); struct session *session = session_find(sid); if (session == NULL) luaL_error(L, "session.fd(): session does not exit"); lua_pushinteger(L, session->fd); return 1; } /** * Pretty print peer name. */ static int lbox_session_peer(struct lua_State *L) { if (lua_gettop(L) > 1) luaL_error(L, "session.peer(sid): bad arguments"); int fd; struct session *session; if (lua_gettop(L) == 1) session = session_find(luaL_checkint(L, 1)); else session = current_session(); if (session == NULL) luaL_error(L, "session.peer(): session does not exit"); fd = session->fd; if (fd < 0) { lua_pushnil(L); /* no associated peer */ return 1; } struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); sio_getpeername(fd, (struct sockaddr *)&addr, &addrlen); lua_pushstring(L, sio_strfaddr((struct sockaddr *)&addr, addrlen)); return 1; } /** * run on_connect|on_disconnect trigger */ static void lbox_session_run_trigger(struct trigger *trigger, void * /* event */) { lua_State *L = lua_newthread(tarantool_L); LuarefGuard coro_guard(tarantool_L); lua_rawgeti(L, LUA_REGISTRYINDEX, (intptr_t) trigger->data); lbox_call(L, 0, 0); } static int lbox_session_on_connect(struct lua_State *L) { return lbox_trigger_reset(L, 2, &session_on_connect, lbox_session_run_trigger); } static int lbox_session_on_disconnect(struct lua_State *L) { return lbox_trigger_reset(L, 2, &session_on_disconnect, lbox_session_run_trigger); } void session_storage_cleanup(int sid) { static int ref = LUA_REFNIL; struct lua_State *L = tarantool_L; int top = lua_gettop(L); if (ref == LUA_REFNIL) { lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); if (!lua_istable(L, -1)) goto exit; lua_getfield(L, -1, "session"); if (!lua_istable(L, -1)) goto exit; lua_getmetatable(L, -1); if (!lua_istable(L, -1)) goto exit; lua_getfield(L, -1, "aggregate_storage"); if (!lua_istable(L, -1)) goto exit; ref = luaL_ref(L, LUA_REGISTRYINDEX); } lua_rawgeti(L, LUA_REGISTRYINDEX, ref); lua_pushnil(L); lua_rawseti(L, -2, sid); exit: lua_settop(L, top); } void box_lua_session_init(struct lua_State *L) { static const struct luaL_reg sessionlib[] = { {"id", lbox_session_id}, {"sync", lbox_session_sync}, {"uid", lbox_session_uid}, {"user", lbox_session_user}, {"su", lbox_session_su}, {"fd", lbox_session_fd}, {"exists", lbox_session_exists}, {"peer", lbox_session_peer}, {"on_connect", lbox_session_on_connect}, {"on_disconnect", lbox_session_on_disconnect}, {NULL, NULL} }; luaL_register_module(L, sessionlib_name, sessionlib); lua_pop(L, 1); }
24.654676
69
0.707616
Mons
082f10948e4ea7c3ff2cfe8a118a4017a325e170
1,839
cpp
C++
server/languages/cxx/source/CodegenManager.cpp
adamrehn/language-toolbox
f86c39784b2a6952719afdd7c3769a6a6b5f2630
[ "MIT" ]
2
2018-12-18T07:53:06.000Z
2020-02-28T11:13:21.000Z
server/languages/cxx/source/CodegenManager.cpp
adamrehn/language-toolbox
f86c39784b2a6952719afdd7c3769a6a6b5f2630
[ "MIT" ]
null
null
null
server/languages/cxx/source/CodegenManager.cpp
adamrehn/language-toolbox
f86c39784b2a6952719afdd7c3769a6a6b5f2630
[ "MIT" ]
null
null
null
#include "CodegenManager.h" #include "TempDirectory.h" #include "Utility.h" #include <boost/process.hpp> namespace process = boost::process; CodegenManager::CodegenManager(const string& templateDir) { this->redirectHeader = Utility::readFile(templateDir + "/redirect.h"); this->redirectCode = Utility::readFile(templateDir + "/redirect.cpp"); this->templateCode = Utility::readFile(templateDir + "/template.cpp"); this->cmakeLists = Utility::readFile(templateDir + "/CMakeLists.txt"); } string CodegenManager::performCodegen(const string& prefixCode, const string& mainCode) { //Create an auto-deleting temporary directory to hold our codegen build TempDirectory tempDir; //Populate the template source code string codegenSource = this->templateCode; codegenSource = Utility::strReplace("//$$__PREFIX_CODE__$$", prefixCode, codegenSource); codegenSource = Utility::strReplace("//$$__MAIN_CODE__$$", mainCode, codegenSource); //Write our template files to the temp directory Utility::writeFile(tempDir.getPath() + "/redirect.h", this->redirectHeader); Utility::writeFile(tempDir.getPath() + "/redirect.cpp", this->redirectCode); Utility::writeFile(tempDir.getPath() + "/template.cpp", codegenSource); Utility::writeFile(tempDir.getPath() + "/CMakeLists.txt", this->cmakeLists); //Attempt to perform codegen auto cmake = process::search_path("cmake"); Utility::execute(tempDir.getPath(), cmake, "."); ProcessOutput output = Utility::execute(tempDir.getPath(), cmake, "--build", ".", "--target", "install"); if (output.code != 0) { throw std::runtime_error("codegen failed with exit code " + std::to_string(output.code) + " and stdout: \"" + output.stdout + "\" and stderr: \"" + output.stderr + "\""); } //Retrieve the generated executable data return Utility::readFile(tempDir.getPath() + "/bin/out"); }
42.767442
172
0.728113
adamrehn
082f53921e10192d7abfdb1ca2b8d18d9607fb94
1,142
cpp
C++
src/RSA.cpp
W-angler/crypto
155f0872fa325897bc55a06dfeba4e61014ee350
[ "MIT" ]
null
null
null
src/RSA.cpp
W-angler/crypto
155f0872fa325897bc55a06dfeba4e61014ee350
[ "MIT" ]
null
null
null
src/RSA.cpp
W-angler/crypto
155f0872fa325897bc55a06dfeba4e61014ee350
[ "MIT" ]
null
null
null
#include "RSA.h" #include "prime.h" const bigint RSA::DEFAULT_E(65537); /** * RSA密钥生成 * * @param bits 密钥长度 * @return 密钥对 */ RSA::KeyPair RSA::generate(size_t bits) { size_t len = (bits + 1) / 2; bigint N; bigint p; bigint q; while (true) { p = prime::generate(len); q = prime::generate(len); N = p * q; if (N.bitLength() == bits) { break; } } auto pSubtractOne = p - bigint::ONE; auto qSubtractOne = q - bigint::ONE; bigint d = DEFAULT_E.modInverse(pSubtractOne * qSubtractOne); PublicKey publicKey(N, DEFAULT_E); // e·dP = 1 (mod (p–1)) // e·dQ = 1 (mod (q–1)) // q·qInv = 1 (mod p) PrivateKey privateKey(N, p, q, d, DEFAULT_E.modInverse(pSubtractOne), DEFAULT_E.modInverse(qSubtractOne), q.modInverse(p)); return KeyPair(privateKey, publicKey); } bigint RSA::encrypt(const bigint &m, const RSA::PublicKey &publicKey) { return m.modPow(publicKey.e, publicKey.n); } bigint RSA::decrypt(const bigint &c, const RSA::PrivateKey &privateKey) { return c.modPow(privateKey.d, privateKey.n); }
25.954545
115
0.596322
W-angler
0830d1f9bf68f1605da7ca3d31d7ae526d01e8e6
856
cpp
C++
codes/cpp/mains/test_gardp.cpp
henriquebecker91/masters
1783c05b6f916cc4eb883df26fd4eb3460f98816
[ "Unlicense" ]
1
2020-05-18T23:01:41.000Z
2020-05-18T23:01:41.000Z
codes/cpp/mains/test_gardp.cpp
henriquebecker91/masters
1783c05b6f916cc4eb883df26fd4eb3460f98816
[ "Unlicense" ]
null
null
null
codes/cpp/mains/test_gardp.cpp
henriquebecker91/masters
1783c05b6f916cc4eb883df26fd4eb3460f98816
[ "Unlicense" ]
2
2017-08-13T15:24:56.000Z
2020-03-06T00:20:48.000Z
#include "gardp.hpp" #include "test_common.hpp" // Execute the dynamic programming algorithm presented at p. 221, Integer // Programming, Robert S. Garfinkel, over a hardcoded set of instances. Used to // check if it is still working after a change. All the instances have only // integers, but we execute the gardp version where the profit values are // stored as doubles to test it. int main(int argc, char** argv) { int exit_code; std::cout << "hbm::benchmark_pyasukp<size_t, size_t, size_t>(&hbm::gardp, argc, argv)" << std::endl; exit_code = hbm::benchmark_pyasukp<size_t, size_t, size_t>(&hbm::gardp, argc, argv); if (exit_code != EXIT_SUCCESS) return exit_code; std::cout << "hbm::benchmark_pyasukp<size_t, double, size_t>(&hbm::gardp)" << std::endl; return hbm::benchmark_pyasukp<size_t, double, size_t>(&hbm::gardp, argc, argv); }
42.8
102
0.721963
henriquebecker91
0832a853640cac788942ef7fa9d02d958306b7cd
1,288
cc
C++
reformat-the-string.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
reformat-the-string.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
reformat-the-string.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <vector> #include <string> #include <cctype> class Solution { public: std::string reformat(std::string s) { if (!s.size()) return ""; int count[2]{}; // digit, alpha for (const auto c : s) count[std::isalpha(c) ? 1 : 0]++; std::string res; if (std::abs(count[0] - count[1]) <= 1) { res.resize(s.size()); int alpha{}, digit{}; if (count[0] < count[1]) { for (int i = 0; i < s.size(); i++) { if (std::isalpha(s[i])) { res[2 * alpha++] = s[i]; } else { res[2 * (digit++) + 1] = s[i]; } } } else { for (int i = 0; i < s.size(); i++) { if (std::isalpha(s[i])) { res[2 * (alpha++) + 1] = s[i]; } else { res[2 * digit++] = s[i]; } } } } return res; } };
24.769231
54
0.270186
ArCan314
08333bcdef125c0cb9ae7a23914aa69d1f9af39c
1,482
cpp
C++
Code/Resource.cpp
JaumeMontagut/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
1
2020-07-09T00:38:40.000Z
2020-07-09T00:38:40.000Z
Code/Resource.cpp
YessicaSD/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
null
null
null
Code/Resource.cpp
YessicaSD/CITM_3_GameEngine
57a85b89a72723ce555a4eec3830e6bf00499de9
[ "MIT" ]
null
null
null
#include "Resource.h" #include "ModuleFileSystem.h" #include "JSONFile.h" #include <stdio.h> const uint Resource::type = std::hash<std::string>()(TO_STRING(Resource)); UID Resource::GetUID() const { return uid; } void Resource::SaveVariable(void * info, char ** data_cursor, size_t bytes) { memcpy(*data_cursor, info, bytes); *data_cursor += bytes; } void Resource::LoadVariable(void* info, char ** data_cursor, size_t bytes) { memcpy(info, *data_cursor, bytes); *data_cursor += bytes; } //INFO: Keeps the resource but deletes all its data bool Resource::ReleaseData() { bool ret = false; return ret; } Resource::Resource() { } //INFO: Called each time a GameObject needs to use this resource //INFO: Only load resource once bool Resource::StartUsingResource() { if (reference_count > 0u) { ++reference_count; } else { if (LoadFileData()) { ++reference_count; } } return reference_count > 0u; } uint Resource::GetReferenceCount() const { return reference_count; } //INFO: Called each time a GameObject stops using this resource //INFO: Unload resource when no GameObject references it bool Resource::StopUsingResource() { bool ret = true; --reference_count; if (reference_count == 0u) { ret = ReleaseData(); } return ret; } void Resource::SaveModifiedDate(JSONFile * meta_file, const char * asset_path) { struct stat file_stat; if (stat(asset_path, &file_stat) == 0) { meta_file->SaveNumber("dateModified", file_stat.st_atime); } }
18.525
78
0.711876
JaumeMontagut