text
string
size
int64
token_count
int64
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* 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/. */ /* Implement shared vtbl methods. */ #include "xptcprivate.h" #include "xptiprivate.h" /* * This is for Windows XP 64-Bit Edition / Server 2003 for AMD64 or later. */ extern "C" nsresult PrepareAndDispatch(nsXPTCStubBase* self, uint32_t methodIndex, uint64_t* args, uint64_t *gprData, double *fprData) { #define PARAM_BUFFER_COUNT 16 // // "this" pointer is first parameter, so parameter count is 3. // #define PARAM_GPR_COUNT 3 #define PARAM_FPR_COUNT 3 nsXPTCMiniVariant paramBuffer[PARAM_BUFFER_COUNT]; nsXPTCMiniVariant* dispatchParams = NULL; const nsXPTMethodInfo* info = NULL; uint8_t paramCount; uint8_t i; nsresult result = NS_ERROR_FAILURE; NS_ASSERTION(self,"no self"); self->mEntry->GetMethodInfo(uint16_t(methodIndex), &info); NS_ASSERTION(info,"no method info"); paramCount = info->GetParamCount(); // // setup variant array pointer // if(paramCount > PARAM_BUFFER_COUNT) dispatchParams = new nsXPTCMiniVariant[paramCount]; else dispatchParams = paramBuffer; NS_ASSERTION(dispatchParams,"no place for params"); uint64_t* ap = args; uint32_t iCount = 0; for(i = 0; i < paramCount; i++) { const nsXPTParamInfo& param = info->GetParam(i); const nsXPTType& type = param.GetType(); nsXPTCMiniVariant* dp = &dispatchParams[i]; if(param.IsOut() || !type.IsArithmetic()) { if (iCount < PARAM_GPR_COUNT) dp->val.p = (void*)gprData[iCount++]; else dp->val.p = (void*)*ap++; continue; } // else switch(type) { case nsXPTType::T_I8: if (iCount < PARAM_GPR_COUNT) dp->val.i8 = (int8_t)gprData[iCount++]; else dp->val.i8 = *((int8_t*)ap++); break; case nsXPTType::T_I16: if (iCount < PARAM_GPR_COUNT) dp->val.i16 = (int16_t)gprData[iCount++]; else dp->val.i16 = *((int16_t*)ap++); break; case nsXPTType::T_I32: if (iCount < PARAM_GPR_COUNT) dp->val.i32 = (int32_t)gprData[iCount++]; else dp->val.i32 = *((int32_t*)ap++); break; case nsXPTType::T_I64: if (iCount < PARAM_GPR_COUNT) dp->val.i64 = (int64_t)gprData[iCount++]; else dp->val.i64 = *((int64_t*)ap++); break; case nsXPTType::T_U8: if (iCount < PARAM_GPR_COUNT) dp->val.u8 = (uint8_t)gprData[iCount++]; else dp->val.u8 = *((uint8_t*)ap++); break; case nsXPTType::T_U16: if (iCount < PARAM_GPR_COUNT) dp->val.u16 = (uint16_t)gprData[iCount++]; else dp->val.u16 = *((uint16_t*)ap++); break; case nsXPTType::T_U32: if (iCount < PARAM_GPR_COUNT) dp->val.u32 = (uint32_t)gprData[iCount++]; else dp->val.u32 = *((uint32_t*)ap++); break; case nsXPTType::T_U64: if (iCount < PARAM_GPR_COUNT) dp->val.u64 = (uint64_t)gprData[iCount++]; else dp->val.u64 = *((uint64_t*)ap++); break; case nsXPTType::T_FLOAT: if (iCount < PARAM_FPR_COUNT) // The value in xmm register is already prepared to // be retrieved as a float. Therefore, we pass the // value verbatim, as a double without conversion. dp->val.d = (double)fprData[iCount++]; else dp->val.f = *((float*)ap++); break; case nsXPTType::T_DOUBLE: if (iCount < PARAM_FPR_COUNT) dp->val.d = (double)fprData[iCount++]; else dp->val.d = *((double*)ap++); break; case nsXPTType::T_BOOL: if (iCount < PARAM_GPR_COUNT) // We need cast to uint8_t to remove garbage on upper 56-bit // at first. dp->val.b = (bool)(uint8_t)gprData[iCount++]; else dp->val.b = *((bool*)ap++); break; case nsXPTType::T_CHAR: if (iCount < PARAM_GPR_COUNT) dp->val.c = (char)gprData[iCount++]; else dp->val.c = *((char*)ap++); break; case nsXPTType::T_WCHAR: if (iCount < PARAM_GPR_COUNT) dp->val.wc = (wchar_t)gprData[iCount++]; else dp->val.wc = *((wchar_t*)ap++); break; default: NS_ERROR("bad type"); break; } } result = self->mOuter->CallMethod((uint16_t)methodIndex, info, dispatchParams); if(dispatchParams != paramBuffer) delete [] dispatchParams; return result; } #define STUB_ENTRY(n) /* defined in the assembly file */ #define SENTINEL_ENTRY(n) \ nsresult nsXPTCStubBase::Sentinel##n() \ { \ NS_ERROR("nsXPTCStubBase::Sentinel called"); \ return NS_ERROR_NOT_IMPLEMENTED; \ } #include "xptcstubsdef.inc" void xptc_dummy() { }
5,619
2,055
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/browser/cast_permission_manager.h" #include "base/callback.h" #include "base/logging.h" #include "content/public/browser/permission_type.h" namespace chromecast { namespace shell { CastPermissionManager::CastPermissionManager() : content::PermissionManager() { } CastPermissionManager::~CastPermissionManager() { } void CastPermissionManager::RequestPermission( content::PermissionType permission, content::RenderFrameHost* render_frame_host, int request_id, const GURL& origin, bool user_gesture, const base::Callback<void(content::PermissionStatus)>& callback) { LOG(INFO) << __FUNCTION__ << ": " << static_cast<int>(permission); callback.Run(content::PermissionStatus::PERMISSION_STATUS_GRANTED); } void CastPermissionManager::CancelPermissionRequest( content::PermissionType permission, content::RenderFrameHost* render_frame_host, int request_id, const GURL& origin) { } void CastPermissionManager::ResetPermission( content::PermissionType permission, const GURL& requesting_origin, const GURL& embedding_origin) { } content::PermissionStatus CastPermissionManager::GetPermissionStatus( content::PermissionType permission, const GURL& requesting_origin, const GURL& embedding_origin) { LOG(INFO) << __FUNCTION__ << ": " << static_cast<int>(permission); return content::PermissionStatus::PERMISSION_STATUS_GRANTED; } void CastPermissionManager::RegisterPermissionUsage( content::PermissionType permission, const GURL& requesting_origin, const GURL& embedding_origin) { } int CastPermissionManager::SubscribePermissionStatusChange( content::PermissionType permission, const GURL& requesting_origin, const GURL& embedding_origin, const base::Callback<void(content::PermissionStatus)>& callback) { return -1; } void CastPermissionManager::UnsubscribePermissionStatusChange( int subscription_id) { } } // namespace shell } // namespace chromecast
2,158
602
// // Created by theppsh on 17-4-13. // #include <iostream> #include <iomanip> #include "src/aes.hpp" #include "src/triple_des.hpp" int main(int argc,char ** args){ /**aes 加密*/ /// 128位全0的秘钥 u_char key_block[]={0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0 }; u_char plain_block[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18, }; u_char cipher_block[16]; AES aes_test(key_block); std::cout<<"********** aes 加密测试 **********"<<std::endl; std::memcpy(cipher_block,plain_block,16); aes_test.Cipher(cipher_block); auto cout_default_flags = std::cout.flags(); for(int i=0;i<16;i++){ std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(cipher_block[i])<<" "; } std::cout.setf(cout_default_flags); std::cout<<std::endl; std::cout<<std::endl; std::cout<<"********** aes 解密测试 **********"<<std::endl; std::memcpy(plain_block,cipher_block,16); aes_test.InvCipher(plain_block); for(int i=0;i<16;i++){ std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(plain_block[i])<<" "; } std::cout<<std::endl; std::cout.setf(cout_default_flags); /// ***aes加密文件测试 *** std::cout<<std::endl; std::cout<<"******** aes 加密文件测试 ********"<<std::endl; std::string plain_txt= "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/plain.txt"; std::string cipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/cipher.txt"; std::string decipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/decipher.txt"; aes_test.CipherFile(plain_txt,cipher_txt); std::cout<<std::endl; std::cout<<"******** 解密文件测试 ********"<<std::endl; aes_test.InvCipherFile(cipher_txt,decipher_txt); [](const std::string & file_path1,const std::string file_path2){ std::fstream f1,f2; f1.open(file_path1); f2.open(file_path2); assert(f1.is_open()); assert(f2.is_open()); f1.seekg(0,std::ios::end); f2.seekg(0,std::ios::end); int f1_size = static_cast<int>(f1.tellg()); int f2_size = static_cast<int>(f2.tellg()); std::shared_ptr<char> f1_file_buffer(new char[f1_size+1]); std::shared_ptr<char> f2_file_buffer(new char[f2_size+1]); f1.seekg(0,std::ios::beg); f2.seekg(0,std::ios::beg); f1.read(f1_file_buffer.get(),f1_size); f2.read(f2_file_buffer.get(),f2_size); f1_file_buffer.get()[f1_size]='\0'; f2_file_buffer.get()[f2_size]='\0'; if(std::strcmp(f1_file_buffer.get(),f2_file_buffer.get())!=0){ std::cout<<"文件加密解密后的文件与原来的文件不一致"<<std::endl; exit(0); }else{ std::cout<<"文件加密解密通过!"<<std::endl; } }(plain_txt,decipher_txt); /// aes 与 des 的加密解密的速度的测试 均加密128位即16个byete的数据 std::cout<<std::endl; std::cout<<"******** ase & 3des ecb加密解密的速度的测试****** "<< std::endl; int enc_times =100000; //加密而次数s // 先测试 des { u_char des_bit_keys[64]; u_char des_sub_keys[16][48]; auto t1= std::chrono::system_clock::now(); for (int _time =0 ; _time < enc_times; _time++){ des::Char8ToBit64(key_block,des_bit_keys); des::DES_MakeSubKeys(des_bit_keys,des_sub_keys); _3_des::_3_DES_EncryptBlock(plain_block,key_block,key_block,key_block,cipher_block); _3_des::_3_DES_EncryptBlock(plain_block+8,key_block,key_block,key_block,cipher_block+8); //des的块是8个字节也就是64位的。。。 _3_des::_3_DES_DecryptBlock(cipher_block,key_block,key_block,key_block,plain_block); _3_des::_3_DES_DecryptBlock(cipher_block+8,key_block,key_block,key_block,plain_block+8); } auto t2 = std::chrono::system_clock::now(); float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f; std::cout<<"加密解密128位数消息"<<enc_times<<"次, 3_des-ecb总共花费了:"<<total_time<<" ms"<<std::endl; std::cout<<"加密解密128位数消息"<<enc_times<<"次, 3_des-ecb平均花费了:"<<total_time/enc_times<<" ms"<<std::endl; } // 再测试aes { auto t1 =std::chrono::system_clock::now(); for(int _time = 0; _time<enc_times;_time++){ aes_test.Cipher(plain_block); memcpy(cipher_block,plain_block,16); aes_test.InvCipher(cipher_block); memcpy(plain_block,cipher_block,16); } auto t2 = std::chrono::system_clock::now(); float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f; std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes总共花费了:"<<total_time<<" ms"<<std::endl; std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes平均花费了:"<<total_time/enc_times<<" ms"<<std::endl; } return 0; }
4,918
2,283
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> st; TreeNode* lastVisited(NULL); while (!st.empty() || root) { if (root) { st.push(root); root = root->left; } else { auto peek = st.top(); if (peek->right && lastVisited != peek->right) root = peek->right; else { res.push_back(peek->val); lastVisited = peek; st.pop(); } } } return res; } };
960
278
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP #define KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP #include "common/buffer.hpp" #include "storage/face/write_batch.hpp" #include "storage/trie/impl/polkadot_trie_db.hpp" namespace kagome::storage::trie { class PolkadotTrieBatch : public face::WriteBatch<common::Buffer, common::Buffer> { enum class Action { PUT, REMOVE }; struct Command { Action action; common::Buffer key{}; // value is unnecessary when action is REMOVE common::Buffer value{}; }; public: explicit PolkadotTrieBatch(PolkadotTrieDb &trie); ~PolkadotTrieBatch() override = default; // value will be copied outcome::result<void> put(const common::Buffer &key, const common::Buffer &value) override; outcome::result<void> put(const common::Buffer &key, common::Buffer &&value) override; outcome::result<void> remove(const common::Buffer &key) override; outcome::result<void> commit() override; void clear() override; bool is_empty() const; private: outcome::result<PolkadotTrieDb::NodePtr> applyPut(PolkadotTrie &trie, const common::Buffer &key, common::Buffer &&value); outcome::result<PolkadotTrieDb::NodePtr> applyRemove(PolkadotTrie &trie, const common::Buffer &key); PolkadotTrieDb &storage_; std::list<Command> commands_; }; } // namespace kagome::storage::trie #endif // KAGOME_CORE_STORAGE_TRIE_IMPL_POLKADOT_TRIE_BATCH_HPP
1,659
587
// Copyright (c) Glyn Matthews 2012, 2013, 2014. // Copyright 2012 Google, Inc. // 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 <gtest/gtest.h> #include <network/uri.hpp> #include "string_utility.hpp" TEST(builder_test, empty_uri_doesnt_throw) { network::uri_builder builder; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, empty_uri) { network::uri_builder builder; network::uri instance(builder); ASSERT_TRUE(instance.empty()); } TEST(builder_test, simple_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, simple_uri) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, simple_uri_has_scheme) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, simple_uri_scheme_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("http", *builder.uri().scheme()); } TEST(builder_test, simple_uri_has_no_user_info) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().user_info()); } TEST(builder_test, simple_uri_has_host) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, simple_uri_host_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, simple_uri_has_no_port) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().port()); } TEST(builder_test, simple_uri_has_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, simple_uri_path_value) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_EQ("/", *builder.uri().path()); } TEST(builder_test, simple_uri_has_no_query) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().query()); } TEST(builder_test, simple_uri_has_no_fragment) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().fragment()); } TEST(builder_test, simple_opaque_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, simple_opaque_uri) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_EQ("mailto:john.doe@example.com", builder.uri()); } TEST(builder_test, simple_opaque_uri_has_scheme) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, simple_opaque_uri_scheme_value) { network::uri_builder builder; builder .scheme("mailto") .path("john.doe@example.com") ; ASSERT_EQ("mailto", *builder.uri().scheme()); } TEST(builder_test, relative_hierarchical_uri_doesnt_throw) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, relative_hierarchical_uri) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com/", builder.uri()); } TEST(builder_test, relative_opaque_uri_doesnt_throw) { network::uri_builder builder; builder .path("john.doe@example.com") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, relative_opaque_uri) { network::uri_builder builder; builder .path("john.doe@example.com") ; ASSERT_EQ("john.doe@example.com", builder.uri()); } TEST(builder_test, full_uri_doesnt_throw) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_NO_THROW(builder.uri()); } TEST(builder_test, full_uri) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("http://user:password@www.example.com:80/path?query#fragment", builder.uri()); } TEST(builder_test, full_uri_has_scheme) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().scheme()); } TEST(builder_test, full_uri_scheme_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("http", *builder.uri().scheme()); } TEST(builder_test, full_uri_has_user_info) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().user_info()); } TEST(builder_test, full_uri_user_info_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("user:password", *builder.uri().user_info()); } TEST(builder_test, full_uri_has_host) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, full_uri_host_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, full_uri_has_port) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().port()); } TEST(builder_test, full_uri_has_path) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, full_uri_path_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("/path", *builder.uri().path()); } TEST(builder_test, full_uri_has_query) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().query()); } TEST(builder_test, full_uri_query_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("query", *builder.uri().query()); } TEST(builder_test, full_uri_has_fragment) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_TRUE(builder.uri().fragment()); } TEST(builder_test, full_uri_fragment_value) { network::uri_builder builder; builder .scheme("http") .user_info("user:password") .host("www.example.com") .port("80") .path("/path") .query("query") .fragment("fragment") ; ASSERT_EQ("fragment", *builder.uri().fragment()); } TEST(builder_test, relative_uri) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com/", builder.uri()); } TEST(builder_test, relative_uri_scheme) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_FALSE(builder.uri().scheme()); } TEST(builder_test, authority) { network::uri_builder builder; builder .scheme("http") .authority("www.example.com:8080") .path("/") ; ASSERT_EQ("http://www.example.com:8080/", builder.uri()); ASSERT_EQ("www.example.com", *builder.uri().host()); ASSERT_EQ("8080", *builder.uri().port()); } TEST(builder_test, relative_uri_has_host) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().host()); } TEST(builder_test, relative_uri_host_value) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("www.example.com", *builder.uri().host()); } TEST(builder_test, relative_uri_has_path) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_TRUE(builder.uri().path()); } TEST(builder_test, relative_uri_path_value) { network::uri_builder builder; builder .host("www.example.com") .path("/") ; ASSERT_EQ("/", *builder.uri().path()); } TEST(builder_test, build_relative_uri_with_path_query_and_fragment) { network::uri_builder builder; builder .path("/path/") .query("key", "value") .fragment("fragment") ; ASSERT_EQ("/path/", *builder.uri().path()); ASSERT_EQ("key=value", *builder.uri().query()); ASSERT_EQ("fragment", *builder.uri().fragment()); } TEST(builder_test, build_uri_with_capital_scheme) { network::uri_builder builder; builder .scheme("HTTP") .host("www.example.com") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_uri_with_capital_host) { network::uri_builder builder; builder .scheme("http") .host("WWW.EXAMPLE.COM") .path("/") ; ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_uri_with_unencoded_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/A path with spaces") ; ASSERT_EQ("http://www.example.com/A%20path%20with%20spaces", builder.uri()); } TEST(builder_test, DISABLED_builder_uri_and_remove_dot_segments_from_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/A/./path/") ; ASSERT_EQ("http://www.example.com/A/path/", builder.uri()); } TEST(builder_test, build_uri_with_qmark_in_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/?/") ; ASSERT_EQ("http://www.example.com/%3F/", builder.uri()); } TEST(builder_test, build_uri_with_hash_in_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/#/") ; ASSERT_EQ("http://www.example.com/%23/", builder.uri()); } TEST(builder_test, DISABLED_build_uri_from_filesystem_path) { network::uri_builder builder; builder .scheme("file") .path(boost::filesystem::path("/path/to/a/file.html")) ; ASSERT_EQ("file:///path/to/a/file.html", builder.uri()); } TEST(builder_test, build_http_uri_from_filesystem_path) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path(boost::filesystem::path("/path/to/a/file.html")) ; ASSERT_EQ("http://www.example.com/path/to/a/file.html", builder.uri()); } TEST(builder_test, DISABLED_build_uri_from_filesystem_path_with_encoded_chars) { network::uri_builder builder; builder .scheme("file") .path(boost::filesystem::path("/path/to/a/file with spaces.html")) ; ASSERT_EQ("file:///path/to/a/file%20with%20spaces.html", builder.uri()); } TEST(builder_test, DISABLED_build_uri_with_encoded_unreserved_characters) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .path("/%7Eglynos/") ; ASSERT_EQ("http://www.example.com/~glynos/", builder.uri()); } TEST(builder_test, simple_port) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .port(8000) .path("/") ; ASSERT_EQ("http://www.example.com:8000/", builder.uri()); } // This seems to work, but I don't want to add the Boost.System // dependency just for this. TEST(builder_test, build_uri_with_ipv4_address) { using namespace boost::asio::ip; network::uri_builder builder; builder .scheme("http") .host(address_v4::loopback()) .path("/") ; ASSERT_EQ("http://127.0.0.1/", builder.uri()); } TEST(builder_test, build_uri_with_ipv6_address) { using namespace boost::asio::ip; network::uri_builder builder; builder .scheme("http") .host(address_v6::loopback()) .path("/") ; ASSERT_EQ("http://[::1]/", builder.uri()); } TEST(builder_test, build_uri_with_query_item) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .query("a", "1") .path("/") ; ASSERT_EQ("http://www.example.com/?a=1", builder.uri()); } TEST(builder_test, build_uri_with_multiple_query_items) { network::uri_builder builder; builder .scheme("http") .host("www.example.com") .query("a", "1") .query("b", "2") .path("/") ; ASSERT_EQ("http://www.example.com/?a=1&b=2", builder.uri()); } //TEST(builder_test, build_uri_with_multiple_query_items_with_int_values) { // network::uri_builder builder; // builder // .scheme("http") // .host("www.example.com") // .query("a", 1) // .query("b", 2) // .path("/") // ; // ASSERT_EQ("http://www.example.com/?a=1&b=2", builder.uri()); //} TEST(builder_test, construct_from_existing_uri) { network::uri instance("http://www.example.com/"); network::uri_builder builder(instance); ASSERT_EQ("http://www.example.com/", builder.uri()); } TEST(builder_test, build_from_existing_uri) { network::uri instance("http://www.example.com/"); network::uri_builder builder(instance); builder.query("a", "1").query("b", "2").fragment("fragment"); ASSERT_EQ("http://www.example.com/?a=1&b=2#fragment", builder.uri()); } TEST(builder_test, authority_port_test) { network::uri_builder builder; builder .scheme("https") .authority("www.example.com") ; ASSERT_EQ("www.example.com", *builder.uri().authority()); } TEST(builder_test, clear_user_info_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_user_info(); ASSERT_EQ("http://www.example.com:80/path?query#fragment", builder.uri()); } TEST(builder_test, clear_port_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_port(); ASSERT_EQ("http://user:password@www.example.com/path?query#fragment", builder.uri()); } TEST(builder_test, clear_path_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_path(); ASSERT_EQ("http://user:password@www.example.com:80?query#fragment", builder.uri()); } TEST(builder_test, clear_query_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_query(); ASSERT_EQ("http://user:password@www.example.com:80/path#fragment", builder.uri()); } TEST(builder_test, clear_fragment_test) { network::uri instance("http://user:password@www.example.com:80/path?query#fragment"); network::uri_builder builder(instance); builder.clear_fragment(); ASSERT_EQ("http://user:password@www.example.com:80/path?query", builder.uri()); } TEST(builder_test, empty_username) { std::string user_info(":"); network::uri_builder builder; builder.scheme("ftp").host("127.0.0.1").user_info(user_info); ASSERT_EQ("ftp://:@127.0.0.1", builder.uri()); } TEST(builder_test, path_should_be_prefixed_with_slash) { std::string path("relative"); network::uri_builder builder; builder.scheme("ftp").host("127.0.0.1").path(path); ASSERT_EQ("ftp://127.0.0.1/relative", builder.uri()); } TEST(builder_test, path_should_be_prefixed_with_slash_2) { network::uri_builder builder; builder .scheme("ftp").host("127.0.0.1").path("noleadingslash/foo.txt"); ASSERT_EQ("/noleadingslash/foo.txt", *builder.uri().path()); }
17,761
6,657
#include <Rcpp.h> using namespace Rcpp; RcppExport SEXP rnorm_manual(SEXP n) { NumericVector out( as<int>(n) ); RNGScope rngScope; out = rnorm(as<int>(n), 0.0, 1.0); return out; }
200
95
// Only for matrix with dimension 2, 4, 8, 16... #ifndef SQUARE_MATRIX_MULTIPLY_RECURSIVE_H #define SQUARE_MATRIX_MULTIPLY_RECURSIVE_H #include <utility> namespace CLRS { template <typename T, std::size_t n> void divide_matrix_4(T (&a)[n][n], T (&b)[n/2][n/2], T (&c)[n/2][n/2], T (&d)[n/2][n/2], T (&e)[n/2][n/2]) { for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = 0; j != n / 2; ++j) b[i][j] = a[i][j]; for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = n / 2; j != n; ++j) c[i][j - n/2] = a[i][j]; for(std::size_t i = n / 2; i != n; ++i) for(std::size_t j = 0; j != n / 2; ++j) d[i - n/2][j] = a[i][j]; for(std::size_t i = n / 2; i != n; ++i) for(std::size_t j = n / 2; j != n; ++j) e[i - n/2][j - n/2] = a[i][j]; } template <typename T, std::size_t n> void combine_matrix_4(T (&a)[n][n], T (&b)[n/2][n/2], T (&c)[n/2][n/2], T (&d)[n/2][n/2], T (&e)[n/2][n/2]) { for(std::size_t i = 0; i != n / 2; ++i) for(std::size_t j = 0; j != n / 2; ++j) { a[i][j] = b[i][j]; a[i][j + n/2] = c[i][j]; a[i + n/2][j] = d[i][j]; a[i + n/2][j + n/2] = e[i][j]; } } template <typename T, std::size_t n> void add_matrix(T (&c)[n][n], T (&a)[n][n], T (&b)[n][n]) { for(std::size_t i = 0; i != n; ++i) for(std::size_t j = 0; j != n; ++j) c[i][j] = a[i][j] + b[i][j]; } template <typename T> void square_matrix_multiply_recursive(T (&a)[1][1], T (&b)[1][1], T (&c)[1][1]) // more specific function template for recursive base case when n equals 1. { c[0][0] = a[0][0] * b[0][0]; } template <typename T, std::size_t n> void square_matrix_multiply_recursive(T (&a)[n][n], T (&b)[n][n], T (&c)[n][n]) { T a00[n/2][n/2]; T a01[n/2][n/2]; T a10[n/2][n/2]; T a11[n/2][n/2]; divide_matrix_4(a, a00, a01, a10, a11); T b00[n/2][n/2]; T b01[n/2][n/2]; T b10[n/2][n/2]; T b11[n/2][n/2]; divide_matrix_4(b, b00, b01, b10, b11); T temp1[n/2][n/2]; T temp2[n/2][n/2]; square_matrix_multiply_recursive(a00, b00, temp1); square_matrix_multiply_recursive(a01, b10, temp2); T c00[n/2][n/2]; add_matrix(c00, temp1, temp2); square_matrix_multiply_recursive(a00, b01, temp1); square_matrix_multiply_recursive(a01, b11, temp2); T c01[n/2][n/2]; add_matrix(c01, temp1, temp2); square_matrix_multiply_recursive(a10, b00, temp1); square_matrix_multiply_recursive(a11, b10, temp2); T c10[n/2][n/2]; add_matrix(c10, temp1, temp2); square_matrix_multiply_recursive(a10, b01, temp1); square_matrix_multiply_recursive(a11, b11, temp2); T c11[n/2][n/2]; add_matrix(c11, temp1, temp2); combine_matrix_4(c, c00, c01, c10, c11); } } #endif
2,807
1,513
#ifndef TOOLS_HPP # define TOOLS_HPP # include <string> # include <vector> # include "client.hpp" # include <list> # include "ircserv.hpp" typedef std::vector<std::string> t_strvect; typedef std::list<Client>::iterator t_citer; /****************************************************/ /* additional tools helping the server (tools.cpp) */ /****************************************************/ t_citer ft_findclientfd(t_citer const &begin, t_citer const &end, int fd); t_citer ft_findnick(t_citer const &begin, t_citer const &end, std::string const &nick); t_server *find_server_by_fd(int fd, IRCserv *serv); Client *find_client_by_nick(std::string const &nick, IRCserv *serv); Client *find_client_by_fd(int fd, IRCserv *serv); Channel *find_channel_by_name(const std::string &name, IRCserv *serv); t_server *find_server_by_mask(std::string const &mask, IRCserv *serv); t_server *find_server_by_name(std::string const &name, IRCserv *serv); Client *find_client_by_user_or_nick_and_host(std::string const &str, IRCserv *serv); Client *find_client_by_info(std::string const &info, IRCserv *serv); t_server *find_server_by_token(std::string const &token, IRCserv *serv); t_service *find_service_by_name(std::string const &name, IRCserv *serv); t_service *find_service_by_fd(int fd, IRCserv *serv); std::string get_servername_by_mask(std::string const &mask, IRCserv *serv); std::string get_servername_by_token(std::string const &token, IRCserv *serv); std::string get_hopcount_by_token(std::string const &token, IRCserv *serv); std::string ft_buildmsg(std::string const &from, std::string const &msgcode, std::string const &to, std::string const &cmd, std::string const &msg); void addtonickhistory(IRCserv *serv, t_citer const client); int nick_forward(IRCserv *serv, Client *client); bool remove_channel(Channel *channel, IRCserv *serv); bool remove_client_by_ptr(Client *ptr, IRCserv *serv); bool remove_client_by_nick(std::string const &nick, IRCserv *serv); void remove_server_by_name(std::string const &servername, IRCserv *serv); void self_cmd_squit(int fd, t_fd &fdref, IRCserv *serv); void self_cmd_quit(int fd, t_fd &fdref, IRCserv *serv, std::string const &reason); void self_service_quit(int fd, t_fd &fdref, IRCserv *serv); /****************************************************/ /* string manipulation functions (stringtools.cpp) */ /****************************************************/ t_strvect ft_splitstring(std::string msg, std::string const &delim); t_strvect ft_splitstring(std::string str, char delim); t_strvect ft_splitstringbyany(std::string msg, std::string const &delim); /** * ft_splitcmdbyspace * splits until the second occurance of ':' symbol * (special for irc msg format) */ t_strvect ft_splitcmdbyspace(std::string msg); std::string strvect_to_string(const t_strvect &split, char delim = ' ', size_t pos = 0, size_t len = std::string::npos); bool match(const char *s1, const char *s2); bool match(std::string const &s1, std::string const &s2); std::string ft_strtoupper(std::string const &str); std::string ft_strtolower(std::string const &str); std::string get_nick_from_info(std::string const &info); std::string get_mask_reply(Channel *channel, Client *client, std::string mode, IRCserv *serv); bool is_valid_mask(std::string mask); bool is_valid_serv_host_mask(std::string mask); // ft_tostring std::string ft_tostring(int val); std::string ft_tostring(long val); std::string ft_tostring(uint val); std::string ft_tostring(ulong val); // ft_sto* int ft_stoi(std::string const &str); long ft_stol(std::string const &str); uint ft_stou(std::string const &str); ulong ft_stoul(std::string const &str); /****************************************************/ /* time related functions (timetools.cpp) */ /****************************************************/ time_t ft_getcompiletime(void); time_t ft_getcurrenttime(void); std::string ft_timetostring(time_t rawtime); #endif
3,996
1,424
// Copyright 2015 The Weave 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 <weave/error.h> #include <gtest/gtest.h> namespace weave { namespace { ErrorPtr GenerateNetworkError() { tracked_objects::Location loc("GenerateNetworkError", "error_unittest.cc", 15, ::tracked_objects::GetProgramCounter()); return Error::Create(loc, "not_found", "Resource not found"); } ErrorPtr GenerateHttpError() { ErrorPtr inner = GenerateNetworkError(); return Error::Create(FROM_HERE, "404", "Not found", std::move(inner)); } } // namespace TEST(Error, Single) { ErrorPtr err = GenerateNetworkError(); EXPECT_EQ("not_found", err->GetCode()); EXPECT_EQ("Resource not found", err->GetMessage()); EXPECT_EQ("GenerateNetworkError", err->GetLocation().function_name); EXPECT_EQ("error_unittest.cc", err->GetLocation().file_name); EXPECT_EQ(15, err->GetLocation().line_number); EXPECT_EQ(nullptr, err->GetInnerError()); EXPECT_TRUE(err->HasError("not_found")); EXPECT_FALSE(err->HasError("404")); EXPECT_FALSE(err->HasError("bar")); } TEST(Error, Nested) { ErrorPtr err = GenerateHttpError(); EXPECT_EQ("404", err->GetCode()); EXPECT_EQ("Not found", err->GetMessage()); EXPECT_NE(nullptr, err->GetInnerError()); EXPECT_TRUE(err->HasError("not_found")); EXPECT_TRUE(err->HasError("404")); EXPECT_FALSE(err->HasError("bar")); } TEST(Error, Clone) { ErrorPtr err = GenerateHttpError(); ErrorPtr clone = err->Clone(); const Error* error1 = err.get(); const Error* error2 = clone.get(); while (error1 && error2) { EXPECT_NE(error1, error2); EXPECT_EQ(error1->GetCode(), error2->GetCode()); EXPECT_EQ(error1->GetMessage(), error2->GetMessage()); EXPECT_EQ(error1->GetLocation().function_name, error2->GetLocation().function_name); EXPECT_EQ(error1->GetLocation().file_name, error2->GetLocation().file_name); EXPECT_EQ(error1->GetLocation().line_number, error2->GetLocation().line_number); error1 = error1->GetInnerError(); error2 = error2->GetInnerError(); } EXPECT_EQ(error1, error2); } } // namespace weave
2,237
782
/* Copyright (c) 2021 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include <folly/Benchmark.h> #include <folly/Format.h> #include <folly/String.h> #include <folly/container/Enumerate.h> #include <folly/init/Init.h> #include <gtest/gtest.h> #include <thrift/lib/cpp/util/EnumUtils.h> #include "common/fs/TempDir.h" #include "mock/MockCluster.h" #include "mock/MockData.h" #include "storage/CommonUtils.h" #include "storage/mutate/UpdateEdgeProcessor.h" #include "storage/test/ChainTestUtils.h" #include "storage/test/QueryTestUtils.h" #include "storage/test/TestUtils.h" #include "storage/transaction/ChainAddEdgesGroupProcessor.h" #include "storage/transaction/ChainAddEdgesProcessorLocal.h" #include "storage/transaction/ChainResumeProcessor.h" #include "storage/transaction/ChainUpdateEdgeProcessorRemote.h" #include "storage/transaction/ConsistUtil.h" namespace nebula { namespace storage { // using Code = ::nebula::cpp2::ErrorCode; constexpr int32_t mockSpaceId = 1; constexpr int32_t mockPartNum = 6; constexpr int32_t mockSpaceVidLen = 32; ChainTestUtils gTestUtil; ChainUpdateEdgeTestHelper helper; TEST(ChainUpdateEdgeTest, updateTest1) { fs::TempDir rootPath("/tmp/UpdateEdgeTest.XXXXXX"); mock::MockCluster cluster; cluster.initStorageKV(rootPath.path()); auto* env = cluster.storageEnv_.get(); auto mClient = MetaClientTestUpdater::makeDefaultMetaClient(); env->metaClient_ = mClient.get(); auto parts = cluster.getTotalParts(); EXPECT_TRUE(QueryTestUtils::mockEdgeData(env, parts, mockSpaceVidLen)); LOG(INFO) << "Test updateTest1..."; auto req = helper.makeDefaultRequest(); env->txnMan_->iClient_ = FakeInternalStorageClient::instance(env); auto reversedRequest = helper.reverseRequest(env, req); auto* proc = new FakeChainUpdateProcessor(env); LOG(INFO) << "proc: " << proc; auto f = proc->getFuture(); proc->process(req); auto resp = std::move(f).get(); EXPECT_TRUE(helper.checkResp2(resp)); EXPECT_TRUE(helper.checkRequestUpdated(env, req)); EXPECT_TRUE(helper.checkRequestUpdated(env, reversedRequest)); EXPECT_TRUE(helper.edgeExist(env, req)); EXPECT_FALSE(helper.primeExist(env, req)); EXPECT_FALSE(helper.doublePrimeExist(env, req)); } TEST(ChainUpdateEdgeTest, updateTest2) { fs::TempDir rootPath("/tmp/UpdateEdgeTest.XXXXXX"); mock::MockCluster cluster; cluster.initStorageKV(rootPath.path()); auto* env = cluster.storageEnv_.get(); auto mClient = MetaClientTestUpdater::makeDefaultMetaClient(); env->metaClient_ = mClient.get(); auto parts = cluster.getTotalParts(); EXPECT_TRUE(QueryTestUtils::mockEdgeData(env, parts, mockSpaceVidLen)); LOG(INFO) << "Test UpdateEdgeRequest..."; auto goodRequest = helper.makeDefaultRequest(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_FALSE(helper.primeExist(env, goodRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, goodRequest)); auto badRequest = helper.makeInvalidRequest(); auto* proc = new FakeChainUpdateProcessor(env); auto f = proc->getFuture(); proc->rcProcessRemote = Code::E_KEY_NOT_FOUND; proc->process(badRequest); auto resp = std::move(f).get(); EXPECT_EQ(1, (*resp.result_ref()).failed_parts.size()); EXPECT_FALSE(helper.checkResp2(resp)); EXPECT_FALSE(helper.edgeExist(env, badRequest)); EXPECT_FALSE(helper.primeExist(env, badRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, badRequest)); } TEST(ChainUpdateEdgeTest, updateTest3) { fs::TempDir rootPath("/tmp/UpdateEdgeTest.XXXXXX"); mock::MockCluster cluster; cluster.initStorageKV(rootPath.path()); auto* env = cluster.storageEnv_.get(); auto mClient = MetaClientTestUpdater::makeDefaultMetaClient(); env->metaClient_ = mClient.get(); auto parts = cluster.getTotalParts(); EXPECT_TRUE(QueryTestUtils::mockEdgeData(env, parts, mockSpaceVidLen)); LOG(INFO) << "Test UpdateEdgeRequest..."; auto goodRequest = helper.makeDefaultRequest(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_FALSE(helper.primeExist(env, goodRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, goodRequest)); auto* proc = new FakeChainUpdateProcessor(env); auto f = proc->getFuture(); proc->rcProcessRemote = Code::SUCCEEDED; proc->rcProcessLocal = Code::SUCCEEDED; proc->process(goodRequest); auto resp = std::move(f).get(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_TRUE(helper.primeExist(env, goodRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, goodRequest)); } TEST(ChainUpdateEdgeTest, updateTest4) { fs::TempDir rootPath("/tmp/UpdateEdgeTest.XXXXXX"); mock::MockCluster cluster; cluster.initStorageKV(rootPath.path()); auto* env = cluster.storageEnv_.get(); auto mClient = MetaClientTestUpdater::makeDefaultMetaClient(); env->metaClient_ = mClient.get(); auto parts = cluster.getTotalParts(); EXPECT_TRUE(QueryTestUtils::mockEdgeData(env, parts, mockSpaceVidLen)); LOG(INFO) << "Test UpdateEdgeRequest..."; auto goodRequest = helper.makeDefaultRequest(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_FALSE(helper.primeExist(env, goodRequest)); EXPECT_FALSE(helper.doublePrimeExist(env, goodRequest)); auto* proc = new FakeChainUpdateProcessor(env); auto f = proc->getFuture(); proc->rcProcessRemote = Code::E_RPC_FAILURE; proc->process(goodRequest); auto resp = std::move(f).get(); EXPECT_TRUE(helper.edgeExist(env, goodRequest)); EXPECT_FALSE(helper.primeExist(env, goodRequest)); EXPECT_TRUE(helper.doublePrimeExist(env, goodRequest)); } } // namespace storage } // namespace nebula int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); folly::init(&argc, &argv, false); google::SetStderrLogging(google::INFO); return RUN_ALL_TESTS(); } // ***** Test Plan ***** /** * @brief updateTest1 (update a normal edge will succeed) * previous update * prepareLocal succeed succeed * processRemote succeed succeed * processLocal succeed succeed * expect: edge true * edge prime false * double prime false * prop changed true */ /** * @brief updateTest2 (update non-exist edge will fail) * previous update * prepareLocal failed succeed * processRemote skip succeed * processLocal failed succeed * expect: edge false * edge prime false * double prime false * prop changed true */ /** * @brief updateTest3 (remote update failed will not change anything) * previous update * prepareLocal succeed succeed * processRemote skip failed * processLocal skip failed * expect: edge true * edge prime true * double prime false * prop changed false */ /** * @brief updateTest4 (remote update outdate will add double prime) * previous update * prepareLocal succeed succeed * processRemote skip outdate * processLocal skip succeed * expect: edge true * edge prime false * double prime true * prop changed false */ // /** // * @brief updateTest5 (update1 + resume) // * previous update // * prepareLocal succeed succeed // * processRemote skip succeed // * processLocal succeed succeed // * expect: edge true // * edge prime false // * double prime false // * prop changed true // */ // /** // * @brief updateTest6 (update2 + resume) // * previous update // * prepareLocal failed succeed // * processRemote skip succeed // * processLocal failed succeed // * expect: edge false // * edge prime false // * double prime false // * prop changed true // */ // /** // * @brief updateTest7 (updateTest3 + resume) // * previous resume // * prepareLocal succeed succeed // * processRemote skip failed // * processLocal skip failed // * expect: edge true // * edge prime true // * double prime false // * prop changed false // */ // /** // * @brief updateTest8 // * previous resume // * prepareLocal succeed succeed // * processRemote skip outdate // * processLocal skip succeed // * expect: edge true // * edge prime false // * double prime true // * prop changed false // */ // ***** End Test Plan *****
8,856
2,775
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "pxr/base/gf/matrix4d.h" #include "pxr/base/gf/rotation.h" #include "pxr/base/gf/transform.h" #include "pxr/base/gf/vec3d.h" #include "pxr/base/tf/pyUtils.h" #include "pxr/base/tf/wrapTypeHelpers.h" #include <boost/python/args.hpp> #include <boost/python/class.hpp> #include <boost/python/copy_const_reference.hpp> #include <boost/python/init.hpp> #include <boost/python/operators.hpp> #include <boost/python/return_arg.hpp> #include <string> using std::string; using std::vector; using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE namespace { static GfVec3d _NoTranslation() { return GfVec3d(0,0,0); } static GfVec3d _IdentityScale() { return GfVec3d(1,1,1); } static GfRotation _NoRotation() { return GfRotation( GfVec3d::XAxis(), 0.0 ); } static string _Repr(GfTransform const &self) { string prefix = TF_PY_REPR_PREFIX + "Transform("; string indent(prefix.size(), ' '); // Use keyword args for clarity. // Only use args that do not match the defaults. vector<string> kwargs; if (self.GetTranslation() != _NoTranslation()) kwargs.push_back( "translation = " + TfPyRepr(self.GetTranslation()) ); if (self.GetRotation() != _NoRotation()) kwargs.push_back( "rotation = " + TfPyRepr(self.GetRotation()) ); if (self.GetScale() != _IdentityScale()) kwargs.push_back( "scale = " + TfPyRepr(self.GetScale()) ); if (self.GetPivotPosition() != _NoTranslation()) kwargs.push_back( "pivotPosition = " + TfPyRepr(self.GetPivotPosition()) ); if (self.GetPivotOrientation() != _NoRotation()) kwargs.push_back( "pivotOrientation = " + TfPyRepr(self.GetPivotOrientation()) ); return prefix + TfStringJoin(kwargs, string(", \n" + indent).c_str()) + ")"; } } // anonymous namespace void wrapTransform() { typedef GfTransform This; class_<This>( "Transform", init<>() ) .def(init<const GfVec3d&, const GfRotation&, const GfVec3d&, const GfVec3d&, const GfRotation&> ((args("translation") = _NoTranslation(), args("rotation") = _NoRotation(), args("scale") = _IdentityScale(), args("pivotPosition") = _NoTranslation(), args("pivotOrientation") = _NoRotation()), "Initializer used by 3x code.")) // This is the constructor used by 2x code. Leave the initial // arguments as non-default to force the user to provide enough // values to indicate her intentions. .def(init<const GfVec3d &, const GfRotation &, const GfRotation&, const GfVec3d &, const GfVec3d &> ((args("scale"), args("pivotOrientation"), args("rotation"), args("pivotPosition"), args("translation")), "Initializer used by old 2x code. (Deprecated)")) .def(init<const GfMatrix4d &>()) .def( TfTypePythonClass() ) .def( "Set", (This & (This::*)( const GfVec3d &, const GfRotation &, const GfVec3d &, const GfVec3d &, const GfRotation & ))( &This::Set ), return_self<>(), (args("translation") = _NoTranslation(), args("rotation") = _NoRotation(), args("scale") = _IdentityScale(), args("pivotPosition") = _NoTranslation(), args("pivotOrientation") = _NoRotation())) .def( "Set", (This & (This::*)( const GfVec3d &, const GfRotation &, const GfRotation &, const GfVec3d &, const GfVec3d &))&This::Set, return_self<>(), (args("scale"), args("pivotOrientation"), args("rotation"), args("pivotPosition"), args("translation")), "Set method used by old 2x code. (Deprecated)") .def( "SetMatrix", &This::SetMatrix, return_self<>() ) .def( "GetMatrix", &This::GetMatrix ) .def( "SetIdentity", &This::SetIdentity, return_self<>() ) .add_property( "translation", make_function (&This::GetTranslation, return_value_policy<return_by_value>()), &This::SetTranslation ) .add_property( "rotation", make_function (&This::GetRotation, return_value_policy<return_by_value>()), &This::SetRotation ) .add_property( "scale", make_function (&This::GetScale, return_value_policy<return_by_value>()), &This::SetScale ) .add_property( "pivotPosition", make_function (&This::GetPivotPosition, return_value_policy<return_by_value>()), &This::SetPivotPosition ) .add_property( "pivotOrientation", make_function (&This::GetPivotOrientation, return_value_policy<return_by_value>()), &This::SetPivotOrientation ) .def("GetTranslation", &This::GetTranslation, return_value_policy<return_by_value>()) .def("SetTranslation", &This::SetTranslation ) .def("GetRotation", &This::GetRotation, return_value_policy<return_by_value>()) .def("SetRotation", &This::SetRotation) .def("GetScale", &This::GetScale, return_value_policy<return_by_value>()) .def("SetScale", &This::SetScale ) .def("GetPivotPosition", &This::GetPivotPosition, return_value_policy<return_by_value>()) .def("SetPivotPosition", &This::SetPivotPosition ) .def("GetPivotOrientation", &This::GetPivotOrientation, return_value_policy<return_by_value>()) .def("SetPivotOrientation", &This::SetPivotOrientation ) .def( str(self) ) .def( self == self ) .def( self != self ) .def( self *= self ) .def( self * self ) .def("__repr__", _Repr) ; }
7,451
2,230
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * * Copyright (C) 2000-2015, International Business Machines * Corporation and others. All Rights Reserved. * ******************************************************************************* * * File reslist.cpp * * Modification History: * * Date Name Description * 02/21/00 weiv Creation. ******************************************************************************* */ // Safer use of UnicodeString. #ifndef UNISTR_FROM_CHAR_EXPLICIT # define UNISTR_FROM_CHAR_EXPLICIT explicit #endif // Less important, but still a good idea. #ifndef UNISTR_FROM_STRING_EXPLICIT # define UNISTR_FROM_STRING_EXPLICIT explicit #endif #include <assert.h> #include <stdio.h> #include "unicode/localpointer.h" #include "reslist.h" #include "unewdata.h" #include "unicode/ures.h" #include "unicode/putil.h" #include "errmsg.h" #include "uarrsort.h" #include "uelement.h" #include "uhash.h" #include "uinvchar.h" #include "ustr_imp.h" #include "unicode/utf16.h" /* * Align binary data at a 16-byte offset from the start of the resource bundle, * to be safe for any data type it may contain. */ #define BIN_ALIGNMENT 16 // This numeric constant must be at least 1. // If StringResource.fNumUnitsSaved == 0 then the string occurs only once, // and it makes no sense to move it to the pool bundle. // The larger the threshold for fNumUnitsSaved // the smaller the savings, and the smaller the pool bundle. // We trade some total size reduction to reduce the pool bundle a bit, // so that one can reasonably save data size by // removing bundle files without rebuilding the pool bundle. // This can also help to keep the pool and total (pool+local) string indexes // within 16 bits, that is, within range of Table16 and Array16 containers. #ifndef GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING # define GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING 10 #endif U_NAMESPACE_USE static UBool gIncludeCopyright = FALSE; static UBool gUsePoolBundle = FALSE; static UBool gIsDefaultFormatVersion = TRUE; static int32_t gFormatVersion = 3; /* How do we store string values? */ enum { STRINGS_UTF16_V1, /* formatVersion 1: int length + UChars + NUL + padding to 4 bytes */ STRINGS_UTF16_V2 /* formatVersion 2 & up: optional length in 1..3 UChars + UChars + NUL */ }; static const int32_t MAX_IMPLICIT_STRING_LENGTH = 40; /* do not store the length explicitly for such strings */ static const ResFile kNoPoolBundle; /* * res_none() returns the address of kNoResource, * for use in non-error cases when no resource is to be added to the bundle. * (NULL is used in error cases.) */ static SResource kNoResource; // TODO: const static UDataInfo dataInfo= { sizeof(UDataInfo), 0, U_IS_BIG_ENDIAN, U_CHARSET_FAMILY, sizeof(UChar), 0, {0x52, 0x65, 0x73, 0x42}, /* dataFormat="ResB" */ {1, 3, 0, 0}, /* formatVersion */ {1, 4, 0, 0} /* dataVersion take a look at version inside parsed resb*/ }; static const UVersionInfo gFormatVersions[4] = { /* indexed by a major-formatVersion integer */ { 0, 0, 0, 0 }, { 1, 3, 0, 0 }, { 2, 0, 0, 0 }, { 3, 0, 0, 0 } }; // Remember to update genrb.h GENRB_VERSION when changing the data format. // (Or maybe we should remove GENRB_VERSION and report the ICU version number?) static uint8_t calcPadding(uint32_t size) { /* returns space we need to pad */ return (uint8_t) ((size % sizeof(uint32_t)) ? (sizeof(uint32_t) - (size % sizeof(uint32_t))) : 0); } void setIncludeCopyright(UBool val){ gIncludeCopyright=val; } UBool getIncludeCopyright(void){ return gIncludeCopyright; } void setFormatVersion(int32_t formatVersion) { gIsDefaultFormatVersion = FALSE; gFormatVersion = formatVersion; } int32_t getFormatVersion() { return gFormatVersion; } void setUsePoolBundle(UBool use) { gUsePoolBundle = use; } // TODO: return const pointer, or find another way to express "none" struct SResource* res_none() { return &kNoResource; } SResource::SResource() : fType(URES_NONE), fWritten(FALSE), fRes(RES_BOGUS), fRes16(-1), fKey(-1), fKey16(-1), line(0), fNext(NULL) { ustr_init(&fComment); } SResource::SResource(SRBRoot *bundle, const char *tag, int8_t type, const UString* comment, UErrorCode &errorCode) : fType(type), fWritten(FALSE), fRes(RES_BOGUS), fRes16(-1), fKey(bundle != NULL ? bundle->addTag(tag, errorCode) : -1), fKey16(-1), line(0), fNext(NULL) { ustr_init(&fComment); if(comment != NULL) { ustr_cpy(&fComment, comment, &errorCode); } } SResource::~SResource() { ustr_deinit(&fComment); } ContainerResource::~ContainerResource() { SResource *current = fFirst; while (current != NULL) { SResource *next = current->fNext; delete current; current = next; } } TableResource::~TableResource() {} // TODO: clarify that containers adopt new items, even in error cases; use LocalPointer void TableResource::add(SResource *res, int linenumber, UErrorCode &errorCode) { if (U_FAILURE(errorCode) || res == NULL || res == &kNoResource) { return; } /* remember this linenumber to report to the user if there is a duplicate key */ res->line = linenumber; /* here we need to traverse the list */ ++fCount; /* is the list still empty? */ if (fFirst == NULL) { fFirst = res; res->fNext = NULL; return; } const char *resKeyString = fRoot->fKeys + res->fKey; SResource *current = fFirst; SResource *prev = NULL; while (current != NULL) { const char *currentKeyString = fRoot->fKeys + current->fKey; int diff; /* * formatVersion 1: compare key strings in native-charset order * formatVersion 2 and up: compare key strings in ASCII order */ if (gFormatVersion == 1 || U_CHARSET_FAMILY == U_ASCII_FAMILY) { diff = uprv_strcmp(currentKeyString, resKeyString); } else { diff = uprv_compareInvCharsAsAscii(currentKeyString, resKeyString); } if (diff < 0) { prev = current; current = current->fNext; } else if (diff > 0) { /* we're either in front of the list, or in the middle */ if (prev == NULL) { /* front of the list */ fFirst = res; } else { /* middle of the list */ prev->fNext = res; } res->fNext = current; return; } else { /* Key already exists! ERROR! */ error(linenumber, "duplicate key '%s' in table, first appeared at line %d", currentKeyString, current->line); errorCode = U_UNSUPPORTED_ERROR; return; } } /* end of list */ prev->fNext = res; res->fNext = NULL; } ArrayResource::~ArrayResource() {} void ArrayResource::add(SResource *res) { if (res != NULL && res != &kNoResource) { if (fFirst == NULL) { fFirst = res; } else { fLast->fNext = res; } fLast = res; ++fCount; } } PseudoListResource::~PseudoListResource() {} void PseudoListResource::add(SResource *res) { if (res != NULL && res != &kNoResource) { res->fNext = fFirst; fFirst = res; ++fCount; } } StringBaseResource::StringBaseResource(SRBRoot *bundle, const char *tag, int8_t type, const UChar *value, int32_t len, const UString* comment, UErrorCode &errorCode) : SResource(bundle, tag, type, comment, errorCode) { if (len == 0 && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(type); fWritten = TRUE; return; } fString.setTo(ConstChar16Ptr(value), len); fString.getTerminatedBuffer(); // Some code relies on NUL-termination. if (U_SUCCESS(errorCode) && fString.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; } } StringBaseResource::StringBaseResource(SRBRoot *bundle, int8_t type, const icu::UnicodeString &value, UErrorCode &errorCode) : SResource(bundle, NULL, type, NULL, errorCode), fString(value) { if (value.isEmpty() && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(type); fWritten = TRUE; return; } fString.getTerminatedBuffer(); // Some code relies on NUL-termination. if (U_SUCCESS(errorCode) && fString.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; } } // Pool bundle string, alias the buffer. Guaranteed NUL-terminated and not empty. StringBaseResource::StringBaseResource(int8_t type, const UChar *value, int32_t len, UErrorCode &errorCode) : SResource(NULL, NULL, type, NULL, errorCode), fString(TRUE, value, len) { assert(len > 0); assert(!fString.isBogus()); } StringBaseResource::~StringBaseResource() {} static int32_t U_CALLCONV string_hash(const UElement key) { const StringResource *res = static_cast<const StringResource *>(key.pointer); return res->fString.hashCode(); } static UBool U_CALLCONV string_comp(const UElement key1, const UElement key2) { const StringResource *res1 = static_cast<const StringResource *>(key1.pointer); const StringResource *res2 = static_cast<const StringResource *>(key2.pointer); return res1->fString == res2->fString; } StringResource::~StringResource() {} AliasResource::~AliasResource() {} IntResource::IntResource(SRBRoot *bundle, const char *tag, int32_t value, const UString* comment, UErrorCode &errorCode) : SResource(bundle, tag, URES_INT, comment, errorCode) { fValue = value; fRes = URES_MAKE_RESOURCE(URES_INT, value & RES_MAX_OFFSET); fWritten = TRUE; } IntResource::~IntResource() {} IntVectorResource::IntVectorResource(SRBRoot *bundle, const char *tag, const UString* comment, UErrorCode &errorCode) : SResource(bundle, tag, URES_INT_VECTOR, comment, errorCode), fCount(0), fArray(new uint32_t[RESLIST_MAX_INT_VECTOR]) { if (fArray == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } } IntVectorResource::~IntVectorResource() { delete[] fArray; } void IntVectorResource::add(int32_t value, UErrorCode &errorCode) { if (U_SUCCESS(errorCode)) { fArray[fCount++] = value; } } BinaryResource::BinaryResource(SRBRoot *bundle, const char *tag, uint32_t length, uint8_t *data, const char* fileName, const UString* comment, UErrorCode &errorCode) : SResource(bundle, tag, URES_BINARY, comment, errorCode), fLength(length), fData(NULL), fFileName(NULL) { if (U_FAILURE(errorCode)) { return; } if (fileName != NULL && *fileName != 0){ fFileName = new char[uprv_strlen(fileName)+1]; if (fFileName == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } uprv_strcpy(fFileName, fileName); } if (length > 0) { fData = new uint8_t[length]; if (fData == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } uprv_memcpy(fData, data, length); } else { if (gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_BINARY); fWritten = TRUE; } } } BinaryResource::~BinaryResource() { delete[] fData; delete[] fFileName; } /* Writing Functions */ void StringResource::handlePreflightStrings(SRBRoot *bundle, UHashtable *stringSet, UErrorCode &errorCode) { assert(fSame == NULL); fSame = static_cast<StringResource *>(uhash_get(stringSet, this)); if (fSame != NULL) { // This is a duplicate of a pool bundle string or of an earlier-visited string. if (++fSame->fNumCopies == 1) { assert(fSame->fWritten); int32_t poolStringIndex = (int32_t)RES_GET_OFFSET(fSame->fRes); if (poolStringIndex >= bundle->fPoolStringIndexLimit) { bundle->fPoolStringIndexLimit = poolStringIndex + 1; } } return; } /* Put this string into the set for finding duplicates. */ fNumCopies = 1; uhash_put(stringSet, this, this, &errorCode); if (bundle->fStringsForm != STRINGS_UTF16_V1) { int32_t len = length(); if (len <= MAX_IMPLICIT_STRING_LENGTH && !U16_IS_TRAIL(fString[0]) && fString.indexOf((UChar)0) < 0) { /* * This string will be stored without an explicit length. * Runtime will detect !U16_IS_TRAIL(s[0]) and call u_strlen(). */ fNumCharsForLength = 0; } else if (len <= 0x3ee) { fNumCharsForLength = 1; } else if (len <= 0xfffff) { fNumCharsForLength = 2; } else { fNumCharsForLength = 3; } bundle->f16BitStringsLength += fNumCharsForLength + len + 1; /* +1 for the NUL */ } } void ContainerResource::handlePreflightStrings(SRBRoot *bundle, UHashtable *stringSet, UErrorCode &errorCode) { for (SResource *current = fFirst; current != NULL; current = current->fNext) { current->preflightStrings(bundle, stringSet, errorCode); } } void SResource::preflightStrings(SRBRoot *bundle, UHashtable *stringSet, UErrorCode &errorCode) { if (U_FAILURE(errorCode)) { return; } if (fRes != RES_BOGUS) { /* * The resource item word was already precomputed, which means * no further data needs to be written. * This might be an integer, or an empty string/binary/etc. */ return; } handlePreflightStrings(bundle, stringSet, errorCode); } void SResource::handlePreflightStrings(SRBRoot * /*bundle*/, UHashtable * /*stringSet*/, UErrorCode & /*errorCode*/) { /* Neither a string nor a container. */ } int32_t SRBRoot::makeRes16(uint32_t resWord) const { if (resWord == 0) { return 0; /* empty string */ } uint32_t type = RES_GET_TYPE(resWord); int32_t offset = (int32_t)RES_GET_OFFSET(resWord); if (type == URES_STRING_V2) { assert(offset > 0); if (offset < fPoolStringIndexLimit) { if (offset < fPoolStringIndex16Limit) { return offset; } } else { offset = offset - fPoolStringIndexLimit + fPoolStringIndex16Limit; if (offset <= 0xffff) { return offset; } } } return -1; } int32_t SRBRoot::mapKey(int32_t oldpos) const { const KeyMapEntry *map = fKeyMap; if (map == NULL) { return oldpos; } int32_t i, start, limit; /* do a binary search for the old, pre-compactKeys() key offset */ start = fUsePoolBundle->fKeysCount; limit = start + fKeysCount; while (start < limit - 1) { i = (start + limit) / 2; if (oldpos < map[i].oldpos) { limit = i; } else { start = i; } } assert(oldpos == map[start].oldpos); return map[start].newpos; } /* * Only called for UTF-16 v1 strings and duplicate UTF-16 v2 strings. * For unique UTF-16 v2 strings, write16() sees fRes != RES_BOGUS * and exits early. */ void StringResource::handleWrite16(SRBRoot * /*bundle*/) { SResource *same; if ((same = fSame) != NULL) { /* This is a duplicate. */ assert(same->fRes != RES_BOGUS && same->fWritten); fRes = same->fRes; fWritten = same->fWritten; } } void ContainerResource::writeAllRes16(SRBRoot *bundle) { for (SResource *current = fFirst; current != NULL; current = current->fNext) { bundle->f16BitUnits.append((UChar)current->fRes16); } fWritten = TRUE; } void ArrayResource::handleWrite16(SRBRoot *bundle) { if (fCount == 0 && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_ARRAY); fWritten = TRUE; return; } int32_t res16 = 0; for (SResource *current = fFirst; current != NULL; current = current->fNext) { current->write16(bundle); res16 |= current->fRes16; } if (fCount <= 0xffff && res16 >= 0 && gFormatVersion > 1) { fRes = URES_MAKE_RESOURCE(URES_ARRAY16, bundle->f16BitUnits.length()); bundle->f16BitUnits.append((UChar)fCount); writeAllRes16(bundle); } } void TableResource::handleWrite16(SRBRoot *bundle) { if (fCount == 0 && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_TABLE); fWritten = TRUE; return; } /* Find the smallest table type that fits the data. */ int32_t key16 = 0; int32_t res16 = 0; for (SResource *current = fFirst; current != NULL; current = current->fNext) { current->write16(bundle); key16 |= current->fKey16; res16 |= current->fRes16; } if(fCount > (uint32_t)bundle->fMaxTableLength) { bundle->fMaxTableLength = fCount; } if (fCount <= 0xffff && key16 >= 0) { if (res16 >= 0 && gFormatVersion > 1) { /* 16-bit count, key offsets and values */ fRes = URES_MAKE_RESOURCE(URES_TABLE16, bundle->f16BitUnits.length()); bundle->f16BitUnits.append((UChar)fCount); for (SResource *current = fFirst; current != NULL; current = current->fNext) { bundle->f16BitUnits.append((UChar)current->fKey16); } writeAllRes16(bundle); } else { /* 16-bit count, 16-bit key offsets, 32-bit values */ fTableType = URES_TABLE; } } else { /* 32-bit count, key offsets and values */ fTableType = URES_TABLE32; } } void PseudoListResource::handleWrite16(SRBRoot * /*bundle*/) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_TABLE); fWritten = TRUE; } void SResource::write16(SRBRoot *bundle) { if (fKey >= 0) { // A tagged resource has a non-negative key index into the parsed key strings. // compactKeys() built a map from parsed key index to the final key index. // After the mapping, negative key indexes are used for shared pool bundle keys. fKey = bundle->mapKey(fKey); // If the key index fits into a Key16 for a Table or Table16, // then set the fKey16 field accordingly. // Otherwise keep it at -1. if (fKey >= 0) { if (fKey < bundle->fLocalKeyLimit) { fKey16 = fKey; } } else { int32_t poolKeyIndex = fKey & 0x7fffffff; if (poolKeyIndex <= 0xffff) { poolKeyIndex += bundle->fLocalKeyLimit; if (poolKeyIndex <= 0xffff) { fKey16 = poolKeyIndex; } } } } /* * fRes != RES_BOGUS: * The resource item word was already precomputed, which means * no further data needs to be written. * This might be an integer, or an empty or UTF-16 v2 string, * an empty binary, etc. */ if (fRes == RES_BOGUS) { handleWrite16(bundle); } // Compute fRes16 for precomputed as well as just-computed fRes. fRes16 = bundle->makeRes16(fRes); } void SResource::handleWrite16(SRBRoot * /*bundle*/) { /* Only a few resource types write 16-bit units. */ } /* * Only called for UTF-16 v1 strings, and for aliases. * For UTF-16 v2 strings, preWrite() sees fRes != RES_BOGUS * and exits early. */ void StringBaseResource::handlePreWrite(uint32_t *byteOffset) { /* Write the UTF-16 v1 string. */ fRes = URES_MAKE_RESOURCE(fType, *byteOffset >> 2); *byteOffset += 4 + (length() + 1) * U_SIZEOF_UCHAR; } void IntVectorResource::handlePreWrite(uint32_t *byteOffset) { if (fCount == 0 && gFormatVersion > 1) { fRes = URES_MAKE_EMPTY_RESOURCE(URES_INT_VECTOR); fWritten = TRUE; } else { fRes = URES_MAKE_RESOURCE(URES_INT_VECTOR, *byteOffset >> 2); *byteOffset += (1 + fCount) * 4; } } void BinaryResource::handlePreWrite(uint32_t *byteOffset) { uint32_t pad = 0; uint32_t dataStart = *byteOffset + sizeof(fLength); if (dataStart % BIN_ALIGNMENT) { pad = (BIN_ALIGNMENT - dataStart % BIN_ALIGNMENT); *byteOffset += pad; /* pad == 4 or 8 or 12 */ } fRes = URES_MAKE_RESOURCE(URES_BINARY, *byteOffset >> 2); *byteOffset += 4 + fLength; } void ContainerResource::preWriteAllRes(uint32_t *byteOffset) { for (SResource *current = fFirst; current != NULL; current = current->fNext) { current->preWrite(byteOffset); } } void ArrayResource::handlePreWrite(uint32_t *byteOffset) { preWriteAllRes(byteOffset); fRes = URES_MAKE_RESOURCE(URES_ARRAY, *byteOffset >> 2); *byteOffset += (1 + fCount) * 4; } void TableResource::handlePreWrite(uint32_t *byteOffset) { preWriteAllRes(byteOffset); if (fTableType == URES_TABLE) { /* 16-bit count, 16-bit key offsets, 32-bit values */ fRes = URES_MAKE_RESOURCE(URES_TABLE, *byteOffset >> 2); *byteOffset += 2 + fCount * 6; } else { /* 32-bit count, key offsets and values */ fRes = URES_MAKE_RESOURCE(URES_TABLE32, *byteOffset >> 2); *byteOffset += 4 + fCount * 8; } } void SResource::preWrite(uint32_t *byteOffset) { if (fRes != RES_BOGUS) { /* * The resource item word was already precomputed, which means * no further data needs to be written. * This might be an integer, or an empty or UTF-16 v2 string, * an empty binary, etc. */ return; } handlePreWrite(byteOffset); *byteOffset += calcPadding(*byteOffset); } void SResource::handlePreWrite(uint32_t * /*byteOffset*/) { assert(FALSE); } /* * Only called for UTF-16 v1 strings, and for aliases. For UTF-16 v2 strings, * write() sees fWritten and exits early. */ void StringBaseResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { /* Write the UTF-16 v1 string. */ int32_t len = length(); udata_write32(mem, len); udata_writeUString(mem, getBuffer(), len + 1); *byteOffset += 4 + (len + 1) * U_SIZEOF_UCHAR; fWritten = TRUE; } void ContainerResource::writeAllRes(UNewDataMemory *mem, uint32_t *byteOffset) { uint32_t i = 0; for (SResource *current = fFirst; current != NULL; ++i, current = current->fNext) { current->write(mem, byteOffset); } assert(i == fCount); } void ContainerResource::writeAllRes32(UNewDataMemory *mem, uint32_t *byteOffset) { for (SResource *current = fFirst; current != NULL; current = current->fNext) { udata_write32(mem, current->fRes); } *byteOffset += fCount * 4; } void ArrayResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { writeAllRes(mem, byteOffset); udata_write32(mem, fCount); *byteOffset += 4; writeAllRes32(mem, byteOffset); } void IntVectorResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { udata_write32(mem, fCount); for(uint32_t i = 0; i < fCount; ++i) { udata_write32(mem, fArray[i]); } *byteOffset += (1 + fCount) * 4; } void BinaryResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { uint32_t pad = 0; uint32_t dataStart = *byteOffset + sizeof(fLength); if (dataStart % BIN_ALIGNMENT) { pad = (BIN_ALIGNMENT - dataStart % BIN_ALIGNMENT); udata_writePadding(mem, pad); /* pad == 4 or 8 or 12 */ *byteOffset += pad; } udata_write32(mem, fLength); if (fLength > 0) { udata_writeBlock(mem, fData, fLength); } *byteOffset += 4 + fLength; } void TableResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) { writeAllRes(mem, byteOffset); if(fTableType == URES_TABLE) { udata_write16(mem, (uint16_t)fCount); for (SResource *current = fFirst; current != NULL; current = current->fNext) { udata_write16(mem, current->fKey16); } *byteOffset += (1 + fCount)* 2; if ((fCount & 1) == 0) { /* 16-bit count and even number of 16-bit key offsets need padding before 32-bit resource items */ udata_writePadding(mem, 2); *byteOffset += 2; } } else /* URES_TABLE32 */ { udata_write32(mem, fCount); for (SResource *current = fFirst; current != NULL; current = current->fNext) { udata_write32(mem, (uint32_t)current->fKey); } *byteOffset += (1 + fCount)* 4; } writeAllRes32(mem, byteOffset); } void SResource::write(UNewDataMemory *mem, uint32_t *byteOffset) { if (fWritten) { assert(fRes != RES_BOGUS); return; } handleWrite(mem, byteOffset); uint8_t paddingSize = calcPadding(*byteOffset); if (paddingSize > 0) { udata_writePadding(mem, paddingSize); *byteOffset += paddingSize; } fWritten = TRUE; } void SResource::handleWrite(UNewDataMemory * /*mem*/, uint32_t * /*byteOffset*/) { assert(FALSE); } void SRBRoot::write(const char *outputDir, const char *outputPkg, char *writtenFilename, int writtenFilenameLen, UErrorCode &errorCode) { UNewDataMemory *mem = NULL; uint32_t byteOffset = 0; uint32_t top, size; char dataName[1024]; int32_t indexes[URES_INDEX_TOP]; compactKeys(errorCode); /* * Add padding bytes to fKeys so that fKeysTop is 4-aligned. * Safe because the capacity is a multiple of 4. */ while (fKeysTop & 3) { fKeys[fKeysTop++] = (char)0xaa; } /* * In URES_TABLE, use all local key offsets that fit into 16 bits, * and use the remaining 16-bit offsets for pool key offsets * if there are any. * If there are no local keys, then use the whole 16-bit space * for pool key offsets. * Note: This cannot be changed without changing the major formatVersion. */ if (fKeysBottom < fKeysTop) { if (fKeysTop <= 0x10000) { fLocalKeyLimit = fKeysTop; } else { fLocalKeyLimit = 0x10000; } } else { fLocalKeyLimit = 0; } UHashtable *stringSet; if (gFormatVersion > 1) { stringSet = uhash_open(string_hash, string_comp, string_comp, &errorCode); if (U_SUCCESS(errorCode) && fUsePoolBundle != NULL && fUsePoolBundle->fStrings != NULL) { for (SResource *current = fUsePoolBundle->fStrings->fFirst; current != NULL; current = current->fNext) { StringResource *sr = static_cast<StringResource *>(current); sr->fNumCopies = 0; sr->fNumUnitsSaved = 0; uhash_put(stringSet, sr, sr, &errorCode); } } fRoot->preflightStrings(this, stringSet, errorCode); } else { stringSet = NULL; } if (fStringsForm == STRINGS_UTF16_V2 && f16BitStringsLength > 0) { compactStringsV2(stringSet, errorCode); } uhash_close(stringSet); if (U_FAILURE(errorCode)) { return; } int32_t formatVersion = gFormatVersion; if (fPoolStringIndexLimit != 0) { int32_t sum = fPoolStringIndexLimit + fLocalStringIndexLimit; if ((sum - 1) > RES_MAX_OFFSET) { errorCode = U_BUFFER_OVERFLOW_ERROR; return; } if (fPoolStringIndexLimit < 0x10000 && sum <= 0x10000) { // 16-bit indexes work for all pool + local strings. fPoolStringIndex16Limit = fPoolStringIndexLimit; } else { // Set the pool index threshold so that 16-bit indexes work // for some pool strings and some local strings. fPoolStringIndex16Limit = (int32_t)( ((int64_t)fPoolStringIndexLimit * 0xffff) / sum); } } else if (gIsDefaultFormatVersion && formatVersion == 3 && !fIsPoolBundle) { // If we just default to formatVersion 3 // but there are no pool bundle strings to share // and we do not write a pool bundle, // then write formatVersion 2 which is just as good. formatVersion = 2; } fRoot->write16(this); if (f16BitUnits.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } if (f16BitUnits.length() & 1) { f16BitUnits.append((UChar)0xaaaa); /* pad to multiple of 4 bytes */ } /* all keys have been mapped */ uprv_free(fKeyMap); fKeyMap = NULL; byteOffset = fKeysTop + f16BitUnits.length() * 2; fRoot->preWrite(&byteOffset); /* total size including the root item */ top = byteOffset; if (writtenFilename && writtenFilenameLen) { *writtenFilename = 0; } if (writtenFilename) { int32_t off = 0, len = 0; if (outputDir) { len = (int32_t)uprv_strlen(outputDir); if (len > writtenFilenameLen) { len = writtenFilenameLen; } uprv_strncpy(writtenFilename, outputDir, len); } if (writtenFilenameLen -= len) { off += len; writtenFilename[off] = U_FILE_SEP_CHAR; if (--writtenFilenameLen) { ++off; if(outputPkg != NULL) { uprv_strcpy(writtenFilename+off, outputPkg); off += (int32_t)uprv_strlen(outputPkg); writtenFilename[off] = '_'; ++off; } len = (int32_t)uprv_strlen(fLocale); if (len > writtenFilenameLen) { len = writtenFilenameLen; } uprv_strncpy(writtenFilename + off, fLocale, len); if (writtenFilenameLen -= len) { off += len; len = 5; if (len > writtenFilenameLen) { len = writtenFilenameLen; } uprv_strncpy(writtenFilename + off, ".res", len); } } } } if(outputPkg) { uprv_strcpy(dataName, outputPkg); uprv_strcat(dataName, "_"); uprv_strcat(dataName, fLocale); } else { uprv_strcpy(dataName, fLocale); } uprv_memcpy(dataInfo.formatVersion, gFormatVersions + formatVersion, sizeof(UVersionInfo)); mem = udata_create(outputDir, "res", dataName, &dataInfo, (gIncludeCopyright==TRUE)? U_COPYRIGHT_STRING:NULL, &errorCode); if(U_FAILURE(errorCode)){ return; } /* write the root item */ udata_write32(mem, fRoot->fRes); /* * formatVersion 1.1 (ICU 2.8): * write int32_t indexes[] after root and before the key strings * to make it easier to parse resource bundles in icuswap or from Java etc. */ uprv_memset(indexes, 0, sizeof(indexes)); indexes[URES_INDEX_LENGTH]= fIndexLength; indexes[URES_INDEX_KEYS_TOP]= fKeysTop>>2; indexes[URES_INDEX_RESOURCES_TOP]= (int32_t)(top>>2); indexes[URES_INDEX_BUNDLE_TOP]= indexes[URES_INDEX_RESOURCES_TOP]; indexes[URES_INDEX_MAX_TABLE_LENGTH]= fMaxTableLength; /* * formatVersion 1.2 (ICU 3.6): * write indexes[URES_INDEX_ATTRIBUTES] with URES_ATT_NO_FALLBACK set or not set * the memset() above initialized all indexes[] to 0 */ if (fNoFallback) { indexes[URES_INDEX_ATTRIBUTES]=URES_ATT_NO_FALLBACK; } /* * formatVersion 2.0 (ICU 4.4): * more compact string value storage, optional pool bundle */ if (URES_INDEX_16BIT_TOP < fIndexLength) { indexes[URES_INDEX_16BIT_TOP] = (fKeysTop>>2) + (f16BitUnits.length()>>1); } if (URES_INDEX_POOL_CHECKSUM < fIndexLength) { if (fIsPoolBundle) { indexes[URES_INDEX_ATTRIBUTES] |= URES_ATT_IS_POOL_BUNDLE | URES_ATT_NO_FALLBACK; uint32_t checksum = computeCRC((const char *)(fKeys + fKeysBottom), (uint32_t)(fKeysTop - fKeysBottom), 0); if (f16BitUnits.length() <= 1) { // no pool strings to checksum } else if (U_IS_BIG_ENDIAN) { checksum = computeCRC(reinterpret_cast<const char *>(f16BitUnits.getBuffer()), (uint32_t)f16BitUnits.length() * 2, checksum); } else { // Swap to big-endian so we get the same checksum on all platforms // (except for charset family, due to the key strings). UnicodeString s(f16BitUnits); s.append((UChar)1); // Ensure that we own this buffer. assert(!s.isBogus()); uint16_t *p = const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(s.getBuffer())); for (int32_t count = f16BitUnits.length(); count > 0; --count) { uint16_t x = *p; *p++ = (uint16_t)((x << 8) | (x >> 8)); } checksum = computeCRC((const char *)p, (uint32_t)f16BitUnits.length() * 2, checksum); } indexes[URES_INDEX_POOL_CHECKSUM] = (int32_t)checksum; } else if (gUsePoolBundle) { indexes[URES_INDEX_ATTRIBUTES] |= URES_ATT_USES_POOL_BUNDLE; indexes[URES_INDEX_POOL_CHECKSUM] = fUsePoolBundle->fChecksum; } } // formatVersion 3 (ICU 56): // share string values via pool bundle strings indexes[URES_INDEX_LENGTH] |= fPoolStringIndexLimit << 8; // bits 23..0 -> 31..8 indexes[URES_INDEX_ATTRIBUTES] |= (fPoolStringIndexLimit >> 12) & 0xf000; // bits 27..24 -> 15..12 indexes[URES_INDEX_ATTRIBUTES] |= fPoolStringIndex16Limit << 16; /* write the indexes[] */ udata_writeBlock(mem, indexes, fIndexLength*4); /* write the table key strings */ udata_writeBlock(mem, fKeys+fKeysBottom, fKeysTop-fKeysBottom); /* write the v2 UTF-16 strings, URES_TABLE16 and URES_ARRAY16 */ udata_writeBlock(mem, f16BitUnits.getBuffer(), f16BitUnits.length()*2); /* write all of the bundle contents: the root item and its children */ byteOffset = fKeysTop + f16BitUnits.length() * 2; fRoot->write(mem, &byteOffset); assert(byteOffset == top); size = udata_finish(mem, &errorCode); if(top != size) { fprintf(stderr, "genrb error: wrote %u bytes but counted %u\n", (int)size, (int)top); errorCode = U_INTERNAL_PROGRAM_ERROR; } } /* Opening Functions */ TableResource* table_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) { LocalPointer<TableResource> res(new TableResource(bundle, tag, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } ArrayResource* array_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) { LocalPointer<ArrayResource> res(new ArrayResource(bundle, tag, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } struct SResource *string_open(struct SRBRoot *bundle, const char *tag, const UChar *value, int32_t len, const struct UString* comment, UErrorCode *status) { LocalPointer<SResource> res( new StringResource(bundle, tag, value, len, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } struct SResource *alias_open(struct SRBRoot *bundle, const char *tag, UChar *value, int32_t len, const struct UString* comment, UErrorCode *status) { LocalPointer<SResource> res( new AliasResource(bundle, tag, value, len, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } IntVectorResource *intvector_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) { LocalPointer<IntVectorResource> res( new IntVectorResource(bundle, tag, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } struct SResource *int_open(struct SRBRoot *bundle, const char *tag, int32_t value, const struct UString* comment, UErrorCode *status) { LocalPointer<SResource> res(new IntResource(bundle, tag, value, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } struct SResource *bin_open(struct SRBRoot *bundle, const char *tag, uint32_t length, uint8_t *data, const char* fileName, const struct UString* comment, UErrorCode *status) { LocalPointer<SResource> res( new BinaryResource(bundle, tag, length, data, fileName, comment, *status), *status); return U_SUCCESS(*status) ? res.orphan() : NULL; } SRBRoot::SRBRoot(const UString *comment, UBool isPoolBundle, UErrorCode &errorCode) : fRoot(NULL), fLocale(NULL), fIndexLength(0), fMaxTableLength(0), fNoFallback(FALSE), fStringsForm(STRINGS_UTF16_V1), fIsPoolBundle(isPoolBundle), fKeys(NULL), fKeyMap(NULL), fKeysBottom(0), fKeysTop(0), fKeysCapacity(0), fKeysCount(0), fLocalKeyLimit(0), f16BitUnits(), f16BitStringsLength(0), fUsePoolBundle(&kNoPoolBundle), fPoolStringIndexLimit(0), fPoolStringIndex16Limit(0), fLocalStringIndexLimit(0), fWritePoolBundle(NULL) { if (U_FAILURE(errorCode)) { return; } if (gFormatVersion > 1) { // f16BitUnits must start with a zero for empty resources. // We might be able to omit it if there are no empty 16-bit resources. f16BitUnits.append((UChar)0); } fKeys = (char *) uprv_malloc(sizeof(char) * KEY_SPACE_SIZE); if (isPoolBundle) { fRoot = new PseudoListResource(this, errorCode); } else { fRoot = new TableResource(this, NULL, comment, errorCode); } if (fKeys == NULL || fRoot == NULL || U_FAILURE(errorCode)) { if (U_SUCCESS(errorCode)) { errorCode = U_MEMORY_ALLOCATION_ERROR; } return; } fKeysCapacity = KEY_SPACE_SIZE; /* formatVersion 1.1 and up: start fKeysTop after the root item and indexes[] */ if (gUsePoolBundle || isPoolBundle) { fIndexLength = URES_INDEX_POOL_CHECKSUM + 1; } else if (gFormatVersion >= 2) { fIndexLength = URES_INDEX_16BIT_TOP + 1; } else /* formatVersion 1 */ { fIndexLength = URES_INDEX_ATTRIBUTES + 1; } fKeysBottom = (1 /* root */ + fIndexLength) * 4; uprv_memset(fKeys, 0, fKeysBottom); fKeysTop = fKeysBottom; if (gFormatVersion == 1) { fStringsForm = STRINGS_UTF16_V1; } else { fStringsForm = STRINGS_UTF16_V2; } } /* Closing Functions */ void res_close(struct SResource *res) { delete res; } SRBRoot::~SRBRoot() { delete fRoot; uprv_free(fLocale); uprv_free(fKeys); uprv_free(fKeyMap); } /* Misc Functions */ void SRBRoot::setLocale(UChar *locale, UErrorCode &errorCode) { if(U_FAILURE(errorCode)) { return; } uprv_free(fLocale); fLocale = (char*) uprv_malloc(sizeof(char) * (u_strlen(locale)+1)); if(fLocale == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } u_UCharsToChars(locale, fLocale, u_strlen(locale)+1); } const char * SRBRoot::getKeyString(int32_t key) const { if (key < 0) { return fUsePoolBundle->fKeys + (key & 0x7fffffff); } else { return fKeys + key; } } const char * SResource::getKeyString(const SRBRoot *bundle) const { if (fKey == -1) { return NULL; } return bundle->getKeyString(fKey); } const char * SRBRoot::getKeyBytes(int32_t *pLength) const { *pLength = fKeysTop - fKeysBottom; return fKeys + fKeysBottom; } int32_t SRBRoot::addKeyBytes(const char *keyBytes, int32_t length, UErrorCode &errorCode) { int32_t keypos; if (U_FAILURE(errorCode)) { return -1; } if (length < 0 || (keyBytes == NULL && length != 0)) { errorCode = U_ILLEGAL_ARGUMENT_ERROR; return -1; } if (length == 0) { return fKeysTop; } keypos = fKeysTop; fKeysTop += length; if (fKeysTop >= fKeysCapacity) { /* overflow - resize the keys buffer */ fKeysCapacity += KEY_SPACE_SIZE; fKeys = static_cast<char *>(uprv_realloc(fKeys, fKeysCapacity)); if(fKeys == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return -1; } } uprv_memcpy(fKeys + keypos, keyBytes, length); return keypos; } int32_t SRBRoot::addTag(const char *tag, UErrorCode &errorCode) { int32_t keypos; if (U_FAILURE(errorCode)) { return -1; } if (tag == NULL) { /* no error: the root table and array items have no keys */ return -1; } keypos = addKeyBytes(tag, (int32_t)(uprv_strlen(tag) + 1), errorCode); if (U_SUCCESS(errorCode)) { ++fKeysCount; } return keypos; } static int32_t compareInt32(int32_t lPos, int32_t rPos) { /* * Compare possibly-negative key offsets. Don't just return lPos - rPos * because that is prone to negative-integer underflows. */ if (lPos < rPos) { return -1; } else if (lPos > rPos) { return 1; } else { return 0; } } static int32_t U_CALLCONV compareKeySuffixes(const void *context, const void *l, const void *r) { const struct SRBRoot *bundle=(const struct SRBRoot *)context; int32_t lPos = ((const KeyMapEntry *)l)->oldpos; int32_t rPos = ((const KeyMapEntry *)r)->oldpos; const char *lStart = bundle->getKeyString(lPos); const char *lLimit = lStart; const char *rStart = bundle->getKeyString(rPos); const char *rLimit = rStart; int32_t diff; while (*lLimit != 0) { ++lLimit; } while (*rLimit != 0) { ++rLimit; } /* compare keys in reverse character order */ while (lStart < lLimit && rStart < rLimit) { diff = (int32_t)(uint8_t)*--lLimit - (int32_t)(uint8_t)*--rLimit; if (diff != 0) { return diff; } } /* sort equal suffixes by descending key length */ diff = (int32_t)(rLimit - rStart) - (int32_t)(lLimit - lStart); if (diff != 0) { return diff; } /* Sort pool bundle keys first (negative oldpos), and otherwise keys in parsing order. */ return compareInt32(lPos, rPos); } static int32_t U_CALLCONV compareKeyNewpos(const void * /*context*/, const void *l, const void *r) { return compareInt32(((const KeyMapEntry *)l)->newpos, ((const KeyMapEntry *)r)->newpos); } static int32_t U_CALLCONV compareKeyOldpos(const void * /*context*/, const void *l, const void *r) { return compareInt32(((const KeyMapEntry *)l)->oldpos, ((const KeyMapEntry *)r)->oldpos); } void SRBRoot::compactKeys(UErrorCode &errorCode) { KeyMapEntry *map; char *keys; int32_t i; int32_t keysCount = fUsePoolBundle->fKeysCount + fKeysCount; if (U_FAILURE(errorCode) || fKeysCount == 0 || fKeyMap != NULL) { return; } map = (KeyMapEntry *)uprv_malloc(keysCount * sizeof(KeyMapEntry)); if (map == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } keys = (char *)fUsePoolBundle->fKeys; for (i = 0; i < fUsePoolBundle->fKeysCount; ++i) { map[i].oldpos = (int32_t)(keys - fUsePoolBundle->fKeys) | 0x80000000; /* negative oldpos */ map[i].newpos = 0; while (*keys != 0) { ++keys; } /* skip the key */ ++keys; /* skip the NUL */ } keys = fKeys + fKeysBottom; for (; i < keysCount; ++i) { map[i].oldpos = (int32_t)(keys - fKeys); map[i].newpos = 0; while (*keys != 0) { ++keys; } /* skip the key */ ++keys; /* skip the NUL */ } /* Sort the keys so that each one is immediately followed by all of its suffixes. */ uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry), compareKeySuffixes, this, FALSE, &errorCode); /* * Make suffixes point into earlier, longer strings that contain them * and mark the old, now unused suffix bytes as deleted. */ if (U_SUCCESS(errorCode)) { keys = fKeys; for (i = 0; i < keysCount;) { /* * This key is not a suffix of the previous one; * keep this one and delete the following ones that are * suffixes of this one. */ const char *key; const char *keyLimit; int32_t j = i + 1; map[i].newpos = map[i].oldpos; if (j < keysCount && map[j].oldpos < 0) { /* Key string from the pool bundle, do not delete. */ i = j; continue; } key = getKeyString(map[i].oldpos); for (keyLimit = key; *keyLimit != 0; ++keyLimit) {} for (; j < keysCount && map[j].oldpos >= 0; ++j) { const char *k; char *suffix; const char *suffixLimit; int32_t offset; suffix = keys + map[j].oldpos; for (suffixLimit = suffix; *suffixLimit != 0; ++suffixLimit) {} offset = static_cast<int32_t>((keyLimit - key) - (suffixLimit - suffix)); if (offset < 0) { break; /* suffix cannot be longer than the original */ } /* Is it a suffix of the earlier, longer key? */ for (k = keyLimit; suffix < suffixLimit && *--k == *--suffixLimit;) {} if (suffix == suffixLimit && *k == *suffixLimit) { map[j].newpos = map[i].oldpos + offset; /* yes, point to the earlier key */ /* mark the suffix as deleted */ while (*suffix != 0) { *suffix++ = 1; } *suffix = 1; } else { break; /* not a suffix, restart from here */ } } i = j; } /* * Re-sort by newpos, then modify the key characters array in-place * to squeeze out unused bytes, and readjust the newpos offsets. */ uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry), compareKeyNewpos, NULL, FALSE, &errorCode); if (U_SUCCESS(errorCode)) { int32_t oldpos, newpos, limit; oldpos = newpos = fKeysBottom; limit = fKeysTop; /* skip key offsets that point into the pool bundle rather than this new bundle */ for (i = 0; i < keysCount && map[i].newpos < 0; ++i) {} if (i < keysCount) { while (oldpos < limit) { if (keys[oldpos] == 1) { ++oldpos; /* skip unused bytes */ } else { /* adjust the new offsets for keys starting here */ while (i < keysCount && map[i].newpos == oldpos) { map[i++].newpos = newpos; } /* move the key characters to their new position */ keys[newpos++] = keys[oldpos++]; } } assert(i == keysCount); } fKeysTop = newpos; /* Re-sort once more, by old offsets for binary searching. */ uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry), compareKeyOldpos, NULL, FALSE, &errorCode); if (U_SUCCESS(errorCode)) { /* key size reduction by limit - newpos */ fKeyMap = map; map = NULL; } } } uprv_free(map); } static int32_t U_CALLCONV compareStringSuffixes(const void * /*context*/, const void *l, const void *r) { const StringResource *left = *((const StringResource **)l); const StringResource *right = *((const StringResource **)r); const UChar *lStart = left->getBuffer(); const UChar *lLimit = lStart + left->length(); const UChar *rStart = right->getBuffer(); const UChar *rLimit = rStart + right->length(); int32_t diff; /* compare keys in reverse character order */ while (lStart < lLimit && rStart < rLimit) { diff = (int32_t)*--lLimit - (int32_t)*--rLimit; if (diff != 0) { return diff; } } /* sort equal suffixes by descending string length */ return right->length() - left->length(); } static int32_t U_CALLCONV compareStringLengths(const void * /*context*/, const void *l, const void *r) { const StringResource *left = *((const StringResource **)l); const StringResource *right = *((const StringResource **)r); int32_t diff; /* Make "is suffix of another string" compare greater than a non-suffix. */ diff = (int)(left->fSame != NULL) - (int)(right->fSame != NULL); if (diff != 0) { return diff; } /* sort by ascending string length */ diff = left->length() - right->length(); if (diff != 0) { return diff; } // sort by descending size reduction diff = right->fNumUnitsSaved - left->fNumUnitsSaved; if (diff != 0) { return diff; } // sort lexically return left->fString.compare(right->fString); } void StringResource::writeUTF16v2(int32_t base, UnicodeString &dest) { int32_t len = length(); fRes = URES_MAKE_RESOURCE(URES_STRING_V2, base + dest.length()); fWritten = TRUE; switch(fNumCharsForLength) { case 0: break; case 1: dest.append((UChar)(0xdc00 + len)); break; case 2: dest.append((UChar)(0xdfef + (len >> 16))); dest.append((UChar)len); break; case 3: dest.append((UChar)0xdfff); dest.append((UChar)(len >> 16)); dest.append((UChar)len); break; default: break; /* will not occur */ } dest.append(fString); dest.append((UChar)0); } void SRBRoot::compactStringsV2(UHashtable *stringSet, UErrorCode &errorCode) { if (U_FAILURE(errorCode)) { return; } // Store the StringResource pointers in an array for // easy sorting and processing. // We enumerate a set of strings, so there are no duplicates. int32_t count = uhash_count(stringSet); LocalArray<StringResource *> array(new StringResource *[count], errorCode); if (U_FAILURE(errorCode)) { return; } for (int32_t pos = UHASH_FIRST, i = 0; i < count; ++i) { array[i] = (StringResource *)uhash_nextElement(stringSet, &pos)->key.pointer; } /* Sort the strings so that each one is immediately followed by all of its suffixes. */ uprv_sortArray(array.getAlias(), count, (int32_t)sizeof(struct SResource **), compareStringSuffixes, NULL, FALSE, &errorCode); if (U_FAILURE(errorCode)) { return; } /* * Make suffixes point into earlier, longer strings that contain them. * Temporarily use fSame and fSuffixOffset for suffix strings to * refer to the remaining ones. */ for (int32_t i = 0; i < count;) { /* * This string is not a suffix of the previous one; * write this one and subsume the following ones that are * suffixes of this one. */ StringResource *res = array[i]; res->fNumUnitsSaved = (res->fNumCopies - 1) * res->get16BitStringsLength(); // Whole duplicates of pool strings are already account for in fPoolStringIndexLimit, // see StringResource::handlePreflightStrings(). int32_t j; for (j = i + 1; j < count; ++j) { StringResource *suffixRes = array[j]; /* Is it a suffix of the earlier, longer string? */ if (res->fString.endsWith(suffixRes->fString)) { assert(res->length() != suffixRes->length()); // Set strings are unique. if (suffixRes->fWritten) { // Pool string, skip. } else if (suffixRes->fNumCharsForLength == 0) { /* yes, point to the earlier string */ suffixRes->fSame = res; suffixRes->fSuffixOffset = res->length() - suffixRes->length(); if (res->fWritten) { // Suffix-share res which is a pool string. // Compute the resource word and collect the maximum. suffixRes->fRes = res->fRes + res->fNumCharsForLength + suffixRes->fSuffixOffset; int32_t poolStringIndex = (int32_t)RES_GET_OFFSET(suffixRes->fRes); if (poolStringIndex >= fPoolStringIndexLimit) { fPoolStringIndexLimit = poolStringIndex + 1; } suffixRes->fWritten = TRUE; } res->fNumUnitsSaved += suffixRes->fNumCopies * suffixRes->get16BitStringsLength(); } else { /* write the suffix by itself if we need explicit length */ } } else { break; /* not a suffix, restart from here */ } } i = j; } /* * Re-sort the strings by ascending length (except suffixes last) * to optimize for URES_TABLE16 and URES_ARRAY16: * Keep as many as possible within reach of 16-bit offsets. */ uprv_sortArray(array.getAlias(), count, (int32_t)sizeof(struct SResource **), compareStringLengths, NULL, FALSE, &errorCode); if (U_FAILURE(errorCode)) { return; } if (fIsPoolBundle) { // Write strings that are sufficiently shared. // Avoid writing other strings. int32_t numStringsWritten = 0; int32_t numUnitsSaved = 0; int32_t numUnitsNotSaved = 0; for (int32_t i = 0; i < count; ++i) { StringResource *res = array[i]; // Maximum pool string index when suffix-sharing the last character. int32_t maxStringIndex = f16BitUnits.length() + res->fNumCharsForLength + res->length() - 1; if (res->fNumUnitsSaved >= GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING && maxStringIndex < RES_MAX_OFFSET) { res->writeUTF16v2(0, f16BitUnits); ++numStringsWritten; numUnitsSaved += res->fNumUnitsSaved; } else { numUnitsNotSaved += res->fNumUnitsSaved; res->fRes = URES_MAKE_EMPTY_RESOURCE(URES_STRING); res->fWritten = TRUE; } } if (f16BitUnits.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; } if (getShowWarning()) { // not quiet printf("number of shared strings: %d\n", (int)numStringsWritten); printf("16-bit units for strings: %6d = %6d bytes\n", (int)f16BitUnits.length(), (int)f16BitUnits.length() * 2); printf("16-bit units saved: %6d = %6d bytes\n", (int)numUnitsSaved, (int)numUnitsSaved * 2); printf("16-bit units not saved: %6d = %6d bytes\n", (int)numUnitsNotSaved, (int)numUnitsNotSaved * 2); } } else { assert(fPoolStringIndexLimit <= fUsePoolBundle->fStringIndexLimit); /* Write the non-suffix strings. */ int32_t i; for (i = 0; i < count && array[i]->fSame == NULL; ++i) { StringResource *res = array[i]; if (!res->fWritten) { int32_t localStringIndex = f16BitUnits.length(); if (localStringIndex >= fLocalStringIndexLimit) { fLocalStringIndexLimit = localStringIndex + 1; } res->writeUTF16v2(fPoolStringIndexLimit, f16BitUnits); } } if (f16BitUnits.isBogus()) { errorCode = U_MEMORY_ALLOCATION_ERROR; return; } if (fWritePoolBundle != NULL && gFormatVersion >= 3) { PseudoListResource *poolStrings = static_cast<PseudoListResource *>(fWritePoolBundle->fRoot); for (i = 0; i < count && array[i]->fSame == NULL; ++i) { assert(!array[i]->fString.isEmpty()); StringResource *poolString = new StringResource(fWritePoolBundle, array[i]->fString, errorCode); if (poolString == NULL) { errorCode = U_MEMORY_ALLOCATION_ERROR; break; } poolStrings->add(poolString); } } /* Write the suffix strings. Make each point to the real string. */ for (; i < count; ++i) { StringResource *res = array[i]; if (res->fWritten) { continue; } StringResource *same = res->fSame; assert(res->length() != same->length()); // Set strings are unique. res->fRes = same->fRes + same->fNumCharsForLength + res->fSuffixOffset; int32_t localStringIndex = (int32_t)RES_GET_OFFSET(res->fRes) - fPoolStringIndexLimit; // Suffixes of pool strings have been set already. assert(localStringIndex >= 0); if (localStringIndex >= fLocalStringIndexLimit) { fLocalStringIndexLimit = localStringIndex + 1; } res->fWritten = TRUE; } } // +1 to account for the initial zero in f16BitUnits assert(f16BitUnits.length() <= (f16BitStringsLength + 1)); }
58,391
19,355
// Yule Zhang #include <iostream> #include <fstream> using namespace std; #include "queue_eda.h" template <typename T> class listaPlus : public queue<T> { using Nodo = typename queue<T>::Nodo; public: void mezclar(listaPlus<T> & l1, listaPlus<T> & l2) { if (l1.nelems == 0) {//Si l1 es vacia this->prim = l2.prim; this->ult = l2.ult; } else if (l2.nelems == 0) {//Si l2 es vacia this->prim = l1.prim; this->ult = l1.ult; } else {//Si ni l1 ni l2 son vacias Nodo* nodo1 = l1.prim; Nodo* nodo2 = l2.prim; if (nodo1->elem <= nodo2->elem) { this->prim = nodo1; nodo1 = nodo1->sig; } else { this->prim = nodo2; nodo2 = nodo2->sig; } Nodo* nodo = this->prim; while (nodo1 != nullptr && nodo2 != nullptr) { if (nodo1->elem <= nodo2->elem) { nodo->sig = nodo1; nodo1 = nodo1->sig; nodo = nodo->sig; } else { nodo->sig = nodo2; nodo2 = nodo2->sig; nodo = nodo->sig; } } while (nodo1 != nullptr) { nodo->sig = nodo1; nodo1 = nodo1->sig; nodo = nodo->sig; } while (nodo2 != nullptr) { nodo->sig = nodo2; nodo2 = nodo2->sig; nodo = nodo->sig; } } this->nelems = l1.nelems + l2.nelems; l1.prim = l1.ult = nullptr; l2.prim = l2.ult = nullptr; l1.nelems = l2.nelems = 0; } void print() const { Nodo* aux = this->prim; while (aux != nullptr) { cout << aux->elem << ' '; aux = aux->sig; } cout << endl; } }; void resuelveCaso() { int n; cin >> n;//Leer datos de entrada listaPlus<int> l1;//Primera lista listaPlus<int> l2;//Segunda lista while (n != 0) { l1.push(n); cin >> n; } int m; cin >> m; while (m != 0) { l2.push(m); cin >> m; } listaPlus<int> l;//Lista final l.mezclar(l1, l2); l.print(); } int main() { // ajustes para que cin extraiga directamente de un fichero #ifndef DOMJUDGE std::ifstream in("casos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); #endif int numCasos; std::cin >> numCasos; for (int i = 0; i < numCasos; ++i) resuelveCaso(); // para dejar todo como estaba al principio #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
2,205
1,137
#ifndef RAYTRACING_MATERIAL_H #define RAYTRACING_MATERIAL_H #include "Vector.hpp" enum class MaterialType { DIFFUSE }; class Material { private: // Compute reflection direction Vector3f reflect(const Vector3f &I, const Vector3f &N) const { return I - 2 * I.dot(N) * N; } // Compute refraction direction using Snell's law // // We need to handle with care the two possible situations: // // - When the ray is inside the object // // - When the ray is outside. // // If the ray is outside, you need to make cosi positive cosi = -N.I // // If the ray is inside, you need to invert the refractive indices and negate the normal N Vector3f refract(const Vector3f &I, const Vector3f &N, const float &ior) const { float cosi = clamp(-1, 1, I.dot(N)); float etai = 1, etat = ior; Vector3f n = N; if (cosi < 0) { cosi = -cosi; } else { std::swap(etai, etat); n = -N; } float eta = etai / etat; float k = 1 - eta * eta * (1 - cosi * cosi); return k < 0 ? 0 : eta * I + (eta * cosi - sqrt(k)) * n; } // Compute Fresnel equation // // \param I is the incident view direction // // \param N is the normal at the intersection point // // \param ior is the material refractive index // // \param[out] kr is the amount of light reflected void fresnel(const Vector3f &I, const Vector3f &N, const float &ior, float &kr) const { float cosi = clamp(-1, 1, I.dot(N)); float etai = 1, etat = ior; if (cosi > 0) { std::swap(etai, etat); } // Compute sini using Snell's law float sint = etai / etat * sqrtf(std::max(0.f, 1 - cosi * cosi)); // Total internal reflection if (sint >= 1) { kr = 1; } else { float cost = sqrtf(std::max(0.f, 1 - sint * sint)); cosi = fabsf(cosi); float Rs = ((etat * cosi) - (etai * cost)) / ((etat * cosi) + (etai * cost)); float Rp = ((etai * cosi) - (etat * cost)) / ((etai * cosi) + (etat * cost)); kr = (Rs * Rs + Rp * Rp) / 2; } // As a consequence of the conservation of energy, transmittance is given by: // kt = 1 - kr; } Vector3f toWorld(const Vector3f &a, const Vector3f &N) { Vector3f B, C; if (std::fabs(N.x) > std::fabs(N.y)) { float invLen = 1.0f / std::sqrt(N.x * N.x + N.z * N.z); C = Vector3f(N.z * invLen, 0.0f, -N.x * invLen); } else { float invLen = 1.0f / std::sqrt(N.y * N.y + N.z * N.z); C = Vector3f(0.0f, N.z * invLen, -N.y * invLen); } B = C.cross(N); return a.x * B + a.y * C + a.z * N; } public: MaterialType m_type; Vector3f emit; float ior; Vector3f Kd, Ks; float specularExponent; //Texture tex; Material(MaterialType t = MaterialType::DIFFUSE, Vector3f e = Vector3f(0, 0, 0)) { m_type = t; emit = e; } inline bool hasEmit() { return emit.length() > EPSILON ? true : false; } // sample a ray by Material properties inline Vector3f sample(const Vector3f &wi, const Vector3f &N); // given a ray, calculate the PdF of this ray inline float pdf(const Vector3f &wi, const Vector3f &wo, const Vector3f &N); // given a ray, calculate the contribution of this ray inline Vector3f eval(const Vector3f &wi, const Vector3f &wo, const Vector3f &N); }; Vector3f Material::sample(const Vector3f &wi, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // uniform sample on the hemisphere float x_1 = get_random_float(), x_2 = get_random_float(); float z = std::fabs(1.0f - 2.0f * x_1); float r = std::sqrt(1.0f - z * z), phi = 2 * M_PI * x_2; Vector3f localRay(r * std::cos(phi), r * std::sin(phi), z); return toWorld(localRay, N); break; } } } float Material::pdf(const Vector3f &wi, const Vector3f &wo, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // uniform sample probability 1 / (2 * PI) if (wo.dot(N) > 0.0f) return 0.5f / M_PI; else return 0.0f; break; } } } Vector3f Material::eval(const Vector3f &wi, const Vector3f &wo, const Vector3f &N) { switch (m_type) { case MaterialType::DIFFUSE: { // calculate the contribution of diffuse model float cosalpha = wo.dot(N); if (cosalpha > 0.0f) { Vector3f diffuse = Kd / M_PI; return diffuse; } else return Vector3f(0.0f); break; } } } #endif //RAYTRACING_MATERIAL_H
4,217
1,850
/// \file /// \brief Internal header file that contains implementation of the position /// class. /// \author Lyberta /// \copyright BSLv1. #pragma once namespace std::io { constexpr position::position(streamoff off) noexcept : m_position{off} { } constexpr position::position(offset off) noexcept : m_position{off.value()} { } constexpr streamoff position::value() const noexcept { return m_position; } constexpr position& position::operator++() noexcept { ++m_position; return *this; } constexpr position position::operator++(int) noexcept { position temp{*this}; ++(*this); return temp; } constexpr position& position::operator--() noexcept { --m_position; return *this; } constexpr position position::operator--(int) noexcept { position temp{*this}; --(*this); return temp; } constexpr position& position::operator+=(offset rhs) noexcept { m_position += rhs.value(); return *this; } constexpr position& position::operator-=(offset rhs) noexcept { m_position -= rhs.value(); return *this; } constexpr position position::max() noexcept { return position{numeric_limits<streamoff>::max()}; } constexpr bool operator==(position lhs, position rhs) noexcept { return lhs.value() == rhs.value(); } constexpr strong_ordering operator<=>(position lhs, position rhs) noexcept { return lhs.value() <=> rhs.value(); } constexpr position operator+(position lhs, offset rhs) noexcept { return lhs += rhs; } constexpr position operator+(offset lhs, position rhs) noexcept { return rhs += lhs; } constexpr position operator-(position lhs, offset rhs) noexcept { return lhs -= rhs; } constexpr offset operator-(position lhs, position rhs) noexcept { return offset{lhs.value() - rhs.value()}; } }
1,726
564
/** \file "Object/inst/null_collection_type_manager.hh" Template class for instance_collection's type manager. $Id: null_collection_type_manager.hh,v 1.12 2007/04/15 05:52:19 fang Exp $ */ #ifndef __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__ #define __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__ #include <iosfwd> #include "Object/type/canonical_type_fwd.hh" // just for conditional #include "util/persistent_fwd.hh" #include "util/boolean_types.hh" #include "util/memory/pointer_classes_fwd.hh" namespace HAC { namespace entity { class const_param_expr_list; using std::istream; using std::ostream; using util::good_bool; using util::bad_bool; using util::persistent_object_manager; using util::memory::count_ptr; class footprint; template <class> struct class_traits; //============================================================================= /** Appropriate for built-in types with no template parameters. Pretty much only useful to bool. TODO: write a quick raw-type comparison without having to construct canonical type. */ template <class Tag> class null_collection_type_manager { private: typedef null_collection_type_manager<Tag> this_type; typedef class_traits<Tag> traits_type; protected: typedef typename traits_type::instance_collection_generic_type instance_collection_generic_type; typedef typename traits_type::instance_collection_parameter_type instance_collection_parameter_type; typedef typename traits_type::type_ref_ptr_type type_ref_ptr_type; typedef typename traits_type::resolved_type_ref_type resolved_type_ref_type; // has no type parameter struct dumper; void collect_transient_info_base(persistent_object_manager&) const { } void write_object_base(const persistent_object_manager&, ostream&) const { } void load_object_base(const persistent_object_manager&, istream&) { } public: // distinguish internal type from canonical_type /** Only used internally with collections. */ instance_collection_parameter_type __get_raw_type(void) const { return instance_collection_parameter_type(); } resolved_type_ref_type get_resolved_canonical_type(void) const; good_bool complete_type_definition_footprint( const count_ptr<const const_param_expr_list>&) const { return good_bool(true); } bool is_complete_type(void) const { return true; } bool is_relaxed_type(void) const { return false; } // bool doesn't have a footprint static good_bool create_definition_footprint( const instance_collection_parameter_type&, const footprint& /* top */) { return good_bool(true); } protected: bool must_be_collectibly_type_equivalent(const this_type&) const { return true; } bad_bool check_type(const instance_collection_parameter_type&) const { return bad_bool(false); } /** \param t type must be resolved constant. \pre first time called for the collection. */ good_bool commit_type_first_time( const instance_collection_parameter_type&) const { return good_bool(true); } }; // end struct null_collection_type_manager //============================================================================= } // end namespace entity } // end namespace HAC #endif // __HAC_OBJECT_INST_NULL_COLLECTION_TYPE_MANAGER_H__
3,271
1,136
// Copyright 2010-2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ortools/linear_solver/gurobi_environment.h" #include <string> #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "ortools/base/logging.h" #include "ortools/linear_solver/linear_solver.h" namespace operations_research { absl::Status LoadGurobiEnvironment(GRBenv** env) { constexpr int GRB_OK = 0; const char kGurobiEnvErrorMsg[] = "Could not load Gurobi environment. Is gurobi correctly installed and " "licensed on this machine?"; if (GRBloadenv(env, nullptr) != 0 || *env == nullptr) { return absl::FailedPreconditionError( absl::StrFormat("%s %s", kGurobiEnvErrorMsg, GRBgeterrormsg(*env))); } return absl::OkStatus(); } std::function<int(GRBmodel*, int, int*, double*, double, double, const char*)> GRBaddrangeconstr = nullptr; std::function<int(GRBmodel* model, int numnz, int* vind, double* vval, double obj, double lb, double ub, char vtype, const char* varname)> GRBaddvar = nullptr; std::function<int(GRBmodel*, int, int, int*, int*, double*, double*, double*, double*, char*, char**)> GRBaddvars = nullptr; std::function<int(GRBmodel* model, int numchgs, int* cind, int* vind, double* val)> GRBchgcoeffs = nullptr; std::function<void(GRBenv*)> GRBfreeenv = nullptr; std::function<int(GRBmodel*)> GRBfreemodel = nullptr; std::function<int(GRBmodel*, const char*, int, char*)> GRBgetcharattrelement = nullptr; std::function<int(GRBmodel*, const char*, double*)> GRBgetdblattr = nullptr; std::function<int(GRBmodel*, const char*, int, int, double*)> GRBgetdblattrarray = nullptr; std::function<int(GRBmodel*, const char*, int, double*)> GRBgetdblattrelement = nullptr; std::function<int(GRBenv*, const char*, double*)> GRBgetdblparam = nullptr; std::function<GRBenv*(GRBmodel*)> GRBgetenv = nullptr; std::function<char*(GRBenv*)> GRBgeterrormsg = nullptr; std::function<int(GRBmodel*, const char*, int*)> GRBgetintattr = nullptr; std::function<int(GRBmodel*, const char*, int, int*)> GRBgetintattrelement = nullptr; std::function<int(GRBenv**, const char*)> GRBloadenv = nullptr; std::function<int(GRBenv*, GRBmodel**, const char*, int numvars, double*, double*, double*, char*, char**)> GRBnewmodel = nullptr; std::function<int(GRBmodel*)> GRBoptimize = nullptr; std::function<int(GRBenv*, const char*)> GRBreadparams = nullptr; std::function<int(GRBenv*)> GRBresetparams = nullptr; std::function<int(GRBmodel*, const char*, int, char)> GRBsetcharattrelement = nullptr; std::function<int(GRBmodel*, const char*, double)> GRBsetdblattr = nullptr; std::function<int(GRBmodel*, const char*, int, double)> GRBsetdblattrelement = nullptr; std::function<int(GRBenv*, const char*, double)> GRBsetdblparam = nullptr; std::function<int(GRBmodel*, const char*, int)> GRBsetintattr = nullptr; std::function<int(GRBenv*, const char*, int)> GRBsetintparam = nullptr; std::function<void(GRBmodel*)> GRBterminate = nullptr; std::function<int(GRBmodel*)> GRBupdatemodel = nullptr; std::function<void(int*, int*, int*)> GRBversion = nullptr; std::function<int(GRBmodel*, const char*)> GRBwrite = nullptr; std::function<int(void* cbdata, int where, int what, void* resultP)> GRBcbget = nullptr; std::function<int(void* cbdata, int cutlen, const int* cutind, const double* cutval, char cutsense, double cutrhs)> GRBcbcut = nullptr; std::function<int(void* cbdata, int lazylen, const int* lazyind, const double* lazyval, char lazysense, double lazyrhs)> GRBcblazy = nullptr; std::function<int(void* cbdata, const double* solution, double* objvalP)> GRBcbsolution = nullptr; std::function<int(GRBmodel* model, int numnz, int* cind, double* cval, char sense, double rhs, const char* constrname)> GRBaddconstr = nullptr; std::function<int(GRBmodel* model, const char* name, int binvar, int binval, int nvars, const int* vars, const double* vals, char sense, double rhs)> GRBaddgenconstrIndicator = nullptr; std::function<int(GRBmodel* model, const char* attrname, int element, int newvalue)> GRBsetintattrelement = nullptr; std::function<int(GRBmodel* model, int(STDCALL* cb)(CB_ARGS), void* usrdata)> GRBsetcallbackfunc = nullptr; std::function<int(GRBenv* env, const char* paramname, const char* value)> GRBsetparam = nullptr; std::function<int(GRBmodel* model, int numsos, int nummembers, int* types, int* beg, int* ind, double* weight)> GRBaddsos = nullptr; std::function<int(GRBmodel* model, int numlnz, int* lind, double* lval, int numqnz, int* qrow, int* qcol, double* qval, char sense, double rhs, const char* QCname)> GRBaddqconstr = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int nvars, const int* vars, double constant)> GRBaddgenconstrMax = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int nvars, const int* vars, double constant)> GRBaddgenconstrMin = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int argvar)> GRBaddgenconstrAbs = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int nvars, const int* vars)> GRBaddgenconstrAnd = nullptr; std::function<int(GRBmodel* model, const char* name, int resvar, int nvars, const int* vars)> GRBaddgenconstrOr = nullptr; std::function<int(GRBmodel* model, int numqnz, int* qrow, int* qcol, double* qval)> GRBaddqpterms = nullptr; std::unique_ptr<DynamicLibrary> gurobi_dynamic_library; std::string gurobi_library_path; void LoadGurobiFunctions() { gurobi_dynamic_library->GetFunction(&GRBaddrangeconstr, NAMEOF(GRBaddrangeconstr)); gurobi_dynamic_library->GetFunction(&GRBaddvar, NAMEOF(GRBaddvar)); gurobi_dynamic_library->GetFunction(&GRBaddvars, NAMEOF(GRBaddvars)); gurobi_dynamic_library->GetFunction(&GRBchgcoeffs, NAMEOF(GRBchgcoeffs)); gurobi_dynamic_library->GetFunction(&GRBfreeenv, NAMEOF(GRBfreeenv)); gurobi_dynamic_library->GetFunction(&GRBfreemodel, NAMEOF(GRBfreemodel)); gurobi_dynamic_library->GetFunction(&GRBgetcharattrelement, NAMEOF(GRBgetcharattrelement)); gurobi_dynamic_library->GetFunction(&GRBgetdblattr, NAMEOF(GRBgetdblattr)); gurobi_dynamic_library->GetFunction(&GRBgetdblattrarray, NAMEOF(GRBgetdblattrarray)); gurobi_dynamic_library->GetFunction(&GRBgetdblattrelement, NAMEOF(GRBgetdblattrelement)); gurobi_dynamic_library->GetFunction(&GRBgetdblparam, NAMEOF(GRBgetdblparam)); gurobi_dynamic_library->GetFunction(&GRBgetenv, NAMEOF(GRBgetenv)); gurobi_dynamic_library->GetFunction(&GRBgeterrormsg, NAMEOF(GRBgeterrormsg)); gurobi_dynamic_library->GetFunction(&GRBgetintattr, NAMEOF(GRBgetintattr)); gurobi_dynamic_library->GetFunction(&GRBgetintattrelement, NAMEOF(GRBgetintattrelement)); gurobi_dynamic_library->GetFunction(&GRBloadenv, NAMEOF(GRBloadenv)); gurobi_dynamic_library->GetFunction(&GRBnewmodel, NAMEOF(GRBnewmodel)); gurobi_dynamic_library->GetFunction(&GRBoptimize, NAMEOF(GRBoptimize)); gurobi_dynamic_library->GetFunction(&GRBreadparams, NAMEOF(GRBreadparams)); gurobi_dynamic_library->GetFunction(&GRBresetparams, NAMEOF(GRBresetparams)); gurobi_dynamic_library->GetFunction(&GRBsetcharattrelement, NAMEOF(GRBsetcharattrelement)); gurobi_dynamic_library->GetFunction(&GRBsetdblattr, NAMEOF(GRBsetdblattr)); gurobi_dynamic_library->GetFunction(&GRBsetdblattrelement, NAMEOF(GRBsetdblattrelement)); gurobi_dynamic_library->GetFunction(&GRBsetdblparam, NAMEOF(GRBsetdblparam)); gurobi_dynamic_library->GetFunction(&GRBsetintattr, NAMEOF(GRBsetintattr)); gurobi_dynamic_library->GetFunction(&GRBsetintparam, NAMEOF(GRBsetintparam)); gurobi_dynamic_library->GetFunction(&GRBterminate, NAMEOF(GRBterminate)); gurobi_dynamic_library->GetFunction(&GRBupdatemodel, NAMEOF(GRBupdatemodel)); gurobi_dynamic_library->GetFunction(&GRBversion, NAMEOF(GRBversion)); gurobi_dynamic_library->GetFunction(&GRBwrite, NAMEOF(GRBwrite)); gurobi_dynamic_library->GetFunction(&GRBcbget, NAMEOF(GRBcbget)); gurobi_dynamic_library->GetFunction(&GRBcbcut, NAMEOF(GRBcbcut)); gurobi_dynamic_library->GetFunction(&GRBcblazy, NAMEOF(GRBcblazy)); gurobi_dynamic_library->GetFunction(&GRBcbsolution, NAMEOF(GRBcbsolution)); gurobi_dynamic_library->GetFunction(&GRBaddconstr, NAMEOF(GRBaddconstr)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrIndicator, NAMEOF(GRBaddgenconstrIndicator)); gurobi_dynamic_library->GetFunction(&GRBsetintattrelement, NAMEOF(GRBsetintattrelement)); gurobi_dynamic_library->GetFunction(&GRBsetcallbackfunc, NAMEOF(GRBsetcallbackfunc)); gurobi_dynamic_library->GetFunction(&GRBsetparam, NAMEOF(GRBsetparam)); gurobi_dynamic_library->GetFunction(&GRBaddsos, NAMEOF(GRBaddsos)); gurobi_dynamic_library->GetFunction(&GRBaddqconstr, NAMEOF(GRBaddqconstr)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrMax, NAMEOF(GRBaddgenconstrMax)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrMin, NAMEOF(GRBaddgenconstrMin)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrAbs, NAMEOF(GRBaddgenconstrAbs)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrAnd, NAMEOF(GRBaddgenconstrAnd)); gurobi_dynamic_library->GetFunction(&GRBaddgenconstrOr, NAMEOF(GRBaddgenconstrOr)); gurobi_dynamic_library->GetFunction(&GRBaddqpterms, NAMEOF(GRBaddqpterms)); } bool LoadSpecificGurobiLibrary(const std::string& full_library_path) { CHECK(gurobi_dynamic_library.get() != nullptr); VLOG(1) << "Try to load from " << full_library_path; return gurobi_dynamic_library->TryToLoad(full_library_path); } namespace { const std::vector<std::vector<std::string>> GurobiVersionLib = { {"911", "91"}, {"910", "91"}, {"903", "90"}, {"902", "90"}}; } bool SearchForGurobiDynamicLibrary() { if (!gurobi_library_path.empty() && LoadSpecificGurobiLibrary(gurobi_library_path)) { return true; } const char* gurobi_home_from_env = getenv("GUROBI_HOME"); for (const std::vector<std::string>& version_lib : GurobiVersionLib) { const std::string& dir = version_lib[0]; const std::string& number = version_lib[1]; #if defined(_MSC_VER) // Windows if (gurobi_home_from_env != nullptr && LoadSpecificGurobiLibrary(absl::StrCat( gurobi_home_from_env, "\\bin\\gurobi", number, ".dll"))) { return true; } if (LoadSpecificGurobiLibrary( absl::StrCat("C:\\Program Files\\gurobi", dir, "\\win64\\bin\\gurobi", number, ".dll"))) { return true; } #elif defined(__APPLE__) // OS X if (gurobi_home_from_env != nullptr && LoadSpecificGurobiLibrary(absl::StrCat( gurobi_home_from_env, "/lib/libgurobi", number, ".dylib"))) { return true; } if (LoadSpecificGurobiLibrary(absl::StrCat( "/Library/gurobi", dir, "/mac64/lib/libgurobi", number, ".dylib"))) { return true; } #elif defined(__GNUC__) // Linux if (gurobi_home_from_env != nullptr && LoadSpecificGurobiLibrary(absl::StrCat( gurobi_home_from_env, "/lib/libgurobi", number, ".so"))) { return true; } if (gurobi_home_from_env != nullptr && LoadSpecificGurobiLibrary(absl::StrCat( gurobi_home_from_env, "/lib64/libgurobi", number, ".so"))) { return true; } #endif } return false; } bool MPSolver::LoadGurobiSharedLibrary() { if (gurobi_dynamic_library.get() != nullptr) { return gurobi_dynamic_library->LibraryIsLoaded(); } gurobi_dynamic_library.reset(new DynamicLibrary()); if (SearchForGurobiDynamicLibrary()) { LoadGurobiFunctions(); return true; } return false; } void MPSolver::SetGurobiLibraryPath(const std::string& full_library_path) { gurobi_library_path = full_library_path; } bool MPSolver::GurobiIsCorrectlyInstalled() { if (!LoadGurobiSharedLibrary()) return false; GRBenv* env; if (GRBloadenv(&env, nullptr) != 0 || env == nullptr) return false; GRBfreeenv(env); return true; } } // namespace operations_research
13,504
4,593
/* * Copyright Andrey Semashev 2007 - 2015. * 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 <string> #include <iostream> #include <stdexcept> #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/smart_ptr/make_shared_object.hpp> #include <boost/lexical_cast.hpp> #include <boost/phoenix.hpp> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/attributes/attribute_name.hpp> #include <boost/log/attributes/scoped_attribute.hpp> #include <boost/log/sources/logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/utility/value_ref.hpp> #include <boost/log/utility/formatting_ostream.hpp> #include <boost/log/utility/manipulators/add_value.hpp> #include <boost/log/utility/setup/filter_parser.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> namespace logging = boost::log; namespace attrs = boost::log::attributes; namespace src = boost::log::sources; namespace expr = boost::log::expressions; namespace sinks = boost::log::sinks; namespace keywords = boost::log::keywords; struct point { float m_x, m_y; point() : m_x(0.0f), m_y(0.0f) {} point(float x, float y) : m_x(x), m_y(y) {} }; bool operator== (point const& left, point const& right); bool operator!= (point const& left, point const& right); template< typename CharT, typename TraitsT > std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, point const& p); template< typename CharT, typename TraitsT > std::basic_istream< CharT, TraitsT >& operator>> (std::basic_istream< CharT, TraitsT >& strm, point& p); const float epsilon = 0.0001f; bool operator== (point const& left, point const& right) { return (left.m_x - epsilon <= right.m_x && left.m_x + epsilon >= right.m_x) && (left.m_y - epsilon <= right.m_y && left.m_y + epsilon >= right.m_y); } bool operator!= (point const& left, point const& right) { return !(left == right); } template< typename CharT, typename TraitsT > std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, point const& p) { if (strm.good()) strm << "(" << p.m_x << ", " << p.m_y << ")"; return strm; } template< typename CharT, typename TraitsT > std::basic_istream< CharT, TraitsT >& operator>> (std::basic_istream< CharT, TraitsT >& strm, point& p) { if (strm.good()) { CharT left_brace = static_cast< CharT >(0), comma = static_cast< CharT >(0), right_brace = static_cast< CharT >(0); strm.setf(std::ios_base::skipws); strm >> left_brace >> p.m_x >> comma >> p.m_y >> right_brace; if (left_brace != '(' || comma != ',' || right_brace != ')') strm.setstate(std::ios_base::failbit); } return strm; } //[ example_extension_filter_parser_rectangle_definition struct rectangle { point m_top_left, m_bottom_right; }; template< typename CharT, typename TraitsT > std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, rectangle const& r); template< typename CharT, typename TraitsT > std::basic_istream< CharT, TraitsT >& operator>> (std::basic_istream< CharT, TraitsT >& strm, rectangle& r); //] template< typename CharT, typename TraitsT > std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, rectangle const& r) { if (strm.good()) strm << "{" << r.m_top_left << " - " << r.m_bottom_right << "}"; return strm; } template< typename CharT, typename TraitsT > std::basic_istream< CharT, TraitsT >& operator>> (std::basic_istream< CharT, TraitsT >& strm, rectangle& r) { if (strm.good()) { CharT left_brace = static_cast< CharT >(0), dash = static_cast< CharT >(0), right_brace = static_cast< CharT >(0); strm.setf(std::ios_base::skipws); strm >> left_brace >> r.m_top_left >> dash >> r.m_bottom_right >> right_brace; if (left_brace != '{' || dash != '-' || right_brace != '}') strm.setstate(std::ios_base::failbit); } return strm; } //[ example_extension_custom_filter_factory_with_custom_rel // The function checks if the point is inside the rectangle bool is_in_rectangle(logging::value_ref< point > const& p, rectangle const& r) { if (p) { return p->m_x >= r.m_top_left.m_x && p->m_x <= r.m_bottom_right.m_x && p->m_y >= r.m_top_left.m_y && p->m_y <= r.m_bottom_right.m_y; } return false; } // Custom point filter factory class point_filter_factory : public logging::filter_factory< char > { public: logging::filter on_exists_test(logging::attribute_name const& name) { return expr::has_attr< point >(name); } logging::filter on_equality_relation(logging::attribute_name const& name, string_type const& arg) { return expr::attr< point >(name) == boost::lexical_cast< point >(arg); } logging::filter on_inequality_relation(logging::attribute_name const& name, string_type const& arg) { return expr::attr< point >(name) != boost::lexical_cast< point >(arg); } logging::filter on_custom_relation(logging::attribute_name const& name, string_type const& rel, string_type const& arg) { if (rel == "is_in_rectangle") { return boost::phoenix::bind(&is_in_rectangle, expr::attr< point >(name), boost::lexical_cast< rectangle >(arg)); } throw std::runtime_error("Unsupported filter relation: " + rel); } }; void init_factories() { //<- logging::register_simple_formatter_factory< point, char >("Coordinates"); //-> logging::register_filter_factory("Coordinates", boost::make_shared< point_filter_factory >()); } //] void init_logging() { init_factories(); logging::add_console_log ( std::clog, keywords::filter = "%Coordinates% is_in_rectangle \"{(0, 0) - (20, 20)}\"", keywords::format = "%TimeStamp% %Coordinates% %Message%" ); logging::add_common_attributes(); } int main(int, char*[]) { init_logging(); src::logger lg; // We have to use scoped attributes in order coordinates to be passed to filters { BOOST_LOG_SCOPED_LOGGER_TAG(lg, "Coordinates", point(10, 10)); BOOST_LOG(lg) << "Hello, world with coordinates (10, 10)!"; } { BOOST_LOG_SCOPED_LOGGER_TAG(lg, "Coordinates", point(50, 50)); BOOST_LOG(lg) << "Hello, world with coordinates (50, 50)!"; // this message will be suppressed by filter } return 0; }
6,712
2,387
// ********************************************************************************************************************* // Description: Stack Information // // Module: GSRoot // Namespace: GS // Contact person: MM // // SG compatible // ********************************************************************************************************************* #if !defined (STACKINFO_HPP) #define STACKINFO_HPP #pragma once // from GSRoot #include "Definitions.hpp" #if defined (WINDOWS) #include "IntelStackWalkWin.hpp" #endif #include "LoadedModuleListDefs.hpp" namespace StackInfoPrivate { GSROOT_DLL_EXPORT UInt32 CalculateStackHash (void* const addresses[], UInt32 MaxStackDepth, UInt32* pSigIndex); GSROOT_DLL_EXPORT UInt16 GetCallStack (Int32 ignoreDepth, UInt16 maxDepth, void* address[]); GSROOT_DLL_EXPORT void* RVAToVA (const LoadedModuleListDefs::RVAOrVA& rva); GSROOT_DLL_EXPORT GS::IntPtr GetCurrentUsageDebugInfo (); GSROOT_DLL_EXPORT UInt16 CaptureStackBackTr (Int32 ignoreDepth, UInt16 maxDepth, void* address[]); } // namespace StackInfoPrivate namespace GS { // --------------------------------------------------------------------------------------------------------------------- // StackInfo struct, saved into the allocated memory blocks // --------------------------------------------------------------------------------------------------------------------- template <UInt16 MaxCallDepth> class StackInfoCustomDepth { public: typedef UInt8 WalkType; enum WalkTypes { FastWalkRVA, // Store relative addresses, plus module IDs FastWalk, // Store absolute addresses DbgHelpWalk // Rely on dbghelp.dll's stack walk (absolute addresses) }; private: enum { Signature = 'STCK' }; union AddressReference { LoadedModuleListDefs::RVAOrVA rva; void* absoluteAddress; }; UInt32 signature; UInt16 depth; WalkType type; AddressReference addresses[MaxCallDepth]; GS::UIntPtr usageDebugInfo; public: explicit StackInfoCustomDepth (Int32 ignoreDepth = 0, UInt16 maxDepth = MaxCallDepth, WalkType walkType = FastWalk); bool IsValid () const { return signature == Signature; } UInt32 GetStackHashCode (UInt32* pSigIndex) const; UInt32 GetDepth () const { return depth; } void* GetAbsoluteAddress (Int32 i) const; GS::UIntPtr GetUsageDebugInfo () const { return usageDebugInfo; } }; typedef StackInfoCustomDepth<20> StackInfo; } // namespace GS // --------------------------------------------------------------------------------------------------------------------- // StackInfo class implementation // --------------------------------------------------------------------------------------------------------------------- template <UInt16 MaxCallDepth> GS::StackInfoCustomDepth<MaxCallDepth>::StackInfoCustomDepth (Int32 ignoreDepth, UInt16 maxDepth, WalkType walkType) : signature (Signature), depth (maxDepth), type (walkType) { memset (addresses, 0, sizeof addresses); usageDebugInfo = StackInfoPrivate::GetCurrentUsageDebugInfo (); if (maxDepth == 0) { return; } #if defined (WINDOWS) switch (type) { case FastWalkRVA: depth = GS::IntelStackWalk (nullptr, ignoreDepth, maxDepth, &addresses->rva, Relative); break; case FastWalk: depth = StackInfoPrivate::CaptureStackBackTr (ignoreDepth, maxDepth, &addresses->absoluteAddress); break; case DbgHelpWalk: depth = StackInfoPrivate::GetCallStack (ignoreDepth, maxDepth, &addresses->absoluteAddress); break; } #elif defined (macintosh) || defined (__linux__) UNUSED_PARAMETER (ignoreDepth); #endif } template <UInt16 MaxCallDepth> void* GS::StackInfoCustomDepth<MaxCallDepth>::GetAbsoluteAddress (Int32 i) const { return type == FastWalkRVA ? StackInfoPrivate::RVAToVA (addresses[i].rva) : addresses[i].absoluteAddress; } template <UInt16 MaxCallDepth> UInt32 GS::StackInfoCustomDepth<MaxCallDepth>::GetStackHashCode (UInt32* pSigIndex) const { if (type == FastWalkRVA) { void* absoluteAddresses[MaxCallDepth]; for (UInt32 i = 0; i < MaxCallDepth; ++i) absoluteAddresses[i] = StackInfoPrivate::RVAToVA (addresses[i].rva); return StackInfoPrivate::CalculateStackHash (absoluteAddresses, MaxCallDepth, pSigIndex); } else { return StackInfoPrivate::CalculateStackHash (&addresses->absoluteAddress, MaxCallDepth, pSigIndex); } } #endif
4,361
1,488
/** * Copyright 2017 M. Shulhan (ms@kilabit.info). All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "DNSRecordType.hh" namespace vos { const char* DNSRecordType::__cname = "DNSRecordType"; const int DNSRecordType::SIZE = 22; const char* DNSRecordType::NAMES[DNSRecordType::SIZE] = { "A" ,"NS" ,"MD" ,"MF", "CNAME" , "SOA" ,"MB" ,"MG" ,"MR", "NULL" , "WKS" ,"PTR" ,"HINFO","MINFO","MX" , "TXT" ,"AAAA" ,"SRV" ,"AXFR" ,"MAILB" , "MAILA" ,"*" }; const int DNSRecordType::VALUES[DNSRecordType::SIZE] = { 1 ,2 ,3 ,4 ,5 , 6 ,7 ,8 ,9 ,10 , 11 ,12 ,13 ,14 ,15 , 16 ,28 ,33 ,252 ,253 , 254 ,255 }; DNSRecordType::DNSRecordType() : Object() {} DNSRecordType::~DNSRecordType() {} /** * `GET_NAME()` will search list of record type with value is `type` and * return their NAME representation. * * It will return NULL if no match found. */ const char* DNSRecordType::GET_NAME(const int type) { int x = 0; for (; x < SIZE; x++) { if (VALUES[x] == type) { return NAMES[x]; } } return NULL; } /** * `GET_VALUE()` will search list of record type that match with `name` and * return their TYPE representation. * * It will return -1 if no match found. */ int DNSRecordType::GET_VALUE(const char* name) { int x = 0; for (; x < SIZE; x++) { if (strcasecmp(NAMES[x], name) == 0) { return VALUES[x]; } } return -1; } }
1,447
657
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "nsal.h" #include "xtitle_service.h" NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_BEGIN template<typename T> void add_endpoint_helper( _In_ std::vector<T>& endpoints, _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ nsal_host_name_type hostNameType, _In_ int port, _In_ const string_t& path, _In_ const string_t& relyingParty, _In_ const string_t& subRelyingParty, _In_ const string_t& tokenType, _In_ int signaturePolicyIndex) { // First check if there's already a match nsal_endpoint_info newInfo(relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); for (auto endpoint = endpoints.begin(); endpoint != endpoints.end(); endpoint++) { if (endpoint->is_same(protocol, hostName, port)) { nsal_endpoint_info existingInfo; if (endpoint->get_info_for_exact_path(path, existingInfo)) { // The endpoint already exists, make sure all the info about it matches if (existingInfo == newInfo) { return; } else { throw std::runtime_error("endpoints conflict"); } } else { // The specific path does not exist so add it endpoint->add_info(path, newInfo); return; } } } // No matching endpoints so we create a new one. endpoints.emplace_back(protocol, hostName, hostNameType, port); endpoints.back().add_info(path, newInfo); } void nsal::add_endpoint( _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ nsal_host_name_type hostNameType, _In_ int port, _In_ const string_t& path, _In_ const string_t& relyingParty, _In_ const string_t& subRelyingParty, _In_ const string_t& tokenType, _In_ int signaturePolicyIndex) { switch (hostNameType) { case nsal_host_name_type::fqdn: add_endpoint_helper<fqdn_nsal_endpoint>( m_fqdnEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::wildcard: add_endpoint_helper<wildcard_nsal_endpoint>( m_wildcardEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::ip: add_endpoint_helper<ip_nsal_endpoint>( m_ipEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; case nsal_host_name_type::cidr: add_endpoint_helper<cidr_nsal_endpoint>( m_cidrEndpoints, protocol, hostName, hostNameType, port, path, relyingParty, subRelyingParty, tokenType, signaturePolicyIndex); break; default: throw std::runtime_error("unsupported host name type"); } } template<typename TEndpoint, typename THostName> bool get_helper( _In_ const std::vector<TEndpoint>& endpoints, _In_ nsal_protocol protocol, _In_ const THostName& hostName, _In_ int port, _In_ const string_t& path, _Out_ nsal_endpoint_info& info) { for (auto endpoint = endpoints.begin(); endpoint != endpoints.end(); endpoint++) { if (endpoint->is_match(protocol, hostName, port)) { return endpoint->get_info(path, info); } } return false; } bool nsal::get_endpoint( _In_ web::http::uri& uri, _Out_ nsal_endpoint_info& info) const { nsal_protocol protocol = nsal::deserialize_protocol(uri.scheme()); int port = nsal::get_port(protocol, uri.port()); return get_endpoint(protocol, uri.host(), port, uri.path(), info); } bool nsal::get_endpoint( _In_ nsal_protocol protocol, _In_ const string_t& hostName, _In_ int port, _In_ const string_t& path, _Out_ nsal_endpoint_info& info) const { string_t hostNameWithoutEnv = hostName; string_t dnet = _T(".dnet"); size_t f = hostNameWithoutEnv.find(dnet); if ( f != string_t::npos ) { hostNameWithoutEnv.replace(f, dnet.length(), _T("")); } ip_address ipAddr; if (ip_address::try_parse(hostNameWithoutEnv, ipAddr)) { if (get_helper(m_ipEndpoints, protocol, ipAddr, port, path, info)) { return true; } if (get_helper(m_cidrEndpoints, protocol, ipAddr, port, path, info)) { return true; } } else { if (get_helper(m_fqdnEndpoints, protocol, hostNameWithoutEnv, port, path, info)) { return true; } if (get_helper(m_wildcardEndpoints, protocol, hostNameWithoutEnv, port, path, info)) { return true; } } return false; } void nsal::add_signature_policy(_In_ const signature_policy& signaturePolicy) { m_signaturePolicies.push_back(signaturePolicy); } const signature_policy& nsal::get_signature_policy(_In_ int index) const { return m_signaturePolicies[index]; } nsal_protocol nsal::deserialize_protocol(_In_ const utility::string_t& str) { if (_T("https") == str) return nsal_protocol::https; if (_T("http") == str) return nsal_protocol::http; if (_T("tcp") == str) return nsal_protocol::tcp; if (_T("udp") == str) return nsal_protocol::udp; if (_T("wss") == str) return nsal_protocol::wss; throw web::json::json_exception(_T("Invalid protocol for NSAL endpoint")); } nsal_host_name_type nsal::deserialize_host_name_type(_In_ const utility::string_t& str) { if (_T("fqdn") == str) return nsal_host_name_type::fqdn; if (_T("wildcard") == str) return nsal_host_name_type::wildcard; if (_T("ip") == str) return nsal_host_name_type::ip; if (_T("cidr") == str) return nsal_host_name_type::cidr; throw web::json::json_exception(_T("Invalid NSAL host name type")); } int nsal::deserialize_port(_In_ nsal_protocol protocol, _In_ const web::json::value& json) { int port = utils::extract_json_int(json, _T("Port"), false, 0); return nsal::get_port(protocol, port); } int nsal::get_port( _In_ nsal_protocol protocol, _In_ int port ) { if (port == 0) { switch (protocol) { case nsal_protocol::https: return 443; case nsal_protocol::http: case nsal_protocol::wss: return 80; default: throw web::json::json_exception(_T("Must specify port when protocol is not http or https")); } } return port; } void nsal::deserialize_endpoint( _In_ nsal& nsal, _In_ const web::json::value& endpoint) { utility::string_t relyingParty(utils::extract_json_string(endpoint, _T("RelyingParty"))); if (relyingParty.empty()) { // If there's no RP, we don't care since there's no token to attach return; } utility::string_t subRelyingParty(utils::extract_json_string(endpoint, _T("SubRelyingParty"))); nsal_protocol protocol(nsal::deserialize_protocol(utils::extract_json_string(endpoint, _T("Protocol"), true))); nsal_host_name_type hostNameType(deserialize_host_name_type(utils::extract_json_string(endpoint, _T("HostType"), true))); int port = deserialize_port(protocol, endpoint); nsal.add_endpoint( protocol, utils::extract_json_string(endpoint, _T("Host"), true), hostNameType, port, utils::extract_json_string(endpoint, _T("Path")), relyingParty, subRelyingParty, utils::extract_json_string(endpoint, _T("TokenType"), true), utils::extract_json_int(endpoint, _T("SignaturePolicyIndex"), false, -1)); } void nsal::deserialize_signature_policy(_In_ nsal& nsal, _In_ const web::json::value& json) { std::error_code errc = xbox_live_error_code::no_error; int version = utils::extract_json_int(json, _T("Version"), true); int maxBodyBytes = utils::extract_json_int(json, _T("MaxBodyBytes"), true); std::vector<string_t> extraHeaders( utils::extract_json_vector<string_t>(utils::json_string_extractor, json, _T("ExtraHeaders"), errc, false)); nsal.add_signature_policy(signature_policy(version, maxBodyBytes, extraHeaders)); } nsal nsal::deserialize(_In_ const web::json::value& json) { nsal nsal; auto& jsonObj(json.as_object()); auto it = jsonObj.find(_T("SignaturePolicies")); if (it != jsonObj.end()) { web::json::array signaturePolicies(it->second.as_array()); for (auto it2 = signaturePolicies.begin(); it2 != signaturePolicies.end(); ++it2) { deserialize_signature_policy(nsal, *it2); } } it = jsonObj.find(_T("EndPoints")); if (it != jsonObj.end()) { web::json::array endpoints(it->second.as_array()); for (auto it2 = endpoints.begin(); it2 != endpoints.end(); ++it2) { deserialize_endpoint(nsal, *it2); } } nsal.add_endpoint( nsal_protocol::wss, _T("*.xboxlive.com"), nsal_host_name_type::wildcard, 80, string_t(), _T("http://xboxlive.com"), string_t(), _T("JWT"), 0 ); nsal._Sort_wildcard_endpoints(); return nsal; } void nsal::_Sort_wildcard_endpoints() { std::sort( m_wildcardEndpoints.begin(), m_wildcardEndpoints.end(), [](_In_ const wildcard_nsal_endpoint& lhs, _In_ const wildcard_nsal_endpoint& rhs) -> bool { return lhs.length() > rhs.length(); }); } NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_END
10,584
3,481
/* -*-C-*- ******************************************************************************** * * File: seam.c (Formerly seam.c) * Description: * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Fri May 17 16:30:13 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** 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. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "seam.h" #include "callcpp.h" #include "structures.h" #include "makechop.h" #ifdef __UNIX__ #include <assert.h> #endif /*---------------------------------------------------------------------- V a r i a b l e s ----------------------------------------------------------------------*/ #define NUM_STARTING_SEAMS 20 #define SEAMBLOCK 100 /* Cells per block */ makestructure (newseam, free_seam, printseam, SEAM, freeseam, SEAMBLOCK, "SEAM", seamcount); /*---------------------------------------------------------------------- Public Function Code ----------------------------------------------------------------------*/ /** * @name point_in_split * * Check to see if either of these points are present in the current * split. * @returns TRUE if one of them is split. */ bool point_in_split(SPLIT *split, EDGEPT *point1, EDGEPT *point2) { return ((split) ? ((exact_point (split->point1, point1) || exact_point (split->point1, point2) || exact_point (split->point2, point1) || exact_point (split->point2, point2)) ? TRUE : FALSE) : FALSE); } /** * @name point_in_seam * * Check to see if either of these points are present in the current * seam. * @returns TRUE if one of them is. */ bool point_in_seam(SEAM *seam, SPLIT *split) { return (point_in_split (seam->split1, split->point1, split->point2) || point_in_split (seam->split2, split->point1, split->point2) || point_in_split (seam->split3, split->point1, split->point2)); } /** * @name add_seam * * Add another seam to a collection of seams. */ SEAMS add_seam(SEAMS seam_list, SEAM *seam) { return (array_push (seam_list, seam)); } /** * @name combine_seam * * Combine two seam records into a single seam. Move the split * references from the second seam to the first one. The argument * convention is patterned after strcpy. */ void combine_seams(SEAM *dest_seam, SEAM *source_seam) { dest_seam->priority += source_seam->priority; dest_seam->location += source_seam->location; dest_seam->location /= 2; if (source_seam->split1) { if (!dest_seam->split1) dest_seam->split1 = source_seam->split1; else if (!dest_seam->split2) dest_seam->split2 = source_seam->split1; else if (!dest_seam->split3) dest_seam->split3 = source_seam->split1; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } if (source_seam->split2) { if (!dest_seam->split2) dest_seam->split2 = source_seam->split2; else if (!dest_seam->split3) dest_seam->split3 = source_seam->split2; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } if (source_seam->split3) { if (!dest_seam->split3) dest_seam->split3 = source_seam->split3; else cprintf ("combine_seam: Seam is too crowded, can't be combined !\n"); } free_seam(source_seam); } /** * @name delete_seam * * Free this seam record and the splits that are attached to it. */ void delete_seam(void *arg) { //SEAM *seam) SEAM *seam = (SEAM *) arg; if (seam) { if (seam->split1) delete_split (seam->split1); if (seam->split2) delete_split (seam->split2); if (seam->split3) delete_split (seam->split3); free_seam(seam); } } /** * @name free_seam_list * * Free all the seams that have been allocated in this list. Reclaim * the memory for each of the splits as well. */ void free_seam_list(SEAMS seam_list) { int x; array_loop (seam_list, x) delete_seam (array_value (seam_list, x)); array_free(seam_list); } /** * @name test_insert_seam * * @returns true if insert_seam will succeed. */ bool test_insert_seam(SEAMS seam_list, int index, TBLOB *left_blob, TBLOB *first_blob) { SEAM *test_seam; TBLOB *blob; int test_index; int list_length; list_length = array_count (seam_list); for (test_index = 0, blob = first_blob->next; test_index < index; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index + test_seam->widthp < index && test_seam->widthp + test_index == index - 1 && account_splits_right(test_seam, blob) < 0) return false; } for (test_index = index, blob = left_blob->next; test_index < list_length; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index - test_seam->widthn >= index && test_index - test_seam->widthn == index && account_splits_left(test_seam, first_blob, blob) < 0) return false; } return true; } /** * @name insert_seam * * Add another seam to a collection of seams at a particular location * in the seam array. */ SEAMS insert_seam(SEAMS seam_list, int index, SEAM *seam, TBLOB *left_blob, TBLOB *first_blob) { SEAM *test_seam; TBLOB *blob; int test_index; int list_length; list_length = array_count (seam_list); for (test_index = 0, blob = first_blob->next; test_index < index; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index + test_seam->widthp >= index) { test_seam->widthp++; /*got in the way */ } else if (test_seam->widthp + test_index == index - 1) { test_seam->widthp = account_splits_right(test_seam, blob); if (test_seam->widthp < 0) { cprintf ("Failed to find any right blob for a split!\n"); print_seam("New dud seam", seam); print_seam("Failed seam", test_seam); } } } for (test_index = index, blob = left_blob->next; test_index < list_length; test_index++, blob = blob->next) { test_seam = (SEAM *) array_value (seam_list, test_index); if (test_index - test_seam->widthn < index) { test_seam->widthn++; /*got in the way */ } else if (test_index - test_seam->widthn == index) { test_seam->widthn = account_splits_left(test_seam, first_blob, blob); if (test_seam->widthn < 0) { cprintf ("Failed to find any left blob for a split!\n"); print_seam("New dud seam", seam); print_seam("Failed seam", test_seam); } } } return (array_insert (seam_list, index, seam)); } /** * @name account_splits_right * * Account for all the splits by looking to the right. * in the blob list. */ int account_splits_right(SEAM *seam, TBLOB *blob) { inT8 found_em[3]; inT8 width; found_em[0] = seam->split1 == NULL; found_em[1] = seam->split2 == NULL; found_em[2] = seam->split3 == NULL; if (found_em[0] && found_em[1] && found_em[2]) return 0; width = 0; do { if (!found_em[0]) found_em[0] = find_split_in_blob (seam->split1, blob); if (!found_em[1]) found_em[1] = find_split_in_blob (seam->split2, blob); if (!found_em[2]) found_em[2] = find_split_in_blob (seam->split3, blob); if (found_em[0] && found_em[1] && found_em[2]) { return width; } width++; blob = blob->next; } while (blob != NULL); return -1; } /** * @name account_splits_left * * Account for all the splits by looking to the left. * in the blob list. */ int account_splits_left(SEAM *seam, TBLOB *blob, TBLOB *end_blob) { static inT32 depth = 0; static inT8 width; static inT8 found_em[3]; if (blob != end_blob) { depth++; account_splits_left (seam, blob->next, end_blob); depth--; } else { found_em[0] = seam->split1 == NULL; found_em[1] = seam->split2 == NULL; found_em[2] = seam->split3 == NULL; width = 0; } if (!found_em[0]) found_em[0] = find_split_in_blob (seam->split1, blob); if (!found_em[1]) found_em[1] = find_split_in_blob (seam->split2, blob); if (!found_em[2]) found_em[2] = find_split_in_blob (seam->split3, blob); if (!found_em[0] || !found_em[1] || !found_em[2]) { width++; if (depth == 0) { width = -1; } } return width; } /** * @name find_split_in_blob * * @returns TRUE if the split is somewhere in this blob. */ bool find_split_in_blob(SPLIT *split, TBLOB *blob) { TESSLINE *outline; #if 0 for (outline = blob->outlines; outline != NULL; outline = outline->next) if (is_split_outline (outline, split)) return TRUE; return FALSE; #endif for (outline = blob->outlines; outline != NULL; outline = outline->next) if (point_in_outline(split->point1, outline)) break; if (outline == NULL) return FALSE; for (outline = blob->outlines; outline != NULL; outline = outline->next) if (point_in_outline(split->point2, outline)) return TRUE; return FALSE; } /** * @name join_two_seams * * Merge these two seams into a new seam. Duplicate the split records * in both of the input seams. Return the resultant seam. */ SEAM *join_two_seams(SEAM *seam1, SEAM *seam2) { SEAM *result = NULL; SEAM *temp; assert(seam1 &&seam2); if (((seam1->split3 == NULL && seam2->split2 == NULL) || (seam1->split2 == NULL && seam2->split3 == NULL) || seam1->split1 == NULL || seam2->split1 == NULL) && (!shared_split_points (seam1, seam2))) { clone_seam(result, seam1); clone_seam(temp, seam2); combine_seams(result, temp); } return (result); } /** * @name new_seam * * Create a structure for a "seam" between two blobs. This data * structure may actually hold up to three different splits. * Initailization of this record is done by this routine. */ SEAM *new_seam(PRIORITY priority, int x_location, SPLIT *split1, SPLIT *split2, SPLIT *split3) { SEAM *seam; seam = newseam (); seam->priority = priority; seam->location = x_location; seam->widthp = 0; seam->widthn = 0; seam->split1 = split1; seam->split2 = split2; seam->split3 = split3; return (seam); } /** * @name new_seam_list * * Create a collection of seam records in an array. */ SEAMS new_seam_list() { return (array_new (NUM_STARTING_SEAMS)); } /** * @name print_seam * * Print a list of splits. Show the coordinates of both points in * each split. */ void print_seam(const char *label, SEAM *seam) { if (seam) { cprintf(label); cprintf (" %6.2f @ %5d, p=%d, n=%d ", seam->priority, seam->location, seam->widthp, seam->widthn); print_split (seam->split1); if (seam->split2) { cprintf (", "); print_split (seam->split2); if (seam->split3) { cprintf (", "); print_split (seam->split3); } } cprintf ("\n"); } } /** * @name print_seams * * Print a list of splits. Show the coordinates of both points in * each split. */ void print_seams(const char *label, SEAMS seams) { int x; char number[CHARS_PER_LINE]; if (seams) { cprintf ("%s\n", label); array_loop(seams, x) { sprintf (number, "%2d: ", x); print_seam (number, (SEAM *) array_value (seams, x)); } cprintf ("\n"); } } /** * @name shared_split_points * * Check these two seams to make sure that neither of them have two * points in common. Return TRUE if any of the same points are present * in any of the splits of both seams. */ int shared_split_points(SEAM *seam1, SEAM *seam2) { if (seam1 == NULL || seam2 == NULL) return (FALSE); if (seam2->split1 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split1)) return (TRUE); if (seam2->split2 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split2)) return (TRUE); if (seam2->split3 == NULL) return (FALSE); if (point_in_seam (seam1, seam2->split3)) return (TRUE); return (FALSE); }
13,043
4,740
/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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. =========================================================================*/ #ifndef __tubeTreeFilters_hxx #define __tubeTreeFilters_hxx #include "itkNumericTraits.h" namespace tube { //------------------------------------------------------------------------ template< unsigned int VDimension > void TreeFilters< VDimension >:: FillGap( typename TubeGroupType::Pointer & pTubeGroup, char InterpolationMethod ) { char tubeName[] = "Tube"; TubeListPointerType pTubeList = pTubeGroup->GetChildren( pTubeGroup->GetMaximumDepth(), tubeName ); for( typename TubeGroupType::ChildrenListType::iterator itSourceTubes = pTubeList->begin(); itSourceTubes != pTubeList->end(); ++itSourceTubes ) { TubePointerType pCurTube = dynamic_cast< TubeType * >( itSourceTubes->GetPointer() ); TubeIdType curParentTubeId = pCurTube->GetParentId(); TubePointType* parentNearestPoint = NULL; if( pCurTube->GetRoot() == false && curParentTubeId != pTubeGroup->GetId() ) { //find parent target tube for( typename TubeGroupType::ChildrenListType::iterator itTubes = pTubeList->begin(); itTubes != pTubeList->end(); ++itTubes ) { TubePointerType pTube = dynamic_cast< TubeType * >( itTubes->GetPointer() ); if( pTube->GetId() == curParentTubeId ) { double minDistance = itk::NumericTraits<double>::max(); int flag =-1; for( unsigned int index = 0; index < pTube->GetNumberOfPoints(); ++index ) { TubePointType* tubePoint = dynamic_cast< TubePointType* >( pTube->GetPoint( index ) ); PositionType tubePointPosition = tubePoint->GetPosition(); double distance = tubePointPosition.SquaredEuclideanDistanceTo( pCurTube->GetPoint( 0 )->GetPosition() ); if( minDistance > distance ) { minDistance = distance; parentNearestPoint = tubePoint; flag = 1; } distance = tubePointPosition.SquaredEuclideanDistanceTo( pCurTube->GetPoint( pCurTube->GetNumberOfPoints() - 1 ) ->GetPosition() ); if( minDistance > distance ) { minDistance = distance; parentNearestPoint = tubePoint; flag = 2; } } TubePointListType newTubePoints; if( flag == 1 ) { TubePointType* childTubeStartPoint = dynamic_cast< TubePointType* >( pCurTube->GetPoint( 0 ) ); InterpolatePath( parentNearestPoint, childTubeStartPoint, newTubePoints, InterpolationMethod ); TubePointListType targetTubePoints = pCurTube->GetPoints(); pCurTube->Clear(); for( unsigned int index = 0; index < newTubePoints.size(); ++index ) { pCurTube->GetPoints().push_back( newTubePoints[ index ] ); } for( unsigned int i = 0; i < targetTubePoints.size(); ++i ) { pCurTube->GetPoints().push_back( targetTubePoints[ i ] ); } } if( flag == 2 ) { TubePointType* childTubeEndPoint = dynamic_cast< TubePointType* > ( pCurTube->GetPoint( pCurTube->GetNumberOfPoints() - 1 ) ); InterpolatePath( parentNearestPoint, childTubeEndPoint, newTubePoints, InterpolationMethod ); for( int index = newTubePoints.size() - 1; index >= 0; index-- ) { pCurTube->GetPoints().push_back( newTubePoints[ index ] ); } } break; } } } } } //------------------------------------------------------------------------ template< unsigned int VDimension > void TreeFilters< VDimension >:: InterpolatePath( typename TubeType::TubePointType * parentNearestPoint, typename TubeType::TubePointType * itkNotUsed( childEndPoint ), typename TubeType::PointListType & newTubePoints, char InterpolationMethod ) { if( InterpolationMethod == 'S' ) { newTubePoints.push_back( *parentNearestPoint ); } return; } } // End namespace tube #endif // End !defined( __tubeTreeFilters_hxx )
5,081
1,441
#include <vcpkg-test/catch.h> #include <vcpkg-test/util.h> #include <vcpkg/dependencies.h> #include <vcpkg/sourceparagraph.h> #include <vcpkg/triplet.h> #include <memory> #include <unordered_map> #include <vector> using namespace vcpkg; using Test::make_status_feature_pgh; using Test::make_status_pgh; using Test::unsafe_pspec; static std::unique_ptr<SourceControlFile> make_control_file( const char* name, const char* depends, const std::vector<std::pair<const char*, const char*>>& features = {}, const std::vector<const char*>& default_features = {}) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<Pgh> scf_pghs; scf_pghs.push_back(Pgh{{"Source", name}, {"Version", "0"}, {"Build-Depends", depends}, {"Default-Features", Strings::join(", ", default_features)}}); for (auto&& feature : features) { scf_pghs.push_back(Pgh{ {"Feature", feature.first}, {"Description", "feature"}, {"Build-Depends", feature.second}, }); } auto m_pgh = vcpkg::SourceControlFile::parse_control_file(std::move(scf_pghs)); REQUIRE(m_pgh.has_value()); return std::move(*m_pgh.get()); } /// <summary> /// Assert that the given action an install of given features from given package. /// </summary> static void features_check(Dependencies::AnyAction& install_action, std::string pkg_name, std::vector<std::string> vec, const Triplet& triplet = Triplet::X86_WINDOWS) { REQUIRE(install_action.install_action.has_value()); const auto& plan = install_action.install_action.value_or_exit(VCPKG_LINE_INFO); const auto& feature_list = plan.feature_list; REQUIRE(plan.spec.triplet().to_string() == triplet.to_string()); auto& scfl = *plan.source_control_file_location.get(); REQUIRE(pkg_name == scfl.source_control_file->core_paragraph->name); REQUIRE(feature_list.size() == vec.size()); for (auto&& feature_name : vec) { // TODO: see if this can be simplified if (feature_name == "core" || feature_name == "") { REQUIRE((Util::find(feature_list, "core") != feature_list.end() || Util::find(feature_list, "") != feature_list.end())); continue; } REQUIRE(Util::find(feature_list, feature_name) != feature_list.end()); } } /// <summary> /// Assert that the given action is a remove of given package. /// </summary> static void remove_plan_check(Dependencies::AnyAction& remove_action, std::string pkg_name, const Triplet& triplet = Triplet::X86_WINDOWS) { const auto& plan = remove_action.remove_action.value_or_exit(VCPKG_LINE_INFO); REQUIRE(plan.spec.triplet().to_string() == triplet.to_string()); REQUIRE(pkg_name == plan.spec.name()); } /// <summary> /// Map of source control files by their package name. /// </summary> struct PackageSpecMap { std::unordered_map<std::string, SourceControlFileLocation> map; Triplet triplet; PackageSpecMap(const Triplet& t = Triplet::X86_WINDOWS) noexcept { triplet = t; } PackageSpec emplace(const char* name, const char* depends = "", const std::vector<std::pair<const char*, const char*>>& features = {}, const std::vector<const char*>& default_features = {}) { auto scfl = SourceControlFileLocation{make_control_file(name, depends, features, default_features), ""}; return emplace(std::move(scfl)); } PackageSpec emplace(vcpkg::SourceControlFileLocation&& scfl) { auto spec = PackageSpec::from_name_and_triplet(scfl.source_control_file->core_paragraph->name, triplet); REQUIRE(spec.has_value()); map.emplace(scfl.source_control_file->core_paragraph->name, std::move(scfl)); return PackageSpec{*spec.get()}; } }; TEST_CASE ("basic install scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "b"); auto spec_b = spec_map.emplace("b", "c"); auto spec_c = spec_map.emplace("c"); Dependencies::MapPortFileProvider map_port(spec_map.map); auto install_plan = Dependencies::create_feature_install_plan( map_port, {FeatureSpec{spec_a, ""}}, StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 3); REQUIRE(install_plan.at(0).spec().name() == "c"); REQUIRE(install_plan.at(1).spec().name() == "b"); REQUIRE(install_plan.at(2).spec().name() == "a"); } TEST_CASE ("multiple install scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "d"); auto spec_b = spec_map.emplace("b", "d, e"); auto spec_c = spec_map.emplace("c", "e, h"); auto spec_d = spec_map.emplace("d", "f, g, h"); auto spec_e = spec_map.emplace("e", "g"); auto spec_f = spec_map.emplace("f"); auto spec_g = spec_map.emplace("g"); auto spec_h = spec_map.emplace("h"); Dependencies::MapPortFileProvider map_port(spec_map.map); auto install_plan = Dependencies::create_feature_install_plan( map_port, {FeatureSpec{spec_a, ""}, FeatureSpec{spec_b, ""}, FeatureSpec{spec_c, ""}}, StatusParagraphs(std::move(status_paragraphs))); auto iterator_pos = [&](const PackageSpec& spec) { auto it = std::find_if(install_plan.begin(), install_plan.end(), [&](auto& action) { return action.spec() == spec; }); REQUIRE(it != install_plan.end()); return it - install_plan.begin(); }; const auto a_pos = iterator_pos(spec_a); const auto b_pos = iterator_pos(spec_b); const auto c_pos = iterator_pos(spec_c); const auto d_pos = iterator_pos(spec_d); const auto e_pos = iterator_pos(spec_e); const auto f_pos = iterator_pos(spec_f); const auto g_pos = iterator_pos(spec_g); const auto h_pos = iterator_pos(spec_h); REQUIRE(a_pos > d_pos); REQUIRE(b_pos > e_pos); REQUIRE(b_pos > d_pos); REQUIRE(c_pos > e_pos); REQUIRE(c_pos > h_pos); REQUIRE(d_pos > f_pos); REQUIRE(d_pos > g_pos); REQUIRE(d_pos > h_pos); REQUIRE(e_pos > g_pos); } TEST_CASE ("existing package scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(vcpkg::Test::make_status_pgh("a")); PackageSpecMap spec_map; auto spec_a = FullPackageSpec{spec_map.emplace("a")}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({spec_a}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 1); const auto p = install_plan.at(0).install_action.get(); REQUIRE(p); REQUIRE(p->spec.name() == "a"); REQUIRE(p->plan_type == Dependencies::InstallPlanType::ALREADY_INSTALLED); REQUIRE(p->request_type == Dependencies::RequestType::USER_REQUESTED); } TEST_CASE ("user requested package scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map; const auto spec_a = FullPackageSpec{spec_map.emplace("a", "b")}; const auto spec_b = FullPackageSpec{spec_map.emplace("b")}; const auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({spec_a}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 2); const auto p = install_plan.at(0).install_action.get(); REQUIRE(p); REQUIRE(p->spec.name() == "b"); REQUIRE(p->plan_type == Dependencies::InstallPlanType::BUILD_AND_INSTALL); REQUIRE(p->request_type == Dependencies::RequestType::AUTO_SELECTED); const auto p2 = install_plan.at(1).install_action.get(); REQUIRE(p2); REQUIRE(p2->spec.name() == "a"); REQUIRE(p2->plan_type == Dependencies::InstallPlanType::BUILD_AND_INSTALL); REQUIRE(p2->request_type == Dependencies::RequestType::USER_REQUESTED); } TEST_CASE ("long install scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("j", "k")); status_paragraphs.push_back(make_status_pgh("k")); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "b, c, d, e, f, g, h, j, k"); auto spec_b = spec_map.emplace("b", "c, d, e, f, g, h, j, k"); auto spec_c = spec_map.emplace("c", "d, e, f, g, h, j, k"); auto spec_d = spec_map.emplace("d", "e, f, g, h, j, k"); auto spec_e = spec_map.emplace("e", "f, g, h, j, k"); auto spec_f = spec_map.emplace("f", "g, h, j, k"); auto spec_g = spec_map.emplace("g", "h, j, k"); auto spec_h = spec_map.emplace("h", "j, k"); auto spec_j = spec_map.emplace("j", "k"); auto spec_k = spec_map.emplace("k"); Dependencies::MapPortFileProvider map_port(spec_map.map); auto install_plan = Dependencies::create_feature_install_plan( map_port, {FeatureSpec{spec_a, ""}}, StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 8); REQUIRE(install_plan.at(0).spec().name() == "h"); REQUIRE(install_plan.at(1).spec().name() == "g"); REQUIRE(install_plan.at(2).spec().name() == "f"); REQUIRE(install_plan.at(3).spec().name() == "e"); REQUIRE(install_plan.at(4).spec().name() == "d"); REQUIRE(install_plan.at(5).spec().name() == "c"); REQUIRE(install_plan.at(6).spec().name() == "b"); REQUIRE(install_plan.at(7).spec().name() == "a"); } TEST_CASE ("basic feature test 1", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("a", "b, b[b1]")); status_paragraphs.push_back(make_status_pgh("b")); status_paragraphs.push_back(make_status_feature_pgh("b", "b1")); PackageSpecMap spec_map; auto spec_a = FullPackageSpec{spec_map.emplace("a", "b, b[b1]", {{"a1", "b[b2]"}}), {"a1"}}; auto spec_b = FullPackageSpec{spec_map.emplace("b", "", {{"b1", ""}, {"b2", ""}, {"b3", ""}})}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({spec_a}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 4); remove_plan_check(install_plan.at(0), "a"); remove_plan_check(install_plan.at(1), "b"); features_check(install_plan.at(2), "b", {"b1", "core", "b1"}); features_check(install_plan.at(3), "a", {"a1", "core"}); } TEST_CASE ("basic feature test 2", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map; auto spec_a = FullPackageSpec{spec_map.emplace("a", "b[b1]", {{"a1", "b[b2]"}}), {"a1"}}; auto spec_b = FullPackageSpec{spec_map.emplace("b", "", {{"b1", ""}, {"b2", ""}, {"b3", ""}})}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({spec_a}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 2); features_check(install_plan.at(0), "b", {"b1", "b2", "core"}); features_check(install_plan.at(1), "a", {"a1", "core"}); } TEST_CASE ("basic feature test 3", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("a")); PackageSpecMap spec_map; auto spec_a = FullPackageSpec{spec_map.emplace("a", "b", {{"a1", ""}}), {"core"}}; auto spec_b = FullPackageSpec{spec_map.emplace("b")}; auto spec_c = FullPackageSpec{spec_map.emplace("c", "a[a1]"), {"core"}}; auto install_plan = Dependencies::create_feature_install_plan(spec_map.map, FullPackageSpec::to_feature_specs({spec_c, spec_a}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 4); remove_plan_check(install_plan.at(0), "a"); features_check(install_plan.at(1), "b", {"core"}); features_check(install_plan.at(2), "a", {"a1", "core"}); features_check(install_plan.at(3), "c", {"core"}); } TEST_CASE ("basic feature test 4", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("a")); status_paragraphs.push_back(make_status_feature_pgh("a", "a1", "")); PackageSpecMap spec_map; auto spec_a = FullPackageSpec{spec_map.emplace("a", "b", {{"a1", ""}})}; auto spec_b = FullPackageSpec{spec_map.emplace("b")}; auto spec_c = FullPackageSpec{spec_map.emplace("c", "a[a1]"), {"core"}}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({spec_c}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 1); features_check(install_plan.at(0), "c", {"core"}); } TEST_CASE ("basic feature test 5", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map; auto spec_a = FullPackageSpec{spec_map.emplace("a", "", {{"a1", "b[b1]"}, {"a2", "b[b2]"}, {"a3", "a[a2]"}}), {"a3"}}; auto spec_b = FullPackageSpec{spec_map.emplace("b", "", {{"b1", ""}, {"b2", ""}})}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({spec_a}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 2); features_check(install_plan.at(0), "b", {"core", "b2"}); features_check(install_plan.at(1), "a", {"core", "a3", "a2"}); } TEST_CASE ("basic feature test 6", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("b")); PackageSpecMap spec_map; auto spec_a = FullPackageSpec{spec_map.emplace("a", "b[core]"), {"core"}}; auto spec_b = FullPackageSpec{spec_map.emplace("b", "", {{"b1", ""}}), {"b1"}}; auto install_plan = Dependencies::create_feature_install_plan(spec_map.map, FullPackageSpec::to_feature_specs({spec_a, spec_b}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 3); remove_plan_check(install_plan.at(0), "b"); features_check(install_plan.at(1), "b", {"core", "b1"}); features_check(install_plan.at(2), "a", {"core"}); } TEST_CASE ("basic feature test 7", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("x", "b")); status_paragraphs.push_back(make_status_pgh("b")); PackageSpecMap spec_map; auto spec_a = FullPackageSpec{spec_map.emplace("a")}; auto spec_x = FullPackageSpec{spec_map.emplace("x", "a"), {"core"}}; auto spec_b = FullPackageSpec{spec_map.emplace("b", "", {{"b1", ""}}), {"b1"}}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({spec_b}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 5); remove_plan_check(install_plan.at(0), "x"); remove_plan_check(install_plan.at(1), "b"); // TODO: order here may change but A < X, and B anywhere features_check(install_plan.at(2), "b", {"core", "b1"}); features_check(install_plan.at(3), "a", {"core"}); features_check(install_plan.at(4), "x", {"core"}); } TEST_CASE ("basic feature test 8", "[plan][!mayfail]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("a")); status_paragraphs.push_back(make_status_pgh("a")); status_paragraphs.back()->package.spec = PackageSpec::from_name_and_triplet("a", Triplet::X64_WINDOWS).value_or_exit(VCPKG_LINE_INFO); PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_a_64 = FullPackageSpec{spec_map.emplace("a", "b", {{"a1", ""}}), {"core"}}; auto spec_b_64 = FullPackageSpec{spec_map.emplace("b")}; auto spec_c_64 = FullPackageSpec{spec_map.emplace("c", "a[a1]"), {"core"}}; spec_map.triplet = Triplet::X86_WINDOWS; auto spec_a_86 = FullPackageSpec{spec_map.emplace("a", "b", {{"a1", ""}}), {"core"}}; auto spec_b_86 = FullPackageSpec{spec_map.emplace("b")}; auto spec_c_86 = FullPackageSpec{spec_map.emplace("c", "a[a1]"), {"core"}}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({spec_c_64, spec_a_86, spec_a_64, spec_c_86}), StatusParagraphs(std::move(status_paragraphs))); remove_plan_check(install_plan.at(0), "a", Triplet::X64_WINDOWS); remove_plan_check(install_plan.at(1), "a"); features_check(install_plan.at(2), "b", {"core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(3), "a", {"a1", "core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(4), "c", {"core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(5), "b", {"core"}); features_check(install_plan.at(6), "a", {"a1", "core"}); features_check(install_plan.at(7), "c", {"core"}); } TEST_CASE ("install all features test", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_a_64 = FullPackageSpec{spec_map.emplace("a", "", {{"0", ""}, {"1", ""}}), {"core"}}; auto install_specs = FullPackageSpec::from_string("a[*]", Triplet::X64_WINDOWS); REQUIRE(install_specs.has_value()); if (!install_specs.has_value()) return; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 1); features_check(install_plan.at(0), "a", {"0", "1", "core"}, Triplet::X64_WINDOWS); } TEST_CASE ("install default features test 1", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; // Add a port "a" with default features "1" and features "0" and "1". PackageSpecMap spec_map(Triplet::X64_WINDOWS); spec_map.emplace("a", "", {{"0", ""}, {"1", ""}}, {"1"}); // Install "a" (without explicit feature specification) auto install_specs = FullPackageSpec::from_string("a", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); // Expect the default feature "1" to be installed, but not "0" REQUIRE(install_plan.size() == 1); features_check(install_plan.at(0), "a", {"1", "core"}, Triplet::X64_WINDOWS); } TEST_CASE ("install default features test 2", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("a")); status_paragraphs.back()->package.spec = PackageSpec::from_name_and_triplet("a", Triplet::X64_WINDOWS).value_or_exit(VCPKG_LINE_INFO); // Add a port "a" of which "core" is already installed, but we will // install the default features "explicitly" // "a" has two features, of which "a1" is default. PackageSpecMap spec_map(Triplet::X64_WINDOWS); spec_map.emplace("a", "", {{"a0", ""}, {"a1", ""}}, {"a1"}); // Install "a" (without explicit feature specification) auto install_specs = FullPackageSpec::from_string("a", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); // Expect "a" to get removed for rebuild and then installed with default // features. REQUIRE(install_plan.size() == 2); remove_plan_check(install_plan.at(0), "a", Triplet::X64_WINDOWS); features_check(install_plan.at(1), "a", {"a1", "core"}, Triplet::X64_WINDOWS); } TEST_CASE ("install default features test 3", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; // "a" has two features, of which "a1" is default. PackageSpecMap spec_map(Triplet::X64_WINDOWS); spec_map.emplace("a", "", {{"a0", ""}, {"a1", ""}}, {"a1"}); // Explicitly install "a" without default features auto install_specs = FullPackageSpec::from_string("a[core]", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); // Expect the default feature not to get installed. REQUIRE(install_plan.size() == 1); features_check(install_plan.at(0), "a", {"core"}, Triplet::X64_WINDOWS); } TEST_CASE ("install default features of dependency test 1", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; // Add a port "a" which depends on the core of "b" PackageSpecMap spec_map(Triplet::X64_WINDOWS); spec_map.emplace("a", "b[core]"); // "b" has two features, of which "b1" is default. spec_map.emplace("b", "", {{"b0", ""}, {"b1", ""}}, {"b1"}); // Install "a" (without explicit feature specification) auto install_specs = FullPackageSpec::from_string("a", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); // Expect "a" to get installed and defaults of "b" through the dependency, // as no explicit features of "b" are installed by the user. REQUIRE(install_plan.size() == 2); features_check(install_plan.at(0), "b", {"b1", "core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(1), "a", {"core"}, Triplet::X64_WINDOWS); } TEST_CASE ("do not install default features of existing dependency", "[plan]") { // Add a port "a" which depends on the core of "b" PackageSpecMap spec_map(Triplet::X64_WINDOWS); spec_map.emplace("a", "b[core]"); // "b" has two features, of which "b1" is default. spec_map.emplace("b", "", {{"b0", ""}, {"b1", ""}}, {"b1"}); std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; // "b[core]" is already installed status_paragraphs.push_back(make_status_pgh("b")); status_paragraphs.back()->package.spec = PackageSpec::from_name_and_triplet("b", Triplet::X64_WINDOWS).value_or_exit(VCPKG_LINE_INFO); // Install "a" (without explicit feature specification) auto install_specs = FullPackageSpec::from_string("a", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); // Expect "a" to get installed, but not require rebuilding "b" REQUIRE(install_plan.size() == 1); features_check(install_plan.at(0), "a", {"core"}, Triplet::X64_WINDOWS); } TEST_CASE ("install default features of dependency test 2", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(make_status_pgh("b")); status_paragraphs.back()->package.spec = PackageSpec::from_name_and_triplet("b", Triplet::X64_WINDOWS).value_or_exit(VCPKG_LINE_INFO); // Add a port "a" which depends on the core of "b", which was already // installed explicitly PackageSpecMap spec_map(Triplet::X64_WINDOWS); spec_map.emplace("a", "b[core]"); // "b" has two features, of which "b1" is default. spec_map.emplace("b", "", {{"b0", ""}, {"b1", ""}}, {"b1"}); // Install "a" (without explicit feature specification) auto install_specs = FullPackageSpec::from_string("a", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); // Expect "a" to get installed, not the defaults of "b", as the required // dependencies are already there, installed explicitly by the user. REQUIRE(install_plan.size() == 1); features_check(install_plan.at(0), "a", {"core"}, Triplet::X64_WINDOWS); } TEST_CASE ("install plan action dependencies", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; // Add a port "a" which depends on the core of "b", which was already // installed explicitly PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_c = spec_map.emplace("c"); auto spec_b = spec_map.emplace("b", "c"); spec_map.emplace("a", "b"); // Install "a" (without explicit feature specification) auto install_specs = FullPackageSpec::from_string("a", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 3); features_check(install_plan.at(0), "c", {"core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(1), "b", {"core"}, Triplet::X64_WINDOWS); REQUIRE(install_plan.at(1).install_action.get()->computed_dependencies == std::vector<PackageSpec>{spec_c}); features_check(install_plan.at(2), "a", {"core"}, Triplet::X64_WINDOWS); REQUIRE(install_plan.at(2).install_action.get()->computed_dependencies == std::vector<PackageSpec>{spec_b}); } TEST_CASE ("install plan action dependencies 2", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; // Add a port "a" which depends on the core of "b", which was already // installed explicitly PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_c = spec_map.emplace("c"); auto spec_b = spec_map.emplace("b", "c"); spec_map.emplace("a", "c, b"); // Install "a" (without explicit feature specification) auto install_specs = FullPackageSpec::from_string("a", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 3); features_check(install_plan.at(0), "c", {"core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(1), "b", {"core"}, Triplet::X64_WINDOWS); REQUIRE(install_plan.at(1).install_action.get()->computed_dependencies == std::vector<PackageSpec>{spec_c}); features_check(install_plan.at(2), "a", {"core"}, Triplet::X64_WINDOWS); REQUIRE(install_plan.at(2).install_action.get()->computed_dependencies == std::vector<PackageSpec>{spec_b, spec_c}); } TEST_CASE ("install plan action dependencies 3", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; // Add a port "a" which depends on the core of "b", which was already // installed explicitly PackageSpecMap spec_map(Triplet::X64_WINDOWS); spec_map.emplace("a", "", {{"0", ""}, {"1", "a[0]"}}, {"1"}); // Install "a" (without explicit feature specification) auto install_specs = FullPackageSpec::from_string("a", Triplet::X64_WINDOWS); auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 1); features_check(install_plan.at(0), "a", {"1", "0", "core"}, Triplet::X64_WINDOWS); REQUIRE(install_plan.at(0).install_action.get()->computed_dependencies == std::vector<PackageSpec>{}); } TEST_CASE ("install with default features", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a", "")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto b_spec = spec_map.emplace("b", "", {{"0", ""}}, {"0"}); auto a_spec = spec_map.emplace("a", "b[core]", {{"0", ""}}); // Install "a" and indicate that "b" should not install default features auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, {FeatureSpec{a_spec, "0"}, FeatureSpec{b_spec, "core"}}, status_db); REQUIRE(install_plan.size() == 3); remove_plan_check(install_plan.at(0), "a"); features_check(install_plan.at(1), "b", {"core"}); features_check(install_plan.at(2), "a", {"0", "core"}); } TEST_CASE ("upgrade with default features 1", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a", "", "1")); pghs.push_back(make_status_feature_pgh("a", "0")); StatusParagraphs status_db(std::move(pghs)); // Add a port "a" of which "core" and "0" are already installed. PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "", {{"0", ""}, {"1", ""}}, {"1"}); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); // The upgrade should not install the default feature REQUIRE(plan.size() == 2); REQUIRE(plan.at(0).spec().name() == "a"); remove_plan_check(plan.at(0), "a"); features_check(plan.at(1), "a", {"core", "0"}); } TEST_CASE ("upgrade with default features 2", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; // B is currently installed _without_ default feature b0 pghs.push_back(make_status_pgh("b", "", "b0", "x64-windows")); pghs.push_back(make_status_pgh("a", "b[core]", "", "x64-windows")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_a = spec_map.emplace("a", "b[core]"); auto spec_b = spec_map.emplace("b", "", {{"b0", ""}, {"b1", ""}}, {"b0", "b1"}); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); graph.upgrade(spec_b); auto plan = graph.serialize(); // The upgrade should install the new default feature b1 but not b0 REQUIRE(plan.size() == 4); remove_plan_check(plan.at(0), "a", Triplet::X64_WINDOWS); remove_plan_check(plan.at(1), "b", Triplet::X64_WINDOWS); features_check(plan.at(2), "b", {"core", "b1"}, Triplet::X64_WINDOWS); features_check(plan.at(3), "a", {"core"}, Triplet::X64_WINDOWS); } TEST_CASE ("upgrade with default features 3", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; // note: unrelated package due to x86 triplet pghs.push_back(make_status_pgh("b", "", "", "x86-windows")); pghs.push_back(make_status_pgh("a", "", "", "x64-windows")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_a = spec_map.emplace("a", "b[core]"); spec_map.emplace("b", "", {{"b0", ""}, {"b1", ""}}, {"b0"}); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); // The upgrade should install the default feature REQUIRE(plan.size() == 3); remove_plan_check(plan.at(0), "a", Triplet::X64_WINDOWS); features_check(plan.at(1), "b", {"b0", "core"}, Triplet::X64_WINDOWS); features_check(plan.at(2), "a", {"core"}, Triplet::X64_WINDOWS); } TEST_CASE ("upgrade with new default feature", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a", "", "0", "x86-windows")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "", {{"0", ""}, {"1", ""}, {"2", ""}}, {"0", "1"}); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); // The upgrade should install the new default feature but not the old default feature 0 REQUIRE(plan.size() == 2); remove_plan_check(plan.at(0), "a", Triplet::X86_WINDOWS); features_check(plan.at(1), "a", {"core", "1"}, Triplet::X86_WINDOWS); } TEST_CASE ("transitive features test", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_a_64 = FullPackageSpec{spec_map.emplace("a", "b", {{"0", "b[0]"}}), {"core"}}; auto spec_b_64 = FullPackageSpec{spec_map.emplace("b", "c", {{"0", "c[0]"}}), {"core"}}; auto spec_c_64 = FullPackageSpec{spec_map.emplace("c", "", {{"0", ""}}), {"core"}}; auto install_specs = FullPackageSpec::from_string("a[*]", Triplet::X64_WINDOWS); REQUIRE(install_specs.has_value()); if (!install_specs.has_value()) return; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 3); features_check(install_plan.at(0), "c", {"0", "core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(1), "b", {"0", "core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(2), "a", {"0", "core"}, Triplet::X64_WINDOWS); } TEST_CASE ("no transitive features test", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_a_64 = FullPackageSpec{spec_map.emplace("a", "b", {{"0", ""}}), {"core"}}; auto spec_b_64 = FullPackageSpec{spec_map.emplace("b", "c", {{"0", ""}}), {"core"}}; auto spec_c_64 = FullPackageSpec{spec_map.emplace("c", "", {{"0", ""}}), {"core"}}; auto install_specs = FullPackageSpec::from_string("a[*]", Triplet::X64_WINDOWS); REQUIRE(install_specs.has_value()); if (!install_specs.has_value()) return; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 3); features_check(install_plan.at(0), "c", {"core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(1), "b", {"core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(2), "a", {"0", "core"}, Triplet::X64_WINDOWS); } TEST_CASE ("only transitive features test", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_a_64 = FullPackageSpec{spec_map.emplace("a", "", {{"0", "b[0]"}}), {"core"}}; auto spec_b_64 = FullPackageSpec{spec_map.emplace("b", "", {{"0", "c[0]"}}), {"core"}}; auto spec_c_64 = FullPackageSpec{spec_map.emplace("c", "", {{"0", ""}}), {"core"}}; auto install_specs = FullPackageSpec::from_string("a[*]", Triplet::X64_WINDOWS); REQUIRE(install_specs.has_value()); if (!install_specs.has_value()) return; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, FullPackageSpec::to_feature_specs({install_specs.value_or_exit(VCPKG_LINE_INFO)}), StatusParagraphs(std::move(status_paragraphs))); REQUIRE(install_plan.size() == 3); features_check(install_plan.at(0), "c", {"0", "core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(1), "b", {"0", "core"}, Triplet::X64_WINDOWS); features_check(install_plan.at(2), "a", {"0", "core"}, Triplet::X64_WINDOWS); } TEST_CASE ("basic remove scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); StatusParagraphs status_db(std::move(pghs)); auto remove_plan = Dependencies::create_remove_plan({unsafe_pspec("a")}, status_db); REQUIRE(remove_plan.size() == 1); REQUIRE(remove_plan.at(0).spec.name() == "a"); } TEST_CASE ("recurse remove scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_pgh("b", "a")); StatusParagraphs status_db(std::move(pghs)); auto remove_plan = Dependencies::create_remove_plan({unsafe_pspec("a")}, status_db); REQUIRE(remove_plan.size() == 2); REQUIRE(remove_plan.at(0).spec.name() == "b"); REQUIRE(remove_plan.at(1).spec.name() == "a"); } TEST_CASE ("features depend remove scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_pgh("b")); pghs.push_back(make_status_feature_pgh("b", "0", "a")); StatusParagraphs status_db(std::move(pghs)); auto remove_plan = Dependencies::create_remove_plan({unsafe_pspec("a")}, status_db); REQUIRE(remove_plan.size() == 2); REQUIRE(remove_plan.at(0).spec.name() == "b"); REQUIRE(remove_plan.at(1).spec.name() == "a"); } TEST_CASE ("features depend remove scheme once removed", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("expat")); pghs.push_back(make_status_pgh("vtk", "expat")); pghs.push_back(make_status_pgh("opencv")); pghs.push_back(make_status_feature_pgh("opencv", "vtk", "vtk")); StatusParagraphs status_db(std::move(pghs)); auto remove_plan = Dependencies::create_remove_plan({unsafe_pspec("expat")}, status_db); REQUIRE(remove_plan.size() == 3); REQUIRE(remove_plan.at(0).spec.name() == "opencv"); REQUIRE(remove_plan.at(1).spec.name() == "vtk"); REQUIRE(remove_plan.at(2).spec.name() == "expat"); } TEST_CASE ("features depend remove scheme once removed x64", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("expat", "", "", "x64")); pghs.push_back(make_status_pgh("vtk", "expat", "", "x64")); pghs.push_back(make_status_pgh("opencv", "", "", "x64")); pghs.push_back(make_status_feature_pgh("opencv", "vtk", "vtk", "x64")); StatusParagraphs status_db(std::move(pghs)); auto remove_plan = Dependencies::create_remove_plan({unsafe_pspec("expat", Triplet::from_canonical_name("x64"))}, status_db); REQUIRE(remove_plan.size() == 3); REQUIRE(remove_plan.at(0).spec.name() == "opencv"); REQUIRE(remove_plan.at(1).spec.name() == "vtk"); REQUIRE(remove_plan.at(2).spec.name() == "expat"); } TEST_CASE ("features depend core remove scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("curl", "", "", "x64")); pghs.push_back(make_status_pgh("cpr", "curl[core]", "", "x64")); StatusParagraphs status_db(std::move(pghs)); auto remove_plan = Dependencies::create_remove_plan({unsafe_pspec("curl", Triplet::from_canonical_name("x64"))}, status_db); REQUIRE(remove_plan.size() == 2); REQUIRE(remove_plan.at(0).spec.name() == "cpr"); REQUIRE(remove_plan.at(1).spec.name() == "curl"); } TEST_CASE ("features depend core remove scheme 2", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("curl", "", "", "x64")); pghs.push_back(make_status_feature_pgh("curl", "a", "", "x64")); pghs.push_back(make_status_feature_pgh("curl", "b", "curl[a]", "x64")); StatusParagraphs status_db(std::move(pghs)); auto remove_plan = Dependencies::create_remove_plan({unsafe_pspec("curl", Triplet::from_canonical_name("x64"))}, status_db); REQUIRE(remove_plan.size() == 1); REQUIRE(remove_plan.at(0).spec.name() == "curl"); } TEST_CASE ("basic upgrade scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a"); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); REQUIRE(plan.size() == 2); REQUIRE(plan.at(0).spec().name() == "a"); REQUIRE(plan.at(0).remove_action.has_value()); REQUIRE(plan.at(1).spec().name() == "a"); REQUIRE(plan.at(1).install_action.has_value()); } TEST_CASE ("basic upgrade scheme with recurse", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_pgh("b", "a")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a"); spec_map.emplace("b", "a"); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); REQUIRE(plan.size() == 4); REQUIRE(plan.at(0).spec().name() == "b"); REQUIRE(plan.at(0).remove_action.has_value()); REQUIRE(plan.at(1).spec().name() == "a"); REQUIRE(plan.at(1).remove_action.has_value()); REQUIRE(plan.at(2).spec().name() == "a"); REQUIRE(plan.at(2).install_action.has_value()); REQUIRE(plan.at(3).spec().name() == "b"); REQUIRE(plan.at(3).install_action.has_value()); } TEST_CASE ("basic upgrade scheme with bystander", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_pgh("b")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a"); spec_map.emplace("b", "a"); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); REQUIRE(plan.size() == 2); REQUIRE(plan.at(0).spec().name() == "a"); REQUIRE(plan.at(0).remove_action.has_value()); REQUIRE(plan.at(1).spec().name() == "a"); REQUIRE(plan.at(1).install_action.has_value()); } TEST_CASE ("basic upgrade scheme with new dep", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "b"); spec_map.emplace("b"); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); REQUIRE(plan.size() == 3); REQUIRE(plan.at(0).spec().name() == "a"); REQUIRE(plan.at(0).remove_action.has_value()); REQUIRE(plan.at(1).spec().name() == "b"); REQUIRE(plan.at(1).install_action.has_value()); REQUIRE(plan.at(2).spec().name() == "a"); REQUIRE(plan.at(2).install_action.has_value()); } TEST_CASE ("basic upgrade scheme with features", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_feature_pgh("a", "a1")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "", {{"a1", ""}}); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); REQUIRE(plan.size() == 2); REQUIRE(plan.at(0).spec().name() == "a"); REQUIRE(plan.at(0).remove_action.has_value()); features_check(plan.at(1), "a", {"core", "a1"}); } TEST_CASE ("basic upgrade scheme with new default feature", "[plan]") { // only core of package "a" is installed std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); StatusParagraphs status_db(std::move(pghs)); // a1 was added as a default feature and should be installed in upgrade PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "", {{"a1", ""}}, {"a1"}); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); REQUIRE(plan.size() == 2); REQUIRE(plan.at(0).spec().name() == "a"); REQUIRE(plan.at(0).remove_action.has_value()); features_check(plan.at(1), "a", {"core", "a1"}); } TEST_CASE ("basic upgrade scheme with self features", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_feature_pgh("a", "a1", "")); pghs.push_back(make_status_feature_pgh("a", "a2", "a[a1]")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "", {{"a1", ""}, {"a2", "a[a1]"}}); Dependencies::MapPortFileProvider provider(spec_map.map); Dependencies::PackageGraph graph(provider, status_db); graph.upgrade(spec_a); auto plan = graph.serialize(); REQUIRE(plan.size() == 2); REQUIRE(plan.at(0).spec().name() == "a"); REQUIRE(plan.at(0).remove_action.has_value()); REQUIRE(plan.at(1).spec().name() == "a"); REQUIRE(plan.at(1).install_action.has_value()); REQUIRE(plan.at(1).install_action.get()->feature_list == std::set<std::string>{"core", "a1", "a2"}); } TEST_CASE ("basic export scheme", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a"); auto plan = Dependencies::create_export_plan({spec_a}, status_db); REQUIRE(plan.size() == 1); REQUIRE(plan.at(0).spec.name() == "a"); REQUIRE(plan.at(0).plan_type == Dependencies::ExportPlanType::ALREADY_BUILT); } TEST_CASE ("basic export scheme with recurse", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_pgh("b", "a")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a"); auto spec_b = spec_map.emplace("b", "a"); auto plan = Dependencies::create_export_plan({spec_b}, status_db); REQUIRE(plan.size() == 2); REQUIRE(plan.at(0).spec.name() == "a"); REQUIRE(plan.at(0).plan_type == Dependencies::ExportPlanType::ALREADY_BUILT); REQUIRE(plan.at(1).spec.name() == "b"); REQUIRE(plan.at(1).plan_type == Dependencies::ExportPlanType::ALREADY_BUILT); } TEST_CASE ("basic export scheme with bystander", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_pgh("b")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a"); auto spec_b = spec_map.emplace("b", "a"); auto plan = Dependencies::create_export_plan({spec_a}, status_db); REQUIRE(plan.size() == 1); REQUIRE(plan.at(0).spec.name() == "a"); REQUIRE(plan.at(0).plan_type == Dependencies::ExportPlanType::ALREADY_BUILT); } TEST_CASE ("basic export scheme with missing", "[plan]") { StatusParagraphs status_db; PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a"); auto plan = Dependencies::create_export_plan({spec_a}, status_db); REQUIRE(plan.size() == 1); REQUIRE(plan.at(0).spec.name() == "a"); REQUIRE(plan.at(0).plan_type == Dependencies::ExportPlanType::NOT_BUILT); } TEST_CASE ("basic export scheme with features", "[plan]") { std::vector<std::unique_ptr<StatusParagraph>> pghs; pghs.push_back(make_status_pgh("b")); pghs.push_back(make_status_pgh("a")); pghs.push_back(make_status_feature_pgh("a", "a1", "b[core]")); StatusParagraphs status_db(std::move(pghs)); PackageSpecMap spec_map; auto spec_a = spec_map.emplace("a", "", {{"a1", ""}}); auto plan = Dependencies::create_export_plan({spec_a}, status_db); REQUIRE(plan.size() == 2); REQUIRE(plan.at(0).spec.name() == "b"); REQUIRE(plan.at(0).plan_type == Dependencies::ExportPlanType::ALREADY_BUILT); REQUIRE(plan.at(1).spec.name() == "a"); REQUIRE(plan.at(1).plan_type == Dependencies::ExportPlanType::ALREADY_BUILT); }
49,499
18,155
#include "partition/partitioned_petsc_vec/02_partitioned_petsc_vec_for_hyperelasticity.h" #include "utility/mpi_utility.h" // ---- incompressible case ---- template<typename DisplacementsFunctionSpaceType, typename PressureFunctionSpaceType, typename Term, int nComponents> std::string PartitionedPetscVecForHyperelasticity<DisplacementsFunctionSpaceType,PressureFunctionSpaceType,Term,nComponents,std::enable_if_t<Term::isIncompressible,Term>>:: getString(bool horizontal, std::string vectorName) const { // do not assemble a horizontal string for console in release mode, because this is only needed for debugging output //#ifdef NDEBUG // if (horizontal) // return std::string(""); //#endif #ifndef NDEBUG std::stringstream result; int ownRankNo = this->meshPartition_->ownRankNo(); // the master rank collects all data and writes the file if (ownRankNo == 0) { // handle displacement values std::vector<std::vector<global_no_t>> dofNosGlobalNatural(this->meshPartition_->nRanks()); std::vector<std::vector<double>> values(this->meshPartition_->nRanks()); std::vector<int> nDofsOnRank(this->meshPartition_->nRanks()); std::vector<int> nPressureDofsOnRank(this->meshPartition_->nRanks()); VLOG(1) << "values: " << values; // handle own rank // get dof nos in global natural ordering int nDofsLocalWithoutGhosts = this->meshPartition_->nDofsLocalWithoutGhosts(); nDofsOnRank[0] = nDofsLocalWithoutGhosts; std::vector<global_no_t> dofNosGlobalNaturalOwn; this->meshPartition_->getDofNosGlobalNatural(dofNosGlobalNaturalOwn); dofNosGlobalNatural[0].resize(nDofsLocalWithoutGhosts); std::copy(dofNosGlobalNaturalOwn.begin(), dofNosGlobalNaturalOwn.end(), dofNosGlobalNatural[0].begin()); // get displacement values values[0].resize(nComponents*nDofsLocalWithoutGhosts); for (int i = 0; i < nComponents; i++) { this->getValues(i, nDofsLocalWithoutGhosts, this->meshPartition_->dofNosLocal().data(), values[0].data() + i*nDofsLocalWithoutGhosts); } VLOG(1) << "get own displacement values: " << values; for (int rankNo = 0; rankNo < this->meshPartition_->nRanks(); rankNo++) { VLOG(1) << "rank " << rankNo; if (rankNo == 0) continue; // receive number of dofs on rank MPIUtility::handleReturnValue(MPI_Recv(&nDofsOnRank[rankNo], 1, MPI_INT, rankNo, 0, this->meshPartition_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << ", nDofsOnRank: " << nDofsOnRank[rankNo]; VLOG(1) << "recv from " << rankNo << " " << nDofsOnRank[rankNo] << " dofs and displacements values"; // receive dof nos dofNosGlobalNatural[rankNo].resize(nDofsOnRank[rankNo]); MPIUtility::handleReturnValue(MPI_Recv(dofNosGlobalNatural[rankNo].data(), nDofsOnRank[rankNo], MPI_UNSIGNED_LONG_LONG, rankNo, 0, this->meshPartition_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "received displacements dofs: " << dofNosGlobalNatural[rankNo]; // receive values values[rankNo].resize(nComponents*nDofsOnRank[rankNo]); MPIUtility::handleReturnValue(MPI_Recv(values[rankNo].data(), nComponents*nDofsOnRank[rankNo], MPI_DOUBLE, rankNo, 0, this->meshPartition_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "received displacements values: " << values[rankNo]; } VLOG(1) << "values: " << values; // handle pressure values std::vector<std::vector<global_no_t>> dofNosGlobalNaturalPressure(this->meshPartition_->nRanks()); std::vector<std::vector<double>> valuesPressure(this->meshPartition_->nRanks()); // handle own rank // get global natural dof nos for pressure nDofsLocalWithoutGhosts = this->meshPartitionPressure_->nDofsLocalWithoutGhosts(); nPressureDofsOnRank[0] = nDofsLocalWithoutGhosts; VLOG(1) << "nRanks: " << this->meshPartition_->nRanks() << ", nDofsLocalWithoutGhosts: " << nDofsLocalWithoutGhosts; std::vector<global_no_t> dofNosGlobalNaturalPressureOwn; this->meshPartitionPressure_->getDofNosGlobalNatural(dofNosGlobalNaturalPressureOwn); dofNosGlobalNaturalPressure[0].resize(nDofsLocalWithoutGhosts); std::copy(dofNosGlobalNaturalPressureOwn.begin(), dofNosGlobalNaturalPressureOwn.end(), dofNosGlobalNaturalPressure[0].begin()); // get pressure values valuesPressure[0].resize(nDofsLocalWithoutGhosts); this->getValues(componentNoPressure_, nDofsLocalWithoutGhosts, this->meshPartitionPressure_->dofNosLocal().data(), valuesPressure[0].data()); // loop over other ranks for (int rankNo = 0; rankNo < this->meshPartitionPressure_->nRanks(); rankNo++) { if (rankNo == 0) continue; // receive number of dofs on rank VLOG(1) << "pressure rank " << rankNo << " n dofs: " << nPressureDofsOnRank[rankNo]; // receive number of dofs on rank MPIUtility::handleReturnValue(MPI_Recv(&nPressureDofsOnRank[rankNo], 1, MPI_INT, rankNo, 0, this->meshPartition_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "recv from " << rankNo << " " << nPressureDofsOnRank[rankNo] << " dofs and pressure values"; // receive dof nos dofNosGlobalNaturalPressure[rankNo].resize(nPressureDofsOnRank[rankNo]); MPIUtility::handleReturnValue(MPI_Recv(dofNosGlobalNaturalPressure[rankNo].data(), nPressureDofsOnRank[rankNo], MPI_UNSIGNED_LONG_LONG, rankNo, 0, this->meshPartitionPressure_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "received pressureDofs: " << dofNosGlobalNaturalPressure[rankNo]; // receive values valuesPressure[rankNo].resize(nPressureDofsOnRank[rankNo]); MPIUtility::handleReturnValue(MPI_Recv(valuesPressure[rankNo].data(), nPressureDofsOnRank[rankNo], MPI_DOUBLE, rankNo, 0, this->meshPartitionPressure_->rankSubset()->mpiCommunicator(), MPI_STATUS_IGNORE), "MPI_Recv"); VLOG(1) << "received pressure values: " << valuesPressure[rankNo]; } // sort displacement values according to global natural dof no std::vector<std::pair<global_no_t,std::array<double,nComponents>>> displacementEntries; displacementEntries.reserve(this->nEntriesGlobal_); for (int rankNo = 0; rankNo < this->meshPartition_->nRanks(); rankNo++) { assert(nDofsOnRank[rankNo] == dofNosGlobalNatural[rankNo].size()); for (int i = 0; i < nDofsOnRank[rankNo]; i++) { std::pair<global_no_t,std::array<double,nComponents>> displacementEntry; displacementEntry.first = dofNosGlobalNatural[rankNo][i]; std::array<double,nComponents> valuesDof; for (int componentNo = 0; componentNo < nComponents; componentNo++) { valuesDof[componentNo] = values[rankNo][componentNo*nDofsOnRank[rankNo] + i]; } displacementEntry.second = valuesDof; displacementEntries.push_back(displacementEntry); } } // sort list according to dof no.s std::sort(displacementEntries.begin(), displacementEntries.end(), [&](std::pair<global_no_t,std::array<double,nComponents>> a, std::pair<global_no_t,std::array<double,nComponents>> b) { return a.first < b.first; }); // sort pressure values according to global natural dof no std::vector<std::pair<global_no_t,double>> pressureEntries; pressureEntries.reserve(this->nEntriesGlobal_); for (int rankNo = 0; rankNo < this->meshPartitionPressure_->nRanks(); rankNo++) { int nDofsOnRank = dofNosGlobalNaturalPressure[rankNo].size(); for (int i = 0; i < nDofsOnRank; i++) { pressureEntries.push_back(std::pair<global_no_t,double>( dofNosGlobalNaturalPressure[rankNo][i], valuesPressure[rankNo][i] )); } } // sort list according to dof no.s std::sort(pressureEntries.begin(), pressureEntries.end(), [&](std::pair<global_no_t,double> a, std::pair<global_no_t,double> b) { return a.first < b.first; }); if (VLOG_IS_ON(1)) { VLOG(1) << "dofNosGlobalNatural: " << dofNosGlobalNatural; VLOG(1) << "values: " << values; VLOG(1) << "nDofsOnRank: " << nDofsOnRank; VLOG(1) << "nPressureDofsOnRank: " << nPressureDofsOnRank; VLOG(1) << "valuesPressure: " << valuesPressure; VLOG(1) << "displacementEntries: " << displacementEntries; VLOG(1) << "pressureEntries: " << pressureEntries; } // write file std::string newline = "\n"; std::string separator = ", "; std::array<std::string,nComponents> componentNames; componentNames[0] = "ux"; componentNames[1] = "uy"; componentNames[2] = "uz"; if (nComponents == 6) { componentNames[3] = "vx"; componentNames[4] = "vy"; componentNames[5] = "vz"; } if (horizontal) { newline = ""; separator = ", "; result << std::endl; } else { result << vectorName << "r" << this->meshPartitionPressure_->nRanks() << " = ["; } // loop over not-pressure components (u and possibly v) for (int componentNo = 0; componentNo < nComponents; componentNo++) { // start of component if (horizontal) { result << componentNames[componentNo] << " = [" << newline; // print e.g. "ux = [" } // write displacement values for (int i = 0; i < displacementEntries.size(); i++) { if (i != 0) result << separator; result << displacementEntries[i].first << ":" << (fabs(displacementEntries[i].second[componentNo]) < 1e-13? 0 : displacementEntries[i].second[componentNo]); } // end of component if (horizontal) { result << newline << "]; " << std::endl; } else { result << ", ...\n "; } } if (horizontal) { result << " p = [" << newline; } else { result << ", ...\n "; } for (int i = 0; i < pressureEntries.size(); i++) { if (i != 0) result << separator; result << pressureEntries[i].first << ":" << (fabs(pressureEntries[i].second) < 1e-13? 0 : pressureEntries[i].second); } if (horizontal) { result << newline << "];" << std::endl; } else { result << "]; " << std::endl; } } else { // all other ranks send the data to rank 0 int nDofsLocalWithoutGhosts = this->meshPartition_->nDofsLocalWithoutGhosts(); // send number of local dofs MPIUtility::handleReturnValue(MPI_Send(&nDofsLocalWithoutGhosts, 1, MPI_INT, 0, 0, this->meshPartition_->rankSubset()->mpiCommunicator()), "MPI_Send"); // send global natural dof nos for displacements std::vector<global_no_t> dofNosGlobalNatural; this->meshPartition_->getDofNosGlobalNatural(dofNosGlobalNatural); assert(dofNosGlobalNatural.size() == nDofsLocalWithoutGhosts); VLOG(1) << "send to 0 " << nDofsLocalWithoutGhosts << " dofs and displacements values"; MPIUtility::handleReturnValue(MPI_Send(dofNosGlobalNatural.data(), nDofsLocalWithoutGhosts, MPI_UNSIGNED_LONG_LONG, 0, 0, this->meshPartition_->rankSubset()->mpiCommunicator()), "MPI_Send"); VLOG(1) << "sent displacements dofs: " << dofNosGlobalNatural; // send displacement values std::vector<double> values(nComponents*nDofsLocalWithoutGhosts); for (int componentNo = 0; componentNo < nComponents; componentNo++) { this->getValues(componentNo, nDofsLocalWithoutGhosts, this->meshPartition_->dofNosLocal().data(), values.data() + componentNo*nDofsLocalWithoutGhosts); } MPIUtility::handleReturnValue(MPI_Send(values.data(), nComponents*nDofsLocalWithoutGhosts, MPI_DOUBLE, 0, 0, this->meshPartition_->rankSubset()->mpiCommunicator()), "MPI_Send"); VLOG(1) << "sent displacements values: " << values; nDofsLocalWithoutGhosts = this->meshPartitionPressure_->nDofsLocalWithoutGhosts(); // send number of local pressure dofs MPIUtility::handleReturnValue(MPI_Send(&nDofsLocalWithoutGhosts, 1, MPI_INT, 0, 0, this->meshPartition_->rankSubset()->mpiCommunicator()), "MPI_Send"); // send global natural dof nos for pressure VLOG(1) << "send to 0 " << nDofsLocalWithoutGhosts << " pressure dofs and values"; std::vector<global_no_t> dofNosGlobalNaturalPressure; this->meshPartitionPressure_->getDofNosGlobalNatural(dofNosGlobalNaturalPressure); assert(dofNosGlobalNaturalPressure.size() == nDofsLocalWithoutGhosts); MPIUtility::handleReturnValue(MPI_Send(dofNosGlobalNaturalPressure.data(), nDofsLocalWithoutGhosts, MPI_UNSIGNED_LONG_LONG, 0, 0, this->meshPartitionPressure_->rankSubset()->mpiCommunicator()), "MPI_Send"); VLOG(1) << "sent pressure dofs: " << dofNosGlobalNaturalPressure; // send pressure values std::vector<double> valuesPressure(nDofsLocalWithoutGhosts); this->getValues(componentNoPressure_, nDofsLocalWithoutGhosts, this->meshPartitionPressure_->dofNosLocal().data(), valuesPressure.data()); MPIUtility::handleReturnValue(MPI_Send(valuesPressure.data(), nDofsLocalWithoutGhosts, MPI_DOUBLE, 0, 0, this->meshPartitionPressure_->rankSubset()->mpiCommunicator()), "MPI_Send"); VLOG(1) << "sent pressure values: " << valuesPressure; } return result.str(); #else // in release mode, do not gather all the data from all processes return std::string(""); #endif }
13,991
4,891
/* * Copyright (C) 2009, 2010, 2012 Research In Motion Limited. 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 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 "config.h" #include "TestRunner.h" #include "DatabaseTracker.h" #include "Document.h" #include "DocumentLoader.h" #include "DocumentMarker.h" #include "DumpRenderTree.h" #include "DumpRenderTreeBlackBerry.h" #include "DumpRenderTreeSupport.h" #include "EditingBehaviorTypes.h" #include "EditorClientBlackBerry.h" #include "Element.h" #include "Frame.h" #include "HTMLInputElement.h" #include "JSElement.h" #include "KURL.h" #include "NotImplemented.h" #include "Page.h" #include "RenderTreeAsText.h" #include "SchemeRegistry.h" #include "SecurityOrigin.h" #include "SecurityPolicy.h" #include "Settings.h" #include "WorkQueue.h" #include "WorkQueueItem.h" #include <JavaScriptCore/APICast.h> #include <SharedPointer.h> #include <WebPage.h> #include <WebSettings.h> #include <wtf/OwnArrayPtr.h> #include <wtf/text/CString.h> using WebCore::toElement; using WebCore::toJS; TestRunner::~TestRunner() { } void TestRunner::addDisallowedURL(JSStringRef url) { UNUSED_PARAM(url); notImplemented(); } void TestRunner::clearAllDatabases() { #if ENABLE(DATABASE) WebCore::DatabaseTracker::tracker().deleteAllDatabases(); #endif } void TestRunner::clearBackForwardList() { BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->clearBackForwardList(true); } void TestRunner::clearPersistentUserStyleSheet() { notImplemented(); } JSStringRef TestRunner::copyDecodedHostName(JSStringRef name) { UNUSED_PARAM(name); notImplemented(); return 0; } JSStringRef TestRunner::copyEncodedHostName(JSStringRef name) { UNUSED_PARAM(name); notImplemented(); return 0; } void TestRunner::dispatchPendingLoadRequests() { notImplemented(); } void TestRunner::display() { notImplemented(); } static String jsStringRefToWebCoreString(JSStringRef str) { size_t strArrSize = JSStringGetMaximumUTF8CStringSize(str); OwnArrayPtr<char> strArr = adoptArrayPtr(new char[strArrSize]); JSStringGetUTF8CString(str, strArr.get(), strArrSize); return String::fromUTF8(strArr.get()); } void TestRunner::execCommand(JSStringRef name, JSStringRef value) { if (!mainFrame) return; String nameStr = jsStringRefToWebCoreString(name); String valueStr = jsStringRefToWebCoreString(value); mainFrame->editor()->command(nameStr).execute(valueStr); } bool TestRunner::isCommandEnabled(JSStringRef name) { if (!mainFrame) return false; String nameStr = jsStringRefToWebCoreString(name); return mainFrame->editor()->command(nameStr).isEnabled(); } void TestRunner::keepWebHistory() { notImplemented(); } void TestRunner::notifyDone() { if (m_waitToDump && (!topLoadingFrame || BlackBerry::WebKit::DumpRenderTree::currentInstance()->loadFinished()) && !WorkQueue::shared()->count()) dump(); m_waitToDump = false; waitForPolicy = false; } JSStringRef TestRunner::pathToLocalResource(JSContextRef, JSStringRef url) { return JSStringRetain(url); } void TestRunner::queueLoad(JSStringRef url, JSStringRef target) { size_t urlArrSize = JSStringGetMaximumUTF8CStringSize(url); OwnArrayPtr<char> urlArr = adoptArrayPtr(new char[urlArrSize]); JSStringGetUTF8CString(url, urlArr.get(), urlArrSize); WebCore::KURL base = mainFrame->loader()->documentLoader()->response().url(); WebCore::KURL absolute(base, urlArr.get()); JSRetainPtr<JSStringRef> absoluteURL(Adopt, JSStringCreateWithUTF8CString(absolute.string().utf8().data())); WorkQueue::shared()->queue(new LoadItem(absoluteURL.get(), target)); } void TestRunner::setAcceptsEditing(bool acceptsEditing) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->setAcceptsEditing(acceptsEditing); } void TestRunner::setAppCacheMaximumSize(unsigned long long quota) { UNUSED_PARAM(quota); notImplemented(); } void TestRunner::setAuthorAndUserStylesEnabled(bool enable) { mainFrame->page()->settings()->setAuthorAndUserStylesEnabled(enable); } void TestRunner::setCacheModel(int) { notImplemented(); } void TestRunner::setCustomPolicyDelegate(bool setDelegate, bool permissive) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->setCustomPolicyDelegate(setDelegate, permissive); } void TestRunner::clearApplicationCacheForOrigin(OpaqueJSString*) { // FIXME: Implement to support deleting all application caches for an origin. notImplemented(); } long long TestRunner::localStorageDiskUsageForOrigin(JSStringRef) { // FIXME: Implement to support getting disk usage in bytes for an origin. notImplemented(); return 0; } JSValueRef TestRunner::originsWithApplicationCache(JSContextRef context) { // FIXME: Implement to get origins that contain application caches. notImplemented(); return JSValueMakeUndefined(context); } void TestRunner::setDatabaseQuota(unsigned long long quota) { if (!mainFrame) return; WebCore::DatabaseTracker::tracker().setQuota(mainFrame->document()->securityOrigin(), quota); } void TestRunner::setDomainRelaxationForbiddenForURLScheme(bool forbidden, JSStringRef scheme) { WebCore::SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(forbidden, jsStringRefToWebCoreString(scheme)); } void TestRunner::setIconDatabaseEnabled(bool iconDatabaseEnabled) { UNUSED_PARAM(iconDatabaseEnabled); notImplemented(); } void TestRunner::setMainFrameIsFirstResponder(bool flag) { UNUSED_PARAM(flag); notImplemented(); } void TestRunner::setPersistentUserStyleSheetLocation(JSStringRef path) { UNUSED_PARAM(path); notImplemented(); } void TestRunner::setPopupBlockingEnabled(bool flag) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setJavaScriptOpenWindowsAutomatically(!flag); } void TestRunner::setPrivateBrowsingEnabled(bool flag) { UNUSED_PARAM(flag); notImplemented(); } void TestRunner::setXSSAuditorEnabled(bool flag) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setXSSAuditorEnabled(flag); } void TestRunner::setTabKeyCyclesThroughElements(bool cycles) { if (!mainFrame) return; mainFrame->page()->setTabKeyCyclesThroughElements(cycles); } void TestRunner::setUseDashboardCompatibilityMode(bool flag) { UNUSED_PARAM(flag); notImplemented(); } void TestRunner::setUserStyleSheetEnabled(bool flag) { UNUSED_PARAM(flag); notImplemented(); } void TestRunner::setUserStyleSheetLocation(JSStringRef path) { String pathStr = jsStringRefToWebCoreString(path); BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setUserStyleSheetLocation(pathStr); } void TestRunner::waitForPolicyDelegate() { setCustomPolicyDelegate(true, true); setWaitToDump(true); waitForPolicy = true; } size_t TestRunner::webHistoryItemCount() { SharedArray<BlackBerry::WebKit::WebPage::BackForwardEntry> backForwardList; BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->getBackForwardList(backForwardList); return backForwardList.length(); } int TestRunner::windowCount() { notImplemented(); return 0; } void TestRunner::setWaitToDump(bool waitToDump) { // Change from 30s to 35s because some test cases in multipart need 30 seconds, // refer to http/tests/multipart/resources/multipart-wait-before-boundary.php please. static const double kWaitToDumpWatchdogInterval = 35.0; m_waitToDump = waitToDump; if (m_waitToDump) BlackBerry::WebKit::DumpRenderTree::currentInstance()->setWaitToDumpWatchdog(kWaitToDumpWatchdogInterval); } void TestRunner::setWindowIsKey(bool windowIsKey) { m_windowIsKey = windowIsKey; notImplemented(); } void TestRunner::removeAllVisitedLinks() { notImplemented(); } void TestRunner::overridePreference(JSStringRef key, JSStringRef value) { if (!mainFrame) return; String keyStr = jsStringRefToWebCoreString(key); String valueStr = jsStringRefToWebCoreString(value); if (keyStr == "WebKitUsesPageCachePreferenceKey") BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setMaximumPagesInCache(1); else if (keyStr == "WebKitUsePreHTML5ParserQuirks") mainFrame->page()->settings()->setUsePreHTML5ParserQuirks(true); else if (keyStr == "WebKitTabToLinksPreferenceKey") DumpRenderTreeSupport::setLinksIncludedInFocusChain(valueStr == "true" || valueStr == "1"); else if (keyStr == "WebKitHyperlinkAuditingEnabled") mainFrame->page()->settings()->setHyperlinkAuditingEnabled(valueStr == "true" || valueStr == "1"); else if (keyStr == "WebSocketsEnabled") BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setWebSocketsEnabled(valueStr == "true" || valueStr == "1"); else if (keyStr == "WebKitDefaultTextEncodingName") BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setDefaultTextEncodingName(valueStr); else if (keyStr == "WebKitDisplayImagesKey") BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->settings()->setLoadsImagesAutomatically(valueStr == "true" || valueStr == "1"); } void TestRunner::setAlwaysAcceptCookies(bool alwaysAcceptCookies) { UNUSED_PARAM(alwaysAcceptCookies); notImplemented(); } void TestRunner::setMockGeolocationPosition(double latitude, double longitude, double accuracy, bool providesAltitude, double altitude, bool providesAltitudeAccuracy, double altitudeAccuracy, bool providesHeading, double heading, bool providesSpeed, double speed) { DumpRenderTreeSupport::setMockGeolocationPosition(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page(), latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed); } void TestRunner::setMockGeolocationPositionUnavailableError(JSStringRef message) { String messageStr = jsStringRefToWebCoreString(message); DumpRenderTreeSupport::setMockGeolocationPositionUnavailableError(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page(), messageStr); } void TestRunner::showWebInspector() { notImplemented(); } void TestRunner::closeWebInspector() { notImplemented(); } void TestRunner::evaluateInWebInspector(long callId, JSStringRef script) { UNUSED_PARAM(callId); UNUSED_PARAM(script); notImplemented(); } void TestRunner::evaluateScriptInIsolatedWorldAndReturnValue(unsigned worldID, JSObjectRef globalObject, JSStringRef script) { UNUSED_PARAM(worldID); UNUSED_PARAM(globalObject); UNUSED_PARAM(script); notImplemented(); } void TestRunner::evaluateScriptInIsolatedWorld(unsigned worldID, JSObjectRef globalObject, JSStringRef script) { UNUSED_PARAM(worldID); UNUSED_PARAM(globalObject); UNUSED_PARAM(script); notImplemented(); } void TestRunner::addUserScript(JSStringRef source, bool runAtStart, bool allFrames) { UNUSED_PARAM(source); UNUSED_PARAM(runAtStart); UNUSED_PARAM(allFrames); notImplemented(); } void TestRunner::addUserStyleSheet(JSStringRef, bool) { notImplemented(); } void TestRunner::setScrollbarPolicy(JSStringRef, JSStringRef) { notImplemented(); } void TestRunner::setWebViewEditable(bool) { notImplemented(); } void TestRunner::authenticateSession(JSStringRef, JSStringRef, JSStringRef) { notImplemented(); } bool TestRunner::callShouldCloseOnWebView() { notImplemented(); return false; } void TestRunner::setSpatialNavigationEnabled(bool) { notImplemented(); } void TestRunner::addOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains) { WebCore::SecurityPolicy::addOriginAccessWhitelistEntry(*WebCore::SecurityOrigin::createFromString(jsStringRefToWebCoreString(sourceOrigin)), jsStringRefToWebCoreString(destinationProtocol), jsStringRefToWebCoreString(destinationHost), allowDestinationSubdomains); } void TestRunner::removeOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains) { WebCore::SecurityPolicy::removeOriginAccessWhitelistEntry(*WebCore::SecurityOrigin::createFromString(jsStringRefToWebCoreString(sourceOrigin)), jsStringRefToWebCoreString(destinationProtocol), jsStringRefToWebCoreString(destinationHost), allowDestinationSubdomains); } void TestRunner::setAllowFileAccessFromFileURLs(bool enabled) { if (!mainFrame) return; mainFrame->page()->settings()->setAllowFileAccessFromFileURLs(enabled); } void TestRunner::setAllowUniversalAccessFromFileURLs(bool enabled) { if (!mainFrame) return; mainFrame->page()->settings()->setAllowUniversalAccessFromFileURLs(enabled); } void TestRunner::apiTestNewWindowDataLoadBaseURL(JSStringRef, JSStringRef) { notImplemented(); } void TestRunner::apiTestGoToCurrentBackForwardItem() { notImplemented(); } void TestRunner::setJavaScriptCanAccessClipboard(bool flag) { BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->setJavaScriptCanAccessClipboard(flag); } void TestRunner::setPluginsEnabled(bool) { notImplemented(); } void TestRunner::abortModal() { notImplemented(); } void TestRunner::clearAllApplicationCaches() { notImplemented(); } void TestRunner::setApplicationCacheOriginQuota(unsigned long long) { notImplemented(); } void TestRunner::setMockDeviceOrientation(bool canProvideAlpha, double alpha, bool canProvideBeta, double beta, bool canProvideGamma, double gamma) { DumpRenderTreeSupport::setMockDeviceOrientation(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page(), canProvideAlpha, alpha, canProvideBeta, beta, canProvideGamma, gamma); } void TestRunner::addMockSpeechInputResult(JSStringRef, double, JSStringRef) { notImplemented(); } void TestRunner::setGeolocationPermission(bool allow) { setGeolocationPermissionCommon(allow); DumpRenderTreeSupport::setMockGeolocationPermission(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page(), allow); } void TestRunner::setViewModeMediaFeature(const JSStringRef) { notImplemented(); } void TestRunner::setSerializeHTTPLoads(bool) { // FIXME: Implement if needed for https://bugs.webkit.org/show_bug.cgi?id=50758. notImplemented(); } void TestRunner::setTextDirection(JSStringRef) { notImplemented(); } void TestRunner::goBack() { // FIXME: implement to enable loader/navigation-while-deferring-loads.html notImplemented(); } void TestRunner::setDefersLoading(bool) { // FIXME: implement to enable loader/navigation-while-deferring-loads.html notImplemented(); } JSValueRef TestRunner::originsWithLocalStorage(JSContextRef context) { notImplemented(); return JSValueMakeUndefined(context); } void TestRunner::observeStorageTrackerNotifications(unsigned) { notImplemented(); } void TestRunner::syncLocalStorage() { notImplemented(); } void TestRunner::deleteAllLocalStorage() { notImplemented(); } int TestRunner::numberOfPendingGeolocationPermissionRequests() { return DumpRenderTreeSupport::numberOfPendingGeolocationPermissionRequests(BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()); } bool TestRunner::findString(JSContextRef context, JSStringRef target, JSObjectRef optionsArray) { WebCore::FindOptions options = 0; String nameStr = jsStringRefToWebCoreString(target); JSRetainPtr<JSStringRef> lengthPropertyName(Adopt, JSStringCreateWithUTF8CString("length")); size_t length = 0; if (optionsArray) { JSValueRef lengthValue = JSObjectGetProperty(context, optionsArray, lengthPropertyName.get(), 0); if (!JSValueIsNumber(context, lengthValue)) return false; length = static_cast<size_t>(JSValueToNumber(context, lengthValue, 0)); } for (size_t i = 0; i < length; ++i) { JSValueRef value = JSObjectGetPropertyAtIndex(context, optionsArray, i, 0); if (!JSValueIsString(context, value)) continue; JSRetainPtr<JSStringRef> optionName(Adopt, JSValueToStringCopy(context, value, 0)); if (JSStringIsEqualToUTF8CString(optionName.get(), "CaseInsensitive")) options |= WebCore::CaseInsensitive; else if (JSStringIsEqualToUTF8CString(optionName.get(), "AtWordStarts")) options |= WebCore::AtWordStarts; else if (JSStringIsEqualToUTF8CString(optionName.get(), "TreatMedialCapitalAsWordStart")) options |= WebCore::TreatMedialCapitalAsWordStart; else if (JSStringIsEqualToUTF8CString(optionName.get(), "Backwards")) options |= WebCore::Backwards; else if (JSStringIsEqualToUTF8CString(optionName.get(), "WrapAround")) options |= WebCore::WrapAround; else if (JSStringIsEqualToUTF8CString(optionName.get(), "StartInSelection")) options |= WebCore::StartInSelection; } // FIXME: we don't need to call WebPage::findNextString(), this is a workaround // so that test platform/blackberry/editing/text-iterator/findString-markers.html can pass. // Our layout tests assume find will wrap and highlight all matches. BlackBerry::WebKit::DumpRenderTree::currentInstance()->page()->findNextString(nameStr.utf8().data(), !(options & WebCore::Backwards), !(options & WebCore::CaseInsensitive), true /* wrap */, true /* highlightAllMatches */, false /* selectActiveMatchOnClear */); return mainFrame->page()->findString(nameStr, options); } void TestRunner::deleteLocalStorageForOrigin(JSStringRef) { // FIXME: Implement. } void TestRunner::setValueForUser(JSContextRef context, JSValueRef nodeObject, JSStringRef value) { JSC::ExecState* exec = toJS(context); WebCore::Element* element = toElement(toJS(exec, nodeObject)); if (!element) return; WebCore::HTMLInputElement* inputElement = element->toInputElement(); if (!inputElement) return; inputElement->setValueForUser(jsStringRefToWebCoreString(value)); } long long TestRunner::applicationCacheDiskUsageForOrigin(JSStringRef) { // FIXME: Implement to support getting disk usage by all application caches for an origin. return 0; } void TestRunner::addChromeInputField() { } void TestRunner::removeChromeInputField() { } void TestRunner::focusWebView() { } void TestRunner::setBackingScaleFactor(double) { } void TestRunner::setMockSpeechInputDumpRect(bool) { } void TestRunner::grantWebNotificationPermission(JSStringRef) { } void TestRunner::denyWebNotificationPermission(JSStringRef) { } void TestRunner::removeAllWebNotificationPermissions() { } void TestRunner::simulateWebNotificationClick(JSValueRef) { } void TestRunner::simulateLegacyWebNotificationClick(JSStringRef) { } void TestRunner::resetPageVisibility() { notImplemented(); } void TestRunner::setPageVisibility(const char*) { notImplemented(); } void TestRunner::setAutomaticLinkDetectionEnabled(bool) { notImplemented(); } void TestRunner::setStorageDatabaseIdleInterval(double) { // FIXME: Implement this. notImplemented(); } void TestRunner::closeIdleLocalStorageDatabases() { notImplemented(); }
20,135
6,286
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-01-25 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxscale/ccdefs.hh> #include <mutex> #include <string> #include <unordered_map> #include <maxscale/config_common.hh> #include <maxscale/ssl.hh> #include <maxscale/target.hh> /** * Server configuration parameters names */ extern const char CN_MONITORPW[]; extern const char CN_MONITORUSER[]; extern const char CN_PERSISTMAXTIME[]; extern const char CN_PERSISTPOOLMAX[]; extern const char CN_PROXY_PROTOCOL[]; /** * The SERVER structure defines a backend server. Each server has a name * or IP address for the server, a port that the server listens on and * the name of a protocol module that is loaded to implement the protocol * between the gateway and the server. */ class SERVER : public mxs::Target { public: /** * Stores server version info. Encodes/decodes to/from the version number received from the server. * Also stores the version string and parses information from it. Assumed to rarely change, so reads * are not synchronized. */ class VersionInfo { public: enum class Type { UNKNOWN, /**< Not connected yet */ MYSQL, /**< MySQL 5.5 or later. */ MARIADB, /**< MariaDB 5.5 or later */ XPAND, /**< Xpand node */ BLR /**< Binlog router */ }; struct Version { uint64_t total {0}; /**< Total version number received from server */ uint32_t major {0}; /**< Major version */ uint32_t minor {0}; /**< Minor version */ uint32_t patch {0}; /**< Patch version */ }; /** * Reads in version data. Deduces server type from version string. * * @param version_num Version number from server * @param version_string Version string from server */ void set(uint64_t version_num, const std::string& version_string); /** * Return true if the server is a real database and can process queries. Returns false if server * type is unknown or if the server is a binlogrouter. * * @return True if server is a real database */ bool is_database() const; Type type() const; const Version& version_num() const; const char* version_string() const; private: static const int MAX_VERSION_LEN = 256; mutable std::mutex m_lock; /**< Protects against concurrent writing */ Version m_version_num; /**< Numeric version */ Type m_type {Type::UNKNOWN}; /**< Server type */ char m_version_str[MAX_VERSION_LEN + 1] {'\0'}; /**< Server version string */ }; struct PoolStats { int n_persistent = 0; /**< Current persistent pool */ uint64_t n_new_conn = 0; /**< Times the current pool was empty */ uint64_t n_from_pool = 0; /**< Times when a connection was available from the pool */ int persistmax = 0; /**< Maximum pool size actually achieved since startup */ }; /** * Find a server with the specified name. * * @param name Name of the server * @return The server or NULL if not found */ static SERVER* find_by_unique_name(const std::string& name); /** * Find several servers with the names specified in an array. The returned array is equal in size * to the server_names-array. If any server name was not found, then the corresponding element * will be NULL. * * @param server_names An array of server names * @return Array of servers */ static std::vector<SERVER*> server_find_by_unique_names(const std::vector<std::string>& server_names); virtual ~SERVER() = default; /** * Get server address */ virtual const char* address() const = 0; /** * Get server port */ virtual int port() const = 0; /** * Get server extra port */ virtual int extra_port() const = 0; /** * Is proxy protocol in use? */ virtual bool proxy_protocol() const = 0; /** * Set proxy protocol * * @param proxy_protocol Whether proxy protocol is used */ virtual void set_proxy_protocol(bool proxy_protocol) = 0; /** * Get server character set * * @return The numeric character set or 0 if no character set has been read */ virtual uint8_t charset() const = 0; /** * Set server character set * * @param charset Character set to set */ virtual void set_charset(uint8_t charset) = 0; /** * Connection pool statistics * * @return A reference to the pool statistics object */ virtual PoolStats& pool_stats() = 0; /** * Check if server has disk space threshold settings. * * @return True if limits exist */ virtual bool have_disk_space_limits() const = 0; /** * Get a copy of disk space limit settings. * * @return A copy of settings */ virtual DiskSpaceLimits get_disk_space_limits() const = 0; /** * Is persistent connection pool enabled. * * @return True if enabled */ virtual bool persistent_conns_enabled() const = 0; /** * Update server version. * * @param version_num New numeric version * @param version_str New version string */ virtual void set_version(uint64_t version_num, const std::string& version_str) = 0; /** * Get version information. The contents of the referenced object may change at any time, * although in practice this is rare. * * @return Version information */ virtual const VersionInfo& info() const = 0; /** * Update server address. * * @param address The new address */ virtual bool set_address(const std::string& address) = 0; /** * Update the server port. * * @param new_port New port. The value is not checked but should generally be 1 -- 65535. */ virtual void set_port(int new_port) = 0; /** * Update the server extra port. * * @param new_port New port. The value is not checked but should generally be 1 -- 65535. */ virtual void set_extra_port(int new_port) = 0; /** * @brief Check if a server points to a local MaxScale service * * @return True if the server points to a local MaxScale service */ virtual bool is_mxs_service() const = 0; /** * Set current ping * * @param ping Ping in milliseconds */ virtual void set_ping(int64_t ping) = 0; /** * Set replication lag * * @param lag The current replication lag in seconds */ virtual void set_replication_lag(int64_t lag) = 0; // TODO: Don't expose this to the modules and instead destroy the server // via ServerManager (currently needed by xpandmon) virtual void deactivate() = 0; /** * Set a status bit in the server without locking * * @param bit The bit to set for the server */ virtual void set_status(uint64_t bit) = 0; /** * Clear a status bit in the server without locking * * @param bit The bit to clear for the server */ virtual void clear_status(uint64_t bit) = 0; /** * Assign server status * * @param status Status to assign */ virtual void assign_status(uint64_t status) = 0; /** * Get SSL provider */ virtual const mxs::SSLProvider& ssl() const = 0; virtual mxs::SSLProvider& ssl() = 0; /** * Set server variables * * @param variables Variables and their values to set */ virtual void set_variables(std::unordered_map<std::string, std::string>&& variables) = 0; /** * Get server variable * * @param key Variable name to get * * @return Variable value or empty string if it was not found */ virtual std::string get_variable(const std::string& key) const = 0; /** * Set GTID positions * * @param positions List of pairs for the domain and the GTID position for it */ virtual void set_gtid_list(const std::vector<std::pair<uint32_t, uint64_t>>& positions) = 0; /** * Remove all stored GTID positions */ virtual void clear_gtid_list() = 0; /** * Get current server priority * * This should be used to decide which server is chosen as a master. Currently only galeramon uses it. */ virtual int64_t priority() const = 0; };
9,011
2,642
/* * Created on: Sept 15, 2012 * Author: guille */ #include "date-delegate.h" #include <utils.h> #include <QDateEdit> DateDelegate::DateDelegate() : QStyledItemDelegate() { } void DateDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { int epoch = index.model()->index(index.row(), index.column()).data().toInt(); QDateTime dateTime = utils::toDateTime(epoch); if (option.state & QStyle::State_Selected) { painter->fillRect(option.rect, option.palette.highlight()); painter->save(); painter->setPen(option.palette.highlightedText().color()); } painter->drawText(QRect(option.rect.topLeft(), option.rect.bottomRight()), Qt::AlignCenter, dateTime.date().toString("dd/MM/yyyy")); if (option.state & QStyle::State_Selected) painter->restore(); } QWidget *DateDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex & /*index*/) const { QDateEdit *editor = new QDateEdit(parent); editor->setFrame(false); editor->setDisplayFormat("dd/MM/yyyy"); editor->setCalendarPopup(true); return editor; } void DateDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QDate value = utils::toDate(index.model()->data(index, Qt::EditRole).toInt()); QDateEdit *edit = static_cast<QDateEdit*>(editor); edit->setDate(value); } void DateDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QDateEdit *edit = static_cast<QDateEdit*>(editor); int value = utils::toDateStamp(edit->date()); model->setData(index, value, Qt::EditRole); } void DateDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { editor->setGeometry(option.rect); } DateDelegate::~DateDelegate() { }
2,144
646
//------------------------------------------------------------------------------ // physicsbody.cc // (C) 2012-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "physics/physicsbody.h" namespace Physics { #if (__USE_BULLET__) __ImplementClass(Physics::PhysicsBody, 'PHBO', Bullet::BulletBody); #elif(__USE_PHYSX__) __ImplementClass(Physics::PhysicsBody, 'PHBO', PhysX::PhysXBody); #elif(__USE_HAVOK__) __ImplementClass(Physics::PhysicsBody, 'PHBO', Havok::HavokBody); #else #error "Physics::PhysicsBody not implemented" #endif }
642
210
#include "uv_secnet.hh" #include <iostream> #include <functional> #include <string> #include <sstream> #include <uv.h> #include <memory.h> #include <memory> #include <http_parser.h> typedef struct { int counter = 0; std::shared_ptr<uv_secnet::IConnection> conn = 0; uv_timer_t* timer = nullptr; uv_tcp_t* tcpHandle = nullptr; sockaddr_in* addr = nullptr; uv_secnet::IConnectionObserver* obs = nullptr; } secnet_ctx_s; typedef secnet_ctx_s secnet_ctx_t; void freeHandle(uv_handle_t* handle) { free(handle); } void initCtx (secnet_ctx_t* ctx) { ctx->counter = 0; ctx->conn = nullptr; ctx->timer = (uv_timer_t*)malloc(sizeof(uv_timer_t)); ctx->tcpHandle = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); ctx->addr = (sockaddr_in*)malloc(sizeof(sockaddr_in)); ctx->obs = new uv_secnet::IConnectionObserver(); uv_timer_init(uv_default_loop(), ctx->timer); uv_tcp_init(uv_default_loop(), ctx->tcpHandle); ctx->timer->data = ctx; ctx->tcpHandle->data = ctx; } void freeCtx(secnet_ctx_t* ctx) { free(ctx->timer); uv_close((uv_handle_t*) ctx->tcpHandle, freeHandle); ctx->conn = nullptr; free(ctx->addr); delete ctx->obs; free(ctx); } void timerTick(uv_timer_t* handle) { auto ctx = (secnet_ctx_t*) handle->data; if(++ctx->counter == 20) { std::cout << "Reached final tick, stopping counter" << std::endl; uv_timer_stop(handle); ctx->conn->close(); } else { std::cout << "Processing tick #" << ctx->counter << std::endl; std::stringstream ss; ss << "Hello from C++ tick #" << ctx->counter << std::endl; auto sd = ss.str(); int sl = sd.length(); char* data = (char*)malloc(sl + 1); strcpy(data, sd.c_str()); ctx->conn->write(uv_secnet::Buffer::makeShared(data, sl+1)); } } void connectCb(uv_connect_t* req, int status) { if(status != 0) { std::cout << "Connection Error: " << uv_err_name(status) << std::endl; } else { auto ctx = (secnet_ctx_t*) req->data; auto ssl_ctx = uv_secnet::TLSContext::getDefault(); // ctx->conn = ssl_ctx->secureClientConnection(uv_secnet::TCPConnection::create((uv_stream_t*)req->handle), "google.com"); ctx->conn = uv_secnet::TCPConnection::create((uv_stream_t*)req->handle); ctx->conn->initialize(ctx->obs); uv_secnet::HTTPObject obj("http://locahost:9999/post"); obj.setHeader("Connection", "Upgrade") ->setHeader("Upgrade", "websocket") ->setHeader("Sec-WebSocket-Key", "2BMqVIxuwA32Yuh1ydRutw==") ->setHeader("Sec-WebSocket-Version", "13"); ctx->conn->write(obj.toBuffer()); ctx->conn->close(); } free(req); } void runLoop() { uv_loop_t* loop = uv_default_loop(); secnet_ctx_t* ctx = (secnet_ctx_t*)malloc(sizeof(secnet_ctx_t)); initCtx(ctx); uv_ip4_addr("127.0.0.1", 9999, ctx->addr); // uv_ip4_addr("216.58.201.110", 443, ctx->addr); uv_connect_t* cReq = (uv_connect_t*)malloc(sizeof(uv_connect_t)); cReq->data = ctx; uv_tcp_connect(cReq, ctx->tcpHandle, (sockaddr*)ctx->addr, connectCb); uv_run(loop, UV_RUN_DEFAULT); freeCtx(ctx); } void testUri(std::string url) { auto uri = uv_secnet::Url::parse(url); return; } void on_addr_info(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { auto i4 = AF_INET; auto i6 = AF_INET6; if (status != 0) { char e[1024]; uv_err_name_r(status, e, 1024); std::cout << e << std::endl; return; } if (res->ai_family == AF_INET) { std::cout << inet_ntoa(((sockaddr_in*)res->ai_addr)->sin_addr) << ":" << ((sockaddr_in*)res->ai_addr)->sin_port << std::endl; } std::cout << "DONE!" << std::endl; } class LogObserver : public uv_secnet::IClientObserver { public: uv_secnet::HTTPObject* o; uv_secnet::TCPClient* c; LogObserver() : o(nullptr), c(nullptr) {}; virtual void onClientStatusChanged(uv_secnet::IClient::STATUS status) { std::cout << "Client status changed" << std::endl; }; // <0 - do not reconnect, 0 - reconnect now, >0 - reconnect delay virtual int onClientError(uv_secnet::IClient::ERR, std::string err) { std::cout << "Error: " << err << std::endl; } virtual void onClientData(uv_secnet::buffer_ptr_t data) { // std::cout << "Got data::" << std::endl << std::string(data->base, data->len) << std::endl; } virtual void onClientConnectionStatusChanged(uv_secnet::IClient::CONNECTION_STATUS status) { if (status == uv_secnet::IClient::CONNECTION_STATUS::OPEN) { std::cout << "Connected" << std::endl; c->send(o->toBuffer()); c->close(); } std::cout << "Connection status changed" << std::endl; } }; int main () { // std::string s("https://admin:fickmich@localhost:443/something?query=string"); // runLoop(); // auto buf = uv_secnet::safe_alloc<char>(16); // uv_secnet::randomBytes(buf, 16); // auto data = uv_secnet::vendor::base64_encode((unsigned char*)buf, 16); // std::string body("Text payload, yeah baby!"); // auto buf = uv_secnet::Buffer::makeShared(const_cast<char*>(body.c_str()), body.length()); // uv_secnet::HTTPObject obj(s); // obj.createBody("text/plain", buf) // ->setHeader("X-Auth-Token", "trlalala") // ->setHeader("User-Agent", "fucking_C++_baby!"); // auto b = obj.toBuffer(); // // std::cout << std::string(d, one.length() + two.length()); // std::cout << std::string(b->base, b->len); // std::cout << data << std::endl; uv_loop_t* loop = uv_default_loop(); // uv_secnet::TLSTransform::debug = true; std::string host("https://google.com:443/"); LogObserver o; uv_secnet::TCPClient client(loop, host, &o); auto httpO = uv_secnet::HTTPObject(host); httpO.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.86 Chrome/73.0.3683.86 Safari/537.36"); httpO.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); o.o = &httpO; o.c = &client; client.enableTLS(); client.connect(); uv_run(loop, UV_RUN_DEFAULT); return 0; }
6,105
2,449
/** * \file OSGB.cpp * \brief Implementation for geographic_lib::OSGB class * * Copyright (c) Charles Karney (2010-2017) <charles@karney.com> and licensed * under the MIT/X11 License. For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ #include <geographic_lib/OSGB.hpp> #include <geographic_lib/Utility.hpp> namespace geographic_lib { using namespace std; const char* const OSGB::letters_ = "ABCDEFGHJKLMNOPQRSTUVWXYZ"; const char* const OSGB::digits_ = "0123456789"; const TransverseMercator& OSGB::OSGBTM() { static const TransverseMercator osgbtm(MajorRadius(), Flattening(), CentralScale()); return osgbtm; } Math::real OSGB::computenorthoffset() { real x, y; static const real northoffset = ( OSGBTM().Forward(real(0), OriginLatitude(), real(0), x, y), FalseNorthing() - y ); return northoffset; } void OSGB::GridReference(real x, real y, int prec, std::string& gridref) { CheckCoords(x, y); if (!(prec >= 0 && prec <= maxprec_)) throw GeographicErr("OSGB precision " + Utility::str(prec) + " not in [0, " + Utility::str(int(maxprec_)) + "]"); if (Math::isnan(x) || Math::isnan(y)) { gridref = "INVALID"; return; } char grid[2 + 2 * maxprec_]; int xh = int(floor(x / tile_)), yh = int(floor(y / tile_)); real xf = x - tile_ * xh, yf = y - tile_ * yh; xh += tileoffx_; yh += tileoffy_; int z = 0; grid[z++] = letters_[(tilegrid_ - (yh / tilegrid_) - 1) * tilegrid_ + (xh / tilegrid_)]; grid[z++] = letters_[(tilegrid_ - (yh % tilegrid_) - 1) * tilegrid_ + (xh % tilegrid_)]; // Need extra real because, since C++11, pow(float, int) returns double real mult = real(pow(real(base_), max(tilelevel_ - prec, 0))); int ix = int(floor(xf / mult)), iy = int(floor(yf / mult)); for (int c = min(prec, int(tilelevel_)); c--;) { grid[z + c] = digits_[ ix % base_ ]; ix /= base_; grid[z + c + prec] = digits_[ iy % base_ ]; iy /= base_; } if (prec > tilelevel_) { xf -= floor(xf / mult); yf -= floor(yf / mult); mult = real(pow(real(base_), prec - tilelevel_)); ix = int(floor(xf * mult)); iy = int(floor(yf * mult)); for (int c = prec - tilelevel_; c--;) { grid[z + c + tilelevel_] = digits_[ ix % base_ ]; ix /= base_; grid[z + c + tilelevel_ + prec] = digits_[ iy % base_ ]; iy /= base_; } } int mlen = z + 2 * prec; gridref.resize(mlen); copy(grid, grid + mlen, gridref.begin()); } void OSGB::GridReference(const std::string& gridref, real& x, real& y, int& prec, bool centerp) { int len = int(gridref.size()), p = 0; if (len >= 2 && toupper(gridref[0]) == 'I' && toupper(gridref[1]) == 'N') { x = y = Math::NaN(); prec = -2; // For compatibility with MGRS::Reverse. return; } char grid[2 + 2 * maxprec_]; for (int i = 0; i < len; ++i) { if (!isspace(gridref[i])) { if (p >= 2 + 2 * maxprec_) throw GeographicErr("OSGB string " + gridref + " too long"); grid[p++] = gridref[i]; } } len = p; p = 0; if (len < 2) throw GeographicErr("OSGB string " + gridref + " too short"); if (len % 2) throw GeographicErr("OSGB string " + gridref + " has odd number of characters"); int xh = 0, yh = 0; while (p < 2) { int i = Utility::lookup(letters_, grid[p++]); if (i < 0) throw GeographicErr("Illegal prefix character " + gridref); yh = yh * tilegrid_ + tilegrid_ - (i / tilegrid_) - 1; xh = xh * tilegrid_ + (i % tilegrid_); } xh -= tileoffx_; yh -= tileoffy_; int prec1 = (len - p)/2; real unit = tile_, x1 = unit * xh, y1 = unit * yh; for (int i = 0; i < prec1; ++i) { unit /= base_; int ix = Utility::lookup(digits_, grid[p + i]), iy = Utility::lookup(digits_, grid[p + i + prec1]); if (ix < 0 || iy < 0) throw GeographicErr("Encountered a non-digit in " + gridref); x1 += unit * ix; y1 += unit * iy; } if (centerp) { x1 += unit/2; y1 += unit/2; } x = x1; y = y1; prec = prec1; } void OSGB::CheckCoords(real x, real y) { // Limits are all multiples of 100km and are all closed on the lower end // and open on the upper end -- and this is reflected in the error // messages. NaNs are let through. if (x < minx_ || x >= maxx_) throw GeographicErr("Easting " + Utility::str(int(floor(x/1000))) + "km not in OSGB range [" + Utility::str(minx_/1000) + "km, " + Utility::str(maxx_/1000) + "km)"); if (y < miny_ || y >= maxy_) throw GeographicErr("Northing " + Utility::str(int(floor(y/1000))) + "km not in OSGB range [" + Utility::str(miny_/1000) + "km, " + Utility::str(maxy_/1000) + "km)"); } } // namespace geographic_lib
5,461
1,972
/******************************************************************************** Copyright 2017 Frank Imeson and Stephen L. Smith 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 "formula.hpp" using namespace formula; #define DEBUG /******************************************************************************** * * Functions * ********************************************************************************/ /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (const Lit &a, const Lit &b) { Formula* formula = new Formula(F_OR); formula->add(~a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (const Lit &a, Formula* b) { Formula* formula = new Formula(F_OR); formula->add(~a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (Formula *a, const Lit &b) { Formula* formula = new Formula(F_OR); a->negate(); formula->add(a); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_implies (Formula *a, Formula* b) { Formula* formula = new Formula(F_OR); formula->add(a->negate()); formula->add(b); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::get_solution (const Solver &solver, vec<Lit> &lits, Var max_var) { if (max_var < 0) max_var = solver.model.size()-1; for (unsigned int i=0; i<=max_var; i++) lits.push( mkLit(i, solver.model[i] == l_False) ); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_iff (const Lit &a, const Lit &b) { Formula* formula = new Formula(F_OR); Formula* f0 = new Formula(F_AND); Formula* f1 = new Formula(F_AND); f0->add(a); f0->add(b); f1->add(~a); f1->add(~b); formula->add(f0); formula->add(f1); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_at_least_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) formula->add(mkLit(var_list[i], false)); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) { Formula* f0 = new Formula(F_AND); for (int j=0; j<var_list.size(); j++) { if (i == j) f0->add(mkLit(var_list[j], false)); else f0->add(mkLit(var_list[j], true)); } formula->add(f0); } return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula* formula::constraint_at_most_one_in_a_set (const vector<int> &var_list) { Formula* formula = new Formula(F_OR); for (int i=0; i<var_list.size(); i++) { Formula* f0 = new Formula(F_AND); for (int j=0; j<var_list.size(); j++) { if (i == j) f0->add(mkLit(var_list[j], false)); else f0->add(mkLit(var_list[j], true)); } formula->add(f0); } Formula* f0 = new Formula(F_AND); for (int i=0; i<var_list.size(); i++) { f0->add(mkLit(var_list[i], true)); } formula->add(f0); return formula; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::negate_solution (const vec<Lit> &lits, Solver &solver) { vec<Lit> nlits; for (unsigned int i=0; i<lits.size(); i++) nlits.push( ~lits[i] ); solver.addClause(nlits); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Lit formula::translate (const int &lit) { return mkLit(abs(lit)-1, (lit<0)); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int formula::translate (const Lit &lit) { return sign(lit) ? -var(lit)-1:var(lit)+1; } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const Con &connective) { switch (connective) { case F_AND: return "^"; case F_OR: return "v"; default: return " "; } } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const Lit &lit) { stringstream out; if (sign(lit)) out << "-"; else out << " "; out << (var(lit)+1); return out.str(); } /************************************************************//** * @brief * @return string representation of connective * @version v0.01b ****************************************************************/ string formula::str (const vec<Lit> &lits) { string result; for (unsigned int i=0; i<lits.size(); i++) result += str(lits[i]) + " "; return result; } /************************************************************//** * @brief * @return negated connective, -1 on error * @version v0.01b ****************************************************************/ Con formula::negate (const Con &connective) { switch (connective) { case F_AND: return F_OR; case F_OR: return F_AND; default: return -1; } } /************************************************************//** * @brief * @return negated litteral * @version v0.01b ****************************************************************/ Lit formula::negate (const Lit &lit) { return ~lit; } /******************************************************************************** * * Formula Class * ********************************************************************************/ /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::~Formula () { clear(); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::Formula () : connective(F_AND) , max_var(0) {} /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Formula::Formula (Con _connective) : connective(_connective) , max_var(0) {} /************************************************************//** * @brief Clear all contents of Formula recursively * @version v0.01b ****************************************************************/ int Formula::clear () { try { for (unsigned int i=0; i<formuli.size(); i++) { if (formuli[i] != NULL) { delete formuli[i]; formuli[i] = NULL; } } formuli.clear(); } catch(...) { perror("error Formula::clear(): "); exit(1); } return 0; } /************************************************************//** * @brief Negate entire formula * @return 0 on succession, < 0 on error * @version v0.01b ****************************************************************/ int Formula::negate () { connective = ::negate(connective); if (connective < 0) return connective; for (unsigned int i=0; i<lits.size(); i++) lits[i] = ::negate(lits[i]); for (unsigned int i=0; i<formuli.size(); i++) { int rtn = formuli[i]->negate(); if (rtn < 0) return rtn; } return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ void Formula::track_max (const Var &var) { if (var > max_var) max_var = var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const Lit &lit) { track_max(var(lit)); lits.push(lit); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const int &lit) { return add(translate(lit)); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (const vec<Lit> &lits) { for (unsigned int i=0; i<lits.size(); i++) add(lits[i]); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::add (Formula *formula) { track_max(formula->maxVar()); if (formula != NULL) formuli.push(formula); return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Var Formula::newVar () { max_var++; return max_var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ Var Formula::maxVar () { return max_var; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ int Formula::export_cnf (Lit &out, Formula *formula, Solver *solver) { if ( (formula == NULL && solver == NULL) || (formula != NULL && solver != NULL) ) return -1; // setup vars in solver // translation requires a new var to replace nested phrases if (solver != NULL) { while (solver->nVars() < max_var+1) solver->newVar(); out = mkLit( solver->newVar(), false ); } else { while (formula->maxVar() < max_var) formula->newVar(); out = mkLit( formula->newVar(), false ); } vec<Lit> big_clause; switch (connective) { case F_OR: // Variables for (unsigned int i=0; i<lits.size(); i++) { big_clause.push(lits[i]); if (solver != NULL) { solver->addClause(~lits[i], out); } else { Formula *phrase = new Formula(F_OR); phrase->add(~lits[i]); phrase->add(out); formula->add(phrase); } } // Nested formuli for (unsigned int i=0; i<formuli.size(); i++) { Lit cnf_out; if (int err = formuli[i]->export_cnf(cnf_out, formula, solver) < 0) return err; big_clause.push(cnf_out); if (solver != NULL) { solver->addClause(~cnf_out, out); } else { Formula *phrase = new Formula(F_OR); phrase->add(~cnf_out); phrase->add(out); formula->add(phrase); } } big_clause.push(~out); break; case F_AND: // Variables for (unsigned int i=0; i<lits.size(); i++) { big_clause.push(~lits[i]); if (solver != NULL) { solver->addClause(lits[i], ~out); } else { Formula *phrase = new Formula(F_OR); phrase->add(lits[i]); phrase->add(~out); formula->add(phrase); } } // Nested formuli for (unsigned int i=0; i<formuli.size(); i++) { Lit cnf_out; if (int err = formuli[i]->export_cnf(cnf_out, formula, solver) < 0) return err; big_clause.push(~cnf_out); if (solver != NULL) { solver->addClause(cnf_out, ~out); } else { Formula *phrase = new Formula(F_OR); phrase->add(cnf_out); phrase->add(~out); formula->add(phrase); } } big_clause.push(out); break; default: break; } if (solver != NULL) { solver->addClause(big_clause); } else { Formula *phrase = new Formula(F_OR); phrase->add(big_clause); formula->add(phrase); } return 0; } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ string Formula::str () { return str(string("")); } /************************************************************//** * @brief * @version v0.01b ****************************************************************/ string Formula::str (string prefix) { string result = prefix; if (formuli.size() == 0) { // result += "( "; for (unsigned int i=0; i<lits.size(); i++) result += ::str(lits[i]) + " " + ::str(connective) + " "; result.resize(result.size()-2); // result += ")\n"; result += "\n"; } else { result += prefix + ::str(connective) + '\n'; for (unsigned int i=0; i<lits.size(); i++) result += prefix + " " + ::str(lits[i]) + '\n'; for (unsigned int i=0; i<formuli.size(); i++) result += formuli[i]->str(prefix+" "); } return result; }
16,195
4,865
/* * Copyright 2016-2017 Nikolay Aleksiev. All rights reserved. * License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE */ // Copyright Epic Games, Inc. All Rights Reserved. // Modifications for Unreal Engine #pragma once #include "declare.hpp" #include "imp_DepthStencil.hpp" #include "ns.hpp" #include "device.hpp" MTLPP_BEGIN namespace ue4 { template<> struct ITable<id<MTLDepthStencilState>, void> : public IMPTable<id<MTLDepthStencilState>, void>, public ITableCacheRef { ITable() { } ITable(Class C) : IMPTable<id<MTLDepthStencilState>, void>(C) { } }; template<> inline ITable<MTLStencilDescriptor*, void>* CreateIMPTable(MTLStencilDescriptor* handle) { static ITable<MTLStencilDescriptor*, void> Table(object_getClass(handle)); return &Table; } template<> inline ITable<MTLDepthStencilDescriptor*, void>* CreateIMPTable(MTLDepthStencilDescriptor* handle) { static ITable<MTLDepthStencilDescriptor*, void> Table(object_getClass(handle)); return &Table; } } namespace mtlpp { enum class CompareFunction { Never = 0, Less = 1, Equal = 2, LessEqual = 3, Greater = 4, NotEqual = 5, GreaterEqual = 6, Always = 7, } MTLPP_AVAILABLE(10_11, 8_0); enum class StencilOperation { Keep = 0, Zero = 1, Replace = 2, IncrementClamp = 3, DecrementClamp = 4, Invert = 5, IncrementWrap = 6, DecrementWrap = 7, } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT StencilDescriptor : public ns::Object<MTLStencilDescriptor*> { public: StencilDescriptor(); StencilDescriptor(ns::Ownership const retain) : ns::Object<MTLStencilDescriptor*>(retain) {} StencilDescriptor(MTLStencilDescriptor* handle, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<MTLStencilDescriptor*>(handle, retain) { } CompareFunction GetStencilCompareFunction() const; StencilOperation GetStencilFailureOperation() const; StencilOperation GetDepthFailureOperation() const; StencilOperation GetDepthStencilPassOperation() const; uint32_t GetReadMask() const; uint32_t GetWriteMask() const; void SetStencilCompareFunction(CompareFunction stencilCompareFunction); void SetStencilFailureOperation(StencilOperation stencilFailureOperation); void SetDepthFailureOperation(StencilOperation depthFailureOperation); void SetDepthStencilPassOperation(StencilOperation depthStencilPassOperation); void SetReadMask(uint32_t readMask); void SetWriteMask(uint32_t writeMask); } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT DepthStencilDescriptor : public ns::Object<MTLDepthStencilDescriptor*> { public: DepthStencilDescriptor(); DepthStencilDescriptor(MTLDepthStencilDescriptor* handle, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<MTLDepthStencilDescriptor*>(handle, retain) { } CompareFunction GetDepthCompareFunction() const; bool IsDepthWriteEnabled() const; ns::AutoReleased<StencilDescriptor> GetFrontFaceStencil() const; ns::AutoReleased<StencilDescriptor> GetBackFaceStencil() const; ns::AutoReleased<ns::String> GetLabel() const; void SetDepthCompareFunction(CompareFunction depthCompareFunction) const; void SetDepthWriteEnabled(bool depthWriteEnabled) const; void SetFrontFaceStencil(const StencilDescriptor& frontFaceStencil) const; void SetBackFaceStencil(const StencilDescriptor& backFaceStencil) const; void SetLabel(const ns::String& label) const; } MTLPP_AVAILABLE(10_11, 8_0); class MTLPP_EXPORT DepthStencilState : public ns::Object<ns::Protocol<id<MTLDepthStencilState>>::type> { public: DepthStencilState() { } DepthStencilState(ns::Protocol<id<MTLDepthStencilState>>::type handle, ue4::ITableCache* cache = nullptr, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<ns::Protocol<id<MTLDepthStencilState>>::type>(handle, retain, ue4::ITableCacheRef(cache).GetDepthStencilState(handle)) { } ns::AutoReleased<ns::String> GetLabel() const; ns::AutoReleased<Device> GetDevice() const; } MTLPP_AVAILABLE(10_11, 8_0); } MTLPP_END
4,486
1,532
// Example 7.12, page 198 // Schaum's Outline of Programming with C++ by John R. Hubbard // Copyright McGraw-Hill, 1996 using namespace std; #include <iostream> // NOTA: ORMAI DEPRECATO DALLO STANDARD ATTUALE: // EX0712.cc:10: warning: deprecated conversion from string constant to ‘char*’ int main() { char* name[] = { "George Washington", "John Adams", "Thomas Jefferson" }; cout << "The names are:\n"; for (int i = 0; i < 3; i++) cout << "\t" << i << ". [" << name[i] << "]" << endl; return 0; }
524
206
#include "config.h" #include "utils.hpp" #include <phosphor-logging/elog-errors.hpp> #include <phosphor-logging/elog.hpp> #include <phosphor-logging/log.hpp> #include <xyz/openbmc_project/Common/error.hpp> #if OPENSSL_VERSION_NUMBER < 0x10100000L #include <string.h> static void* OPENSSL_zalloc(size_t num) { void* ret = OPENSSL_malloc(num); if (ret != NULL) { memset(ret, 0, num); } return ret; } EVP_MD_CTX* EVP_MD_CTX_new(void) { return (EVP_MD_CTX*)OPENSSL_zalloc(sizeof(EVP_MD_CTX)); } void EVP_MD_CTX_free(EVP_MD_CTX* ctx) { EVP_MD_CTX_cleanup(ctx); OPENSSL_free(ctx); } #endif // OPENSSL_VERSION_NUMBER < 0x10100000L namespace utils { using sdbusplus::exception::SdBusError; using namespace phosphor::logging; constexpr auto HIOMAPD_PATH = "/xyz/openbmc_project/Hiomapd"; constexpr auto HIOMAPD_INTERFACE = "xyz.openbmc_project.Hiomapd.Control"; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; std::string getService(sdbusplus::bus::bus& bus, const std::string& path, const std::string& intf) { auto mapper = bus.new_method_call(MAPPER_BUSNAME, MAPPER_PATH, MAPPER_INTERFACE, "GetObject"); mapper.append(path, std::vector<std::string>({intf})); try { auto mapperResponseMsg = bus.call(mapper); std::vector<std::pair<std::string, std::vector<std::string>>> mapperResponse; mapperResponseMsg.read(mapperResponse); if (mapperResponse.empty()) { log<level::ERR>("Error reading mapper response"); throw std::runtime_error("Error reading mapper response"); } return mapperResponse[0].first; } catch (const sdbusplus::exception::SdBusError& ex) { log<level::ERR>("Mapper call failed", entry("METHOD=%d", "GetObject"), entry("PATH=%s", path.c_str()), entry("INTERFACE=%s", intf.c_str())); throw std::runtime_error("Mapper call failed"); } } void hiomapdSuspend(sdbusplus::bus::bus& bus) { auto service = getService(bus, HIOMAPD_PATH, HIOMAPD_INTERFACE); auto method = bus.new_method_call(service.c_str(), HIOMAPD_PATH, HIOMAPD_INTERFACE, "Suspend"); try { bus.call_noreply(method); } catch (const SdBusError& e) { log<level::ERR>("Error in mboxd suspend call", entry("ERROR=%s", e.what())); } } void hiomapdResume(sdbusplus::bus::bus& bus) { auto service = getService(bus, HIOMAPD_PATH, HIOMAPD_INTERFACE); auto method = bus.new_method_call(service.c_str(), HIOMAPD_PATH, HIOMAPD_INTERFACE, "Resume"); method.append(true); // Indicate PNOR is modified try { bus.call_noreply(method); } catch (const SdBusError& e) { log<level::ERR>("Error in mboxd suspend call", entry("ERROR=%s", e.what())); } } } // namespace utils
3,097
1,113
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <java/text/DateFormat_Field.hpp> extern void unimplemented_(const char16_t* name); java::text::DateFormat_Field::DateFormat_Field(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } java::text::DateFormat_Field::DateFormat_Field(::java::lang::String* name, int32_t calendarField) : DateFormat_Field(*static_cast< ::default_init_tag* >(0)) { ctor(name, calendarField); } java::text::DateFormat_Field*& java::text::DateFormat_Field::AM_PM() { clinit(); return AM_PM_; } java::text::DateFormat_Field* java::text::DateFormat_Field::AM_PM_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_MONTH() { clinit(); return DAY_OF_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_WEEK() { clinit(); return DAY_OF_WEEK_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_WEEK_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_WEEK_IN_MONTH() { clinit(); return DAY_OF_WEEK_IN_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_WEEK_IN_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::DAY_OF_YEAR() { clinit(); return DAY_OF_YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::DAY_OF_YEAR_; java::text::DateFormat_Field*& java::text::DateFormat_Field::ERA() { clinit(); return ERA_; } java::text::DateFormat_Field* java::text::DateFormat_Field::ERA_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR0() { clinit(); return HOUR0_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR0_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR1() { clinit(); return HOUR1_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR1_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR_OF_DAY0() { clinit(); return HOUR_OF_DAY0_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR_OF_DAY0_; java::text::DateFormat_Field*& java::text::DateFormat_Field::HOUR_OF_DAY1() { clinit(); return HOUR_OF_DAY1_; } java::text::DateFormat_Field* java::text::DateFormat_Field::HOUR_OF_DAY1_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MILLISECOND() { clinit(); return MILLISECOND_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MILLISECOND_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MINUTE() { clinit(); return MINUTE_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MINUTE_; java::text::DateFormat_Field*& java::text::DateFormat_Field::MONTH() { clinit(); return MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::SECOND() { clinit(); return SECOND_; } java::text::DateFormat_Field* java::text::DateFormat_Field::SECOND_; java::text::DateFormat_Field*& java::text::DateFormat_Field::TIME_ZONE() { clinit(); return TIME_ZONE_; } java::text::DateFormat_Field* java::text::DateFormat_Field::TIME_ZONE_; java::text::DateFormat_Field*& java::text::DateFormat_Field::WEEK_OF_MONTH() { clinit(); return WEEK_OF_MONTH_; } java::text::DateFormat_Field* java::text::DateFormat_Field::WEEK_OF_MONTH_; java::text::DateFormat_Field*& java::text::DateFormat_Field::WEEK_OF_YEAR() { clinit(); return WEEK_OF_YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::WEEK_OF_YEAR_; java::text::DateFormat_Field*& java::text::DateFormat_Field::YEAR() { clinit(); return YEAR_; } java::text::DateFormat_Field* java::text::DateFormat_Field::YEAR_; java::text::DateFormat_FieldArray*& java::text::DateFormat_Field::calendarToFieldMapping() { clinit(); return calendarToFieldMapping_; } java::text::DateFormat_FieldArray* java::text::DateFormat_Field::calendarToFieldMapping_; java::util::Map*& java::text::DateFormat_Field::instanceMap() { clinit(); return instanceMap_; } java::util::Map* java::text::DateFormat_Field::instanceMap_; constexpr int64_t java::text::DateFormat_Field::serialVersionUID; void ::java::text::DateFormat_Field::ctor(::java::lang::String* name, int32_t calendarField) { /* stub */ /* super::ctor(); */ unimplemented_(u"void ::java::text::DateFormat_Field::ctor(::java::lang::String* name, int32_t calendarField)"); } int32_t java::text::DateFormat_Field::getCalendarField() { /* stub */ return calendarField ; /* getter */ } java::text::DateFormat_Field* java::text::DateFormat_Field::ofCalendarField(int32_t calendarField) { /* stub */ clinit(); unimplemented_(u"java::text::DateFormat_Field* java::text::DateFormat_Field::ofCalendarField(int32_t calendarField)"); return 0; } java::lang::Object* java::text::DateFormat_Field::readResolve() { /* stub */ unimplemented_(u"java::lang::Object* java::text::DateFormat_Field::readResolve()"); return 0; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* java::text::DateFormat_Field::class_() { static ::java::lang::Class* c = ::class_(u"java.text.DateFormat.Field", 26); return c; } java::lang::Class* java::text::DateFormat_Field::getClass0() { return class_(); }
5,463
1,890
/* MIT LICENSE Copyright (c) 2014-2021 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 <ctime> #include <string> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <iomanip> #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include "ISPose.h" #include "DeviceLogKML.h" #include "ISLogger.h" #include "ISConstants.h" using namespace std; void cDeviceLogKML::InitDeviceForWriting(int pHandle, std::string timestamp, std::string directory, uint64_t maxDiskSpace, uint32_t maxFileSize) { memset(&m_Log, 0, sizeof(m_Log)); cDeviceLog::InitDeviceForWriting(pHandle, timestamp, directory, maxDiskSpace, maxFileSize); } bool cDeviceLogKML::CloseAllFiles() { cDeviceLog::CloseAllFiles(); for (int kid = 0; kid < cDataKML::MAX_NUM_KID; kid++) { // Close file CloseWriteFile(kid, m_Log[kid]); } return true; } bool cDeviceLogKML::CloseWriteFile(int kid, sKmlLog &log) { // Ensure we have data int64_t dataSize = (int64_t)log.data.size(); if (dataSize <= 0) { return false; } // Ensure directory exists if (m_directory.empty()) { return false; } _MKDIR(m_directory.c_str()); // Create filename log.fileCount++; int serNum = m_devInfo.serialNumber; if (!serNum) { serNum = m_pHandle; } log.fileName = GetNewFileName(serNum, log.fileCount, m_kml.GetDatasetName(kid).c_str()); #define BUF_SIZE 100 char buf[BUF_SIZE]; int styleCnt = 1; string altitudeMode; string iconScale = "0.5"; string labelScale = "0.5"; string iconUrl; if (m_showPointTimestamps) labelScale = "0.5"; else labelScale = "0.01"; // Altitude mode if(m_altClampToGround) altitudeMode = "clampToGround"; else altitudeMode = "absolute"; // Style string styleStr, colorStr; iconUrl = "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png"; // iconUrl = "http://earth.google.com/images/kml-icons/track-directional/track-none.png"; // colors are ABGR switch (kid) { case cDataKML::KID_INS: iconUrl = "http://earth.google.com/images/kml-icons/track-directional/track-0.png"; colorStr = "ff00ffff"; // yellow break; case cDataKML::KID_GPS: colorStr = "ff0000ff"; // red break; case cDataKML::KID_GPS1: colorStr = "ffff0000"; // blue break; case cDataKML::KID_RTK: colorStr = "ffffff00"; // cyan break; case cDataKML::KID_REF: iconUrl = "http://earth.google.com/images/kml-icons/track-directional/track-0.png"; colorStr = "ffff00ff"; // magenta break; } // Add XML version info and document TiXmlElement *Style, *LineStyle, *IconStyle, *LabelStyle, *Placemark, *Point, *LineString, *heading, *elem, *href; TiXmlDocument tDoc; TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "UTF-8", ""); tDoc.LinkEndChild(decl); TiXmlElement* kml = new TiXmlElement("kml"); tDoc.LinkEndChild(kml); TiXmlElement* Document = new TiXmlElement("Document"); kml->LinkEndChild(Document); kml->SetAttribute("xmlns", "http://www.opengis.net/kml/2.2"); kml->SetAttribute("xmlns:gx", "http://www.google.com/kml/ext/2.2"); // Show sample (dot) if (m_showPoints) { // Style styleStr = string("stylesel_"); Style = new TiXmlElement("Style"); Style->SetAttribute("id", styleStr); Document->LinkEndChild(Style); // Icon style IconStyle = new TiXmlElement("IconStyle"); Style->LinkEndChild(IconStyle); elem = new TiXmlElement("color"); elem->LinkEndChild(new TiXmlText(colorStr)); IconStyle->LinkEndChild(elem); elem = new TiXmlElement("colorMode"); elem->LinkEndChild(new TiXmlText("normal")); IconStyle->LinkEndChild(elem); elem = new TiXmlElement("scale"); elem->LinkEndChild(new TiXmlText(iconScale)); IconStyle->LinkEndChild(elem); heading = new TiXmlElement("heading"); heading->LinkEndChild(new TiXmlText("0")); IconStyle->LinkEndChild(heading); href = new TiXmlElement("href"); href->LinkEndChild(new TiXmlText(iconUrl)); elem = new TiXmlElement("Icon"); elem->LinkEndChild(href); IconStyle->LinkEndChild(elem); // Label style LabelStyle = new TiXmlElement("LabelStyle"); Style->LinkEndChild(LabelStyle); elem = new TiXmlElement("colorMode"); elem->LinkEndChild(new TiXmlText("normal")); LabelStyle->LinkEndChild(elem); elem = new TiXmlElement("scale"); elem->LinkEndChild(new TiXmlText(labelScale)); LabelStyle->LinkEndChild(elem); double nextTime = log.data[0].time; for (size_t i = 0; i < log.data.size(); i++) { sKmlLogData& item = (log.data[i]); // Log only every iconUpdatePeriodSec if (item.time < nextTime) { continue; } nextTime = item.time - fmod(item.time, m_pointUpdatePeriodSec) + m_pointUpdatePeriodSec; // Placemark Placemark = new TiXmlElement("Placemark"); Document->LinkEndChild(Placemark); // Name elem = new TiXmlElement("name"); ostringstream timeStream; switch (kid) { case cDataKML::KID_GPS: case cDataKML::KID_GPS1: case cDataKML::KID_GPS2: case cDataKML::KID_RTK: timeStream << fixed << setprecision(1) << item.time; break; default: timeStream << fixed << setprecision(3) << item.time; break; } elem->LinkEndChild(new TiXmlText(timeStream.str())); Placemark->LinkEndChild(elem); // styleUrl elem = new TiXmlElement("styleUrl"); if (item.theta[2] != 0.0f) { // Style - to indicate heading string styleCntStr = styleStr + to_string(styleCnt++); TiXmlNode *StyleNode = Style->Clone(); StyleNode->ToElement()->SetAttribute("id", styleCntStr); StyleNode->FirstChildElement("IconStyle")->FirstChildElement("heading")->FirstChild()->ToText()->SetValue(to_string(item.theta[2] * C_RAD2DEG_F)); Document->LinkEndChild(StyleNode); elem->LinkEndChild(new TiXmlText("#" + styleCntStr)); } else { elem->LinkEndChild(new TiXmlText("#" + styleStr)); } Placemark->LinkEndChild(elem); Point = new TiXmlElement("Point"); Placemark->LinkEndChild(Point); elem = new TiXmlElement("coordinates"); #if 1 double lat = _CLAMP(item.lla[0] * DEG2RADMULT, -C_PIDIV2, C_PIDIV2) * RAD2DEGMULT; double lon = _CLAMP(item.lla[1] * DEG2RADMULT, -C_PI, C_PI) * RAD2DEGMULT; double alt = _CLAMP(item.lla[2], -1000, 100000); snprintf(buf, BUF_SIZE, "%.8lf,%.8lf,%.3lf", lon, lat, alt); elem->LinkEndChild(new TiXmlText(buf)); #else ostringstream coordinateStream; // Not getting digits of precision coordinateStream << fixed << setprecision(8) << item->lla[1] << "," // Lat << item->lla[0] << "," // Lon << setprecision(3) << item->lla[2] << " "; // Alt elem->LinkEndChild(new TiXmlText(coordinateStream.str())); #endif Point->LinkEndChild(elem); elem = new TiXmlElement("altitudeMode"); elem->LinkEndChild(new TiXmlText(altitudeMode)); Point->LinkEndChild(elem); } }// if (m_showSample) // Show path (track) if (m_showTracks) { // Track style styleStr = string("stylesel_") + to_string(styleCnt++); Style = new TiXmlElement("Style"); Style->SetAttribute("id", styleStr); Document->LinkEndChild(Style); LineStyle = new TiXmlElement("LineStyle"); Style->LinkEndChild(LineStyle); elem = new TiXmlElement("color"); elem->LinkEndChild(new TiXmlText(colorStr)); LineStyle->LinkEndChild(elem); elem = new TiXmlElement("colorMode"); elem->LinkEndChild(new TiXmlText("normal")); LineStyle->LinkEndChild(elem); elem = new TiXmlElement("width"); elem->LinkEndChild(new TiXmlText("2")); LineStyle->LinkEndChild(elem); // Track Placemark = new TiXmlElement("Placemark"); Document->LinkEndChild(Placemark); elem = new TiXmlElement("name"); elem->LinkEndChild(new TiXmlText("Tracks")); Placemark->LinkEndChild(elem); elem = new TiXmlElement("description"); elem->LinkEndChild(new TiXmlText("SN tracks")); Placemark->LinkEndChild(elem); elem = new TiXmlElement("styleUrl"); elem->LinkEndChild(new TiXmlText("#" + styleStr)); Placemark->LinkEndChild(elem); LineString = new TiXmlElement("LineString"); Placemark->LinkEndChild(LineString); ostringstream coordinateStream; int j = 0; for (size_t i = 0; i < log.data.size(); i++) { sKmlLogData& item = (log.data[i]); double lat = _CLAMP(item.lla[0] * DEG2RADMULT, -C_PIDIV2, C_PIDIV2) * RAD2DEGMULT; double lon = _CLAMP(item.lla[1] * DEG2RADMULT, -C_PI, C_PI) * RAD2DEGMULT; double alt = _CLAMP(item.lla[2], -1000, 100000); if (i >= log.data.size()-2) { j++; } snprintf(buf, BUF_SIZE, "%.8lf,%.8lf,%.3lf ", lon, lat, alt); // if (strcmp("-111.65863637,40.05570543,1418.282 ", buf) == 0) // { // j++; // } // qDebug() << string(buf); // std::cout << "Value of str is : "; coordinateStream << string(buf); } elem = new TiXmlElement("coordinates"); elem->LinkEndChild(new TiXmlText(coordinateStream.str())); LineString->LinkEndChild(elem); elem = new TiXmlElement("extrude"); elem->LinkEndChild(new TiXmlText("1")); LineString->LinkEndChild(elem); elem = new TiXmlElement("altitudeMode"); elem->LinkEndChild(new TiXmlText(altitudeMode)); LineString->LinkEndChild(elem); } // Write XML to file if (!tDoc.SaveFile(log.fileName.c_str())) { return false; } // Remove data log.data.clear(); return true; } bool cDeviceLogKML::OpenWithSystemApp(void) { #if PLATFORM_IS_WINDOWS for (int kid = 0; kid < cDataKML::MAX_NUM_KID; kid++) { sKmlLog &log = m_Log[kid]; if (log.fileName.empty()) { continue; } std::wstring stemp = std::wstring(log.fileName.begin(), log.fileName.end()); LPCWSTR filename = stemp.c_str(); ShellExecuteW(0, 0, filename, 0, 0, SW_SHOW); } #endif return true; } bool cDeviceLogKML::SaveData(p_data_hdr_t *dataHdr, const uint8_t *dataBuf) { cDeviceLog::SaveData(dataHdr, dataBuf); // Save data to file if (!WriteDateToFile(dataHdr, dataBuf)) { return false; } // Convert formats uDatasets& d = (uDatasets&)(*dataBuf); switch (dataHdr->id) { case DID_INS_2: ins_1_t ins1; ins1.week = d.ins2.week; ins1.timeOfWeek = d.ins2.timeOfWeek; ins1.hdwStatus = d.ins2.hdwStatus; ins1.insStatus = d.ins2.insStatus; quat2euler(d.ins2.qn2b, ins1.theta); memcpy(ins1.uvw, d.ins2.uvw, 12); memcpy(ins1.lla, d.ins2.lla, 24); p_data_hdr_t dHdr = { DID_INS_1 , sizeof(ins_1_t), 0 }; // Save data to file if (!WriteDateToFile(&dHdr, (uint8_t*)&ins1)) { return false; } break; } return true; } bool cDeviceLogKML::WriteDateToFile(const p_data_hdr_t *dataHdr, const uint8_t* dataBuf) { int kid = cDataKML::DID_TO_KID(dataHdr->id); // Only use selected data if (kid < 0) { return true; } // Reference current log sKmlLog &log = m_Log[kid]; // Write date to file m_kml.WriteDataToFile(log.data, dataHdr, dataBuf); // File byte size int nBytes = (int)(log.data.size() * cDataKML::BYTES_PER_KID(kid)); log.fileSize = nBytes; m_fileSize = _MAX(m_fileSize, log.fileSize); m_logSize = nBytes; if (log.fileSize >= m_maxFileSize) { // Close existing file if (!CloseWriteFile(kid, log)) { return false; } } return true; } p_data_t* cDeviceLogKML::ReadData() { p_data_t* data = NULL; // Read data from chunk while (!(data = ReadDataFromChunk())) { // Read next chunk from file if (!ReadChunkFromFile()) { return NULL; } } // Read is good cDeviceLog::OnReadData(data); return data; } p_data_t* cDeviceLogKML::ReadDataFromChunk() { return NULL; } bool cDeviceLogKML::ReadChunkFromFile() { return true; } void cDeviceLogKML::SetSerialNumber(uint32_t serialNumber) { m_devInfo.serialNumber = serialNumber; }
12,747
5,252
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 6 End-User License Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020). End User License Agreement: www.juce.com/juce-6-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { //============================================================================== #if ! JUCE_ANDROID && ! JUCE_IOS && ! JUCE_MAC bool PushNotifications::Notification::isValid() const noexcept { return true; } #endif PushNotifications::Notification::Notification (const Notification& other) : identifier (other.identifier), title (other.title), body (other.body), subtitle (other.subtitle), groupId (other.groupId), badgeNumber (other.badgeNumber), soundToPlay (other.soundToPlay), properties (other.properties), category (other.category), triggerIntervalSec (other.triggerIntervalSec), repeat (other.repeat), icon (other.icon), channelId (other.channelId), largeIcon (other.largeIcon), tickerText (other.tickerText), actions (other.actions), progress (other.progress), person (other.person), type (other.type), priority (other.priority), lockScreenAppearance (other.lockScreenAppearance), publicVersion (other.publicVersion.get() != nullptr ? new Notification (*other.publicVersion) : nullptr), groupSortKey (other.groupSortKey), groupSummary (other.groupSummary), accentColour (other.accentColour), ledColour (other.ledColour), ledBlinkPattern (other.ledBlinkPattern), vibrationPattern (other.vibrationPattern), shouldAutoCancel (other.shouldAutoCancel), localOnly (other.localOnly), ongoing (other.ongoing), alertOnlyOnce (other.alertOnlyOnce), timestampVisibility (other.timestampVisibility), badgeIconType (other.badgeIconType), groupAlertBehaviour (other.groupAlertBehaviour), timeoutAfterMs (other.timeoutAfterMs) { } //============================================================================== JUCE_IMPLEMENT_SINGLETON (PushNotifications) PushNotifications::PushNotifications() #if JUCE_PUSH_NOTIFICATIONS : pimpl (new Pimpl (*this)) #endif { } PushNotifications::~PushNotifications() { clearSingletonInstance(); } void PushNotifications::addListener (Listener* l) { listeners.add (l); } void PushNotifications::removeListener (Listener* l) { listeners.remove (l); } void PushNotifications::requestPermissionsWithSettings (const PushNotifications::Settings& settings) { #if JUCE_PUSH_NOTIFICATIONS && (JUCE_IOS || JUCE_MAC) pimpl->requestPermissionsWithSettings (settings); #else ignoreUnused (settings); listeners.call ([] (Listener& l) { l.notificationSettingsReceived ({}); }); #endif } void PushNotifications::requestSettingsUsed() { #if JUCE_PUSH_NOTIFICATIONS && (JUCE_IOS || JUCE_MAC) pimpl->requestSettingsUsed(); #else listeners.call ([] (Listener& l) { l.notificationSettingsReceived ({}); }); #endif } bool PushNotifications::areNotificationsEnabled() const { #if JUCE_PUSH_NOTIFICATIONS return pimpl->areNotificationsEnabled(); #else return false; #endif } void PushNotifications::getDeliveredNotifications() const { #if JUCE_PUSH_NOTIFICATIONS pimpl->getDeliveredNotifications(); #endif } void PushNotifications::removeAllDeliveredNotifications() { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeAllDeliveredNotifications(); #endif } String PushNotifications::getDeviceToken() const { #if JUCE_PUSH_NOTIFICATIONS return pimpl->getDeviceToken(); #else return {}; #endif } void PushNotifications::setupChannels (const Array<ChannelGroup>& groups, const Array<Channel>& channels) { #if JUCE_PUSH_NOTIFICATIONS pimpl->setupChannels (groups, channels); #else ignoreUnused (groups, channels); #endif } void PushNotifications::getPendingLocalNotifications() const { #if JUCE_PUSH_NOTIFICATIONS pimpl->getPendingLocalNotifications(); #endif } void PushNotifications::removeAllPendingLocalNotifications() { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeAllPendingLocalNotifications(); #endif } void PushNotifications::subscribeToTopic (const String& topic) { #if JUCE_PUSH_NOTIFICATIONS pimpl->subscribeToTopic (topic); #else ignoreUnused (topic); #endif } void PushNotifications::unsubscribeFromTopic (const String& topic) { #if JUCE_PUSH_NOTIFICATIONS pimpl->unsubscribeFromTopic (topic); #else ignoreUnused (topic); #endif } void PushNotifications::sendLocalNotification (const Notification& n) { #if JUCE_PUSH_NOTIFICATIONS pimpl->sendLocalNotification (n); #else ignoreUnused (n); #endif } void PushNotifications::removeDeliveredNotification (const String& identifier) { #if JUCE_PUSH_NOTIFICATIONS pimpl->removeDeliveredNotification (identifier); #else ignoreUnused (identifier); #endif } void PushNotifications::removePendingLocalNotification (const String& identifier) { #if JUCE_PUSH_NOTIFICATIONS pimpl->removePendingLocalNotification (identifier); #else ignoreUnused (identifier); #endif } void PushNotifications::sendUpstreamMessage (const String& serverSenderId, const String& collapseKey, const String& messageId, const String& messageType, int timeToLive, const StringPairArray& additionalData) { #if JUCE_PUSH_NOTIFICATIONS pimpl->sendUpstreamMessage (serverSenderId, collapseKey, messageId, messageType, timeToLive, additionalData); #else ignoreUnused (serverSenderId, collapseKey, messageId, messageType); ignoreUnused (timeToLive, additionalData); #endif } } // namespace juce
6,969
2,169
#include "ExplosionEvent.h" Go::ExplosionEvent::ExplosionEvent(ModuleLibrary *module) : IEvent(module) { } void Go::ExplosionEvent::Call(const alt::CEvent *ev) { static auto call = GET_FUNC(Library, "altExplosionEvent", bool (*)(alt::IPlayer* source, Entity target, Position position, short explosionType, unsigned int explosionFX)); if (call == nullptr) { alt::ICore::Instance().LogError("Couldn't not call ExplosionEvent."); return; } auto event = dynamic_cast<const alt::CExplosionEvent *>(ev); auto target = event->GetTarget(); auto source = event->GetSource().Get(); auto pos = event->GetPosition(); auto expFX = event->GetExplosionFX(); auto expType = event->GetExplosionType(); Entity e = Go::Runtime::GetInstance()->GetEntity(target); Position cPos; cPos.x = pos.x; cPos.y = pos.y; cPos.z = pos.z; auto cancel = call(source, e, cPos, static_cast<short>(expType), expFX); if(!cancel) { event->Cancel(); } }
1,018
347
/***************************************************************************** * Xidi * DirectInput interface for XInput controllers. ***************************************************************************** * Authored by Samuel Grossman * Copyright (c) 2016-2021 *************************************************************************//** * @file VirtualDirectInputDevice.cpp * Implementation of an IDirectInputDevice interface wrapper around virtual * controllers. *****************************************************************************/ #include "ApiDirectInput.h" #include "ApiGUID.h" #include "ControllerIdentification.h" #include "ControllerTypes.h" #include "DataFormat.h" #include "Message.h" #include "Strings.h" #include "VirtualController.h" #include "VirtualDirectInputDevice.h" #include <atomic> #include <cstdio> #include <cstring> #include <memory> #include <optional> // -------- MACROS --------------------------------------------------------- // /// Logs a DirectInput interface method invocation and returns. #define LOG_INVOCATION_AND_RETURN(result, severity) \ do \ { \ const HRESULT kResult = (result); \ Message::OutputFormatted(severity, L"Invoked %s on Xidi virtual controller %u, result = 0x%08x.", __FUNCTIONW__ L"()", (1 + controller->GetIdentifier()), kResult); \ return kResult; \ } while (false) /// Logs a DirectInput property-related method invocation and returns. #define LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, propvalfmt, ...) \ do \ { \ const HRESULT kResult = (result); \ Message::OutputFormatted(severity, L"Invoked function %s on Xidi virtual controller %u, result = 0x%08x, property = %s" propvalfmt L".", __FUNCTIONW__ L"()", (1 + controller->GetIdentifier()), kResult, PropertyGuidString(rguidprop), ##__VA_ARGS__); \ return kResult; \ } while (false) /// Logs a DirectInput property-related method without a value and returns. #define LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(result, severity, rguidprop) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L"") /// Logs a DirectInput property-related method where the value is provided in a DIPROPDWORD structure and returns. #define LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(result, severity, rguidprop, ppropval) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L", value = { dwData = %u }", ((LPDIPROPDWORD)ppropval)->dwData) /// Logs a DirectInput property-related method where the value is provided in a DIPROPRANGE structure and returns. #define LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(result, severity, rguidprop, ppropval) LOG_PROPERTY_INVOCATION_AND_RETURN(result, severity, rguidprop, L", value = { lMin = %ld, lMax = %ld }", ((LPDIPROPRANGE)ppropval)->lMin, ((LPDIPROPRANGE)ppropval)->lMax) /// Produces and returns a human-readable string from a given DirectInput property GUID. #define DI_PROPERTY_STRING(rguid, diprop) if (&diprop == &rguid) return _CRT_WIDE(#diprop); namespace Xidi { // -------- INTERNAL FUNCTIONS ----------------------------------------- // /// Converts from axis type enumerator to axis type GUID. /// @param [in] axis Axis type enumerator to convert. /// @return Read-only reference to the corresponding GUID object. static const GUID& AxisTypeGuid(Controller::EAxis axis) { switch (axis) { case Controller::EAxis::X: return GUID_XAxis; case Controller::EAxis::Y: return GUID_YAxis; case Controller::EAxis::Z: return GUID_ZAxis; case Controller::EAxis::RotX: return GUID_RxAxis; case Controller::EAxis::RotY: return GUID_RyAxis; case Controller::EAxis::RotZ: return GUID_RzAxis; default: return GUID_Unknown; } } /// Returns a string representation of the way in which a controller element is identified. /// @param [in] dwHow Value to check. /// @return String representation of the identification method. static const wchar_t* IdentificationMethodString(DWORD dwHow) { switch (dwHow) { case DIPH_DEVICE: return L"DIPH_DEVICE"; case DIPH_BYOFFSET: return L"DIPH_BYOFFSET"; case DIPH_BYUSAGE: return L"DIPH_BYUSAGE"; case DIPH_BYID: return L"DIPH_BYID"; default: return L"(unknown)"; } } /// Returns a human-readable string that represents the specified property GUID. /// @param [in] pguid GUID to check. /// @return String representation of the GUID's semantics. static const wchar_t* PropertyGuidString(REFGUID rguidProp) { switch ((size_t)&rguidProp) { #if DIRECTINPUT_VERSION >= 0x0800 case ((size_t)&DIPROP_KEYNAME): return L"DIPROP_KEYNAME"; case ((size_t)&DIPROP_CPOINTS): return L"DIPROP_CPOINTS"; case ((size_t)&DIPROP_APPDATA): return L"DIPROP_APPDATA"; case ((size_t)&DIPROP_SCANCODE): return L"DIPROP_SCANCODE"; case ((size_t)&DIPROP_VIDPID): return L"DIPROP_VIDPID"; case ((size_t)&DIPROP_USERNAME): return L"DIPROP_USERNAME"; case ((size_t)&DIPROP_TYPENAME): return L"DIPROP_TYPENAME"; #endif case ((size_t)&DIPROP_BUFFERSIZE): return L"DIPROP_BUFFERSIZE"; case ((size_t)&DIPROP_AXISMODE): return L"DIPROP_AXISMODE"; case ((size_t)&DIPROP_GRANULARITY): return L"DIPROP_GRANULARITY"; case ((size_t)&DIPROP_RANGE): return L"DIPROP_RANGE"; case ((size_t)&DIPROP_DEADZONE): return L"DIPROP_DEADZONE"; case ((size_t)&DIPROP_SATURATION): return L"DIPROP_SATURATION"; case ((size_t)&DIPROP_FFGAIN): return L"DIPROP_FFGAIN"; case ((size_t)&DIPROP_FFLOAD): return L"DIPROP_FFLOAD"; case ((size_t)&DIPROP_AUTOCENTER): return L"DIPROP_AUTOCENTER"; case ((size_t)&DIPROP_CALIBRATIONMODE): return L"DIPROP_CALIBRATIONMODE"; case ((size_t)&DIPROP_CALIBRATION): return L"DIPROP_CALIBRATION"; case ((size_t)&DIPROP_GUIDANDPATH): return L"DIPROP_GUIDANDPATH"; case ((size_t)&DIPROP_INSTANCENAME): return L"DIPROP_INSTANCENAME"; case ((size_t)&DIPROP_PRODUCTNAME): return L"DIPROP_PRODUCTNAME"; case ((size_t)&DIPROP_JOYSTICKID): return L"DIPROP_JOYSTICKID"; case ((size_t)&DIPROP_GETPORTDISPLAYNAME): return L"DIPROP_GETPORTDISPLAYNAME"; case ((size_t)&DIPROP_PHYSICALRANGE): return L"DIPROP_PHYSICALRANGE"; case ((size_t)&DIPROP_LOGICALRANGE): return L"DIPROP_LOGICALRANGE"; default: return L"(unknown)"; } } /// Performs property-specific validation of the supplied property header. /// Ensures the header exists and all sizes are correct. /// @param [in] rguidProp GUID of the property for which the header is being validated. /// @param [in] pdiph Pointer to the property header structure to validate. /// @return `true` if the header is valid, `false` otherwise. static bool IsPropertyHeaderValid(REFGUID rguidProp, LPCDIPROPHEADER pdiph) { if (nullptr == pdiph) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected null property header for %s.", PropertyGuidString(rguidProp)); return false; } else if ((sizeof(DIPROPHEADER) != pdiph->dwHeaderSize)) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPHEADER (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPHEADER), (unsigned int)pdiph->dwHeaderSize); return false; } else if ((DIPH_DEVICE == pdiph->dwHow) && (0 != pdiph->dwObj)) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect object identification value used with DIPH_DEVICE (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)0, (unsigned int)pdiph->dwObj); return false; } // Look for reasons why the property header might be invalid and reject it if any are found. switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): case ((size_t)&DIPROP_DEADZONE): case ((size_t)&DIPROP_GRANULARITY): case ((size_t)&DIPROP_SATURATION): // Axis mode, deadzone, granularity, and saturation all use DIPROPDWORD. if (sizeof(DIPROPDWORD) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPDWORD (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPDWORD), (unsigned int)pdiph->dwSize); return false; } break; case ((size_t)&DIPROP_BUFFERSIZE): case ((size_t)&DIPROP_FFGAIN): case ((size_t)&DIPROP_JOYSTICKID): // Buffer size, force feedback gain, and joystick ID all use DIPROPDWORD and are exclusively device-wide properties. if (DIPH_DEVICE != pdiph->dwHow) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect object identification method for this property (expected %s, got %s).", PropertyGuidString(rguidProp), IdentificationMethodString(DIPH_DEVICE), IdentificationMethodString(pdiph->dwHow)); return false; } else if (sizeof(DIPROPDWORD) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPDWORD (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPDWORD), (unsigned int)pdiph->dwSize); return false; } break; case ((size_t)&DIPROP_RANGE): case ((size_t)&DIPROP_LOGICALRANGE): case ((size_t)&DIPROP_PHYSICALRANGE): // Range-related properties use DIPROPRANGE. if (sizeof(DIPROPRANGE) != pdiph->dwSize) { Message::OutputFormatted(Message::ESeverity::Warning, L"Rejected invalid property header for %s: Incorrect size for DIPROPRANGE (expected %u, got %u).", PropertyGuidString(rguidProp), (unsigned int)sizeof(DIPROPRANGE), (unsigned int)pdiph->dwSize); return false; } break; default: // Any property not listed here is not supported by Xidi and therefore not validated by it. Message::OutputFormatted(Message::ESeverity::Warning, L"Skipped property header validation because the property %s is not supported.", PropertyGuidString(rguidProp)); return true; } Message::OutputFormatted(Message::ESeverity::Info, L"Accepted valid property header for %s.", PropertyGuidString(rguidProp)); return true; } /// Dumps the top-level components of a property request. /// @param [in] rguidProp GUID of the property. /// @param [in] pdiph Pointer to the property header. /// @param [in] requestTypeIsSet `true` if the request type is SetProperty, `false` if it is GetProperty. static void DumpPropertyRequest(REFGUID rguidProp, LPCDIPROPHEADER pdiph, bool requestTypeIsSet) { constexpr Message::ESeverity kDumpSeverity = Message::ESeverity::Debug; if (Message::WillOutputMessageOfSeverity(kDumpSeverity)) { Message::Output(kDumpSeverity, L"Begin dump of property request."); Message::Output(kDumpSeverity, L" Metadata:"); Message::OutputFormatted(kDumpSeverity, L" operation = %sProperty", ((true == requestTypeIsSet) ? L"Set" : L"Get")); Message::OutputFormatted(kDumpSeverity, L" rguidProp = %s", PropertyGuidString(rguidProp)); Message::Output(kDumpSeverity, L" Header:"); if (nullptr == pdiph) { Message::Output(kDumpSeverity, L" (missing)"); } else { Message::OutputFormatted(kDumpSeverity, L" dwSize = %u", pdiph->dwSize); Message::OutputFormatted(kDumpSeverity, L" dwHeaderSize = %u", pdiph->dwHeaderSize); Message::OutputFormatted(kDumpSeverity, L" dwObj = %u (0x%08x)", pdiph->dwObj, pdiph->dwObj); Message::OutputFormatted(kDumpSeverity, L" dwHow = %u (%s)", pdiph->dwHow, IdentificationMethodString(pdiph->dwHow)); } Message::Output(kDumpSeverity, L"End dump of property request."); } } /// Fills the specified buffer with a friendly string representation of the specified controller element. /// Default version does nothing. /// @tparam CharType String character type, either `char` or `wchar_t`. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <typename CharType> static void ElementToString(Controller::SElementIdentifier element, CharType* buf, int bufcount) { // Nothing to do here. } /// Fills the specified buffer with a friendly string representation of the specified controller element, specialized for ASCII. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <> static void ElementToString<char>(Controller::SElementIdentifier element, char* buf, int bufcount) { switch (element.type) { case Controller::EElementType::Axis: switch (element.axis) { case Controller::EAxis::X: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_X, _countof(XIDI_AXIS_NAME_X)); break; case Controller::EAxis::Y: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_Y, _countof(XIDI_AXIS_NAME_Y)); break; case Controller::EAxis::Z: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_Z, _countof(XIDI_AXIS_NAME_Z)); break; case Controller::EAxis::RotX: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RX, _countof(XIDI_AXIS_NAME_RX)); break; case Controller::EAxis::RotY: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RY, _countof(XIDI_AXIS_NAME_RY)); break; case Controller::EAxis::RotZ: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_RZ, _countof(XIDI_AXIS_NAME_RZ)); break; default: strncpy_s(buf, bufcount, XIDI_AXIS_NAME_UNKNOWN, _countof(XIDI_AXIS_NAME_UNKNOWN)); break; } break; case Controller::EElementType::Button: sprintf_s(buf, bufcount, XIDI_BUTTON_NAME_FORMAT, (1 + (unsigned int)element.button)); break; case Controller::EElementType::Pov: strncpy_s(buf, bufcount, XIDI_POV_NAME, _countof(XIDI_POV_NAME)); break; case Controller::EElementType::WholeController: strncpy_s(buf, bufcount, XIDI_WHOLE_CONTROLLER_NAME, _countof(XIDI_WHOLE_CONTROLLER_NAME)); break; } } /// Fills the specified buffer with a friendly string representation of the specified controller element, specialized for ASCII. /// @param [in] element Controller element for which a string is desired. /// @param [out] buf Buffer to be filled with the string. /// @param [in] bufcount Buffer size in number of characters. template <> static void ElementToString<wchar_t>(Controller::SElementIdentifier element, wchar_t* buf, int bufcount) { switch (element.type) { case Controller::EElementType::Axis: switch (element.axis) { case Controller::EAxis::X: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_X), _countof(_CRT_WIDE(XIDI_AXIS_NAME_X))); break; case Controller::EAxis::Y: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_Y), _countof(_CRT_WIDE(XIDI_AXIS_NAME_Y))); break; case Controller::EAxis::Z: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_Z), _countof(_CRT_WIDE(XIDI_AXIS_NAME_Z))); break; case Controller::EAxis::RotX: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RX), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RX))); break; case Controller::EAxis::RotY: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RY), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RY))); break; case Controller::EAxis::RotZ: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_RZ), _countof(_CRT_WIDE(XIDI_AXIS_NAME_RZ))); break; default: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_AXIS_NAME_UNKNOWN), _countof(_CRT_WIDE(XIDI_AXIS_NAME_UNKNOWN))); break; } break; case Controller::EElementType::Button: swprintf_s(buf, bufcount, _CRT_WIDE(XIDI_BUTTON_NAME_FORMAT), (1 + (unsigned int)element.button)); break; case Controller::EElementType::Pov: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_POV_NAME), _countof(_CRT_WIDE(XIDI_POV_NAME))); break; case Controller::EElementType::WholeController: wcsncpy_s(buf, bufcount, _CRT_WIDE(XIDI_WHOLE_CONTROLLER_NAME), _countof(_CRT_WIDE(XIDI_WHOLE_CONTROLLER_NAME))); break; } } /// Computes the offset in a virtual controller's "native" data packet. /// For application information only. Cannot be used to identify objects. /// Application is presented with the image of a native data packet that stores axes first, then buttons (one byte per button), then POV. /// @param [in] controllerElement Virtual controller element for which a native offset is desired. /// @return Native offset value for providing to applications. static TOffset NativeOffsetForElement(Controller::SElementIdentifier controllerElement) { switch (controllerElement.type) { case Controller::EElementType::Axis: return offsetof(Controller::SState, axis[(int)controllerElement.axis]); case Controller::EElementType::Button: return offsetof(Controller::SState, button) + (TOffset)controllerElement.button; case Controller::EElementType::Pov: return offsetof(Controller::SState, button) + (TOffset)Controller::EButton::Count; default: // This should never happen. return DataFormat::kInvalidOffsetValue; } } /// Fills the specified object instance information structure with information about the specified controller element. /// Size member must already be initialized because multiple versions of the structure exist, so it is used to determine which members to fill in. /// @tparam charMode Selects between ASCII ("A" suffix) and Unicode ("W") suffix versions of types and interfaces. /// @param [in] controllerCapabilities Capabilities that describe the layout of the virtual controller. /// @param [in] controllerElement Virtual controller element about which to fill information. /// @param [in] offset Offset to place into the object instance information structure. /// @param objectInfo [out] Structure to be filled with instance information. template <ECharMode charMode> static void FillObjectInstanceInfo(const Controller::SCapabilities controllerCapabilities, Controller::SElementIdentifier controllerElement, TOffset offset, typename DirectInputDeviceType<charMode>::DeviceObjectInstanceType* objectInfo) { objectInfo->dwOfs = offset; ElementToString(controllerElement, objectInfo->tszName, _countof(objectInfo->tszName)); switch (controllerElement.type) { case Controller::EElementType::Axis: objectInfo->guidType = AxisTypeGuid(controllerElement.axis); objectInfo->dwType = DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE((int)controllerCapabilities.FindAxis(controllerElement.axis)); objectInfo->dwFlags = DIDOI_POLLED | DIDOI_ASPECTPOSITION; break; case Controller::EElementType::Button: objectInfo->guidType = GUID_Button; objectInfo->dwType = DIDFT_PSHBUTTON | DIDFT_MAKEINSTANCE((int)controllerElement.button); objectInfo->dwFlags = DIDOI_POLLED; break; case Controller::EElementType::Pov: objectInfo->guidType = GUID_POV; objectInfo->dwType = DIDFT_POV | DIDFT_MAKEINSTANCE(0); objectInfo->dwFlags = DIDOI_POLLED; break; } // DirectInput versions 5 and higher include extra members in this structure, and this is indicated on input using the size member of the structure. if (objectInfo->dwSize > sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceCompatType)) { // These fields are zeroed out because Xidi does not currently offer any of the functionality they represent. objectInfo->dwFFMaxForce = 0; objectInfo->dwFFForceResolution = 0; objectInfo->wCollectionNumber = 0; objectInfo->wDesignatorIndex = 0; objectInfo->wUsagePage = 0; objectInfo->wUsage = 0; objectInfo->dwDimension = 0; objectInfo->wExponent = 0; objectInfo->wReportId = 0; } } /// Signals the specified event if its handle is valid. /// @param [in] eventHandle Handle that can be used to identify the desired event object. static inline void SignalEventIfEnabled(HANDLE eventHandle) { if ((NULL != eventHandle) && (INVALID_HANDLE_VALUE != eventHandle)) SetEvent(eventHandle); } // -------- CONSTRUCTION AND DESTRUCTION ------------------------------- // // See "VirtualDirectInputDevice.h" for documentation. template <ECharMode charMode> VirtualDirectInputDevice<charMode>::VirtualDirectInputDevice(std::unique_ptr<Controller::VirtualController>&& controller) : controller(std::move(controller)), dataFormat(), refCount(1), stateChangeEventHandle(NULL) { // Nothing to do here. } // -------- INSTANCE METHODS ------------------------------------------- // // See "VirtualDirectInputDevice.h" for documentation. template <ECharMode charMode> std::optional<Controller::SElementIdentifier> VirtualDirectInputDevice<charMode>::IdentifyElement(DWORD dwObj, DWORD dwHow) const { switch (dwHow) { case DIPH_DEVICE: // Whole device is referenced. // Per DirectInput documentation, the object identifier must be 0. if (0 == dwObj) return Controller::SElementIdentifier({.type = Controller::EElementType::WholeController}); break; case DIPH_BYOFFSET: // Controller element is being identified by offset. // Object identifier is an offset into the application's data format. if (true == IsApplicationDataFormatSet()) return dataFormat->GetElementForOffset(dwObj); break; case DIPH_BYID: // Controller element is being identified by instance identifier. // Object identifier contains type and index, and the latter refers to the controller's reported capabilities. if ((unsigned int)DIDFT_GETINSTANCE(dwObj) >= 0) { const unsigned int kType = (unsigned int)DIDFT_GETTYPE(dwObj); const unsigned int kIndex = (unsigned int)DIDFT_GETINSTANCE(dwObj); switch (kType) { case DIDFT_ABSAXIS: if ((kIndex < (unsigned int)Controller::EAxis::Count) && (kIndex < (unsigned int)controller->GetCapabilities().numAxes)) return Controller::SElementIdentifier({.type = Controller::EElementType::Axis, .axis = controller->GetCapabilities().axisType[kIndex]}); break; case DIDFT_PSHBUTTON: if ((kIndex < (unsigned int)Controller::EButton::Count) && (kIndex < (unsigned int)controller->GetCapabilities().numButtons)) return Controller::SElementIdentifier({.type = Controller::EElementType::Button, .button = (Controller::EButton)kIndex}); break; case DIDFT_POV: if (kIndex == 0) return Controller::SElementIdentifier({.type = Controller::EElementType::Pov}); break; } } break; } return std::nullopt; } // -------- METHODS: IUnknown ------------------------------------------ // // See IUnknown documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::QueryInterface(REFIID riid, LPVOID* ppvObj) { if (nullptr == ppvObj) return E_POINTER; bool validInterfaceRequested = false; if (ECharMode::W == charMode) { #if DIRECTINPUT_VERSION >= 0x0800 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice8W)) #else if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice7W) || IsEqualIID(riid, IID_IDirectInputDevice2W) || IsEqualIID(riid, IID_IDirectInputDeviceW)) #endif validInterfaceRequested = true; } else { #if DIRECTINPUT_VERSION >= 0x0800 if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice8A)) #else if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDirectInputDevice7A) || IsEqualIID(riid, IID_IDirectInputDevice2A) || IsEqualIID(riid, IID_IDirectInputDeviceA)) #endif validInterfaceRequested = true; } if (true == validInterfaceRequested) { AddRef(); *ppvObj = this; return S_OK; } return E_NOINTERFACE; } // --------- template <ECharMode charMode> ULONG VirtualDirectInputDevice<charMode>::AddRef(void) { return ++refCount; } // --------- template <ECharMode charMode> ULONG VirtualDirectInputDevice<charMode>::Release(void) { const unsigned long numRemainingRefs = --refCount; if (0 == numRemainingRefs) delete this; return (ULONG)numRemainingRefs; } // -------- METHODS: IDirectInputDevice COMMON ------------------------- // // See DirectInput documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Acquire(void) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; // Controller acquisition is a no-op for Xidi virtual controllers. // However, DirectInput documentation requires that the application data format already be set. if (false == IsApplicationDataFormatSet()) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::CreateEffect(REFGUID rguid, LPCDIEFFECT lpeff, LPDIRECTINPUTEFFECT* ppdeff, LPUNKNOWN punkOuter) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumCreatedEffectObjects(LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback, LPVOID pvRef, DWORD fl) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumEffects(DirectInputDeviceType<charMode>::EnumEffectsCallbackType lpCallback, LPVOID pvRef, DWORD dwEffType) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumEffectsInFile(DirectInputDeviceType<charMode>::ConstStringType lptszFileName, LPDIENUMEFFECTSINFILECALLBACK pec, LPVOID pvRef, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::EnumObjects(DirectInputDeviceType<charMode>::EnumObjectsCallbackType lpCallback, LPVOID pvRef, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; const bool willEnumerateAxes = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_ABSAXIS))); const bool willEnumerateButtons = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_PSHBUTTON))); const bool willEnumeratePov = ((DIDFT_ALL == dwFlags) || (0 != (dwFlags & DIDFT_POV))); if (nullptr == lpCallback) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); if ((true == willEnumerateAxes) || (true == willEnumerateButtons) || (true == willEnumeratePov)) { std::unique_ptr<DirectInputDeviceType<charMode>::DeviceObjectInstanceType> objectDescriptor = std::make_unique<DirectInputDeviceType<charMode>::DeviceObjectInstanceType>(); const Controller::SCapabilities controllerCapabilities = controller->GetCapabilities(); if (true == willEnumerateAxes) { for (int i = 0; i < controllerCapabilities.numAxes; ++i) { const Controller::EAxis kAxis = controllerCapabilities.axisType[i]; const Controller::SElementIdentifier kAxisIdentifier = {.type = Controller::EElementType::Axis, .axis = kAxis}; const TOffset kAxisOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kAxisIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kAxisIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kAxisIdentifier, kAxisOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } if (true == willEnumerateButtons) { for (int i = 0; i < controllerCapabilities.numButtons; ++i) { const Controller::EButton kButton = (Controller::EButton)i; const Controller::SElementIdentifier kButtonIdentifier = {.type = Controller::EElementType::Button, .button = kButton}; const TOffset kButtonOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kButtonIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kButtonIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kButtonIdentifier, kButtonOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } if (true == willEnumeratePov) { if (true == controllerCapabilities.hasPov) { const Controller::SElementIdentifier kPovIdentifier = {.type = Controller::EElementType::Pov}; const TOffset kPovOffset = ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(kPovIdentifier).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(kPovIdentifier)); *objectDescriptor = {.dwSize = sizeof(*objectDescriptor)}; FillObjectInstanceInfo<charMode>(controllerCapabilities, kPovIdentifier, kPovOffset, objectDescriptor.get()); switch (lpCallback(objectDescriptor.get(), pvRef)) { case DIENUM_CONTINUE: break; case DIENUM_STOP: LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } } } } LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Escape(LPDIEFFESCAPE pesc) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetCapabilities(LPDIDEVCAPS lpDIDevCaps) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == lpDIDevCaps) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (lpDIDevCaps->dwSize) { case (sizeof(DIDEVCAPS)): // Force feedback information, only present in the latest version of the structure. lpDIDevCaps->dwFFSamplePeriod = 0; lpDIDevCaps->dwFFMinTimeResolution = 0; lpDIDevCaps->dwFirmwareRevision = 0; lpDIDevCaps->dwHardwareRevision = 0; lpDIDevCaps->dwFFDriverVersion = 0; case (sizeof(DIDEVCAPS_DX3)): // Top-level controller information is common to all virtual controllers. lpDIDevCaps->dwFlags = DIDC_ATTACHED | DIDC_EMULATED | DIDC_POLLEDDEVICE | DIDC_POLLEDDATAFORMAT; lpDIDevCaps->dwDevType = DINPUT_DEVTYPE_XINPUT_GAMEPAD; // Information about controller layout comes from controller capabilities. lpDIDevCaps->dwAxes = controller->GetCapabilities().numAxes; lpDIDevCaps->dwButtons = controller->GetCapabilities().numButtons; lpDIDevCaps->dwPOVs = ((true == controller->GetCapabilities().hasPov) ? 1 : 0); break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceData(DWORD cbObjectData, LPDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; static constexpr Message::ESeverity kMethodSeverityForError = Message::ESeverity::Info; // DIDEVICEOBJECTDATA and DIDEVICEOBJECTDATA_DX3 are defined identically for all DirectInput versions below 8. // There is therefore no need to differentiate, as the distinction between "dinput" and "dinput8" takes care of it. if ((false == IsApplicationDataFormatSet()) || (nullptr == pdwInOut) || (sizeof(DIDEVICEOBJECTDATA) != cbObjectData)) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); switch (dwFlags) { case 0: case DIGDD_PEEK: break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); } if (false == controller->IsEventBufferEnabled()) LOG_INVOCATION_AND_RETURN(DIERR_NOTBUFFERED, kMethodSeverityForError); auto lock = controller->Lock(); const DWORD kNumEventsAffected = std::min(*pdwInOut, (DWORD)controller->GetEventBufferCount()); const bool kEventBufferOverflowed = controller->IsEventBufferOverflowed(); const bool kShouldPopEvents = (0 == (dwFlags & DIGDD_PEEK)); if (nullptr != rgdod) { for (DWORD i = 0; i < kNumEventsAffected; ++i) { const Controller::StateChangeEventBuffer::SEvent& event = controller->GetEventBufferEvent(i); ZeroMemory(&rgdod[i], sizeof(rgdod[i])); rgdod[i].dwOfs = dataFormat->GetOffsetForElement(event.data.element).value(); // A value should always be present. rgdod[i].dwTimeStamp = event.timestamp; rgdod[i].dwSequence = event.sequence; switch (event.data.element.type) { case Controller::EElementType::Axis: rgdod[i].dwData = (DWORD)DataFormat::DirectInputAxisValue(event.data.value.axis); break; case Controller::EElementType::Button: rgdod[i].dwData = (DWORD)DataFormat::DirectInputButtonValue(event.data.value.button); break; case Controller::EElementType::Pov: rgdod[i].dwData = (DWORD)DataFormat::DirectInputPovValue(event.data.value.povDirection); break; default: LOG_INVOCATION_AND_RETURN(DIERR_GENERIC, kMethodSeverityForError); // This should never happen. break; } } } if (true == kShouldPopEvents) controller->PopEventBufferOldestEvents(kNumEventsAffected); *pdwInOut = kNumEventsAffected; LOG_INVOCATION_AND_RETURN(((true == kEventBufferOverflowed) ? DI_BUFFEROVERFLOW : DI_OK), kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceInfo(DirectInputDeviceType<charMode>::DeviceInstanceType* pdidi) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == pdidi) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (pdidi->dwSize) { case (sizeof(DirectInputDeviceType<charMode>::DeviceInstanceType)): case (sizeof(DirectInputDeviceType<charMode>::DeviceInstanceCompatType)): break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } FillVirtualControllerInfo(*pdidi, controller->GetIdentifier()); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetDeviceState(DWORD cbData, LPVOID lpvData) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; static constexpr Message::ESeverity kMethodSeverityForError = Message::ESeverity::Info; if ((nullptr == lpvData) || (false == IsApplicationDataFormatSet()) || (cbData < dataFormat->GetPacketSizeBytes())) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverityForError); bool writeDataPacketResult = false; do { auto lock = controller->Lock(); writeDataPacketResult = dataFormat->WriteDataPacket(lpvData, cbData, controller->GetStateRef()); } while (false); LOG_INVOCATION_AND_RETURN(((true == writeDataPacketResult) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetEffectInfo(DirectInputDeviceType<charMode>::EffectInfoType* pdei, REFGUID rguid) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetForceFeedbackState(LPDWORD pdwOut) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetObjectInfo(DirectInputDeviceType<charMode>::DeviceObjectInstanceType* pdidoi, DWORD dwObj, DWORD dwHow) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == pdidoi) LOG_INVOCATION_AND_RETURN(E_POINTER, kMethodSeverity); switch (pdidoi->dwSize) { case (sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceType)): case (sizeof(DirectInputDeviceType<charMode>::DeviceObjectInstanceCompatType)): break; default: LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); } const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(dwObj, dwHow); if (false == maybeElement.has_value()) LOG_INVOCATION_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity); const Controller::SElementIdentifier element = maybeElement.value(); if (Controller::EElementType::WholeController == element.type) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); FillObjectInstanceInfo<charMode>(controller->GetCapabilities(), element, ((true == IsApplicationDataFormatSet()) ? dataFormat->GetOffsetForElement(element).value_or(DataFormat::kInvalidOffsetValue) : NativeOffsetForElement(element)), pdidoi); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetProperty(REFGUID rguidProp, LPDIPROPHEADER pdiph) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; DumpPropertyRequest(rguidProp, pdiph, false); if (false == IsPropertyHeaderValid(rguidProp, pdiph)) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(pdiph->dwObj, pdiph->dwHow); if (false == maybeElement.has_value()) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity, rguidProp); const Controller::SElementIdentifier element = maybeElement.value(); switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): if (Controller::EElementType::WholeController != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = DIPROPAXISMODE_ABS; LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_BUFFERSIZE): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetEventBufferCapacity(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_DEADZONE): if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = controller->GetAxisDeadzone(element.axis); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_FFGAIN): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetForceFeedbackGain(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_GRANULARITY): switch (element.type) { case Controller::EElementType::Axis: case Controller::EElementType::WholeController: break; default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); } ((LPDIPROPDWORD)pdiph)->dwData = 1; LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_JOYSTICKID): ((LPDIPROPDWORD)pdiph)->dwData = controller->GetIdentifier(); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_LOGICALRANGE): case ((size_t)&DIPROP_PHYSICALRANGE): switch (element.type) { case Controller::EElementType::Axis: case Controller::EElementType::WholeController: break; default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); } ((LPDIPROPRANGE)pdiph)->lMin = Controller::kAnalogValueMin; ((LPDIPROPRANGE)pdiph)->lMax = Controller::kAnalogValueMax; LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_RANGE): do { if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::pair kRange = controller->GetAxisRange(element.axis); ((LPDIPROPRANGE)pdiph)->lMin = kRange.first; ((LPDIPROPRANGE)pdiph)->lMax = kRange.second; } while (false); LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_SATURATION): if (Controller::EElementType::Axis != element.type) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); ((LPDIPROPDWORD)pdiph)->dwData = controller->GetAxisSaturation(element.axis); LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_OK, kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp); } } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Initialize(HINSTANCE hinst, DWORD dwVersion, REFGUID rguid) { // Not required for Xidi virtual controllers as they are implemented now. // However, this method is needed for creating IDirectInputDevice objects via COM. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Poll(void) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::SuperDebug; // DirectInput documentation requires that the application data format already be set before a device can be polled. if (false == IsApplicationDataFormatSet()) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); if (true == controller->RefreshState()) SignalEventIfEnabled(stateChangeEventHandle); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::RunControlPanel(HWND hwndOwner, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SendDeviceData(DWORD cbObjectData, LPCDIDEVICEOBJECTDATA rgdod, LPDWORD pdwInOut, DWORD fl) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SendForceFeedbackCommand(DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetCooperativeLevel(HWND hwnd, DWORD dwFlags) { // Presently this is a no-op. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetDataFormat(LPCDIDATAFORMAT lpdf) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; if (nullptr == lpdf) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); // If this operation fails, then the current data format and event filter remain unaltered. std::unique_ptr<DataFormat> newDataFormat = DataFormat::CreateFromApplicationFormatSpec(*lpdf, controller->GetCapabilities()); if (nullptr == newDataFormat) LOG_INVOCATION_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity); // Use the event filter to prevent the controller from buffering any events that correspond to elements with no offsets. auto lock = controller->Lock(); controller->EventFilterAddAllElements(); for (int i = 0; i < (int)Controller::EAxis::Count; ++i) { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Axis, .axis = (Controller::EAxis)i}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } for (int i = 0; i < (int)Controller::EButton::Count; ++i) { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Button, .button = (Controller::EButton)i}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } do { const Controller::SElementIdentifier kElement = {.type = Controller::EElementType::Pov}; if (false == newDataFormat->HasElement(kElement)) controller->EventFilterRemoveElement(kElement); } while (false); dataFormat = std::move(newDataFormat); LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetEventNotification(HANDLE hEvent) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; stateChangeEventHandle = hEvent; LOG_INVOCATION_AND_RETURN(DI_POLLEDDEVICE, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetProperty(REFGUID rguidProp, LPCDIPROPHEADER pdiph) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; DumpPropertyRequest(rguidProp, pdiph, true); if (false == IsPropertyHeaderValid(rguidProp, pdiph)) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp); const std::optional<Controller::SElementIdentifier> maybeElement = IdentifyElement(pdiph->dwObj, pdiph->dwHow); if (false == maybeElement.has_value()) LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_OBJECTNOTFOUND, kMethodSeverity, rguidProp); const Controller::SElementIdentifier element = maybeElement.value(); switch ((size_t)&rguidProp) { case ((size_t)&DIPROP_AXISMODE): if (DIPROPAXISMODE_ABS == ((LPDIPROPDWORD)pdiph)->dwData) LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DI_PROPNOEFFECT, kMethodSeverity, rguidProp, pdiph); else LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_BUFFERSIZE): LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetEventBufferCapacity(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_DEADZONE): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAxisDeadzone(element.axis, ((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAllAxisDeadzone(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } case ((size_t)&DIPROP_FFGAIN): LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetForceFeedbackGain(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case ((size_t)&DIPROP_RANGE): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(((true == controller->SetAxisRange(element.axis, ((LPDIPROPRANGE)pdiph)->lMin, ((LPDIPROPRANGE)pdiph)->lMax)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(((true == controller->SetAllAxisRange(((LPDIPROPRANGE)pdiph)->lMin, ((LPDIPROPRANGE)pdiph)->lMax)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPRANGE_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } case ((size_t)&DIPROP_SATURATION): switch (element.type) { case Controller::EElementType::Axis: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAxisSaturation(element.axis, ((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); case Controller::EElementType::WholeController: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(((true == controller->SetAllAxisSaturation(((LPDIPROPDWORD)pdiph)->dwData)) ? DI_OK : DIERR_INVALIDPARAM), kMethodSeverity, rguidProp, pdiph); default: LOG_PROPERTY_INVOCATION_DIPROPDWORD_AND_RETURN(DIERR_INVALIDPARAM, kMethodSeverity, rguidProp, pdiph); } default: LOG_PROPERTY_INVOCATION_NO_VALUE_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity, rguidProp); } } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::Unacquire(void) { // Controller acquisition is a no-op for Xidi virtual controllers. static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DI_OK, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::WriteEffectToFile(DirectInputDeviceType<charMode>::ConstStringType lptszFileName, DWORD dwEntries, LPDIFILEEFFECT rgDiFileEft, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } #if DIRECTINPUT_VERSION >= 0x0800 // -------- METHODS: IDirectInputDevice8 ONLY ------------------------------ // // See DirectInput documentation for more information. template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::BuildActionMap(DirectInputDeviceType<charMode>::ActionFormatType* lpdiaf, DirectInputDeviceType<charMode>::ConstStringType lpszUserName, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::GetImageInfo(DirectInputDeviceType<charMode>::DeviceImageInfoHeaderType* lpdiDevImageInfoHeader) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } // --------- template <ECharMode charMode> HRESULT VirtualDirectInputDevice<charMode>::SetActionMap(DirectInputDeviceType<charMode>::ActionFormatType* lpdiActionFormat, DirectInputDeviceType<charMode>::ConstStringType lptszUserName, DWORD dwFlags) { static constexpr Message::ESeverity kMethodSeverity = Message::ESeverity::Info; LOG_INVOCATION_AND_RETURN(DIERR_UNSUPPORTED, kMethodSeverity); } #endif // -------- EXPLICIT TEMPLATE INSTANTIATION ---------------------------- // // Instantiates both the ASCII and Unicode versions of this class. template class VirtualDirectInputDevice<ECharMode::A>; template class VirtualDirectInputDevice<ECharMode::W>; }
59,762
18,266
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from https://www.nuget.org/packages/Aspose.Email/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/email */ #include <system/string.h> #include <system/shared_ptr.h> #include <system/object.h> #include <system/date_time.h> #include <Mapi/TaskSaveFormat.h> #include <Mapi/MapiTaskState.h> #include <Mapi/MapiTask.h> #include <Mapi/MapiCalendarRecurrencePatternType.h> #include <Mapi/MapiCalendarRecurrencePattern.h> #include <Mapi/MapiCalendarRecurrenceEndType.h> #include <Mapi/MapiCalendarDailyRecurrencePattern.h> #include <cstdint> #include <Calendar/Recurrences/DateCollection.h> #include <Calendar/Recurrences/CalendarRecurrence.h> #include "Examples.h" using namespace Aspose::Email; using namespace Aspose::Email::Mapi; using namespace Aspose::Email::Calendar::Recurrences; static uint32_t GetOccurrenceCount(System::DateTime start, System::DateTime endBy, System::String rrule) { System::SharedPtr<CalendarRecurrence> pattern = System::MakeObject<CalendarRecurrence>(System::String::Format(u"DTSTART:{0}\r\nRRULE:{1}", start.ToString(u"yyyyMMdd"), rrule)); System::SharedPtr<DateCollection> dates = pattern->GenerateOccurrences(start, endBy); return (uint32_t)dates->get_Count(); } void SetRecurrenceEveryDay() { System::String dataDir = GetDataDir_Outlook(); System::DateTime StartDate(2015, 7, 16); System::DateTime endByDate(2015, 8, 1); System::DateTime DueDate(2015, 7, 16); System::SharedPtr<MapiTask> task = System::MakeObject<MapiTask>(u"This is test task", u"Sample Body", StartDate, DueDate); task->set_State(Aspose::Email::Mapi::MapiTaskState::NotAssigned); // ExStart:SetRecurrenceEveryDay // Set the Daily recurrence auto record = [&]{ auto tmp_0 = System::MakeObject<MapiCalendarDailyRecurrencePattern>(); tmp_0->set_PatternType(Aspose::Email::Mapi::MapiCalendarRecurrencePatternType::Day); tmp_0->set_Period(1); tmp_0->set_EndType(Aspose::Email::Mapi::MapiCalendarRecurrenceEndType::EndAfterDate); tmp_0->set_OccurrenceCount(GetOccurrenceCount(StartDate, endByDate, u"FREQ=DAILY;INTERVAL=1")); tmp_0->set_EndDate(endByDate); return tmp_0; }(); // ExEnd:SetRecurrenceEveryDay task->set_Recurrence(record); task->Save(dataDir + u"SetRecurrenceEveryDay_out.msg", Aspose::Email::Mapi::TaskSaveFormat::Msg); // ExStart:SetRecurrenceEveryDayInterval // Set the Daily recurrence auto record1 = [&]{ auto tmp_1 = System::MakeObject<MapiCalendarDailyRecurrencePattern>(); tmp_1->set_PatternType(Aspose::Email::Mapi::MapiCalendarRecurrencePatternType::Day); tmp_1->set_Period(2); tmp_1->set_EndType(Aspose::Email::Mapi::MapiCalendarRecurrenceEndType::EndAfterDate); tmp_1->set_OccurrenceCount(GetOccurrenceCount(StartDate, endByDate, u"FREQ=DAILY;INTERVAL=2")); tmp_1->set_EndDate(endByDate); return tmp_1; }(); // ExEnd:SetRecurrenceEveryDayInterval task->set_Recurrence(record); task->Save(dataDir + u"SetRecurrenceEveryDayInterval_out.msg", Aspose::Email::Mapi::TaskSaveFormat::Msg); }
3,467
1,149
#ifndef ENTT_ENTITY_SNAPSHOT_HPP #define ENTT_ENTITY_SNAPSHOT_HPP #include "../../TinySTL/array.h" #include <cstddef> #include <utility> #include <cassert> #include <iterator> #include <type_traits> #include "../../TinySTL/unordered_map.h" #include "../config/config.h" #include "entt_traits.hpp" #include "utility.hpp" namespace entt { /** * @brief Forward declaration of the registry class. */ template<typename> class Registry; /** * @brief Utility class to create snapshots from a registry. * * A _snapshot_ can be either a dump of the entire registry or a narrower * selection of components and tags of interest.<br/> * This type can be used in both cases if provided with a correctly configured * output archive. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class Snapshot final { /*! @brief A registry is allowed to create snapshots. */ friend class Registry<Entity>; using follow_fn_type = Entity(const Registry<Entity> &, const Entity); Snapshot(const Registry<Entity> &registry, Entity seed, follow_fn_type *follow) ENTT_NOEXCEPT : registry{registry}, seed{seed}, follow{follow} {} template<typename Component, typename Archive, typename It> void get(Archive &archive, size_t sz, It first, It last) const { archive(static_cast<Entity>(sz)); while(first != last) { const auto entity = *(first++); if(registry.template has<Component>(entity)) { archive(entity, registry.template get<Component>(entity)); } } } template<typename... Component, typename Archive, typename It, size_t... Indexes> void component(Archive &archive, It first, It last, std::index_sequence<Indexes...>) const { tinystl::array<size_t, sizeof...(Indexes)> size{}; auto begin = first; while(begin != last) { const auto entity = *(begin++); using accumulator_type = size_t[]; accumulator_type accumulator = { (registry.template has<Component>(entity) ? ++size[Indexes] : size[Indexes])... }; (void)accumulator; } using accumulator_type = int[]; accumulator_type accumulator = { (get<Component>(archive, size[Indexes], first, last), 0)... }; (void)accumulator; } public: /*! @brief Copying a snapshot isn't allowed. */ Snapshot(const Snapshot &) = delete; /*! @brief Default move constructor. */ Snapshot(Snapshot &&) = default; /*! @brief Copying a snapshot isn't allowed. @return This snapshot. */ Snapshot & operator=(const Snapshot &) = delete; /*! @brief Default move assignment operator. @return This snapshot. */ Snapshot & operator=(Snapshot &&) = default; /** * @brief Puts aside all the entities that are still in use. * * Entities are serialized along with their versions. Destroyed entities are * not taken in consideration by this function. * * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Archive> const Snapshot & entities(Archive &archive) const { archive(static_cast<Entity>(registry.alive())); registry.each([&archive](const auto entity) { archive(entity); }); return *this; } /** * @brief Puts aside destroyed entities. * * Entities are serialized along with their versions. Entities that are * still in use are not taken in consideration by this function. * * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Archive> const Snapshot & destroyed(Archive &archive) const { auto size = registry.size() - registry.alive(); archive(static_cast<Entity>(size)); if(size) { auto curr = seed; archive(curr); for(--size; size; --size) { curr = follow(registry, curr); archive(curr); } } return *this; } /** * @brief Puts aside the given component. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Type of component to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Component, typename Archive> const Snapshot & component(Archive &archive) const { const auto sz = registry.template size<Component>(); const auto *entities = registry.template data<Component>(); archive(static_cast<Entity>(sz)); for(std::remove_const_t<decltype(sz)> i{}; i < sz; ++i) { const auto entity = entities[i]; archive(entity, registry.template get<Component>(entity)); }; return *this; } /** * @brief Puts aside the given components. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Types of components to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename... Component, typename Archive> std::enable_if_t<(sizeof...(Component) > 1), const Snapshot &> component(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (component<Component>(archive), 0)... }; (void)accumulator; return *this; } /** * @brief Puts aside the given components for the entities in a range. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Component Types of components to serialize. * @tparam Archive Type of output archive. * @tparam It Type of input iterator. * @param archive A valid reference to an output archive. * @param first An iterator to the first element of the range to serialize. * @param last An iterator past the last element of the range to serialize. * @return An object of this type to continue creating the snapshot. */ template<typename... Component, typename Archive, typename It> const Snapshot & component(Archive &archive, It first, It last) const { component<Component...>(archive, first, last, std::make_index_sequence<sizeof...(Component)>{}); return *this; } /** * @brief Puts aside the given tag. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Tag Type of tag to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename Tag, typename Archive> const Snapshot & tag(Archive &archive) const { const bool has = registry.template has<Tag>(); // numerical length is forced for tags to facilitate loading archive(has ? Entity(1): Entity{}); if(has) { archive(registry.template attachee<Tag>(), registry.template get<Tag>()); } return *this; } /** * @brief Puts aside the given tags. * * Each instance is serialized together with the entity to which it belongs. * Entities are serialized along with their versions. * * @tparam Tag Types of tags to serialize. * @tparam Archive Type of output archive. * @param archive A valid reference to an output archive. * @return An object of this type to continue creating the snapshot. */ template<typename... Tag, typename Archive> std::enable_if_t<(sizeof...(Tag) > 1), const Snapshot &> tag(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (tag<Tag>(archive), 0)... }; (void)accumulator; return *this; } private: const Registry<Entity> &registry; const Entity seed; follow_fn_type *follow; }; /** * @brief Utility class to restore a snapshot as a whole. * * A snapshot loader requires that the destination registry be empty and loads * all the data at once while keeping intact the identifiers that the entities * originally had.<br/> * An example of use is the implementation of a save/restore utility. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class SnapshotLoader final { /*! @brief A registry is allowed to create snapshot loaders. */ friend class Registry<Entity>; using assure_fn_type = void(Registry<Entity> &, const Entity, const bool); SnapshotLoader(Registry<Entity> &registry, assure_fn_type *assure_fn) ENTT_NOEXCEPT : registry{registry}, assure_fn{assure_fn} { // restore a snapshot as a whole requires a clean registry assert(!registry.capacity()); } template<typename Archive> void assure(Archive &archive, bool destroyed) const { Entity length{}; archive(length); while(length--) { Entity entity{}; archive(entity); assure_fn(registry, entity, destroyed); } } template<typename Type, typename Archive, typename... Args> void assign(Archive &archive, Args... args) const { Entity length{}; archive(length); while(length--) { Entity entity{}; Type instance{}; archive(entity, instance); static constexpr auto destroyed = false; assure_fn(registry, entity, destroyed); registry.template assign<Type>(args..., entity, static_cast<const Type &>(instance)); } } public: /*! @brief Copying a snapshot loader isn't allowed. */ SnapshotLoader(const SnapshotLoader &) = delete; /*! @brief Default move constructor. */ SnapshotLoader(SnapshotLoader &&) = default; /*! @brief Copying a snapshot loader isn't allowed. @return This loader. */ SnapshotLoader & operator=(const SnapshotLoader &) = delete; /*! @brief Default move assignment operator. @return This loader. */ SnapshotLoader & operator=(SnapshotLoader &&) = default; /** * @brief Restores entities that were in use during serialization. * * This function restores the entities that were in use during serialization * and gives them the versions they originally had. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename Archive> const SnapshotLoader & entities(Archive &archive) const { static constexpr auto destroyed = false; assure(archive, destroyed); return *this; } /** * @brief Restores entities that were destroyed during serialization. * * This function restores the entities that were destroyed during * serialization and gives them the versions they originally had. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename Archive> const SnapshotLoader & destroyed(Archive &archive) const { static constexpr auto destroyed = true; assure(archive, destroyed); return *this; } /** * @brief Restores components and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the component is * assigned doesn't exist yet, the loader will take care to create it with * the version it originally had. * * @tparam Component Types of components to restore. * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename... Component, typename Archive> const SnapshotLoader & component(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (assign<Component>(archive), 0)... }; (void)accumulator; return *this; } /** * @brief Restores tags and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the tag is assigned * doesn't exist yet, the loader will take care to create it with the * version it originally had. * * @tparam Tag Types of tags to restore. * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A valid loader to continue restoring data. */ template<typename... Tag, typename Archive> const SnapshotLoader & tag(Archive &archive) const { using accumulator_type = int[]; accumulator_type accumulator = { 0, (assign<Tag>(archive, tag_t{}), 0)... }; (void)accumulator; return *this; } /** * @brief Destroys those entities that have neither components nor tags. * * In case all the entities were serialized but only part of the components * and tags was saved, it could happen that some of the entities have * neither components nor tags once restored.<br/> * This functions helps to identify and destroy those entities. * * @return A valid loader to continue restoring data. */ const SnapshotLoader & orphans() const { registry.orphans([this](const auto entity) { registry.destroy(entity); }); return *this; } private: Registry<Entity> &registry; assure_fn_type *assure_fn; }; /** * @brief Utility class for _continuous loading_. * * A _continuous loader_ is designed to load data from a source registry to a * (possibly) non-empty destination. The loader can accomodate in a registry * more than one snapshot in a sort of _continuous loading_ that updates the * destination one step at a time.<br/> * Identifiers that entities originally had are not transferred to the target. * Instead, the loader maps remote identifiers to local ones while restoring a * snapshot.<br/> * An example of use is the implementation of a client-server applications with * the requirement of transferring somehow parts of the representation side to * side. * * @tparam Entity A valid entity type (see entt_traits for more details). */ template<typename Entity> class ContinuousLoader final { using traits_type = entt_traits<Entity>; void destroy(Entity entity) { const auto it = remloc.find(entity); if(it == remloc.cend()) { const auto local = registry.create(); remloc.emplace(entity, tinystl::make_pair(local, true)); registry.destroy(local); } } void restore(Entity entity) { const auto it = remloc.find(entity); if(it == remloc.cend()) { const auto local = registry.create(); remloc.emplace(entity, tinystl::make_pair(local, true)); } else { remloc[entity].first = registry.valid(remloc[entity].first) ? remloc[entity].first : registry.create(); // set the dirty flag remloc[entity].second = true; } } template<typename Type, typename Member> std::enable_if_t<std::is_same<Member, Entity>::value> update(Type &instance, Member Type:: *member) { instance.*member = map(instance.*member); } template<typename Type, typename Member> std::enable_if_t<std::is_same<typename std::iterator_traits<typename Member::iterator>::value_type, Entity>::value> update(Type &instance, Member Type:: *member) { for(auto &entity: instance.*member) { entity = map(entity); } } template<typename Other, typename Type, typename Member> std::enable_if_t<!std::is_same<Other, Type>::value> update(Other &, Member Type:: *) {} template<typename Archive> void assure(Archive &archive, void(ContinuousLoader:: *member)(Entity)) { Entity length{}; archive(length); while(length--) { Entity entity{}; archive(entity); (this->*member)(entity); } } template<typename Component> void reset() { for(auto &&ref: remloc) { const auto local = ref.second.first; if(registry.valid(local)) { registry.template reset<Component>(local); } } } template<typename Other, typename Archive, typename Func, typename... Type, typename... Member> void assign(Archive &archive, Func func, Member Type:: *... member) { Entity length{}; archive(length); while(length--) { Entity entity{}; Other instance{}; archive(entity, instance); restore(entity); using accumulator_type = int[]; accumulator_type accumulator = { 0, (update(instance, member), 0)... }; (void)accumulator; func(map(entity), instance); } } public: /*! @brief Underlying entity identifier. */ using entity_type = Entity; /** * @brief Constructs a loader that is bound to a given registry. * @param registry A valid reference to a registry. */ ContinuousLoader(Registry<entity_type> &registry) ENTT_NOEXCEPT : registry{registry} {} /*! @brief Copying a snapshot loader isn't allowed. */ ContinuousLoader(const ContinuousLoader &) = delete; /*! @brief Default move constructor. */ ContinuousLoader(ContinuousLoader &&) = default; /*! @brief Copying a snapshot loader isn't allowed. @return This loader. */ ContinuousLoader & operator=(const ContinuousLoader &) = delete; /*! @brief Default move assignment operator. @return This loader. */ ContinuousLoader & operator=(ContinuousLoader &&) = default; /** * @brief Restores entities that were in use during serialization. * * This function restores the entities that were in use during serialization * and creates local counterparts for them if required. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A non-const reference to this loader. */ template<typename Archive> ContinuousLoader & entities(Archive &archive) { assure(archive, &ContinuousLoader::restore); return *this; } /** * @brief Restores entities that were destroyed during serialization. * * This function restores the entities that were destroyed during * serialization and creates local counterparts for them if required. * * @tparam Archive Type of input archive. * @param archive A valid reference to an input archive. * @return A non-const reference to this loader. */ template<typename Archive> ContinuousLoader & destroyed(Archive &archive) { assure(archive, &ContinuousLoader::destroy); return *this; } /** * @brief Restores components and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the component is * assigned doesn't exist yet, the loader will take care to create a local * counterpart for it.<br/> * Members can be either data members of type entity_type or containers of * entities. In both cases, the loader will visit them and update the * entities by replacing each one with its local counterpart. * * @tparam Component Type of component to restore. * @tparam Archive Type of input archive. * @tparam Type Types of components to update with local counterparts. * @tparam Member Types of members to update with their local counterparts. * @param archive A valid reference to an input archive. * @param member Members to update with their local counterparts. * @return A non-const reference to this loader. */ template<typename... Component, typename Archive, typename... Type, typename... Member> ContinuousLoader & component(Archive &archive, Member Type:: *... member) { auto apply = [this](const auto entity, const auto &component) { registry.template accommodate<std::decay_t<decltype(component)>>(entity, component); }; using accumulator_type = int[]; accumulator_type accumulator = { 0, (reset<Component>(), assign<Component>(archive, apply, member...), 0)... }; (void)accumulator; return *this; } /** * @brief Restores tags and assigns them to the right entities. * * The template parameter list must be exactly the same used during * serialization. In the event that the entity to which the tag is assigned * doesn't exist yet, the loader will take care to create a local * counterpart for it.<br/> * Members can be either data members of type entity_type or containers of * entities. In both cases, the loader will visit them and update the * entities by replacing each one with its local counterpart. * * @tparam Tag Type of tag to restore. * @tparam Archive Type of input archive. * @tparam Type Types of components to update with local counterparts. * @tparam Member Types of members to update with their local counterparts. * @param archive A valid reference to an input archive. * @param member Members to update with their local counterparts. * @return A non-const reference to this loader. */ template<typename... Tag, typename Archive, typename... Type, typename... Member> ContinuousLoader & tag(Archive &archive, Member Type:: *... member) { auto apply = [this](const auto entity, const auto &tag) { registry.template assign<std::decay_t<decltype(tag)>>(tag_t{}, entity, tag); }; using accumulator_type = int[]; accumulator_type accumulator = { 0, (registry.template remove<Tag>(), assign<Tag>(archive, apply, member...), 0)... }; (void)accumulator; return *this; } /** * @brief Helps to purge entities that no longer have a conterpart. * * Users should invoke this member function after restoring each snapshot, * unless they know exactly what they are doing. * * @return A non-const reference to this loader. */ ContinuousLoader & shrink() { auto it = remloc.begin(); while(it != remloc.cend()) { const auto local = it->second.first; bool &dirty = it->second.second; if(dirty) { dirty = false; ++it; } else { if(registry.valid(local)) { registry.destroy(local); } it = remloc.erase(it); } } return *this; } /** * @brief Destroys those entities that have neither components nor tags. * * In case all the entities were serialized but only part of the components * and tags was saved, it could happen that some of the entities have * neither components nor tags once restored.<br/> * This functions helps to identify and destroy those entities. * * @return A non-const reference to this loader. */ ContinuousLoader & orphans() { registry.orphans([this](const auto entity) { registry.destroy(entity); }); return *this; } /** * @brief Tests if a loader knows about a given entity. * @param entity An entity identifier. * @return True if `entity` is managed by the loader, false otherwise. */ bool has(entity_type entity) const ENTT_NOEXCEPT { return (remloc.find(entity) != remloc.cend()); } /** * @brief Returns the identifier to which an entity refers. * * @warning * Attempting to use an entity that isn't managed by the loader results in * undefined behavior.<br/> * An assertion will abort the execution at runtime in debug mode if the * loader doesn't knows about the entity. * * @param entity An entity identifier. * @return The identifier to which `entity` refers in the target registry. */ entity_type map(entity_type entity) const ENTT_NOEXCEPT { assert(has(entity)); return remloc.find(entity)->second.first; } private: tinystl::unordered_map<Entity, tinystl::pair<Entity, bool>> remloc; Registry<Entity> &registry; }; } #endif // ENTT_ENTITY_SNAPSHOT_HPP
25,705
6,904
/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2016 Soumyajit De * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/lib/common.h> #include <shogun/kernel/ShiftInvariantKernel.h> #include <shogun/distance/CustomDistance.h> using namespace shogun; CShiftInvariantKernel::CShiftInvariantKernel() : CKernel(0) { register_params(); } CShiftInvariantKernel::CShiftInvariantKernel(CFeatures *l, CFeatures *r) : CKernel(l, r, 0) { register_params(); init(l, r); } CShiftInvariantKernel::~CShiftInvariantKernel() { cleanup(); SG_UNREF(m_distance); } bool CShiftInvariantKernel::init(CFeatures* l, CFeatures* r) { REQUIRE(m_distance, "The distance instance cannot be NULL!\n"); CKernel::init(l,r); m_distance->init(l, r); return init_normalizer(); } void CShiftInvariantKernel::precompute_distance() { REQUIRE(m_distance, "The distance instance cannot be NULL!\n"); REQUIRE(m_distance->init(lhs, rhs), "Could not initialize the distance instance!\n"); SGMatrix<float32_t> dist_mat=m_distance->get_distance_matrix<float32_t>(); if (m_precomputed_distance==NULL) { m_precomputed_distance=new CCustomDistance(); SG_REF(m_precomputed_distance); } if (lhs==rhs) m_precomputed_distance->set_triangle_distance_matrix_from_full(dist_mat.data(), dist_mat.num_rows, dist_mat.num_cols); else m_precomputed_distance->set_full_distance_matrix_from_full(dist_mat.data(), dist_mat.num_rows, dist_mat.num_cols); } void CShiftInvariantKernel::cleanup() { SG_UNREF(m_precomputed_distance); m_precomputed_distance=NULL; CKernel::cleanup(); m_distance->cleanup(); } EDistanceType CShiftInvariantKernel::get_distance_type() const { REQUIRE(m_distance, "The distance instance cannot be NULL!\n"); return m_distance->get_distance_type(); } float64_t CShiftInvariantKernel::distance(int32_t a, int32_t b) const { REQUIRE(m_distance, "The distance instance cannot be NULL!\n"); if (m_precomputed_distance!=NULL) return m_precomputed_distance->distance(a, b); else return m_distance->distance(a, b); } void CShiftInvariantKernel::register_params() { SG_ADD((CSGObject**) &m_distance, "m_distance", "Distance to be used."); SG_ADD((CSGObject**) &m_precomputed_distance, "m_precomputed_distance", "Precomputed istance to be used."); m_distance=NULL; m_precomputed_distance=NULL; } void CShiftInvariantKernel::set_precomputed_distance(CCustomDistance* precomputed_distance) { REQUIRE(precomputed_distance, "The precomputed distance instance cannot be NULL!\n"); SG_REF(precomputed_distance); SG_UNREF(m_precomputed_distance); m_precomputed_distance=precomputed_distance; } CCustomDistance* CShiftInvariantKernel::get_precomputed_distance() const { REQUIRE(m_precomputed_distance, "The precomputed distance instance cannot be NULL!\n"); SG_REF(m_precomputed_distance); return m_precomputed_distance; }
4,379
1,579
// Uncomment this to look for MPI-related memory leaks. //#define COMPOSE_DEBUG_MPI //>> cedr_kokkos.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_KOKKOS_HPP #define INCLUDE_CEDR_KOKKOS_HPP #include <Kokkos_Core.hpp> #define KIF KOKKOS_INLINE_FUNCTION // Clarify that a class member type is meant to be private but is // marked public for Cuda visibility. #define PRIVATE_CUDA public #define PROTECTED_CUDA public #if defined KOKKOS_COMPILER_GNU // See https://github.com/kokkos/kokkos-kernels/issues/129 # define ConstExceptGnu #else # define ConstExceptGnu const #endif namespace cedr { namespace impl { // Turn a View's MemoryTraits (traits::memory_traits) into the equivalent // unsigned int mask. template <typename View> struct MemoryTraitsMask { enum : unsigned int { #ifndef KOKKOS_VERSION // pre-v3 value = ((View::traits::memory_traits::RandomAccess ? Kokkos::RandomAccess : 0) | (View::traits::memory_traits::Atomic ? Kokkos::Atomic : 0) | (View::traits::memory_traits::Restrict ? Kokkos::Restrict : 0) | (View::traits::memory_traits::Aligned ? Kokkos::Aligned : 0) | (View::traits::memory_traits::Unmanaged ? Kokkos::Unmanaged : 0)) #else // >= v3 value = ((View::traits::memory_traits::is_random_access ? Kokkos::RandomAccess : 0) | (View::traits::memory_traits::is_atomic ? Kokkos::Atomic : 0) | (View::traits::memory_traits::is_restrict ? Kokkos::Restrict : 0) | (View::traits::memory_traits::is_aligned ? Kokkos::Aligned : 0) | (View::traits::memory_traits::is_unmanaged ? Kokkos::Unmanaged : 0)) #endif }; }; // Make the input View Unmanaged, whether or not it already is. One might // imagine that View::unmanaged_type would provide this. // Use: Unmanaged<ViewType> template <typename View> using Unmanaged = // Provide a full View type specification, augmented with Unmanaged. Kokkos::View<typename View::traits::scalar_array_type, typename View::traits::array_layout, typename View::traits::device_type, Kokkos::MemoryTraits< // All the current values... MemoryTraitsMask<View>::value | // ... |ed with the one we want, whether or not it's // already there. Kokkos::Unmanaged> >; template <typename View> using Const = typename View::const_type; template <typename View> using ConstUnmanaged = Const<Unmanaged<View> >; template <typename ExeSpace> struct DeviceType { typedef Kokkos::Device<typename ExeSpace::execution_space, typename ExeSpace::memory_space> type; }; #ifdef KOKKOS_HAVE_CUDA typedef Kokkos::Device<Kokkos::CudaSpace::execution_space, Kokkos::CudaSpace::memory_space> DefaultDeviceType; template <> struct DeviceType<Kokkos::Cuda> { typedef DefaultDeviceType type; }; #else typedef Kokkos::Device<Kokkos::DefaultExecutionSpace::execution_space, Kokkos::DefaultExecutionSpace::memory_space> DefaultDeviceType; #endif template <typename ES> struct OnGpu { enum : bool { value = #ifdef COMPOSE_MIMIC_GPU true #else false #endif }; }; #ifdef KOKKOS_ENABLE_CUDA template <> struct OnGpu<Kokkos::Cuda> { enum : bool { value = true }; }; #endif template <typename ExeSpace = Kokkos::DefaultExecutionSpace> struct ExeSpaceUtils { using TeamPolicy = Kokkos::TeamPolicy<ExeSpace>; using Member = typename TeamPolicy::member_type; static TeamPolicy get_default_team_policy (int outer, int inner) { #ifdef COMPOSE_MIMIC_GPU const int max_threads = #ifdef KOKKOS_ENABLE_OPENMP ExeSpace::concurrency() #else 1 #endif ; const int team_size = max_threads < 7 ? max_threads : 7; return TeamPolicy(outer, team_size, 1); #else return TeamPolicy(outer, 1, 1); #endif } }; #ifdef KOKKOS_ENABLE_CUDA template <> struct ExeSpaceUtils<Kokkos::Cuda> { using TeamPolicy = Kokkos::TeamPolicy<Kokkos::Cuda>; using Member = typename TeamPolicy::member_type; static TeamPolicy get_default_team_policy (int outer, int inner) { return TeamPolicy(outer, std::min(128, 32*((inner + 31)/32)), 1); } }; #endif // GPU-friendly replacements for std::*. template <typename T> KOKKOS_INLINE_FUNCTION const T& min (const T& a, const T& b) { return a < b ? a : b; } template <typename T> KOKKOS_INLINE_FUNCTION const T& max (const T& a, const T& b) { return a > b ? a : b; } template <typename T> KOKKOS_INLINE_FUNCTION void swap (T& a, T& b) { const T tmp = a; a = b; b = tmp; } } // namespace impl } // namespace cedr #endif //>> cedr.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_HPP #define INCLUDE_CEDR_HPP //#include "cedr_kokkos.hpp" // Communication-Efficient Constrained Density Reconstructors namespace cedr { typedef int Int; typedef long int Long; typedef std::size_t Size; typedef double Real; // CDRs in general implement // * tracer mass, Qm, conservation; // * mixing ratio, q, shape preservation: any of local bound preservation, // dynamic range preservation, or simply non-negativity; and // * tracer consistency, which follows from dynamic range preservation or // stronger (including local bound preservation) with rhom coming from the // dynamics. // // One can solve a subset of these. // If !conserve, then the CDR does not alter the tracer mass, but it does not // correct for any failure in mass conservation in the field given to it. // If consistent but !shapepreserve, then the CDR solves the dynamic range // preservation problem rather than the local bound preservation problem. struct ProblemType { enum : Int { conserve = 1, shapepreserve = 1 << 1, consistent = 1 << 2, // The 'nonnegative' problem type can be combined only with 'conserve'. The // caller can implement nonnegativity when running with 'shapepreserve' or // 'consistent' simply by setting Qm_min = 0. The 'nonnegativity' type is // reserved for a particularly efficient type of problem in which // Qm_{min,max} are not specified. nonnegative = 1 << 3 }; }; } #endif //>> cedr_mpi.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_MPI_HPP #define INCLUDE_CEDR_MPI_HPP #include <memory> #include <mpi.h> //#include "compose_config.hpp" //#include "cedr.hpp" namespace cedr { namespace mpi { class Parallel { MPI_Comm comm_; public: typedef std::shared_ptr<Parallel> Ptr; Parallel(MPI_Comm comm) : comm_(comm) {} MPI_Comm comm () const { return comm_; } Int size() const; Int rank() const; Int root () const { return 0; } bool amroot () const { return rank() == root(); } }; struct Request { MPI_Request request; #ifdef COMPOSE_DEBUG_MPI int unfreed; Request(); ~Request(); #endif }; Parallel::Ptr make_parallel(MPI_Comm comm); template <typename T> MPI_Datatype get_type(); template <typename T> int reduce(const Parallel& p, const T* sendbuf, T* rcvbuf, int count, MPI_Op op, int root); template <typename T> int all_reduce(const Parallel& p, const T* sendbuf, T* rcvbuf, int count, MPI_Op op); template <typename T> int isend(const Parallel& p, const T* buf, int count, int dest, int tag, Request* ireq = nullptr); template <typename T> int irecv(const Parallel& p, T* buf, int count, int src, int tag, Request* ireq = nullptr); int waitany(int count, Request* reqs, int* index, MPI_Status* stats = nullptr); int waitall(int count, Request* reqs, MPI_Status* stats = nullptr); template<typename T> int gather(const Parallel& p, const T* sendbuf, int sendcount, T* recvbuf, int recvcount, int root); template <typename T> int gatherv(const Parallel& p, const T* sendbuf, int sendcount, T* recvbuf, const int* recvcounts, const int* displs, int root); bool all_ok(const Parallel& p, bool im_ok); struct Op { typedef std::shared_ptr<Op> Ptr; Op (MPI_User_function* function, bool commute) { MPI_Op_create(function, static_cast<int>(commute), &op_); } ~Op () { MPI_Op_free(&op_); } const MPI_Op& get () const { return op_; } private: MPI_Op op_; }; } // namespace mpi } // namespace cedr //#include "cedr_mpi_inl.hpp" #endif //>> cedr_util.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_UTIL_HPP #define INCLUDE_CEDR_UTIL_HPP #include <sstream> //#include "cedr_kokkos.hpp" //#include "cedr_mpi.hpp" namespace cedr { namespace util { template <typename T> KOKKOS_INLINE_FUNCTION constexpr T square (const T& x) { return x*x; } bool eq(const std::string& a, const char* const b1, const char* const b2 = 0); // Uniform rand in [0, 1). Real urand(); #define pr(m) do { \ int _pid_ = 0; \ MPI_Comm_rank(MPI_COMM_WORLD, &_pid_); \ std::stringstream _ss_; \ _ss_.precision(15); \ _ss_ << "pid " << _pid_ << " " << m << std::endl; \ std::cerr << _ss_.str(); \ } while (0) #define pr0(m) do { \ int _pid_; MPI_Comm_rank(MPI_COMM_WORLD, &_pid_); \ if (_pid_ != 0) break; \ std::stringstream _ss_; \ _ss_ << "pid " << _pid_ << " " << m << std::endl; \ std::cerr << _ss_.str(); \ } while (0) #define prc(m) pr(#m << " | " << (m)) #define pr0c(m) pr0(#m << " | " << (m)) #define puf(m) "(" << #m << " " << (m) << ")" #define pu(m) << " " << puf(m) template <typename T> void prarr (const std::string& name, const T* const v, const size_t n) { std::stringstream ss; ss.precision(15); ss << name << " = ["; for (size_t i = 0; i < n; ++i) ss << " " << v[i]; ss << "];"; pr(ss.str()); } #define mprarr(m) cedr::util::prarr(#m, m.data(), m.size()) #ifndef NDEBUG # define cedr_assert(condition) do { \ if ( ! (condition)) { \ std::stringstream _ss_; \ _ss_ << __FILE__ << ":" << __LINE__ << ": FAIL:\n" << #condition \ << "\n"; \ throw std::logic_error(_ss_.str()); \ } \ } while (0) # define cedr_kernel_assert(condition) do { \ if ( ! (condition)) \ Kokkos::abort(#condition); \ } while (0) #else # define cedr_assert(condition) # define cedr_kernel_assert(condition) #endif #define cedr_throw_if(condition, message) do { \ if (condition) { \ std::stringstream _ss_; \ _ss_ << __FILE__ << ":" << __LINE__ << ": The condition:\n" \ << #condition "\nled to the exception\n" << message << "\n"; \ throw std::logic_error(_ss_.str()); \ } \ } while (0) #define cedr_kernel_throw_if(condition, message) do { \ if (condition) \ Kokkos::abort(#condition " led to the exception\n" message); \ } while (0) inline Real reldif (const Real a, const Real b) { return std::abs(b - a)/std::max(std::abs(a), std::abs(b)); } Real reldif(const Real* a, const Real* b, const Int n); struct FILECloser { void operator() (FILE* fh) { fclose(fh); } }; template <typename T, typename ExeSpace> struct RawArrayRaft { typedef typename cedr::impl::DeviceType<ExeSpace>::type Device; typedef Kokkos::View<T*, Device> List; RawArrayRaft (T* a, const Int n) : a_(a), n_(n) { a_d_ = List("RawArrayRaft::a_d_", n_); a_h_ = typename List::HostMirror(a_, n_); } const List& sync_device () { Kokkos::deep_copy(a_d_, a_h_); return a_d_; } T* sync_host () { Kokkos::deep_copy(a_h_, a_d_); return a_; } T* device_ptr () { return a_d_.data(); } private: T* a_; Int n_; List a_d_; typename List::HostMirror a_h_; }; } } #endif //>> cedr_cdr.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_CDR_HPP #define INCLUDE_CEDR_CDR_HPP //#include "cedr_mpi.hpp" namespace cedr { // Constrained Density Reconstructor interface. // Find a point Qm in the set // { Qm: ( i) e'Qm = Qm_global // (ii) Qm_min <= Qm <= Qm_max }, // where e is the vector of 1s. Each algorithm in CEDR has its own optimality // principle to decide on the point. struct CDR { typedef std::shared_ptr<CDR> Ptr; struct Options { // In exact arithmetic, mass is conserved exactly and bounds of a feasible // problem are not violated. In inexact arithmetic, these properties are // inexact, and approximation quality of one can be preferred to that of the // other. Use this option to prefer numerical mass conservation over // numerical bounds nonviolation. In practice, this option governs errrs at // the level of 10 to 1000 times numeric_limits<Real>::epsilon(). bool prefer_numerical_mass_conservation_to_numerical_bounds; Options () : prefer_numerical_mass_conservation_to_numerical_bounds(false) {} }; CDR (const Options options = Options()) : options_(options) {} virtual void print(std::ostream& os) const {} const Options& get_options () const { return options_; } // Set up QLT tracer metadata. Call declare_tracer in order of the tracer // index in the caller's numbering. Once end_tracer_declarations is called, it // is an error to call declare_tracer again. // Associate the tracer with a rhom index. In many problems, there will be // only one rhom, so rhomidx is always 0. // It is an error to call this function from a parallel region. virtual void declare_tracer(int problem_type, const Int& rhomidx) = 0; // It is an error to call this function from a parallel region. virtual void end_tracer_declarations() = 0; // Optionally query the sizes of the two primary memory buffers. This // operation is valid after end_tracer_declarations was called. virtual void get_buffers_sizes(size_t& buf1, size_t& buf2) = 0; // Optionally provide the two primary memory buffers. These pointers must // point to memory having at least the sizes returned by get_buffer_sizes. virtual void set_buffers(Real* buf1, Real* buf2) = 0; // Call this method to finish the setup phase. The subsequent methods are // valid only after this method has been called. virtual void finish_setup() = 0; virtual int get_problem_type(const Int& tracer_idx) const = 0; virtual Int get_num_tracers() const = 0; // set_{rhom,Qm}: Set cell values prior to running the QLT algorithm. // // Notation: // rho: Total density. // Q: Tracer density. // q: Tracer mixing ratio = Q/rho. // *m: Mass corresponding to the density; results from an integral over a // region, such as a cell. // Some CDRs have a nontrivial local <-> global cell index map. For these // CDRs, lclcellidx may be nontrivial. For others, the caller should provide // the index into the local cell. // // set_rhom must be called before set_Qm. KOKKOS_FUNCTION virtual void set_rhom( const Int& lclcellidx, const Int& rhomidx, // Current total mass in this cell. const Real& rhom) const = 0; KOKKOS_FUNCTION virtual void set_Qm( const Int& lclcellidx, const Int& tracer_idx, // Current tracer mass in this cell. const Real& Qm, // Minimum and maximum permitted tracer mass in this cell. Ignored if // ProblemType is 'nonnegative'. const Real& Qm_min, const Real& Qm_max, // If mass conservation is requested, provide the previous Qm, which will be // summed to give the desired global mass. const Real Qm_prev = std::numeric_limits<Real>::infinity()) const = 0; // Run the QLT algorithm with the values set by set_{rho,Q}. It is an error to // call this function from a parallel region. virtual void run() = 0; // Get a cell's tracer mass Qm after the QLT algorithm has run. KOKKOS_FUNCTION virtual Real get_Qm(const Int& lclcellidx, const Int& tracer_idx) const = 0; protected: Options options_; }; } // namespace cedr #endif //>> cedr_qlt.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_QLT_HPP #define INCLUDE_CEDR_QLT_HPP #include <mpi.h> #include <memory> #include <string> #include <iostream> #include <vector> #include <map> #include <list> //#include "cedr_cdr.hpp" //#include "cedr_util.hpp" namespace cedr { // QLT: Quasi-local tree-based non-iterative tracer density reconstructor for // mass conservation, shape preservation, and tracer consistency. namespace qlt { using cedr::mpi::Parallel; namespace impl { struct NodeSets { typedef std::shared_ptr<const NodeSets> ConstPtr; enum : int { mpitag = 42 }; // A node in the tree that is relevant to this rank. struct Node { // Rank of the node. If the node is in a level, then its rank is my rank. If // it's not in a level, then it is a comm partner of a node on this rank. Int rank; // cellidx if leaf node, ie, if nkids == 0; otherwise, undefined. Int id; // This node's parent, a comm partner, if such a partner is required. Int parent; // This node's kids, comm partners, if such partners are required. Parent // and kid nodes are pruned relative to the full tree over the mesh to // contain just the nodes that matter to this rank. Int nkids; Int kids[2]; // Offset factor into bulk data. An offset is a unit; actual buffer sizes // are multiples of this unit. Int offset; KOKKOS_FUNCTION Node () : rank(-1), id(-1), parent(-1), nkids(0), offset(-1) {} }; // A level in the level schedule that is constructed to orchestrate // communication. A node in a level depends only on nodes in lower-numbered // levels (l2r) or higher-numbered (r2l). // // The communication patterns are as follows: // > l2r // MPI rcv into kids // sum into node // MPI send from node // > r2l // MPI rcv into node // solve QP for kids // MPI send from kids struct Level { struct MPIMetaData { Int rank; // Rank of comm partner. Int offset; // Offset to start of buffer for this comm. Int size; // Size of this buffer in units of offsets. }; // The nodes in the level. std::vector<Int> nodes; // MPI information for this level. std::vector<MPIMetaData> me, kids; mutable std::vector<mpi::Request> me_send_req, me_recv_req, kids_req; }; // Levels. nodes[0] is level 0, the leaf level. std::vector<Level> levels; // Number of data slots this rank needs. Each node owned by this rank, plus // kids on other ranks, have an associated slot. Int nslots; // Allocate a node. The list node_mem_ is the mechanism for memory ownership; // node_mem_ isn't used for anything other than owning nodes. Int alloc () { const Int idx = node_mem_.size(); node_mem_.push_back(Node()); return idx; } Int nnode () const { return node_mem_.size(); } Node* node_h (const Int& idx) { cedr_assert(idx >= 0 && idx < static_cast<Int>(node_mem_.size())); return &node_mem_[idx]; } const Node* node_h (const Int& idx) const { return const_cast<NodeSets*>(this)->node_h(idx); } void print(std::ostream& os) const; private: std::vector<Node> node_mem_; }; template <typename ExeSpace> struct NodeSetsDeviceData { typedef typename cedr::impl::DeviceType<ExeSpace>::type Device; typedef Kokkos::View<Int*, Device> IntList; typedef Kokkos::View<NodeSets::Node*, Device> NodeList; NodeList node; // lvl(lvlptr(l):lvlptr(l+1)-1) is the list of node indices into node for // level l. IntList lvl, lvlptr; }; typedef impl::NodeSetsDeviceData<Kokkos::DefaultHostExecutionSpace> NodeSetsHostData; } // namespace impl namespace tree { // The caller builds a tree of these nodes to pass to QLT. struct Node { typedef std::shared_ptr<Node> Ptr; const Node* parent; // (Can't be a shared_ptr: would be a circular dependency.) Int rank; // Owning rank. Long cellidx; // If a leaf, the cell to which this node corresponds. Int nkids; // 0 at leaf, 1 or 2 otherwise. Node::Ptr kids[2]; Int reserved; // For internal use. Int level; // If providing only partial trees, set level to // the level of this node, with a leaf node at // level 0. Node () : parent(nullptr), rank(-1), cellidx(-1), nkids(0), reserved(-1), level(-1) {} }; // Utility to make a tree over a 1D mesh. For testing, it can be useful to // create an imbalanced tree. Node::Ptr make_tree_over_1d_mesh(const Parallel::Ptr& p, const Int& ncells, const bool imbalanced = false); } // namespace tree template <typename ExeSpace = Kokkos::DefaultExecutionSpace> class QLT : public cedr::CDR { public: typedef typename cedr::impl::DeviceType<ExeSpace>::type Device; typedef QLT<ExeSpace> Me; typedef std::shared_ptr<Me> Ptr; typedef Kokkos::View<Real*, Device> RealList; // Set up QLT topology and communication data structures based on a tree. Both // ncells and tree refer to the global mesh, not just this processor's // part. The tree must be identical across ranks. QLT(const Parallel::Ptr& p, const Int& ncells, const tree::Node::Ptr& tree, CDR::Options options = Options()); void print(std::ostream& os) const override; // Number of cells owned by this rank. Int nlclcells() const; // Cells owned by this rank, in order of local numbering. Thus, // gci2lci(gcis[i]) == i. Ideally, the caller never actually calls gci2lci(), // and instead uses the information from get_owned_glblcells to determine // local cell indices. void get_owned_glblcells(std::vector<Long>& gcis) const; // For global cell index cellidx, i.e., the globally unique ordinal associated // with a cell in the caller's tree, return this rank's local index for // it. This is not an efficient operation. Int gci2lci(const Int& gci) const; void declare_tracer(int problem_type, const Int& rhomidx) override; void end_tracer_declarations() override; void get_buffers_sizes(size_t& buf1, size_t& buf2) override; void set_buffers(Real* buf1, Real* buf2) override; void finish_setup() override; int get_problem_type(const Int& tracer_idx) const override; Int get_num_tracers() const override; // lclcellidx is gci2lci(cellidx). KOKKOS_INLINE_FUNCTION void set_rhom(const Int& lclcellidx, const Int& rhomidx, const Real& rhom) const override; // lclcellidx is gci2lci(cellidx). KOKKOS_INLINE_FUNCTION void set_Qm(const Int& lclcellidx, const Int& tracer_idx, const Real& Qm, const Real& Qm_min, const Real& Qm_max, const Real Qm_prev = std::numeric_limits<Real>::infinity()) const override; void run() override; KOKKOS_INLINE_FUNCTION Real get_Qm(const Int& lclcellidx, const Int& tracer_idx) const override; protected: typedef Kokkos::View<Int*, Device> IntList; typedef cedr::impl::Const<IntList> ConstIntList; typedef cedr::impl::ConstUnmanaged<IntList> ConstUnmanagedIntList; static void init(const std::string& name, IntList& d, typename IntList::HostMirror& h, size_t n); struct MetaDataBuilder { typedef std::shared_ptr<MetaDataBuilder> Ptr; std::vector<int> trcr2prob; }; PROTECTED_CUDA: struct MetaData { enum : Int { nprobtypes = 6 }; template <typename IntListT> struct Arrays { // trcr2prob(i) is the ProblemType of tracer i. IntListT trcr2prob; // bidx2trcr(prob2trcrptr(i) : prob2trcrptr(i+1)-1) is the list of // tracers having ProblemType index i. bidx2trcr is the permutation // from the user's tracer index to the bulk data's ordering (bidx). Int prob2trcrptr[nprobtypes+1]; IntListT bidx2trcr; // Inverse of bidx2trcr. IntListT trcr2bidx; // Points to the start of l2r bulk data for each problem type, within a // slot. Int prob2bl2r[nprobtypes + 1]; // Point to the start of l2r bulk data for each tracer, within a slot. IntListT trcr2bl2r; // Same for r2l bulk data. Int prob2br2l[nprobtypes + 1]; IntListT trcr2br2l; }; KOKKOS_INLINE_FUNCTION static int get_problem_type(const int& idx); // icpc doesn't let us use problem_type_ here, even though it's constexpr. static int get_problem_type_idx(const int& mask); KOKKOS_INLINE_FUNCTION static int get_problem_type_l2r_bulk_size(const int& mask); static int get_problem_type_r2l_bulk_size(const int& mask); struct CPT { // The only problem not supported is conservation alone. It makes very // little sense to use QLT for conservation alone. // The remaining problems fall into 6 categories of details. These // categories are tracked by QLT; which of the original problems being // solved is not important. enum { // l2r: rhom, (Qm_min, Qm, Qm_max)*; r2l: Qm* s = ProblemType::shapepreserve, st = ProblemType::shapepreserve | ProblemType::consistent, // l2r: rhom, (Qm_min, Qm, Qm_max, Qm_prev)*; r2l: Qm* cs = ProblemType::conserve | s, cst = ProblemType::conserve | st, // l2r: rhom, (q_min, Qm, q_max)*; r2l: (Qm, q_min, q_max)* t = ProblemType::consistent, // l2r: rhom, (q_min, Qm, q_max, Qm_prev)*; r2l: (Qm, q_min, q_max)* ct = ProblemType::conserve | t, // l2r: rhom, Qm*; r2l: Qm* nn = ProblemType::nonnegative, // l2r: rhom, (Qm, Qm_prev)*; r2l: Qm* cnn = ProblemType::conserve | nn }; }; Arrays<typename ConstUnmanagedIntList::HostMirror> a_h; Arrays<ConstUnmanagedIntList> a_d; void init(const MetaDataBuilder& mdb); private: Arrays<typename IntList::HostMirror> a_h_; Arrays<IntList> a_d_; }; struct BulkData { typedef cedr::impl::Unmanaged<RealList> UnmanagedRealList; UnmanagedRealList l2r_data, r2l_data; BulkData () : inited_(false) {} bool inited () const { return inited_; } void init(const size_t& l2r_sz, const size_t& r2l_sz); void init(Real* l2r_buf, const size_t& l2r_sz, Real* r2l_buf, const size_t& r2l_sz); private: bool inited_; RealList l2r_data_, r2l_data_; }; protected: void init(const Parallel::Ptr& p, const Int& ncells, const tree::Node::Ptr& tree); void init_ordinals(); /// Pointer data for initialization and host computation. Parallel::Ptr p_; // Tree and communication topology. std::shared_ptr<const impl::NodeSets> ns_; // Data extracted from ns_ for use in run() on device. std::shared_ptr<impl::NodeSetsDeviceData<ExeSpace> > nsdd_; std::shared_ptr<impl::NodeSetsHostData> nshd_; // Globally unique cellidx -> rank-local index. typedef std::map<Int,Int> Gci2LciMap; std::shared_ptr<Gci2LciMap> gci2lci_; // Temporary to collect caller's tracer information prior to calling // end_tracer_declarations(). typename MetaDataBuilder::Ptr mdb_; /// View data for host and device computation. // Constructed in end_tracer_declarations(). MetaData md_; BulkData bd_; PRIVATE_CUDA: void l2r_recv(const impl::NodeSets::Level& lvl, const Int& l2rndps) const; void l2r_combine_kid_data(const Int& lvlidx, const Int& l2rndps) const; void l2r_send_to_parents(const impl::NodeSets::Level& lvl, const Int& l2rndps) const; void root_compute(const Int& l2rndps, const Int& r2lndps) const; void r2l_recv(const impl::NodeSets::Level& lvl, const Int& r2lndps) const; void r2l_solve_qp(const Int& lvlidx, const Int& l2rndps, const Int& r2lndps) const; void r2l_send_to_kids(const impl::NodeSets::Level& lvl, const Int& r2lndps) const; }; namespace test { struct Input { bool unittest, perftest, write; Int ncells, ntracers, tracer_type, nrepeat; bool pseudorandom, verbose; }; Int run_unit_and_randomized_tests(const Parallel::Ptr& p, const Input& in); Int test_qlt(const Parallel::Ptr& p, const tree::Node::Ptr& tree, const Int& ncells, const Int nrepeat, // Diagnostic output for dev and illustration purposes. To be // clear, no QLT unit test requires output to be checked; each // checks in-memory data and returns a failure count. const bool write, // Provide memory to QLT for its buffers. const bool external_memory, // Set CDR::Options.prefer_numerical_mass_conservation_to_numerical_bounds. const bool prefer_mass_con_to_bounds, const bool verbose); } // namespace test } // namespace qlt } // namespace cedr // These are the definitions that must be visible in the calling translation // unit, unless Cuda relocatable device code is enabled. //#include "cedr_qlt_inl.hpp" #endif //>> cedr_caas.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_CAAS_HPP #define INCLUDE_CEDR_CAAS_HPP //#include "cedr_cdr.hpp" namespace cedr { // ClipAndAssuredSum. namespace caas { template <typename ExeSpace = Kokkos::DefaultExecutionSpace> class CAAS : public CDR { public: typedef typename cedr::impl::DeviceType<ExeSpace>::type Device; typedef CAAS<ExeSpace> Me; typedef std::shared_ptr<Me> Ptr; typedef Kokkos::View<Real*, Kokkos::LayoutLeft, Device> RealList; public: struct UserAllReducer { typedef std::shared_ptr<const UserAllReducer> Ptr; virtual int n_accum_in_place () const { return 1; } virtual int operator()(const mpi::Parallel& p, // In Fortran, these are formatted as // sendbuf(nlocal, nfld) // rcvbuf(nfld) // The implementation is permitted to modify sendbuf. Real* sendbuf, Real* rcvbuf, // nlocal is number of values to reduce in this rank. // nfld is number of fields. int nlocal, int nfld, MPI_Op op) const = 0; }; CAAS(const mpi::Parallel::Ptr& p, const Int nlclcells, const typename UserAllReducer::Ptr& r = nullptr); void declare_tracer(int problem_type, const Int& rhomidx) override; void end_tracer_declarations() override; void get_buffers_sizes(size_t& buf1, size_t& buf2) override; void set_buffers(Real* buf1, Real* buf2) override; void finish_setup() override; int get_problem_type(const Int& tracer_idx) const override; Int get_num_tracers() const override; // lclcellidx is trivial; it is the user's index for the cell. KOKKOS_INLINE_FUNCTION void set_rhom(const Int& lclcellidx, const Int& rhomidx, const Real& rhom) const override; KOKKOS_INLINE_FUNCTION void set_Qm(const Int& lclcellidx, const Int& tracer_idx, const Real& Qm, const Real& Qm_min, const Real& Qm_max, const Real Qm_prev = std::numeric_limits<Real>::infinity()) const override; void run() override; KOKKOS_INLINE_FUNCTION Real get_Qm(const Int& lclcellidx, const Int& tracer_idx) const override; protected: typedef cedr::impl::Unmanaged<RealList> UnmanagedRealList; typedef Kokkos::View<Int*, Kokkos::LayoutLeft, Device> IntList; struct Decl { int probtype; Int rhomidx; Decl (const int probtype_, const Int rhomidx_) : probtype(probtype_), rhomidx(rhomidx_) {} }; mpi::Parallel::Ptr p_; typename UserAllReducer::Ptr user_reducer_; Int nlclcells_, nrhomidxs_; std::shared_ptr<std::vector<Decl> > tracer_decls_; bool need_conserve_; IntList probs_, t2r_; typename IntList::HostMirror probs_h_; RealList d_, send_, recv_; bool finished_setup_; void reduce_globally(); PRIVATE_CUDA: void reduce_locally(); void finish_locally(); private: void get_buffers_sizes(size_t& buf1, size_t& buf2, size_t& buf3); }; namespace test { Int unittest(const mpi::Parallel::Ptr& p); } // namespace test } // namespace caas } // namespace cedr //#include "cedr_caas_inl.hpp" #endif //>> cedr_caas_inl.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_CAAS_INL_HPP #define INCLUDE_CEDR_CAAS_INL_HPP //#include "cedr_util.hpp" namespace cedr { // ClipAndAssuredSum. namespace caas { template <typename ES> KOKKOS_INLINE_FUNCTION void CAAS<ES>::set_rhom (const Int& lclcellidx, const Int& rhomidx, const Real& rhom) const { cedr_kernel_assert(lclcellidx >= 0 && lclcellidx < nlclcells_); cedr_kernel_assert(rhomidx >= 0 && rhomidx < nrhomidxs_); d_(lclcellidx) = rhom; } template <typename ES> KOKKOS_INLINE_FUNCTION void CAAS<ES> ::set_Qm (const Int& lclcellidx, const Int& tracer_idx, const Real& Qm, const Real& Qm_min, const Real& Qm_max, const Real Qm_prev) const { cedr_kernel_assert(lclcellidx >= 0 && lclcellidx < nlclcells_); cedr_kernel_assert(tracer_idx >= 0 && tracer_idx < probs_.extent_int(0)); const Int nt = probs_.size(); d_((1 + tracer_idx)*nlclcells_ + lclcellidx) = Qm; d_((1 + nt + tracer_idx)*nlclcells_ + lclcellidx) = Qm_min; d_((1 + 2*nt + tracer_idx)*nlclcells_ + lclcellidx) = Qm_max; if (need_conserve_) d_((1 + 3*nt + tracer_idx)*nlclcells_ + lclcellidx) = Qm_prev; } template <typename ES> KOKKOS_INLINE_FUNCTION Real CAAS<ES>::get_Qm (const Int& lclcellidx, const Int& tracer_idx) const { cedr_kernel_assert(lclcellidx >= 0 && lclcellidx < nlclcells_); cedr_kernel_assert(tracer_idx >= 0 && tracer_idx < probs_.extent_int(0)); return d_((1 + tracer_idx)*nlclcells_ + lclcellidx); } } // namespace caas } // namespace cedr #endif //>> cedr_local.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_LOCAL_HPP #define INCLUDE_CEDR_LOCAL_HPP //#include "cedr.hpp" //#include "cedr_kokkos.hpp" namespace cedr { namespace local { // The following routines solve // min_x norm(x - y; w) // st a'x = b // xlo <= x <= xhi, // a > 0, w > 0. // Minimize the weighted 2-norm. Return 0 on success and x == y, 1 on success // and x != y, -1 if infeasible, -2 if max_its hit with no solution. See section // 3 of Bochev, Ridzal, Shashkov, Fast optimization-based conservative remap of // scalar fields through aggregate mass transfer. KOKKOS_INLINE_FUNCTION Int solve_1eq_bc_qp(const Int n, const Real* w, const Real* a, const Real b, const Real* xlo, const Real* xhi, const Real* y, Real* x, const Int max_its = 100); KOKKOS_INLINE_FUNCTION Int solve_1eq_bc_qp_2d(const Real* w, const Real* a, const Real b, const Real* xlo, const Real* xhi, const Real* y, Real* x, const bool clip = true, // The 2D algorithm doesn't need to terminate based on a // tolerance, but by default it will exit early if the ND // algorithm would. Set this to false to run the full 2D // algorithm w/o checking the tolerance at start. If this // is false, the feasibility check is also disabled. const bool early_exit_on_tol = true); // ClipAndAssuredSum. Minimize the 1-norm with w = 1s. Does not check for // feasibility. KOKKOS_INLINE_FUNCTION void caas(const Int n, const Real* a, const Real b, const Real* xlo, const Real* xhi, const Real* y, Real* x, const bool clip = true); struct Method { enum Enum { least_squares, caas }; }; // Solve // min_x norm(x - y; w) // st a'x = b // x >= 0, // a, w > 0. Return 0 on success and x == y, 1 on success and x != y, -1 if // infeasible. w is used only if lcl_method = least_squares. KOKKOS_INLINE_FUNCTION Int solve_1eq_nonneg(const Int n, const Real* a, const Real b, const Real* y, Real* x, const Real* w, const Method::Enum lcl_method); Int unittest(); } // namespace local } // namespace cedr //#include "cedr_local_inl.hpp" #endif //>> cedr_mpi_inl.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_MPI_INL_HPP #define INCLUDE_CEDR_MPI_INL_HPP namespace cedr { namespace mpi { template <typename T> int reduce (const Parallel& p, const T* sendbuf, T* rcvbuf, int count, MPI_Op op, int root) { MPI_Datatype dt = get_type<T>(); return MPI_Reduce(const_cast<T*>(sendbuf), rcvbuf, count, dt, op, root, p.comm()); } template <typename T> int all_reduce (const Parallel& p, const T* sendbuf, T* rcvbuf, int count, MPI_Op op) { MPI_Datatype dt = get_type<T>(); return MPI_Allreduce(const_cast<T*>(sendbuf), rcvbuf, count, dt, op, p.comm()); } template <typename T> int isend (const Parallel& p, const T* buf, int count, int dest, int tag, Request* ireq) { MPI_Datatype dt = get_type<T>(); MPI_Request ureq; MPI_Request* req = ireq ? &ireq->request : &ureq; int ret = MPI_Isend(const_cast<T*>(buf), count, dt, dest, tag, p.comm(), req); if ( ! ireq) MPI_Request_free(req); #ifdef COMPOSE_DEBUG_MPI else ireq->unfreed++; #endif return ret; } template <typename T> int irecv (const Parallel& p, T* buf, int count, int src, int tag, Request* ireq) { MPI_Datatype dt = get_type<T>(); MPI_Request ureq; MPI_Request* req = ireq ? &ireq->request : &ureq; int ret = MPI_Irecv(buf, count, dt, src, tag, p.comm(), req); if ( ! ireq) MPI_Request_free(req); #ifdef COMPOSE_DEBUG_MPI else ireq->unfreed++; #endif return ret; } template<typename T> int gather (const Parallel& p, const T* sendbuf, int sendcount, T* recvbuf, int recvcount, int root) { MPI_Datatype dt = get_type<T>(); return MPI_Gather(sendbuf, sendcount, dt, recvbuf, recvcount, dt, root, p.comm()); } template <typename T> int gatherv (const Parallel& p, const T* sendbuf, int sendcount, T* recvbuf, const int* recvcounts, const int* displs, int root) { MPI_Datatype dt = get_type<T>(); return MPI_Gatherv(sendbuf, sendcount, dt, recvbuf, recvcounts, displs, dt, root, p.comm()); } } // namespace mpi } // namespace cedr #endif //>> cedr_local_inl.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_LOCAL_INL_HPP #define INCLUDE_CEDR_LOCAL_INL_HPP //#include "cedr_util.hpp" namespace cedr { namespace local { namespace impl { KOKKOS_INLINE_FUNCTION Real calc_r_tol (const Real b, const Real* a, const Real* y, const Int n) { Real ab = std::abs(b); for (Int i = 0; i < n; ++i) ab = cedr::impl::max(ab, std::abs(a[i]*y[i])); return 1e1*std::numeric_limits<Real>::epsilon()*std::abs(ab); } // Eval r at end points to check for feasibility, and also possibly a quick exit // on a common case. Return -1 if infeasible, 1 if a corner is a solution, 0 if // feasible and a corner is not. KOKKOS_INLINE_FUNCTION Int check_lu (const Int n, const Real* a, const Real& b, const Real* xlo, const Real* xhi, const Real& r_tol, Real* x) { Real r = -b; for (Int i = 0; i < n; ++i) { x[i] = xlo[i]; r += a[i]*x[i]; } if (std::abs(r) <= r_tol) return 1; if (r > 0) return -1; r = -b; for (Int i = 0; i < n; ++i) { x[i] = xhi[i]; r += a[i]*x[i]; } if (std::abs(r) <= r_tol) return 1; if (r < 0) return -1; return 0; } KOKKOS_INLINE_FUNCTION void calc_r (const Int n, const Real* w, const Real* a, const Real b, const Real* xlo, const Real* xhi, const Real* y, const Real& lambda, Real* x, Real& r, Real& r_lambda) { r = 0; r_lambda = 0; for (Int i = 0; i < n; ++i) { const Real q = a[i]/w[i]; const Real x_trial = y[i] + lambda*q; Real xtmp; if (x_trial < (xtmp = xlo[i])) x[i] = xtmp; else if (x_trial > (xtmp = xhi[i])) x[i] = xtmp; else { x[i] = x_trial; r_lambda += a[i]*q; } r += a[i]*x[i]; } r -= b; } } // namespace impl // 2D special case for efficiency. KOKKOS_INLINE_FUNCTION Int solve_1eq_bc_qp_2d (const Real* w, const Real* a, const Real b, const Real* xlo, const Real* xhi, const Real* y, Real* x, const bool clip, const bool early_exit_on_tol) { Int info; if (early_exit_on_tol) { const Real r_tol = impl::calc_r_tol(b, a, y, 2); Int info = impl::check_lu(2, a, b, xlo, xhi, r_tol, x); if (info == -1) return info; } { // Check if the optimal point ignoring bound constraints is in bounds. Real qmass = 0, dm = b; for (int i = 0; i < 2; ++i) { const Real qi = a[i]/w[i]; qmass += a[i]*qi; dm -= a[i]*y[i]; } const Real lambda = dm/qmass; bool ok = true; for (int i = 0; i < 2; ++i) { x[i] = y[i] + lambda*(a[i]/w[i]); if (x[i] < xlo[i] || x[i] > xhi[i]) { ok = false; break; } } if (ok) return 1; } // Solve for intersection of a'x = b, given by the parameterized line // p(alpa) = x_base + alpha x_dir, // with a bounding line. // Get parameterized line. Real x_base[2]; for (int i = 0; i < 2; ++i) x_base[i] = 0.5*b/a[i]; Real x_dir[] = {-a[1], a[0]}; // Get the 4 alpha values. Real alphas[4]; alphas[0] = (xlo[1] - x_base[1])/x_dir[1]; // bottom alphas[1] = (xhi[0] - x_base[0])/x_dir[0]; // right alphas[2] = (xhi[1] - x_base[1])/x_dir[1]; // top alphas[3] = (xlo[0] - x_base[0])/x_dir[0]; // left // Find the middle two in the sorted alphas. Real min = alphas[0], max = min; Int imin = 0, imax = 0; for (Int i = 1; i < 4; ++i) { const Real alpha = alphas[i]; if (alpha < min) { min = alpha; imin = i; } if (alpha > max) { max = alpha; imax = i; } } Int ais[2]; Int cnt = 0; for (Int i = 0; i < 4; ++i) if (i != imin && i != imax) { ais[cnt++] = i; if (cnt == 2) break; } Real objs[2]; Real alpha_mid = 0; for (Int j = 0; j < 2; ++j) { const Real alpha = alphas[ais[j]]; alpha_mid += alpha; Real obj = 0; for (Int i = 0; i < 2; ++i) { x[i] = x_base[i] + alpha*x_dir[i]; obj += w[i]*cedr::util::square(y[i] - x[i]); } objs[j] = obj; } const Int ai = ais[objs[0] <= objs[1] ? 0 : 1]; info = 1; Int i0 = 0; switch (ai) { case 0: case 2: x[1] = ai == 0 ? xlo[1] : xhi[1]; i0 = 1; break; case 1: case 3: x[0] = ai == 1 ? xhi[0] : xlo[0]; i0 = 0; break; default: cedr_kernel_assert(0); info = -2; } const Int i1 = (i0 + 1) % 2; x[i1] = (b - a[i0]*x[i0])/a[i1]; if (clip) x[i1] = cedr::impl::min(xhi[i1], cedr::impl::max(xlo[i1], x[i1])); return info; } KOKKOS_INLINE_FUNCTION Int solve_1eq_bc_qp (const Int n, const Real* w, const Real* a, const Real b, const Real* xlo, const Real* xhi, const Real* y, Real* x, const Int max_its) { const Real r_tol = impl::calc_r_tol(b, a, y, n); Int info = impl::check_lu(n, a, b, xlo, xhi, r_tol, x); if (info != 0) return info; for (int i = 0; i < n; ++i) if (x[i] != y[i]) { info = 1; x[i] = y[i]; } // In our use case, the caller has already checked (more cheaply) for a quick // exit. #if 0 { // Check for a quick exit. bool all_in = true; Real r = 0; for (Int i = 0; i < n; ++i) { if (x[i] < xlo[i] || x[i] > xhi[i]) { all_in = false; break; } r += a[i]*x[i]; } if (all_in) { r -= b; if (std::abs(r) <= r_tol) return info; } } #endif const Real wall_dist = 1e-3; // Get lambda endpoints. Real lamlo = 0, lamhi = 0; for (Int i = 0; i < n; ++i) { const Real rq = w[i]/a[i]; const Real lamlo_i = rq*(xlo[i] - y[i]); const Real lamhi_i = rq*(xhi[i] - y[i]); if (i == 0) { lamlo = lamlo_i; lamhi = lamhi_i; } else { lamlo = cedr::impl::min(lamlo, lamlo_i); lamhi = cedr::impl::max(lamhi, lamhi_i); } } const Real lamlo_feas = lamlo, lamhi_feas = lamhi; Real lambda = lamlo <= 0 && lamhi >= 0 ? 0 : lamlo; // Bisection-safeguarded Newton iteration for r(lambda) = 0. bool prev_step_bisect = false; Int nbisect = 0; info = -2; for (Int iteration = 0; iteration < max_its; ++iteration) { // Compute x, r, r_lambda. Real r, r_lambda; impl::calc_r(n, w, a, b, xlo, xhi, y, lambda, x, r, r_lambda); // Is r(lambda) - b sufficiently == 0? if (std::abs(r) <= r_tol) { info = 1; break; } // Check if the lambda bounds are too close. if (nbisect > 64) { if (lamhi == lamhi_feas || lamlo == lamlo_feas) { // r isn't small enough and one lambda bound is on the feasibility // limit. The QP must not be feasible. info = -1; break; } info = 1; break; } // Adjust lambda bounds. if (r > 0) lamhi = lambda; else lamlo = lambda; if (r_lambda != 0) { // Newton step. lambda -= r/r_lambda; } else { // Force bisection. lambda = lamlo; } // Safeguard. The wall distance check assures progress, but use it only // every other potential bisection. const Real D = prev_step_bisect ? 0 : wall_dist*(lamhi - lamlo); if (lambda - lamlo < D || lamhi - lambda < D) { lambda = 0.5*(lamlo + lamhi); ++nbisect; prev_step_bisect = true; } else { prev_step_bisect = false; } } return info; } KOKKOS_INLINE_FUNCTION void caas (const Int n, const Real* a, const Real b, const Real* xlo, const Real* xhi, const Real* y, Real* x, const bool clip) { Real dm = b; for (Int i = 0; i < n; ++i) { x[i] = cedr::impl::max(xlo[i], cedr::impl::min(xhi[i], y[i])); dm -= a[i]*x[i]; } if (dm == 0) return; if (dm > 0) { Real fac = 0; for (Int i = 0; i < n; ++i) fac += a[i]*(xhi[i] - x[i]); if (fac > 0) { fac = dm/fac; for (Int i = 0; i < n; ++i) x[i] += fac*(xhi[i] - x[i]); } } else if (dm < 0) { Real fac = 0; for (Int i = 0; i < n; ++i) fac += a[i]*(x[i] - xlo[i]); if (fac > 0) { fac = dm/fac; for (Int i = 0; i < n; ++i) x[i] += fac*(x[i] - xlo[i]); } } // Clip again for numerics. if (clip) for (Int i = 0; i < n; ++i) x[i] = cedr::impl::max(xlo[i], cedr::impl::min(xhi[i], x[i])); } KOKKOS_INLINE_FUNCTION Int solve_1eq_nonneg (const Int n, const Real* a, const Real b, const Real* y, Real* x, const Real* w, const Method::Enum method) { cedr_kernel_assert(n <= 16); if (b < 0) return -1; const Real zero[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // Set the upper bound to the value that implies that just one slot gets all // of the mass. Real xhi[16]; for (int i = 0; i < n; ++i) xhi[i] = b/a[i]; if (method == Method::caas) { caas(n, a, b, zero, xhi, y, x); return 1; } else { if (n == 2) return solve_1eq_bc_qp_2d(w, a, b, zero, xhi, y, x); else return solve_1eq_bc_qp(n, w, a, b, zero, xhi, y, x); } } } // namespace local } // namespace cedr #endif //>> cedr_qlt_inl.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_QLT_INL_HPP #define INCLUDE_CEDR_QLT_INL_HPP #include <cassert> //#include "cedr_local.hpp" namespace cedr { namespace qlt { template <typename ES> KOKKOS_INLINE_FUNCTION void QLT<ES>::set_rhom (const Int& lclcellidx, const Int& rhomidx, const Real& rhom) const { const Int ndps = md_.a_d.prob2bl2r[md_.nprobtypes]; bd_.l2r_data(ndps*lclcellidx) = rhom; } template <typename ES> KOKKOS_INLINE_FUNCTION void QLT<ES>::set_Qm (const Int& lclcellidx, const Int& tracer_idx, const Real& Qm, const Real& Qm_min, const Real& Qm_max, const Real Qm_prev) const { const Int ndps = md_.a_d.prob2bl2r[md_.nprobtypes]; Real* bd; { const Int bdi = md_.a_d.trcr2bl2r(tracer_idx); bd = &bd_.l2r_data(ndps*lclcellidx + bdi); } { const Int problem_type = md_.a_d.trcr2prob(tracer_idx); Int next = 0; if (problem_type & ProblemType::shapepreserve) { bd[0] = Qm_min; bd[1] = Qm; bd[2] = Qm_max; next = 3; } else if (problem_type & ProblemType::consistent) { const Real rhom = bd_.l2r_data(ndps*lclcellidx); bd[0] = Qm_min / rhom; bd[1] = Qm; bd[2] = Qm_max / rhom; next = 3; } else if (problem_type & ProblemType::nonnegative) { bd[0] = Qm; next = 1; } else { cedr_kernel_throw_if(true, "set_Q: invalid problem_type."); } if (problem_type & ProblemType::conserve) { cedr_kernel_throw_if(Qm_prev == std::numeric_limits<Real>::infinity(), "Qm_prev was not provided to set_Q."); bd[next] = Qm_prev; } } } template <typename ES> KOKKOS_INLINE_FUNCTION Real QLT<ES>::get_Qm (const Int& lclcellidx, const Int& tracer_idx) const { const Int ndps = md_.a_d.prob2br2l[md_.nprobtypes]; const Int bdi = md_.a_d.trcr2br2l(tracer_idx); return bd_.r2l_data(ndps*lclcellidx + bdi); } //todo Replace this and the calling code with ReconstructSafely. KOKKOS_INLINE_FUNCTION void r2l_nl_adjust_bounds (Real Qm_bnd[2], const Real rhom[2], Real Qm_extra) { Real q[2]; for (Int i = 0; i < 2; ++i) q[i] = Qm_bnd[i] / rhom[i]; if (Qm_extra < 0) { Int i0, i1; if (q[0] >= q[1]) { i0 = 0; i1 = 1; } else { i0 = 1; i1 = 0; } const Real Qm_gap = (q[i1] - q[i0])*rhom[i0]; if (Qm_gap <= Qm_extra) { Qm_bnd[i0] += Qm_extra; return; } } else { Int i0, i1; if (q[0] <= q[1]) { i0 = 0; i1 = 1; } else { i0 = 1; i1 = 0; } const Real Qm_gap = (q[i1] - q[i0])*rhom[i0]; if (Qm_gap >= Qm_extra) { Qm_bnd[i0] += Qm_extra; return; } } { // Have to adjust both. Adjust so that the q bounds are the same. This // procedure assures that as long as rhom is conservative, then the // adjustment never pushes q_{min,max} out of the safety bounds. const Real Qm_tot = Qm_bnd[0] + Qm_bnd[1] + Qm_extra; const Real rhom_tot = rhom[0] + rhom[1]; const Real q_tot = Qm_tot / rhom_tot; for (Int i = 0; i < 2; ++i) Qm_bnd[i] = q_tot*rhom[i]; } } template <typename ES> KOKKOS_INLINE_FUNCTION int QLT<ES>::MetaData::get_problem_type (const int& idx) { static const Int problem_type[] = { CPT::st, CPT::cst, CPT::t, CPT::ct, CPT::nn, CPT::cnn }; return problem_type[idx]; } template <typename ES> KOKKOS_INLINE_FUNCTION int QLT<ES>::MetaData::get_problem_type_l2r_bulk_size (const int& mask) { if (mask & ProblemType::nonnegative) { if (mask & ProblemType::conserve) return 2; return 1; } if (mask & ProblemType::conserve) return 4; return 3; } namespace impl { KOKKOS_INLINE_FUNCTION void solve_node_problem (const Real& rhom, const Real* pd, const Real& Qm, const Real& rhom0, const Real* k0d, Real& Qm0, const Real& rhom1, const Real* k1d, Real& Qm1, const bool prefer_mass_con_to_bounds) { Real Qm_min_kids [] = {k0d[0], k1d[0]}; Real Qm_orig_kids[] = {k0d[1], k1d[1]}; Real Qm_max_kids [] = {k0d[2], k1d[2]}; { // The ideal problem is not assuredly feasible. Test for feasibility. If not // feasible, adjust bounds to solve the safety problem, which is assuredly // feasible if the total density field rho is mass conserving (Q doesn't // have to be mass conserving, of course; achieving mass conservation is one // use for QLT). const Real Qm_min = pd[0], Qm_max = pd[2]; const bool lo = Qm < Qm_min, hi = Qm > Qm_max; if (lo || hi) { // If the discrepancy is numerical noise, don't act on it. const Real tol = 10*std::numeric_limits<Real>::epsilon(); const Real discrepancy = lo ? Qm_min - Qm : Qm - Qm_max; if (discrepancy > tol*(Qm_max - Qm_min)) { const Real rhom_kids[] = {rhom0, rhom1}; r2l_nl_adjust_bounds(lo ? Qm_min_kids : Qm_max_kids, rhom_kids, Qm - (lo ? Qm_min : Qm_max)); } } else { // Quick exit if everything is OK as is. This is a speedup, and it also // lets the subnode solver make ~1 ulp changes instead of having to keep x // = y if y satisfies the conditions. Without this block, the // no_change_should_hold tests can fail. if (Qm == pd[1] && // Was our total tracer mass adjusted? // Are the kids' problems feasible? Qm_orig_kids[0] >= Qm_min_kids[0] && Qm_orig_kids[0] <= Qm_max_kids[0] && Qm_orig_kids[1] >= Qm_min_kids[1] && Qm_orig_kids[1] <= Qm_max_kids[1]) { // Don't need to do anything, so skip even the math-based quick exits in // solve_node_problem. Qm0 = Qm_orig_kids[0]; Qm1 = Qm_orig_kids[1]; return; } } } { // Solve the node's QP. static const Real ones[] = {1, 1}; const Real w[] = {1/rhom0, 1/rhom1}; Real Qm_kids[] = {k0d[1], k1d[1]}; local::solve_1eq_bc_qp_2d(w, ones, Qm, Qm_min_kids, Qm_max_kids, Qm_orig_kids, Qm_kids, ! prefer_mass_con_to_bounds /* clip */, ! prefer_mass_con_to_bounds /* early_exit_on_tol */); Qm0 = Qm_kids[0]; Qm1 = Qm_kids[1]; } } KOKKOS_INLINE_FUNCTION void solve_node_problem (const Int problem_type, const Real& rhom, const Real* pd, const Real& Qm, const Real& rhom0, const Real* k0d, Real& Qm0, const Real& rhom1, const Real* k1d, Real& Qm1, const bool prefer_mass_con_to_bounds) { if ((problem_type & ProblemType::consistent) && ! (problem_type & ProblemType::shapepreserve)) { Real mpd[3], mk0d[3], mk1d[3]; mpd[0] = pd [0]*rhom ; mpd [1] = pd[1] ; mpd [2] = pd [2]*rhom ; mk0d[0] = k0d[0]*rhom0; mk0d[1] = k0d[1]; mk0d[2] = k0d[2]*rhom0; mk1d[0] = k1d[0]*rhom1; mk1d[1] = k1d[1]; mk1d[2] = k1d[2]*rhom1; solve_node_problem(rhom, mpd, Qm, rhom0, mk0d, Qm0, rhom1, mk1d, Qm1, prefer_mass_con_to_bounds); return; } else if (problem_type & ProblemType::nonnegative) { static const Real ones[] = {1, 1}; const Real w[] = {1/rhom0, 1/rhom1}; Real Qm_orig_kids[] = {k0d[0], k1d[0]}; Real Qm_kids[2] = {k0d[0], k1d[0]}; local::solve_1eq_nonneg(2, ones, Qm, Qm_orig_kids, Qm_kids, w, local::Method::least_squares); Qm0 = Qm_kids[0]; Qm1 = Qm_kids[1]; } else { solve_node_problem(rhom, pd, Qm, rhom0, k0d, Qm0, rhom1, k1d, Qm1, prefer_mass_con_to_bounds); } } } // namespace impl } // namespace qlt } // namespace cedr #endif //>> cedr_test_randomized.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_TEST_RANDOMIZED_HPP #define INCLUDE_CEDR_TEST_RANDOMIZED_HPP //#include "cedr_cdr.hpp" //#include "cedr_mpi.hpp" //#include "cedr_util.hpp" namespace cedr { namespace test { class TestRandomized { public: TestRandomized(const std::string& cdr_name, const mpi::Parallel::Ptr& p, const Int& ncells, const bool verbose = false, const CDR::Options options = CDR::Options()); // The subclass should call this, probably in its constructor. void init(); template <typename CDRT, typename ExeSpace = Kokkos::DefaultExecutionSpace> Int run(const Int nrepeat = 1, const bool write=false); private: const std::string cdr_name_; const CDR::Options options_; protected: struct Tracer { typedef ProblemType PT; Int idx; Int problem_type; Int perturbation_type; bool no_change_should_hold, safe_should_hold, local_should_hold; bool write; std::string str() const; Tracer () : idx(-1), problem_type(-1), perturbation_type(-1), no_change_should_hold(false), safe_should_hold(true), local_should_hold(true), write(false) {} }; struct ValuesPartition { Int ncells () const { return ncells_; } KIF Real* rhom () const { return v_; } KIF Real* Qm_min (const Int& ti) const { return v_ + ncells_*(1 + 4*ti ); } KIF Real* Qm (const Int& ti) const { return v_ + ncells_*(1 + 4*ti + 1); } KIF Real* Qm_max (const Int& ti) const { return v_ + ncells_*(1 + 4*ti + 2); } KIF Real* Qm_prev (const Int& ti) const { return v_ + ncells_*(1 + 4*ti + 3); } protected: void init (const Int ncells, Real* v) { ncells_ = ncells; v_ = v; } private: Int ncells_; Real* v_; }; struct Values : public ValuesPartition { Values (const Int ntracers, const Int ncells) : v_((4*ntracers + 1)*ncells) { init(ncells, v_.data()); } Real* data () { return v_.data(); } size_t size () const { return v_.size(); } private: std::vector<Real> v_; }; PRIVATE_CUDA: template <typename ExeSpace> struct ValuesDevice : public ValuesPartition { // This Values object is the source of data and gets updated by sync_host. ValuesDevice (Values& v) : rar_(v.data(), v.size()) { init(v.ncells(), rar_.device_ptr()); } // Values -> device. void sync_device () { rar_.sync_device(); } // Update Values from device. void sync_host () { rar_.sync_host(); } private: util::RawArrayRaft<Real, ExeSpace> rar_; }; protected: // For solution output, if requested. struct Writer { std::unique_ptr<FILE, cedr::util::FILECloser> fh; std::vector<Int> ngcis; // Number of i'th rank's gcis_ array. std::vector<Long> gcis; // Global cell indices packed by rank's gcis_ vector. std::vector<int> displs; // Cumsum of above. ~Writer(); }; const mpi::Parallel::Ptr p_; const Int ncells_; // Global mesh entity IDs, 1-1 with reduction array index or QLT leaf node. std::vector<Long> gcis_; std::vector<Tracer> tracers_; // Tell this class the CDR. virtual CDR& get_cdr() = 0; // Fill gcis_. virtual void init_numbering() = 0; // Using tracers_, the vector of Tracers, initialize the CDR's tracers. virtual void init_tracers() = 0; virtual void run_impl(const Int trial) = 0; private: // For optional output. bool write_inited_; std::shared_ptr<Writer> w_; // Only on root. void init_tracers_vector(); void add_const_to_Q( const Tracer& t, Values& v, // Move 0 < alpha <= 1 of the way to the QLT or safety feasibility bound. const Real& alpha, // Whether the modification should be done in a mass-conserving way. const bool conserve_mass, // Only safety problem is feasible. const bool safety_problem); void perturb_Q(const Tracer& t, Values& v); void init_writer(); void gather_field(const Real* Qm_lcl, std::vector<Real>& Qm_gbl, std::vector<Real>& wrk); void write_field(const std::string& tracer_name, const std::string& field_name, const std::vector<Real>& Qm); void write_pre(const Tracer& t, Values& v); void write_post(const Tracer& t, Values& v); static void generate_rho(Values& v); static void generate_Q(const Tracer& t, Values& v); static void permute_Q(const Tracer& t, Values& v); static std::string get_tracer_name(const Tracer& t); Int check(const std::string& cdr_name, const mpi::Parallel& p, const std::vector<Tracer>& ts, const Values& v); }; } // namespace test } // namespace cedr //#include "cedr_test_randomized_inl.hpp" #endif //>> cedr_test_randomized_inl.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_TEST_RANDOMIZED_INL_HPP #define INCLUDE_CEDR_TEST_RANDOMIZED_INL_HPP //#include "cedr_test_randomized.hpp" namespace cedr { namespace test { template <typename CDRT, typename ES> Int TestRandomized::run (const Int nrepeat, const bool write) { const Int nt = tracers_.size(), nlclcells = gcis_.size(); Values v(nt, nlclcells); generate_rho(v); for (const auto& t : tracers_) { generate_Q(t, v); perturb_Q(t, v); } if (write) for (const auto& t : tracers_) write_pre(t, v); CDRT cdr = static_cast<CDRT&>(get_cdr()); ValuesDevice<ES> vd(v); vd.sync_device(); { const auto rhom = vd.rhom(); const auto set_rhom = KOKKOS_LAMBDA (const Int& i) { cdr.set_rhom(i, 0, rhom[i]); }; Kokkos::parallel_for(Kokkos::RangePolicy<ES>(0, nlclcells), set_rhom); } // repeat > 1 runs the same values repeatedly for performance // meaurement. for (Int trial = 0; trial <= nrepeat; ++trial) { const auto set_Qm = KOKKOS_LAMBDA (const Int& j) { const auto ti = j / nlclcells; const auto i = j % nlclcells; cdr.set_Qm(i, ti, vd.Qm(ti)[i], vd.Qm_min(ti)[i], vd.Qm_max(ti)[i], vd.Qm_prev(ti)[i]); }; Kokkos::parallel_for(Kokkos::RangePolicy<ES>(0, nt*nlclcells), set_Qm); run_impl(trial); } { const auto get_Qm = KOKKOS_LAMBDA (const Int& j) { const auto ti = j / nlclcells; const auto i = j % nlclcells; vd.Qm(ti)[i] = cdr.get_Qm(i, ti); }; Kokkos::parallel_for(Kokkos::RangePolicy<ES>(0, nt*nlclcells), get_Qm); } vd.sync_host(); // => v contains computed values if (write) for (const auto& t : tracers_) write_post(t, v); return check(cdr_name_, *p_, tracers_, v); } } // namespace test } // namespace cedr #endif //>> cedr_test.hpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. #ifndef INCLUDE_CEDR_TEST_HPP #define INCLUDE_CEDR_TEST_HPP //#include "cedr.hpp" //#include "cedr_mpi.hpp" namespace cedr { namespace test { namespace transport1d { struct Input { Int ncells; bool verbose; }; Int run(const mpi::Parallel::Ptr& p, const Input& in); } // namespace transport1d } // namespace test } // namespace cedr #endif //>> cedr_util.cpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. //#include "cedr_util.hpp" namespace cedr { namespace util { bool eq (const std::string& a, const char* const b1, const char* const b2) { return (a == std::string(b1) || (b2 && a == std::string(b2)) || a == std::string("-") + std::string(b1)); } Real urand () { return std::rand() / ((Real) RAND_MAX + 1.0); } Real reldif (const Real* a, const Real* b, const Int n) { Real num = 0, den = 0; for (Int i = 0; i < n; ++i) { num += std::abs(a[i] - b[i]); den += std::abs(a[i]); } return num/den; } } } //>> cedr_local.cpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. //#include "cedr_local.hpp" //#include "cedr_local_inl.hpp" namespace cedr { namespace local { namespace test { // Check the first-order optimality conditions. Return true if OK, false // otherwise. If quiet, don't print anything. bool check_1eq_bc_qp_foc ( const char* label, const Int n, const Real* w, const Real* a, const Real b, const Real* xlo, const Real* xhi, const Real* y, const Real* x, const bool verbose) { auto& os = std::cout; bool ok = true; Real xtmp; // Check the bound constraints. for (Int i = 0; i < n; ++i) if (x[i] < (xtmp = xlo[i])) { if (verbose) os << "x[" << i << "] = " << x[i] << " but x[i] - xlo[i] = " << (x[i] - xtmp) << "\n"; ok = false; } for (Int i = 0; i < n; ++i) if (x[i] > (xtmp = xhi[i])) { if (verbose) os << "x[" << i << "] = " << x[i] << " but xhi[i] - x[i] = " << (xtmp - x[i]) << "\n"; ok = false; } // Check the equality constraint. Real r = 0; for (Int i = 0; i < n; ++i) r += a[i]*x[i]; r -= b; if (std::abs(r) > impl::calc_r_tol(b, a, y, n)) { if (verbose) os << "r = " << r << "\n"; ok = false; } // Check the gradient is 0 when projected into the constraints. Compute // g = W (x - y) // g_reduced = g - C ((C'C) \ (C'g)) // where // IA = I(:,A) // C = [IA a], // and A is the active set. const Real padtol = 1e5*std::numeric_limits<Real>::epsilon(); Real lambda = 0, den = 0; for (Int i = 0; i < n; ++i) { const Real pad = padtol*(xhi[i] - xlo[i]); if (xlo[i] + pad <= x[i] && x[i] <= xhi[i] - pad) { const Real gi = w[i]*(x[i] - y[i]); lambda += a[i]*gi; den += a[i]*a[i]; } } lambda /= den; Real normg = 0, normy = 0; for (Int i = 0; i < n; ++i) { normy += cedr::util::square(y[i]); const Real pad = padtol*(xhi[i] - xlo[i]); if (xlo[i] + pad <= x[i] && x[i] <= xhi[i] - pad) normg += cedr::util::square(w[i]*(x[i] - y[i]) - a[i]*lambda); } normy = std::sqrt(normy); normg = std::sqrt(normg); const Real gtol = 1e4*std::numeric_limits<Real>::epsilon()*normy; if (normg > gtol) { if (verbose) os << "norm(g) = " << normg << " gtol = " << gtol << "\n"; ok = false; } // Check the gradient at the active boundaries. for (Int i = 0; i < n; ++i) { const bool onlo = x[i] == xlo[i]; const bool onhi = onlo ? false : x[i] == xhi[i]; if (onlo || onhi) { const Real rg = w[i]*(x[i] - y[i]) - a[i]*lambda; if (onlo && rg < -gtol) { if (verbose) os << "onlo but rg = " << rg << "\n"; ok = false; } else if (onhi && rg > gtol) { if (verbose) os << "onhi but rg = " << rg << "\n"; ok = false; } } } if ( ! ok && verbose) os << "label: " << label << "\n"; return ok; } Int test_1eq_bc_qp () { bool verbose = true; Int nerr = 0; Int n; static const Int N = 16; Real w[N], a[N], b, xlo[N], xhi[N], y[N], x[N], al, au; auto run = [&] () { const Int info = solve_1eq_bc_qp(n, w, a, b, xlo, xhi, y, x); const bool ok = test::check_1eq_bc_qp_foc( "unittest", n, w, a, b, xlo, xhi, y, x, verbose); if ( ! ok) ++nerr; if (n == 2) { // This version never returns 0. Real x2[2]; const Int info2 = solve_1eq_bc_qp_2d(w, a, b, xlo, xhi, y, x2); if (info2 != 1 && (info == 0 || info == 1)) { if (verbose) pr(puf(info) pu(info2)); ++nerr; } const Real rd = cedr::util::reldif(x, x2, 2); if (rd > 1e4*std::numeric_limits<Real>::epsilon()) { if (verbose) printf("%1.1e | y %1.15e %1.15e | x %1.15e %1.15e | " "x2 %1.15e %1.15e | l %1.15e %1.15e | u %1.15e %1.15e\n", rd, y[0], y[1], x[0], x[1], x2[0], x2[1], xlo[0], xlo[1], xhi[0], xhi[1]); ++nerr; } } caas(n, a, b, xlo, xhi, y, x); Real m = 0, den = 0; for (Int i = 0; i < n; ++i) { m += a[i]*x[i]; den += std::abs(a[i]*x[i]); if (x[i] < xlo[i]) ++nerr; else if (x[i] > xhi[i]) ++nerr; } const Real rd = std::abs(b - m)/den; if (rd > 1e3*std::numeric_limits<Real>::epsilon()) { if (verbose) pr(puf(rd) pu(n) pu(b) pu(m)); ++nerr; } }; auto gena = [&] () { for (Int i = 0; i < n; ++i) a[i] = 0.1 + cedr::util::urand(); }; auto genw = [&] () { for (Int i = 0; i < n; ++i) w[i] = 0.1 + cedr::util::urand(); }; auto genbnds = [&] () { al = au = 0; for (Int i = 0; i < n; ++i) { xlo[i] = cedr::util::urand() - 0.5; al += a[i]*xlo[i]; xhi[i] = xlo[i] + cedr::util::urand(); au += a[i]*xhi[i]; } }; auto genb = [&] (const bool in) { if (in) { const Real alpha = cedr::util::urand(); b = alpha*al + (1 - alpha)*au; } else { if (cedr::util::urand() > 0.5) b = au + 0.01 + cedr::util::urand(); else b = al - 0.01 - cedr::util::urand(); } }; auto geny = [&] (const bool in) { if (in) { for (Int i = 0; i < n; ++i) { const Real alpha = cedr::util::urand(); y[i] = alpha*xlo[i] + (1 - alpha)*xhi[i]; } } else if (cedr::util::urand() > 0.2) { for (Int i = 1; i < n; i += 2) { const Real alpha = cedr::util::urand(); y[i] = alpha*xlo[i] + (1 - alpha)*xhi[i]; cedr_assert(y[i] >= xlo[i] && y[i] <= xhi[i]); } for (Int i = 0; i < n; i += 4) y[i] = xlo[i] - cedr::util::urand(); for (Int i = 2; i < n; i += 4) y[i] = xhi[i] + cedr::util::urand(); } else { for (Int i = 0; i < n; i += 2) y[i] = xlo[i] - cedr::util::urand(); for (Int i = 1; i < n; i += 2) y[i] = xhi[i] + cedr::util::urand(); } }; auto b4y = [&] () { b = 0; for (Int i = 0; i < n; ++i) b += a[i]*y[i]; }; for (n = 2; n <= N; ++n) { const Int count = n == 2 ? 100 : 10; for (Int i = 0; i < count; ++i) { gena(); genw(); genbnds(); genb(true); geny(true); run(); b4y(); run(); genb(true); geny(false); run(); } } return nerr; } Int test_1eq_nonneg () { using cedr::util::urand; using cedr::util::reldif; bool verbose = true; Int nerr = 0; Int n; static const Int N = 16; Real w[N], a[N], b, xlo[N], xhi[N], y[N], x_ls[N], x_caas[N], x1_ls[N], x1_caas[N]; for (n = 2; n <= 2; ++n) { const Int count = 20; for (Int trial = 0; trial < count; ++trial) { b = 0.5*n*urand(); for (Int i = 0; i < n; ++i) { w[i] = 0.1 + urand(); a[i] = 0.1 + urand(); xlo[i] = 0; xhi[i] = b/a[i]; y[i] = urand(); if (urand() > 0.8) y[i] *= -1; x1_caas[i] = urand() > 0.5 ? y[i] : -1; x1_ls[i] = urand() > 0.5 ? y[i] : -1; } solve_1eq_nonneg(n, a, b, y, x1_caas, w, Method::caas); caas(n, a, b, xlo, xhi, y, x_caas); solve_1eq_nonneg(n, a, b, y, x1_ls, w, Method::least_squares); solve_1eq_bc_qp(n, w, a, b, xlo, xhi, y, x_ls); const Real rd_caas = reldif(x_caas, x1_caas, 2); const Real rd_ls = reldif(x_ls, x1_ls, 2); if (rd_ls > 5e1*std::numeric_limits<Real>::epsilon() || rd_caas > 1e1*std::numeric_limits<Real>::epsilon()) { pr(puf(rd_ls) pu(rd_caas)); if (verbose) { using cedr::util::prarr; prarr("w", w, n); prarr("a", a, n); prarr("xhi", xhi, n); prarr("y", y, n); prarr("x_ls", x_ls, n); prarr("x1_ls", x1_ls, n); prarr("x_caas", x_caas, n); prarr("x1_caas", x1_caas, n); prc(b); Real mass = 0; for (Int i = 0; i < n; ++i) mass += a[i]*x_ls[i]; prc(mass); mass = 0; for (Int i = 0; i < n; ++i) mass += a[i]*x_ls[i]; prc(mass); mass = 0; for (Int i = 0; i < n; ++i) mass += a[i]*x_caas[i]; prc(mass); } ++nerr; } } } return nerr; } } // namespace test Int unittest () { Int nerr = 0; nerr += test::test_1eq_bc_qp(); nerr += test::test_1eq_nonneg(); return nerr; } } // namespace local } // namespace cedr //>> cedr_mpi.cpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. //#include "cedr_mpi.hpp" //#include "cedr_util.hpp" namespace cedr { namespace mpi { Parallel::Ptr make_parallel (MPI_Comm comm) { return std::make_shared<Parallel>(comm); } Int Parallel::size () const { int sz = 0; MPI_Comm_size(comm_, &sz); return sz; } Int Parallel::rank () const { int pid = 0; MPI_Comm_rank(comm_, &pid); return pid; } #ifdef COMPOSE_DEBUG_MPI Request::Request () : unfreed(0) {} Request::~Request () { if (unfreed) { std::stringstream ss; ss << "Request is being deleted with unfreed = " << unfreed; int fin; MPI_Finalized(&fin); if (fin) { ss << "\n"; std::cerr << ss.str(); } else { pr(ss.str()); } } } #endif template <> MPI_Datatype get_type<int>() { return MPI_INT; } template <> MPI_Datatype get_type<double>() { return MPI_DOUBLE; } template <> MPI_Datatype get_type<long>() { return MPI_LONG_INT; } int waitany (int count, Request* reqs, int* index, MPI_Status* stats) { #ifdef COMPOSE_DEBUG_MPI std::vector<MPI_Request> vreqs(count); for (int i = 0; i < count; ++i) vreqs[i] = reqs[i].request; const auto out = MPI_Waitany(count, vreqs.data(), index, stats ? stats : MPI_STATUS_IGNORE); for (int i = 0; i < count; ++i) reqs[i].request = vreqs[i]; reqs[*index].unfreed--; return out; #else return MPI_Waitany(count, reinterpret_cast<MPI_Request*>(reqs), index, stats ? stats : MPI_STATUS_IGNORE); #endif } int waitall (int count, Request* reqs, MPI_Status* stats) { #ifdef COMPOSE_DEBUG_MPI std::vector<MPI_Request> vreqs(count); for (int i = 0; i < count; ++i) vreqs[i] = reqs[i].request; const auto out = MPI_Waitall(count, vreqs.data(), stats ? stats : MPI_STATUS_IGNORE); for (int i = 0; i < count; ++i) { reqs[i].request = vreqs[i]; reqs[i].unfreed--; } return out; #else return MPI_Waitall(count, reinterpret_cast<MPI_Request*>(reqs), stats ? stats : MPI_STATUS_IGNORE); #endif } bool all_ok (const Parallel& p, bool im_ok) { int ok = im_ok, msg; all_reduce<int>(p, &ok, &msg, 1, MPI_LAND); return static_cast<bool>(msg); } } // namespace mpi } // namespace cedr //>> cedr_qlt.cpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. //#include "cedr_qlt.hpp" //#include "cedr_test_randomized.hpp" #include <sys/time.h> #include <cassert> #include <cmath> #include <set> #include <limits> #include <algorithm> namespace cedr { namespace qlt { class Timer { public: enum Op { tree, analyze, qltrun, qltrunl2r, qltrunr2l, snp, waitall, total, NTIMERS }; static inline void init () { #ifdef COMPOSE_QLT_TIME for (int i = 0; i < NTIMERS; ++i) { et_[i] = 0; cnt_[i] = 0; } #endif } static inline void reset (const Op op) { #ifdef COMPOSE_QLT_TIME et_[op] = 0; cnt_[op] = 0; #endif } static inline void start (const Op op) { #ifdef COMPOSE_QLT_TIME gettimeofday(&t_start_[op], 0); ++cnt_[op]; #endif } static inline void stop (const Op op) { #ifdef COMPOSE_QLT_TIME timeval t2; gettimeofday(&t2, 0); const timeval& t1 = t_start_[op]; static const double us = 1.0e6; et_[op] += (t2.tv_sec*us + t2.tv_usec - t1.tv_sec*us - t1.tv_usec)/us; #endif } # define tpr(op) do { \ printf("%-20s %10.3e %10.1f (%4d %10.3e)\n", \ #op, et_[op], 100*et_[op]/tot, cnt_[op], et_[op]/cnt_[op]); \ } while (0) static void print () { #ifdef COMPOSE_QLT_TIME const double tot = et_[total]; tpr(tree); tpr(analyze); tpr(qltrun); tpr(qltrunl2r); tpr(qltrunr2l); tpr(snp); tpr(waitall); printf("%-20s %10.3e %10.1f\n", "total", tot, 100.0); #endif } #undef tpr private: #ifdef COMPOSE_QLT_TIME static timeval t_start_[NTIMERS]; static double et_[NTIMERS]; static int cnt_[NTIMERS]; #endif }; #ifdef COMPOSE_QLT_TIME timeval Timer::t_start_[Timer::NTIMERS]; double Timer::et_[Timer::NTIMERS]; int Timer::cnt_[Timer::NTIMERS]; #endif namespace impl { void NodeSets::print (std::ostream& os) const { std::stringstream ss; if (levels.empty()) return; const Int myrank = node_h(levels[0].nodes[0])->rank; ss << "pid " << myrank << ":"; ss << " #levels " << levels.size(); for (size_t i = 0; i < levels.size(); ++i) { const auto& lvl = levels[i]; ss << "\n " << i << ": " << lvl.nodes.size(); std::set<Int> ps, ks; for (size_t j = 0; j < lvl.nodes.size(); ++j) { const auto n = node_h(lvl.nodes[j]); for (Int k = 0; k < n->nkids; ++k) if (node_h(n->kids[k])->rank != myrank) ks.insert(node_h(n->kids[k])->rank); if (n->parent >= 0 && node_h(n->parent)->rank != myrank) ps.insert(node_h(n->parent)->rank); } ss << " |"; for (const auto& e : ks) ss << " " << e; if ( ! lvl.kids.empty()) ss << " (" << lvl.kids.size() << ") |"; for (const auto& e : ps) ss << " " << e; if ( ! lvl.me.empty()) ss << " (" << lvl.me.size() << ")"; } ss << "\n"; os << ss.str(); } // Find tree depth, assign ranks to non-leaf nodes, and init 'reserved'. Int init_tree (const Int& my_rank, const tree::Node::Ptr& node, Int& id) { node->reserved = -1; Int depth = 0; for (Int i = 0; i < node->nkids; ++i) { cedr_assert(node.get() == node->kids[i]->parent); depth = std::max(depth, init_tree(my_rank, node->kids[i], id)); } if (node->nkids) { if (node->rank < 0) node->rank = node->kids[0]->rank; node->cellidx = id++; } else { cedr_throw_if(node->rank == my_rank && (node->cellidx < 0 || node->cellidx >= id), "cellidx is " << node->cellidx << " but should be between " << 0 << " and " << id); } return depth + 1; } void level_schedule_and_collect ( NodeSets& ns, const Int& my_rank, const tree::Node::Ptr& node, Int& level, bool& need_parent_ns_node) { cedr_assert(node->rank != -1); level = -1; bool make_ns_node = false; for (Int i = 0; i < node->nkids; ++i) { Int kid_level; bool kid_needs_ns_node; level_schedule_and_collect(ns, my_rank, node->kids[i], kid_level, kid_needs_ns_node); level = std::max(level, kid_level); if (kid_needs_ns_node) make_ns_node = true; } ++level; if (node->level >= 0) { // The caller built only partial trees and so must provide the // level. level = node->level; cedr_assert(level < static_cast<Int>(ns.levels.size())); } // Is parent node needed for isend? const bool node_is_owned = node->rank == my_rank; need_parent_ns_node = node_is_owned; if (node_is_owned || make_ns_node) { cedr_assert(node->reserved == -1); const auto ns_node_idx = ns.alloc(); // Levels hold only owned nodes. if (node_is_owned) ns.levels[level].nodes.push_back(ns_node_idx); node->reserved = ns_node_idx; NodeSets::Node* ns_node = ns.node_h(ns_node_idx); ns_node->rank = node->rank; if (node->nkids == 0) ns_node->id = node->cellidx; if (node_is_owned) { // If this node is owned, it needs to have information about all kids. ns_node->nkids = node->nkids; for (Int i = 0; i < node->nkids; ++i) { const auto& kid = node->kids[i]; if (kid->reserved == -1) { // This kid isn't owned by this rank. But need it for irecv. const auto ns_kid_idx = ns.alloc(); NodeSets::Node* ns_kid = ns.node_h(ns_kid_idx); kid->reserved = ns_kid_idx; ns_node = ns.node_h(ns_node_idx); ns_node->kids[i] = ns_kid_idx; cedr_assert(kid->rank != my_rank); ns_kid->rank = kid->rank; ns_kid->id = kid->cellidx; // The kid may have kids in the original tree, but in the tree pruned // according to rank, it does not. ns_kid->nkids = 0; } else { // This kid is owned by this rank, so fill in its parent pointer. NodeSets::Node* ns_kid = ns.node_h(kid->reserved); ns_node = ns.node_h(ns_node_idx); ns_node->kids[i] = kid->reserved; ns_kid->parent = ns_node_idx; } } } else { // This node is not owned. Update the owned kids with its parent. ns_node->nkids = 0; for (Int i = 0; i < node->nkids; ++i) { const auto& kid = node->kids[i]; if (kid->reserved >= 0 && kid->rank == my_rank) { const auto ns_kid_idx = kid->reserved; ns_node->kids[ns_node->nkids++] = ns_kid_idx; NodeSets::Node* ns_kid = ns.node_h(ns_kid_idx); ns_kid->parent = ns_node_idx; } } } } } void level_schedule_and_collect (NodeSets& ns, const Int& my_rank, const tree::Node::Ptr& tree) { Int iunused; bool bunused; level_schedule_and_collect(ns, my_rank, tree, iunused, bunused); } void consolidate (NodeSets& ns) { auto levels = ns.levels; ns.levels.clear(); for (const auto& level : levels) if ( ! level.nodes.empty()) ns.levels.push_back(level); } typedef std::pair<Int, NodeSets::Node*> RankNode; void init_offsets (const Int my_rank, std::vector<RankNode>& rns, std::vector<NodeSets::Level::MPIMetaData>& mmds, Int& offset) { // Set nodes on my rank to have rank -1 so that they sort first. for (auto& rn : rns) if (rn.first == my_rank) rn.first = -1; // Sort so that all comms with a given rank are contiguous. Stable sort so // that rns retains its order, in particular in the leaf node level. std::stable_sort(rns.begin(), rns.end()); // Collect nodes into groups by rank and set up comm metadata for each group. Int prev_rank = -1; for (auto& rn : rns) { const Int rank = rn.first; if (rank == -1) { if (rn.second->offset == -1) rn.second->offset = offset++; continue; } if (rank != prev_rank) { cedr_assert(rank > prev_rank); prev_rank = rank; mmds.push_back(NodeSets::Level::MPIMetaData()); auto& mmd = mmds.back(); mmd.rank = rank; mmd.offset = offset; mmd.size = 0; } ++mmds.back().size; rn.second->offset = offset++; } } // Set up comm data. Consolidate so that there is only one message between me // and another rank per level. Determine an offset for each node, to be // multiplied by data-size factors later, for use in data buffers. void init_comm (const Int my_rank, NodeSets& ns) { ns.nslots = 0; for (auto& lvl : ns.levels) { Int nkids = 0; for (const auto& idx : lvl.nodes) { const auto n = ns.node_h(idx); nkids += n->nkids; } std::vector<RankNode> me(lvl.nodes.size()), kids(nkids); for (size_t i = 0, mi = 0, ki = 0; i < lvl.nodes.size(); ++i) { const auto n = ns.node_h(lvl.nodes[i]); me[mi].first = n->parent >= 0 ? ns.node_h(n->parent)->rank : my_rank; me[mi].second = const_cast<NodeSets::Node*>(n); ++mi; for (Int k = 0; k < n->nkids; ++k) { kids[ki].first = ns.node_h(n->kids[k])->rank; kids[ki].second = ns.node_h(n->kids[k]); ++ki; } } init_offsets(my_rank, me, lvl.me, ns.nslots); lvl.me_send_req.resize(lvl.me.size()); lvl.me_recv_req.resize(lvl.me.size()); init_offsets(my_rank, kids, lvl.kids, ns.nslots); lvl.kids_req.resize(lvl.kids.size()); } } // Analyze the tree to extract levels. Levels are run from 0 to #level - 1. Each // level has nodes whose corresponding operations depend on only nodes in // lower-indexed levels. This mechanism prevents deadlock in the general case of // multiple cells per rank, with multiple ranks appearing in a subtree other // than the root. // In addition, the set of nodes collected into levels are just those owned by // this rank, and those with which owned nodes must communicate. // Once this function is done, the tree can be deleted. NodeSets::ConstPtr analyze (const Parallel::Ptr& p, const Int& ncells, const tree::Node::Ptr& tree) { const auto nodesets = std::make_shared<NodeSets>(); cedr_assert( ! tree->parent); Int id = ncells; Int depth = init_tree(p->rank(), tree, id); if (tree->level >= 0) { // If level is provided, don't trust depth from init_tree. Partial trees can // make depth too small. depth = tree->level + 1; } nodesets->levels.resize(depth); level_schedule_and_collect(*nodesets, p->rank(), tree); consolidate(*nodesets); init_comm(p->rank(), *nodesets); return nodesets; } // Check that the offsets are self consistent. Int check_comm (const NodeSets& ns) { Int nerr = 0; std::vector<Int> offsets(ns.nslots, 0); for (const auto& lvl : ns.levels) for (const auto& idx : lvl.nodes) { const auto n = ns.node_h(idx); cedr_assert(n->offset < ns.nslots); ++offsets[n->offset]; for (Int i = 0; i < n->nkids; ++i) { const auto kid = ns.node_h(n->kids[i]); if (kid->rank != n->rank) ++offsets[kid->offset]; } } for (const auto& e : offsets) if (e != 1) ++nerr; return nerr; } // Check that there are the correct number of leaf nodes, and that their offsets // all come first and are ordered the same as ns->levels[0]->nodes. Int check_leaf_nodes (const Parallel::Ptr& p, const NodeSets& ns, const Int ncells) { Int nerr = 0; cedr_assert( ! ns.levels.empty()); cedr_assert( ! ns.levels[0].nodes.empty()); Int my_nleaves = 0; for (const auto& idx : ns.levels[0].nodes) { const auto n = ns.node_h(idx); cedr_assert( ! n->nkids); ++my_nleaves; } for (const auto& idx : ns.levels[0].nodes) { const auto n = ns.node_h(idx); cedr_assert(n->offset < my_nleaves); cedr_assert(n->id < ncells); } Int glbl_nleaves = 0; mpi::all_reduce(*p, &my_nleaves, &glbl_nleaves, 1, MPI_SUM); if (glbl_nleaves != ncells) ++nerr; return nerr; } // Sum cellidx using the QLT comm pattern. Int test_comm_pattern (const Parallel::Ptr& p, const NodeSets& ns, const Int ncells) { Int nerr = 0; // Rank-wide data buffer. std::vector<Int> data(ns.nslots); // Sum this rank's cellidxs. for (const auto& idx : ns.levels[0].nodes) { const auto n = ns.node_h(idx); data[n->offset] = n->id; } // Leaves to root. for (size_t il = 0; il < ns.levels.size(); ++il) { auto& lvl = ns.levels[il]; // Set up receives. for (size_t i = 0; i < lvl.kids.size(); ++i) { const auto& mmd = lvl.kids[i]; mpi::irecv(*p, &data[mmd.offset], mmd.size, mmd.rank, NodeSets::mpitag, &lvl.kids_req[i]); } mpi::waitall(lvl.kids_req.size(), lvl.kids_req.data()); // Combine kids' data. for (const auto& idx : lvl.nodes) { const auto n = ns.node_h(idx); if ( ! n->nkids) continue; data[n->offset] = 0; for (Int i = 0; i < n->nkids; ++i) data[n->offset] += data[ns.node_h(n->kids[i])->offset]; } // Send to parents. for (size_t i = 0; i < lvl.me.size(); ++i) { const auto& mmd = lvl.me[i]; mpi::isend(*p, &data[mmd.offset], mmd.size, mmd.rank, NodeSets::mpitag); } } // Root to leaves. for (size_t il = ns.levels.size(); il > 0; --il) { auto& lvl = ns.levels[il-1]; // Get the global sum from parent. for (size_t i = 0; i < lvl.me.size(); ++i) { const auto& mmd = lvl.me[i]; mpi::irecv(*p, &data[mmd.offset], mmd.size, mmd.rank, NodeSets::mpitag, &lvl.me_recv_req[i]); } mpi::waitall(lvl.me_recv_req.size(), lvl.me_recv_req.data()); // Pass to kids. for (const auto& idx : lvl.nodes) { const auto n = ns.node_h(idx); if ( ! n->nkids) continue; for (Int i = 0; i < n->nkids; ++i) data[ns.node_h(n->kids[i])->offset] = data[n->offset]; } // Send. for (size_t i = 0; i < lvl.kids.size(); ++i) { const auto& mmd = lvl.kids[i]; mpi::isend(*p, &data[mmd.offset], mmd.size, mmd.rank, NodeSets::mpitag); } } { // Check that all leaf nodes have the right number. const Int desired_sum = (ncells*(ncells - 1)) / 2; for (const auto& idx : ns.levels[0].nodes) { const auto n = ns.node_h(idx); if (data[n->offset] != desired_sum) ++nerr; } if (false && p->amroot()) { std::cout << " " << data[ns.node_h(ns.levels[0].nodes[0])->offset]; std::cout.flush(); } } return nerr; } // Unit tests for NodeSets. Int unittest (const Parallel::Ptr& p, const NodeSets::ConstPtr& ns, const Int ncells) { Int nerr = 0, ne; ne = check_comm(*ns); if (ne && p->amroot()) pr("check_comm failed"); nerr += ne; ne = check_leaf_nodes(p, *ns, ncells); if (ne && p->amroot()) pr("check_leaf_nodes failed"); nerr += ne; for (Int trial = 0; trial < 11; ++trial) { ne = test_comm_pattern(p, *ns, ncells); if (ne && p->amroot()) pr("test_comm_pattern failed for trial" pu(trial)); nerr += ne; } return nerr; } } // namespace impl template <typename ES> void QLT<ES>::init (const std::string& name, IntList& d, typename IntList::HostMirror& h, size_t n) { d = IntList("QLT " + name, n); h = Kokkos::create_mirror_view(d); } template <typename ES> int QLT<ES>::MetaData::get_problem_type_idx (const int& mask) { switch (mask) { case CPT::s: case CPT::st: return 0; case CPT::cs: case CPT::cst: return 1; case CPT::t: return 2; case CPT::ct: return 3; case CPT::nn: return 4; case CPT::cnn: return 5; default: cedr_kernel_throw_if(true, "Invalid problem type."); return -1; } } template <typename ES> int QLT<ES>::MetaData::get_problem_type_r2l_bulk_size (const int& mask) { if (mask & ProblemType::shapepreserve) return 1; return 3; } template <typename ES> void QLT<ES>::MetaData::init (const MetaDataBuilder& mdb) { const Int ntracers = mdb.trcr2prob.size(); Me::init("trcr2prob", a_d_.trcr2prob, a_h_.trcr2prob, ntracers); std::copy(mdb.trcr2prob.begin(), mdb.trcr2prob.end(), a_h_.trcr2prob.data()); Kokkos::deep_copy(a_d_.trcr2prob, a_h_.trcr2prob); Me::init("bidx2trcr", a_d_.bidx2trcr, a_h_.bidx2trcr, ntracers); Me::init("trcr2bl2r", a_d_.trcr2bl2r, a_h_.trcr2bl2r, ntracers); Me::init("trcr2br2l", a_d_.trcr2br2l, a_h_.trcr2br2l, ntracers); a_h_.prob2trcrptr[0] = 0; a_h_.prob2bl2r[0] = 1; // rho is at 0. a_h_.prob2br2l[0] = 0; for (Int pi = 0; pi < nprobtypes; ++pi) { a_h_.prob2trcrptr[pi+1] = a_h_.prob2trcrptr[pi]; const Int l2rbulksz = get_problem_type_l2r_bulk_size(get_problem_type(pi)); const Int r2lbulksz = get_problem_type_r2l_bulk_size(get_problem_type(pi)); for (Int ti = 0; ti < ntracers; ++ti) { const auto problem_type = a_h_.trcr2prob[ti]; if (problem_type != get_problem_type(pi)) continue; const auto tcnt = a_h_.prob2trcrptr[pi+1] - a_h_.prob2trcrptr[pi]; a_h_.trcr2bl2r[ti] = a_h_.prob2bl2r[pi] + tcnt*l2rbulksz; a_h_.trcr2br2l[ti] = a_h_.prob2br2l[pi] + tcnt*r2lbulksz; a_h_.bidx2trcr[a_h_.prob2trcrptr[pi+1]++] = ti; } Int ni = a_h_.prob2trcrptr[pi+1] - a_h_.prob2trcrptr[pi]; a_h_.prob2bl2r[pi+1] = a_h_.prob2bl2r[pi] + ni*l2rbulksz; a_h_.prob2br2l[pi+1] = a_h_.prob2br2l[pi] + ni*r2lbulksz; } Kokkos::deep_copy(a_d_.bidx2trcr, a_h_.bidx2trcr); Kokkos::deep_copy(a_d_.trcr2bl2r, a_h_.trcr2bl2r); Kokkos::deep_copy(a_d_.trcr2br2l, a_h_.trcr2br2l); Me::init("trcr2bidx", a_d_.trcr2bidx, a_h_.trcr2bidx, ntracers); for (Int ti = 0; ti < ntracers; ++ti) a_h_.trcr2bidx(a_h_.bidx2trcr(ti)) = ti; Kokkos::deep_copy(a_d_.trcr2bidx, a_h_.trcr2bidx); a_h = a_h_; // Won't default construct Unmanaged, so have to do pointer stuff and raw // array copy explicitly. a_d.trcr2prob = a_d_.trcr2prob; a_d.bidx2trcr = a_d_.bidx2trcr; a_d.trcr2bidx = a_d_.trcr2bidx; a_d.trcr2bl2r = a_d_.trcr2bl2r; a_d.trcr2br2l = a_d_.trcr2br2l; std::copy(a_h_.prob2trcrptr, a_h_.prob2trcrptr + nprobtypes + 1, a_d.prob2trcrptr); std::copy(a_h_.prob2bl2r, a_h_.prob2bl2r + nprobtypes + 1, a_d.prob2bl2r); std::copy(a_h_.prob2br2l, a_h_.prob2br2l + nprobtypes + 1, a_d.prob2br2l); cedr_assert(a_d.prob2trcrptr[nprobtypes] == ntracers); } template <typename ES> void QLT<ES>::BulkData::init (const size_t& l2r_sz, const size_t& r2l_sz) { l2r_data_ = RealList("QLT l2r_data", l2r_sz); r2l_data_ = RealList("QLT r2l_data", r2l_sz); l2r_data = l2r_data_; r2l_data = r2l_data_; inited_ = true; } template <typename ES> void QLT<ES>::BulkData::init (Real* buf1, const size_t& l2r_sz, Real* buf2, const size_t& r2l_sz) { l2r_data_ = RealList(buf1, l2r_sz); r2l_data_ = RealList(buf2, r2l_sz); l2r_data = l2r_data_; r2l_data = r2l_data_; inited_ = true; } template <typename ES> void init_device_data (const impl::NodeSets& ns, impl::NodeSetsHostData& h, impl::NodeSetsDeviceData<ES>& d) { typedef impl::NodeSetsDeviceData<ES> NSDD; d.node = typename NSDD::NodeList("NSDD::node", ns.nnode()); h.node = Kokkos::create_mirror_view(d.node); d.lvlptr = typename NSDD::IntList("NSDD::lvlptr", ns.levels.size() + 1); h.lvlptr = Kokkos::create_mirror_view(d.lvlptr); Int nnode = 0; for (const auto& lvl : ns.levels) nnode += lvl.nodes.size(); d.lvl = typename NSDD::IntList("NSDD::lvl", nnode); h.lvl = Kokkos::create_mirror_view(d.lvl); h.lvlptr(0) = 0; for (size_t il = 0; il < ns.levels.size(); ++il) { const auto& level = ns.levels[il]; h.lvlptr(il+1) = h.lvlptr(il) + level.nodes.size(); for (Int os = h.lvlptr(il), i = 0; i < h.lvlptr(il+1) - os; ++i) h.lvl(os+i) = level.nodes[i]; nnode += level.nodes.size(); } for (Int i = 0; i < ns.nnode(); ++i) h.node(i) = *ns.node_h(i); Kokkos::deep_copy(d.node, h.node); Kokkos::deep_copy(d.lvl, h.lvl); Kokkos::deep_copy(d.lvlptr, h.lvlptr); } template <typename ES> void QLT<ES>::init (const Parallel::Ptr& p, const Int& ncells, const tree::Node::Ptr& tree) { p_ = p; Timer::start(Timer::analyze); ns_ = impl::analyze(p, ncells, tree); nshd_ = std::make_shared<impl::NodeSetsHostData>(); nsdd_ = std::make_shared<impl::NodeSetsDeviceData<ES> >(); init_device_data(*ns_, *nshd_, *nsdd_); init_ordinals(); Timer::stop(Timer::analyze); mdb_ = std::make_shared<MetaDataBuilder>(); } template <typename ES> void QLT<ES>::init_ordinals () { gci2lci_ = std::make_shared<Gci2LciMap>(); for (const auto& idx : ns_->levels[0].nodes) { const auto n = ns_->node_h(idx); (*gci2lci_)[n->id] = n->offset; } } template <typename ES> QLT<ES>::QLT (const Parallel::Ptr& p, const Int& ncells, const tree::Node::Ptr& tree, Options options) : CDR(options) { init(p, ncells, tree); cedr_throw_if(nlclcells() == 0, "QLT does not support 0 cells on a rank."); } template <typename ES> void QLT<ES>::print (std::ostream& os) const { ns_->print(os); } // Number of cells owned by this rank. template <typename ES> Int QLT<ES>::nlclcells () const { return ns_->levels[0].nodes.size(); } // Cells owned by this rank, in order of local numbering. Thus, // gci2lci(gcis[i]) == i. Ideally, the caller never actually calls gci2lci(), // and instead uses the information from get_owned_glblcells to determine // local cell indices. template <typename ES> void QLT<ES>::get_owned_glblcells (std::vector<Long>& gcis) const { gcis.resize(ns_->levels[0].nodes.size()); for (const auto& idx : ns_->levels[0].nodes) { const auto n = ns_->node_h(idx); gcis[n->offset] = n->id; } } // For global cell index cellidx, i.e., the globally unique ordinal associated // with a cell in the caller's tree, return this rank's local index for // it. This is not an efficient operation. template <typename ES> Int QLT<ES>::gci2lci (const Int& gci) const { const auto it = gci2lci_->find(gci); if (it == gci2lci_->end()) { pr(puf(gci)); std::vector<Long> gcis; get_owned_glblcells(gcis); mprarr(gcis); } cedr_throw_if(it == gci2lci_->end(), "gci " << gci << " not in gci2lci map."); return it->second; } template <typename ES> void QLT<ES>::declare_tracer (int problem_type, const Int& rhomidx) { cedr_throw_if( ! mdb_, "end_tracer_declarations was already called; " "it is an error to call declare_tracer now."); cedr_throw_if(rhomidx > 0, "rhomidx > 0 is not supported yet."); // For its exception side effect, and to get canonical problem type, since // some possible problem types map to the same canonical one: problem_type = md_.get_problem_type(md_.get_problem_type_idx(problem_type)); mdb_->trcr2prob.push_back(problem_type); } template <typename ES> void QLT<ES>::end_tracer_declarations () { md_.init(*mdb_); mdb_ = nullptr; } template <typename ES> void QLT<ES>::get_buffers_sizes (size_t& buf1, size_t& buf2) { const auto nslots = ns_->nslots; buf1 = md_.a_h.prob2bl2r[md_.nprobtypes]*nslots; buf2 = md_.a_h.prob2br2l[md_.nprobtypes]*nslots; } template <typename ES> void QLT<ES>::set_buffers (Real* buf1, Real* buf2) { size_t l2r_sz, r2l_sz; get_buffers_sizes(l2r_sz, r2l_sz); bd_.init(buf1, l2r_sz, buf2, r2l_sz); } template <typename ES> void QLT<ES>::finish_setup () { if (bd_.inited()) return; size_t l2r_sz, r2l_sz; get_buffers_sizes(l2r_sz, r2l_sz); bd_.init(l2r_sz, r2l_sz); } template <typename ES> int QLT<ES>::get_problem_type (const Int& tracer_idx) const { cedr_throw_if(tracer_idx < 0 || tracer_idx > md_.a_h.trcr2prob.extent_int(0), "tracer_idx is out of bounds: " << tracer_idx); return md_.a_h.trcr2prob[tracer_idx]; } template <typename ES> Int QLT<ES>::get_num_tracers () const { return md_.a_h.trcr2prob.size(); } template <typename ES> void QLT<ES> ::l2r_recv (const impl::NodeSets::Level& lvl, const Int& l2rndps) const { for (size_t i = 0; i < lvl.kids.size(); ++i) { const auto& mmd = lvl.kids[i]; mpi::irecv(*p_, bd_.l2r_data.data() + mmd.offset*l2rndps, mmd.size*l2rndps, mmd.rank, impl::NodeSets::mpitag, &lvl.kids_req[i]); } Timer::start(Timer::waitall); mpi::waitall(lvl.kids_req.size(), lvl.kids_req.data()); Timer::stop(Timer::waitall); } template <typename ES> void QLT<ES> ::l2r_combine_kid_data (const Int& lvlidx, const Int& l2rndps) const { if (cedr::impl::OnGpu<ES>::value) { const auto d = *nsdd_; const auto l2r_data = bd_.l2r_data; const auto a = md_.a_d; const Int ntracer = a.trcr2prob.size(); const Int nfield = ntracer + 1; const Int lvl_os = nshd_->lvlptr(lvlidx); const Int N = nfield*(nshd_->lvlptr(lvlidx+1) - lvl_os); const auto combine_kid_data = KOKKOS_LAMBDA (const Int& k) { const Int il = lvl_os + k / nfield; const Int fi = k % nfield; const auto node_idx = d.lvl(il); const auto& n = d.node(node_idx); if ( ! n.nkids) return; cedr_kernel_assert(n.nkids == 2); if (fi == 0) { // Total density. l2r_data(n.offset*l2rndps) = (l2r_data(d.node(n.kids[0]).offset*l2rndps) + l2r_data(d.node(n.kids[1]).offset*l2rndps)); } else { // Tracers. Order by bulk index for efficiency of memory access. const Int bi = fi - 1; // bulk index const Int ti = a.bidx2trcr(bi); // tracer (user) index const Int problem_type = a.trcr2prob(ti); const bool nonnegative = problem_type & ProblemType::nonnegative; const bool shapepreserve = problem_type & ProblemType::shapepreserve; const bool conserve = problem_type & ProblemType::conserve; const Int bdi = a.trcr2bl2r(ti); Real* const me = &l2r_data(n.offset*l2rndps + bdi); const auto& kid0 = d.node(n.kids[0]); const auto& kid1 = d.node(n.kids[1]); const Real* const k0 = &l2r_data(kid0.offset*l2rndps + bdi); const Real* const k1 = &l2r_data(kid1.offset*l2rndps + bdi); if (nonnegative) { me[0] = k0[0] + k1[0]; if (conserve) me[1] = k0[1] + k1[1]; } else { me[0] = shapepreserve ? k0[0] + k1[0] : cedr::impl::min(k0[0], k1[0]); me[1] = k0[1] + k1[1]; me[2] = shapepreserve ? k0[2] + k1[2] : cedr::impl::max(k0[2], k1[2]); if (conserve) me[3] = k0[3] + k1[3] ; } } }; Kokkos::parallel_for(Kokkos::RangePolicy<ES>(0, N), combine_kid_data); Kokkos::fence(); } else { const auto& lvl = ns_->levels[lvlidx]; const Int n_lvl_nodes = lvl.nodes.size(); #ifdef KOKKOS_ENABLE_OPENMP # pragma omp parallel for #endif for (Int ni = 0; ni < n_lvl_nodes; ++ni) { const auto lvlidx = lvl.nodes[ni]; const auto n = ns_->node_h(lvlidx); if ( ! n->nkids) continue; cedr_assert(n->nkids == 2); // Total density. bd_.l2r_data(n->offset*l2rndps) = (bd_.l2r_data(ns_->node_h(n->kids[0])->offset*l2rndps) + bd_.l2r_data(ns_->node_h(n->kids[1])->offset*l2rndps)); // Tracers. for (Int pti = 0; pti < md_.nprobtypes; ++pti) { const Int problem_type = md_.get_problem_type(pti); const bool nonnegative = problem_type & ProblemType::nonnegative; const bool shapepreserve = problem_type & ProblemType::shapepreserve; const bool conserve = problem_type & ProblemType::conserve; const Int bis = md_.a_d.prob2trcrptr[pti], bie = md_.a_d.prob2trcrptr[pti+1]; for (Int bi = bis; bi < bie; ++bi) { const Int bdi = md_.a_d.trcr2bl2r(md_.a_d.bidx2trcr(bi)); Real* const me = &bd_.l2r_data(n->offset*l2rndps + bdi); const auto kid0 = ns_->node_h(n->kids[0]); const auto kid1 = ns_->node_h(n->kids[1]); const Real* const k0 = &bd_.l2r_data(kid0->offset*l2rndps + bdi); const Real* const k1 = &bd_.l2r_data(kid1->offset*l2rndps + bdi); if (nonnegative) { me[0] = k0[0] + k1[0]; if (conserve) me[1] = k0[1] + k1[1]; } else { me[0] = shapepreserve ? k0[0] + k1[0] : cedr::impl::min(k0[0], k1[0]); me[1] = k0[1] + k1[1]; me[2] = shapepreserve ? k0[2] + k1[2] : cedr::impl::max(k0[2], k1[2]); if (conserve) me[3] = k0[3] + k1[3] ; } } } } } } template <typename ES> void QLT<ES> ::l2r_send_to_parents (const impl::NodeSets::Level& lvl, const Int& l2rndps) const { for (size_t i = 0; i < lvl.me.size(); ++i) { const auto& mmd = lvl.me[i]; mpi::isend(*p_, bd_.l2r_data.data() + mmd.offset*l2rndps, mmd.size*l2rndps, mmd.rank, impl::NodeSets::mpitag); } } template <typename ES> void QLT<ES> ::root_compute (const Int& l2rndps, const Int& r2lndps) const { if (ns_->levels.empty() || ns_->levels.back().nodes.size() != 1 || ns_->node_h(ns_->levels.back().nodes[0])->parent >= 0) return; const auto d = *nsdd_; const auto l2r_data = bd_.l2r_data; const auto r2l_data = bd_.r2l_data; const auto a = md_.a_d; const Int nlev = nshd_->lvlptr.size() - 1; const Int node_idx = nshd_->lvl(nshd_->lvlptr(nlev-1)); const Int ntracer = a.trcr2prob.size(); const auto compute = KOKKOS_LAMBDA (const Int& bi) { const auto& n = d.node(node_idx); const Int ti = a.bidx2trcr(bi); const Int problem_type = a.trcr2prob(ti); const Int l2rbdi = a.trcr2bl2r(a.bidx2trcr(bi)); const Int r2lbdi = a.trcr2br2l(a.bidx2trcr(bi)); // If QLT is enforcing global mass conservation, set root's r2l Qm value to // the l2r Qm_prev's sum; otherwise, copy the l2r Qm value to the r2l one. const Int os = (problem_type & ProblemType::conserve ? md_.get_problem_type_l2r_bulk_size(problem_type) - 1 : (problem_type & ProblemType::nonnegative ? 0 : 1)); r2l_data(n.offset*r2lndps + r2lbdi) = l2r_data(n.offset*l2rndps + l2rbdi + os); if ((problem_type & ProblemType::consistent) && ! (problem_type & ProblemType::shapepreserve)) { // Consistent but not shape preserving, so we're solving a dynamic range // preservation problem. We now know the global q_{min,max}. Start // propagating it leafward. r2l_data(n.offset*r2lndps + r2lbdi + 1) = l2r_data(n.offset*l2rndps + l2rbdi + 0); r2l_data(n.offset*r2lndps + r2lbdi + 2) = l2r_data(n.offset*l2rndps + l2rbdi + 2); } }; Kokkos::parallel_for(Kokkos::RangePolicy<ES>(0, ntracer), compute); Kokkos::fence(); } template <typename ES> void QLT<ES> ::r2l_recv (const impl::NodeSets::Level& lvl, const Int& r2lndps) const { for (size_t i = 0; i < lvl.me.size(); ++i) { const auto& mmd = lvl.me[i]; mpi::irecv(*p_, bd_.r2l_data.data() + mmd.offset*r2lndps, mmd.size*r2lndps, mmd.rank, impl::NodeSets::mpitag, &lvl.me_recv_req[i]); } Timer::start(Timer::waitall); mpi::waitall(lvl.me_recv_req.size(), lvl.me_recv_req.data()); Timer::stop(Timer::waitall); } template <typename Data> KOKKOS_INLINE_FUNCTION void r2l_solve_qp_set_q ( const Data& l2r_data, const Data& r2l_data, const Int& os, const Int& l2rndps, const Int& r2lndps, const Int& l2rbdi, const Int& r2lbdi, const Real& q_min, const Real& q_max) { l2r_data(os*l2rndps + l2rbdi + 0) = q_min; l2r_data(os*l2rndps + l2rbdi + 2) = q_max; r2l_data(os*r2lndps + r2lbdi + 1) = q_min; r2l_data(os*r2lndps + r2lbdi + 2) = q_max; } template <typename Data> KOKKOS_INLINE_FUNCTION void r2l_solve_qp_solve_node_problem ( const Data& l2r_data, const Data& r2l_data, const Int& problem_type, const impl::NodeSets::Node& n, const impl::NodeSets::Node& k0, const impl::NodeSets::Node& k1, const Int& l2rndps, const Int& r2lndps, const Int& l2rbdi, const Int& r2lbdi, const bool prefer_mass_con_to_bounds) { impl::solve_node_problem( problem_type, l2r_data( n.offset*l2rndps), &l2r_data( n.offset*l2rndps + l2rbdi), r2l_data( n.offset*r2lndps + r2lbdi), l2r_data(k0.offset*l2rndps), &l2r_data(k0.offset*l2rndps + l2rbdi), r2l_data(k0.offset*r2lndps + r2lbdi), l2r_data(k1.offset*l2rndps), &l2r_data(k1.offset*l2rndps + l2rbdi), r2l_data(k1.offset*r2lndps + r2lbdi), prefer_mass_con_to_bounds); } template <typename ES> void QLT<ES> ::r2l_solve_qp (const Int& lvlidx, const Int& l2rndps, const Int& r2lndps) const { Timer::start(Timer::snp); const bool prefer_mass_con_to_bounds = options_.prefer_numerical_mass_conservation_to_numerical_bounds; if (cedr::impl::OnGpu<ES>::value) { const auto d = *nsdd_; const auto l2r_data = bd_.l2r_data; const auto r2l_data = bd_.r2l_data; const auto a = md_.a_d; const Int ntracer = a.trcr2prob.size(); const Int lvl_os = nshd_->lvlptr(lvlidx); const Int N = ntracer*(nshd_->lvlptr(lvlidx+1) - lvl_os); const auto solve_qp = KOKKOS_LAMBDA (const Int& k) { const Int il = lvl_os + k / ntracer; const Int bi = k % ntracer; const auto node_idx = d.lvl(il); const auto& n = d.node(node_idx); if ( ! n.nkids) return; const Int ti = a.bidx2trcr(bi); const Int problem_type = a.trcr2prob(ti); const Int l2rbdi = a.trcr2bl2r(a.bidx2trcr(bi)); const Int r2lbdi = a.trcr2br2l(a.bidx2trcr(bi)); cedr_kernel_assert(n.nkids == 2); if ((problem_type & ProblemType::consistent) && ! (problem_type & ProblemType::shapepreserve)) { // Pass q_{min,max} info along. l2r data are updated for use in // solve_node_problem. r2l data are updated for use in isend. const Real q_min = r2l_data(n.offset*r2lndps + r2lbdi + 1); const Real q_max = r2l_data(n.offset*r2lndps + r2lbdi + 2); l2r_data(n.offset*l2rndps + l2rbdi + 0) = q_min; l2r_data(n.offset*l2rndps + l2rbdi + 2) = q_max; for (Int k = 0; k < 2; ++k) r2l_solve_qp_set_q(l2r_data, r2l_data, d.node(n.kids[k]).offset, l2rndps, r2lndps, l2rbdi, r2lbdi, q_min, q_max); } r2l_solve_qp_solve_node_problem( l2r_data, r2l_data, problem_type, n, d.node(n.kids[0]), d.node(n.kids[1]), l2rndps, r2lndps, l2rbdi, r2lbdi, prefer_mass_con_to_bounds); }; Kokkos::parallel_for(Kokkos::RangePolicy<ES>(0, N), solve_qp); Kokkos::fence(); } else { const auto& lvl = ns_->levels[lvlidx]; const Int n_lvl_nodes = lvl.nodes.size(); #ifdef KOKKOS_ENABLE_OPENMP # pragma omp parallel for #endif for (Int ni = 0; ni < n_lvl_nodes; ++ni) { const auto lvlidx = lvl.nodes[ni]; const auto n = ns_->node_h(lvlidx); if ( ! n->nkids) continue; for (Int pti = 0; pti < md_.nprobtypes; ++pti) { const Int problem_type = md_.get_problem_type(pti); const Int bis = md_.a_d.prob2trcrptr[pti], bie = md_.a_d.prob2trcrptr[pti+1]; for (Int bi = bis; bi < bie; ++bi) { const Int l2rbdi = md_.a_d.trcr2bl2r(md_.a_d.bidx2trcr(bi)); const Int r2lbdi = md_.a_d.trcr2br2l(md_.a_d.bidx2trcr(bi)); cedr_assert(n->nkids == 2); if ((problem_type & ProblemType::consistent) && ! (problem_type & ProblemType::shapepreserve)) { const Real q_min = bd_.r2l_data(n->offset*r2lndps + r2lbdi + 1); const Real q_max = bd_.r2l_data(n->offset*r2lndps + r2lbdi + 2); bd_.l2r_data(n->offset*l2rndps + l2rbdi + 0) = q_min; bd_.l2r_data(n->offset*l2rndps + l2rbdi + 2) = q_max; for (Int k = 0; k < 2; ++k) r2l_solve_qp_set_q(bd_.l2r_data, bd_.r2l_data, ns_->node_h(n->kids[k])->offset, l2rndps, r2lndps, l2rbdi, r2lbdi, q_min, q_max); } r2l_solve_qp_solve_node_problem( bd_.l2r_data, bd_.r2l_data, problem_type, *n, *ns_->node_h(n->kids[0]), *ns_->node_h(n->kids[1]), l2rndps, r2lndps, l2rbdi, r2lbdi, prefer_mass_con_to_bounds); } } } } Timer::stop(Timer::snp); } template <typename ES> void QLT<ES> ::r2l_send_to_kids (const impl::NodeSets::Level& lvl, const Int& r2lndps) const { for (size_t i = 0; i < lvl.kids.size(); ++i) { const auto& mmd = lvl.kids[i]; mpi::isend(*p_, bd_.r2l_data.data() + mmd.offset*r2lndps, mmd.size*r2lndps, mmd.rank, impl::NodeSets::mpitag); } } template <typename ES> void QLT<ES>::run () { cedr_assert(bd_.inited()); Timer::start(Timer::qltrunl2r); // Number of data per slot. const Int l2rndps = md_.a_h.prob2bl2r[md_.nprobtypes]; const Int r2lndps = md_.a_h.prob2br2l[md_.nprobtypes]; for (size_t il = 0; il < ns_->levels.size(); ++il) { auto& lvl = ns_->levels[il]; if (lvl.kids.size()) l2r_recv(lvl, l2rndps); l2r_combine_kid_data(il, l2rndps); if (lvl.me.size()) l2r_send_to_parents(lvl, l2rndps); } Timer::stop(Timer::qltrunl2r); Timer::start(Timer::qltrunr2l); root_compute(l2rndps, r2lndps); for (size_t il = ns_->levels.size(); il > 0; --il) { auto& lvl = ns_->levels[il-1]; if (lvl.me.size()) r2l_recv(lvl, r2lndps); r2l_solve_qp(il-1, l2rndps, r2lndps); if (lvl.kids.size()) r2l_send_to_kids(lvl, r2lndps); } Timer::stop(Timer::qltrunr2l); } namespace test { using namespace impl; class TestQLT : public cedr::test::TestRandomized { public: typedef QLT<Kokkos::DefaultExecutionSpace> QLTT; TestQLT (const Parallel::Ptr& p, const tree::Node::Ptr& tree, const Int& ncells, const bool external_memory, const bool verbose, CDR::Options options) : TestRandomized("QLT", p, ncells, verbose, options), qlt_(p, ncells, tree, options), tree_(tree), external_memory_(external_memory) { if (verbose) qlt_.print(std::cout); init(); } private: QLTT qlt_; tree::Node::Ptr tree_; bool external_memory_; typename QLTT::RealList buf1_, buf2_; CDR& get_cdr () override { return qlt_; } void init_numbering () override { init_numbering(tree_); } void init_numbering (const tree::Node::Ptr& node) { check(qlt_); // TestQLT doesn't actually care about a particular ordering, as there is no // geometry to the test problem. However, use *some* ordering to model what // a real problem must do. if ( ! node->nkids) { if (node->rank == p_->rank()) gcis_.push_back(node->cellidx); return; } for (Int i = 0; i < node->nkids; ++i) init_numbering(node->kids[i]); } static void check (const QLTT& qlt) { const Int n = qlt.nlclcells(); std::vector<Long> gcis; qlt.get_owned_glblcells(gcis); cedr_assert(static_cast<Int>(gcis.size()) == n); for (Int i = 0; i < n; ++i) cedr_assert(qlt.gci2lci(gcis[i]) == i); } void init_tracers () override { for (const auto& t : tracers_) qlt_.declare_tracer(t.problem_type, 0); qlt_.end_tracer_declarations(); if (external_memory_) { size_t l2r_sz, r2l_sz; qlt_.get_buffers_sizes(l2r_sz, r2l_sz); buf1_ = typename QLTT::RealList("buf1", l2r_sz); buf2_ = typename QLTT::RealList("buf2", r2l_sz); qlt_.set_buffers(buf1_.data(), buf2_.data()); } qlt_.finish_setup(); cedr_assert(qlt_.get_num_tracers() == static_cast<Int>(tracers_.size())); for (size_t i = 0; i < tracers_.size(); ++i) { const auto pt = qlt_.get_problem_type(i); cedr_assert((pt == ((tracers_[i].problem_type | ProblemType::consistent) & ~ProblemType::nonnegative)) || (pt == ((tracers_[i].problem_type | ProblemType::nonnegative) & ~ProblemType::consistent))); } } void run_impl (const Int trial) override { MPI_Barrier(p_->comm()); Timer::start(Timer::qltrun); qlt_.run(); MPI_Barrier(p_->comm()); Timer::stop(Timer::qltrun); if (trial == 0) { Timer::reset(Timer::qltrun); Timer::reset(Timer::qltrunl2r); Timer::reset(Timer::qltrunr2l); Timer::reset(Timer::waitall); Timer::reset(Timer::snp); } } }; // Test all QLT variations and situations. Int test_qlt (const Parallel::Ptr& p, const tree::Node::Ptr& tree, const Int& ncells, const Int nrepeat, const bool write, const bool external_memory, const bool prefer_mass_con_to_bounds, const bool verbose) { CDR::Options options; options.prefer_numerical_mass_conservation_to_numerical_bounds = prefer_mass_con_to_bounds; return TestQLT(p, tree, ncells, external_memory, verbose, options) .run<TestQLT::QLTT>(nrepeat, write); } } // namespace test // Tree for a 1-D periodic domain, for unit testing. namespace oned { struct Mesh { struct ParallelDecomp { enum Enum { // The obvious distribution of ranks: 1 rank takes exactly 1 contiguous // set of cell indices. contiguous, // For heavy-duty testing of QLT comm pattern, use a ridiculous assignment // of ranks to cell indices. This forces the QLT tree to communicate, // pack, and unpack in silly ways. pseudorandom }; }; Mesh (const Int nc, const Parallel::Ptr& p, const ParallelDecomp::Enum& parallel_decomp = ParallelDecomp::contiguous) { init(nc, p, parallel_decomp); } void init (const Int nc, const Parallel::Ptr& p, const ParallelDecomp::Enum& parallel_decomp) { nc_ = nc; nranks_ = p->size(); p_ = p; pd_ = parallel_decomp; cedr_throw_if(nranks_ > nc_, "#GIDs < #ranks is not supported."); } Int ncell () const { return nc_; } const Parallel::Ptr& parallel () const { return p_; } Int rank (const Int& ci) const { switch (pd_) { case ParallelDecomp::contiguous: return std::min(nranks_ - 1, ci / (nc_ / nranks_)); default: { const auto chunk = ci / nranks_; return (ci + chunk) % nranks_; } } } static Int unittest (const Parallel::Ptr& p) { const Mesh::ParallelDecomp::Enum dists[] = { Mesh::ParallelDecomp::pseudorandom, Mesh::ParallelDecomp::contiguous }; Int ne = 0; for (size_t id = 0; id < sizeof(dists)/sizeof(*dists); ++id) { Mesh m(std::max(42, 3*p->size()), p, dists[id]); const Int nc = m.ncell(); for (Int ci = 0; ci < nc; ++ci) if (m.rank(ci) < 0 || m.rank(ci) >= p->size()) ++ne; } return ne; } private: Int nc_, nranks_; Parallel::Ptr p_; ParallelDecomp::Enum pd_; }; tree::Node::Ptr make_tree (const Mesh& m, const Int cs, const Int ce, const tree::Node* parent, const bool imbalanced) { const Int cn = ce - cs, cn0 = ( imbalanced && cn > 2 ? cn/3 : cn/2 ); tree::Node::Ptr n = std::make_shared<tree::Node>(); n->parent = parent; if (cn == 1) { n->nkids = 0; n->rank = m.rank(cs); n->cellidx = cs; return n; } n->nkids = 2; n->kids[0] = make_tree(m, cs, cs + cn0, n.get(), imbalanced); n->kids[1] = make_tree(m, cs + cn0, ce, n.get(), imbalanced); return n; } tree::Node::Ptr make_tree (const Mesh& m, const bool imbalanced) { return make_tree(m, 0, m.ncell(), nullptr, imbalanced); } tree::Node::Ptr make_tree (const Parallel::Ptr& p, const Int& ncells, const bool imbalanced) { Mesh m(ncells, p); return make_tree(m, imbalanced); } namespace test { void mark_cells (const tree::Node::Ptr& node, std::vector<Int>& cells) { if ( ! node->nkids) { ++cells[node->cellidx]; return; } for (Int i = 0; i < node->nkids; ++i) mark_cells(node->kids[i], cells); } Int unittest (const Parallel::Ptr& p) { const Mesh::ParallelDecomp::Enum dists[] = { Mesh::ParallelDecomp::pseudorandom, Mesh::ParallelDecomp::contiguous }; Int ne = 0; for (size_t id = 0; id < sizeof(dists)/sizeof(*dists); ++id) for (bool imbalanced: {false, true}) { Mesh m(std::max(42, 3*p->size()), p, Mesh::ParallelDecomp::pseudorandom); tree::Node::Ptr tree = make_tree(m, imbalanced); std::vector<Int> cells(m.ncell(), 0); mark_cells(tree, cells); for (Int i = 0; i < m.ncell(); ++i) if (cells[i] != 1) ++ne; } return ne; } } // namespace test } // namespace oned tree::Node::Ptr tree::make_tree_over_1d_mesh (const Parallel::Ptr& p, const Int& ncells, const bool imbalanced) { return oned::make_tree(oned::Mesh(ncells, p), imbalanced); } namespace test { Int unittest_NodeSets (const Parallel::Ptr& p) { using Mesh = oned::Mesh; const Int szs[] = { p->size(), 3*p->size() }; const Mesh::ParallelDecomp::Enum dists[] = { Mesh::ParallelDecomp::pseudorandom, Mesh::ParallelDecomp::contiguous }; Int nerr = 0; for (size_t is = 0; is < sizeof(szs)/sizeof(*szs); ++is) for (size_t id = 0; id < sizeof(dists)/sizeof(*dists); ++id) for (bool imbalanced: {false, true}) { Mesh m(szs[is], p, dists[id]); tree::Node::Ptr tree = make_tree(m, imbalanced); impl::NodeSets::ConstPtr nodesets = impl::analyze(p, m.ncell(), tree); tree = nullptr; nerr += impl::unittest(p, nodesets, m.ncell()); } return nerr; } Int unittest_QLT (const Parallel::Ptr& p, const bool write_requested=false) { using Mesh = oned::Mesh; const Int szs[] = { p->size(), 2*p->size(), 7*p->size(), 21*p->size() }; const Mesh::ParallelDecomp::Enum dists[] = { Mesh::ParallelDecomp::contiguous, Mesh::ParallelDecomp::pseudorandom }; Int nerr = 0; for (size_t is = 0, islim = sizeof(szs)/sizeof(*szs); is < islim; ++is) { for (size_t id = 0, idlim = sizeof(dists)/sizeof(*dists); id < idlim; ++id) { for (bool imbalanced : {false, true}) { for (bool prefer_mass_con_to_bounds : {false, true}) { const auto external_memory = imbalanced; if (p->amroot()) { std::cout << " (" << szs[is] << ", " << id << ", " << imbalanced << ", " << prefer_mass_con_to_bounds << ")"; std::cout.flush(); } Mesh m(szs[is], p, dists[id]); tree::Node::Ptr tree = make_tree(m, imbalanced); const bool write = (write_requested && m.ncell() < 3000 && is == islim-1 && id == idlim-1); nerr += test::test_qlt(p, tree, m.ncell(), 1, write, external_memory, prefer_mass_con_to_bounds, false); } } } } return nerr; } Int run_unit_and_randomized_tests (const Parallel::Ptr& p, const Input& in) { Int nerr = 0; if (in.unittest) { Int ne; ne = oned::Mesh::unittest(p); if (ne && p->amroot()) std::cerr << "FAIL: Mesh::unittest()\n"; nerr += ne; ne = oned::test::unittest(p); if (ne && p->amroot()) std::cerr << "FAIL: oned::unittest_tree()\n"; nerr += ne; ne = unittest_NodeSets(p); if (ne && p->amroot()) std::cerr << "FAIL: oned::unittest_NodeSets()\n"; nerr += ne; ne = unittest_QLT(p, in.write); if (ne && p->amroot()) std::cerr << "FAIL: oned::unittest_QLT()\n"; nerr += ne; if (p->amroot()) std::cout << "\n"; } // Performance test. if (in.perftest && in.ncells > 0) { oned::Mesh m(in.ncells, p, (in.pseudorandom ? oned::Mesh::ParallelDecomp::pseudorandom : oned::Mesh::ParallelDecomp::contiguous)); Timer::init(); Timer::start(Timer::total); Timer::start(Timer::tree); tree::Node::Ptr tree = make_tree(m, false); Timer::stop(Timer::tree); test::test_qlt(p, tree, in.ncells, in.nrepeat, false, false, false, in.verbose); Timer::stop(Timer::total); if (p->amroot()) Timer::print(); } return nerr; } } // namespace test } // namespace qlt } // namespace cedr #ifdef KOKKOS_ENABLE_SERIAL template class cedr::qlt::QLT<Kokkos::Serial>; #endif #ifdef KOKKOS_ENABLE_OPENMP template class cedr::qlt::QLT<Kokkos::OpenMP>; #endif #ifdef KOKKOS_ENABLE_CUDA template class cedr::qlt::QLT<Kokkos::Cuda>; #endif #ifdef KOKKOS_ENABLE_THREADS template class cedr::qlt::QLT<Kokkos::Threads>; #endif //>> cedr_caas.cpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. //#include "cedr_caas.hpp" //#include "cedr_util.hpp" //#include "cedr_test_randomized.hpp" namespace Kokkos { struct Real2 { cedr::Real v[2]; KOKKOS_INLINE_FUNCTION Real2 () { v[0] = v[1] = 0; } KOKKOS_INLINE_FUNCTION void operator= (const Real2& s) { v[0] = s.v[0]; v[1] = s.v[1]; } KOKKOS_INLINE_FUNCTION void operator= (const volatile Real2& s) volatile { v[0] = s.v[0]; v[1] = s.v[1]; } KOKKOS_INLINE_FUNCTION Real2& operator+= (const Real2& o) { v[0] += o.v[0]; v[1] += o.v[1]; return *this; } }; template<> struct reduction_identity<Real2> { KOKKOS_INLINE_FUNCTION static Real2 sum() { return Real2(); } }; } // namespace Kokkos namespace cedr { namespace caas { template <typename ES> CAAS<ES>::CAAS (const mpi::Parallel::Ptr& p, const Int nlclcells, const typename UserAllReducer::Ptr& uar) : p_(p), user_reducer_(uar), nlclcells_(nlclcells), nrhomidxs_(0), need_conserve_(false), finished_setup_(false) { cedr_throw_if(nlclcells == 0, "CAAS does not support 0 cells on a rank."); tracer_decls_ = std::make_shared<std::vector<Decl> >(); } template <typename ES> void CAAS<ES>::declare_tracer(int problem_type, const Int& rhomidx) { cedr_throw_if( ! (problem_type & ProblemType::shapepreserve), "CAAS does not support ! shapepreserve yet."); cedr_throw_if(rhomidx > 0, "rhomidx > 0 is not supported yet."); tracer_decls_->push_back(Decl(problem_type, rhomidx)); if (problem_type & ProblemType::conserve) need_conserve_ = true; nrhomidxs_ = std::max(nrhomidxs_, rhomidx+1); } template <typename ES> void CAAS<ES>::end_tracer_declarations () { cedr_throw_if(tracer_decls_->size() == 0, "#tracers is 0."); cedr_throw_if(nrhomidxs_ == 0, "#rhomidxs is 0."); probs_ = IntList("CAAS probs", static_cast<Int>(tracer_decls_->size())); probs_h_ = Kokkos::create_mirror_view(probs_); //t2r_ = IntList("CAAS t2r", static_cast<Int>(tracer_decls_->size())); for (Int i = 0; i < probs_.extent_int(0); ++i) { probs_h_(i) = (*tracer_decls_)[i].probtype; //t2r_(i) = (*tracer_decls_)[i].rhomidx; } Kokkos::deep_copy(probs_, probs_h_); tracer_decls_ = nullptr; } template <typename ES> void CAAS<ES>::get_buffers_sizes (size_t& buf1, size_t& buf2, size_t& buf3) { const Int e = need_conserve_ ? 1 : 0; const auto nslots = 4*probs_.size(); buf1 = nlclcells_ * ((3+e)*probs_.size() + 1); cedr_assert( ! user_reducer_ || nlclcells_ % user_reducer_->n_accum_in_place() == 0); buf2 = nslots*(user_reducer_ ? (nlclcells_ / user_reducer_->n_accum_in_place()) : 1); buf3 = nslots; } template <typename ES> void CAAS<ES>::get_buffers_sizes (size_t& buf1, size_t& buf2) { size_t buf3; get_buffers_sizes(buf1, buf2, buf3); buf2 += buf3; } template <typename ES> void CAAS<ES>::set_buffers (Real* buf1, Real* buf2) { size_t buf1sz, buf2sz, buf3sz; get_buffers_sizes(buf1sz, buf2sz, buf3sz); d_ = RealList(buf1, buf1sz); send_ = RealList(buf2, buf2sz); recv_ = RealList(buf2 + buf2sz, buf3sz); } template <typename ES> void CAAS<ES>::finish_setup () { if (recv_.size() > 0) { finished_setup_ = true; return; } size_t buf1, buf2, buf3; get_buffers_sizes(buf1, buf2, buf3); // (rho, Qm, Qm_min, Qm_max, [Qm_prev]) d_ = RealList("CAAS data", buf1); // (e'Qm_clip, e'Qm, e'Qm_min, e'Qm_max, [e'Qm_prev]) send_ = RealList("CAAS send", buf2); recv_ = RealList("CAAS recv", buf3); finished_setup_ = true; } template <typename ES> int CAAS<ES>::get_problem_type (const Int& tracer_idx) const { cedr_assert(tracer_idx >= 0 && tracer_idx < probs_.extent_int(0)); return probs_h_[tracer_idx]; } template <typename ES> Int CAAS<ES>::get_num_tracers () const { return probs_.extent_int(0); } template <typename RealList, typename IntList> KOKKOS_INLINE_FUNCTION static void calc_Qm_scalars (const RealList& d, const IntList& probs, const Int& nt, const Int& nlclcells, const Int& k, const Int& os, const Int& i, Real& Qm_clip, Real& Qm_term) { const Real Qm = d(os+i); Qm_term = (probs(k) & ProblemType::conserve ? d(os + nlclcells*3*nt + i) /* Qm_prev */ : Qm); const Real Qm_min = d(os + nlclcells* nt + i); const Real Qm_max = d(os + nlclcells*2*nt + i); Qm_clip = cedr::impl::min(Qm_max, cedr::impl::max(Qm_min, Qm)); } template <typename Func> void homme_parallel_for (const Int& beg, const Int& end, const Func& f) { #ifdef HORIZ_OPENMP # pragma omp for #endif for (Int i = beg; i < end; ++i) f(i); } template <typename ES> void CAAS<ES>::reduce_locally () { const bool user_reduces = user_reducer_ != nullptr; ConstExceptGnu Int nt = probs_.size(), nlclcells = nlclcells_; const auto probs = probs_; const auto send = send_; const auto d = d_; if (user_reduces) { const Int n_accum_in_place = user_reducer_->n_accum_in_place(); const Int nlclaccum = nlclcells / n_accum_in_place; const auto calc_Qm_clip = KOKKOS_LAMBDA (const Int& j) { const auto k = j / nlclaccum; const auto bi = j % nlclaccum; const auto os = (k+1)*nlclcells; Real accum_clip = 0, accum_term = 0; for (Int ai = 0; ai < n_accum_in_place; ++ai) { const Int i = n_accum_in_place*bi + ai; Real Qm_clip, Qm_term; calc_Qm_scalars(d, probs, nt, nlclcells, k, os, i, Qm_clip, Qm_term); d(os + i) = Qm_clip; accum_clip += Qm_clip; accum_term += Qm_term; } send(nlclaccum* k + bi) = accum_clip; send(nlclaccum*(nt + k) + bi) = accum_term; }; homme_parallel_for(0, nt*nlclaccum, calc_Qm_clip); const auto set_Qm_minmax = KOKKOS_LAMBDA (const Int& j) { const auto k = 2*nt + j / nlclaccum; const auto bi = j % nlclaccum; const auto os = (k-nt+1)*nlclcells; Real accum_ext = 0; for (Int ai = 0; ai < n_accum_in_place; ++ai) { const Int i = n_accum_in_place*bi + ai; accum_ext += d(os + i); } send(nlclaccum*k + bi) = accum_ext; }; homme_parallel_for(0, 2*nt*nlclaccum, set_Qm_minmax); } else { using ESU = cedr::impl::ExeSpaceUtils<ES>; const auto calc_Qm_clip = KOKKOS_LAMBDA (const typename ESU::Member& t) { const auto k = t.league_rank(); const auto os = (k+1)*nlclcells; const auto reduce = [&] (const Int& i, Kokkos::Real2& accum) { Real Qm_clip, Qm_term; calc_Qm_scalars(d, probs, nt, nlclcells, k, os, i, Qm_clip, Qm_term); d(os+i) = Qm_clip; accum.v[0] += Qm_clip; accum.v[1] += Qm_term; }; Kokkos::Real2 accum; Kokkos::parallel_reduce(Kokkos::TeamThreadRange(t, nlclcells), reduce, Kokkos::Sum<Kokkos::Real2>(accum)); send( k) = accum.v[0]; send(nt + k) = accum.v[1]; }; Kokkos::parallel_for(ESU::get_default_team_policy(nt, nlclcells), calc_Qm_clip); const auto set_Qm_minmax = KOKKOS_LAMBDA (const typename ESU::Member& t) { const auto k = 2*nt + t.league_rank(); const auto os = (k-nt+1)*nlclcells; Real accum = 0; Kokkos::parallel_reduce(Kokkos::TeamThreadRange(t, nlclcells), [&] (const Int& i, Real& accum) { accum += d(os+i); }, Kokkos::Sum<Real>(accum)); send(k) = accum; }; Kokkos::parallel_for(ESU::get_default_team_policy(2*nt, nlclcells), set_Qm_minmax); } } template <typename ES> void CAAS<ES>::reduce_globally () { const int err = mpi::all_reduce(*p_, send_.data(), recv_.data(), send_.size(), MPI_SUM); cedr_throw_if(err != MPI_SUCCESS, "CAAS::reduce_globally MPI_Allreduce returned " << err); } template <typename ES> void CAAS<ES>::finish_locally () { using ESU = cedr::impl::ExeSpaceUtils<ES>; ConstExceptGnu Int nt = probs_.size(), nlclcells = nlclcells_; const auto recv = recv_; const auto d = d_; const auto adjust_Qm = KOKKOS_LAMBDA (const Int& k) { const auto os = (k+1)*nlclcells; const auto Qm_clip_sum = recv( k); const auto Qm_sum = recv(nt + k); const auto m = Qm_sum - Qm_clip_sum; if (m < 0) { const auto Qm_min_sum = recv(2*nt + k); auto fac = Qm_clip_sum - Qm_min_sum; if (fac > 0) { fac = m/fac; for (Int i = 0; i < nlclcells; ++i) { const auto Qm_min = d(os + nlclcells * nt + i); auto& Qm = d(os+i); Qm += fac*(Qm - Qm_min); Qm = impl::max(Qm_min, Qm); }; } } else if (m > 0) { const auto Qm_max_sum = recv(3*nt + k); auto fac = Qm_max_sum - Qm_clip_sum; if (fac > 0) { fac = m/fac; for (Int i = 0; i < nlclcells; ++i) { const auto Qm_max = d(os + nlclcells*2*nt + i); auto& Qm = d(os+i); Qm += fac*(Qm_max - Qm); Qm = impl::min(Qm_max, Qm); }; } } }; homme_parallel_for(0, nt, adjust_Qm); } template <typename ES> void CAAS<ES>::run () { cedr_assert(finished_setup_); reduce_locally(); const bool user_reduces = user_reducer_ != nullptr; if (user_reduces) (*user_reducer_)(*p_, send_.data(), recv_.data(), nlclcells_ / user_reducer_->n_accum_in_place(), recv_.size(), MPI_SUM); else reduce_globally(); finish_locally(); } namespace test { struct TestCAAS : public cedr::test::TestRandomized { typedef CAAS<Kokkos::DefaultExecutionSpace> CAAST; struct TestAllReducer : public CAAST::UserAllReducer { int operator() (const mpi::Parallel& p, Real* sendbuf, Real* rcvbuf, int nlcl, int count, MPI_Op op) const override { Kokkos::View<Real*> s(sendbuf, nlcl*count), r(rcvbuf, count); const auto s_h = Kokkos::create_mirror_view(s); Kokkos::deep_copy(s_h, s); const auto r_h = Kokkos::create_mirror_view(r); for (int i = 1; i < nlcl; ++i) s_h(0) += s_h(i); for (int k = 1; k < count; ++k) { s_h(k) = s_h(nlcl*k); for (int i = 1; i < nlcl; ++i) s_h(k) += s_h(nlcl*k + i); } const int err = mpi::all_reduce(p, s_h.data(), r_h.data(), count, op); Kokkos::deep_copy(r, r_h); return err; } }; TestCAAS (const mpi::Parallel::Ptr& p, const Int& ncells, const bool use_own_reducer, const bool external_memory, const bool verbose) : TestRandomized("CAAS", p, ncells, verbose), p_(p), external_memory_(external_memory) { const auto np = p->size(), rank = p->rank(); nlclcells_ = ncells / np; const Int todo = ncells - nlclcells_ * np; if (rank < todo) ++nlclcells_; caas_ = std::make_shared<CAAST>( p, nlclcells_, use_own_reducer ? std::make_shared<TestAllReducer>() : nullptr); init(); } CDR& get_cdr () override { return *caas_; } void init_numbering () override { const auto np = p_->size(), rank = p_->rank(); Int start = 0; for (Int lrank = 0; lrank < rank; ++lrank) start += get_nllclcells(ncells_, np, lrank); gcis_.resize(nlclcells_); for (Int i = 0; i < nlclcells_; ++i) gcis_[i] = start + i; } void init_tracers () override { // CAAS doesn't yet support everything, so remove a bunch of the tracers. std::vector<TestRandomized::Tracer> tracers; Int idx = 0; for (auto& t : tracers_) { if ( ! (t.problem_type & ProblemType::shapepreserve) || ! t.local_should_hold) continue; t.idx = idx++; tracers.push_back(t); caas_->declare_tracer(t.problem_type, 0); } tracers_ = tracers; caas_->end_tracer_declarations(); if (external_memory_) { size_t l2r_sz, r2l_sz; caas_->get_buffers_sizes(l2r_sz, r2l_sz); buf1_ = typename CAAST::RealList("buf1", l2r_sz); buf2_ = typename CAAST::RealList("buf2", r2l_sz); caas_->set_buffers(buf1_.data(), buf2_.data()); } caas_->finish_setup(); } void run_impl (const Int trial) override { caas_->run(); } private: mpi::Parallel::Ptr p_; bool external_memory_; Int nlclcells_; CAAST::Ptr caas_; typename CAAST::RealList buf1_, buf2_; static Int get_nllclcells (const Int& ncells, const Int& np, const Int& rank) { Int nlclcells = ncells / np; const Int todo = ncells - nlclcells * np; if (rank < todo) ++nlclcells; return nlclcells; } }; Int unittest (const mpi::Parallel::Ptr& p) { const auto np = p->size(); Int nerr = 0; for (Int nlclcells : {1, 2, 4, 11}) { Long ncells = np*nlclcells; if (ncells > np) ncells -= np/2; for (const bool own_reducer : {false, true}) for (const bool external_memory : {false, true}) nerr += TestCAAS(p, ncells, own_reducer, external_memory, false) .run<TestCAAS::CAAST>(1, false); } return nerr; } } // namespace test } // namespace caas } // namespace cedr #ifdef KOKKOS_ENABLE_SERIAL template class cedr::caas::CAAS<Kokkos::Serial>; #endif #ifdef KOKKOS_ENABLE_OPENMP template class cedr::caas::CAAS<Kokkos::OpenMP>; #endif #ifdef KOKKOS_ENABLE_CUDA template class cedr::caas::CAAS<Kokkos::Cuda>; #endif #ifdef KOKKOS_ENABLE_THREADS template class cedr::caas::CAAS<Kokkos::Threads>; #endif //>> cedr_test_randomized.cpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. //#include "cedr_test_randomized.hpp" namespace cedr { namespace test { std::string TestRandomized::Tracer::str () const { std::stringstream ss; ss << "(ti " << idx; if (problem_type & PT::conserve) ss << " c"; if (problem_type & PT::shapepreserve) ss << " s"; if (problem_type & PT::consistent) ss << " t"; if (problem_type & PT::nonnegative) ss << " nn"; ss << " pt " << perturbation_type << " ssh " << safe_should_hold << " lsh " << local_should_hold << ")"; return ss.str(); } TestRandomized::Writer::~Writer () { if ( ! fh) return; fprintf(fh.get(), " return s\n"); } void TestRandomized::init_tracers_vector () { typedef Tracer::PT PT; static const Int pts[] = { PT::conserve | PT::shapepreserve | PT::consistent, PT::shapepreserve, PT::conserve | PT::consistent, PT::consistent, PT::nonnegative, PT::nonnegative | PT::conserve }; Int tracer_idx = 0; for (Int perturb = 0; perturb < 6; ++perturb) for (size_t ti = 0; ti < sizeof(pts)/sizeof(*pts); ++ti) { Tracer t; t.problem_type = pts[ti]; const bool shapepreserve = t.problem_type & PT::shapepreserve; const bool nonnegative = t.problem_type & PT::nonnegative; t.idx = tracer_idx++; t.perturbation_type = perturb; t.safe_should_hold = true; t.no_change_should_hold = perturb == 0; t.local_should_hold = perturb < 4 && (shapepreserve || nonnegative); t.write = perturb == 2 && ti == 2; tracers_.push_back(t); } } static Real urand () { return rand() / ((Real) RAND_MAX + 1.0); } void TestRandomized::generate_rho (Values& v) { auto r = v.rhom(); const Int n = v.ncells(); for (Int i = 0; i < n; ++i) r[i] = 0.5*(1 + urand()); } void TestRandomized::generate_Q (const Tracer& t, Values& v) { Real* rhom = v.rhom(), * Qm_min = v.Qm_min(t.idx), * Qm = v.Qm(t.idx), * Qm_max = v.Qm_max(t.idx), * Qm_prev = v.Qm_prev(t.idx); const Int n = v.ncells(); const bool nonneg_only = t.problem_type & ProblemType::nonnegative; for (Int i = 0; i < n; ++i) { if (nonneg_only) { // Make sure the generated Qm is globally positive. Qm[i] = (t.no_change_should_hold ? urand() : ((i % 2 == 0) ? 0.75 : -0.75) + urand()); // Qm_min,max are unused in QLT, but need them to be set here for // bookkeeping in check(). Qm_min[i] = 0; Qm_max[i] = 10; } else { // The typical use case has 0 <= q_min <= q, but test with general sign. const Real q_min = -0.75 + urand(), q_max = q_min + urand(), q = q_min + (q_max - q_min)*urand(); // Check correctness up to FP. cedr_assert(q_min <= q && q <= q_max); Qm_min[i] = q_min*rhom[i]; Qm_max[i] = q_max*rhom[i]; // Protect against FP error. Qm[i] = std::max<Real>(Qm_min[i], std::min(Qm_max[i], q*rhom[i])); } // Set previous Qm to the current unperturbed value. Qm_prev[i] = Qm[i]; } } static void gen_rand_perm (const size_t n, std::vector<Int>& p) { p.resize(n); for (size_t i = 0; i < n; ++i) p[i] = i; for (size_t i = 0; i < n; ++i) { const int j = urand()*n, k = urand()*n; std::swap(p[j], p[k]); } } // Permuting the Qm array, even just on a rank as long as there is > 1 cell, // produces a problem likely requiring considerable reconstruction, which // reconstruction assuredly satisfies the properties. But because this is a // local operation only, it doesn't test the 1 cell/rank case. void TestRandomized::permute_Q (const Tracer& t, Values& v) { Real* const Qm = v.Qm(t.idx); const Int N = v.ncells(); std::vector<Int> p; gen_rand_perm(N, p); std::vector<Real> Qm_orig(N); std::copy(Qm, Qm + N, Qm_orig.begin()); for (Int i = 0; i < N; ++i) Qm[i] = Qm_orig[p[i]]; } void TestRandomized ::add_const_to_Q (const Tracer& t, Values& v, // Move 0 < alpha <= 1 of the way to the QLT or safety // feasibility bound. const Real& alpha, // Whether the modification should be done in a // mass-conserving way. const bool conserve_mass, // Only safety problem is feasible. const bool safety_problem) { // Some of these reductions aren't used at present. Might add more test // options later that use them. Real rhom, Qm, Qm_max; { Real Qm_sum_lcl[3] = {0}; for (Int i = 0; i < v.ncells(); ++i) { Qm_sum_lcl[0] += v.rhom()[i]; Qm_sum_lcl[1] += v.Qm(t.idx)[i]; Qm_sum_lcl[2] += v.Qm_max(t.idx)[i]; } Real Qm_sum_gbl[3] = {0}; mpi::all_reduce(*p_, Qm_sum_lcl, Qm_sum_gbl, 3, MPI_SUM); rhom = Qm_sum_gbl[0]; Qm = Qm_sum_gbl[1]; Qm_max = Qm_sum_gbl[2]; } Real Qm_max_safety = 0; if (safety_problem && v.ncells()) { Real q_safety_lcl = v.Qm_max(t.idx)[0] / v.rhom()[0]; for (Int i = 1; i < v.ncells(); ++i) q_safety_lcl = std::max(q_safety_lcl, v.Qm_max(t.idx)[i] / v.rhom()[i]); Real q_safety_gbl = 0; mpi::all_reduce(*p_, &q_safety_lcl, &q_safety_gbl, 1, MPI_MAX); Qm_max_safety = q_safety_gbl*rhom; } const Real dQm = safety_problem ? ((Qm_max - Qm) + alpha * (Qm_max_safety - Qm_max)) / ncells_ : alpha * (Qm_max - Qm) / ncells_; for (Int i = 0; i < v.ncells(); ++i) v.Qm(t.idx)[i] += dQm; // Now permute Qm so that it's a little more interesting. permute_Q(t, v); // Adjust Qm_prev. Qm_prev is used to test the PT::conserve case, and also // simply to record the correct total mass. The modification above modified // Q's total mass. If conserve_mass, then Qm_prev needs to be made to sum to // the same new mass. If ! conserve_mass, we want Qm_prev to be modified in // an interesting way, so that PT::conserve doesn't trivially undo the mod // that was made above when the root fixes the mass discrepancy. const Real relax = 0.9, dQm_prev = (conserve_mass ? dQm : (safety_problem ? ((Qm_max - Qm) + relax*alpha * (Qm_max_safety - Qm_max)) / ncells_ : relax*alpha * (Qm_max - Qm) / ncells_)); for (Int i = 0; i < v.ncells(); ++i) v.Qm_prev(t.idx)[i] += dQm_prev; } void TestRandomized::perturb_Q (const Tracer& t, Values& v) { // QLT is naturally mass conserving. But if QLT isn't being asked to impose // mass conservation, then the caller better have a conservative // method. Here, we model that by saying that Qm_prev and Qm should sum to // the same mass. const bool cm = ! (t.problem_type & Tracer::PT::conserve); // For the edge cases, we cannot be exactly on the edge and still expect the // q-limit checks to pass to machine precision. Thus, back away from the // edge by an amount that bounds the error in the global mass due to FP, // assuming each cell's mass is O(1). const Real edg = 1 - ncells_*std::numeric_limits<Real>::epsilon(); switch (t.perturbation_type) { case 0: // Do nothing, to test that QLT doesn't make any changes if none is // needed. break; case 1: permute_Q(t, v); break; case 2: add_const_to_Q(t, v, 0.5, cm, false); break; case 3: add_const_to_Q(t, v, edg, cm, false); break; case 4: add_const_to_Q(t, v, 0.5, cm, true ); break; case 5: add_const_to_Q(t, v, edg, cm, true ); break; } } std::string TestRandomized::get_tracer_name (const Tracer& t) { std::stringstream ss; ss << "t" << t.idx; return ss.str(); } void TestRandomized::init_writer () { if (p_->amroot()) { w_ = std::make_shared<Writer>(); w_->fh = std::unique_ptr<FILE, cedr::util::FILECloser>(fopen("out_QLT.py", "w")); int n = gcis_.size(); w_->ngcis.resize(p_->size()); mpi::gather(*p_, &n, 1, w_->ngcis.data(), 1, p_->root()); w_->displs.resize(p_->size() + 1); w_->displs[0] = 0; for (size_t i = 0; i < w_->ngcis.size(); ++i) w_->displs[i+1] = w_->displs[i] + w_->ngcis[i]; cedr_assert(w_->displs.back() == ncells_); w_->gcis.resize(ncells_); mpi::gatherv(*p_, gcis_.data(), gcis_.size(), w_->gcis.data(), w_->ngcis.data(), w_->displs.data(), p_->root()); } else { int n = gcis_.size(); mpi::gather(*p_, &n, 1, static_cast<int*>(nullptr), 0, p_->root()); Long* Lnull = nullptr; const int* inull = nullptr; mpi::gatherv(*p_, gcis_.data(), gcis_.size(), Lnull, inull, inull, p_->root()); } write_inited_ = true; } void TestRandomized ::gather_field (const Real* Qm_lcl, std::vector<Real>& Qm_gbl, std::vector<Real>& wrk) { if (p_->amroot()) { Qm_gbl.resize(ncells_); wrk.resize(ncells_); mpi::gatherv(*p_, Qm_lcl, gcis_.size(), wrk.data(), w_->ngcis.data(), w_->displs.data(), p_->root()); for (Int i = 0; i < ncells_; ++i) Qm_gbl[w_->gcis[i]] = wrk[i]; } else { Real* rnull = nullptr; const int* inull = nullptr; mpi::gatherv(*p_, Qm_lcl, gcis_.size(), rnull, inull, inull, p_->root()); } } void TestRandomized ::write_field (const std::string& tracer_name, const std::string& field_name, const std::vector<Real>& Qm) { if ( ! p_->amroot()) return; fprintf(w_->fh.get(), " s.%s.%s = [", tracer_name.c_str(), field_name.c_str()); for (const auto& e : Qm) fprintf(w_->fh.get(), "%1.15e, ", e); fprintf(w_->fh.get(), "]\n"); } void TestRandomized::write_pre (const Tracer& t, Values& v) { if ( ! t.write) return; std::vector<Real> f, wrk; if ( ! write_inited_) { init_writer(); if (w_) fprintf(w_->fh.get(), "def getsolns():\n" " class Struct:\n" " pass\n" " s = Struct()\n" " s.all = Struct()\n"); gather_field(v.rhom(), f, wrk); write_field("all", "rhom", f); } const auto name = get_tracer_name(t); if (w_) fprintf(w_->fh.get(), " s.%s = Struct()\n", name.c_str()); gather_field(v.Qm_min(t.idx), f, wrk); write_field(name, "Qm_min", f); gather_field(v.Qm_prev(t.idx), f, wrk); write_field(name, "Qm_orig", f); gather_field(v.Qm(t.idx), f, wrk); write_field(name, "Qm_pre", f); gather_field(v.Qm_max(t.idx), f, wrk); write_field(name, "Qm_max", f); } void TestRandomized::write_post (const Tracer& t, Values& v) { if ( ! t.write) return; const auto name = get_tracer_name(t); std::vector<Real> Qm, wrk; gather_field(v.Qm(t.idx), Qm, wrk); write_field(name, "Qm_qlt", Qm); } Int TestRandomized ::check (const std::string& cdr_name, const mpi::Parallel& p, const std::vector<Tracer>& ts, const Values& v) { static const bool details = true; static const Real eps = std::numeric_limits<Real>::epsilon(); static const Real ulp3 = 3*eps; const auto prefer_mass_con_to_bounds = options_.prefer_numerical_mass_conservation_to_numerical_bounds; const Real lv_tol = prefer_mass_con_to_bounds ? 100*eps : 0; const Real safety_tol = prefer_mass_con_to_bounds ? 100*eps : ulp3; Int nerr = 0; std::vector<Real> lcl_mass(2*ts.size()), q_min_lcl(ts.size()), q_max_lcl(ts.size()); std::vector<Int> t_ok(ts.size(), 1), local_violated(ts.size(), 0); for (size_t ti = 0; ti < ts.size(); ++ti) { const auto& t = ts[ti]; cedr_assert(t.safe_should_hold); const bool safe_only = ! t.local_should_hold; const bool nonneg_only = t.problem_type & ProblemType::nonnegative; const Int n = v.ncells(); const Real* rhom = v.rhom(), * Qm_min = v.Qm_min(t.idx), * Qm = v.Qm(t.idx), * Qm_max = v.Qm_max(t.idx), * Qm_prev = v.Qm_prev(t.idx); q_min_lcl[ti] = 1e3; q_max_lcl[ti] = -1e3; for (Int i = 0; i < n; ++i) { const bool lv = (nonneg_only ? Qm[i] < 0 : Qm[i] < Qm_min[i] - lv_tol || Qm[i] > Qm_max[i] + lv_tol); if (lv) local_violated[ti] = 1; if ( ! safe_only && lv) { // If this fails at ~ machine eps, check r2l_nl_adjust_bounds code in // solve_node_problem. if (details) pr("check q " << t.str() << ": " << Qm[i] << " " << (Qm[i] < Qm_min[i] ? Qm[i] - Qm_min[i] : Qm[i] - Qm_max[i])); t_ok[ti] = false; ++nerr; } if (t.no_change_should_hold && Qm[i] != Qm_prev[i]) { if (details) pr("Q should be unchanged but is not: " << Qm_prev[i] << " changed to " << Qm[i] << " in " << t.str()); t_ok[ti] = false; ++nerr; } lcl_mass[2*ti ] += Qm_prev[i]; lcl_mass[2*ti + 1] += Qm[i]; q_min_lcl[ti] = std::min(q_min_lcl[ti], Qm_min[i]/rhom[i]); q_max_lcl[ti] = std::max(q_max_lcl[ti], Qm_max[i]/rhom[i]); } } std::vector<Real> q_min_gbl(ts.size(), 0), q_max_gbl(ts.size(), 0); mpi::all_reduce(p, q_min_lcl.data(), q_min_gbl.data(), q_min_lcl.size(), MPI_MIN); mpi::all_reduce(p, q_max_lcl.data(), q_max_gbl.data(), q_max_lcl.size(), MPI_MAX); for (size_t ti = 0; ti < ts.size(); ++ti) { // Check safety problem. If local_should_hold and it does, then the safety // problem is by construction also solved (since it's a relaxation of the // local problem). const auto& t = ts[ti]; const bool safe_only = ! t.local_should_hold; const bool nonneg_only = t.problem_type & ProblemType::nonnegative; if (safe_only) { const Int n = v.ncells(); const Real* rhom = v.rhom(), * Qm_min = v.Qm_min(t.idx), * Qm = v.Qm(t.idx), * Qm_max = v.Qm_max(t.idx); const Real q_min = nonneg_only ? 0 : q_min_gbl[ti], q_max = q_max_gbl[ti]; for (Int i = 0; i < n; ++i) { const Real delta = (q_max - q_min)*safety_tol; const bool lv = (nonneg_only ? Qm[i] < -ulp3 : (Qm[i] < q_min*rhom[i] - delta || Qm[i] > q_max*rhom[i] + delta)); if (lv) { if (details) pr("check q (safety) " << t.str() << ": " << q_min*rhom[i] << " " << Qm_min[i] << " " << Qm[i] << " " << Qm_max[i] << " " << q_max*rhom[i] << " | " << (Qm[i] < q_min*rhom[i] ? Qm[i] - q_min*rhom[i] : Qm[i] - q_max*rhom[i])); t_ok[ti] = false; ++nerr; } } } } std::vector<Real> glbl_mass(2*ts.size(), 0); mpi::reduce(p, lcl_mass.data(), glbl_mass.data(), lcl_mass.size(), MPI_SUM, p.root()); std::vector<Int> t_ok_gbl(ts.size(), 0); mpi::reduce(p, t_ok.data(), t_ok_gbl.data(), t_ok.size(), MPI_MIN, p.root()); // Right now we're not using these: std::vector<Int> local_violated_gbl(ts.size(), 0); mpi::reduce(p, local_violated.data(), local_violated_gbl.data(), local_violated.size(), MPI_MAX, p.root()); if (p.amroot()) { const Real tol = 1e3*std::numeric_limits<Real>::epsilon(); for (size_t ti = 0; ti < ts.size(); ++ti) { // Check mass conservation. const Real desired_mass = glbl_mass[2*ti], actual_mass = glbl_mass[2*ti+1], rd = cedr::util::reldif(desired_mass, actual_mass); const bool mass_failed = rd > tol; if (mass_failed) { ++nerr; t_ok_gbl[ti] = false; } if ( ! t_ok_gbl[ti]) { std::cout << "FAIL " << cdr_name << ": " << ts[ti].str(); if (mass_failed) std::cout << " mass re " << rd; std::cout << "\n"; //pr(puf(desired_mass) pu(actual_mass)); } } } return nerr; } TestRandomized ::TestRandomized (const std::string& name, const mpi::Parallel::Ptr& p, const Int& ncells, const bool verbose, const CDR::Options options) : cdr_name_(name), options_(options), p_(p), ncells_(ncells), write_inited_(false) {} void TestRandomized::init () { init_numbering(); init_tracers_vector(); init_tracers(); } } // namespace test } // namespace cedr //>> cedr_test_1d_transport.cpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. //#include "cedr_test.hpp" //#include "cedr_qlt.hpp" //#include "cedr_caas.hpp" #include <algorithm> namespace cedr { namespace test { namespace transport1d { namespace interp { inline Real to_periodic_core (const Real& xl, const Real& xr, const Real& x) { if (x >= xl && x <= xr) return x; const Real w = xr - xl, xmxl = x - xl; return x - w*std::floor(xmxl / w); } inline Real get_slope (const Real x[2], const Real y[2]) { return (y[1] - y[0]) / (x[1] - x[0]); } inline void get_cubic (Real dx, Real v1, Real s1, Real v2, Real s2, Real c[4]) { Real dx2 = dx*dx; Real dx3 = dx2*dx; Real den = -dx3; Real b1, b2; c[2] = s1; c[3] = v1; b1 = v2 - dx*c[2] - c[3]; b2 = s2 - c[2]; c[0] = (2.0*b1 - dx*b2) / den; c[1] = (-3.0*dx*b1 + dx2*b2) / den; } void cubic_interp_periodic ( const Real* const x, const Int nx, const Real* const y, const Real* const xi, const Int nxi, Real* const yi, Int* const dod) { const int nc = nx - 1; #ifdef _OPENMP # pragma omp parallel for #endif for (Int j = 0; j < nxi; ++j) { const Real xi_per = to_periodic_core(x[0], x[nc], xi[j]); Int ip1 = std::upper_bound(x, x + nx, xi_per) - x; // Handle numerical issues at boundaries. if (ip1 == 0) ++ip1; else if (ip1 == nx) --ip1; const Int i = ip1 - 1; // Domain of dependence. Int* dodj = dod + 4*j; for (Int k = 0; k < 4; ++k) dodj[k] = (i - 1 + k + nc) % nc; // Slopes. const bool at_start = i == 0, at_end = i == nc - 1; const Real smid = get_slope(x+i, y+i); Real s1, s2; if (at_start) { const Real a = (x[nc] - x[nc-1]) / ((x[1] - x[0]) + (x[nc] - x[nc-1])); s1 = (1 - a)*get_slope(x+nc-1, y+nc-1) + a*smid; } else { const Real a = (x[i] - x[i-1]) / (x[ip1] - x[i-1]); s1 = (1 - a)*get_slope(x+i-1, y+i-1) + a*smid; } if (at_end) { const Real a = (x[ip1] - x[i]) / ((x[ip1] - x[i]) + (x[1] - x[0])); s2 = (1 - a)*smid + a*get_slope(x, y); } else { const Real a = (x[ip1] - x[i]) / (x[i+2] - x[i]); s2 = (1 - a)*smid + a*get_slope(x+ip1, y+ip1); } // Interp. Real c[4]; get_cubic(x[ip1] - x[i], y[i], s1, y[ip1], s2, c); const Real xij = xi_per - x[i]; yi[j] = (((c[0]*xij + c[1])*xij) + c[2])*xij + c[3]; } } } // namespace interp class PyWriter { typedef std::unique_ptr<FILE, cedr::util::FILECloser> FilePtr; FilePtr fh_; public: PyWriter(const std::string& filename); void write(const std::string& field_name, const std::vector<Real>& v) const; }; PyWriter::PyWriter (const std::string& filename) { fh_ = FilePtr(fopen((filename + ".py").c_str(), "w")); fprintf(fh_.get(), "s = {};\n"); } void PyWriter::write (const std::string& field_name, const std::vector<Real>& v) const { fprintf(fh_.get(), "s['%s'] = [", field_name.c_str()); for (const auto& e: v) fprintf(fh_.get(), " %1.15e,", e); fprintf(fh_.get(), "]\n"); } struct InitialCondition { enum Enum { sin, bell, rect, uniform }; static std::string convert (const Enum& e) { switch (e) { case Enum::sin: return "sin"; case Enum::bell: return "bell"; case Enum::rect: return "rect"; case Enum::uniform: return "uniform"; } cedr_throw_if(true, "InitialCondition::convert can't convert " << e); } static Enum convert (const std::string& s) { using util::eq; if (eq(s, "sin")) return Enum::sin; if (eq(s, "bell")) return Enum::bell; if (eq(s, "rect")) return Enum::rect; if (eq(s, "uniform")) return Enum::uniform; cedr_throw_if(true, "InitialCondition::convert can't convert " << s); } static Real eval (const Enum& ic, const Real x) { switch (ic) { case Enum::sin: return 0.1 + 0.8*0.5*(1 + std::sin(6*M_PI*x)); case Enum::bell: return x < 0.5 ? std::sin(2*M_PI*x) : 0; case Enum::rect: return x > 0.66 || x < 0.33 ? 0 : 1; case Enum::uniform: return 0.42; } cedr_throw_if(true, "InitialCondition::eval can't convert " << ic); } }; class Problem1D { std::vector<Real> xb_, xcp_, rwrk_; std::vector<Int> iwrk_; void init_mesh (const Int ncells, const bool nonuniform_mesh) { xb_.resize(ncells+1); xcp_.resize(ncells+1); xb_[0] = 0; if (nonuniform_mesh) { // Large-scale, continuous variation in cell size, plus a huge jump at the // periodic boundary. for (Int i = 1; i <= ncells; ++i) { const Real x = cedr::util::square(Real(i) / ncells); xb_[i] = 0.01 + sin(0.5*M_PI*x*x*x*x); } // Random local cell sizes. for (Int i = 1; i <= ncells; ++i) xb_[i] *= 0.3 + cedr::util::urand(); // Cumsum. for (Int i = 1; i <= ncells; ++i) xb_[i] += xb_[i-1]; // Normalize. for (Int i = 1; i <= ncells; ++i) xb_[i] /= xb_[ncells]; } else { xb_.back() = 1; for (Int i = 1; i < ncells; ++i) xb_[i] = Real(i) / ncells; } for (Int i = 0; i < ncells; ++i) xcp_[i] = 0.5*(xb_[i] + xb_[i+1]); xcp_.back() = 1 + xcp_[0]; } static void run_cdr (const Problem1D& p, CDR& cdr, const Real* yp, Real* y, const Int* dods) { const Int n = p.ncells(); for (Int i = 0; i < n; ++i) { const Int* dod = dods + 4*i; Real min = yp[dod[0]], max = min; for (Int j = 1; j < 4; ++j) { const Real v = yp[dod[j]]; min = std::min(min, v); max = std::max(max, v); } const Real area_i = p.area(i); cdr.set_Qm(i, 0, y[i]*area_i, min*area_i, max*area_i, yp[i]*area_i); } cdr.run(); for (Int i = 0; i < n; ++i) y[i] = cdr.get_Qm(i, 0) / p.area(i); y[n] = y[0]; } static void run_caas (const Problem1D& p, const Real* yp, Real* y, const Int* dods) { const Int n = p.ncells(); std::vector<Real> lo(n), up(n), w(n); Real m = 0; for (Int i = 0; i < n; ++i) { const Int* dod = dods + 4*i; Real min = yp[dod[0]], max = min; for (Int j = 1; j < 4; ++j) { const Real v = yp[dod[j]]; min = std::min(min, v); max = std::max(max, v); } const Real area_i = p.area(i); lo[i] = min*area_i; up[i] = max*area_i; y[i] = std::max(min, std::min(max, y[i])); m += (yp[i] - y[i])*area_i; } Real wsum = 0; for (Int i = 0; i < n; ++i) { w[i] = m >= 0 ? up[i] - y[i]*p.area(i) : y[i]*p.area(i) - lo[i]; wsum += w[i]; } for (Int i = 0; i < n; ++i) y[i] += (m/(wsum*p.area(i)))*w[i]; } public: Problem1D (const Int ncells, const bool nonuniform_mesh = false) { init_mesh(ncells, nonuniform_mesh); } Int ncells () const { return xb_.size() - 1; } Real xb (const Int& i) const { return xb_[i]; } Real xcp (const Int& i) const { return xcp_[i]; } Real area (const Int& i) const { return xb_[i+1] - xb_[i]; } const std::vector<Real> get_xb () const { return xb_; } const std::vector<Real> get_xcp () const { return xcp_; } void cycle (const Int& nsteps, const Real* y0, Real* yf, CDR* cdr = nullptr) { const Int n = xcp_.size(); rwrk_.resize(2*n); iwrk_.resize(4*n); Real* xcpi = rwrk_.data(); Int* dod = iwrk_.data(); const Real xos = -1.0 / nsteps; for (Int i = 0; i < n; ++i) xcpi[i] = xcp_[i] + xos; Real* ys[] = {xcpi + n, yf}; std::copy(y0, y0 + n, ys[0]); for (Int ti = 0; ti < nsteps; ++ti) { interp::cubic_interp_periodic(xcp_.data(), n, ys[0], xcpi, n, ys[1], dod); if (cdr) run_cdr(*this, *cdr, ys[0], ys[1], dod); else run_caas(*this, ys[0], ys[1], dod); std::swap(ys[0], ys[1]); } std::copy(ys[0], ys[0] + n, yf); } }; //todo Clean this up. Right now everything is hardcoded and kludgy. // - optional write // - some sort of brief quantitative output // - better, more canonical IC // - optional tree imbalance // - optional mesh nonuniformity // - parallel? Int run (const mpi::Parallel::Ptr& parallel, const Input& in) { cedr_throw_if(parallel->size() > 1, "run_1d_transport_test runs in serial only."); Int nerr = 0; Problem1D p(in.ncells, false /* nonuniform_mesh */ ); auto tree = qlt::tree::make_tree_over_1d_mesh(parallel, in.ncells, false /* imbalanced */); typedef qlt::QLT<Kokkos::DefaultHostExecutionSpace> QLTT; QLTT qltnn(parallel, in.ncells, tree), qlt(parallel, in.ncells, tree); typedef caas::CAAS<Kokkos::DefaultHostExecutionSpace> CAAST; CAAST caas(parallel, in.ncells); CDR* cdrs[] = {&qltnn, &qlt, &caas}; const int ncdrs = sizeof(cdrs)/sizeof(*cdrs); bool first = true; for (CDR* cdr : cdrs) { if (first) { QLTT* qlt = dynamic_cast<QLTT*>(cdr); cedr_assert(qlt); qlt->declare_tracer(cedr::ProblemType::conserve | cedr::ProblemType::nonnegative, 0); first = false; } else cdr->declare_tracer(cedr::ProblemType::conserve | cedr::ProblemType::shapepreserve, 0); cdr->end_tracer_declarations(); cdr->finish_setup(); for (Int i = 0; i < in.ncells; ++i) cdr->set_rhom(i, 0, p.area(i)); cdr->print(std::cout); } std::vector<Real> y0(in.ncells+1); for (Int i = 0, nc = p.ncells(); i < nc; ++i) y0[i] = (p.xcp(i) < 0.4 || p.xcp(i) > 0.9 ? InitialCondition::eval(InitialCondition::sin, p.xcp(i)) : InitialCondition::eval(InitialCondition::rect, p.xcp(i))); y0.back() = y0[0]; PyWriter w("out_transport1d"); w.write("xb", p.get_xb()); w.write("xcp", p.get_xcp()); w.write("y0", y0); std::vector<Real> yf(in.ncells+1); const Int nsteps = Int(3.17*in.ncells); const Int ncycles = 1; const char* names[] = {"yqltnn", "yqlt", "ycaas"}; for (int ic = 0; ic < ncdrs; ++ic) { std::copy(y0.begin(), y0.end(), yf.begin()); for (Int i = 0; i < ncycles; ++i) p.cycle(nsteps, yf.data(), yf.data(), cdrs[ic]); w.write(names[ic], yf); } std::copy(y0.begin(), y0.end(), yf.begin()); for (Int i = 0; i < ncycles; ++i) p.cycle(nsteps, yf.data(), yf.data()); w.write("ylcaas", yf); return nerr; } } // namespace transport1d } // namespace test } // namespace cedr //>> cedr_test.cpp // COMPOSE version 1.0: Copyright 2018 NTESS. This software is released under // the BSD license; see LICENSE in the top-level directory. //#include "cedr_qlt.hpp" //#include "cedr_caas.hpp" //#include "cedr_mpi.hpp" //#include "cedr_util.hpp" //#include "cedr_test.hpp" #include <stdexcept> #include <sstream> namespace cedr { struct InputParser { qlt::test::Input qin; test::transport1d::Input tin; class ArgAdvancer { const int argc_; char const* const* argv_; int i_; public: ArgAdvancer (int argc, char** argv) : argc_(argc), argv_(argv), i_(1) {} const char* advance () { if (i_+1 >= argc_) cedr_throw_if(true, "Command line is missing an argument."); return argv_[++i_]; } const char* token () const { return argv_[i_]; } void incr () { ++i_; } bool more () const { return i_ < argc_; } }; InputParser (int argc, char** argv, const qlt::Parallel::Ptr& p) { using util::eq; qin.unittest = false; qin.perftest = false; qin.write = false; qin.ncells = 0; qin.ntracers = 1; qin.tracer_type = 0; qin.nrepeat = 1; qin.pseudorandom = false; qin.verbose = false; tin.ncells = 0; for (ArgAdvancer aa(argc, argv); aa.more(); aa.incr()) { const char* token = aa.token(); if (eq(token, "-t", "--unittest")) qin.unittest = true; else if (eq(token, "-pt", "--perftest")) qin.perftest = true; else if (eq(token, "-w", "--write")) qin.write = true; else if (eq(token, "-nc", "--ncells")) qin.ncells = std::atoi(aa.advance()); else if (eq(token, "-nt", "--ntracers")) qin.ntracers = std::atoi(aa.advance()); else if (eq(token, "-tt", "--tracertype")) qin.tracer_type = std::atoi(aa.advance()); else if (eq(token, "-nr", "--nrepeat")) qin.nrepeat = std::atoi(aa.advance()); else if (eq(token, "--proc-random")) qin.pseudorandom = true; else if (eq(token, "-v", "--verbose")) qin.verbose = true; else if (eq(token, "-t1d", "--transport1dtest")) tin.ncells = 1; else cedr_throw_if(true, "Invalid token " << token); } if (tin.ncells) { tin.ncells = qin.ncells; tin.verbose = qin.verbose; } cedr_throw_if(qin.tracer_type < 0 || qin.tracer_type >= 4, "Tracer type is out of bounds [0, 3]."); cedr_throw_if(qin.ntracers < 1, "Number of tracers is < 1."); } void print (std::ostream& os) const { os << "ncells " << qin.ncells << " nrepeat " << qin.nrepeat; if (qin.pseudorandom) os << " random"; os << "\n"; } }; } // namespace cedr // -------------------- Homme-specific impl details -------------------- // #if 0 // Includes if using compose library. #include "compose/cedr.hpp" // Use these when rewriting each CDR's run() function to interact nicely with // Homme's nested OpenMP and top-level horizontal threading scheme. #include "compose/cedr_qlt.hpp" #include "compose/cedr_caas.hpp" #endif #define THREAD_QLT_RUN #ifndef QLT_MAIN # ifdef HAVE_CONFIG_H # include "config.h.c" # endif #endif typedef Kokkos::DefaultHostExecutionSpace ComposeDefaultExecutionSpace; namespace homme { namespace compose { template <typename ES> class QLT : public cedr::qlt::QLT<ES> { typedef cedr::Int Int; typedef cedr::Real Real; typedef cedr::qlt::QLT<ES> Super; typedef typename Super::RealList RealList; //todo All of this VerticalLevelsData-related code should be impl'ed // using a new optional root-node-function QLT registration function. struct VerticalLevelsData { typedef std::shared_ptr<VerticalLevelsData> Ptr; RealList lo, hi, mass, ones, wrk; VerticalLevelsData (const cedr::Int n) : lo("lo", n), hi("hi", n), mass("mass", n), ones("ones", n), wrk("wrk", n) { for (cedr::Int k = 0; k < n; ++k) ones(k) = 1; } }; typename VerticalLevelsData::Ptr vld_; void reconcile_vertical (const Int problem_type, const Int bd_os, const Int bis, const Int bie) { using cedr::ProblemType; cedr_assert((problem_type & ProblemType::shapepreserve) && (problem_type & ProblemType::conserve)); auto& md = this->md_; auto& bd = this->bd_; const auto& vld = *vld_; const Int nlev = vld.lo.extent_int(0); const Int nprob = (bie - bis)/nlev; #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp master #endif for (Int pi = 0; pi < nprob; ++pi) { const Int bd_os_pi = bd_os + md.a_d.trcr2bl2r(md.a_d.bidx2trcr(bis + pi)); #ifdef RV_DIAG Real oob = 0; #endif Real tot_mass = 0; for (Int k = 0; k < nlev; ++k) { const Int bd_os_k = bd_os_pi + nprob*4*k; vld.lo (k) = bd.l2r_data(bd_os_k ); vld.hi (k) = bd.l2r_data(bd_os_k + 2); vld.mass(k) = bd.l2r_data(bd_os_k + 3); // previous mass, not current one tot_mass += vld.mass(k); #ifdef RV_DIAG if (vld.mass(k) < vld.lo(k)) oob += vld.lo(k) - vld.mass(k); if (vld.mass(k) > vld.hi(k)) oob += vld.mass(k) - vld.hi(k); #endif } solve(nlev, vld, tot_mass); Real tot_mass_slv = 0, oob_slv = 0; for (Int k = 0; k < nlev; ++k) { const Int bd_os_k = bd_os_pi + nprob*4*k; bd.l2r_data(bd_os_k + 3) = vld.mass(k); // previous mass, not current one #ifdef RV_DIAG tot_mass_slv += vld.mass(k); if (vld.mass(k) < vld.lo(k)) oob_slv += vld.lo(k) - vld.mass(k); if (vld.mass(k) > vld.hi(k)) oob_slv += vld.mass(k) - vld.hi(k); #endif } #ifdef RV_DIAG printf("%2d %9.2e %9.2e %9.2e %9.2e\n", pi, oob/tot_mass, oob_slv/tot_mass, tot_mass, std::abs(tot_mass_slv - tot_mass)/tot_mass); #endif } #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp barrier #endif } static Int solve (const Int n, const Real* a, const Real b, const Real* xlo, const Real* xhi, Real* x, Real* wrk) { #ifndef NDEBUG cedr_assert(b >= 0); for (Int i = 0; i < n; ++i) { cedr_assert(a[i] > 0); cedr_assert(xlo[i] >= 0); cedr_assert(xhi[i] >= xlo[i]); } #endif Int status = 0; Real tot_lo = 0, tot_hi = 0; for (Int i = 0; i < n; ++i) tot_lo += a[i]*xlo[i]; for (Int i = 0; i < n; ++i) tot_hi += a[i]*xhi[i]; if (b < tot_lo) { status = -2; for (Int i = 0; i < n; ++i) wrk[i] = 0; for (Int i = 0; i < n; ++i) x[i] = xlo[i]; // Find a new xlo >= 0 minimally far from the current one. This // is also the solution x. cedr::local::caas(n, a, b, wrk, xlo, x, x, false); } else if (b > tot_hi) { status = -1; const Real f = b/tot_hi; // a[i] divides out. for (Int i = 0; i < n; ++i) x[i] = f*xhi[i]; } else { cedr::local::caas(n, a, b, xlo, xhi, x, x, false); } return status; } static Int solve (const Int nlev, const VerticalLevelsData& vld, const Real& tot_mass) { solve(nlev, vld.ones.data(), tot_mass, vld.lo.data(), vld.hi.data(), vld.mass.data(), vld.wrk.data()); } static Int solve_unittest () { static const auto eps = std::numeric_limits<Real>::epsilon(); static const Int n = 7; Real a[n], xlo[n], xhi[n], x[n], wrk[n]; static const Real x0 [n] = { 1.2, 0.5,3 , 2 , 1.5, 1.8,0.2}; static const Real dxlo[n] = {-0.1,-0.2,0.5,-1.5,-0.1,-1.1,0.1}; static const Real dxhi[n] = { 0.1,-0.1,1 ,-0.5, 0.1,-0.2,0.5}; for (Int i = 0; i < n; ++i) a[i] = i+1; for (Int i = 0; i < n; ++i) xlo[i] = x0[i] + dxlo[i]; for (Int i = 0; i < n; ++i) xhi[i] = x0[i] + dxhi[i]; Real b, b1; Int status, nerr = 0; const auto check_mass = [&] () { b1 = 0; for (Int i = 0; i < n; ++i) b1 += a[i]*x[i]; if (std::abs(b1 - b) >= 10*eps*b) ++nerr; }; for (Int i = 0; i < n; ++i) x[i] = x0[i]; b = 0; for (Int i = 0; i < n; ++i) b += a[i]*xlo[i]; b *= 0.9; status = solve(n, a, b, xlo, xhi, x, wrk); if (status != -2) ++nerr; check_mass(); for (Int i = 0; i < n; ++i) if (x[i] > xhi[i]*(1 + 10*eps)) ++nerr; for (Int i = 0; i < n; ++i) x[i] = x0[i]; b = 0; for (Int i = 0; i < n; ++i) b += a[i]*xhi[i]; b *= 1.1; status = solve(n, a, b, xlo, xhi, x, wrk); if (status != -1) ++nerr; check_mass(); for (Int i = 0; i < n; ++i) if (x[i] < xlo[i]*(1 - 10*eps)) ++nerr; for (Int i = 0; i < n; ++i) x[i] = x0[i]; b = 0; for (Int i = 0; i < n; ++i) b += 0.5*a[i]*(xlo[i] + xhi[i]); status = solve(n, a, b, xlo, xhi, x, wrk); if (status != 0) ++nerr; check_mass(); for (Int i = 0; i < n; ++i) if (x[i] < xlo[i]*(1 - 10*eps)) ++nerr; for (Int i = 0; i < n; ++i) if (x[i] > xhi[i]*(1 + 10*eps)) ++nerr; return nerr; } public: QLT (const cedr::mpi::Parallel::Ptr& p, const cedr::Int& ncells, const cedr::qlt::tree::Node::Ptr& tree, const cedr::CDR::Options& options, const cedr::Int& vertical_levels) : cedr::qlt::QLT<ES>(p, ncells, tree, options) { if (vertical_levels) vld_ = std::make_shared<VerticalLevelsData>(vertical_levels); } void run () override { static const int mpitag = 42; using cedr::Int; using cedr::Real; using cedr::ProblemType; using cedr::qlt::impl::NodeSets; namespace mpi = cedr::mpi; auto& md_ = this->md_; auto& bd_ = this->bd_; auto& ns_ = this->ns_; auto& p_ = this->p_; #if ! defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp master { #endif // Number of data per slot. const Int l2rndps = md_.a_d.prob2bl2r[md_.nprobtypes]; const Int r2lndps = md_.a_d.prob2br2l[md_.nprobtypes]; // Leaves to root. for (size_t il = 0; il < ns_->levels.size(); ++il) { auto& lvl = ns_->levels[il]; // Set up receives. if (lvl.kids.size()) { #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp master #endif { for (size_t i = 0; i < lvl.kids.size(); ++i) { const auto& mmd = lvl.kids[i]; mpi::irecv(*p_, &bd_.l2r_data(mmd.offset*l2rndps), mmd.size*l2rndps, mmd.rank, mpitag, &lvl.kids_req[i]); } mpi::waitall(lvl.kids_req.size(), lvl.kids_req.data()); } #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp barrier #endif } // Combine kids' data. if (lvl.nodes.size()) { #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp for #endif for (size_t ni = 0; ni < lvl.nodes.size(); ++ni) { const auto lvlidx = lvl.nodes[ni]; const auto n = ns_->node_h(lvlidx); if ( ! n->nkids) continue; cedr_kernel_assert(n->nkids == 2); // Total density. bd_.l2r_data(n->offset*l2rndps) = (bd_.l2r_data(ns_->node_h(n->kids[0])->offset*l2rndps) + bd_.l2r_data(ns_->node_h(n->kids[1])->offset*l2rndps)); // Tracers. for (Int pti = 0; pti < md_.nprobtypes; ++pti) { const Int problem_type = md_.get_problem_type(pti); const bool nonnegative = problem_type & ProblemType::nonnegative; const bool shapepreserve = problem_type & ProblemType::shapepreserve; const bool conserve = problem_type & ProblemType::conserve; const Int bis = md_.a_d.prob2trcrptr[pti], bie = md_.a_d.prob2trcrptr[pti+1]; #if defined THREAD_QLT_RUN && defined COLUMN_OPENMP # pragma omp parallel for #endif for (Int bi = bis; bi < bie; ++bi) { const Int bdi = md_.a_d.trcr2bl2r(md_.a_d.bidx2trcr(bi)); Real* const me = &bd_.l2r_data(n->offset*l2rndps + bdi); const auto kid0 = ns_->node_h(n->kids[0]); const auto kid1 = ns_->node_h(n->kids[1]); const Real* const k0 = &bd_.l2r_data(kid0->offset*l2rndps + bdi); const Real* const k1 = &bd_.l2r_data(kid1->offset*l2rndps + bdi); if (nonnegative) { me[0] = k0[0] + k1[0]; if (conserve) me[1] = k0[1] + k1[1]; } else { me[0] = shapepreserve ? k0[0] + k1[0] : cedr::impl::min(k0[0], k1[0]); me[1] = k0[1] + k1[1]; me[2] = shapepreserve ? k0[2] + k1[2] : cedr::impl::max(k0[2], k1[2]); if (conserve) me[3] = k0[3] + k1[3] ; } } } } } // Send to parents. if (lvl.me.size()) #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp master #endif { for (size_t i = 0; i < lvl.me.size(); ++i) { const auto& mmd = lvl.me[i]; mpi::isend(*p_, &bd_.l2r_data(mmd.offset*l2rndps), mmd.size*l2rndps, mmd.rank, mpitag); } } #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp barrier #endif } // Root. if ( ! (ns_->levels.empty() || ns_->levels.back().nodes.size() != 1 || ns_->node_h(ns_->levels.back().nodes[0])->parent >= 0)) { const auto n = ns_->node_h(ns_->levels.back().nodes[0]); for (Int pti = 0; pti < md_.nprobtypes; ++pti) { const Int bis = md_.a_d.prob2trcrptr[pti], bie = md_.a_d.prob2trcrptr[pti+1]; if (bie == bis) continue; const Int problem_type = md_.get_problem_type(pti); if (vld_) reconcile_vertical(problem_type, n->offset*l2rndps, bis, bie); #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP && defined COLUMN_OPENMP # pragma omp parallel #endif #if defined THREAD_QLT_RUN && (defined HORIZ_OPENMP || defined COLUMN_OPENMP) # pragma omp for #endif for (Int bi = bis; bi < bie; ++bi) { const Int l2rbdi = md_.a_d.trcr2bl2r(md_.a_d.bidx2trcr(bi)); const Int r2lbdi = md_.a_d.trcr2br2l(md_.a_d.bidx2trcr(bi)); // If QLT is enforcing global mass conservation, set the root's r2l Qm // value to the l2r Qm_prev's sum; otherwise, copy the l2r Qm value to // the r2l one. const Int os = (problem_type & ProblemType::conserve ? md_.get_problem_type_l2r_bulk_size(problem_type) - 1 : (problem_type & ProblemType::nonnegative ? 0 : 1)); bd_.r2l_data(n->offset*r2lndps + r2lbdi) = bd_.l2r_data(n->offset*l2rndps + l2rbdi + os); if ((problem_type & ProblemType::consistent) && ! (problem_type & ProblemType::shapepreserve)) { // Consistent but not shape preserving, so we're solving a dynamic range // preservation problem. We now know the global q_{min,max}. Start // propagating it leafward. bd_.r2l_data(n->offset*r2lndps + r2lbdi + 1) = bd_.l2r_data(n->offset*l2rndps + l2rbdi + 0); bd_.r2l_data(n->offset*r2lndps + r2lbdi + 2) = bd_.l2r_data(n->offset*l2rndps + l2rbdi + 2); } } } } // Root to leaves. for (size_t il = ns_->levels.size(); il > 0; --il) { auto& lvl = ns_->levels[il-1]; if (lvl.me.size()) { #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp master #endif { for (size_t i = 0; i < lvl.me.size(); ++i) { const auto& mmd = lvl.me[i]; mpi::irecv(*p_, &bd_.r2l_data(mmd.offset*r2lndps), mmd.size*r2lndps, mmd.rank, mpitag, &lvl.me_recv_req[i]); } mpi::waitall(lvl.me_recv_req.size(), lvl.me_recv_req.data()); } #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp barrier #endif } // Solve QP for kids' values. #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp for #endif for (size_t ni = 0; ni < lvl.nodes.size(); ++ni) { const auto lvlidx = lvl.nodes[ni]; const auto n = ns_->node_h(lvlidx); if ( ! n->nkids) continue; for (Int pti = 0; pti < md_.nprobtypes; ++pti) { const Int problem_type = md_.get_problem_type(pti); const Int bis = md_.a_d.prob2trcrptr[pti], bie = md_.a_d.prob2trcrptr[pti+1]; #if defined THREAD_QLT_RUN && defined COLUMN_OPENMP # pragma omp parallel for #endif for (Int bi = bis; bi < bie; ++bi) { const Int l2rbdi = md_.a_d.trcr2bl2r(md_.a_d.bidx2trcr(bi)); const Int r2lbdi = md_.a_d.trcr2br2l(md_.a_d.bidx2trcr(bi)); cedr_assert(n->nkids == 2); if ((problem_type & ProblemType::consistent) && ! (problem_type & ProblemType::shapepreserve)) { // Pass q_{min,max} info along. l2r data are updated for use in // solve_node_problem. r2l data are updated for use in isend. const Real q_min = bd_.r2l_data(n->offset*r2lndps + r2lbdi + 1); const Real q_max = bd_.r2l_data(n->offset*r2lndps + r2lbdi + 2); bd_.l2r_data(n->offset*l2rndps + l2rbdi + 0) = q_min; bd_.l2r_data(n->offset*l2rndps + l2rbdi + 2) = q_max; for (Int k = 0; k < 2; ++k) { const auto os = ns_->node_h(n->kids[k])->offset; bd_.l2r_data(os*l2rndps + l2rbdi + 0) = q_min; bd_.l2r_data(os*l2rndps + l2rbdi + 2) = q_max; bd_.r2l_data(os*r2lndps + r2lbdi + 1) = q_min; bd_.r2l_data(os*r2lndps + r2lbdi + 2) = q_max; } } const auto k0 = ns_->node_h(n->kids[0]); const auto k1 = ns_->node_h(n->kids[1]); cedr::qlt::impl::solve_node_problem( problem_type, bd_.l2r_data( n->offset*l2rndps), &bd_.l2r_data( n->offset*l2rndps + l2rbdi), bd_.r2l_data( n->offset*r2lndps + r2lbdi), bd_.l2r_data(k0->offset*l2rndps), &bd_.l2r_data(k0->offset*l2rndps + l2rbdi), bd_.r2l_data(k0->offset*r2lndps + r2lbdi), bd_.l2r_data(k1->offset*l2rndps), &bd_.l2r_data(k1->offset*l2rndps + l2rbdi), bd_.r2l_data(k1->offset*r2lndps + r2lbdi), this->options_.prefer_numerical_mass_conservation_to_numerical_bounds); } } } // Send. if (lvl.kids.size()) #if defined THREAD_QLT_RUN && defined HORIZ_OPENMP # pragma omp master #endif { for (size_t i = 0; i < lvl.kids.size(); ++i) { const auto& mmd = lvl.kids[i]; mpi::isend(*p_, &bd_.r2l_data(mmd.offset*r2lndps), mmd.size*r2lndps, mmd.rank, mpitag); } } } #if ! defined THREAD_QLT_RUN && defined HORIZ_OPENMP } #endif } static Int unittest () { return solve_unittest(); } }; // We explicitly use Kokkos::Serial here so we can run the Kokkos kernels in the // super class w/o triggering an expecution-space initialization error in // Kokkos. This complication results from the interaction of Homme's // HORIZ_OPENMP threading with Kokkos kernels. struct CAAS : public cedr::caas::CAAS<Kokkos::Serial> { typedef cedr::caas::CAAS<Kokkos::Serial> Super; CAAS (const cedr::mpi::Parallel::Ptr& p, const cedr::Int nlclcells, const typename Super::UserAllReducer::Ptr& uar) : Super(p, nlclcells, uar) {} void run () override { Super::run(); } }; } // namespace compose } // namespace homme #ifdef QLT_MAIN int main (int argc, char** argv) { int nerr = 0, retval = 0; MPI_Init(&argc, &argv); auto p = cedr::mpi::make_parallel(MPI_COMM_WORLD); srand(p->rank()); Kokkos::initialize(argc, argv); #if 0 try #endif { cedr::InputParser inp(argc, argv, p); if (p->amroot()) inp.print(std::cout); if (inp.qin.unittest) { nerr += cedr::local::unittest(); nerr += cedr::caas::test::unittest(p); } if (inp.qin.unittest || inp.qin.perftest) nerr += cedr::qlt::test::run_unit_and_randomized_tests(p, inp.qin); if (inp.tin.ncells > 0) nerr += cedr::test::transport1d::run(p, inp.tin); { int gnerr; cedr::mpi::all_reduce(*p, &nerr, &gnerr, 1, MPI_SUM); retval = gnerr != 0 ? -1 : 0; if (p->amroot()) std::cout << (gnerr != 0 ? "FAIL" : "PASS") << "\n"; } } #if 0 catch (const std::exception& e) { if (p->amroot()) std::cerr << e.what(); retval = -1; } #endif Kokkos::finalize(); if (nerr) prc(nerr); MPI_Finalize(); return retval; } #endif namespace homme { namespace qlt = cedr::qlt; using cedr::Int; using cedr::Real; Int rank2sfc_search (const Int* rank2sfc, const Int& nrank, const Int& sfc) { Int lo = 0, hi = nrank+1; while (hi > lo + 1) { const Int mid = (lo + hi)/2; if (sfc >= rank2sfc[mid]) lo = mid; else hi = mid; } return lo; } // Change leaf node->cellidx from index into space-filling curve to global cell // index. owned_ids is in SFC index order for this rank. void renumber (const Int nrank, const Int nelem, const Int my_rank, const Int* owned_ids, const Int* rank2sfc, const qlt::tree::Node::Ptr& node) { if (node->nkids) { for (Int k = 0; k < node->nkids; ++k) renumber(nrank, nelem, my_rank, owned_ids, rank2sfc, node->kids[k]); } else { const Int sfc = node->cellidx; node->cellidx = node->rank == my_rank ? owned_ids[sfc - rank2sfc[my_rank]] : -1; cedr_assert((node->rank != my_rank && node->cellidx == -1) || (node->rank == my_rank && node->cellidx >= 0 && node->cellidx < nelem)); } } void renumber (const Int* sc2gci, const Int* sc2rank, const qlt::tree::Node::Ptr& node) { if (node->nkids) { for (Int k = 0; k < node->nkids; ++k) renumber(sc2gci, sc2rank, node->kids[k]); } else { const Int ci = node->cellidx; node->cellidx = sc2gci[ci]; node->rank = sc2rank[ci]; } } // Build a subtree over [0, nsublev). void add_sub_levels (const qlt::tree::Node::Ptr& node, const Int nsublev, const Int gci, const Int my_rank, const Int rank, const bool calc_level, const Int slb, const Int sle) { if (slb+1 == sle) { node->cellidx = rank == my_rank ? nsublev*gci + slb : -1; if (calc_level) node->level = 0; } else { node->nkids = 2; for (Int k = 0; k < 2; ++k) { auto kid = std::make_shared<qlt::tree::Node>(); kid->parent = node.get(); kid->rank = rank; node->kids[k] = kid; } const Int mid = slb + (sle - slb)/2; add_sub_levels(node->kids[0], nsublev, gci, my_rank, rank, calc_level, slb, mid); add_sub_levels(node->kids[1], nsublev, gci, my_rank, rank, calc_level, mid, sle); if (calc_level) node->level = 1 + std::max(node->kids[0]->level, node->kids[1]->level); } } // Recurse to each leaf and call add_sub_levels above. void add_sub_levels (const Int my_rank, const qlt::tree::Node::Ptr& node, const Int nsublev, const Int level_offset) { if (node->nkids) { for (Int k = 0; k < node->nkids; ++k) add_sub_levels(my_rank, node->kids[k], nsublev, level_offset); node->level += level_offset; } else { const Int gci = node->cellidx; const Int rank = node->rank; add_sub_levels(node, nsublev, gci, my_rank, rank, level_offset, 0, nsublev); // Level already calculated if requested. cedr_assert(level_offset == 0 || node->level == level_offset); } } // This impl carefully follows the requirements that // cedr::qlt::impl::init_tree, level_schedule_and_collect // establish. init_tree has to be modified to have the condition in // the line // if (node->rank < 0) node->rank = node->kids[0]->rank // since here we're assigning the ranks ourselves. Similarly, it must // check for node->level >= 0; if the tree is partial, it is unable to // compute node level. qlt::tree::Node::Ptr make_my_tree_part (const qlt::oned::Mesh& m, const Int cs, const Int ce, const qlt::tree::Node* parent, const Int& nrank, const Int* rank2sfc) { const auto my_rank = m.parallel()->rank(); const Int cn = ce - cs, cn0 = cn/2; qlt::tree::Node::Ptr n = std::make_shared<qlt::tree::Node>(); n->parent = parent; n->rank = rank2sfc_search(rank2sfc, nrank, cs); n->cellidx = n->rank == my_rank ? cs : -1; cedr_assert(n->rank >= 0 && n->rank < nrank); if (cn == 1) { n->nkids = 0; n->level = 0; return n; } const auto k1 = make_my_tree_part(m, cs, cs + cn0, n.get(), nrank, rank2sfc); const auto k2 = make_my_tree_part(m, cs + cn0, ce, n.get(), nrank, rank2sfc); n->level = 1 + std::max(k1->level, k2->level); if (n->rank == my_rank) { // Need to know both kids for comm. n->nkids = 2; n->kids[0] = k1; n->kids[1] = k2; } else { // Prune parts of the tree irrelevant to my rank. n->nkids = 0; if (k1->nkids > 0 || k1->rank == my_rank) n->kids[n->nkids++] = k1; if (k2->nkids > 0 || k2->rank == my_rank) n->kids[n->nkids++] = k2; if (n->nkids == 0) { // Signal a non-leaf node with 0 kids to init_tree. n->nkids = -1; } } cedr_assert(n->level > 0 || n->nkids == 0); return n; } qlt::tree::Node::Ptr make_my_tree_part (const cedr::mpi::Parallel::Ptr& p, const Int& ncells, const Int& nrank, const Int* rank2sfc) { qlt::oned::Mesh m(ncells, p); return make_my_tree_part(m, 0, m.ncell(), nullptr, nrank, rank2sfc); } static size_t nextpow2 (size_t n) { size_t p = 1; while (p < n) p <<= 1; return p; } static size_t get_tree_height (size_t nleaf) { size_t height = 0; nleaf = nextpow2(nleaf); while (nleaf) { ++height; nleaf >>= 1; } return height; } qlt::tree::Node::Ptr make_tree_sgi (const cedr::mpi::Parallel::Ptr& p, const Int nelem, const Int* owned_ids, const Int* rank2sfc, const Int nsublev) { // Partition 0:nelem-1, the space-filling curve space. auto tree = make_my_tree_part(p, nelem, p->size(), rank2sfc); // Renumber so that node->cellidx records the global element number, and // associate the correct rank with the element. const auto my_rank = p->rank(); renumber(p->size(), nelem, my_rank, owned_ids, rank2sfc, tree); if (nsublev > 1) { const Int level_offset = get_tree_height(nsublev) - 1; add_sub_levels(my_rank, tree, nsublev, level_offset); } return tree; } qlt::tree::Node::Ptr make_tree_non_sgi (const cedr::mpi::Parallel::Ptr& p, const Int nelem, const Int* sc2gci, const Int* sc2rank, const Int nsublev) { auto tree = qlt::tree::make_tree_over_1d_mesh(p, nelem); renumber(sc2gci, sc2rank, tree); const auto my_rank = p->rank(); if (nsublev > 1) add_sub_levels(my_rank, tree, nsublev, 0); return tree; } qlt::tree::Node::Ptr clone (const qlt::tree::Node::Ptr& in, const qlt::tree::Node* parent = nullptr) { const auto out = std::make_shared<qlt::tree::Node>(*in); cedr_assert(out->rank == in->rank && out->level == in->level && out->nkids == in->nkids && out->cellidx == in->cellidx); out->parent = parent; for (Int k = 0; k < in->nkids; ++k) out->kids[k] = clone(in->kids[k], out.get()); return out; } void renumber_leaves (const qlt::tree::Node::Ptr& node, const Int horiz_nleaf, const Int supidx) { if (node->nkids) { for (Int k = 0; k < node->nkids; ++k) renumber_leaves(node->kids[k], horiz_nleaf, supidx); } else { if (node->cellidx != -1) { cedr_assert(node->cellidx >= 0 && node->cellidx < horiz_nleaf); node->cellidx += horiz_nleaf*supidx; } } } void attach_and_renumber_horizontal_trees (const qlt::tree::Node::Ptr& supnode, const qlt::tree::Node::Ptr& htree, const Int horiz_nleaf) { Int level = -1, rank; for (Int k = 0; k < supnode->nkids; ++k) { auto& kid = supnode->kids[k]; if (kid->nkids) { attach_and_renumber_horizontal_trees(kid, htree, horiz_nleaf); } else { const auto supidx = kid->cellidx; supnode->kids[k] = clone(htree); kid = supnode->kids[k]; kid->parent = supnode.get(); kid->cellidx = -1; renumber_leaves(kid, horiz_nleaf, supidx); } rank = kid->rank; level = std::max(level, kid->level); } if (level != -1) ++level; supnode->level = level; supnode->rank = rank; } qlt::tree::Node::Ptr make_tree_over_index_range (const Int cs, const Int ce, const qlt::tree::Node* parent = nullptr) { const Int cn = ce - cs, cn0 = cn/2; const auto n = std::make_shared<qlt::tree::Node>(); n->parent = parent; if (cn == 1) { n->nkids = 0; n->cellidx = cs; } else { n->nkids = 2; n->kids[0] = make_tree_over_index_range(cs, cs + cn0, n.get()); n->kids[1] = make_tree_over_index_range(cs + cn0, ce, n.get()); } return n; } qlt::tree::Node::Ptr combine_superlevels(const qlt::tree::Node::Ptr& horiz_tree, const Int horiz_nleaf, const Int nsuplev) { cedr_assert(horiz_tree->nkids > 0); // In this tree, cellidx 0 is the top super level. const auto suptree = make_tree_over_index_range(0, nsuplev); attach_and_renumber_horizontal_trees(suptree, horiz_tree, horiz_nleaf); return suptree; } void check_tree (const cedr::mpi::Parallel::Ptr& p, const qlt::tree::Node::Ptr& n, const Int nleaf) { #ifndef NDEBUG cedr_assert(n->nkids >= -1 && n->nkids <= 2); cedr_assert(n->rank >= 0); cedr_assert(n->reserved == -1); if (n->nkids == 2) cedr_assert(n->level == 1 + std::max(n->kids[0]->level, n->kids[1]->level)); if (n->nkids == 1) cedr_assert(n->level >= 1 + n->kids[0]->level); if (n->nkids == 0) cedr_assert(n->level == 0); if (n->rank != p->rank()) cedr_assert(n->cellidx == -1); else cedr_assert(n->cellidx < nleaf); for (Int k = 0; k < n->nkids; ++k) { cedr_assert(n.get() == n->kids[k]->parent); check_tree(p, n->kids[k], nleaf); } #endif } qlt::tree::Node::Ptr make_tree (const cedr::mpi::Parallel::Ptr& p, const Int nelem, const Int* gid_data, const Int* rank_data, const Int nsublev, const bool use_sgi, const bool cdr_over_super_levels, const Int nsuplev) { auto tree = use_sgi ? make_tree_sgi (p, nelem, gid_data, rank_data, nsublev) : make_tree_non_sgi(p, nelem, gid_data, rank_data, nsublev); Int nleaf = nelem*nsublev; if (cdr_over_super_levels) { tree = combine_superlevels(tree, nleaf, nsuplev); nleaf *= nsuplev; } if (use_sgi) check_tree(p, tree, nleaf); return tree; } Int test_tree_maker () { Int nerr = 0; if (nextpow2(3) != 4) ++nerr; if (nextpow2(4) != 4) ++nerr; if (nextpow2(5) != 8) ++nerr; if (get_tree_height(3) != 3) ++nerr; if (get_tree_height(4) != 3) ++nerr; if (get_tree_height(5) != 4) ++nerr; if (get_tree_height(8) != 4) ++nerr; return nerr; } extern "C" void compose_repro_sum(const Real* send, Real* recv, Int nlocal, Int nfld, Int fcomm); struct ReproSumReducer : public compose::CAAS::UserAllReducer { ReproSumReducer (Int fcomm, Int n_accum_in_place) : fcomm_(fcomm), n_accum_in_place_(n_accum_in_place) {} int n_accum_in_place () const override { return n_accum_in_place_; } int operator() (const cedr::mpi::Parallel& p, Real* sendbuf, Real* rcvbuf, int nlocal, int count, MPI_Op op) const override { cedr_assert(op == MPI_SUM); #ifdef HORIZ_OPENMP # pragma omp barrier # pragma omp master #endif compose_repro_sum(sendbuf, rcvbuf, nlocal, count, fcomm_); #ifdef HORIZ_OPENMP # pragma omp barrier #endif return 0; } private: const Int fcomm_, n_accum_in_place_; }; struct CDR { typedef std::shared_ptr<CDR> Ptr; typedef compose::QLT<ComposeDefaultExecutionSpace> QLTT; typedef compose::CAAS CAAST; struct Alg { enum Enum { qlt, qlt_super_level, qlt_super_level_local_caas, caas, caas_super_level }; static Enum convert (Int cdr_alg) { switch (cdr_alg) { case 2: return qlt; case 20: return qlt_super_level; case 21: return qlt_super_level_local_caas; case 3: return caas; case 30: return caas_super_level; case 42: return caas_super_level; // actually none default: cedr_throw_if(true, "cdr_alg " << cdr_alg << " is invalid."); } } static bool is_qlt (Enum e) { return (e == qlt || e == qlt_super_level || e == qlt_super_level_local_caas); } static bool is_caas (Enum e) { return e == caas || e == caas_super_level; } static bool is_suplev (Enum e) { return (e == qlt_super_level || e == caas_super_level || e == qlt_super_level_local_caas); } }; enum { nsublev_per_suplev = 8 }; const Alg::Enum alg; const Int ncell, nlclcell, nlev, nsublev, nsuplev; const bool threed, cdr_over_super_levels, caas_in_suplev, hard_zero; const cedr::mpi::Parallel::Ptr p; qlt::tree::Node::Ptr tree; // Don't need this except for unit testing. cedr::CDR::Ptr cdr; std::vector<Int> ie2gci; // Map Homme ie to Homme global cell index. std::vector<Int> ie2lci; // Map Homme ie to CDR local cell index (lclcellidx). std::vector<char> nonneg; CDR (Int cdr_alg_, Int ngblcell_, Int nlclcell_, Int nlev_, bool use_sgi, bool independent_time_steps, const bool hard_zero_, const Int* gid_data, const Int* rank_data, const cedr::mpi::Parallel::Ptr& p_, Int fcomm) : alg(Alg::convert(cdr_alg_)), ncell(ngblcell_), nlclcell(nlclcell_), nlev(nlev_), nsublev(Alg::is_suplev(alg) ? nsublev_per_suplev : 1), nsuplev((nlev + nsublev - 1) / nsublev), threed(independent_time_steps), cdr_over_super_levels(threed && Alg::is_caas(alg)), caas_in_suplev(alg == Alg::qlt_super_level_local_caas && nsublev > 1), hard_zero(hard_zero_), p(p_), inited_tracers_(false) { const Int n_id_in_suplev = caas_in_suplev ? 1 : nsublev; if (Alg::is_qlt(alg)) { tree = make_tree(p, ncell, gid_data, rank_data, n_id_in_suplev, use_sgi, cdr_over_super_levels, nsuplev); cedr::CDR::Options options; options.prefer_numerical_mass_conservation_to_numerical_bounds = true; Int nleaf = ncell*n_id_in_suplev; if (cdr_over_super_levels) nleaf *= nsuplev; cdr = std::make_shared<QLTT>(p, nleaf, tree, options, threed ? nsuplev : 0); tree = nullptr; } else if (Alg::is_caas(alg)) { const Int n_accum_in_place = n_id_in_suplev*(cdr_over_super_levels ? nsuplev : 1); const auto caas = std::make_shared<CAAST>( p, nlclcell*n_accum_in_place, std::make_shared<ReproSumReducer>(fcomm, n_accum_in_place)); cdr = caas; } else { cedr_throw_if(true, "Invalid semi_lagrange_cdr_alg " << alg); } ie2gci.resize(nlclcell); } void init_tracers (const Int qsize, const bool need_conservation) { nonneg.resize(qsize, hard_zero); typedef cedr::ProblemType PT; const Int nt = cdr_over_super_levels ? qsize : nsuplev*qsize; for (Int ti = 0; ti < nt; ++ti) cdr->declare_tracer(PT::shapepreserve | (need_conservation ? PT::conserve : 0), 0); cdr->end_tracer_declarations(); } void get_buffers_sizes (size_t& s1, size_t &s2) { cdr->get_buffers_sizes(s1, s2); } void set_buffers (Real* b1, Real* b2) { cdr->set_buffers(b1, b2); cdr->finish_setup(); } private: bool inited_tracers_; }; void set_ie2gci (CDR& q, const Int ie, const Int gci) { q.ie2gci[ie] = gci; } void init_ie2lci (CDR& q) { const Int n_id_in_suplev = q.caas_in_suplev ? 1 : q.nsublev; const Int nleaf = n_id_in_suplev* q.ie2gci.size()* (q.cdr_over_super_levels ? q.nsuplev : 1); q.ie2lci.resize(nleaf); if (CDR::Alg::is_qlt(q.alg)) { auto qlt = std::static_pointer_cast<CDR::QLTT>(q.cdr); if (q.cdr_over_super_levels) { const auto nlevwrem = q.nsuplev*n_id_in_suplev; for (size_t ie = 0; ie < q.ie2gci.size(); ++ie) for (Int spli = 0; spli < q.nsuplev; ++spli) for (Int sbli = 0; sbli < n_id_in_suplev; ++sbli) // local indexing is fastest over the whole column q.ie2lci[nlevwrem*ie + n_id_in_suplev*spli + sbli] = // but global indexing is organized according to the tree qlt->gci2lci(n_id_in_suplev*(q.ncell*spli + q.ie2gci[ie]) + sbli); } else { for (size_t ie = 0; ie < q.ie2gci.size(); ++ie) for (Int sbli = 0; sbli < n_id_in_suplev; ++sbli) q.ie2lci[n_id_in_suplev*ie + sbli] = qlt->gci2lci(n_id_in_suplev*q.ie2gci[ie] + sbli); } } else { if (q.cdr_over_super_levels) { const auto nlevwrem = q.nsuplev*n_id_in_suplev; for (size_t ie = 0; ie < q.ie2gci.size(); ++ie) for (Int spli = 0; spli < q.nsuplev; ++spli) for (Int sbli = 0; sbli < n_id_in_suplev; ++sbli) { const Int id = nlevwrem*ie + n_id_in_suplev*spli + sbli; q.ie2lci[id] = id; } } else { for (size_t ie = 0; ie < q.ie2gci.size(); ++ie) for (Int sbli = 0; sbli < n_id_in_suplev; ++sbli) { const Int id = n_id_in_suplev*ie + sbli; q.ie2lci[id] = id; } } } } void init_tracers (CDR& q, const Int nlev, const Int qsize, const bool need_conservation) { q.init_tracers(qsize, need_conservation); } namespace sl { // For sl_advection.F90 // Fortran array wrappers. template <typename T> using FA1 = Kokkos::View<T*, Kokkos::LayoutLeft, Kokkos::HostSpace>; template <typename T> using FA2 = Kokkos::View<T**, Kokkos::LayoutLeft, Kokkos::HostSpace>; template <typename T> using FA3 = Kokkos::View<T***, Kokkos::LayoutLeft, Kokkos::HostSpace>; template <typename T> using FA4 = Kokkos::View<T****, Kokkos::LayoutLeft, Kokkos::HostSpace>; template <typename T> using FA5 = Kokkos::View<T*****, Kokkos::LayoutLeft, Kokkos::HostSpace>; // Following are naming conventions in element_state and sl_advection: // elem(ie)%state%Q(:,:,k,q) is tracer mixing ratio. // elem(ie)%state%dp3d(:,:,k,tl%np1) is essentially total density. // elem(ie)%state%Qdp(:,:,k,q,n0_qdp) is Q*dp3d. // rho(:,:,k,ie) is spheremp*dp3d, essentially total mass at a GLL point. // Hence Q*rho = Q*spheremp*dp3d is tracer mass at a GLL point. // We need to get pointers to some of these; elem can't be given the bind(C) // attribute, so we can't take the elem array directly. We get these quantities // at a mix of previous and current time steps. // In the code that follows, _p is previous and _c is current time step. Q is // renamed to q, and Q is tracer mass at a GLL point. struct Data { typedef std::shared_ptr<Data> Ptr; const Int np, nlev, qsize, qsize_d, timelevels; Int n0_qdp, n1_qdp, tl_np1; std::vector<const Real*> spheremp, dp3d_c; std::vector<Real*> q_c, qdp_pc; const Real* dp0; struct Check { Kokkos::View<Real**, Kokkos::Serial> mass_p, mass_c, mass_lo, mass_hi, q_lo, q_hi, q_min_l, q_max_l, qd_lo, qd_hi; Check (const Int nlev, const Int qsize) : mass_p("mass_p", nlev, qsize), mass_c("mass_c", nlev, qsize), mass_lo("mass_lo", nlev, qsize), mass_hi("mass_hi", nlev, qsize), q_lo("q_lo", nlev, qsize), q_hi("q_hi", nlev, qsize), q_min_l("q_min_l", nlev, qsize), q_max_l("q_max_l", nlev, qsize), qd_lo("qd_lo", nlev, qsize), qd_hi("qd_hi", nlev, qsize) {} }; std::shared_ptr<Check> check; Data (Int lcl_ncell, Int np_, Int nlev_, Int qsize_, Int qsize_d_, Int timelevels_) : np(np_), nlev(nlev_), qsize(qsize_), qsize_d(qsize_d_), timelevels(timelevels_), spheremp(lcl_ncell, nullptr), dp3d_c(lcl_ncell, nullptr), q_c(lcl_ncell, nullptr), qdp_pc(lcl_ncell, nullptr) {} }; static void check (const CDR& q, const Data& d) { cedr_assert(q.nlclcell == static_cast<Int>(d.spheremp.size())); } template <typename T> void insert (std::vector<T*>& r, const Int i, T* v) { cedr_assert(i >= 0 && i < static_cast<int>(r.size())); r[i] = v; } void insert (const Data::Ptr& d, const Int ie, const Int ptridx, Real* array, const Int i0 = 0, const Int i1 = 0) { cedr_assert(d); switch (ptridx) { case 0: insert<const double>(d->spheremp, ie, array); break; case 1: insert< double>(d->qdp_pc, ie, array); d->n0_qdp = i0; d->n1_qdp = i1; break; case 2: insert<const double>(d->dp3d_c, ie, array); d->tl_np1 = i0; break; case 3: insert< double>(d->q_c, ie, array); break; case 4: d->dp0 = array; break; default: cedr_throw_if(true, "Invalid pointer index " << ptridx); } } static void run_cdr (CDR& q) { #ifdef HORIZ_OPENMP # pragma omp barrier #endif q.cdr->run(); #ifdef HORIZ_OPENMP # pragma omp barrier #endif } template <int np_> void accum_values (const Int ie, const Int k, const Int q, const Int tl_np1, const Int n0_qdp, const Int np, const bool nonneg, const FA1<const Real>& spheremp, const FA3<const Real>& dp3d_c, const FA4<Real>& q_min, const FA4<const Real>& q_max, const FA4<const Real>& qdp_p, const FA3<const Real>& q_c, Real& volume, Real& rhom, Real& Qm, Real& Qm_prev, Real& Qm_min, Real& Qm_max) { cedr_assert(np == np_); static const Int np2 = np_*np_; for (Int g = 0; g < np2; ++g) { volume += spheremp(g); // * dp0[k]; const Real rhomij = dp3d_c(g,k,tl_np1) * spheremp(g); rhom += rhomij; Qm += q_c(g,k,q) * rhomij; if (nonneg) q_min(g,k,q,ie) = std::max<Real>(q_min(g,k,q,ie), 0); Qm_min += q_min(g,k,q,ie) * rhomij; Qm_max += q_max(g,k,q,ie) * rhomij; Qm_prev += qdp_p(g,k,q,n0_qdp) * spheremp(g); } } template <int np_> void run_global (CDR& cdr, const Data& d, Real* q_min_r, const Real* q_max_r, const Int nets, const Int nete) { static const Int np2 = np_*np_; const Int np = d.np, nlev = d.nlev, qsize = d.qsize, nlevwrem = cdr.nsuplev*cdr.nsublev; cedr_assert(np == np_); FA4< Real> q_min(q_min_r, np2, nlev, qsize, nete+1); FA4<const Real> q_max(q_max_r, np2, nlev, qsize, nete+1); for (Int ie = nets; ie <= nete; ++ie) { FA1<const Real> spheremp(d.spheremp[ie], np2); FA4<const Real> qdp_p(d.qdp_pc[ie], np2, nlev, d.qsize_d, 2); FA3<const Real> dp3d_c(d.dp3d_c[ie], np2, nlev, d.timelevels); FA3<const Real> q_c(d.q_c[ie], np2, nlev, d.qsize_d); #ifdef COLUMN_OPENMP # pragma omp parallel for #endif for (Int q = 0; q < qsize; ++q) { for (Int spli = 0; spli < cdr.nsuplev; ++spli) { const Int k0 = cdr.nsublev*spli; const bool nonneg = cdr.nonneg[q]; const Int ti = cdr.cdr_over_super_levels ? q : spli*qsize + q; Real Qm = 0, Qm_min = 0, Qm_max = 0, Qm_prev = 0, rhom = 0, volume = 0; Int ie_idx; if (cdr.caas_in_suplev) ie_idx = cdr.cdr_over_super_levels ? cdr.nsuplev*ie + spli : ie; for (Int sbli = 0; sbli < cdr.nsublev; ++sbli) { const auto k = k0 + sbli; if ( ! cdr.caas_in_suplev) ie_idx = cdr.cdr_over_super_levels ? nlevwrem*ie + k : cdr.nsublev*ie + sbli; const auto lci = cdr.ie2lci[ie_idx]; if ( ! cdr.caas_in_suplev) { Qm = 0; Qm_min = 0; Qm_max = 0; Qm_prev = 0; rhom = 0; volume = 0; } if (k < nlev) accum_values<np_>(ie, k, q, d.tl_np1, d.n0_qdp, np, nonneg, spheremp, dp3d_c, q_min, q_max, qdp_p, q_c, volume, rhom, Qm, Qm_prev, Qm_min, Qm_max); const bool write = ! cdr.caas_in_suplev || sbli == cdr.nsublev-1; if (write) { // For now, handle just one rhom. For feasible global problems, // it's used only as a weight vector in QLT, so it's fine. In fact, // use just the cell geometry, rather than total density, since in QLT // this field is used as a weight vector. //todo Generalize to one rhom field per level. Until then, we're not // getting QLT's safety benefit. if (ti == 0) cdr.cdr->set_rhom(lci, 0, volume); cdr.cdr->set_Qm(lci, ti, Qm, Qm_min, Qm_max, Qm_prev); if (Qm_prev < -0.5) { static bool first = true; if (first) { first = false; std::stringstream ss; ss << "Qm_prev < -0.5: Qm_prev = " << Qm_prev << " on rank " << cdr.p->rank() << " at (ie,gid,spli,k0,q,ti,sbli,lci,k,n0_qdp,tl_np1) = (" << ie << "," << cdr.ie2gci[ie] << "," << spli << "," << k0 << "," << q << "," << ti << "," << sbli << "," << lci << "," << k << "," << d.n0_qdp << "," << d.tl_np1 << ")\n"; ss << "Qdp(:,:,k,q,n0_qdp) = ["; for (Int g = 0; g < np2; ++g) ss << " " << qdp_p(g,k,q,d.n0_qdp); ss << "]\n"; ss << "dp3d(:,:,k,tl_np1) = ["; for (Int g = 0; g < np2; ++g) ss << " " << dp3d_c(g,k,d.tl_np1); ss << "]\n"; pr(ss.str()); } } } } } } } run_cdr(cdr); } template <int np_> void solve_local (const Int ie, const Int k, const Int q, const Int tl_np1, const Int n1_qdp, const Int np, const bool scalar_bounds, const Int limiter_option, const FA1<const Real>& spheremp, const FA3<const Real>& dp3d_c, const FA4<const Real>& q_min, const FA4<const Real>& q_max, const Real Qm, FA4<Real>& qdp_c, FA3<Real>& q_c) { cedr_assert(np == np_); static const Int np2 = np_*np_; Real wa[np2], qlo[np2], qhi[np2], y[np2], x[np2]; Real rhom = 0; for (Int g = 0; g < np2; ++g) { const Real rhomij = dp3d_c(g,k,tl_np1) * spheremp(g); rhom += rhomij; wa[g] = rhomij; y[g] = q_c(g,k,q); x[g] = y[g]; } //todo Replace with ReconstructSafely. if (scalar_bounds) { qlo[0] = q_min(0,k,q,ie); qhi[0] = q_max(0,k,q,ie); for (Int i = 1; i < np2; ++i) qlo[i] = qlo[0]; for (Int i = 1; i < np2; ++i) qhi[i] = qhi[0]; // We can use either 2-norm minimization or ClipAndAssuredSum for // the local filter. CAAS is the faster. It corresponds to limiter // = 0. 2-norm minimization is the same in spirit as limiter = 8, // but it assuredly achieves the first-order optimality conditions // whereas limiter 8 does not. if (limiter_option == 8) cedr::local::solve_1eq_bc_qp(np2, wa, wa, Qm, qlo, qhi, y, x); else { // We need to use *some* limiter; if 8 isn't chosen, default to // CAAS. cedr::local::caas(np2, wa, Qm, qlo, qhi, y, x); } } else { for (Int g = 0; g < np2; ++g) { qlo[g] = q_min(g,k,q,ie); qhi[g] = q_max(g,k,q,ie); } for (Int trial = 0; trial < 3; ++trial) { int info; if (limiter_option == 8) { info = cedr::local::solve_1eq_bc_qp( np2, wa, wa, Qm, qlo, qhi, y, x); if (info == 1) info = 0; } else { info = 0; cedr::local::caas(np2, wa, Qm, qlo, qhi, y, x, false /* clip */); // Clip for numerics against the cell extrema. Real qlo_s = qlo[0], qhi_s = qhi[0]; for (Int i = 1; i < np2; ++i) { qlo_s = std::min(qlo_s, qlo[i]); qhi_s = std::max(qhi_s, qhi[i]); } for (Int i = 0; i < np2; ++i) x[i] = cedr::impl::max(qlo_s, cedr::impl::min(qhi_s, x[i])); } if (info == 0 || trial == 1) break; switch (trial) { case 0: { Real qlo_s = qlo[0], qhi_s = qhi[0]; for (Int i = 1; i < np2; ++i) { qlo_s = std::min(qlo_s, qlo[i]); qhi_s = std::max(qhi_s, qhi[i]); } for (Int i = 0; i < np2; ++i) qlo[i] = qlo_s; for (Int i = 0; i < np2; ++i) qhi[i] = qhi_s; } break; case 1: { const Real q = Qm / rhom; for (Int i = 0; i < np2; ++i) qlo[i] = std::min(qlo[i], q); for (Int i = 0; i < np2; ++i) qhi[i] = std::max(qhi[i], q); } break; } } } for (Int g = 0; g < np2; ++g) { q_c(g,k,q) = x[g]; qdp_c(g,k,q,n1_qdp) = q_c(g,k,q) * dp3d_c(g,k,tl_np1); } } Int vertical_caas_backup (const Int n, Real* rhom, const Real q_min, const Real q_max, Real Qmlo_tot, Real Qmhi_tot, const Real Qm_tot, Real* Qmlo, Real* Qmhi, Real* Qm) { Int status = 0; if (Qm_tot < Qmlo_tot || Qm_tot > Qmhi_tot) { if (Qm_tot < Qmlo_tot) { status = -2; for (Int i = 0; i < n; ++i) Qmhi[i] = Qmlo[i]; for (Int i = 0; i < n; ++i) Qmlo[i] = q_min*rhom[i]; Qmlo_tot = 0; for (Int i = 0; i < n; ++i) Qmlo_tot += Qmlo[i]; if (Qm_tot < Qmlo_tot) status = -4; } else { status = -1; for (Int i = 0; i < n; ++i) Qmlo[i] = Qmhi[i]; for (Int i = 0; i < n; ++i) Qmhi[i] = q_max*rhom[i]; Qmhi_tot = 0; for (Int i = 0; i < n; ++i) Qmhi_tot += Qmhi[i]; if (Qm_tot > Qmhi_tot) status = -3; } if (status < -2) { Real rhom_tot = 0; for (Int i = 0; i < n; ++i) rhom_tot += rhom[i]; const Real q = Qm_tot/rhom_tot; for (Int i = 0; i < n; ++i) Qm[i] = q*rhom[i]; return status; } } for (Int i = 0; i < n; ++i) rhom[i] = 1; cedr::local::caas(n, rhom, Qm_tot, Qmlo, Qmhi, Qm, Qm, false); return status; } void accum_values (const Int ie, const Int k, const Int q, const Int tl_np1, const Int n0_qdp, const Int np2, const FA1<const Real>& spheremp, const FA3<const Real>& dp3d_c, const FA4<Real>& q_min, const FA4<const Real>& q_max, const FA4<const Real>& qdp_p, const FA3<const Real>& q_c, Real& rhom, Real& Qm, Real& Qm_min, Real& Qm_max) { for (Int g = 0; g < np2; ++g) { const Real rhomij = dp3d_c(g,k,tl_np1) * spheremp(g); rhom += rhomij; Qm += q_c(g,k,q) * rhomij; Qm_min += q_min(g,k,q,ie) * rhomij; Qm_max += q_max(g,k,q,ie) * rhomij; } } template <int np_> void run_local (CDR& cdr, const Data& d, Real* q_min_r, const Real* q_max_r, const Int nets, const Int nete, const bool scalar_bounds, const Int limiter_option) { static const Int np2 = np_*np_; const Int np = d.np, nlev = d.nlev, qsize = d.qsize, nlevwrem = cdr.nsuplev*cdr.nsublev; cedr_assert(np == np_); FA4< Real> q_min(q_min_r, np2, nlev, qsize, nete+1); FA4<const Real> q_max(q_max_r, np2, nlev, qsize, nete+1); for (Int ie = nets; ie <= nete; ++ie) { FA1<const Real> spheremp(d.spheremp[ie], np2); FA4< Real> qdp_c(d.qdp_pc[ie], np2, nlev, d.qsize_d, 2); FA3<const Real> dp3d_c(d.dp3d_c[ie], np2, nlev, d.timelevels); FA3< Real> q_c(d.q_c[ie], np2, nlev, d.qsize_d); #ifdef COLUMN_OPENMP # pragma omp parallel for #endif for (Int q = 0; q < qsize; ++q) { for (Int spli = 0; spli < cdr.nsuplev; ++spli) { const Int k0 = cdr.nsublev*spli; const Int ti = cdr.cdr_over_super_levels ? q : spli*qsize + q; if (cdr.caas_in_suplev) { const auto ie_idx = cdr.cdr_over_super_levels ? cdr.nsuplev*ie + spli : ie; const auto lci = cdr.ie2lci[ie_idx]; const Real Qm_tot = cdr.cdr->get_Qm(lci, ti); Real Qm_min_tot = 0, Qm_max_tot = 0; Real rhom[CDR::nsublev_per_suplev], Qm[CDR::nsublev_per_suplev], Qm_min[CDR::nsublev_per_suplev], Qm_max[CDR::nsublev_per_suplev]; // Redistribute mass in the vertical direction of the super level. Int n = cdr.nsublev; for (Int sbli = 0; sbli < cdr.nsublev; ++sbli) { const Int k = k0 + sbli; if (k >= nlev) { n = sbli; break; } rhom[sbli] = 0; Qm[sbli] = 0; Qm_min[sbli] = 0; Qm_max[sbli] = 0; accum_values(ie, k, q, d.tl_np1, d.n0_qdp, np2, spheremp, dp3d_c, q_min, q_max, qdp_c, q_c, rhom[sbli], Qm[sbli], Qm_min[sbli], Qm_max[sbli]); Qm_min_tot += Qm_min[sbli]; Qm_max_tot += Qm_max[sbli]; } if (Qm_tot >= Qm_min_tot && Qm_tot <= Qm_max_tot) { for (Int i = 0; i < n; ++i) rhom[i] = 1; cedr::local::caas(n, rhom, Qm_tot, Qm_min, Qm_max, Qm, Qm, false); } else { Real q_min_s, q_max_s; bool first = true; for (Int sbli = 0; sbli < n; ++sbli) { const Int k = k0 + sbli; for (Int g = 0; g < np2; ++g) { if (first) { q_min_s = q_min(g,k,q,ie); q_max_s = q_max(g,k,q,ie); first = false; } else { q_min_s = std::min(q_min_s, q_min(g,k,q,ie)); q_max_s = std::max(q_max_s, q_max(g,k,q,ie)); } } } vertical_caas_backup(n, rhom, q_min_s, q_max_s, Qm_min_tot, Qm_max_tot, Qm_tot, Qm_min, Qm_max, Qm); } // Redistribute mass in the horizontal direction of each level. for (Int i = 0; i < n; ++i) { const Int k = k0 + i; solve_local<np_>(ie, k, q, d.tl_np1, d.n1_qdp, np, scalar_bounds, limiter_option, spheremp, dp3d_c, q_min, q_max, Qm[i], qdp_c, q_c); } } else { for (Int sbli = 0; sbli < cdr.nsublev; ++sbli) { const Int k = k0 + sbli; if (k >= nlev) break; const auto ie_idx = cdr.cdr_over_super_levels ? nlevwrem*ie + k : cdr.nsublev*ie + sbli; const auto lci = cdr.ie2lci[ie_idx]; const Real Qm = cdr.cdr->get_Qm(lci, ti); solve_local<np_>(ie, k, q, d.tl_np1, d.n1_qdp, np, scalar_bounds, limiter_option, spheremp, dp3d_c, q_min, q_max, Qm, qdp_c, q_c); } } } } } } void check (CDR& cdr, Data& d, const Real* q_min_r, const Real* q_max_r, const Int nets, const Int nete) { using cedr::mpi::reduce; const Int np = d.np, nlev = d.nlev, nsuplev = cdr.nsuplev, qsize = d.qsize, nprob = cdr.threed ? 1 : nsuplev; Kokkos::View<Real**, Kokkos::Serial> mass_p("mass_p", nprob, qsize), mass_c("mass_c", nprob, qsize), mass_lo("mass_lo", nprob, qsize), mass_hi("mass_hi", nprob, qsize), q_lo("q_lo", nprob, qsize), q_hi("q_hi", nprob, qsize), q_min_l("q_min_l", nprob, qsize), q_max_l("q_max_l", nprob, qsize), qd_lo("qd_lo", nprob, qsize), qd_hi("qd_hi", nprob, qsize); FA5<const Real> q_min(q_min_r, np, np, nlev, qsize, nete+1), q_max(q_max_r, np, np, nlev, qsize, nete+1); Kokkos::deep_copy(q_lo, 1e200); Kokkos::deep_copy(q_hi, -1e200); Kokkos::deep_copy(q_min_l, 1e200); Kokkos::deep_copy(q_max_l, -1e200); Kokkos::deep_copy(qd_lo, 0); Kokkos::deep_copy(qd_hi, 0); Int iprob = 0; bool fp_issue = false; // Limit output once the first issue is seen. for (Int ie = nets; ie <= nete; ++ie) { FA2<const Real> spheremp(d.spheremp[ie], np, np); FA5<const Real> qdp_pc(d.qdp_pc[ie], np, np, nlev, d.qsize_d, 2); FA4<const Real> dp3d_c(d.dp3d_c[ie], np, np, nlev, d.timelevels); FA4<const Real> q_c(d.q_c[ie], np, np, nlev, d.qsize_d); for (Int spli = 0; spli < nsuplev; ++spli) { if (nprob > 1) iprob = spli; for (Int k = spli*cdr.nsublev; k < (spli+1)*cdr.nsublev; ++k) { if (k >= nlev) continue; if ( ! fp_issue) { for (Int j = 0; j < np; ++j) for (Int i = 0; i < np; ++i) { // FP issues. if (std::isnan(dp3d_c(i,j,k,d.tl_np1))) { pr("dp3d NaN:" pu(k) pu(i) pu(j)); fp_issue = true; } if (std::isinf(dp3d_c(i,j,k,d.tl_np1))) { pr("dp3d Inf:" pu(k) pu(i) pu(j)); fp_issue = true; } } } for (Int q = 0; q < qsize; ++q) { Real qlo_s = q_min(0,0,k,q,ie), qhi_s = q_max(0,0,k,q,ie); for (Int j = 0; j < np; ++j) for (Int i = 0; i < np; ++i) { qlo_s = std::min(qlo_s, q_min(i,j,k,q,ie)); qhi_s = std::max(qhi_s, q_max(i,j,k,q,ie)); } for (Int j = 0; j < np; ++j) for (Int i = 0; i < np; ++i) { // FP issues. if ( ! fp_issue) { for (Int i_qdp : {0, 1}) { const Int n_qdp = i_qdp == 0 ? d.n0_qdp : d.n1_qdp; if (std::isnan(qdp_pc(i,j,k,q,n_qdp))) { pr("qdp NaN:" puf(i_qdp) pu(q) pu(k) pu(i) pu(j)); fp_issue = true; } if (std::isinf(qdp_pc(i,j,k,q,n_qdp))) { pr("qdp Inf:" puf(i_qdp) pu(q) pu(k) pu(i) pu(j)); fp_issue = true; } } if (std::isnan(q_c(i,j,k,q))) { pr("q NaN:" pu(q) pu(k) pu(i) pu(j)); fp_issue = true; } if (std::isinf(q_c(i,j,k,q))) { pr("q Inf:" pu(q) pu(k) pu(i) pu(j)); fp_issue = true; } } // Mass conservation. mass_p(iprob,q) += qdp_pc(i,j,k,q,d.n0_qdp) * spheremp(i,j); mass_c(iprob,q) += qdp_pc(i,j,k,q,d.n1_qdp) * spheremp(i,j); // Local bound constraints w.r.t. cell-local extrema. if (q_c(i,j,k,q) < qlo_s) qd_lo(iprob,q) = std::max(qd_lo(iprob,q), qlo_s - q_c(i,j,k,q)); if (q_c(i,j,k,q) > qhi_s) qd_hi(iprob,q) = std::max(qd_hi(iprob,q), q_c(i,j,k,q) - qhi_s); // Safety problem bound constraints. mass_lo(iprob,q) += (q_min(i,j,k,q,ie) * dp3d_c(i,j,k,d.tl_np1) * spheremp(i,j)); mass_hi(iprob,q) += (q_max(i,j,k,q,ie) * dp3d_c(i,j,k,d.tl_np1) * spheremp(i,j)); q_lo(iprob,q) = std::min(q_lo(iprob,q), q_min(i,j,k,q,ie)); q_hi(iprob,q) = std::max(q_hi(iprob,q), q_max(i,j,k,q,ie)); q_min_l(iprob,q) = std::min(q_min_l(iprob,q), q_min(i,j,k,q,ie)); q_max_l(iprob,q) = std::max(q_max_l(iprob,q), q_max(i,j,k,q,ie)); } } } } } #ifdef HORIZ_OPENMP # pragma omp barrier # pragma omp master #endif { if ( ! d.check) d.check = std::make_shared<Data::Check>(nprob, qsize); auto& c = *d.check; Kokkos::deep_copy(c.mass_p, 0); Kokkos::deep_copy(c.mass_c, 0); Kokkos::deep_copy(c.mass_lo, 0); Kokkos::deep_copy(c.mass_hi, 0); Kokkos::deep_copy(c.q_lo, 1e200); Kokkos::deep_copy(c.q_hi, -1e200); Kokkos::deep_copy(c.q_min_l, 1e200); Kokkos::deep_copy(c.q_max_l, -1e200); Kokkos::deep_copy(c.qd_lo, 0); Kokkos::deep_copy(c.qd_hi, 0); } #ifdef HORIZ_OPENMP # pragma omp barrier # pragma omp critical #endif { auto& c = *d.check; for (Int spli = 0; spli < nprob; ++spli) { if (nprob > 1) iprob = spli; for (Int q = 0; q < qsize; ++q) { c.mass_p(iprob,q) += mass_p(iprob,q); c.mass_c(iprob,q) += mass_c(iprob,q); c.qd_lo(iprob,q) = std::max(c.qd_lo(iprob,q), qd_lo(iprob,q)); c.qd_hi(iprob,q) = std::max(c.qd_hi(iprob,q), qd_hi(iprob,q)); c.mass_lo(iprob,q) += mass_lo(iprob,q); c.mass_hi(iprob,q) += mass_hi(iprob,q); c.q_lo(iprob,q) = std::min(c.q_lo(iprob,q), q_lo(iprob,q)); c.q_hi(iprob,q) = std::max(c.q_hi(iprob,q), q_hi(iprob,q)); c.q_min_l(iprob,q) = std::min(c.q_min_l(iprob,q), q_min_l(iprob,q)); c.q_max_l(iprob,q) = std::max(c.q_max_l(iprob,q), q_max_l(iprob,q)); } } } #ifdef HORIZ_OPENMP # pragma omp barrier # pragma omp master #endif { Kokkos::View<Real**, Kokkos::Serial> mass_p_g("mass_p_g", nprob, qsize), mass_c_g("mass_c_g", nprob, qsize), mass_lo_g("mass_lo_g", nprob, qsize), mass_hi_g("mass_hi_g", nprob, qsize), q_lo_g("q_lo_g", nprob, qsize), q_hi_g("q_hi_g", nprob, qsize), q_min_g("q_min_g", nprob, qsize), q_max_g("q_max_g", nprob, qsize), qd_lo_g("qd_lo_g", nprob, qsize), qd_hi_g("qd_hi_g", nprob, qsize); const auto& p = *cdr.p; const auto& c = *d.check; const auto root = cdr.p->root(); const auto N = nprob*qsize; reduce(p, c.mass_p.data(), mass_p_g.data(), N, MPI_SUM, root); reduce(p, c.mass_c.data(), mass_c_g.data(), N, MPI_SUM, root); reduce(p, c.qd_lo.data(), qd_lo_g.data(), N, MPI_MAX, root); reduce(p, c.qd_hi.data(), qd_hi_g.data(), N, MPI_MAX, root); // Safety problem. reduce(p, c.mass_lo.data(), mass_lo_g.data(), N, MPI_SUM, root); reduce(p, c.mass_hi.data(), mass_hi_g.data(), N, MPI_SUM, root); reduce(p, c.q_lo.data(), q_lo_g.data(), N, MPI_MIN, root); reduce(p, c.q_hi.data(), q_hi_g.data(), N, MPI_MAX, root); reduce(p, c.q_min_l.data(), q_min_g.data(), N, MPI_MIN, root); reduce(p, c.q_max_l.data(), q_max_g.data(), N, MPI_MAX, root); if (cdr.p->amroot()) { const Real tol = 1e4*std::numeric_limits<Real>::epsilon(); for (Int k = 0; k < nprob; ++k) for (Int q = 0; q < qsize; ++q) { const Real rd = cedr::util::reldif(mass_p_g(k,q), mass_c_g(k,q)); if (rd > tol) pr(puf(k) pu(q) pu(mass_p_g(k,q)) pu(mass_c_g(k,q)) pu(rd)); if (mass_lo_g(k,q) <= mass_c_g(k,q) && mass_c_g(k,q) <= mass_hi_g(k,q)) { // Local problems should be feasible. if (qd_lo_g(k,q) > 0) pr(puf(k) pu(q) pu(qd_lo_g(k,q))); if (qd_hi_g(k,q) > 0) pr(puf(k) pu(q) pu(qd_hi_g(k,q))); } else { // Safety problem must hold. if (q_lo_g(k,q) < q_min_g(k,q)) pr(puf(k) pu(q) pu(q_lo_g(k,q) - q_min_g(k,q)) pu(q_min_g(k,q))); if (q_hi_g(k,q) > q_max_g(k,q)) pr(puf(k) pu(q) pu(q_max_g(k,q) - q_hi_g(k,q)) pu(q_max_g(k,q))); } } } } } } // namespace sl } // namespace homme // Interface for Homme, through compose_mod.F90. extern "C" void kokkos_init () { Kokkos::InitArguments args; args.disable_warnings = true; Kokkos::initialize(args); } extern "C" void kokkos_finalize () { Kokkos::finalize(); } static homme::CDR::Ptr g_cdr; extern "C" void cedr_init_impl (const homme::Int fcomm, const homme::Int cdr_alg, const bool use_sgi, const homme::Int* gid_data, const homme::Int* rank_data, const homme::Int gbl_ncell, const homme::Int lcl_ncell, const homme::Int nlev, const bool independent_time_steps, const bool hard_zero, const homme::Int, const homme::Int) { const auto p = cedr::mpi::make_parallel(MPI_Comm_f2c(fcomm)); g_cdr = std::make_shared<homme::CDR>( cdr_alg, gbl_ncell, lcl_ncell, nlev, use_sgi, independent_time_steps, hard_zero, gid_data, rank_data, p, fcomm); } extern "C" void cedr_query_bufsz (homme::Int* sendsz, homme::Int* recvsz) { cedr_assert(g_cdr); size_t s1, s2; g_cdr->get_buffers_sizes(s1, s2); *sendsz = static_cast<homme::Int>(s1); *recvsz = static_cast<homme::Int>(s2); } extern "C" void cedr_set_bufs (homme::Real* sendbuf, homme::Real* recvbuf, homme::Int, homme::Int) { g_cdr->set_buffers(sendbuf, recvbuf); } extern "C" void cedr_unittest (const homme::Int fcomm, homme::Int* nerrp) { #if 0 cedr_assert(g_cdr); cedr_assert(g_cdr->tree); auto p = cedr::mpi::make_parallel(MPI_Comm_f2c(fcomm)); if (homme::CDR::Alg::is_qlt(g_cdr->alg)) *nerrp = cedr::qlt::test::test_qlt(p, g_cdr->tree, g_cdr->nsublev*g_cdr->ncell, 1, false, false, true, false); else *nerrp = cedr::caas::test::unittest(p); #endif *nerrp += homme::test_tree_maker(); *nerrp += homme::CDR::QLTT::unittest(); } extern "C" void cedr_set_ie2gci (const homme::Int ie, const homme::Int gci) { cedr_assert(g_cdr); // Now is a good time to drop the tree, whose persistence was used for unit // testing if at all. g_cdr->tree = nullptr; homme::set_ie2gci(*g_cdr, ie - 1, gci - 1); } static homme::sl::Data::Ptr g_sl; extern "C" homme::Int cedr_sl_init ( const homme::Int np, const homme::Int nlev, const homme::Int qsize, const homme::Int qsized, const homme::Int timelevels, const homme::Int need_conservation) { cedr_assert(g_cdr); g_sl = std::make_shared<homme::sl::Data>(g_cdr->nlclcell, np, nlev, qsize, qsized, timelevels); homme::init_ie2lci(*g_cdr); homme::init_tracers(*g_cdr, nlev, qsize, need_conservation); homme::sl::check(*g_cdr, *g_sl); return 1; } extern "C" void cedr_sl_set_pointers_begin (homme::Int nets, homme::Int nete) {} extern "C" void cedr_sl_set_spheremp (homme::Int ie, homme::Real* v) { homme::sl::insert(g_sl, ie - 1, 0, v); } extern "C" void cedr_sl_set_qdp (homme::Int ie, homme::Real* v, homme::Int n0_qdp, homme::Int n1_qdp) { homme::sl::insert(g_sl, ie - 1, 1, v, n0_qdp - 1, n1_qdp - 1); } extern "C" void cedr_sl_set_dp3d (homme::Int ie, homme::Real* v, homme::Int tl_np1) { homme::sl::insert(g_sl, ie - 1, 2, v, tl_np1 - 1); } extern "C" void cedr_sl_set_dp (homme::Int ie, homme::Real* v) { homme::sl::insert(g_sl, ie - 1, 2, v, 0); } extern "C" void cedr_sl_set_q (homme::Int ie, homme::Real* v) { homme::sl::insert(g_sl, ie - 1, 3, v); } extern "C" void cedr_sl_set_dp0 (homme::Real* v) { homme::sl::insert(g_sl, 0, 4, v); } extern "C" void cedr_sl_set_pointers_end () {} // Run QLT. extern "C" void cedr_sl_run (homme::Real* minq, const homme::Real* maxq, homme::Int nets, homme::Int nete) { cedr_assert(minq != maxq); cedr_assert(g_cdr); cedr_assert(g_sl); homme::sl::run_global<4>(*g_cdr, *g_sl, minq, maxq, nets-1, nete-1); } // Run the cell-local limiter problem. extern "C" void cedr_sl_run_local (homme::Real* minq, const homme::Real* maxq, homme::Int nets, homme::Int nete, homme::Int use_ir, homme::Int limiter_option) { cedr_assert(minq != maxq); cedr_assert(g_cdr); cedr_assert(g_sl); homme::sl::run_local<4>(*g_cdr, *g_sl, minq, maxq, nets-1, nete-1, use_ir, limiter_option); } // Check properties for this transport step. extern "C" void cedr_sl_check (const homme::Real* minq, const homme::Real* maxq, homme::Int nets, homme::Int nete) { cedr_assert(g_cdr); cedr_assert(g_sl); homme::sl::check(*g_cdr, *g_sl, minq, maxq, nets-1, nete-1); } extern "C" void cedr_finalize () { g_sl = nullptr; g_cdr = nullptr; }
230,744
93,504
// Copyright (c) 2007-2021 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include <pika/config.hpp> #include <pika/allocator_support/internal_allocator.hpp> #include <pika/async_base/dataflow.hpp> #include <pika/async_base/launch_policy.hpp> #include <pika/async_base/traits/is_launch_policy.hpp> #include <pika/coroutines/detail/get_stack_pointer.hpp> #include <pika/datastructures/tuple.hpp> #include <pika/errors/try_catch_exception_ptr.hpp> #include <pika/execution/executors/execution.hpp> #include <pika/execution_base/traits/is_executor.hpp> #include <pika/executors/parallel_executor.hpp> #include <pika/functional/deferred_call.hpp> #include <pika/functional/invoke_fused.hpp> #include <pika/functional/traits/get_function_annotation.hpp> #include <pika/functional/traits/is_action.hpp> #include <pika/futures/detail/future_transforms.hpp> #include <pika/futures/future.hpp> #include <pika/futures/traits/acquire_future.hpp> #include <pika/futures/traits/future_access.hpp> #include <pika/futures/traits/is_future.hpp> #include <pika/modules/memory.hpp> #include <pika/pack_traversal/pack_traversal_async.hpp> #include <pika/threading_base/annotated_function.hpp> #include <pika/threading_base/thread_num_tss.hpp> #include <cstddef> #include <exception> #include <functional> #include <memory> #include <type_traits> #include <utility> /////////////////////////////////////////////////////////////////////////////// // forward declare the type we will get function annotations from namespace pika::detail { template <typename Frame> struct dataflow_finalization; } // namespace pika::lcos::detail namespace pika { namespace traits { #if defined(PIKA_HAVE_THREAD_DESCRIPTION) /////////////////////////////////////////////////////////////////////////// // traits specialization to get annotation from dataflow_finalization template <typename Frame> struct get_function_annotation<pika::detail::dataflow_finalization<Frame>> { using function_type = typename Frame::function_type; // static constexpr char const* call( pika::detail::dataflow_finalization<Frame> const& f) noexcept { char const* annotation = pika::traits::get_function_annotation< typename std::decay<function_type>::type>::call(f.this_->func_); return annotation; } }; #endif }} // namespace pika::traits /////////////////////////////////////////////////////////////////////////////// namespace pika::detail { template <typename Frame> struct dataflow_finalization { // explicit dataflow_finalization(Frame* df) : this_(df) { } using is_void = typename Frame::is_void; // template <typename Futures> void operator()(Futures&& futures) const { return this_->execute(is_void{}, PIKA_FORWARD(Futures, futures)); } // keep the dataflow frame alive with this pointer reference pika::intrusive_ptr<Frame> this_; }; template <typename F, typename Args> struct dataflow_not_callable { static auto error(F f, Args args) { pika::util::invoke_fused(PIKA_MOVE(f), PIKA_MOVE(args)); } using type = decltype(error(std::declval<F>(), std::declval<Args>())); }; /////////////////////////////////////////////////////////////////////// template <bool IsAction, typename Policy, typename F, typename Args, typename Enable = void> struct dataflow_return_impl { using type = typename dataflow_not_callable<F, Args>::type; }; template <typename Policy, typename F, typename Args> struct dataflow_return_impl< /*IsAction=*/false, Policy, F, Args, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { using type = pika::future< typename util::detail::invoke_fused_result<F, Args>::type>; }; template <typename Executor, typename F, typename Args> struct dataflow_return_impl_executor; template <typename Executor, typename F, typename... Ts> struct dataflow_return_impl_executor<Executor, F, pika::tuple<Ts...>> { using type = decltype(pika::parallel::execution::async_execute( std::declval<Executor&&>(), std::declval<F>(), std::declval<Ts>()...)); }; template <typename Policy, typename F, typename Args> struct dataflow_return_impl< /*IsAction=*/false, Policy, F, Args, typename std::enable_if<traits::is_one_way_executor<Policy>::value || traits::is_two_way_executor<Policy>::value>::type> : dataflow_return_impl_executor<Policy, F, Args> { }; template <typename Policy, typename F, typename Args> struct dataflow_return : detail::dataflow_return_impl<traits::is_action<F>::value, Policy, F, Args> { }; template <typename Executor, typename Frame, typename Func, typename Futures, typename Enable = void> struct has_dataflow_finalize : std::false_type { }; template <typename Executor, typename Frame, typename Func, typename Futures> struct has_dataflow_finalize<Executor, Frame, Func, Futures, std::void_t<decltype(std::declval<Executor>().dataflow_finalize( std::declval<Frame>(), std::declval<Func>(), std::declval<Futures>()))>> : std::true_type { }; /////////////////////////////////////////////////////////////////////////// template <typename Policy, typename Func, typename Futures> struct dataflow_frame //-V690 : pika::lcos::detail::future_data<typename pika::traits::future_traits< typename detail::dataflow_return<Policy, Func, Futures>::type>::type> { using type = typename detail::dataflow_return<Policy, Func, Futures>::type; using result_type = typename pika::traits::future_traits<type>::type; using base_type = pika::lcos::detail::future_data<result_type>; using is_void = std::is_void<result_type>; using function_type = Func; using dataflow_type = dataflow_frame<Policy, Func, Futures>; friend struct dataflow_finalization<dataflow_type>; friend struct traits::get_function_annotation< dataflow_finalization<dataflow_type>>; private: // workaround gcc regression wrongly instantiating constructors dataflow_frame(); dataflow_frame(dataflow_frame const&); public: using init_no_addref = typename base_type::init_no_addref; /// A struct to construct the dataflow_frame in-place struct construction_data { Policy policy_; Func func_; }; /// Construct the dataflow_frame from the given policy /// and callable object. static construction_data construct_from(Policy policy, Func func) { return construction_data{PIKA_MOVE(policy), PIKA_MOVE(func)}; } explicit dataflow_frame(construction_data data) : base_type(init_no_addref{}) , policy_(PIKA_MOVE(data.policy_)) , func_(PIKA_MOVE(data.func_)) { } private: /////////////////////////////////////////////////////////////////////// /// Passes the futures into the evaluation function and /// sets the result future. template <typename Futures_> PIKA_FORCEINLINE void execute(std::false_type, Futures_&& futures) { pika::detail::try_catch_exception_ptr( [&]() { this->set_data(util::invoke_fused( PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures))); }, [&](std::exception_ptr ep) { this->set_exception(PIKA_MOVE(ep)); }); } /// Passes the futures into the evaluation function and /// sets the result future. template <typename Futures_> PIKA_FORCEINLINE void execute(std::true_type, Futures_&& futures) { pika::detail::try_catch_exception_ptr( [&]() { util::invoke_fused( PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures)); this->set_data(util::unused_type()); }, [&](std::exception_ptr ep) { this->set_exception(PIKA_MOVE(ep)); }); } /////////////////////////////////////////////////////////////////////// template <typename Futures_> void finalize(pika::detail::async_policy policy, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::execution::parallel_policy_executor<launch::async_policy> exec{policy}; exec.post(PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Futures_> void finalize(pika::detail::fork_policy policy, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::execution::parallel_policy_executor<launch::fork_policy> exec{ policy}; exec.post(PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Futures_> PIKA_FORCEINLINE void finalize( pika::detail::sync_policy, Futures_&& futures) { // We need to run the completion on a new thread if we are on a // non pika thread. bool recurse_asynchronously = pika::threads::get_self_ptr() == nullptr; #if defined(PIKA_HAVE_THREADS_GET_STACK_POINTER) recurse_asynchronously = !this_thread::has_sufficient_stack_space(); #else struct handle_continuation_recursion_count { handle_continuation_recursion_count() : count_(threads::get_continuation_recursion_count()) { ++count_; } ~handle_continuation_recursion_count() { --count_; } std::size_t& count_; } cnt; recurse_asynchronously = recurse_asynchronously || cnt.count_ > PIKA_CONTINUATION_MAX_RECURSION_DEPTH; #endif if (!recurse_asynchronously) { pika::scoped_annotation annotate(func_); execute(is_void{}, PIKA_FORWARD(Futures_, futures)); } else { finalize(pika::launch::async, PIKA_FORWARD(Futures_, futures)); } } template <typename Futures_> void finalize(launch policy, Futures_&& futures) { if (policy == launch::sync) { finalize(launch::sync, PIKA_FORWARD(Futures_, futures)); } else if (policy == launch::fork) { finalize(launch::fork, PIKA_FORWARD(Futures_, futures)); } else { finalize(launch::async, PIKA_FORWARD(Futures_, futures)); } } // The overload for pika::dataflow taking an executor simply forwards // to the corresponding executor customization point. template <typename Executor, typename Futures_> PIKA_FORCEINLINE typename std::enable_if< (traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value) && !has_dataflow_finalize<Executor, dataflow_frame, Func, Futures_>::value>::type finalize(Executor&& exec, Futures_&& futures) { detail::dataflow_finalization<dataflow_type> this_f_(this); pika::parallel::execution::post(PIKA_FORWARD(Executor, exec), PIKA_MOVE(this_f_), PIKA_FORWARD(Futures_, futures)); } template <typename Executor, typename Futures_> PIKA_FORCEINLINE typename std::enable_if< (traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value) && has_dataflow_finalize<Executor, dataflow_frame, Func, Futures_>::value>::type finalize(Executor&& exec, Futures_&& futures) { #if defined(PIKA_CUDA_VERSION) std::forward<Executor>(exec) #else PIKA_FORWARD(Executor, exec) #endif .dataflow_finalize( this, PIKA_MOVE(func_), PIKA_FORWARD(Futures_, futures)); } public: /// Check whether the current future is ready template <typename T> auto operator()(util::async_traverse_visit_tag, T&& current) -> decltype(async_visit_future(PIKA_FORWARD(T, current))) { return async_visit_future(PIKA_FORWARD(T, current)); } /// Detach the current execution context and continue when the /// current future was set to be ready. template <typename T, typename N> auto operator()(util::async_traverse_detach_tag, T&& current, N&& next) -> decltype(async_detach_future( PIKA_FORWARD(T, current), PIKA_FORWARD(N, next))) { return async_detach_future( PIKA_FORWARD(T, current), PIKA_FORWARD(N, next)); } /// Finish the dataflow when the traversal has finished template <typename Futures_> PIKA_FORCEINLINE void operator()( util::async_traverse_complete_tag, Futures_&& futures) { finalize(policy_, PIKA_FORWARD(Futures_, futures)); } private: Policy policy_; Func func_; }; /////////////////////////////////////////////////////////////////////////// template <typename Policy, typename Func, typename... Ts, typename Frame = dataflow_frame<typename std::decay<Policy>::type, typename std::decay<Func>::type, pika::tuple<typename std::decay<Ts>::type...>>> typename Frame::type create_dataflow( Policy&& policy, Func&& func, Ts&&... ts) { // Create the data which is used to construct the dataflow_frame auto data = Frame::construct_from( PIKA_FORWARD(Policy, policy), PIKA_FORWARD(Func, func)); // Construct the dataflow_frame and traverse // the arguments asynchronously pika::intrusive_ptr<Frame> p = util::traverse_pack_async( util::async_traverse_in_place_tag<Frame>{}, PIKA_MOVE(data), PIKA_FORWARD(Ts, ts)...); using traits::future_access; return future_access<typename Frame::type>::create(PIKA_MOVE(p)); } /////////////////////////////////////////////////////////////////////////// template <typename Allocator, typename Policy, typename Func, typename... Ts, typename Frame = dataflow_frame<typename std::decay<Policy>::type, typename std::decay<Func>::type, pika::tuple<typename std::decay<Ts>::type...>>> typename Frame::type create_dataflow_alloc( Allocator const& alloc, Policy&& policy, Func&& func, Ts&&... ts) { // Create the data which is used to construct the dataflow_frame auto data = Frame::construct_from( PIKA_FORWARD(Policy, policy), PIKA_FORWARD(Func, func)); // Construct the dataflow_frame and traverse // the arguments asynchronously pika::intrusive_ptr<Frame> p = util::traverse_pack_async_allocator( alloc, util::async_traverse_in_place_tag<Frame>{}, PIKA_MOVE(data), PIKA_FORWARD(Ts, ts)...); using traits::future_access; return future_access<typename Frame::type>::create(PIKA_MOVE(p)); } /////////////////////////////////////////////////////////////////////////// template <bool IsAction, typename Policy, typename Enable = void> struct dataflow_dispatch_impl; // launch template <typename Policy> struct dataflow_dispatch_impl<false, Policy, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { template <typename Allocator, typename Policy_, typename F, typename... Ts> PIKA_FORCEINLINE static decltype(auto) call( Allocator const& alloc, Policy_&& policy, F&& f, Ts&&... ts) { return detail::create_dataflow_alloc(alloc, PIKA_FORWARD(Policy_, policy), PIKA_FORWARD(F, f), traits::acquire_future_disp()(PIKA_FORWARD(Ts, ts))...); } }; template <typename Policy> struct dataflow_dispatch<Policy, typename std::enable_if< pika::detail::is_launch_policy<Policy>::value>::type> { template <typename Allocator, typename F, typename... Ts> PIKA_FORCEINLINE static auto call( Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch_impl<false, Policy>::call( alloc, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl<false, Policy>::call( alloc, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } template <typename Allocator, typename P, typename F, typename Id, typename... Ts> PIKA_FORCEINLINE static auto call(Allocator const& alloc, P&& p, F&& f, typename std::enable_if< traits::is_action<typename std::decay<F>::type>::value, Id>::type const& id, Ts&&... ts) -> decltype(dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, Policy>::call(alloc, PIKA_FORWARD(P, p), PIKA_FORWARD(F, f), id, PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, Policy>::call(alloc, PIKA_FORWARD(P, p), PIKA_FORWARD(F, f), id, PIKA_FORWARD(Ts, ts)...); } }; // executors template <typename Executor> struct dataflow_dispatch<Executor, typename std::enable_if<traits::is_one_way_executor<Executor>::value || traits::is_two_way_executor<Executor>::value>::type> { template <typename Allocator, typename Executor_, typename F, typename... Ts> PIKA_FORCEINLINE static decltype(auto) call( Allocator const& alloc, Executor_&& exec, F&& f, Ts&&... ts) { return detail::create_dataflow_alloc(alloc, PIKA_FORWARD(Executor_, exec), PIKA_FORWARD(F, f), traits::acquire_future_disp()(PIKA_FORWARD(Ts, ts))...); } }; // any action, plain function, or function object template <typename FD> struct dataflow_dispatch_impl<false, FD, typename std::enable_if<!pika::detail::is_launch_policy<FD>::value && !(traits::is_one_way_executor<FD>::value || traits::is_two_way_executor<FD>::value)>::type> { template <typename Allocator, typename F, typename... Ts, typename Enable = typename std::enable_if< !traits::is_action<typename std::decay<F>::type>::value>::type> PIKA_FORCEINLINE static auto call(Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch<launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch<launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } }; template <typename FD> struct dataflow_dispatch<FD, typename std::enable_if<!pika::detail::is_launch_policy<FD>::value && !(traits::is_one_way_executor<FD>::value || traits::is_two_way_executor<FD>::value)>::type> { template <typename Allocator, typename F, typename... Ts> PIKA_FORCEINLINE static auto call( Allocator const& alloc, F&& f, Ts&&... ts) -> decltype(dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...)) { return dataflow_dispatch_impl< traits::is_action<typename std::decay<F>::type>::value, launch>::call(alloc, launch::async, PIKA_FORWARD(F, f), PIKA_FORWARD(Ts, ts)...); } }; } // namespace pika::detail
21,081
6,408
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "garnet/lib/far/manifest.h" #include <stdio.h> #include "garnet/lib/far/archive_entry.h" #include "garnet/lib/far/archive_writer.h" #include "lib/fxl/files/file.h" #include "lib/fxl/strings/split_string.h" namespace archive { bool ReadManifest(fxl::StringView path, ArchiveWriter* writer) { std::string manifest; if (!files::ReadFileToString(path.ToString(), &manifest)) { fprintf(stderr, "error: Faile to read '%s'\n", path.ToString().c_str()); return false; } std::vector<fxl::StringView> lines = fxl::SplitString(manifest, "\n", fxl::WhiteSpaceHandling::kKeepWhitespace, fxl::SplitResult::kSplitWantNonEmpty); for (const auto& line : lines) { size_t offset = line.find('='); if (offset == std::string::npos) continue; writer->Add(ArchiveEntry(line.substr(offset + 1).ToString(), line.substr(0, offset).ToString())); } return true; } } // namespace archive
1,140
384
#include "Display.h" #include <kinc/display.h> using namespace Kore; namespace { const int MAXIMUM_DISPLAYS = 16; Display displays[MAXIMUM_DISPLAYS]; } void Display::init() { kinc_display_init(); } Display *Display::primary() { displays[kinc_primary_display()]._index = kinc_primary_display(); return &displays[kinc_primary_display()]; } Display *Display::get(int index) { displays[index]._index = index; return &displays[index]; } int Display::count() { return kinc_count_displays(); } bool Display::available() { return kinc_display_available(_index); } const char *Display::name() { return kinc_display_name(_index); } int Display::x() { return kinc_display_current_mode(_index).x; } int Display::y() { return kinc_display_current_mode(_index).y; } int Display::width() { return kinc_display_current_mode(_index).width; } int Display::height() { return kinc_display_current_mode(_index).height; } int Display::frequency() { return kinc_display_current_mode(_index).frequency; } int Display::pixelsPerInch() { return kinc_display_current_mode(_index).pixels_per_inch; } DisplayMode Display::availableMode(int index) { DisplayMode mode; kinc_display_mode_t kMode = kinc_display_available_mode(_index, index); mode.width = kMode.width; mode.height = kMode.height; mode.frequency = kMode.frequency; mode.bitsPerPixel = kMode.bits_per_pixel; return mode; } int Display::countAvailableModes() { return kinc_display_count_available_modes(_index); } Display::Display() {}
1,509
545
/** * Copyright © 2017 IBM Corporation * * 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 "config.h" #include "argument.hpp" #include "fan.hpp" #include "system.hpp" #include "trust_manager.hpp" #include <sdbusplus/bus.hpp> #include <sdeventplus/event.hpp> #include <sdeventplus/source/signal.hpp> #include <stdplus/signal.hpp> using namespace phosphor::fan::monitor; int main(int argc, char* argv[]) { auto event = sdeventplus::Event::get_default(); auto bus = sdbusplus::bus::new_default(); phosphor::fan::util::ArgumentParser args(argc, argv); if (argc != 2) { args.usage(argv); return 1; } Mode mode; if (args["init"] == "true") { mode = Mode::init; } else if (args["monitor"] == "true") { mode = Mode::monitor; } else { args.usage(argv); return 1; } // Attach the event object to the bus object so we can // handle both sd_events (for the timers) and dbus signals. bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL); System system(mode, bus, event); #ifdef MONITOR_USE_JSON // Enable SIGHUP handling to reload JSON config stdplus::signal::block(SIGHUP); sdeventplus::source::Signal signal(event, SIGHUP, std::bind(&System::sighupHandler, &system, std::placeholders::_1, std::placeholders::_2)); #endif if (mode == Mode::init) { // Fans were initialized to be functional, exit return 0; } return event.loop(); }
2,162
692
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // // ----------------------------------------------------- // Mesh Explorer Miniapp: Explore and manipulate meshes // ----------------------------------------------------- // // This miniapp is a handy tool to examine, visualize and manipulate a given // mesh. Some of its features are: // // - visualizing of mesh materials and individual mesh elements // - mesh scaling, randomization, and general transformation // - manipulation of the mesh curvature // - the ability to simulate parallel partitioning // - quantitative and visual reports of mesh quality // // Compile with: make mesh-explorer // // Sample runs: mesh-explorer // mesh-explorer -m ../../data/beam-tri.mesh // mesh-explorer -m ../../data/star-q2.mesh // mesh-explorer -m ../../data/disc-nurbs.mesh // mesh-explorer -m ../../data/escher-p3.mesh // mesh-explorer -m ../../data/mobius-strip.mesh #include "mfem.hpp" #include <fstream> #include <limits> #include <cstdlib> using namespace mfem; using namespace std; // This transformation can be applied to a mesh with the 't' menu option. void transformation(const Vector &p, Vector &v) { // simple shear transformation double s = 0.1; if (p.Size() == 3) { v(0) = p(0) + s*p(1) + s*p(2); v(1) = p(1) + s*p(2) + s*p(0); v(2) = p(2); } else if (p.Size() == 2) { v(0) = p(0) + s*p(1); v(1) = p(1) + s*p(0); } else { v = p; } } // This function is used with the 'r' menu option, sub-option 'l' to refine a // mesh locally in a region, defined by return values <= region_eps. double region_eps = 1e-8; double region(const Vector &p) { const double x = p(0), y = p(1); // here we describe the region: (x <= 1/4) && (y >= 0) && (y <= 1) return std::max(std::max(x - 0.25, -y), y - 1.0); } // The projection of this function can be plotted with the 'l' menu option double f(const Vector &p) { double x = p(0); double y = p.Size() > 1 ? p(1) : 0.0; double z = p.Size() > 2 ? p(2) : 0.0; if (1) { // torus in the xy-plane const double r_big = 2.0; const double r_small = 1.0; return hypot(r_big - hypot(x, y), z) - r_small; } if (0) { // sphere at the origin: const double r = 1.0; return hypot(hypot(x, y), z) - r; } } Mesh *read_par_mesh(int np, const char *mesh_prefix) { Mesh *mesh; Array<Mesh *> mesh_array; mesh_array.SetSize(np); for (int p = 0; p < np; p++) { ostringstream fname; fname << mesh_prefix << '.' << setfill('0') << setw(6) << p; ifgzstream meshin(fname.str().c_str()); if (!meshin) { cerr << "Can not open mesh file: " << fname.str().c_str() << '!' << endl; for (p--; p >= 0; p--) { delete mesh_array[p]; } return NULL; } mesh_array[p] = new Mesh(meshin, 1, 0); // set element and boundary attributes to be the processor number + 1 if (1) { for (int i = 0; i < mesh_array[p]->GetNE(); i++) { mesh_array[p]->GetElement(i)->SetAttribute(p+1); } for (int i = 0; i < mesh_array[p]->GetNBE(); i++) { mesh_array[p]->GetBdrElement(i)->SetAttribute(p+1); } } } mesh = new Mesh(mesh_array, np); for (int p = 0; p < np; p++) { delete mesh_array[np-1-p]; } mesh_array.DeleteAll(); return mesh; } // Given a 3D mesh, produce a 2D mesh consisting of its boundary elements. Mesh *skin_mesh(Mesh *mesh) { // Determine mapping from vertex to boundary vertex Array<int> v2v(mesh->GetNV()); v2v = -1; for (int i = 0; i < mesh->GetNBE(); i++) { Element *el = mesh->GetBdrElement(i); int *v = el->GetVertices(); int nv = el->GetNVertices(); for (int j = 0; j < nv; j++) { v2v[v[j]] = 0; } } int nbvt = 0; for (int i = 0; i < v2v.Size(); i++) { if (v2v[i] == 0) { v2v[i] = nbvt++; } } // Create a new mesh for the boundary Mesh * bmesh = new Mesh(mesh->Dimension() - 1, nbvt, mesh->GetNBE(), 0, mesh->SpaceDimension()); // Copy vertices to the boundary mesh nbvt = 0; for (int i = 0; i < v2v.Size(); i++) { if (v2v[i] >= 0) { double *c = mesh->GetVertex(i); bmesh->AddVertex(c); nbvt++; } } // Copy elements to the boundary mesh int bv[4]; for (int i = 0; i < mesh->GetNBE(); i++) { Element *el = mesh->GetBdrElement(i); int *v = el->GetVertices(); int nv = el->GetNVertices(); for (int j = 0; j < nv; j++) { bv[j] = v2v[v[j]]; } switch (el->GetGeometryType()) { case Geometry::SEGMENT: bmesh->AddSegment(bv, el->GetAttribute()); break; case Geometry::TRIANGLE: bmesh->AddTriangle(bv, el->GetAttribute()); break; case Geometry::SQUARE: bmesh->AddQuad(bv, el->GetAttribute()); break; default: break; /// This should not happen } } bmesh->FinalizeTopology(); // Copy GridFunction describing nodes if present if (mesh->GetNodes()) { FiniteElementSpace *fes = mesh->GetNodes()->FESpace(); const FiniteElementCollection *fec = fes->FEColl(); if (dynamic_cast<const H1_FECollection*>(fec)) { FiniteElementCollection *fec_copy = FiniteElementCollection::New(fec->Name()); FiniteElementSpace *fes_copy = new FiniteElementSpace(*fes, bmesh, fec_copy); GridFunction *bdr_nodes = new GridFunction(fes_copy); bdr_nodes->MakeOwner(fec_copy); bmesh->NewNodes(*bdr_nodes, true); Array<int> vdofs; Array<int> bvdofs; Vector v; for (int i=0; i<mesh->GetNBE(); i++) { fes->GetBdrElementVDofs(i, vdofs); mesh->GetNodes()->GetSubVector(vdofs, v); fes_copy->GetElementVDofs(i, bvdofs); bdr_nodes->SetSubVector(bvdofs, v); } } else { cout << "\nDiscontinuous nodes not yet supported" << endl; } } return bmesh; } int main (int argc, char *argv[]) { int np = 0; const char *mesh_file = "../../data/beam-hex.mesh"; bool refine = true; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to visualize."); args.AddOption(&np, "-np", "--num-proc", "Load mesh from multiple processors."); args.AddOption(&refine, "-ref", "--refinement", "-no-ref", "--no-refinement", "Prepare the mesh for refinement or not."); args.Parse(); if (!args.Good()) { if (!args.Help()) { args.PrintError(cout); cout << endl; } cout << "Visualize and manipulate a serial mesh:\n" << " mesh-explorer -m <mesh_file>\n" << "Visualize and manipulate a parallel mesh:\n" << " mesh-explorer -np <#proc> -m <mesh_prefix>\n" << endl << "All Options:\n"; args.PrintHelp(cout); return 1; } args.PrintOptions(cout); Mesh *mesh; Mesh *bdr_mesh = NULL; if (np <= 0) { mesh = new Mesh(mesh_file, 1, refine); } else { mesh = read_par_mesh(np, mesh_file); if (mesh == NULL) { return 3; } } int dim = mesh->Dimension(); int sdim = mesh->SpaceDimension(); FiniteElementCollection *bdr_attr_fec = NULL; FiniteElementCollection *attr_fec; if (dim == 2) { attr_fec = new Const2DFECollection; } else { bdr_attr_fec = new Const2DFECollection; attr_fec = new Const3DFECollection; } int print_char = 1; while (1) { if (print_char) { cout << endl; mesh->PrintCharacteristics(); cout << "boundary attribs :"; for (int i = 0; i < mesh->bdr_attributes.Size(); i++) { cout << ' ' << mesh->bdr_attributes[i]; } cout << '\n' << "material attribs :"; for (int i = 0; i < mesh->attributes.Size(); i++) { cout << ' ' << mesh->attributes[i]; } cout << endl; cout << "mesh curvature : "; if (mesh->GetNodalFESpace() != NULL) { cout << mesh->GetNodalFESpace()->FEColl()->Name() << endl; } else { cout << "NONE" << endl; } } print_char = 0; cout << endl; cout << "What would you like to do?\n" "r) Refine\n" "c) Change curvature\n" "s) Scale\n" "t) Transform\n" "j) Jitter\n" "v) View\n" "m) View materials\n" "b) View boundary\n" "e) View elements\n" "h) View element sizes, h\n" "k) View element ratios, kappa\n" "l) Plot a function\n" "x) Print sub-element stats\n" "f) Find physical point in reference space\n" "p) Generate a partitioning\n" "o) Reorder elements\n" "S) Save in MFEM format\n" "V) Save in VTK format (only linear and quadratic meshes)\n" "q) Quit\n" #ifdef MFEM_USE_ZLIB "Z) Save in MFEM format with compression\n" #endif "--> " << flush; char mk; cin >> mk; if (!cin) { break; } if (mk == 'q') { break; } if (mk == 'r') { cout << "Choose type of refinement:\n" "s) standard refinement with Mesh::UniformRefinement()\n" "b) Mesh::UniformRefinement() (bisection for tet meshes)\n" "u) uniform refinement with a factor\n" "g) non-uniform refinement (Gauss-Lobatto) with a factor\n" "l) refine locally using the region() function\n" "--> " << flush; char sk; cin >> sk; switch (sk) { case 's': mesh->UniformRefinement(); // Make sure tet-only meshes are marked for local refinement. mesh->Finalize(true); break; case 'b': mesh->UniformRefinement(1); // ref_algo = 1 break; case 'u': case 'g': { cout << "enter refinement factor --> " << flush; int ref_factor; cin >> ref_factor; if (ref_factor <= 1 || ref_factor > 32) { break; } int ref_type = (sk == 'u') ? BasisType::ClosedUniform : BasisType::GaussLobatto; Mesh *rmesh = new Mesh(mesh, ref_factor, ref_type); delete mesh; mesh = rmesh; break; } case 'l': { Vector pt; Array<int> marked_elements; for (int i = 0; i < mesh->GetNE(); i++) { // check all nodes of the element IsoparametricTransformation T; mesh->GetElementTransformation(i, &T); for (int j = 0; j < T.GetPointMat().Width(); j++) { T.GetPointMat().GetColumnReference(j, pt); if (region(pt) <= region_eps) { marked_elements.Append(i); break; } } } mesh->GeneralRefinement(marked_elements); break; } } print_char = 1; } if (mk == 'c') { int p; cout << "enter new order for mesh curvature --> " << flush; cin >> p; mesh->SetCurvature(p > 0 ? p : -p, p <= 0); print_char = 1; } if (mk == 's') { double factor; cout << "scaling factor ---> " << flush; cin >> factor; GridFunction *nodes = mesh->GetNodes(); if (nodes == NULL) { for (int i = 0; i < mesh->GetNV(); i++) { double *v = mesh->GetVertex(i); v[0] *= factor; v[1] *= factor; if (dim == 3) { v[2] *= factor; } } } else { *nodes *= factor; } print_char = 1; } if (mk == 't') { mesh->Transform(transformation); print_char = 1; } if (mk == 'j') { double jitter; cout << "jitter factor ---> " << flush; cin >> jitter; GridFunction *nodes = mesh->GetNodes(); if (nodes == NULL) { cerr << "The mesh should have nodes, introduce curvature first!\n"; } else { FiniteElementSpace *fespace = nodes->FESpace(); GridFunction rdm(fespace); rdm.Randomize(); rdm -= 0.5; // shift to random values in [-0.5,0.5] rdm *= jitter; // compute minimal local mesh size Vector h0(fespace->GetNDofs()); h0 = infinity(); { Array<int> dofs; for (int i = 0; i < fespace->GetNE(); i++) { fespace->GetElementDofs(i, dofs); for (int j = 0; j < dofs.Size(); j++) { h0(dofs[j]) = std::min(h0(dofs[j]), mesh->GetElementSize(i)); } } } // scale the random values to be of order of the local mesh size for (int i = 0; i < fespace->GetNDofs(); i++) { for (int d = 0; d < dim; d++) { rdm(fespace->DofToVDof(i,d)) *= h0(i); } } char move_bdr = 'n'; cout << "move boundary nodes? [y/n] ---> " << flush; cin >> move_bdr; // don't perturb the boundary if (move_bdr == 'n') { Array<int> vdofs; for (int i = 0; i < fespace->GetNBE(); i++) { fespace->GetBdrElementVDofs(i, vdofs); for (int j = 0; j < vdofs.Size(); j++) { rdm(vdofs[j]) = 0.0; } } } *nodes += rdm; } print_char = 1; } if (mk == 'x') { int sd, nz = 0; DenseMatrix J(dim); double min_det_J, max_det_J, min_det_J_z, max_det_J_z; double min_kappa, max_kappa, max_ratio_det_J_z; min_det_J = min_kappa = infinity(); max_det_J = max_kappa = max_ratio_det_J_z = -infinity(); cout << "subdivision factor ---> " << flush; cin >> sd; Array<int> bad_elems_by_geom(Geometry::NumGeom); bad_elems_by_geom = 0; for (int i = 0; i < mesh->GetNE(); i++) { Geometry::Type geom = mesh->GetElementBaseGeometry(i); ElementTransformation *T = mesh->GetElementTransformation(i); RefinedGeometry *RefG = GlobGeometryRefiner.Refine(geom, sd, 1); IntegrationRule &ir = RefG->RefPts; min_det_J_z = infinity(); max_det_J_z = -infinity(); for (int j = 0; j < ir.GetNPoints(); j++) { T->SetIntPoint(&ir.IntPoint(j)); Geometries.JacToPerfJac(geom, T->Jacobian(), J); double det_J = J.Det(); double kappa = J.CalcSingularvalue(0) / J.CalcSingularvalue(dim-1); min_det_J_z = fmin(min_det_J_z, det_J); max_det_J_z = fmax(max_det_J_z, det_J); min_kappa = fmin(min_kappa, kappa); max_kappa = fmax(max_kappa, kappa); } max_ratio_det_J_z = fmax(max_ratio_det_J_z, max_det_J_z/min_det_J_z); min_det_J = fmin(min_det_J, min_det_J_z); max_det_J = fmax(max_det_J, max_det_J_z); if (min_det_J_z <= 0.0) { nz++; bad_elems_by_geom[geom]++; } } cout << "\nbad elements = " << nz; if (nz) { cout << " -- "; Mesh::PrintElementsByGeometry(dim, bad_elems_by_geom, cout); } cout << "\nmin det(J) = " << min_det_J << "\nmax det(J) = " << max_det_J << "\nglobal ratio = " << max_det_J/min_det_J << "\nmax el ratio = " << max_ratio_det_J_z << "\nmin kappa = " << min_kappa << "\nmax kappa = " << max_kappa << endl; } if (mk == 'f') { DenseMatrix point_mat(sdim,1); cout << "\npoint in physical space ---> " << flush; for (int i = 0; i < sdim; i++) { cin >> point_mat(i,0); } Array<int> elem_ids; Array<IntegrationPoint> ips; // physical -> reference space mesh->FindPoints(point_mat, elem_ids, ips); cout << "point in reference space:"; if (elem_ids[0] == -1) { cout << " NOT FOUND!\n"; } else { cout << " element " << elem_ids[0] << ", ip ="; cout << " " << ips[0].x; if (sdim > 1) { cout << " " << ips[0].y; if (sdim > 2) { cout << " " << ips[0].z; } } cout << endl; } } if (mk == 'o') { cout << "What type of reordering?\n" "g) Gecko edge-product minimization\n" "h) Hilbert spatial sort\n" "--> " << flush; char rk; cin >> rk; Array<int> ordering, tentative; if (rk == 'h') { mesh->GetHilbertElementOrdering(ordering); mesh->ReorderElements(ordering); } else if (rk == 'g') { int outer, inner, window, period; cout << "Enter number of outer iterations (default 5): " << flush; cin >> outer; cout << "Enter number of inner iterations (default 4): " << flush; cin >> inner; cout << "Enter window size (default 4, beware of exponential cost): " << flush; cin >> window; cout << "Enter period for window size increment (default 2): " << flush; cin >> period; double best_cost = infinity(); for (int i = 0; i < outer; i++) { int seed = i+1; double cost = mesh->GetGeckoElementOrdering( tentative, inner, window, period, seed, true); if (cost < best_cost) { ordering = tentative; best_cost = cost; } } cout << "Final cost: " << best_cost << endl; mesh->ReorderElements(ordering); } } // These are most of the cases that open a new GLVis window if (mk == 'm' || mk == 'b' || mk == 'e' || mk == 'v' || mk == 'h' || mk == 'k' || mk == 'p') { Array<int> bdr_part; Array<int> part(mesh->GetNE()); FiniteElementSpace *bdr_attr_fespace = NULL; FiniteElementSpace *attr_fespace = new FiniteElementSpace(mesh, attr_fec); GridFunction bdr_attr; GridFunction attr(attr_fespace); if (mk == 'm') { for (int i = 0; i < mesh->GetNE(); i++) { part[i] = (attr(i) = mesh->GetAttribute(i)) - 1; } } if (mk == 'b') { if (dim == 3) { delete bdr_mesh; bdr_mesh = skin_mesh(mesh); bdr_attr_fespace = new FiniteElementSpace(bdr_mesh, bdr_attr_fec); bdr_part.SetSize(bdr_mesh->GetNE()); bdr_attr.SetSpace(bdr_attr_fespace); for (int i = 0; i < bdr_mesh->GetNE(); i++) { bdr_part[i] = (bdr_attr(i) = bdr_mesh->GetAttribute(i)) - 1; } } else { attr = 1.0; } } if (mk == 'v') { attr = 1.0; } if (mk == 'e') { Array<int> coloring; srand(time(0)); double a = double(rand()) / (double(RAND_MAX) + 1.); int el0 = (int)floor(a * mesh->GetNE()); cout << "Generating coloring starting with element " << el0+1 << " / " << mesh->GetNE() << endl; mesh->GetElementColoring(coloring, el0); for (int i = 0; i < coloring.Size(); i++) { attr(i) = coloring[i]; } cout << "Number of colors: " << attr.Max() + 1 << endl; for (int i = 0; i < mesh->GetNE(); i++) { // part[i] = i; // checkerboard element coloring attr(i) = part[i] = i; // coloring by element number } } if (mk == 'h') { DenseMatrix J(dim); double h_min, h_max; h_min = infinity(); h_max = -h_min; for (int i = 0; i < mesh->GetNE(); i++) { int geom = mesh->GetElementBaseGeometry(i); ElementTransformation *T = mesh->GetElementTransformation(i); T->SetIntPoint(&Geometries.GetCenter(geom)); Geometries.JacToPerfJac(geom, T->Jacobian(), J); attr(i) = J.Det(); if (attr(i) < 0.0) { attr(i) = -pow(-attr(i), 1.0/double(dim)); } else { attr(i) = pow(attr(i), 1.0/double(dim)); } h_min = min(h_min, attr(i)); h_max = max(h_max, attr(i)); } cout << "h_min = " << h_min << ", h_max = " << h_max << endl; } if (mk == 'k') { DenseMatrix J(dim); for (int i = 0; i < mesh->GetNE(); i++) { int geom = mesh->GetElementBaseGeometry(i); ElementTransformation *T = mesh->GetElementTransformation(i); T->SetIntPoint(&Geometries.GetCenter(geom)); Geometries.JacToPerfJac(geom, T->Jacobian(), J); attr(i) = J.CalcSingularvalue(0) / J.CalcSingularvalue(dim-1); } } if (mk == 'p') { int *partitioning = NULL, np; cout << "What type of partitioning?\n" "c) Cartesian\n" "s) Simple 1D split of the element sequence\n" "0) METIS_PartGraphRecursive (sorted neighbor lists)\n" "1) METIS_PartGraphKway (sorted neighbor lists)" " (default)\n" "2) METIS_PartGraphVKway (sorted neighbor lists)\n" "3) METIS_PartGraphRecursive\n" "4) METIS_PartGraphKway\n" "5) METIS_PartGraphVKway\n" "--> " << flush; char pk; cin >> pk; if (pk == 'c') { int nxyz[3]; cout << "Enter nx: " << flush; cin >> nxyz[0]; np = nxyz[0]; if (mesh->Dimension() > 1) { cout << "Enter ny: " << flush; cin >> nxyz[1]; np *= nxyz[1]; if (mesh->Dimension() > 2) { cout << "Enter nz: " << flush; cin >> nxyz[2]; np *= nxyz[2]; } } partitioning = mesh->CartesianPartitioning(nxyz); } else if (pk == 's') { cout << "Enter number of processors: " << flush; cin >> np; partitioning = new int[mesh->GetNE()]; for (int i = 0; i < mesh->GetNE(); i++) { partitioning[i] = i * np / mesh->GetNE(); } } else { int part_method = pk - '0'; if (part_method < 0 || part_method > 5) { continue; } cout << "Enter number of processors: " << flush; cin >> np; partitioning = mesh->GeneratePartitioning(np, part_method); } if (partitioning) { const char part_file[] = "partitioning.txt"; ofstream opart(part_file); opart << "number_of_elements " << mesh->GetNE() << '\n' << "number_of_processors " << np << '\n'; for (int i = 0; i < mesh->GetNE(); i++) { opart << partitioning[i] << '\n'; } cout << "Partitioning file: " << part_file << endl; Array<int> proc_el(np); proc_el = 0; for (int i = 0; i < mesh->GetNE(); i++) { proc_el[partitioning[i]]++; } int min_el = proc_el[0], max_el = proc_el[0]; for (int i = 1; i < np; i++) { if (min_el > proc_el[i]) { min_el = proc_el[i]; } if (max_el < proc_el[i]) { max_el = proc_el[i]; } } cout << "Partitioning stats:\n" << " " << setw(12) << "minimum" << setw(12) << "average" << setw(12) << "maximum" << setw(12) << "total" << '\n'; cout << " elements " << setw(12) << min_el << setw(12) << double(mesh->GetNE())/np << setw(12) << max_el << setw(12) << mesh->GetNE() << endl; } else { continue; } for (int i = 0; i < mesh->GetNE(); i++) { attr(i) = part[i] = partitioning[i]; } delete [] partitioning; } char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); if (sol_sock.is_open()) { sol_sock.precision(14); if (sdim == 2) { sol_sock << "fem2d_gf_data_keys\n"; if (mk != 'p') { mesh->Print(sol_sock); } else { // NURBS meshes do not support PrintWithPartitioning if (mesh->NURBSext) { mesh->Print(sol_sock); for (int i = 0; i < mesh->GetNE(); i++) { attr(i) = part[i]; } } else { mesh->PrintWithPartitioning(part, sol_sock, 1); } } attr.Save(sol_sock); sol_sock << "RjlmAb***********"; if (mk == 'v') { sol_sock << "e"; } else { sol_sock << "\n"; } } else { sol_sock << "fem3d_gf_data_keys\n"; if (mk == 'v' || mk == 'h' || mk == 'k') { mesh->Print(sol_sock); } else if (mk == 'b') { bdr_mesh->Print(sol_sock); bdr_attr.Save(sol_sock); sol_sock << "mcaaA"; // Switch to a discrete color scale sol_sock << "pppppp" << "pppppp" << "pppppp"; } else { // NURBS meshes do not support PrintWithPartitioning if (mesh->NURBSext) { mesh->Print(sol_sock); for (int i = 0; i < mesh->GetNE(); i++) { attr(i) = part[i]; } } else { mesh->PrintWithPartitioning(part, sol_sock); } } if (mk != 'b') { attr.Save(sol_sock); sol_sock << "maaA"; if (mk == 'v') { sol_sock << "aa"; } else { sol_sock << "\n"; } } } sol_sock << flush; } else { cout << "Unable to connect to " << vishost << ':' << visport << endl; } delete attr_fespace; delete bdr_attr_fespace; } if (mk == 'l') { // Project and plot the function 'f' int p; FiniteElementCollection *fec = NULL; cout << "Enter projection space order: " << flush; cin >> p; if (p >= 1) { fec = new H1_FECollection(p, mesh->Dimension(), BasisType::GaussLobatto); } else { fec = new DG_FECollection(-p, mesh->Dimension(), BasisType::GaussLegendre); } FiniteElementSpace fes(mesh, fec); GridFunction level(&fes); FunctionCoefficient coeff(f); level.ProjectCoefficient(coeff); char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock(vishost, visport); if (sol_sock.is_open()) { sol_sock.precision(14); sol_sock << "solution\n" << *mesh << level << flush; } else { cout << "Unable to connect to " << vishost << ':' << visport << endl; } delete fec; } if (mk == 'S') { const char mesh_file[] = "mesh-explorer.mesh"; ofstream omesh(mesh_file); omesh.precision(14); mesh->Print(omesh); cout << "New mesh file: " << mesh_file << endl; } if (mk == 'V') { const char mesh_file[] = "mesh-explorer.vtk"; ofstream omesh(mesh_file); omesh.precision(14); mesh->PrintVTK(omesh); cout << "New VTK mesh file: " << mesh_file << endl; } #ifdef MFEM_USE_ZLIB if (mk == 'Z') { const char mesh_file[] = "mesh-explorer.mesh.gz"; ofgzstream omesh(mesh_file, "zwb9"); omesh.precision(14); mesh->Print(omesh); cout << "New mesh file: " << mesh_file << endl; } #endif } delete bdr_attr_fec; delete attr_fec; delete bdr_mesh; delete mesh; return 0; }
32,524
10,325
#include "utility.h" #include "color.h" #include "internal.h" #include "llvm/IR/CFG.h" #include "llvm/IR/InlineAsm.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; static InstructionList dbgstk; static ValueList dbglst; /* * user can trace back to function argument? * only support simple wrapper * return the cap parameter position in parameter list * TODO: track full def-use chain * return -1 for not found */ int use_parent_func_arg(Value *v, Function *f) { int cnt = 0; for (auto a = f->arg_begin(), b = f->arg_end(); a != b; ++a) { if (dyn_cast<Value>(a) == v) return cnt; cnt++; } return -1; } static bool any_user_of_av_is_v(Value *av, Value *v, ValueSet &visited) { if (av == v) return true; if (visited.count(av)) return false; visited.insert(av); for (auto *u : av->users()) { if (dyn_cast<Value>(u) == v) { return true; } if (any_user_of_av_is_v(u, v, visited)) { return true; } } return false; } /* * full def-use chain */ int use_parent_func_arg_deep(Value *v, Function *f) { int cnt = 0; for (auto a = f->arg_begin(), b = f->arg_end(); a != b; ++a) { Value *av = dyn_cast<Value>(a); ValueSet visited; if (any_user_of_av_is_v(av, v, visited)) return cnt; cnt++; } return -1; } Instruction *GetNextInstruction(Instruction *i) { // if (isa<TerminatorInst>(i)) // return i; BasicBlock::iterator BBI(i); return dyn_cast<Instruction>(++BBI); } Instruction *GetNextNonPHIInstruction(Instruction *i) { // if (isa<TerminatorInst>(i)) // return i; BasicBlock::iterator BBI(i); while (isa<PHINode>(BBI)) ++BBI; return dyn_cast<Instruction>(BBI); } Function *get_callee_function_direct(Instruction *i) { CallInst *ci = dyn_cast<CallInst>(i); if (Function *f = ci->getCalledFunction()) return f; Value *cv = ci->getCalledValue(); Function *f = dyn_cast<Function>(cv->stripPointerCasts()); return f; } StringRef get_callee_function_name(Instruction *i) { if (Function *f = get_callee_function_direct(i)) return f->getName(); return ""; } // compare two indices bool indices_equal(Indices *a, Indices *b) { if (a->size() != b->size()) return false; auto ai = a->begin(); auto bi = b->begin(); while (ai != a->end()) { if (*ai != *bi) return false; bi++; ai++; } return true; } /* * store dyn KMI result into DMInterface so that we can use it later */ void add_function_to_dmi(Function *f, StructType *t, Indices &idcs, DMInterface &dmi) { IFPairs *ifps = dmi[t]; if (ifps == NULL) { ifps = new IFPairs; dmi[t] = ifps; } FunctionSet *fset = NULL; for (auto *p : *ifps) { if (indices_equal(&idcs, p->first)) { fset = p->second; break; } } if (fset == NULL) { fset = new FunctionSet; Indices *idc = new Indices; for (auto i : idcs) idc->push_back(i); IFPair *ifp = new IFPair(idc, fset); ifps->push_back(ifp); } fset->insert(f); } /* * this type exists in dmi? */ bool dmi_type_exists(StructType *t, DMInterface &dmi) { // first method auto ifps = dmi.find(t); std::string stname; // only use this for literal if (t->isLiteral()) { if (ifps != dmi.end()) return true; return false; } // match using name stname = t->getStructName(); str_truncate_dot_number(stname); for (auto &ifpsp : dmi) { StructType *cst = ifpsp.first; if (cst->isLiteral()) continue; std::string cstn = cst->getStructName(); str_truncate_dot_number(cstn); if (cstn == stname) { return true; } } return false; } /* * given StructType and indices, return FunctionSet or NULL */ FunctionSet *dmi_exists(StructType *t, Indices &idcs, DMInterface &dmi) { // first method auto ifps = dmi.find(t); std::string stname; IFPairs *ifpairs; // only use this for literal if (t->isLiteral()) { if (ifps != dmi.end()) { ifpairs = ifps->second; for (auto *p : *ifpairs) if (indices_equal(&idcs, p->first)) return p->second; } goto end; } // match using name stname = t->getStructName(); str_truncate_dot_number(stname); for (auto &ifpsp : dmi) { StructType *cst = ifpsp.first; if (cst->isLiteral()) continue; std::string cstn = cst->getStructName(); str_truncate_dot_number(cstn); if (cstn == stname) { ifpairs = ifpsp.second; for (auto *p : *ifpairs) if (indices_equal(&idcs, p->first)) return p->second; } } end: return NULL; } /* * intra-procedural analysis * * only handle high level type info right now. * maybe we can extend this to global variable as well * * see if store instruction actually store the value to some field of a struct * return non NULL if found, and indices is stored in idcs * */ static StructType *resolve_where_is_it_stored_to(StoreInst *si, Indices &idcs) { StructType *ret = NULL; // po is the place where we want to store to Value *po = si->getPointerOperand(); ValueList worklist; ValueSet visited; worklist.push_back(po); // use worklist to track what du-chain while (worklist.size()) { // fetch an item and skip if visited po = worklist.front(); worklist.pop_front(); if (visited.count(po)) continue; visited.insert(po); /* * pointer operand is global variable? * dont care... we can extend this to support fine grind global-aa, since * we already know the target */ if (dyn_cast<GlobalVariable>(po)) continue; if (ConstantExpr *cxpr = dyn_cast<ConstantExpr>(po)) { Instruction *cxpri = cxpr->getAsInstruction(); worklist.push_back(cxpri); continue; } if (Instruction *i = dyn_cast<Instruction>(po)) { switch (i->getOpcode()) { case (Instruction::PHI): { PHINode *phi = dyn_cast<PHINode>(i); for (unsigned int i = 0; i < phi->getNumIncomingValues(); i++) worklist.push_back(phi->getIncomingValue(i)); break; } case (Instruction::Select): { SelectInst *sli = dyn_cast<SelectInst>(i); worklist.push_back(sli->getTrueValue()); worklist.push_back(sli->getFalseValue()); break; } case (BitCastInst::BitCast): { BitCastInst *bci = dyn_cast<BitCastInst>(i); // FIXME:sometimes struct name is purged into i8.. we don't know why, // but we are not able to resolve those since they are translated // to gep of byte directly without using any struct type/member/field // info example: alloc_buffer, drivers/usb/host/ohci-dbg.c worklist.push_back(bci->getOperand(0)); break; } case (Instruction::IntToPtr): { IntToPtrInst *i2ptr = dyn_cast<IntToPtrInst>(i); worklist.push_back(i2ptr->getOperand(0)); break; } case (Instruction::GetElementPtr): { // only GEP is meaningful GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(i); Type *t = gep->getSourceElementType(); get_gep_indicies(gep, idcs); assert(idcs.size() != 0); ret = dyn_cast<StructType>(t); goto out; break; } case (Instruction::Call): { // ignore interprocedural... break; } case (Instruction::Load): { // we are not able to handle load break; } case (Instruction::Store): { // how come we have a store??? dump_gdblst(dbglst); llvm_unreachable("Store to Store?"); break; } case (Instruction::Alloca): { // store to a stack variable // maybe interesting to explore who used this. break; } case (BinaryOperator::Add): { // adjust pointer using arithmatic, seems to be weired BinaryOperator *bop = dyn_cast<BinaryOperator>(i); for (unsigned int i = 0; i < bop->getNumOperands(); i++) worklist.push_back(bop->getOperand(i)); break; } case (Instruction::PtrToInt): { PtrToIntInst *p2int = dyn_cast<PtrToIntInst>(i); worklist.push_back(p2int->getOperand(0)); break; } default: errs() << "unable to handle instruction:" << ANSI_COLOR_RED; i->print(errs()); errs() << ANSI_COLOR_RESET << "\n"; break; } } else { // we got a function parameter } } out: return ret; } /* * part of dynamic KMI - a data flow analysis * for value v, we want to know whether it is assigned to a struct field, and * we want to know indices and return the struct type * NULL is returned if not assigned to struct * * ! there should be a store instruction in the du-chain * TODO: extend this to inter-procedural analysis */ // known interesting inline bool stub_fatst_is_interesting_value(Value *v) { if (isa<BitCastInst>(v) || isa<CallInst>(v) || isa<ConstantExpr>(v) || isa<StoreInst>(v) || isa<Function>(v)) return true; if (SelectInst *si = dyn_cast<SelectInst>(v)) { // result of select shoule be the same as v if (si->getType() == v->getType()) return true; } if (PHINode *phi = dyn_cast<PHINode>(v)) { if (phi->getType() == v->getType()) return true; } // okay if this is a function parameter // a value that is not global and not an instruction/phi if ((!isa<GlobalValue>(v)) && (!isa<Instruction>(v))) { return true; } return false; } // known uninteresting inline bool stub_fatst_is_uninteresting_value(Value *v) { if (isa<GlobalVariable>(v) || isa<Constant>(v) || isa<ICmpInst>(v) || isa<PtrToIntInst>(v)) return true; return false; } StructType *find_assignment_to_struct_type(Value *v, Indices &idcs, ValueSet &visited) { if (visited.count(v)) return NULL; visited.insert(v); dbglst.push_back(v); // FIXME: it is possible to assign to global variable! // but currently we are not handling them // skip all global variables, // the address is statically assigned to global variable if (!stub_fatst_is_interesting_value(v)) { #if 0 if (!stub_fatst_is_uninteresting_value(v)) { errs()<<ANSI_COLOR_RED<<"XXX:" <<ANSI_COLOR_RESET<<"\n"; dump_gdblst(dbglst); } #endif dbglst.pop_back(); return NULL; } //* ! there should be a store instruction in the du-chain if (StoreInst *si = dyn_cast<StoreInst>(v)) { StructType *ret = resolve_where_is_it_stored_to(si, idcs); dbglst.pop_back(); return ret; } for (auto *u : v->users()) { Value *tu = u; Type *t = u->getType(); if (StructType *t_st = dyn_cast<StructType>(t)) if ((t_st->hasName()) && t_st->getStructName().startswith("struct.kernel_symbol")) continue; // inter-procedural analysis // we are interested if it is used as a function parameter if (CallInst *ci = dyn_cast<CallInst>(tu)) { // currently only deal with direct call... Function *cif = get_callee_function_direct(ci); if ((ci->getCalledValue() == v) || (cif == u)) { // ignore calling myself.. continue; } else if (cif == NULL) { // indirect call... #if 0 errs()<<"fptr used in indirect call"; ci->print(errs());errs()<<"\n"; errs()<<"arg v="; v->print(errs());errs()<<"\n"; #endif continue; } else if (!cif->isVarArg()) { // try to figure out which argument is u corresponds to int argidx = -1; for (unsigned int ai = 0; ai < ci->getNumArgOperands(); ai++) { if (ci->getArgOperand(ai) == v) { argidx = ai; break; } } // argidx should not ==-1 if (argidx == -1) { errs() << "Calling " << cif->getName() << "\n"; ci->print(errs()); errs() << "\n"; errs() << "arg v="; v->print(errs()); errs() << "\n"; } assert(argidx != -1); // errs()<<"Into "<<cif->getName()<<"\n"; // now are are in the callee function // figure out the argument auto targ = cif->arg_begin(); for (int i = 0; i < argidx; i++) targ++; tu = targ; } else { // means that this is a vararg continue; } } // FIXME: visited? if (StructType *st = find_assignment_to_struct_type(tu, idcs, visited)) { dbglst.pop_back(); return st; } } dbglst.pop_back(); return NULL; } InstructionSet get_user_instruction(Value *v) { InstructionSet ret; ValueSet vset; ValueSet visited; visited.insert(v); for (auto *u : v->users()) { vset.insert(u); } while (vset.size()) { for (auto x : vset) { v = x; break; } visited.insert(v); vset.erase(v); // if a user is a instruction add it to ret and remove from vset if (Instruction *i = dyn_cast<Instruction>(v)) { ret.insert(i); continue; } // otherwise add all user of current one for (auto *_u : v->users()) { if (visited.count(_u) == 0) vset.insert(_u); } } return ret; } /* * get CallInst * this can resolve call using bitcast * : call %() bitcast %() @foo() */ static void _get_callsite_inst(Value *u, CallInstSet &cil, int depth) { if (depth > 2) return; Value *v = u; CallInst *cs; cs = dyn_cast<CallInst>(v); if (cs) { cil.insert(cs); return; } // otherwise... for (auto *u : v->users()) _get_callsite_inst(u, cil, depth + 1); } void get_callsite_inst(Value *u, CallInstSet &cil) { _get_callsite_inst(u, cil, 0); } /* * is this type a function pointer type or * this is a composite type which have function pointer type element */ static bool _has_function_pointer_type(Type *type, TypeSet &visited) { if (visited.count(type) != 0) return false; visited.insert(type); strip_pointer: if (type->isPointerTy()) { type = type->getPointerElementType(); goto strip_pointer; } if (type->isFunctionTy()) return true; // ignore array type? // if (!type->isAggregateType()) if (!type->isStructTy()) return false; // for each element in this aggregate type, find out whether the element // type is Function pointer type, need to track down more if element is // aggregate type for (unsigned i = 0; i < type->getStructNumElements(); ++i) { Type *t = type->getStructElementType(i); if (t->isPointerTy()) { if (_has_function_pointer_type(t, visited)) return true; } else if (t->isStructTy()) { if (_has_function_pointer_type(t, visited)) return true; } } // other composite type return false; } bool has_function_pointer_type(Type *type) { TypeSet visited; return _has_function_pointer_type(type, visited); } /* * return global value if this is loaded from global value, otherwise return * NULL */ GlobalValue *get_loaded_from_gv(Value *v) { GlobalValue *ret = NULL; IntToPtrInst *i2ptr = dyn_cast<IntToPtrInst>(v); LoadInst *li; Value *addr; if (!i2ptr) goto end; // next I am expectnig a load instruction li = dyn_cast<LoadInst>(i2ptr->getOperand(0)); if (!li) goto end; addr = li->getPointerOperand()->stripPointerCasts(); // could be a constant expr of gep? if (ConstantExpr *cxpr = dyn_cast<ConstantExpr>(addr)) { GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(cxpr->getAsInstruction()); if (Value *tpobj = gep->getPointerOperand()) ret = dyn_cast<GlobalValue>(tpobj); } end: return ret; } /* * is this a load+bitcast of struct into fptr type? * could be multiple load + bitcast */ StructType *identify_ld_bcst_struct(Value *v) { #if 0 LoadInst* li = dyn_cast<LoadInst>(v); if (!li) return NULL; Value* addr = li->getPointerOperand(); if (BitCastInst* bci = dyn_cast<BitCastInst>(addr)) addr = bci->getOperand(0); else return NULL; //should be pointer type if (PointerType* pt = dyn_cast<PointerType>(addr->getType())) { Type* et = pt->getElementType(); if (StructType *st = dyn_cast<StructType>(et)) { //resolved!, they are trying to load the first function pointer //from a struct type we already know! return st; } } return NULL; #else int num_load = 0; Value *nxtv = v; while (1) { if (LoadInst *li = dyn_cast<LoadInst>(nxtv)) { nxtv = li->getPointerOperand(); num_load++; continue; } if (IntToPtrInst *itoptr = dyn_cast<IntToPtrInst>(nxtv)) { nxtv = itoptr->getOperand(0); continue; } break; } if (num_load == 0) return NULL; if (BitCastInst *bci = dyn_cast<BitCastInst>(nxtv)) { nxtv = bci->getOperand(0); } else return NULL; // num_load = number of * in nxtv Type *ret = nxtv->getType(); while (num_load) { // I am expecting a pointer type PointerType *pt = dyn_cast<PointerType>(ret); if (!pt) { // errs() << "I am expecting a pointer type! got:"; // ret->print(errs()); // errs() << "\n"; return NULL; } // assert(pt); ret = pt->getElementType(); num_load--; } return dyn_cast<StructType>(ret); #endif } /* * trace point function as callee? * similar to load+gep, we can not know callee statically, because it is not * defined trace point is a special case where the indirect callee is defined at * runtime, we simply mark it as resolved since we can find where the callee * fptr is loaded from */ bool is_tracepoint_func(Value *v) { if (StructType *st = identify_ld_bcst_struct(v)) { #if 0 errs()<<"Found:"; if (st->isLiteral()) errs()<<"Literal\n"; else errs()<<st->getStructName()<<"\n"; #endif // no name ... if (!st->hasName()) return false; StringRef name = st->getStructName(); if (name == "struct.tracepoint_func") { // errs()<<" ^ a tpfunc:"; // addr->print(errs()); LoadInst *li = dyn_cast<LoadInst>(v); Value *addr = li->getPointerOperand()->stripPointerCasts(); // addr should be a phi PHINode *phi = dyn_cast<PHINode>(addr); assert(phi); // one of the incomming value should be a load for (unsigned int i = 0; i < phi->getNumIncomingValues(); i++) { Value *iv = phi->getIncomingValue(i); // should be a load from a global defined object if (GlobalValue *gv = get_loaded_from_gv(iv)) { // gv->print(errs()); // errs()<<(gv->getName()); break; } } // errs()<<"\n"; return true; } return false; } // something else? return false; } /* * FIXME: we are currently not able to handle container_of, which is expanded * into gep with negative index and high level type information is stripped * maybe we can define a function to repalce container_of... so that high level * type information won't be stripped during compilation */ bool is_container_of(Value *cv) { InstructionSet geps = get_load_from_gep(cv); for (auto _gep : geps) { GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(_gep); // container_of has gep with negative index // and must have negative or non-zero index in the first element auto i = gep->idx_begin(); ConstantInt *idc = dyn_cast<ConstantInt>(i); if (idc && (idc->getSExtValue() != 0)) { #if 0 Type* pty = gep->getSourceElementType(); if(StructType* sty = dyn_cast<StructType>(pty)) { if (!sty->isLiteral()) errs()<<sty->getStructName()<<" "; } #endif return true; } } return false; } /* * get the type where the function pointer is stored * could be combined with bitcast/gep/select/phi * * addr = (may bit cast) gep(struct addr, field) * ptr = load(addr) * call ptr * * may have other form like: * addr1 = gep * addr2 = gep * ptr0 = phi/select addr1, addr2 * ptr1 = bitcast ptr0 * fptr = load(ptr1) * call fptr * * or no gep at all like * * fptr_addr = bitcast struct addr, func type*() * fptr = load fptr_addr * call fptr * */ InstructionSet get_load_from_gep(Value *v) { InstructionSet lots_of_geps; // handle non load instructions first // might be gep/phi/select/bitcast // collect all load instruction into loads InstructionSet loads; ValueSet visited; ValueList worklist; // first, find all interesting load worklist.push_back(v); while (worklist.size()) { Value *i = worklist.front(); worklist.pop_front(); if (visited.count(i)) continue; visited.insert(i); assert(i != NULL); if (LoadInst *li = dyn_cast<LoadInst>(i)) { loads.insert(li); continue; } if (BitCastInst *bci = dyn_cast<BitCastInst>(i)) { worklist.push_back(bci->getOperand(0)); continue; } if (PHINode *phi = dyn_cast<PHINode>(i)) { for (int k = 0; k < (int)phi->getNumIncomingValues(); k++) worklist.push_back(phi->getIncomingValue(k)); continue; } if (SelectInst *sli = dyn_cast<SelectInst>(i)) { worklist.push_back(sli->getTrueValue()); worklist.push_back(sli->getFalseValue()); continue; } if (IntToPtrInst *itptr = dyn_cast<IntToPtrInst>(i)) { worklist.push_back(itptr->getOperand(0)); continue; } if (PtrToIntInst *ptint = dyn_cast<PtrToIntInst>(i)) { worklist.push_back(ptint->getOperand(0)); continue; } // binary operand for pointer manupulation if (BinaryOperator *bop = dyn_cast<BinaryOperator>(i)) { for (int i = 0; i < (int)bop->getNumOperands(); i++) worklist.push_back(bop->getOperand(i)); continue; } if (ZExtInst *izext = dyn_cast<ZExtInst>(i)) { worklist.push_back(izext->getOperand(0)); continue; } if (SExtInst *isext = dyn_cast<SExtInst>(i)) { worklist.push_back(isext->getOperand(0)); continue; } if (isa<GlobalValue>(i) || isa<ConstantExpr>(i) || isa<GetElementPtrInst>(i) || isa<CallInst>(i)) continue; if (!isa<Instruction>(i)) continue; i->print(errs()); errs() << "\n"; llvm_unreachable("no possible"); } ////////////////////////// // For each load instruction's pointer operand, we want to know whether // it is derived from gep or not.. for (auto *lv : loads) { LoadInst *li = dyn_cast<LoadInst>(lv); Value *addr = li->getPointerOperand(); // track def-use chain worklist.push_back(addr); visited.clear(); while (worklist.size()) { Value *i = worklist.front(); worklist.pop_front(); if (visited.count(i)) continue; visited.insert(i); if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(i)) { lots_of_geps.insert(gep); continue; } if (BitCastInst *bci = dyn_cast<BitCastInst>(i)) { worklist.push_back(bci->getOperand(0)); continue; } if (PHINode *phi = dyn_cast<PHINode>(i)) { for (int k = 0; k < (int)phi->getNumIncomingValues(); k++) worklist.push_back(phi->getIncomingValue(k)); continue; } if (SelectInst *sli = dyn_cast<SelectInst>(i)) { worklist.push_back(sli->getTrueValue()); worklist.push_back(sli->getFalseValue()); continue; } if (IntToPtrInst *itptr = dyn_cast<IntToPtrInst>(i)) { worklist.push_back(itptr->getOperand(0)); continue; } if (PtrToIntInst *ptint = dyn_cast<PtrToIntInst>(i)) { worklist.push_back(ptint->getOperand(0)); continue; } // binary operand for pointer manupulation if (BinaryOperator *bop = dyn_cast<BinaryOperator>(i)) { for (int i = 0; i < (int)bop->getNumOperands(); i++) worklist.push_back(bop->getOperand(i)); continue; } if (ZExtInst *izext = dyn_cast<ZExtInst>(i)) { worklist.push_back(izext->getOperand(0)); continue; } if (SExtInst *isext = dyn_cast<SExtInst>(i)) { worklist.push_back(isext->getOperand(0)); continue; } // gep in constantexpr? if (ConstantExpr *cxpr = dyn_cast<ConstantExpr>(i)) { worklist.push_back(cxpr->getAsInstruction()); continue; } if (isa<GlobalValue>(i) || isa<LoadInst>(i) || isa<AllocaInst>(i) || isa<CallInst>(i)) continue; if (!isa<Instruction>(i)) continue; // what else? i->print(errs()); errs() << "\n"; llvm_unreachable("what else?"); } } return lots_of_geps; } // only care about case where all indices are constantint void get_gep_indicies(GetElementPtrInst *gep, Indices &indices) { if (!gep) return; // replace all non-constant with zero // because they are literally an array... // and we are only interested in the type info for (auto i = gep->idx_begin(); i != gep->idx_end(); ++i) { ConstantInt *idc = dyn_cast<ConstantInt>(i); if (idc) indices.push_back(idc->getSExtValue()); else indices.push_back(0); } } bool function_has_gv_initcall_use(Function *f) { static FunctionSet fs_initcall; static FunctionSet fs_noninitcall; if (fs_initcall.count(f) != 0) return true; if (fs_noninitcall.count(f) != 0) return false; for (auto u : f->users()) if (GlobalValue *gv = dyn_cast<GlobalValue>(u)) { if (!gv->hasName()) continue; if (gv->getName().startswith("__initcall_")) { fs_initcall.insert(f); return true; } } fs_noninitcall.insert(f); return false; } void str_truncate_dot_number(std::string &str) { if (!isdigit(str.back())) return; std::size_t found = str.find_last_of('.'); str = str.substr(0, found); } bool is_skip_struct(StringRef str) { for (int i = 0; i < BUILDIN_STRUCT_TO_SKIP; i++) if (str.startswith(_builtin_struct_to_skip[i])) return true; return false; } /* * match a type/indices with known ones */ static Value *_get_value_from_composit(Value *cv, Indices &indices) { // cv must be global value GlobalVariable *gi = dyn_cast<GlobalVariable>(cv); Constant *initializer = dyn_cast<Constant>(cv); Value *ret = NULL; Value *v; int i; dbglst.push_back(cv); if (!indices.size()) goto end; i = indices.front(); indices.pop_front(); if (gi) initializer = gi->getInitializer(); assert(initializer && "must have a initializer!"); /* * no initializer? the member of struct in question does not have a * concreat assignment, we can return now. */ if (initializer == NULL) goto end; if (initializer->isZeroValue()) goto end; v = initializer->getAggregateElement(i); assert(v != cv); if (v == NULL) goto end; // means that this field is not initialized v = v->stripPointerCasts(); assert(v); if (isa<Function>(v)) { ret = v; goto end; } if (indices.size()) ret = _get_value_from_composit(v, indices); end: dbglst.pop_back(); return ret; } Value *get_value_from_composit(Value *cv, Indices &indices) { Indices i = Indices(indices); return _get_value_from_composit(cv, i); } /* * is this function's address taken? * ignore all use by EXPORT_SYMBOL and perf probe trace defs. */ bool is_address_taken(Function *f) { bool ret = false; for (auto &u : f->uses()) { auto *user = u.getUser(); if (CallInst *ci = dyn_cast<CallInst>(user)) { // used inside inline asm? if (ci->isInlineAsm()) continue; // used as direct call, or parameter inside llvm.* if (Function *_f = get_callee_function_direct(ci)) { if ((_f == f) || (_f->isIntrinsic())) continue; // used as function parameter ret = true; goto end; } else { // used as function parameter ret = true; goto end; } llvm_unreachable("should not reach here"); } // not call instruction ValueList vs; ValueSet visited; vs.push_back(dyn_cast<Value>(user)); while (vs.size()) { Value *v = vs.front(); vs.pop_front(); if (v->hasName()) { auto name = v->getName(); if (name.startswith("__ksymtab") || name.startswith("trace_event") || name.startswith("perf_trace") || name.startswith("trace_raw") || name.startswith("llvm.") || name.startswith("event_class")) continue; ret = true; goto end; } for (auto &u : v->uses()) { auto *user = dyn_cast<Value>(u.getUser()); if (!visited.count(user)) { visited.insert(user); vs.push_back(user); } } } } end: return ret; } bool is_using_function_ptr(Function *f) { bool ret = false; for (Function::iterator fi = f->begin(), fe = f->end(); fi != fe; ++fi) { BasicBlock *bb = dyn_cast<BasicBlock>(fi); for (BasicBlock::iterator ii = bb->begin(), ie = bb->end(); ii != ie; ++ii) { if (CallInst *ci = dyn_cast<CallInst>(ii)) { if (Function *f = get_callee_function_direct(ci)) { // should skip those... if (f->isIntrinsic()) continue; // parameters have function pointer in it? for (auto &i : ci->arg_operands()) { // if (isa<Function>(i->stripPointerCasts())) if (PointerType *pty = dyn_cast<PointerType>(i->getType())) { if (isa<FunctionType>(pty->getElementType())) { ret = true; goto end; } } } // means that direct call is not using a function pointer // in the parameter continue; } else if (ci->isInlineAsm()) { // ignore inlineasm // InlineAsm* iasm = dyn_cast<InlinAsm>(ci->getCalledValue()); continue; } else { ret = true; goto end; } } // any other use of function is considered using function pointer for (auto &i : ii->operands()) { // if (isa<Function>(i->stripPointerCasts())) if (PointerType *pty = dyn_cast<PointerType>(i->getType())) { if (isa<FunctionType>(pty->getElementType())) { ret = true; goto end; } } } } } end: return ret; } //////////////////////////////////////////////////////////////////////////////// SimpleSet *skip_vars; SimpleSet *skip_funcs; SimpleSet *crit_syms; SimpleSet *kernel_api; void initialize_achyb_sets(StringRef knob_skip_func_list, StringRef knob_skip_var_list, StringRef knob_crit_symbol, StringRef knob_kernel_api) { // llvm::errs() << "Load supplimental files...\n"; StringList builtin_skip_functions(std::begin(_builtin_skip_functions), std::end(_builtin_skip_functions)); skip_funcs = new SimpleSet(knob_skip_func_list, builtin_skip_functions); /*if (!skip_funcs->use_builtin()) llvm::errs() << " - Skip function list, total:" << skip_funcs->size() << "\n";*/ StringList builtin_skip_var(std::begin(_builtin_skip_var), std::end(_builtin_skip_var)); skip_vars = new SimpleSet(knob_skip_var_list, builtin_skip_var); /*if (!skip_vars->use_builtin()) llvm::errs() << " - Skip var list, total:" << skip_vars->size() << "\n";*/ StringList builtin_crit_symbol; crit_syms = new SimpleSet(knob_crit_symbol, builtin_crit_symbol); /*if (!crit_syms->use_builtin()) llvm::errs() << " - Critical symbols, total:" << crit_syms->size() << "\n";*/ StringList builtin_kapi; kernel_api = new SimpleSet(knob_kernel_api, builtin_kapi); /*if (!kernel_api->use_builtin()) llvm::errs() << " - Kernel API list, total:" << kernel_api->size() << "\n";*/ } //////////////////////////////////////////////////////////////////////////////// void dump_callstack(InstructionList &callstk) { errs() << ANSI_COLOR_GREEN << "Call Stack:" << ANSI_COLOR_RESET << "\n"; int cnt = 0; for (auto *I : callstk) { errs() << "" << cnt << " " << I->getFunction()->getName() << " "; I->getDebugLoc().print(errs()); errs() << "\n"; cnt++; } errs() << ANSI_COLOR_GREEN << "-------------" << ANSI_COLOR_RESET << "\n"; } bool dump_a_path_worker(std::vector<BasicBlock *> &bbl, Function *f, BasicBlockSet &visited) { BasicBlock *bb = bbl.back(); if (bb == &f->getEntryBlock()) return true; auto I = pred_begin(bb); auto E = pred_end(bb); for (; I != E; ++I) { if (visited.find(*I) != visited.end()) continue; visited.insert(*I); bbl.push_back(*I); if (dump_a_path_worker(bbl, f, visited)) return true; bbl.pop_back(); } return false; } void dump_a_path(InstructionList &callstk) { errs() << ANSI_COLOR_GREEN << "Path: " << ANSI_COLOR_RESET << "\n"; std::vector<std::vector<Instruction *>> ill; for (auto cI = callstk.rbegin(), E = callstk.rend(); cI != E; ++cI) { Instruction *I = *cI; BasicBlockSet visited; std::vector<BasicBlock *> bbl; std::vector<Instruction *> il; Function *f = I->getFunction(); // errs()<<f->getName()<<":"; // trace back till we reach the entry point of the function bbl.push_back(I->getParent()); dump_a_path_worker(bbl, f, visited); // print instructions from ebb till the end for (auto bI = bbl.rbegin(), bE = bbl.rend(); bI != bE; ++bI) { BasicBlock *bb = *bI; for (BasicBlock::iterator ii = bb->begin(), ie = bb->end(); ii != ie; ++ii) { Instruction *i = dyn_cast<Instruction>(ii); if (CallInst *ci = dyn_cast<CallInst>(ii)) if (Function *cf = ci->getCalledFunction()) if (cf->getName().startswith("llvm.")) continue; il.push_back(i); // errs()<<f->getName()<<":"; // i->print(errs()); // errs()<<"\n"; if (i == I) break; } } ill.push_back(il); } for (unsigned int i = 0; i < ill.size(); i++) { auto &il = ill[i]; Function *f = il[0]->getFunction(); auto fname = f->getName(); errs() << "Function:" << fname << "\n"; for (unsigned int j = 0; j < il.size(); j++) { il[j]->print(errs()); errs() << "\n"; } } errs() << ANSI_COLOR_GREEN << "-------------" << ANSI_COLOR_RESET << "\n"; } void dump_dbgstk(InstructionList &dbgstk) { errs() << ANSI_COLOR_GREEN << "Process Stack:" << ANSI_COLOR_RESET << "\n"; int cnt = 0; for (auto *I : dbgstk) { errs() << "" << cnt << " " << I->getFunction()->getName() << " "; I->getDebugLoc().print(errs()); errs() << "\n"; cnt++; } errs() << ANSI_COLOR_GREEN << "-------------" << ANSI_COLOR_RESET << "\n"; } void dump_gdblst(ValueList &list) { errs() << ANSI_COLOR_GREEN << "Process List:" << ANSI_COLOR_RESET << "\n"; int cnt = 0; for (auto *I : list) { errs() << " " << cnt << ":"; if (Function *f = dyn_cast<Function>(I)) errs() << f->getName(); else { I->print(errs()); if (Instruction *i = dyn_cast<Instruction>(I)) { errs() << " "; i->getDebugLoc().print(errs()); } } errs() << "\n"; cnt++; } errs() << ANSI_COLOR_GREEN << "-------------" << ANSI_COLOR_RESET << "\n"; }
35,676
12,436
// Author: b1tank // Email: b1tank@outlook.com //================================= /* 138_copy-list-with-random-pointer LeetCode Solution: - hashmap - "DNA" replication - for the original linked list: cut and splice */ #include <iostream> #include <unordered_map> using namespace std; // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; class Solution { public: Node* copyRandomList(Node* head) { if (!head) return nullptr; Node* cur{head}; // duplicate each node in chain while (cur) { Node* tmp = new Node(cur->val); tmp->next = cur->next; cur->next = tmp; cur = cur->next->next; } // assign random link for each duplicated node cur = head; while (cur) { cur->next->random = cur->random ? cur->random->next : nullptr; cur = cur->next->next; } // split the chain into two cur = head; Node* cur2 = head->next; Node* res = head->next; while (cur && cur->next) { cur->next = cur->next->next; cur = cur->next; if (cur2->next) { cur2->next = cur2->next->next; cur2 = cur2->next; } } return res; // Node* res = new Node(0); // unordered_map<Node*, Node*> m; // // Node* cur{head}; // Node* cur_r{res}; // while (cur != nullptr) { // cur_r->next = new Node(cur->val); // cur_r = cur_r->next; // m[cur] = cur_r; // // cur = cur->next; // } // cur = head; // cur_r = res->next; // while (cur != nullptr) { // cur_r->random = m[cur->random]; // cur_r = cur_r->next; // cur = cur->next; // } // return res->next; } };
2,145
687
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2021 Intel Corporation #include "streaming/onevpl/accelerators/surface/dx11_frame_adapter.hpp" #include "streaming/onevpl/accelerators/dx11_alloc_resource.hpp" #include "streaming/onevpl/accelerators/surface/surface.hpp" #include "logger.hpp" #ifdef HAVE_ONEVPL #include "streaming/onevpl/onevpl_export.hpp" #ifdef HAVE_INF_ENGINE // For IE classes (ParamMap, etc) #include <inference_engine.hpp> #endif // HAVE_INF_ENGINE namespace cv { namespace gapi { namespace wip { namespace onevpl { void lock_mid(mfxMemId mid, mfxFrameData &data, MediaFrame::Access mode) { LockAdapter* alloc_data = reinterpret_cast<LockAdapter *>(mid); if (mode == MediaFrame::Access::R) { alloc_data->read_lock(mid, data); } else { alloc_data->write_lock(mid, data); } } void unlock_mid(mfxMemId mid, mfxFrameData &data, MediaFrame::Access mode) { LockAdapter* alloc_data = reinterpret_cast<LockAdapter*>(data.MemId); if (mode == MediaFrame::Access::R) { alloc_data->unlock_read(mid, data); } else { alloc_data->unlock_write(mid, data); } } VPLMediaFrameDX11Adapter::VPLMediaFrameDX11Adapter(std::shared_ptr<Surface> surface): parent_surface_ptr(surface) { GAPI_Assert(parent_surface_ptr && "Surface is nullptr"); const Surface::info_t& info = parent_surface_ptr->get_info(); Surface::data_t& data = parent_surface_ptr->get_data(); GAPI_LOG_DEBUG(nullptr, "surface: " << parent_surface_ptr->get_handle() << ", w: " << info.Width << ", h: " << info.Height << ", p: " << data.Pitch); switch(info.FourCC) { case MFX_FOURCC_I420: throw std::runtime_error("MediaFrame doesn't support I420 type"); break; case MFX_FOURCC_NV12: frame_desc.fmt = MediaFormat::NV12; break; default: throw std::runtime_error("MediaFrame unknown 'fmt' type: " + std::to_string(info.FourCC)); } frame_desc.size = cv::Size{info.Width, info.Height}; LockAdapter* alloc_data = reinterpret_cast<LockAdapter*>(data.MemId); alloc_data->set_adaptee(this); parent_surface_ptr->obtain_lock(); } VPLMediaFrameDX11Adapter::~VPLMediaFrameDX11Adapter() { // Each VPLMediaFrameDX11Adapter releases mfx surface counter // The last VPLMediaFrameDX11Adapter releases shared Surface pointer // The last surface pointer releases workspace memory Surface::data_t& data = parent_surface_ptr->get_data(); LockAdapter* alloc_data = reinterpret_cast<LockAdapter*>(data.MemId); alloc_data->set_adaptee(nullptr); parent_surface_ptr->release_lock(); } cv::GFrameDesc VPLMediaFrameDX11Adapter::meta() const { return frame_desc; } MediaFrame::View VPLMediaFrameDX11Adapter::access(MediaFrame::Access mode) { Surface::data_t& data = parent_surface_ptr->get_data(); const Surface::info_t& info = parent_surface_ptr->get_info(); void* frame_id = reinterpret_cast<void*>(this); GAPI_LOG_DEBUG(nullptr, "START lock frame in surface: " << parent_surface_ptr->get_handle() << ", frame id: " << frame_id); // lock MT lock_mid(data.MemId, data, mode); GAPI_LOG_DEBUG(nullptr, "FINISH lock frame in surface: " << parent_surface_ptr->get_handle() << ", frame id: " << frame_id); using stride_t = typename cv::MediaFrame::View::Strides::value_type; stride_t pitch = static_cast<stride_t>(data.Pitch); // NB: make copy for some copyable object, because access release may be happened // after source/pool destruction, so we need a copy auto parent_surface_ptr_copy = parent_surface_ptr; switch(info.FourCC) { case MFX_FOURCC_I420: { GAPI_Assert(data.Y && data.U && data.V && "MFX_FOURCC_I420 frame data is nullptr"); cv::MediaFrame::View::Ptrs pp = { data.Y, data.U, data.V, nullptr }; cv::MediaFrame::View::Strides ss = { pitch, pitch / 2, pitch / 2, 0u }; return cv::MediaFrame::View(std::move(pp), std::move(ss), [parent_surface_ptr_copy, frame_id, mode] () { parent_surface_ptr_copy->obtain_lock(); auto& data = parent_surface_ptr_copy->get_data(); GAPI_LOG_DEBUG(nullptr, "START unlock frame in surface: " << parent_surface_ptr_copy->get_handle() << ", frame id: " << frame_id); unlock_mid(data.MemId, data, mode); GAPI_LOG_DEBUG(nullptr, "FINISH unlock frame in surface: " << parent_surface_ptr_copy->get_handle() << ", frame id: " << frame_id); parent_surface_ptr_copy->release_lock(); }); } case MFX_FOURCC_NV12: { if (!data.Y || !data.UV) { GAPI_LOG_WARNING(nullptr, "Empty data detected!!! for surface: " << parent_surface_ptr->get_handle() << ", frame id: " << frame_id); } GAPI_Assert(data.Y && data.UV && "MFX_FOURCC_NV12 frame data is nullptr"); cv::MediaFrame::View::Ptrs pp = { data.Y, data.UV, nullptr, nullptr }; cv::MediaFrame::View::Strides ss = { pitch, pitch, 0u, 0u }; return cv::MediaFrame::View(std::move(pp), std::move(ss), [parent_surface_ptr_copy, frame_id, mode] () { parent_surface_ptr_copy->obtain_lock(); auto& data = parent_surface_ptr_copy->get_data(); GAPI_LOG_DEBUG(nullptr, "START unlock frame in surface: " << parent_surface_ptr_copy->get_handle() << ", frame id: " << frame_id); unlock_mid(data.MemId, data, mode); GAPI_LOG_DEBUG(nullptr, "FINISH unlock frame in surface: " << parent_surface_ptr_copy->get_handle() << ", frame id: " << frame_id); parent_surface_ptr_copy->release_lock(); }); } break; default: throw std::runtime_error("MediaFrame unknown 'fmt' type: " + std::to_string(info.FourCC)); } } cv::util::any VPLMediaFrameDX11Adapter::blobParams() const { #ifdef HAVE_INF_ENGINE GAPI_Assert(false && "VPLMediaFrameDX11Adapter::blobParams() is not fully operable " "in G-API streaming. Please waiting for future PRs"); Surface::data_t& data = parent_surface_ptr->get_data(); NativeHandleAdapter* native_handle_getter = reinterpret_cast<NativeHandleAdapter*>(data.MemId); mfxHDLPair handle{}; native_handle_getter->get_handle(data.MemId, reinterpret_cast<mfxHDL&>(handle)); InferenceEngine::ParamMap params{{"SHARED_MEM_TYPE", "VA_SURFACE"}, {"DEV_OBJECT_HANDLE", handle.first}, {"COLOR_FORMAT", InferenceEngine::ColorFormat::NV12}, {"VA_PLANE", static_cast<DX11AllocationItem::subresource_id_t>( reinterpret_cast<uint64_t>( reinterpret_cast<DX11AllocationItem::subresource_id_t *>( handle.second)))}};//, const Surface::info_t& info = parent_surface_ptr->get_info(); InferenceEngine::TensorDesc tdesc({InferenceEngine::Precision::U8, {1, 3, static_cast<size_t>(info.Height), static_cast<size_t>(info.Width)}, InferenceEngine::Layout::NCHW}); return std::make_pair(tdesc, params); #else GAPI_Assert(false && "VPLMediaFrameDX11Adapter::blobParams() is not implemented"); #endif // HAVE_INF_ENGINE } void VPLMediaFrameDX11Adapter::serialize(cv::gapi::s11n::IOStream&) { GAPI_Assert(false && "VPLMediaFrameDX11Adapter::serialize() is not implemented"); } void VPLMediaFrameDX11Adapter::deserialize(cv::gapi::s11n::IIStream&) { GAPI_Assert(false && "VPLMediaFrameDX11Adapter::deserialize() is not implemented"); } DXGI_FORMAT VPLMediaFrameDX11Adapter::get_dx11_color_format(uint32_t mfx_fourcc) { switch (mfx_fourcc) { case MFX_FOURCC_NV12: return DXGI_FORMAT_NV12; case MFX_FOURCC_YUY2: return DXGI_FORMAT_YUY2; case MFX_FOURCC_RGB4: return DXGI_FORMAT_B8G8R8A8_UNORM; case MFX_FOURCC_P8: case MFX_FOURCC_P8_TEXTURE: return DXGI_FORMAT_P8; case MFX_FOURCC_ARGB16: case MFX_FOURCC_ABGR16: return DXGI_FORMAT_R16G16B16A16_UNORM; case MFX_FOURCC_P010: return DXGI_FORMAT_P010; case MFX_FOURCC_A2RGB10: return DXGI_FORMAT_R10G10B10A2_UNORM; case DXGI_FORMAT_AYUV: case MFX_FOURCC_AYUV: return DXGI_FORMAT_AYUV; default: return DXGI_FORMAT_UNKNOWN; } } } // namespace onevpl } // namespace wip } // namespace gapi } // namespace cv #endif // HAVE_ONEVPL
9,532
3,178
/* cppcryptfs : user-mode cryptographic virtual overlay filesystem. Copyright (C) 2016-2019 Bailey Brown (github.com/bailey27/cppcryptfs) cppcryptfs is based on the design of gocryptfs (github.com/rfjakob/gocryptfs) The MIT License (MIT) 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 "stdafx.h" #include <Softpub.h> #include <wincrypt.h> #include <wintrust.h> // Link with the Wintrust.lib file. #pragma comment (lib, "wintrust") bool VerifyEmbeddedSignature(LPCWSTR pwszSourceFile) { LONG lStatus; // Initialize the WINTRUST_FILE_INFO structure. WINTRUST_FILE_INFO FileData; memset(&FileData, 0, sizeof(FileData)); FileData.cbStruct = sizeof(WINTRUST_FILE_INFO); FileData.pcwszFilePath = pwszSourceFile; FileData.hFile = NULL; FileData.pgKnownSubject = NULL; /* WVTPolicyGUID specifies the policy to apply on the file WINTRUST_ACTION_GENERIC_VERIFY_V2 policy checks: 1) The certificate used to sign the file chains up to a root certificate located in the trusted root certificate store. This implies that the identity of the publisher has been verified by a certification authority. 2) In cases where user interface is displayed (which this example does not do), WinVerifyTrust will check for whether the end entity certificate is stored in the trusted publisher store, implying that the user trusts content from this publisher. 3) The end entity certificate has sufficient permission to sign code, as indicated by the presence of a code signing EKU or no EKU. */ GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2; WINTRUST_DATA WinTrustData; // Initialize the WinVerifyTrust input data structure. // Default all fields to 0. memset(&WinTrustData, 0, sizeof(WinTrustData)); WinTrustData.cbStruct = sizeof(WinTrustData); // Use default code signing EKU. WinTrustData.pPolicyCallbackData = NULL; // No data to pass to SIP. WinTrustData.pSIPClientData = NULL; // Disable WVT UI. WinTrustData.dwUIChoice = WTD_UI_NONE; // No revocation checking. WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE; // Verify an embedded signature on a file. WinTrustData.dwUnionChoice = WTD_CHOICE_FILE; // Verify action. WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY; // Verification sets this value. WinTrustData.hWVTStateData = NULL; // Not used. WinTrustData.pwszURLReference = NULL; // This is not applicable if there is no UI because it changes // the UI to accommodate running applications instead of // installing applications. WinTrustData.dwUIContext = 0; // Set pFile. WinTrustData.pFile = &FileData; // WinVerifyTrust verifies signatures as specified by the GUID // and Wintrust_Data. lStatus = WinVerifyTrust( static_cast<HWND>(INVALID_HANDLE_VALUE), &WVTPolicyGUID, &WinTrustData); bool bRet = lStatus == ERROR_SUCCESS; #if 0 // this code is not needed, but left in for future reference DWORD dwLastError; switch (lStatus) { case ERROR_SUCCESS: /* Signed file: - Hash that represents the subject is trusted. - Trusted publisher without any verification errors. - UI was disabled in dwUIChoice. No publisher or time stamp chain errors. - UI was enabled in dwUIChoice and the user clicked "Yes" when asked to install and run the signed subject. */ wprintf_s(L"The file \"%s\" is signed and the signature " L"was verified.\n", pwszSourceFile); break; case TRUST_E_NOSIGNATURE: // The file was not signed or had a signature // that was not valid. // Get the reason for no signature. dwLastError = GetLastError(); if (TRUST_E_NOSIGNATURE == dwLastError || TRUST_E_SUBJECT_FORM_UNKNOWN == dwLastError || TRUST_E_PROVIDER_UNKNOWN == dwLastError) { // The file was not signed. wprintf_s(L"The file \"%s\" is not signed.\n", pwszSourceFile); } else { // The signature was not valid or there was an error // opening the file. wprintf_s(L"An unknown error occurred trying to " L"verify the signature of the \"%s\" file.\n", pwszSourceFile); } break; case TRUST_E_EXPLICIT_DISTRUST: // The hash that represents the subject or the publisher // is not allowed by the admin or user. wprintf_s(L"The signature is present, but specifically " L"disallowed.\n"); break; case TRUST_E_SUBJECT_NOT_TRUSTED: // The user clicked "No" when asked to install and run. wprintf_s(L"The signature is present, but not " L"trusted.\n"); break; case CRYPT_E_SECURITY_SETTINGS: /* The hash that represents the subject or the publisher was not explicitly trusted by the admin and the admin policy has disabled user trust. No signature, publisher or time stamp errors. */ wprintf_s(L"CRYPT_E_SECURITY_SETTINGS - The hash " L"representing the subject or the publisher wasn't " L"explicitly trusted by the admin and admin policy " L"has disabled user trust. No signature, publisher " L"or timestamp errors.\n"); break; default: // The UI was disabled in dwUIChoice or the admin policy // has disabled user trust. lStatus contains the // publisher or time stamp chain error. wprintf_s(L"Error is: 0x%x.\n", lStatus); break; } #endif // #if 0 // Any hWVTStateData must be released by a call with close. WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE; lStatus = WinVerifyTrust( NULL, &WVTPolicyGUID, &WinTrustData); return bRet; }
6,590
2,409
#include "Entity.h" Entity::Entity(float x, float y, float hitboxSize) : x(x), y(y), hitboxSize(hitboxSize), acceleration(0.0f), velocity(0.0f), angle(0.0f), speedCap(0.0f), frictionF(0.0f), active(true) { } void Entity::moveTo(float x, float y) { this->x = x; this->y = y; updateVertices(); } void Entity::moveRelative(float x, float y) { this->x += x; this->y += y; updateVertices(); } void Entity::updateVertices() { vertices = { this->x - hitboxSize, this->y - hitboxSize, 0.0f, 0.0f, this->x - hitboxSize, this->y + hitboxSize, 0.0f, 1.0f, this->x + hitboxSize, this->y + hitboxSize, 1.0f, 1.0f, this->x + hitboxSize, this->y - hitboxSize, 1.0f, 0.0f }; } #include <iostream> void Entity::updatePosL(float deltaTime) { updatePosL(deltaTime, angle); } void Entity::updatePosL(float deltaTime, float newAngle) { angle = newAngle; const float movementX = speedCap * deltaTime * cos(angle); const float movementY = speedCap * deltaTime * sin(angle); x += movementX; y += movementY; updateVertices(); } void Entity::updatePosQ(float deltaTime) { updatePosQ(deltaTime, angle); } void Entity::updatePosQ(float deltaTime, float newAngle) { const float movementX = 0.5f * acceleration * deltaTime * deltaTime * cos(newAngle) + velocity * deltaTime * cos(angle); const float movementY = 0.5f * acceleration * deltaTime * deltaTime * sin(newAngle) + velocity * deltaTime * sin(angle); angle = atan2(movementY, movementX); x += movementX; y += movementY; //std::cerr << "angle = " << angle << std::endl; //std::cerr << "vel = " << velocity << ", std::abs(vel) = " << std::abs(velocity) << std::endl; const float friction = ρAir * frictionF * velocity * std::abs(velocity); velocity = std::max(std::min(velocity + acceleration * deltaTime - friction, speedCap), -speedCap); updateVertices(); }
1,943
701
/* Copyright 2020 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_lite_support/custom_ops/kernel/sentencepiece/optimized_decoder.h" #include <fstream> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "src/sentencepiece.pb.h" #include "src/sentencepiece_processor.h" #include "tensorflow/core/platform/env.h" #include "tensorflow_lite_support/custom_ops/kernel/sentencepiece/model_converter.h" namespace tflite { namespace ops { namespace custom { namespace sentencepiece { namespace internal { tensorflow::Status TFReadFileToString(const std::string& filepath, std::string* data) { return tensorflow::ReadFileToString(tensorflow::Env::Default(), /*test_path*/ filepath, data); } absl::Status StdReadFileToString(const std::string& filepath, std::string* data) { std::ifstream infile(filepath); if (!infile.is_open()) { return absl::NotFoundError( absl::StrFormat("Error when opening %s", filepath)); } std::string contents((std::istreambuf_iterator<char>(infile)), (std::istreambuf_iterator<char>())); data->append(contents); infile.close(); return absl::OkStatus(); } } // namespace internal namespace { static char kConfigFilePath[] = "tensorflow_lite_support/custom_ops/kernel/" "sentencepiece/testdata/sentencepiece.model"; TEST(OptimizedEncoder, ConfigConverter) { std::string config; auto status = internal::StdReadFileToString(kConfigFilePath, &config); ASSERT_TRUE(status.ok()); ::sentencepiece::SentencePieceProcessor processor; ASSERT_OK(processor.LoadFromSerializedProto(config)); const auto converted_model = ConvertSentencepieceModelForDecoder(config); const std::string test_string("Hello world!\\xF0\\x9F\\x8D\\x95"); ::sentencepiece::SentencePieceText reference_encoded; CHECK_OK(processor.Encode(test_string, &reference_encoded)); std::vector<int> encoded_vector; encoded_vector.reserve(reference_encoded.pieces_size()); for (const auto& piece : reference_encoded.pieces()) { encoded_vector.push_back(piece.id()); } std::string ref_decoded; ASSERT_OK(processor.Decode(encoded_vector, &ref_decoded)); const auto decoded = DecodeString(encoded_vector, converted_model.data()); ASSERT_EQ(decoded.type, DecoderResultType::SUCCESS); ASSERT_EQ(ref_decoded, decoded.decoded); } } // namespace } // namespace sentencepiece } // namespace custom } // namespace ops } // namespace tflite
3,157
980
#include "random.h" #include <iostream> using namespace std; int main(int, char* argv[]) { long long seed = atoll(argv[1]); auto gen = Random(seed); int n = 500'000 - 2; int m = 500'000; printf("p cnf %d %d\n", n, m); // all same for (int i = 1; i < n; i++) { printf("%d %d 0\n", i, - (i + 1)); } printf("%d -1 0\n", n); // some pair, both true(= all true) int a = gen.uniform(1, n); int b = gen.uniform(1, n); printf("%d %d 0\n", a, b); // some pair, both false(= all false) a = gen.uniform(-n, -1); b = gen.uniform(-n, -1); printf("%d %d 0\n", a, b); return 0; }
652
289
// // Created by Aloysio Galvão Lopes on 2020-05-30. // #include "utils/Texture.h" #include "Bird.h" std::vector<GLuint> Bird::textures; Bird::Bird(Shaders &shaders, vcl::vec3 pos, float scale, vcl::vec3 speed, float turning) : Object(true), dp(speed), turining(turning), bird("../src/assets/models/bird.fbx", shaders["mesh"]) { position = pos; if (textures.empty()) { Texture feathers("bird"); textures.push_back(feathers.getId()); } bird.set_textures(textures); bird.set_animation("bird|fly"); animationTime = 0; } void Bird::drawMesh(vcl::camera_scene &camera) { bird.set_light(lights[0]); // TODO add scaling to birds // TODO Add bounding sphere orientation = vcl::rotation_euler(dp, turining); vcl::mat4 transform = {orientation, position}; // Bird draw bird.transform(transform); bird.draw(camera, animationTime); } void Bird::update(float time) { vcl::vec3 projDpo = {odp.x, odp.y, 1}; vcl::vec3 projNdp = {ndp.x, ndp.y, 1}; float targetAngle = projDpo.angle(projNdp)*Constants::BIRD_MAX_TURN_FACTOR; if (targetAngle > M_PI_2) targetAngle = M_PI_2; else if (targetAngle < -M_PI_2) targetAngle = -M_PI_2; turining += Constants::BIRD_TURN_FACTOR*(targetAngle-turining); // Animation part float animationNormalizedPosition = fmod(animationTime, Constants::BIRD_ANIMATION_MAX_TIME); float animationTargetPosition = animationNormalizedPosition+Constants::BIRD_ANIMATION_SPEED; float animationSpeedFactor = 1.0f; float inclination = dp.angle({0,0,1}); if (inclination >= M_PI_2+M_PI_4){ animationTargetPosition = 0.6; } else { animationSpeedFactor = (M_PI_2+M_PI_4-inclination)/(M_PI_2+M_PI_4)*0.6+0.4; animationSpeedFactor += (fabs(turining))/M_PI_2; } if (fabs(animationNormalizedPosition-animationTargetPosition) >= Constants::BIRD_ANIMATION_SPEED/2) animationTime += Constants::BIRD_ANIMATION_SPEED*animationSpeedFactor; } vcl::vec3 Bird::getSpeed() { return dp; } void Bird::setFutureSpeed(vcl::vec3 speed) { ndp = speed; } void Bird::addFutureSpeed(vcl::vec3 speed) { ndp += speed; } vcl::vec3 Bird::getFutureSpeed() { return ndp; } void Bird::setPosition(vcl::vec3 pos) { position = pos; } void Bird::stepSpeed() { odp = dp; dp = ndp; } void Bird::stepPosition() { position += dp; } float Bird::getRotation() { return turining; }
2,482
948
// Generated by Haxe 4.2.0-rc.1+cb30bd580 #include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_fracs_Fracs #include <fracs/Fracs.h> #endif #ifndef INCLUDED_fracs__Fraction_Fraction_Impl_ #include <fracs/_Fraction/Fraction_Impl_.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_32__new,"fracs._Fraction.Fraction_Impl_","_new",0x2a584cf7,"fracs._Fraction.Fraction_Impl_._new","fracs/Fraction.hx",32,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_46_optimize,"fracs._Fraction.Fraction_Impl_","optimize",0x00d44773,"fracs._Fraction.Fraction_Impl_.optimize","fracs/Fraction.hx",46,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_50_optimizeFraction,"fracs._Fraction.Fraction_Impl_","optimizeFraction",0xea05c495,"fracs._Fraction.Fraction_Impl_.optimizeFraction","fracs/Fraction.hx",50,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_55_toFloat,"fracs._Fraction.Fraction_Impl_","toFloat",0xab643c4b,"fracs._Fraction.Fraction_Impl_.toFloat","fracs/Fraction.hx",55,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_63_float,"fracs._Fraction.Fraction_Impl_","float",0xe96e3146,"fracs._Fraction.Fraction_Impl_.float","fracs/Fraction.hx",63,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_67_verbose,"fracs._Fraction.Fraction_Impl_","verbose",0x4e0301ac,"fracs._Fraction.Fraction_Impl_.verbose","fracs/Fraction.hx",67,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_71_fromString,"fracs._Fraction.Fraction_Impl_","fromString",0x6a8439f1,"fracs._Fraction.Fraction_Impl_.fromString","fracs/Fraction.hx",71,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_82_toString,"fracs._Fraction.Fraction_Impl_","toString",0x1c2a8b42,"fracs._Fraction.Fraction_Impl_.toString","fracs/Fraction.hx",82,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_98_fromFloat,"fracs._Fraction.Fraction_Impl_","fromFloat",0x17a7387c,"fracs._Fraction.Fraction_Impl_.fromFloat","fracs/Fraction.hx",98,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_119_firstFloat,"fracs._Fraction.Fraction_Impl_","firstFloat",0x56851b62,"fracs._Fraction.Fraction_Impl_.firstFloat","fracs/Fraction.hx",119,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_126_byDenominator,"fracs._Fraction.Fraction_Impl_","byDenominator",0xa7ebbeb9,"fracs._Fraction.Fraction_Impl_.byDenominator","fracs/Fraction.hx",126,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_138_all,"fracs._Fraction.Fraction_Impl_","all",0x2614464b,"fracs._Fraction.Fraction_Impl_.all","fracs/Fraction.hx",138,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_141_similarToFraction,"fracs._Fraction.Fraction_Impl_","similarToFraction",0x69a71b52,"fracs._Fraction.Fraction_Impl_.similarToFraction","fracs/Fraction.hx",141,0xf40fb512) HX_LOCAL_STACK_FRAME(_hx_pos_2fa7d690c1539e6b_147_similarToValue,"fracs._Fraction.Fraction_Impl_","similarToValue",0x124a8821,"fracs._Fraction.Fraction_Impl_.similarToValue","fracs/Fraction.hx",147,0xf40fb512) namespace fracs{ namespace _Fraction{ void Fraction_Impl__obj::__construct() { } Dynamic Fraction_Impl__obj::__CreateEmpty() { return new Fraction_Impl__obj; } void *Fraction_Impl__obj::_hx_vtable = 0; Dynamic Fraction_Impl__obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< Fraction_Impl__obj > _hx_result = new Fraction_Impl__obj(); _hx_result->__construct(); return _hx_result; } bool Fraction_Impl__obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x1a57794a; } ::Dynamic Fraction_Impl__obj::_new(int numerator,int denominator, ::Dynamic __o_positive, ::Dynamic value){ ::Dynamic positive = __o_positive; if (::hx::IsNull(__o_positive)) positive = true; HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_32__new) HXLINE( 34) bool numNeg = (numerator < 0); HXLINE( 35) bool denoNeg = (denominator < 0); HXLINE( 36) if (::hx::IsNull( value )) { HXLINE( 36) if (( (bool)(positive) )) { HXLINE( 36) value = (( (Float)(numerator) ) / ( (Float)(denominator) )); } else { HXLINE( 36) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) )); } } HXLINE( 37) bool _hx_tmp; HXDLIN( 37) if (!(numNeg)) { HXLINE( 37) _hx_tmp = denoNeg; } else { HXLINE( 37) _hx_tmp = true; } HXDLIN( 37) if (_hx_tmp) { HXLINE( 38) bool _hx_tmp; HXDLIN( 38) if (numNeg) { HXLINE( 38) _hx_tmp = denoNeg; } else { HXLINE( 38) _hx_tmp = false; } HXDLIN( 38) if (!(_hx_tmp)) { HXLINE( 38) positive = !(( (bool)(positive) )); } HXLINE( 39) if (numNeg) { HXLINE( 39) numerator = -(numerator); } HXLINE( 40) if (denoNeg) { HXLINE( 40) denominator = -(denominator); } } HXLINE( 32) ::Dynamic this1 = ::Dynamic(::hx::Anon_obj::Create(4) ->setFixed(0,HX_("numerator",89,82,9c,c2),numerator) ->setFixed(1,HX_("positive",b9,a6,fa,ca),positive) ->setFixed(2,HX_("denominator",a6,25,84,eb),denominator) ->setFixed(3,HX_("value",71,7f,b8,31),value)); HXDLIN( 32) return this1; } STATIC_HX_DEFINE_DYNAMIC_FUNC4(Fraction_Impl__obj,_new,return ) ::Dynamic Fraction_Impl__obj::optimize( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_46_optimize) HXDLIN( 46) Float f = ( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) ); HXDLIN( 46) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXDLIN( 46) Float dist = ::Math_obj::POSITIVE_INFINITY; HXDLIN( 46) Float dif; HXDLIN( 46) int l = arr->length; HXDLIN( 46) Float fracFloat; HXDLIN( 46) ::Dynamic frac; HXDLIN( 46) ::Dynamic fracStore = arr->__get(0); HXDLIN( 46) { HXDLIN( 46) int _g = 0; HXDLIN( 46) int _g1 = l; HXDLIN( 46) while((_g < _g1)){ HXDLIN( 46) _g = (_g + 1); HXDLIN( 46) int i = (_g - 1); HXDLIN( 46) ::Dynamic frac = arr->__get(i); HXDLIN( 46) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXDLIN( 46) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXDLIN( 46) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXDLIN( 46) dif = ::Math_obj::abs((fracFloat - f)); HXDLIN( 46) if ((dif < dist)) { HXDLIN( 46) dist = dif; HXDLIN( 46) fracStore = frac; } } } HXDLIN( 46) return fracStore; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,optimize,return ) ::Dynamic Fraction_Impl__obj::optimizeFraction( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_50_optimizeFraction) HXDLIN( 50) Float f; HXDLIN( 50) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXDLIN( 50) f = (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXDLIN( 50) f = (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXDLIN( 50) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXDLIN( 50) Float dist = ::Math_obj::POSITIVE_INFINITY; HXDLIN( 50) Float dif; HXDLIN( 50) int l = arr->length; HXDLIN( 50) Float fracFloat; HXDLIN( 50) ::Dynamic frac; HXDLIN( 50) ::Dynamic fracStore = arr->__get(0); HXDLIN( 50) { HXDLIN( 50) int _g = 0; HXDLIN( 50) int _g1 = l; HXDLIN( 50) while((_g < _g1)){ HXDLIN( 50) _g = (_g + 1); HXDLIN( 50) int i = (_g - 1); HXDLIN( 50) ::Dynamic frac = arr->__get(i); HXDLIN( 50) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXDLIN( 50) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXDLIN( 50) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXDLIN( 50) dif = ::Math_obj::abs((fracFloat - f)); HXDLIN( 50) if ((dif < dist)) { HXDLIN( 50) dist = dif; HXDLIN( 50) fracStore = frac; } } } HXDLIN( 50) return fracStore; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,optimizeFraction,return ) Float Fraction_Impl__obj::toFloat( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_55_toFloat) HXDLIN( 55) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 56) return (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXLINE( 58) return (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXLINE( 55) return ((Float)0.); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,toFloat,return ) Float Fraction_Impl__obj::_hx_float( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_63_float) HXDLIN( 63) return ( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,_hx_float,return ) ::String Fraction_Impl__obj::verbose( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_67_verbose) HXDLIN( 67) ::String _hx_tmp = ( (::String)(((((HX_("{ numerator:",16,c9,1c,39) + this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) + HX_(", denominator: ",d8,6e,ff,e1)) + this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) + HX_(", positive: ",13,f9,b0,e4))) ); HXDLIN( 67) ::String _hx_tmp1 = ((_hx_tmp + ::Std_obj::string( ::Dynamic(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)))) + HX_(", value: ",63,80,38,d8)); HXDLIN( 67) return ( (::String)(((_hx_tmp1 + this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) + HX_(" }",5d,1c,00,00))) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,verbose,return ) ::Dynamic Fraction_Impl__obj::fromString(::String val){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_71_fromString) HXLINE( 72) int i = val.indexOf(HX_("/",2f,00,00,00),null()); HXLINE( 73) ::Dynamic frac; HXDLIN( 73) if ((i != -1)) { HXLINE( 74) int numerator = ( (int)(::Std_obj::parseInt(val.substr(0,i))) ); HXDLIN( 74) int denominator = ( (int)(::Std_obj::parseInt(val.substr((i + 1),val.length))) ); HXDLIN( 74) ::Dynamic positive = true; HXDLIN( 74) ::Dynamic value = null(); HXDLIN( 74) bool numNeg = (numerator < 0); HXDLIN( 74) bool denoNeg = (denominator < 0); HXDLIN( 74) if (::hx::IsNull( value )) { HXLINE( 74) if (( (bool)(positive) )) { HXLINE( 74) value = (( (Float)(numerator) ) / ( (Float)(denominator) )); } else { HXLINE( 74) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) )); } } HXDLIN( 74) bool frac1; HXDLIN( 74) if (!(numNeg)) { HXLINE( 74) frac1 = denoNeg; } else { HXLINE( 74) frac1 = true; } HXDLIN( 74) if (frac1) { HXLINE( 74) bool frac; HXDLIN( 74) if (numNeg) { HXLINE( 74) frac = denoNeg; } else { HXLINE( 74) frac = false; } HXDLIN( 74) if (!(frac)) { HXLINE( 74) positive = !(( (bool)(positive) )); } HXDLIN( 74) if (numNeg) { HXLINE( 74) numerator = -(numerator); } HXDLIN( 74) if (denoNeg) { HXLINE( 74) denominator = -(denominator); } } HXDLIN( 74) ::Dynamic this1 = ::Dynamic(::hx::Anon_obj::Create(4) ->setFixed(0,HX_("numerator",89,82,9c,c2),numerator) ->setFixed(1,HX_("positive",b9,a6,fa,ca),positive) ->setFixed(2,HX_("denominator",a6,25,84,eb),denominator) ->setFixed(3,HX_("value",71,7f,b8,31),value)); HXLINE( 73) frac = this1; } else { HXLINE( 75) Float f = ::Std_obj::parseFloat(val); HXDLIN( 75) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXDLIN( 75) Float dist = ::Math_obj::POSITIVE_INFINITY; HXDLIN( 75) Float dif; HXDLIN( 75) int l = arr->length; HXDLIN( 75) Float fracFloat; HXDLIN( 75) ::Dynamic frac1; HXDLIN( 75) ::Dynamic fracStore = arr->__get(0); HXDLIN( 75) { HXLINE( 75) int _g = 0; HXDLIN( 75) int _g1 = l; HXDLIN( 75) while((_g < _g1)){ HXLINE( 75) _g = (_g + 1); HXDLIN( 75) int i = (_g - 1); HXDLIN( 75) ::Dynamic frac = arr->__get(i); HXDLIN( 75) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 75) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXLINE( 75) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXDLIN( 75) dif = ::Math_obj::abs((fracFloat - f)); HXDLIN( 75) if ((dif < dist)) { HXLINE( 75) dist = dif; HXDLIN( 75) fracStore = frac; } } } HXLINE( 73) frac = fracStore; } HXLINE( 78) return frac; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,fromString,return ) ::String Fraction_Impl__obj::toString( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_82_toString) HXLINE( 83) int n = ( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ); HXLINE( 84) int d = ( (int)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ); HXLINE( 85) ::String out; HXDLIN( 85) if ((n == 0)) { HXLINE( 85) out = HX_("0",30,00,00,00); } else { HXLINE( 87) if ((n == d)) { HXLINE( 85) out = HX_("1",31,00,00,00); } else { HXLINE( 89) if ((d == 1)) { HXLINE( 90) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 85) out = (HX_("",00,00,00,00) + n); } else { HXLINE( 85) out = (HX_("-",2d,00,00,00) + n); } } else { HXLINE( 92) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 85) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } else { HXLINE( 85) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } } } } HXLINE( 94) return out; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,toString,return ) ::Dynamic Fraction_Impl__obj::fromFloat(Float f){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_98_fromFloat) HXLINE( 99) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXLINE( 100) Float dist = ::Math_obj::POSITIVE_INFINITY; HXLINE( 101) Float dif; HXLINE( 102) int l = arr->length; HXLINE( 103) Float fracFloat; HXLINE( 104) ::Dynamic frac; HXLINE( 105) ::Dynamic fracStore = arr->__get(0); HXLINE( 107) { HXLINE( 107) int _g = 0; HXDLIN( 107) int _g1 = l; HXDLIN( 107) while((_g < _g1)){ HXLINE( 107) _g = (_g + 1); HXDLIN( 107) int i = (_g - 1); HXLINE( 108) ::Dynamic frac = arr->__get(i); HXLINE( 109) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 109) fracFloat = (( (Float)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXLINE( 109) fracFloat = (( (Float)(-(( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXLINE( 110) dif = ::Math_obj::abs((fracFloat - f)); HXLINE( 111) if ((dif < dist)) { HXLINE( 112) dist = dif; HXLINE( 113) fracStore = frac; } } } HXLINE( 116) return fracStore; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,fromFloat,return ) ::Dynamic Fraction_Impl__obj::firstFloat(Float f){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_119_firstFloat) HXLINE( 120) ::Array< ::Dynamic> arr = ::fracs::Fracs_obj::approximateFractions(f); HXLINE( 121) ::Dynamic fracStore = arr->__get(0); HXLINE( 122) return fracStore; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,firstFloat,return ) ::String Fraction_Impl__obj::byDenominator( ::Dynamic this1,int val){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_126_byDenominator) HXLINE( 127) int n = ( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ); HXDLIN( 127) int d = ( (int)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ); HXDLIN( 127) ::String out; HXDLIN( 127) if ((n == 0)) { HXLINE( 127) out = HX_("0",30,00,00,00); } else { HXLINE( 127) if ((n == d)) { HXLINE( 127) out = HX_("1",31,00,00,00); } else { HXLINE( 127) if ((d == 1)) { HXLINE( 127) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 127) out = (HX_("",00,00,00,00) + n); } else { HXLINE( 127) out = (HX_("-",2d,00,00,00) + n); } } else { HXLINE( 127) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 127) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } else { HXLINE( 127) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } } } } HXDLIN( 127) ::String out1 = out; HXLINE( 128) bool _hx_tmp; HXDLIN( 128) bool _hx_tmp1; HXDLIN( 128) if (::hx::IsNotEq( this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic),val )) { HXLINE( 128) _hx_tmp1 = (out1 == HX_("0",30,00,00,00)); } else { HXLINE( 128) _hx_tmp1 = true; } HXDLIN( 128) if (!(_hx_tmp1)) { HXLINE( 128) _hx_tmp = (out1 == HX_("1",31,00,00,00)); } else { HXLINE( 128) _hx_tmp = true; } HXDLIN( 128) if (!(_hx_tmp)) { HXLINE( 130) int dom = ::Math_obj::round((( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) ) * ( (Float)(val) ))); HXLINE( 131) int numerator = dom; HXDLIN( 131) int denominator = val; HXDLIN( 131) ::Dynamic positive = true; HXDLIN( 131) ::Dynamic value = null(); HXDLIN( 131) bool numNeg = (numerator < 0); HXDLIN( 131) bool denoNeg = (denominator < 0); HXDLIN( 131) if (::hx::IsNull( value )) { HXLINE( 131) if (( (bool)(positive) )) { HXLINE( 131) value = (( (Float)(numerator) ) / ( (Float)(denominator) )); } else { HXLINE( 131) value = (( (Float)(-(numerator)) ) / ( (Float)(denominator) )); } } HXDLIN( 131) bool _hx_tmp; HXDLIN( 131) if (!(numNeg)) { HXLINE( 131) _hx_tmp = denoNeg; } else { HXLINE( 131) _hx_tmp = true; } HXDLIN( 131) if (_hx_tmp) { HXLINE( 131) bool _hx_tmp; HXDLIN( 131) if (numNeg) { HXLINE( 131) _hx_tmp = denoNeg; } else { HXLINE( 131) _hx_tmp = false; } HXDLIN( 131) if (!(_hx_tmp)) { HXLINE( 131) positive = !(( (bool)(positive) )); } HXDLIN( 131) if (numNeg) { HXLINE( 131) numerator = -(numerator); } HXDLIN( 131) if (denoNeg) { HXLINE( 131) denominator = -(denominator); } } HXDLIN( 131) ::Dynamic this2 = ::Dynamic(::hx::Anon_obj::Create(4) ->setFixed(0,HX_("numerator",89,82,9c,c2),numerator) ->setFixed(1,HX_("positive",b9,a6,fa,ca),positive) ->setFixed(2,HX_("denominator",a6,25,84,eb),denominator) ->setFixed(3,HX_("value",71,7f,b8,31),value)); HXDLIN( 131) ::Dynamic frac = this2; HXLINE( 132) int n = ( (int)(frac->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ); HXDLIN( 132) int d = ( (int)(frac->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) ); HXDLIN( 132) ::String out; HXDLIN( 132) if ((n == 0)) { HXLINE( 132) out = HX_("0",30,00,00,00); } else { HXLINE( 132) if ((n == d)) { HXLINE( 132) out = HX_("1",31,00,00,00); } else { HXLINE( 132) if ((d == 1)) { HXLINE( 132) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 132) out = (HX_("",00,00,00,00) + n); } else { HXLINE( 132) out = (HX_("-",2d,00,00,00) + n); } } else { HXLINE( 132) if (( (bool)(frac->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 132) out = (((HX_("",00,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } else { HXLINE( 132) out = (((HX_("-",2d,00,00,00) + n) + HX_("/",2f,00,00,00)) + d); } } } } HXDLIN( 132) out1 = out; } HXLINE( 134) return out1; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Fraction_Impl__obj,byDenominator,return ) ::Array< ::Dynamic> Fraction_Impl__obj::all(Float f){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_138_all) HXDLIN( 138) return ::fracs::Fracs_obj::approximateFractions(f); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,all,return ) ::Array< ::Dynamic> Fraction_Impl__obj::similarToFraction( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_141_similarToFraction) HXLINE( 142) Float f; HXDLIN( 142) if (( (bool)(this1->__Field(HX_("positive",b9,a6,fa,ca),::hx::paccDynamic)) )) { HXLINE( 142) f = (( (Float)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } else { HXLINE( 142) f = (( (Float)(-(( (int)(this1->__Field(HX_("numerator",89,82,9c,c2),::hx::paccDynamic)) ))) ) / ( (Float)(this1->__Field(HX_("denominator",a6,25,84,eb),::hx::paccDynamic)) )); } HXLINE( 143) return ::fracs::Fracs_obj::approximateFractions(f); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,similarToFraction,return ) ::Array< ::Dynamic> Fraction_Impl__obj::similarToValue( ::Dynamic this1){ HX_STACKFRAME(&_hx_pos_2fa7d690c1539e6b_147_similarToValue) HXDLIN( 147) return ::fracs::Fracs_obj::approximateFractions(( (Float)(this1->__Field(HX_("value",71,7f,b8,31),::hx::paccDynamic)) )); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Fraction_Impl__obj,similarToValue,return ) Fraction_Impl__obj::Fraction_Impl__obj() { } bool Fraction_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"all") ) { outValue = all_dyn(); return true; } break; case 4: if (HX_FIELD_EQ(inName,"_new") ) { outValue = _new_dyn(); return true; } break; case 5: if (HX_FIELD_EQ(inName,"float") ) { outValue = _hx_float_dyn(); return true; } break; case 7: if (HX_FIELD_EQ(inName,"toFloat") ) { outValue = toFloat_dyn(); return true; } if (HX_FIELD_EQ(inName,"verbose") ) { outValue = verbose_dyn(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"optimize") ) { outValue = optimize_dyn(); return true; } if (HX_FIELD_EQ(inName,"toString") ) { outValue = toString_dyn(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"fromFloat") ) { outValue = fromFloat_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"fromString") ) { outValue = fromString_dyn(); return true; } if (HX_FIELD_EQ(inName,"firstFloat") ) { outValue = firstFloat_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"byDenominator") ) { outValue = byDenominator_dyn(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"similarToValue") ) { outValue = similarToValue_dyn(); return true; } break; case 16: if (HX_FIELD_EQ(inName,"optimizeFraction") ) { outValue = optimizeFraction_dyn(); return true; } break; case 17: if (HX_FIELD_EQ(inName,"similarToFraction") ) { outValue = similarToFraction_dyn(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *Fraction_Impl__obj_sMemberStorageInfo = 0; static ::hx::StaticInfo *Fraction_Impl__obj_sStaticStorageInfo = 0; #endif ::hx::Class Fraction_Impl__obj::__mClass; static ::String Fraction_Impl__obj_sStaticFields[] = { HX_("_new",61,15,1f,3f), HX_("optimize",dd,8c,18,1d), HX_("optimizeFraction",ff,83,8c,53), HX_("toFloat",21,12,1b,cf), HX_("float",9c,c5,96,02), HX_("verbose",82,d7,b9,71), HX_("fromString",db,2d,74,54), HX_("toString",ac,d0,6e,38), HX_("fromFloat",d2,af,1f,b7), HX_("firstFloat",4c,0f,75,40), HX_("byDenominator",0f,99,e1,96), HX_("all",21,f9,49,00), HX_("similarToFraction",a8,d8,07,56), HX_("similarToValue",0b,b9,73,3a), ::String(null()) }; void Fraction_Impl__obj::__register() { Fraction_Impl__obj _hx_dummy; Fraction_Impl__obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("fracs._Fraction.Fraction_Impl_",98,50,12,83); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Fraction_Impl__obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(Fraction_Impl__obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< Fraction_Impl__obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Fraction_Impl__obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Fraction_Impl__obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace fracs } // end namespace _Fraction
27,756
14,225
#include "packetreader.h" #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/ip.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <cstdio> #include <cstring> #include "scchk.h" #define MAXPACKET 128 struct sockaddr_in rpiaddr; PacketReader::PacketReader(int sock, DCDriver &dcDrive, ServoDriver &servoSteer, ServoDriver &servoYaw) : mFD(sock), mDcDrive(dcDrive), mServoSteer(servoSteer), mServoYaw(servoYaw) { static bool rpiaddr_initialized = false; if(!rpiaddr_initialized) { rpiaddr.sin_family = AF_INET; rpiaddr.sin_port = htons(5566); inet_aton("192.168.129.2", &rpiaddr.sin_addr); rpiaddr_initialized = true; } } PacketReader::~PacketReader() { close(mFD); } void PacketReader::readPacket() { struct sockaddr_in saddr; readPacket(&saddr); } void PacketReader::readPacket(struct sockaddr_in *saddr) { socklen_t slen = sizeof(struct sockaddr_in); signed char buf[256]; SC_CHK(::recvfrom, mFD, buf, 256, 0, (struct sockaddr *)saddr, &slen); // fprintf(stderr, "packet received %2x %2x %2x\n", (int)buf[0], (int)buf[1], (int)buf[2]); parsePacket(buf, saddr); } void PacketReader::parsePacket(const signed char *packet, const struct sockaddr_in *saddr) { switch((PacketReader::PacketType)packet[0]) { case Ping: parsePing(packet + 1); break; case DriveControl: parseDriveCmd(packet + 1); break; case CameraControl: parseCameraCmd(packet + 1); break; case Discover: parseDiscover(packet + 1, saddr); break; } } void PacketReader::parseDriveCmd(const signed char *packet) { int speed = packet[0]; int direction = packet[1]; mDcDrive.setDirection(speed > 0?DCDriver::Forward:DCDriver::Backward); mDcDrive.setSpeed(abs(speed)); if (direction > 100) direction = 100; else if (direction < -100) direction = -100; direction = (100 + direction) / 2; mServoSteer.setPosition(direction); } void PacketReader::parseCameraCmd(const signed char *packet) { int yaw = packet[0]; //unsigned int pitch = packet[1]; //unsigned int roll = packet[2]; if (yaw > 100) yaw = 100; else if (yaw < -100) yaw = -100; char ypos = (unsigned char) (100 + yaw) / 2; mServoYaw.setPosition(ypos); } void PacketReader::parsePing(const signed char *packet) { } void PacketReader::parseDiscover(const signed char *packet, const struct sockaddr_in *saddr) const { if(strcmp((char *)packet, "FIIT_TechNoLogic_Motorcontrol_Discover")) return; fprintf(stderr, "Discover received\n"); SC_CHK(::sendto, mFD, "FIIT_TechNoLogic_Motorcontrol_ACK", 33, 0, (const struct sockaddr *)saddr, sizeof(struct sockaddr_in)); system("killall -9 raspivid"); system("pkill -9 sendtemp.sh"); system("ssh pi@192.168.129.2 killall -9 raspivid"); char buf[1024]; char *ip = inet_ntoa(saddr->sin_addr); //sprintf(buf, "ssh pi@192.168.129.2 /home/pi/raspivid -t 999999 -o udp://%s:5567 -w 540 -h 480 -b 850000 &>/dev/null &", ip); // sprintf(buf, "/home/pi/raspivid -t 999999 -o udp://%s:5568 -w 540 -h 480 -b 850000 &>/dev/null &", ip); int w = 1080; int h = 960; int bitrate = 850000; int fps = 25; sprintf(buf, "ssh pi@192.168.129.2 /home/pi/raspivid -t 999999 -o udp://%s:5567 -w %d -h %d -b %d -fps %d &>/dev/null &", ip, w, h, bitrate); system(buf); sprintf(buf, "/home/pi/raspivid -t 999999 -o udp://%s:5568 -w %d -h %d -b %d -fps %d&>/dev/null &", ip, w, h, bitrate, fps); system(buf); sprintf(buf, "/home/pi/udpmotorcontrol/sendtemp.sh %s 5566 2>/dev/null &", ip); system(buf); int gpiofd = open("/sys/class/gpio/gpio23/value", O_WRONLY); write(gpiofd, "1", 1); close(gpiofd); }
3,769
1,690
#ifndef SD_TIMING_HPP #define SD_TIMING_HPP #include "Utility/Base.hpp" #include <cstdint> #include <queue> #include <chrono> namespace SD { using ClockType = std::chrono::high_resolution_clock; class SD_UTILITY_API Clock { public: Clock(); float GetElapsedMS() const; // Restart the clock, and return elapsed millisecond. float Restart(); private: std::chrono::time_point<ClockType> m_lastTicks; }; class SD_UTILITY_API FPSCounter { public: FPSCounter(uint8_t capacity); FPSCounter(const FPSCounter &) = delete; FPSCounter &operator=(const FPSCounter &) = delete; float GetFPS() const; float GetFrameTime() const; void Probe(); private: Clock m_clock; std::deque<float> m_queue; uint8_t m_capacity; }; } // namespace SD #endif /* SD_TIMING_HPP */
832
315
#include <iostream> #include <stack> #define NMAX=10 using namespace std; // A class is created to better implement the problem class Bucket{ private: stack <int> liter_list; // Is a stack where each element can be int(1) int bucket_size;// Max size of bucket public: Bucket(int bucket_size){ this->bucket_size=bucket_size; } int getLiters(){ return liter_list.size(); } void emptyBucket(){ liter_list.pop(); } // Transfers from another bucket until target_bucket is full or donor_bucket is empty void fillBucket(Bucket &donor_bucket){ while(liter_list.size()<bucket_size && !donor_bucket.isEmpty()) {donor_bucket.emptyBucket(); liter_list.push(1); } } // Method only used for filling the 20 liters bucket void fillBucket(){ while(liter_list.size()<bucket_size) liter_list.push(1); } int getSize(){ return bucket_size; } bool isEmpty(){ return (liter_list.size()==0); } bool isFull(){ return (liter_list.size()==bucket_size); } }; // Returns state for all 3 buckets (L1, L2, L3) void return_state(Bucket b1, Bucket b2, Bucket b3, int &state){ cout<<"State "<<state<<endl; cout<<"Bucket with max capacity "<<b1.getSize()<<" l holds "<<b1.getLiters()<<" l of wine "<<endl; cout<<"Bucket with max capacity "<<b2.getSize()<<" l holds "<<b2.getLiters()<<" l of wine "<<endl; cout<<"Bucket with max capacity "<<b3.getSize()<<" l holds "<<b3.getLiters()<<" l of wine "<<endl; cout<<endl; state++; } // int no_of_liters is the number of the desired liters to measure void measure_liters(int no_of_liters,Bucket &b8, Bucket &b5,Bucket &b20){ // Checks if any bucket contains the desired no_of_liters int state=1; while (b8.getLiters()!=no_of_liters && b5.getLiters()!=no_of_liters && b20.getLiters()!=no_of_liters ){ /* The algorithm is a circular one and goes like this: b20->b8->b5 Meaning that: -1)b8 is filled from b20 only when b8 is empty -2)b5 is filled from b8 every time b5 contains <5l of wine -is the main element because the quantity will vary between b8 and b5 -3)b5 is emptied in b20 when b5 is full -e.g. :b20=20, b8=0, b5=0; -> b20=12, b8=8, b5=0; ->b20=12, b8=3, b5=5; ->b20=17, b8=3, b5=0; ->b20=17, b8=0, b5=3; ... etc */ if(b8.isEmpty()){ b8.fillBucket(b20); return_state(b8,b5,b20,state); } else if(b5.isEmpty()){ b5.fillBucket(b8); return_state(b8,b5,b20,state); } else if(b5.isFull()){ b20.fillBucket(b5); return_state(b8,b5,b20,state); } else if (!b5.isFull()) {b5.fillBucket(b8); return_state(b8,b5,b20,state); } else{ cout<<"Other state, quitting"<<endl<<endl; return; } } if(b8.getLiters()==no_of_liters) cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 8l max capacity "<<endl<<endl; else if(b5.getLiters()==no_of_liters) cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 5l max capacity "<<endl<<endl; else{ cout<<"Success! Measured "<<no_of_liters<<" l in Bucket with 20l max capacity "<<endl<<endl; } } void reset_state(Bucket &b1,Bucket &b2,Bucket &b3){ while(!b1.isEmpty() || !b2.isEmpty() || !b3.isEmpty()){ if(!b1.isEmpty()) b1.emptyBucket(); if(!b2.isEmpty()) b2.emptyBucket(); if(!b3.isEmpty()) b3.emptyBucket(); } b3.fillBucket(); } int main() { // I thought that it would be more interesting to be able to measure any quantity of liters int no_of_liters=0; // inputs desired no. of liters to measure bool entered=0; // checks if there existed a first attempt to insert no_of_lites while(no_of_liters<1 || no_of_liters>20) //asks user to input a correct value of no_of_liters { if(entered==0){ cout<< "Insert number of desired liters to measure (1-20)"<<endl; cin>>no_of_liters; entered=1; } else{ cout<<"Please insert a number between 1 and 20 "<<endl; cin>>no_of_liters; } } // Create 3 buckets with max capacities of 8,5 and 20 liters Bucket b8 = Bucket(8); Bucket b5 = Bucket(5); Bucket b20 = Bucket(20); b20.fillBucket(); // fills the bucket with 20l max capacity measure_liters(no_of_liters,b8,b5,b20); }
4,743
1,721
class Solution { public: int removeDuplicates(vector<int>& nums) { int left = 0; int n = nums.size(); for (int i = 0; i < n; ++i) { if (!i or nums[i] != nums[i - 1]) { nums[left++] = nums[i]; } } return left; } };
258
110
#ifdef RECKLESS_ENABLE_TRACE_LOG #include <performance_log/trace_log.hpp> #include <fstream> #endif #include <performance_log/performance_log.hpp> #include <iostream> #include <unistd.h> #include LOG_INCLUDE char c = 'A'; float pi = 3.1415; int main() { unlink("log.txt"); performance_log::logger<4096, performance_log::rdtscp_cpuid_clock> performance_log; { LOG_INIT(6000); performance_log::rdtscp_cpuid_clock::bind_cpu(0); for(int i=0; i!=2500; ++i) { usleep(1000); struct timespec busywait_start; clock_gettime(CLOCK_REALTIME, &busywait_start); struct timespec busywait_end = busywait_start; while( (busywait_end.tv_sec - busywait_start.tv_sec)*1000000 + busywait_end.tv_nsec - busywait_start.tv_nsec < 1000 ) clock_gettime(CLOCK_REALTIME, &busywait_end); auto start = performance_log.start(); LOG(c, i, pi); performance_log.stop(start); } performance_log::rdtscp_cpuid_clock::unbind_cpu(); LOG_CLEANUP(); } for(auto sample : performance_log) { std::cout << sample.start << ' ' << sample.stop << std::endl; } #ifdef RECKLESS_ENABLE_TRACE_LOG std::ofstream trace_log("trace_log.txt", std::ios::trunc); reckless::detail::g_trace_log.save(trace_log); #endif return 0; }
1,385
525
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/global_media_controls/presentation_request_notification_producer.h" #include <utility> #include "base/unguessable_token.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/global_media_controls/media_notification_service.h" #include "components/media_router/browser/media_router.h" #include "components/media_router/browser/media_router_factory.h" #include "components/media_router/browser/presentation/presentation_service_delegate_impl.h" #include "components/media_router/common/providers/cast/cast_media_source.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" namespace { base::WeakPtr<media_router::WebContentsPresentationManager> GetActiveWebContentsPresentationManager() { auto* browser = chrome::FindLastActive(); if (!browser) return nullptr; auto* tab_strip = browser->tab_strip_model(); if (!tab_strip) return nullptr; auto* web_contents = tab_strip->GetActiveWebContents(); if (!web_contents) return nullptr; return media_router::WebContentsPresentationManager::Get(web_contents); } content::WebContents* GetWebContentsFromPresentationRequest( const content::PresentationRequest& request) { auto* rfh = content::RenderFrameHost::FromID(request.render_frame_host_id); return rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr; } } // namespace class PresentationRequestNotificationProducer:: PresentationRequestWebContentsObserver : public content::WebContentsObserver { public: PresentationRequestWebContentsObserver( content::WebContents* web_contents, PresentationRequestNotificationProducer* notification_producer) : content::WebContentsObserver(web_contents), notification_producer_(notification_producer) { DCHECK(notification_producer_); } private: void WebContentsDestroyed() override { notification_producer_->DeleteItemForPresentationRequest("Dialog closed."); } void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override { notification_producer_->DeleteItemForPresentationRequest("Dialog closed."); } void RenderProcessGone(base::TerminationStatus status) override { notification_producer_->DeleteItemForPresentationRequest("Dialog closed."); } PresentationRequestNotificationProducer* const notification_producer_; }; PresentationRequestNotificationProducer:: PresentationRequestNotificationProducer( MediaNotificationService* notification_service) : notification_service_(notification_service), container_observer_set_(this) { notification_service_->AddObserver(this); } PresentationRequestNotificationProducer:: ~PresentationRequestNotificationProducer() { notification_service_->RemoveObserver(this); } base::WeakPtr<media_message_center::MediaNotificationItem> PresentationRequestNotificationProducer::GetNotificationItem( const std::string& id) { if (item_ && item_->id() == id) { return item_->GetWeakPtr(); } else { return nullptr; } } std::set<std::string> PresentationRequestNotificationProducer::GetActiveControllableNotificationIds() const { return (item_ && !should_hide_) ? std::set<std::string>({item_->id()}) : std::set<std::string>(); } void PresentationRequestNotificationProducer::OnItemShown( const std::string& id, MediaNotificationContainerImpl* container) { if (container) { container_observer_set_.Observe(id, container); } } void PresentationRequestNotificationProducer::OnContainerDismissed( const std::string& id) { auto item = GetNotificationItem(id); if (item) { item->Dismiss(); DeleteItemForPresentationRequest("Dialog closed."); } } void PresentationRequestNotificationProducer::OnStartPresentationContextCreated( std::unique_ptr<media_router::StartPresentationContext> context) { DCHECK(context); const auto& request = context->presentation_request(); CreateItemForPresentationRequest(request, std::move(context)); } content::WebContents* PresentationRequestNotificationProducer::GetWebContents() { return item_ ? GetWebContentsFromPresentationRequest(item_->request()) : nullptr; } base::WeakPtr<PresentationRequestNotificationItem> PresentationRequestNotificationProducer::GetNotificationItem() { return item_ ? item_->GetWeakPtr() : nullptr; } void PresentationRequestNotificationProducer::OnNotificationListChanged() { ShowOrHideItem(); } void PresentationRequestNotificationProducer::SetTestPresentationManager( base::WeakPtr<media_router::WebContentsPresentationManager> presentation_manager) { test_presentation_manager_ = presentation_manager; } void PresentationRequestNotificationProducer::OnMediaDialogOpened() { // At the point where this method is called, MediaNotificationService is // in a state where it can't accept new notifications. As a workaround, // we simply defer the handling of the event. content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( &PresentationRequestNotificationProducer::AfterMediaDialogOpened, weak_factory_.GetWeakPtr(), test_presentation_manager_ ? test_presentation_manager_ : GetActiveWebContentsPresentationManager())); } void PresentationRequestNotificationProducer::OnMediaDialogClosed() { // This event needs to be handled asynchronously the be absolutely certain // it's handled later than a prior call to OnMediaDialogOpened(). content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( &PresentationRequestNotificationProducer::AfterMediaDialogClosed, weak_factory_.GetWeakPtr())); } void PresentationRequestNotificationProducer::AfterMediaDialogOpened( base::WeakPtr<media_router::WebContentsPresentationManager> presentation_manager) { presentation_manager_ = presentation_manager; // It's possible the presentation manager was deleted since the call to // this method was scheduled. if (!presentation_manager_) return; presentation_manager_->AddObserver(this); // Handle any request that was created while we weren't watching, first // making sure the dialog hasn't been closed since the we found out it was // opening. This is the normal way notifications are created for a default // presentation request. if (presentation_manager_->HasDefaultPresentationRequest() && notification_service_->HasOpenDialog()) { OnDefaultPresentationChanged( &presentation_manager_->GetDefaultPresentationRequest()); } } void PresentationRequestNotificationProducer::AfterMediaDialogClosed() { DeleteItemForPresentationRequest("Dialog closed."); if (presentation_manager_) presentation_manager_->RemoveObserver(this); presentation_manager_ = nullptr; } void PresentationRequestNotificationProducer::OnMediaRoutesChanged( const std::vector<media_router::MediaRoute>& routes) { if (!routes.empty()) { notification_service_->HideMediaDialog(); item_->Dismiss(); } } void PresentationRequestNotificationProducer::OnDefaultPresentationChanged( const content::PresentationRequest* presentation_request) { // NOTE: We only observe the presentation manager while the media control // dialog is open, so this method is only handling the unusual case where // the default presentation request is changed while the dialog is open. // In the even more unusual case where the dialog is already open with a // notification for a non-default request, we ignored changes in the // default request. if (!HasItemForNonDefaultRequest()) { DeleteItemForPresentationRequest("Default presentation changed."); if (presentation_request) { CreateItemForPresentationRequest(*presentation_request, nullptr); } } } void PresentationRequestNotificationProducer::CreateItemForPresentationRequest( const content::PresentationRequest& request, std::unique_ptr<media_router::StartPresentationContext> context) { presentation_request_observer_ = std::make_unique<PresentationRequestWebContentsObserver>( GetWebContentsFromPresentationRequest(request), this); // This may replace an existing item, which is the right thing to do if // we've reached this point. item_.emplace(notification_service_, request, std::move(context)); ShowOrHideItem(); } void PresentationRequestNotificationProducer::DeleteItemForPresentationRequest( const std::string& message) { if (!item_) return; const auto id{item_->id()}; item_.reset(); presentation_request_observer_.reset(); notification_service_->HideNotification(id); } void PresentationRequestNotificationProducer::ShowOrHideItem() { if (!item_) { should_hide_ = true; return; } auto* web_contents = GetWebContentsFromPresentationRequest(item_->request()); bool new_visibility = web_contents ? notification_service_->HasActiveNotificationsForWebContents( web_contents) : true; if (should_hide_ == new_visibility) return; should_hide_ = new_visibility; if (should_hide_) { notification_service_->HideNotification(item_->id()); } else { notification_service_->ShowNotification(item_->id()); } }
9,773
2,639
//////////////////////////////////////////////////////////////////////////////// // pump.cpp // (c) Andreas Müller // see LICENSE.md //////////////////////////////////////////////////////////////////////////////// #include "ledMatrix.h" //////////////////////////////////////////////////////////////////////////////// class Pump { public: Pump(unsigned char mode) ; void Update() ; void Display() ; void Config(unsigned char type, unsigned char value) ; private: unsigned char _mode ; Rgb &_curRgb ; Rgb _deltaRgb ; Rgb _rgb[LedMatrix::kX/2] ; unsigned char _brightness ; unsigned char _state ; } ; static_assert(sizeof(Pump) < (RAMSIZE - 0x28), "not enough RAM") ; //////////////////////////////////////////////////////////////////////////////// Pump::Pump(unsigned char mode) : _mode(mode), _curRgb(_rgb[LedMatrix::kX/2 - 1]), _brightness(0x7f), _state(0) { for (Rgb *iRgb = _rgb, *eRgb = _rgb + LedMatrix::kX/2 ; iRgb < eRgb ; ++iRgb) iRgb->Clr(0x10) ; _deltaRgb.Rnd(_brightness) ; _deltaRgb.Sub(_curRgb) ; _deltaRgb.DivX() ; } void Pump::Update() { if (_state == 0) { _deltaRgb.Rnd(_brightness) ; _deltaRgb.Sub(_curRgb) ; _deltaRgb.DivX() ; } if (_state < LedMatrix::kX) { for (unsigned char x2 = 0 ; x2 < LedMatrix::kX/2 - 1 ; ++x2) _rgb[x2] = _rgb[x2+1] ; _curRgb.Add(_deltaRgb) ; } else if (_state < LedMatrix::kX * 2) { for (unsigned char x2 = 0 ; x2 < LedMatrix::kX/2 - 1 ; ++x2) _rgb[x2] = _rgb[x2+1] ; } if (++_state == LedMatrix::kX * 3) _state = 0 ; } void Pump::Display() { for (unsigned short idx = 0 ; idx < LedMatrix::kSize ; ++idx) { switch (_mode) { case 1: { unsigned char x, y ; LedMatrix::IdxToCoord(idx, x, y) ; if (x >= LedMatrix::kX/2) x = LedMatrix::kX-1 - x ; if (y >= LedMatrix::kY/2) y = LedMatrix::kY-1 - y ; if (y < x) x = y ; _rgb[x].Send() ; } break ; default: { _curRgb.Send() ; } break ; } } } void Pump::Config(unsigned char type, unsigned char value) { switch (type) { case LedMatrix::ConfigBrightness: _brightness = value ; break ; case LedMatrix::ConfigForceRedraw: break ; } } //////////////////////////////////////////////////////////////////////////////// // EOF ////////////////////////////////////////////////////////////////////////////////
2,400
899
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // 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. //***************************************************************************** // NOTE: This file follows nGraph format style. // Follows nGraph naming convention for public APIs only, else MLIR naming // convention. #pragma once #include <mlir/IR/Builders.h> #include <mlir/IR/Module.h> #include <mlir/IR/Types.h> #include <typeindex> #include <unordered_map> #include <vector> #include "contrib/mlir/runtime/cpu/memory_manager.hpp" #include "ngraph/check.hpp" #include "ngraph/descriptor/tensor.hpp" #include "ngraph/function.hpp" #include "ngraph/log.hpp" #include "ngraph/node.hpp" #include "ngraph/op/experimental/compiled_kernel.hpp" namespace ngraph { namespace runtime { namespace ngmlir { /// MLIR Compiler. Given an nGraph sub-graph, represented as CompiledKernel /// node, it /// translates the graph down to nGraph dialect and applies core optimizations. /// /// The compiler owns the MLIR module until compilation is done. After that, /// the module can be grabbed and plugged into MLIR backends. class MLIRCompiler { public: /// Initializes MLIR environment. It must be called only once. static void init(); public: MLIRCompiler(std::shared_ptr<ngraph::Function> function, ::mlir::MLIRContext& context); /// Compiles a subgraph with MLIR void compile(); ::mlir::OwningModuleRef& get_module() { return m_module; } private: // Converts an nGraph sub-graph to MLIR nGraph dialect. void buildNgDialectModule(); // Applies any nGraph dialect optimizations void optimizeNgDialect(); private: // Sub-graph to be compiled and executed with MLIR. std::shared_ptr<ngraph::Function> m_function; // MLIR context that holds all the MLIR information related to the sub-graph // compilation. ::mlir::MLIRContext& m_context; ::mlir::OwningModuleRef m_module; // Global initialization for MLIR compiler static bool initialized; }; } } }
3,034
799
/* Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq 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/>. */ #define __STDC_LIMIT_MACROS // to define SIZE_MAX with older compilers #include "testutil.hpp" #include "testutil_unity.hpp" void setUp () { } void tearDown () { } void handler (int timer_id_, void *arg_) { (void) timer_id_; // Stop 'unused' compiler warnings *((bool *) arg_) = true; } int sleep_and_execute (void *timers_) { int timeout = zmq_timers_timeout (timers_); // Sleep methods are inaccurate, so we sleep in a loop until time arrived while (timeout > 0) { msleep (timeout); timeout = zmq_timers_timeout (timers_); } return zmq_timers_execute (timers_); } void test_null_timer_pointers () { void *timers = NULL; TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_destroy (&timers)); // TODO this currently triggers an access violation #if 0 TEST_ASSERT_FAILURE_ERRNO(EFAULT, zmq_timers_destroy (NULL)); #endif const size_t dummy_interval = 100; const int dummy_timer_id = 1; TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_add (timers, dummy_interval, &handler, NULL)); TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_add (&timers, dummy_interval, &handler, NULL)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_cancel (timers, dummy_timer_id)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_cancel (&timers, dummy_timer_id)); TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_set_interval (timers, dummy_timer_id, dummy_interval)); TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_set_interval (&timers, dummy_timer_id, dummy_interval)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_reset (timers, dummy_timer_id)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_reset (&timers, dummy_timer_id)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_timeout (timers)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_timeout (&timers)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_execute (timers)); TEST_ASSERT_FAILURE_ERRNO (EFAULT, zmq_timers_execute (&timers)); } void test_corner_cases () { void *timers = zmq_timers_new (); TEST_ASSERT_NOT_NULL (timers); const size_t dummy_interval = SIZE_MAX; const int dummy_timer_id = 1; // attempt to cancel non-existent timer TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_cancel (timers, dummy_timer_id)); // attempt to set interval of non-existent timer TEST_ASSERT_FAILURE_ERRNO ( EINVAL, zmq_timers_set_interval (timers, dummy_timer_id, dummy_interval)); // attempt to reset non-existent timer TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_reset (timers, dummy_timer_id)); // attempt to add NULL handler TEST_ASSERT_FAILURE_ERRNO ( EFAULT, zmq_timers_add (timers, dummy_interval, NULL, NULL)); const int timer_id = TEST_ASSERT_SUCCESS_ERRNO ( zmq_timers_add (timers, dummy_interval, handler, NULL)); // attempt to cancel timer twice // TODO should this case really be an error? canceling twice could be allowed TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_cancel (timers, timer_id)); TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_cancel (timers, timer_id)); // timeout without any timers active TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_timers_timeout (timers)); // cleanup TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_destroy (&timers)); } void test_timers () { void *timers = zmq_timers_new (); TEST_ASSERT_NOT_NULL (timers); bool timer_invoked = false; const unsigned long full_timeout = 100; void *const stopwatch = zmq_stopwatch_start (); const int timer_id = TEST_ASSERT_SUCCESS_ERRNO ( zmq_timers_add (timers, full_timeout, handler, &timer_invoked)); // Timer should not have been invoked yet TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); if (zmq_stopwatch_intermediate (stopwatch) < full_timeout) { TEST_ASSERT_FALSE (timer_invoked); } // Wait half the time and check again long timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers)); msleep (timeout / 2); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); if (zmq_stopwatch_intermediate (stopwatch) < full_timeout) { TEST_ASSERT_FALSE (timer_invoked); } // Wait until the end TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers)); TEST_ASSERT_TRUE (timer_invoked); timer_invoked = false; // Wait half the time and check again timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers)); msleep (timeout / 2); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); if (zmq_stopwatch_intermediate (stopwatch) < 2 * full_timeout) { TEST_ASSERT_FALSE (timer_invoked); } // Reset timer and wait half of the time left TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_reset (timers, timer_id)); msleep (timeout / 2); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); if (zmq_stopwatch_stop (stopwatch) < 2 * full_timeout) { TEST_ASSERT_FALSE (timer_invoked); } // Wait until the end TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers)); TEST_ASSERT_TRUE (timer_invoked); timer_invoked = false; // reschedule TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_set_interval (timers, timer_id, 50)); TEST_ASSERT_SUCCESS_ERRNO (sleep_and_execute (timers)); TEST_ASSERT_TRUE (timer_invoked); timer_invoked = false; // cancel timer timeout = TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_timeout (timers)); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_cancel (timers, timer_id)); msleep (timeout * 2); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_execute (timers)); TEST_ASSERT_FALSE (timer_invoked); TEST_ASSERT_SUCCESS_ERRNO (zmq_timers_destroy (&timers)); } int main () { setup_test_environment (); UNITY_BEGIN (); RUN_TEST (test_timers); RUN_TEST (test_null_timer_pointers); RUN_TEST (test_corner_cases); return UNITY_END (); }
7,561
2,642
/* * $Header: /Book/StatusBar.cpp 14 16.07.04 10:42 Oslph312 $ * * NOTE: Both Toolbar and Statusbar are tailored to TextEdit. * A more general approach would be to derive both from base classes. */ #include "precomp.h" #include "Statusbar.h" #include "MenuFont.h" #include "HTML.h" #include "InstanceSubclasser.h" #include "formatMessage.h" #include "formatNumber.h" #include "graphics.h" #include "utils.h" #include "resource.h" #ifndef SB_SETICON #define SB_SETICON (WM_USER+15) #endif PRIVATE bool sm_bHighlight = false; PRIVATE LRESULT CALLBACK statusbarParentSpy( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ); PRIVATE InstanceSubclasser s_parentSubclasser( statusbarParentSpy ); /** * Recalculates the sizes of the various status bar parts. */ PRIVATE void recalcParts( HWND hwndStatusbar, int nTotalWidth = -1 ) { assert( IsWindow( hwndStatusbar ) ); if ( -1 == nTotalWidth ) { const Rect rc = getWindowRect( hwndStatusbar ); nTotalWidth = rc.width(); } const int nBorder = GetSystemMetrics( SM_CXEDGE ); const int nWidth = nTotalWidth - GetSystemMetrics( SM_CXVSCROLL ) - nBorder - 1; const int nExtra = 4 * nBorder; const int nWidthUnicode = measureString( _T( "Unicode" ) ).cx + nExtra; const int nWidthPosition = measureString( _T( "Ln 99,999 Col 999 100%" ) ).cx + nExtra; const int nWidthToolbarButton = GetSystemMetrics( MenuFont::isLarge() ? SM_CXICON : SM_CXSMICON ); const int nWidthIcon = nWidthToolbarButton + nExtra; const int aParts[] = { nWidth - nWidthPosition - nWidthUnicode - nWidthIcon, nWidth - nWidthUnicode - nWidthIcon, nWidth - nWidthIcon, nWidth - 0, // If we use -1, we overflow into the sizing grip. }; SNDMSG( hwndStatusbar, SB_SETPARTS, dim( aParts ), reinterpret_cast< LPARAM >( aParts ) ); } PRIVATE void drawItem( DRAWITEMSTRUCT *pDIS ) { // This returns a pointer to the static // szMessageBuffer used in setMessageV: LPCTSTR pszText = reinterpret_cast< LPCTSTR >( SNDMSG( pDIS->hwndItem, SB_GETTEXT, 0, 0 ) ); const int nSavedDC = SaveDC( pDIS->hDC ); if ( sm_bHighlight ) { SetTextColor( pDIS->hDC, GetSysColor( COLOR_HIGHLIGHTTEXT ) ); SetBkColor ( pDIS->hDC, GetSysColor( COLOR_HIGHLIGHT ) ); fillSysColorSolidRect( pDIS->hDC, &pDIS->rcItem, COLOR_HIGHLIGHT ); pDIS->rcItem.left += GetSystemMetrics( SM_CXEDGE ); } else { SetTextColor( pDIS->hDC, GetSysColor( COLOR_BTNTEXT ) ); SetBkColor ( pDIS->hDC, GetSysColor( COLOR_BTNFACE ) ); } const int nHeight = Rect( pDIS->rcItem ).height(); const int nExtra = nHeight - MenuFont::getHeight(); pDIS->rcItem.top += nExtra / 2 - 1; pDIS->rcItem.left += GetSystemMetrics( SM_CXEDGE ); paintHTML( pDIS->hDC, pszText, &pDIS->rcItem, GetWindowFont( pDIS->hwndItem ), PHTML_SINGLE_LINE ); verify( RestoreDC( pDIS->hDC, nSavedDC ) ); } PRIVATE LRESULT CALLBACK statusbarParentSpy( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) { const LRESULT lResult = s_parentSubclasser.callOldProc( hwnd, msg, wParam, lParam ); if ( WM_SIZE == msg ) { HWND hwndStatusbar = s_parentSubclasser.getUserDataAsHwnd( hwnd ); assert( IsWindow( hwndStatusbar ) ); const int cx = LOWORD( lParam ); recalcParts( hwndStatusbar, cx ); SNDMSG( hwndStatusbar, WM_SIZE, wParam, lParam ); } else if ( WM_DRAWITEM == msg ) { drawItem( reinterpret_cast< DRAWITEMSTRUCT * >( lParam ) ); } return lResult; } Statusbar::Statusbar( HWND hwndParent, UINT uiID ) : m_hicon( 0 ) , m_nIndex( 0 ) , zoomPercentage( 100 ) { assert( 0 != this ); const HINSTANCE hinst = getModuleHandle(); attach( CreateWindowEx( 0, STATUSCLASSNAME, _T( "" ), SBARS_SIZEGRIP | WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, hwndParent, (HMENU) uiID, hinst, 0 ) ); assert( IsWindow( *this ) ); if ( !IsWindow( *this ) ) { throwException( _T( "Unable to create status bar" ) ); } onSettingChange( 0 ); // Sets the font and the parts. verify( s_parentSubclasser.subclass( hwndParent, m_hwnd ) ); setMessage( IDS_READY ); } Statusbar::~Statusbar() { if ( 0 != m_hicon ) { DestroyIcon( m_hicon ); } } void __cdecl Statusbar::setMessageV( LPCTSTR pszFmt, va_list vl ) { // This *must* be a static buffer. Since the first pane is // SBT_OWNERDRAW, the status bar control doesn't know that // this is text; the lParam is merely 32 arbitrary bits of // application data, and the status bar doesn't retain the // text, just the pointer. static TCHAR szMessageBuffer[ 512 ]; assert( isGoodStringPtr( pszFmt ) ); if ( isGoodStringPtr( pszFmt ) ) { const String strMessage = formatMessageV( pszFmt, vl ); _tcsncpy_s( szMessageBuffer, strMessage.c_str(), _TRUNCATE ); } else { _tcscpy_s( szMessageBuffer, _T( "Internal Error" ) ); } int nPart = message_part | SBT_OWNERDRAW; if ( sm_bHighlight ) { nPart |= SBT_NOBORDERS; // SBT_POPOUT // This invalidation is necessary for SBT_NOBORDERS. // With SBT_POPOUT, it is not necessary. Rect rc; sendMessage( SB_GETRECT, message_part, reinterpret_cast< LPARAM >( &rc ) ); InvalidateRect( *this, &rc, TRUE ); } setText( nPart, szMessageBuffer ); } void __cdecl Statusbar::setMessage( LPCTSTR pszFmt, ... ) { sm_bHighlight = false; va_list vl; va_start( vl, pszFmt ); setMessageV( pszFmt, vl ); va_end( vl ); } void __cdecl Statusbar::setMessage( UINT idFmt, ... ) { sm_bHighlight = false; const String strFmt = loadString( idFmt ); va_list vl; va_start( vl, idFmt ); setMessageV( strFmt.c_str(), vl ); va_end( vl ); } void __cdecl Statusbar::setHighlightMessage( UINT idFmt, ... ) { sm_bHighlight = true; const String strFmt = loadString( idFmt ); va_list vl; va_start( vl, idFmt ); setMessageV( strFmt.c_str(), vl ); va_end( vl ); } void __cdecl Statusbar::setErrorMessage( UINT idFlags, UINT idFmt, ... ) { va_list vl; va_start( vl, idFmt ); MessageBeep( idFlags ); const String strFmt = loadString( idFmt ); if ( IsWindowVisible( *this ) ) { sm_bHighlight = true; setMessageV( strFmt.c_str(), vl ); } else { messageBoxV( GetParent( *this ), MB_OK | idFlags, strFmt.c_str(), vl ); } va_end( vl ); } void Statusbar::update( void ) { #if 0 // TODO: Unit test of formatNumber trace( _T( "testing formatNumber: %d = %s\n" ), 0, formatNumber( 0 ).c_str() ); trace( _T( "testing formatNumber: %d = %s\n" ), 123, formatNumber( 123 ).c_str() ); trace( _T( "testing formatNumber: %d = %s\n" ), 12345, formatNumber( 12345 ).c_str() ); trace( _T( "testing formatNumber: %d = %s\n" ), 1234567890, formatNumber( 1234567890 ).c_str() ); #endif const String strLine = formatNumber( position.y + 1 ); const String strColumn = formatNumber( position.x + 1 ); const String strPos = formatMessage( IDS_POSITION, strLine.c_str(), strColumn.c_str() ); const String strZoom = formatMessage( _T( " %1!d!%%\t" ), this->zoomPercentage ); const String str = strPos + strZoom; setText( position_part, str.c_str() ); const HWND hwndEditWnd = GetDlgItem( GetParent( *this ), IDC_EDIT ); if ( GetFocus() == hwndEditWnd ) { setMessage( IDS_READY ); } } void Statusbar::update( const Point& updatedPosition ) { this->position = updatedPosition; update(); } void Statusbar::update( const int updatedZoomPercentage ) { this->zoomPercentage = updatedZoomPercentage; update(); } void Statusbar::setFileType( const bool isUnicode ) { setText( filetype_part, isUnicode ? _T( "\tUnicode\t" ) : _T( "\tANSI\t" ) ); } void Statusbar::setIcon( int nIndex ) { const int nResource = MenuFont::isLarge() ? 121 : 120; const HINSTANCE hinst = GetModuleHandle(_T("COMCTL32")); const HIMAGELIST hImageList = ImageList_LoadImage(hinst, MAKEINTRESOURCE(nResource), 0, 0, CLR_DEFAULT, IMAGE_BITMAP, LR_DEFAULTSIZE | LR_LOADMAP3DCOLORS); setIcon(hImageList, nIndex); if (0 != hImageList) { verify(ImageList_Destroy(hImageList)); } } void Statusbar::setIcon( HIMAGELIST hImageList, int nIndex ) { if ( 0 != m_hicon ) { DestroyIcon( m_hicon ); m_hicon = 0; } m_nIndex = nIndex; if ( 0 != m_nIndex ) { m_hicon = ImageList_GetIcon( hImageList, m_nIndex, ILD_NORMAL ); } sendMessage( SB_SETICON, action_part, reinterpret_cast< LPARAM >( m_hicon ) ); UpdateWindow( *this ); } void Statusbar::onSettingChange( LPCTSTR pszSection ) { const HFONT hfont = MenuFont::getFont(); assert( 0 != hfont ); SetWindowFont( *this, hfont, true ); setIcon( m_nIndex ); recalcParts( *this ); } // end of file
8,915
3,501
//********************************************************* // Trip_Length_Data.cpp - trip length data class //********************************************************* #include "Trip_Length_Data.hpp" //--------------------------------------------------------- // Trip_Length_Data constructor //--------------------------------------------------------- Trip_Length_Data::Trip_Length_Data (void) : Class2_Index (0, 0) { Count (0); } //--------------------------------------------------------- // Trip_Length_Array constructor //--------------------------------------------------------- Trip_Length_Array::Trip_Length_Array (int max_records) : Class2_Array (sizeof (Trip_Length_Data), max_records), Static_Service () { increment = 0; output_flag = false; } //---- Add Trip ---- bool Trip_Length_Array::Add_Trip (int mode, int purpose1, int purpose2, int length, int count) { Trip_Length_Data *data_ptr, data_rec; if (increment <= 0 || length < 0) return (false); data_rec.Mode (mode); if (purpose1 > purpose2) { data_rec.Purpose1 (purpose2); data_rec.Purpose2 (purpose1); } else { data_rec.Purpose1 (purpose1); data_rec.Purpose2 (purpose2); } length /= increment; if (length >= 0xFFFF) length = 0xFFFE; data_rec.Increment (length); data_ptr = (Trip_Length_Data *) Get (&data_rec); if (data_ptr == NULL) { data_ptr = New_Record (true); if (data_ptr == NULL) return (false); data_rec.Count (0); if (!Add (&data_rec)) return (false); } data_ptr->Add_Count (count); return (true); } //---- Open_Trip_Length_File ---- bool Trip_Length_Array::Open_Trip_Length_File (char *filename, char *label) { if (filename != NULL) { output_flag = true; exe->Print (1); if (label == NULL) { length_file.File_Type ("New Trip Length File"); } else { length_file.File_Type (label); } length_file.File_Access (Db_Code::CREATE); if (!length_file.Open (exe->Project_Filename (filename, exe->Extension ()))) { exe->File_Error ("Creating New Trip Length File", length_file.Filename ()); return (false); } } return (true); } //---- Write_Trip_Length_File ---- void Trip_Length_Array::Write_Trip_Length_File (void) { if (!output_flag) return; int num_out; Trip_Length_Data *data_ptr; FILE *file; exe->Show_Message ("Writing %s -- Record", length_file.File_Type ()); exe->Set_Progress (); file = length_file.File (); //---- write the header ---- fprintf (file, "MODE\tPURPOSE1\tPURPOSE2\tLENGTH\tTRIPS\n"); //---- write each record ---- num_out = 0; for (data_ptr = First_Key (); data_ptr; data_ptr = Next_Key ()) { exe->Show_Progress (); fprintf (file, "%d\t%d\t%d\t%d\t%d\n", data_ptr->Mode (), data_ptr->Purpose1 (), data_ptr->Purpose2 (), data_ptr->Increment () * increment, data_ptr->Count ()); num_out++; } exe->End_Progress (); length_file.Close (); exe->Print (2, "Number of %s Records = %d", length_file.File_Type (), num_out); } // ////---- Report ---- // //void Trip_Length_Array::Report (int number, char *_title, char *_key1, char *_key2) //{ // int size; // Trip_Length_Data *data_ptr, total; // // //---- set header values ---- // // keys = 0; // if (_title != NULL) { // size = (int) strlen (_title) + 1; // title = new char [size]; // str_cpy (title, size, _title); // // exe->Show_Message (title); // } // if (_key1 != NULL) { // size = (int) strlen (_key1) + 1; // key1 = new char [size]; // str_cpy (key1, size, _key1); // keys++; // } // if (_key2 != NULL) { // size = (int) strlen (_key2) + 1; // key2 = new char [size]; // str_cpy (key2, size, _key2); // keys++; // } // // //---- print the report ---- // // exe->Header_Number (number); // // if (!exe->Break_Check (Num_Records () + 7)) { // exe->Print (1); // Header (); // } // // for (data_ptr = First_Key (); data_ptr; data_ptr = Next_Key ()) { // if (data_ptr->Count () == 0) continue; // // if (keys == 2) { // exe->Print (1, "%3d-%-3d", (data_ptr->Group () >> 16), (data_ptr->Group () & 0x00FF)); // } else { // exe->Print (1, "%5d ", data_ptr->Group ()); // } // // exe->Print (0, " %9d %8d %8d %8d %8d %8.2lf %8.2lf %8.2lf %8.2lf", // data_ptr->Count (), (int) (data_ptr->Min_Distance () + 0.5), // (int) (data_ptr->Max_Distance () + 0.5), (int) (data_ptr->Average_Distance () + 0.5), // (int) (data_ptr->StdDev_Distance () + 0.5), data_ptr->Min_Time () / 60.0, // data_ptr->Max_Time () / 60.0, data_ptr->Average_Time () / 60.0, // data_ptr->StdDev_Time () / 60.0); // // if (total.Count () == 0) { // total.Count (data_ptr->Count ()); // total.Distance (data_ptr->Distance ()); // total.Time (data_ptr->Time ()); // total.Distance_Sq (data_ptr->Distance_Sq ()); // total.Time_Sq (data_ptr->Time_Sq ()); // // total.Min_Distance (data_ptr->Min_Distance ()); // total.Max_Distance (data_ptr->Max_Distance ()); // // total.Min_Time (data_ptr->Min_Time ()); // total.Max_Time (data_ptr->Max_Time ()); // } else { // total.Count (total.Count () + data_ptr->Count ()); // total.Distance (total.Distance () + data_ptr->Distance ()); // total.Time (total.Time () + data_ptr->Time ()); // total.Distance_Sq (total.Distance_Sq () + data_ptr->Distance_Sq ()); // total.Time_Sq (total.Time_Sq () + data_ptr->Time_Sq ()); // // if (total.Min_Distance () > data_ptr->Min_Distance ()) total.Min_Distance (data_ptr->Min_Distance ()); // if (total.Max_Distance () < data_ptr->Max_Distance ()) total.Max_Distance (data_ptr->Max_Distance ()); // // if (total.Min_Time () > data_ptr->Min_Time ()) total.Min_Time (data_ptr->Min_Time ()); // if (total.Max_Time () < data_ptr->Max_Time ()) total.Max_Time (data_ptr->Max_Time ()); // } // } // exe->Print (2, "Total %9d %8d %8d %8d %8d %8.2lf %8.2lf %8.2lf %8.2lf", // total.Count (), (int) (total.Min_Distance () + 0.5), (int) (total.Max_Distance () + 0.5), // (int) (total.Average_Distance () + 0.5), (int) (total.StdDev_Distance () + 0.5), // total.Min_Time () / 60.0, total.Max_Time () / 60.0, total.Average_Time () / 60.0, // total.StdDev_Time () / 60.0); // // exe->Header_Number (0); //} // ////---- Header ---- // //void Trip_Length_Array::Header (void) //{ // if (title != NULL) { // exe->Print (1, title); // } else { // exe->Print (1, "Trip Length Summary Report"); // } // if (keys < 2 || key1 == NULL) { // exe->Print (2, "%19c", BLANK); // } else { // exe->Print (2, "%-7.7s%12c", key1, BLANK); // } // exe->Print (0, "------- Distance (meters) -------- --------- Time (minutes) ---------"); // // if (keys == 2 && key2 != NULL) { // exe->Print (1, "%-7.7s", key2); // } else if (keys == 1 && key1 != NULL) { // exe->Print (1, "%-7.7s", key1); // } else { // exe->Print (1, "Group "); // } // exe->Print (0, " Trips Minimum Maximum Average StdDev Minimum Maximum Average StdDev"); // exe->Print (1); //} // ///*********************************************|*********************************************** // // [title] // // [key1] ------- Distance (meters) -------- --------- Time (minutes) --------- // [key2] Trips Minimum Maximum Average StdDev Minimum Maximum Average StdDev // // ddd-ddd ddddddddd ddddddd ddddddd ddddddd ddddddd ffff.ff ffff.ff ffff.ff ffff.ff // // Total ddddddddd ddddddd ddddddd ddddddd ddddddd ffff.ff ffff.ff ffff.ff ffff.ff // //**********************************************|***********************************************/
7,427
3,088
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // // blood.cpp // #include "blood.hpp" #include "context.hpp" #include "info-region.hpp" #include "level.hpp" #include "random.hpp" #include "screen-regions.hpp" #include "settings.hpp" #include "util.hpp" namespace halloween { Blood::Blood() : m_texture() , m_textureCoords1() , m_textureCoords2() , m_isUsingFirstAnim(true) , m_timePerFrame(0.05f) , m_elapsedTimeSec(0.0f) , m_textureIndex(0) , m_sprite() , m_isFinished(true) { // there are two blood splat animation in the same texture m_textureCoords1.emplace_back(0, 0, 128, 128); m_textureCoords1.emplace_back(128, 0, 128, 128); m_textureCoords1.emplace_back(256, 0, 128, 128); m_textureCoords1.emplace_back(384, 0, 128, 128); m_textureCoords1.emplace_back(512, 0, 128, 128); m_textureCoords1.emplace_back(640, 0, 128, 128); m_textureCoords1.emplace_back(768, 0, 128, 128); m_textureCoords1.emplace_back(896, 0, 128, 128); m_textureCoords1.emplace_back(1024, 0, 128, 128); m_textureCoords2.emplace_back(0, 128, 128, 128); m_textureCoords2.emplace_back(128, 128, 128, 128); m_textureCoords2.emplace_back(256, 128, 128, 128); m_textureCoords2.emplace_back(384, 128, 128, 128); m_textureCoords2.emplace_back(512, 128, 128, 128); m_textureCoords2.emplace_back(640, 128, 128, 128); m_textureCoords2.emplace_back(768, 128, 128, 128); m_textureCoords2.emplace_back(896, 128, 128, 128); m_textureCoords2.emplace_back(1024, 128, 128, 128); } void Blood::setup(const Settings & settings) { const std::string PATH = (settings.media_path / "image" / "blood.png").string(); m_texture.loadFromFile(PATH); m_texture.setSmooth(true); m_sprite.setTexture(m_texture); } void Blood::start(Context & context, const sf::Vector2f & POSITION, const bool WILL_SPLASH_RIGHT) { m_isFinished = false; m_elapsedTimeSec = 0.0f; m_textureIndex = 0; m_isUsingFirstAnim = context.random.boolean(); m_sprite.setPosition(POSITION); if (m_isUsingFirstAnim) { m_sprite.setTextureRect(m_textureCoords1.at(0)); } else { m_sprite.setTextureRect(m_textureCoords2.at(0)); } if (WILL_SPLASH_RIGHT) { m_sprite.setScale(1.0f, 1.0f); } else { m_sprite.setScale(-1.0f, 1.0f); } } void Blood::update(Context &, const float FRAME_TIME_SEC) { if (m_isFinished) { return; } m_elapsedTimeSec += FRAME_TIME_SEC; if (m_elapsedTimeSec < m_timePerFrame) { return; } m_elapsedTimeSec -= m_timePerFrame; ++m_textureIndex; if (m_textureIndex >= m_textureCoords1.size()) { m_textureIndex = 0; m_isFinished = true; return; } if (m_isUsingFirstAnim) { m_sprite.setTextureRect(m_textureCoords1.at(m_textureIndex)); } else { m_sprite.setTextureRect(m_textureCoords2.at(m_textureIndex)); } } void Blood::draw(sf::RenderTarget & target, sf::RenderStates states) const { if (!m_isFinished) { target.draw(m_sprite, states); } } } // namespace halloween
3,692
1,528
#include "Button.hpp" Button::Button( sf::Vector2f position, sf::Vector2f dimensions, sf::Font* font, std::string text, unsigned character_size, bool hasBorder, sf::Color text_idle_color, sf::Color text_hover_color, sf::Color text_active_color, sf::Color idle_color, sf::Color hover_color, sf::Color active_color) { /* while (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { continue; } */ this->buttonState = BTN_IDLE; this->setBackdrop(sf::Vector2f(dimensions.x, dimensions.y), idle_color, sf::Vector2f(position.x, position.y), active_color, 1); this->setFont(*font); this->setString(text); this->setFillColor(text_idle_color); this->setCharacterSize(character_size); this->setPosition(position.x + ((dimensions.x - this->getGlobalBounds().width) / 2 - 1), position.y + ((dimensions.y - character_size) / 2) - 5); if (hasBorder) { this->backdrop.setOutlineColor(sf::Color::Black); this->setOutlineColor(sf::Color::Black); } // Update Private Variables this->assignColors(text_idle_color, text_hover_color, text_active_color, idle_color, hover_color, active_color); } Button::~Button () { while (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { continue; } } const bool Button::isPressed() const { if ( this->buttonState == BTN_ACTIVE ) { return true; } return false; } vector <sf::Color> Button::getStateColors (int state) { vector <sf::Color> colors; if (state == BTN_IDLE) { colors.push_back(this->textIdleColor); colors.push_back(this->idleColor); } else if (state == BTN_HOVER) { colors.push_back(this->textHoverColor); colors.push_back(this->hoverColor); } else { colors.push_back(this->textActiveColor); colors.push_back(this->activeColor); } return colors; } void Button::assignColors (sf::Color text_idle_color, sf::Color text_hover_color, sf::Color text_active_color, sf::Color idle_color, sf::Color hover_color, sf::Color active_color) { this->textIdleColor = text_idle_color; this->textHoverColor = text_hover_color; this->textActiveColor = text_active_color; this->idleColor = idle_color; this->hoverColor = hover_color; this->activeColor = active_color; } void Button::update(const sf::Vector2f& mousePos) { // update booleans for hover and pressed this->buttonState = BTN_IDLE; if ( this->backdrop.getGlobalBounds().contains(mousePos) ) { this->buttonState = BTN_HOVER; if ( sf::Mouse::isButtonPressed(sf::Mouse::Left) ) { this->buttonState = BTN_ACTIVE; } } switch ( this->buttonState ) { case BTN_IDLE: this->backdrop.setFillColor(this->idleColor); this->setFillColor(this->textIdleColor); this->backdrop.setOutlineThickness(0); this->setOutlineThickness(0); break; case BTN_HOVER: this->backdrop.setFillColor(this->hoverColor); this->setFillColor(this->textHoverColor); this->backdrop.setOutlineThickness(1); this->setOutlineThickness(1); break; case BTN_ACTIVE: this->backdrop.setFillColor(this->activeColor); this->setFillColor(this->textActiveColor); this->backdrop.setOutlineThickness(1.5); this->setOutlineThickness(0.5); break; default: this->backdrop.setFillColor(sf::Color::Red); this->setFillColor(sf::Color::Blue); break; } } void Button::render(sf::RenderTarget& target) { if (this->checkBackdrop()) { target.draw(this->backdrop); } target.draw(*this); }
3,996
1,293
#pragma once #include <cstddef> namespace thread_pool { void create(std::size_t size); void destroy(); void block(); void schedule(void (*task)(void *), void * args); }
195
68
// Copyright(c) 2017-2020, Intel Corporation // // 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 Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifdef HAVE_CONFIG_H #include <config.h> #endif // HAVE_CONFIG_H #include <json-c/json.h> #include <opae/fpga.h> #include <uuid/uuid.h> #include <algorithm> #include <array> #include <cstdlib> #include <fstream> #include <map> #include <memory> #include <string> #include <vector> #include <cstdarg> #include <linux/ioctl.h> #include "opae_drv.h" #include "types_int.h" #include "sysfs_int.h" #include "mock/mock_opae.h" extern "C" { #include "fpga-dfl.h" #include "token_list_int.h" } #include "xfpga.h" extern "C" { int xfpga_plugin_initialize(void); int xfpga_plugin_finalize(void); } using namespace opae::testing; int dfl_port_info(mock_object * m, int request, va_list argp){ int retval = -1; errno = EINVAL; UNUSED_PARAM(m); UNUSED_PARAM(request); struct dfl_fpga_port_info *pinfo = va_arg(argp, struct dfl_fpga_port_info *); if (!pinfo) { FPGA_MSG("pinfo is NULL"); goto out_EINVAL; } if (pinfo->argsz != sizeof(*pinfo)) { FPGA_MSG("wrong structure size"); goto out_EINVAL; } pinfo->flags = 0; pinfo->num_regions = 2; pinfo->num_umsgs = 0; retval = 0; errno = 0; out: va_end(argp); return retval; out_EINVAL: retval = -1; errno = EINVAL; goto out; } class enum_c_p : public mock_opae_p<2, xfpga_> { protected: enum_c_p() : filter_(nullptr) {} virtual ~enum_c_p() {} virtual void test_setup() override { ASSERT_EQ(xfpga_plugin_initialize(), FPGA_OK); ASSERT_EQ(xfpga_fpgaGetProperties(nullptr, &filter_), FPGA_OK); num_matches_ = 0xc01a; } virtual void test_teardown() override { EXPECT_EQ(fpgaDestroyProperties(&filter_), FPGA_OK); token_cleanup(); xfpga_plugin_finalize(); } // Need a concrete way to determine the number of fpgas on the system // without relying on fpgaEnumerate() since that is the function that // is under test. int GetNumFpgas() { if (platform_.mock_sysfs != nullptr) { return platform_.devices.size(); } int value; std::string cmd = "(ls -l /sys/class/fpga*/region*/*fme*/dev || " "ls -l /sys/class/fpga*/*intel*) | (wc -l)"; ExecuteCmd(cmd, value); return value; } int GetNumMatchedFpga () { if (platform_.mock_sysfs != nullptr) { return 1; } int matches = 0; int socket_id; int i; for (i = 0; i < GetNumFpgas(); i++) { std::string cmd = "cat /sys/class/fpga*/*" + std::to_string(i) + "/*fme." + std::to_string(i) + "/socket_id"; ExecuteCmd(cmd, socket_id); if (socket_id == (int)platform_.devices[0].socket_id) { matches++; } } return matches; } int GetMatchedGuidFpgas() { if (platform_.mock_sysfs != nullptr) { return platform_.devices.size(); } int matches = 0; std::string afu_id; std::string afu_id_expected = platform_.devices[0].afu_guid; afu_id_expected.erase(std::remove(afu_id_expected.begin(), afu_id_expected.end(), '-'), afu_id_expected.end()); transform(afu_id_expected.begin(), afu_id_expected.end(), afu_id_expected.begin(), ::tolower); int i; for (i = 0; i < GetNumFpgas(); i++) { std::string cmd = "cat /sys/class/fpga*/*" + std::to_string(i) + "/*port." + std::to_string(i) + "/afu_id > output.txt"; EXPECT_EQ(std::system(cmd.c_str()), 0); std::ifstream file("output.txt"); EXPECT_TRUE(file.is_open()); EXPECT_TRUE(std::getline(file, afu_id)); file.close(); EXPECT_EQ(unlink("output.txt"), 0); if (afu_id == afu_id_expected) { matches++; } } return matches; } void ExecuteCmd(std::string cmd, int &value) { std::string line; std::string command = cmd + " > output.txt"; EXPECT_EQ(std::system(command.c_str()), 0); std::ifstream file("output.txt"); ASSERT_TRUE(file.is_open()); EXPECT_TRUE(std::getline(file, line)); file.close(); EXPECT_EQ(std::system("rm output.txt"), 0); value = std::stoi(line); } fpga_properties filter_; uint32_t num_matches_; }; /** * @test nullfilter * * @brief When the filter is null and the number of filters * is zero, the function returns all matches. */ TEST_P(enum_c_p, nullfilter) { EXPECT_EQ( xfpga_fpgaEnumerate(nullptr, 0, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas() * 2); } /** * @test nullfilter_neg * * @brief When the filter is null but the number of filters * is greater than zero, the function returns * FPGA_INVALID_PARAM. */ TEST_P(enum_c_p, nullfilter_neg) { EXPECT_EQ( xfpga_fpgaEnumerate(nullptr, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_INVALID_PARAM); } /** * @test nullmatches * * @brief When the number of matches parameter is null, * the function returns FPGA_INVALID_PARAM. */ TEST_P(enum_c_p, nullmatches) { EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), NULL), FPGA_INVALID_PARAM); } /** * @test nulltokens * * @brief When the tokens parameter is null, the function * returns FPGA_INVALID_PARAM. */ TEST_P(enum_c_p, nulltokens) { EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 0, NULL, tokens_.size(), &num_matches_), FPGA_INVALID_PARAM); } /** * @test object_type_accel * * @brief When the filter object type is set to * FPGA_ACCELERATOR, the function returns the * correct number of accelerator matches. */ TEST_P(enum_c_p, object_type_accel) { ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); } /** * @test object_type_dev * * @brief When the filter object type is set to FPGA_DEVICE, * the function returns the correct number of device * matches. */ TEST_P(enum_c_p, object_type_dev) { EXPECT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); } /** * @test parent * * @brief When the filter parent is set to a previously found * FPGA_DEVICE, the function returns the child resource. */ TEST_P(enum_c_p, parent) { EXPECT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); ASSERT_EQ(fpgaClearProperties(filter_), FPGA_OK); fpga_token token = nullptr; EXPECT_EQ(fpgaPropertiesSetParent(filter_, tokens_[0]), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, &token, 1, &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 1); ASSERT_NE(token, nullptr); EXPECT_EQ(xfpga_fpgaDestroyToken(&token), FPGA_OK); } /** * @test parent_neg * * @brief When the filter passed to fpgaEnumerate has a valid * parent field set, but that parent is not found to be the * parent of any device, fpgaEnumerate returns zero matches. */ TEST_P(enum_c_p, parent_neg) { ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), 1, &num_matches_), FPGA_OK); EXPECT_GT(num_matches_, 0); EXPECT_EQ(fpgaPropertiesSetParent(filter_, tokens_[0]), FPGA_OK); EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, NULL, 0, &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test segment * * @brief When the filter segment is set and it is valid, * the function returns the number of resources that * match that segment. */ TEST_P(enum_c_p, segment) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetSegment(filter_, device.segment), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas() * 2); } /** * @test segment_neg * * @brief When the filter segment is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, segment_neg) { ASSERT_EQ(fpgaPropertiesSetSegment(filter_, invalid_device_.segment), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test bus * * @brief When the filter bus is set and it is valid, the * function returns the number of resources that * match that bus. */ TEST_P(enum_c_p, bus) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetBus(filter_, device.bus), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 2); } /** * @test bus_neg * * @brief When the filter bus is set and it is invalid, * the function returns zero matches */ TEST_P(enum_c_p, bus_neg) { ASSERT_EQ(fpgaPropertiesSetBus(filter_, invalid_device_.bus), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test device * * @brief When the filter device is set and it is valid, * the function returns the number of resources that * match that device. */ TEST_P(enum_c_p, device) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetDevice(filter_, device.device), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas() * 2); } /** * @test device_neg * * @brief When the filter device is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, device_neg) { ASSERT_EQ(fpgaPropertiesSetDevice(filter_, invalid_device_.device), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test function * * @brief When the filter function is set and it is valid, * the function returns the number of resources that * match that function. */ TEST_P(enum_c_p, function) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetFunction(filter_, device.function), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas() * 2 - device.num_vfs); DestroyTokens(); for (int i = 0; i < device.num_vfs; ++i) { num_matches_ = 0; ASSERT_EQ(fpgaPropertiesSetFunction(filter_, device.function+i), FPGA_OK); EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 1); DestroyTokens(); } } /** * @test function_neg * * @brief When the filter function is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, function_neg) { ASSERT_EQ(fpgaPropertiesSetFunction(filter_, invalid_device_.function), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test socket_id_neg * * @brief When the filter socket_id is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, socket_id_neg) { ASSERT_EQ(fpgaPropertiesSetSocketID(filter_, invalid_device_.socket_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test vendor_id * * @brief When the filter vendor_id is set and it is valid, * the function returns the number of resources that * match that vendor_id. */ TEST_P(enum_c_p, vendor_id) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetVendorID(filter_, device.vendor_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas() * 2); } /** * @test vendor_id_neg * * @brief When the filter vendor_id is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, vendor_id_neg) { ASSERT_EQ(fpgaPropertiesSetVendorID(filter_, invalid_device_.vendor_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test device_id * * @brief When the filter device_id is set and it is valid, * the function returns the number of resources that * match that device_id. */ TEST_P(enum_c_p, device_id) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetDeviceID(filter_, device.device_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, platform_.devices.size() * 2 - device.num_vfs); DestroyTokens(); for (int i = 0; i < device.num_vfs; ++i) { num_matches_ = 0; ASSERT_EQ(fpgaPropertiesSetDeviceID(filter_, device.device_id+i), FPGA_OK); EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 1); DestroyTokens(); } } /** * @test device_id_neg * * @brief When the filter device_id is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, device_id_neg) { ASSERT_EQ(fpgaPropertiesSetDeviceID(filter_, invalid_device_.device_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test object_id_fme * * @brief When the filter object_id for fme is set and it is * valid, the function returns the number of resources * that match that object_id. */ TEST_P(enum_c_p, object_id_fme) { ASSERT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); ASSERT_GT(num_matches_, 0); fpga_properties prop; uint64_t object_id; EXPECT_EQ(xfpga_fpgaGetProperties(tokens_[0], &prop), FPGA_OK); EXPECT_EQ(fpgaPropertiesGetObjectID(prop, &object_id), FPGA_OK); EXPECT_EQ(fpgaDestroyProperties(&prop), FPGA_OK); DestroyTokens(); ASSERT_EQ(fpgaPropertiesSetObjectID(filter_, object_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 1); } /** * @test object_id_fme_neg * * @brief When the filter object_id for fme is set and it is * invalid, the function returns zero matches. */ TEST_P(enum_c_p, object_id_fme_neg) { ASSERT_EQ(fpgaPropertiesSetObjectID(filter_, invalid_device_.fme_object_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test object_id_port * * @brief When the filter port_id for port is set and it is * valid, the function returns the number of resources * that match that port_id. */ TEST_P(enum_c_p, object_id_port) { ASSERT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); ASSERT_GT(num_matches_, 0); fpga_properties prop; uint64_t object_id; EXPECT_EQ(xfpga_fpgaGetProperties(tokens_[0], &prop), FPGA_OK); EXPECT_EQ(fpgaPropertiesGetObjectID(prop, &object_id), FPGA_OK); EXPECT_EQ(fpgaDestroyProperties(&prop), FPGA_OK); DestroyTokens(); EXPECT_EQ(fpgaPropertiesSetObjectID(filter_, object_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 1); } /** * @test object_id_port_neg * * @brief When the filter object_id for port is set and it is * invalid, the function returns zero matches. */ TEST_P(enum_c_p, object_id_port_neg) { ASSERT_EQ(fpgaPropertiesSetObjectID(filter_, invalid_device_.port_object_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test num_errors_fme_neg * * @brief When the filter num_errors for fme is set and it is * invalid, the function returns zero matches. */ TEST_P(enum_c_p, num_errors_fme_neg) { ASSERT_EQ(fpgaPropertiesSetNumErrors(filter_, invalid_device_.fme_num_errors), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test num_errors_port_neg * * @brief When the filter num_errors for port is set and it is * invalid, the function returns zero matches. */ TEST_P(enum_c_p, num_errors_port_neg) { ASSERT_EQ(fpgaPropertiesSetNumErrors(filter_, invalid_device_.port_num_errors), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test guid_fme * * @brief When the filter guid for fme is set and it is * valid, the function returns the number of resources * that match that guid for fme. */ TEST_P(enum_c_p, guid_fme) { auto device = platform_.devices[0]; fpga_guid fme_guid; ASSERT_EQ(uuid_parse(device.fme_guid, fme_guid), 0); ASSERT_EQ(fpgaPropertiesSetGUID(filter_, fme_guid), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, platform_.devices.size()); } /** * @test guid_fme_neg * * @brief When the filter guid for fme is set and it is * invalid, the function returns zero matches. */ TEST_P(enum_c_p, guid_fme_neg) { fpga_guid invalid_guid; ASSERT_EQ(uuid_parse(invalid_device_.fme_guid, invalid_guid), 0); ASSERT_EQ(fpgaPropertiesSetGUID(filter_, invalid_guid), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test guid_port * * @brief When the filter guid for port is set and it is * valid, the function returns the number of resources * that match that guid for port. */ TEST_P(enum_c_p, guid_port) { auto device = platform_.devices[0]; fpga_guid afu_guid; ASSERT_EQ(uuid_parse(device.afu_guid, afu_guid), 0); ASSERT_EQ(fpgaPropertiesSetGUID(filter_, afu_guid), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetMatchedGuidFpgas()); } /** * @test guid_port_neg * * @brief When the filter guid for port is set and it is * invalid, the function returns zero matches. */ TEST_P(enum_c_p, guid_port_neg) { fpga_guid invalid_guid; ASSERT_EQ(uuid_parse(invalid_device_.afu_guid, invalid_guid), 0); ASSERT_EQ(fpgaPropertiesSetGUID(filter_, invalid_guid), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test clone_token * * @brief Given a valid source token and a valid destination, * xfpga_fpgaCloneToken() returns FPGA_OK. */ TEST_P(enum_c_p, clone_token) { EXPECT_EQ( xfpga_fpgaEnumerate(nullptr, 0, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_GT(num_matches_, 0); fpga_token src = tokens_[0]; fpga_token dst; EXPECT_EQ(xfpga_fpgaCloneToken(src, &dst), FPGA_OK); EXPECT_EQ(xfpga_fpgaDestroyToken(&dst), FPGA_OK); } /** * @test clone_token_neg * * @brief Given an invalid source token or an invalid destination, * xfpga_fpgaCloneToken() returns FPGA_INVALID_PARAM */ TEST_P(enum_c_p, clone_token_neg) { EXPECT_EQ( xfpga_fpgaEnumerate(nullptr, 0, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_GT(num_matches_, 0); fpga_token src = tokens_[0]; fpga_token dst; EXPECT_EQ(xfpga_fpgaCloneToken(NULL, &dst), FPGA_INVALID_PARAM); EXPECT_EQ(xfpga_fpgaCloneToken(&src, NULL), FPGA_INVALID_PARAM); } /** * @test destroy_token * * @brief Given a valid token, xfpga_fpgaDestroyToken() returns * FPGA_OK. */ TEST_P(enum_c_p, destroy_token) { fpga_token token; ASSERT_EQ(xfpga_fpgaEnumerate(nullptr, 0, &token, 1, &num_matches_), FPGA_OK); ASSERT_GT(num_matches_, 0); EXPECT_EQ(xfpga_fpgaDestroyToken(&token), FPGA_OK); } /** * @test destroy_token_neg * * @brief Given a null or invalid token, xfpga_fpgaDestroyToken() * returns FPGA_INVALID_PARAM. */ TEST_P(enum_c_p, destroy_token_neg) { EXPECT_EQ(xfpga_fpgaDestroyToken(nullptr), FPGA_INVALID_PARAM); _fpga_token *dummy = new _fpga_token; memset(dummy, 0, sizeof(*dummy)); EXPECT_EQ(xfpga_fpgaDestroyToken((fpga_token *)&dummy), FPGA_INVALID_PARAM); delete dummy; } /** * @test num_slots * * @brief When the filter num_slots is set and it is valid, * the function returns the number of resources that * match that number of slots. */ TEST_P(enum_c_p, num_slots) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetNumSlots(filter_, device.num_slots), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); } /** * @test num_slots_neg * * @brief When the filter num_slots is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, num_slots_neg) { ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetNumSlots(filter_, invalid_device_.num_slots), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test bbs_id * * @brief When the filter bbs_id is set and it is valid, * the function returns the number of resources that * match that bbs_id. */ TEST_P(enum_c_p, bbs_id) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetBBSID(filter_, device.bbs_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, platform_.devices.size()); } /** * @test bbs_id_neg * * @brief When the filter bbs_id is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, bbs_id_neg) { ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetBBSID(filter_, invalid_device_.bbs_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test bbs_version * * @brief When the filter bbs_version is set and it is valid, * the function returns the number of resources that * match that bbs_version. */ TEST_P(enum_c_p, bbs_version) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetBBSVersion(filter_, device.bbs_version), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, platform_.devices.size()); } /** * @test bbs_version_neg * * @brief When the filter bbs_version is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, bbs_version_neg) { ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetBBSVersion(filter_, invalid_device_.bbs_version), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test accel_state * * @brief When the filter accelerator state is set and it is * valid, the function returns the number of resources * that match that accelerator state. */ TEST_P(enum_c_p, accel_state) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetAcceleratorState(filter_, device.state), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); } /** * @test accel_state_neg * * @brief When the filter accelerator state is set and it is * invalid, the function returns zero matches. */ TEST_P(enum_c_p, state_neg) { ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetAcceleratorState(filter_, invalid_device_.state), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test num_mmio * * @brief When the filter num MMIO is set and it is valid, * the function returns the number of resources that * match that num MMIO. */ TEST_P(enum_c_p, num_mmio) { auto device = platform_.devices[0]; system_->register_ioctl_handler(DFL_FPGA_PORT_GET_INFO, dfl_port_info); ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetNumMMIO(filter_, device.num_mmio), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); } /** * @test num_mmio_neg * * @brief When the filter num MMIO is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, num_mmio_neg) { system_->register_ioctl_handler(DFL_FPGA_PORT_GET_INFO, dfl_port_info); ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetNumMMIO(filter_, invalid_device_.num_mmio), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test num_interrupts * * @brief When the filter num interrupts is set and it is valid, * the function returns the number of resources that * match that num interrupts. */ TEST_P(enum_c_p, num_interrupts) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetNumInterrupts(filter_, device.num_interrupts), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); } /** * @test num_interrupts_neg * * @brief When the filter num interrupts is set and it is invalid, * the function returns zero matches. */ TEST_P(enum_c_p, num_interrupts_neg) { ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetNumInterrupts(filter_, invalid_device_.num_interrupts), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); } /** * @test num_filter_neg * * @brief When the num_filter parameter to fpgaEnumerate is zero, * but the filter parameter is non-NULL, the function * returns FPGA_INVALID_PARAM. */ TEST_P(enum_c_p, num_filter_neg) { EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 0, tokens_.data(), 0, &num_matches_), FPGA_INVALID_PARAM); } /** * @test max_tokens * * @brief fpgaEnumerate honors the input max_tokens value by * limiting the number of output entries written to the * memory at match, even though more may exist. */ TEST_P(enum_c_p, max_tokens) { uint32_t max_tokens = 1; EXPECT_EQ(xfpga_fpgaEnumerate(NULL, 0, tokens_.data(), max_tokens, &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas() * 2); EXPECT_NE(tokens_[0], nullptr); EXPECT_EQ(tokens_[1], nullptr); } /** * @test filter * * @brief fpgaEnumerate honors a "don't care" properties filter by * returning all available tokens. */ TEST_P(enum_c_p, filter) { EXPECT_EQ(FPGA_OK, xfpga_fpgaEnumerate(&filter_, 1, NULL, 0, &num_matches_)); EXPECT_EQ(num_matches_, GetNumFpgas() * 2); } /** * @test get_guid * * @brief Given I have a system with at least one FPGA And I * enumerate with a filter of objtype of FPGA_DEVICE When I * get properties from the resulting token And I query the * GUID from the properties Then the GUID is returned and * the result is FPGA_OK. * */ TEST_P(enum_c_p, get_guid) { fpga_properties prop; fpga_guid guid; fpga_properties filterp = NULL; ASSERT_EQ(xfpga_fpgaGetProperties(NULL, &filterp), FPGA_OK); EXPECT_EQ(fpgaPropertiesSetObjectType(filterp, FPGA_DEVICE), FPGA_OK); EXPECT_EQ(xfpga_fpgaEnumerate(&filterp, 1, tokens_.data(), 1, &num_matches_), FPGA_OK); EXPECT_GT(num_matches_, 0); EXPECT_EQ(fpgaDestroyProperties(&filterp), FPGA_OK); ASSERT_EQ(xfpga_fpgaGetProperties(tokens_[0], &prop), FPGA_OK); EXPECT_EQ(fpgaPropertiesGetGUID(prop, &guid), FPGA_OK); EXPECT_EQ(fpgaDestroyProperties(&prop), FPGA_OK); } INSTANTIATE_TEST_CASE_P(enum_c, enum_c_p, ::testing::ValuesIn(test_platform::platforms({ "dfl-n3000","dfl-d5005" }))); class enum_err_c_p : public enum_c_p {}; /** * @test num_errors_fme * * @brief When the filter num_errors for fme is set and it is * valid, the function returns the number of resources * that match that number of errors for fme. */ TEST_P(enum_err_c_p, num_errors_fme) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetNumErrors(filter_, device.fme_num_errors), FPGA_OK); EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); } /** * @test num_errors_port * * @brief When the filter num_errors for port is set and it is * valid, the function returns the number of resources * that match that number of errors for port. */ TEST_P(enum_err_c_p, num_errors_port) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetNumErrors(filter_, device.port_num_errors), FPGA_OK); EXPECT_EQ(xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumFpgas()); } INSTANTIATE_TEST_CASE_P(enum_c, enum_err_c_p, ::testing::ValuesIn(test_platform::platforms({ "dfl-n3000","dfl-d5005" }))); class enum_socket_c_p : public enum_c_p {}; /** * @test socket_id * * @brief When the filter socket_id is set and it is valid, * the function returns the number of resources that * match that socket_id. */ TEST_P(enum_socket_c_p, socket_id) { auto device = platform_.devices[0]; ASSERT_EQ(fpgaPropertiesSetSocketID(filter_, device.socket_id), FPGA_OK); EXPECT_EQ( xfpga_fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, GetNumMatchedFpga() * 2); } INSTANTIATE_TEST_CASE_P(enum_c, enum_socket_c_p, ::testing::ValuesIn(test_platform::platforms({ "dfl-n3000","dfl-d5005" }))); class enum_mock_only : public enum_c_p {}; /** * @test remove_port * * @brief Given I have a system with at least one FPGA And I * enumerate with a filter of objtype of FPGA_ACCELERATOR * and I get one token for that accelerator * When I remove the port device from the system * And I enumerate again with the same filter * Then I get zero tokens as the result. * */ TEST_P(enum_mock_only, remove_port) { fpga_properties filterp = NULL; ASSERT_EQ(xfpga_fpgaGetProperties(NULL, &filterp), FPGA_OK); EXPECT_EQ(fpgaPropertiesSetObjectType(filterp, FPGA_ACCELERATOR), FPGA_OK); EXPECT_EQ(xfpga_fpgaEnumerate(&filterp, 1, tokens_.data(), 1, &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 1); const char *sysfs_port = "/sys/class/fpga_region/region0/dfl-port.0"; EXPECT_EQ(system_->remove_sysfs_dir(sysfs_port), 0) << "error removing dfl-port.0: " << strerror(errno); EXPECT_EQ(xfpga_fpgaEnumerate(&filterp, 1, tokens_.data(), 1, &num_matches_), FPGA_OK); EXPECT_EQ(num_matches_, 0); EXPECT_EQ(fpgaDestroyProperties(&filterp), FPGA_OK); } INSTANTIATE_TEST_CASE_P(enum_c, enum_mock_only, ::testing::ValuesIn(test_platform::mock_platforms({ "dfl-n3000","dfl-d5005" })));
36,434
13,797
static const char *divisionbyzero_errors[] = { "test/errors/divisionbyzero/__idiv.yasl", "test/errors/divisionbyzero/__mod.yasl", };
137
56
// $Id: StjTrackCutDca.cxx,v 1.1 2008/11/27 07:09:32 tai Exp $ // Copyright (C) 2008 Tai Sakuma <sakuma@bnl.gov> #include "StjTrackCutDca.h" ClassImp(StjTrackCutDca)
169
99
/* Description : Ticket Selling Booth Function Date : 21 Nov 2020 Function Author : Prasad Dangare Input : String,Integer */ #include<iostream> #include<stdlib.h> #include<conio.h> using namespace std; class ticketbooth { unsigned int no_people; double totcash; public: ticketbooth() { no_people = 0; totcash = 0.0; } void ticket() { no_people++; totcash += 5; } void visited() { no_people++; } void display() { cout << "Total Number Of People " << no_people << endl <<"Total Amount " << totcash << endl; } }; int main() { ticketbooth booth1; int ch; cout << "\n Press 1 For Visited " << endl << "\n Press 2 For Visited And Bought Ticket " << endl; do { cout << "\n 1.Visited " << "\n"; cout << "2.Visited And Bought Ticket " << "\n"; cout << "3.Display" << "\n"; cout << "4.Exit" << "\n"; cin >> ch; switch(ch) { case 1:booth1.visited(); break; case 2:booth1.ticket(); break; case 3:booth1.display(); break; case 4:exit(0); } }while(ch<=4); return 0; }
1,170
482
#include "j1Pathfinding.h" #include "j1App.h" #include "j1Textures.h" #include "p2Log.h" #include"Character.h" #include"j1Map.h" #include"j1Enemy.h" #include "Brofiler/Brofiler.h" ///class Pathfinding ------------------ // Constructors ======================= j1Pathfinding::j1Pathfinding() { } // Destructors ======================== j1Pathfinding::~j1Pathfinding() { } //Game Loop =========================== bool j1Pathfinding::Start() { //Generate map cluster abstraction j1Timer timer; //cluster_abstraction = new ClusterAbstraction(App->map, 10); LOG("Cluster abstraction generated in %.3f", timer.ReadSec()); //Load debug tiles trexture //path_texture = App->tex->Load("maps/path_tex.png"); return true; } bool j1Pathfinding::CleanUp() { RELEASE_ARRAY(path_nodes); return true; } void j1Pathfinding::SetMap(uint width, uint height) { this->width = width; this->height = height; map_min_x = 0; map_min_y = 0; map_max_x = width; map_max_y = height; RELEASE_ARRAY(path_nodes); int size = width*height; path_nodes = new PathNode[size]; } void j1Pathfinding::SetMapLimits(int position_x, int position_y, int width, int height) { map_min_x = position_x; map_min_y = position_y; map_max_x = position_x + width; map_max_y = position_y + height; } //Functionality ======================= //Methods used during the paths creation to work with map data bool j1Pathfinding::IsWalkable(const iPoint & destination) const { bool ret = false; uchar t = GetTileAt(destination); if (t) int x = 0; return (t == NOT_COLISION_ID); } bool j1Pathfinding::CheckBoundaries(const iPoint & pos) const { return (pos.x >= map_min_x && pos.x < map_max_x && pos.y >= map_min_y && pos.y < map_max_y); } uchar j1Pathfinding::GetTileAt(const iPoint & pos) const { if (CheckBoundaries(pos)) return GetValueMap(pos.x, pos.y); return NOT_COLISION_ID; } uchar j1Pathfinding::GetValueMap(int x, int y) const { //In future we will have to adapt because with this enemies only can be in logic 0 return App->map->V_Colision[0]->data[(y*width) + x]; } PathNode* j1Pathfinding::GetPathNode(int x, int y) { return &path_nodes[(y*width) + x]; } std::vector<iPoint>* j1Pathfinding::SimpleAstar(const iPoint& origin, const iPoint& destination) { BROFILER_CATEGORY("A star", Profiler::Color::LightYellow); int size = width*height; std::fill(path_nodes, path_nodes + size, PathNode(-1, -1, iPoint(-1, -1), nullptr)); iPoint dest_point(destination.x, destination.y); int ret = -1; //iPoint mouse_position = App->map->FixPointMap(destination.x, destination.y); /*iPoint map_origin = App->map->WorldToMap(origin.x, origin.y); iPoint map_goal = App->map->WorldToMap(dest_point.x, dest_point.y);*/ /* if (map_origin == map_goal) { std::vector<iPoint>* path = new std::vector<iPoint>; path->push_back(mouse_position); return path; }*/ if (IsWalkable(origin) && IsWalkable(dest_point)) { ret = 1; OpenList open; PathNode* firstNode = GetPathNode(origin.x, origin.y); firstNode->SetPosition(origin); firstNode->g = 0; firstNode->h = origin.DistanceManhattan(dest_point); open.queue.push(firstNode); PathNode* current = nullptr; while (open.queue.size() != 0) { current = open.queue.top(); open.queue.top()->on_close = true; open.queue.pop(); if (current->pos == dest_point) { std::vector<iPoint>* path = new std::vector<iPoint>; last_path.clear(); path->push_back(dest_point); iPoint mouse_cell = App->map->WorldToMap(dest_point.x, dest_point.y); if (mouse_cell == current->pos) current = GetPathNode(current->parent->pos.x, current->parent->pos.y); for (; current->parent != nullptr; current = GetPathNode(current->parent->pos.x, current->parent->pos.y)) { last_path.push_back(current->pos); path->push_back({ current->pos.x, current->pos.y }); } last_path.push_back(current->pos); return path; } else { PathList neightbords; current->FindWalkableAdjacents(&neightbords); for (std::list<PathNode*>::iterator item = neightbords.list.begin(); item != neightbords.list.end(); item++) { PathNode* temp = item._Mynode()->_Myval; if (temp->on_close == true) { continue; } else if (temp->on_open == true) { int last_g_value = (int)temp->g; temp->CalculateF(dest_point); if (last_g_value <temp->g) { temp->parent = GetPathNode(current->pos.x, current->pos.y); } else { temp->g = (float)last_g_value; } } else { temp->on_open = true; temp->CalculateF(dest_point); open.queue.push(temp); } } neightbords.list.clear(); } } } return nullptr; } /// ----------------------------------- /// Struct PathNode ------------------- //Constructors ============== PathNode::PathNode() { } PathNode::PathNode(int g, int h, const iPoint & pos, const PathNode * parent) : g((float)g), h(h), pos(pos), parent(parent), on_close(false), on_open(false) { int x = 0; } PathNode::PathNode(const PathNode & node) : g(node.g), h(node.h), pos(node.pos), parent(node.parent) { int x = 0; } //Functionality ============= uint PathNode::FindWalkableAdjacents(PathList* list_to_fill) const { iPoint cell(0,0); uint before = list_to_fill->list.size(); bool northClose = false, southClose = false, eastClose = false, westClose = false; // south cell.create(pos.x, pos.y + 1); if (App->pathfinding->IsWalkable(cell)) { PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y); if (node->pos != cell) { node->parent = this; node->pos = cell; } list_to_fill->list.push_back(node); } else { southClose = true; } // north cell.create(pos.x, pos.y - 1); if (App->pathfinding->IsWalkable(cell)) { PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y); if (node->pos != cell) { node->parent = this; node->pos = cell; } list_to_fill->list.push_back(node); } else { northClose = true; } // east cell.create(pos.x + 1, pos.y); if (App->pathfinding->IsWalkable(cell)) { PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y); if (node->pos != cell) { node->parent = this; node->pos = cell; } list_to_fill->list.push_back(node); } else { eastClose = true; } // west cell.create(pos.x - 1, pos.y); if (App->pathfinding->IsWalkable(cell)) { PathNode* node = App->pathfinding->GetPathNode(cell.x, cell.y); if (node->pos != cell) { node->parent = this; node->pos = cell; } list_to_fill->list.push_back(node); } else { westClose = true; } return list_to_fill->list.size(); } float PathNode::Score() const { return g + h; } int PathNode::CalculateF(const iPoint & destination) { g = parent->g + parent->pos.DistanceManhattan(pos); h = pos.DistanceManhattan(destination) * 10; return (int)g + h; } void PathNode::SetPosition(const iPoint & value) { pos = value; } //Operators ================= bool PathNode::operator==(const PathNode & node) const { return pos == node.pos; } bool PathNode::operator!=(const PathNode & node) const { return !operator==(node); } /// ----------------------------------- ///Struct PathList -------------------- //Functionality ============= /* std::list<PathNode>::iterator PathList::Find(const iPoint & point) { std::list<PathNode*>::iterator item = list.begin(); while (item != list.end()) { if (item->pos == point) { return item; } ++item; } } PathNode* PathList::GetNodeLowestScore() const { PathNode* ret = nullptr; std::list<PathNode>::const_reverse_iterator item = list.crbegin(); float min = 65535; while (item != list.crend()) { if (item->Score() < min) { min = item->Score(); ret = &item.base()._Ptr->_Prev->_Myval; } ++item; } return ret; }*/ void j1Pathfinding::Move(Enemy * enemy, Character* player) { if (enemy->green_enemy_path.size()) { static int i = 1; int temp = enemy->green_enemy_path[enemy->green_enemy_path.size() - i].x; int temp2 = enemy->green_enemy_path[enemy->green_enemy_path.size() - i].y; int x = 0; int y = 0; x = x + (enemy->green_enemy_path[enemy->green_enemy_path.size()-i].x - enemy->tile_pos.x); y = y + (enemy->green_enemy_path[enemy->green_enemy_path.size()- i].y - enemy->tile_pos.y); /* if (last_path.size() > 1) { x = x + (last_path[i + 1].x - enemy->array_pos.x); y = y + (last_path[i + 1].y - enemy->array_pos.y); }*/ //enemy->actual_event = move; //Change this if (x >= 1) { x = 1; enemy->Enemy_Orientation = OrientationEnemy::right_enemy; } if (x <= -1) { x = -1; enemy->Enemy_Orientation = OrientationEnemy::left_enemy; } if (y >= 1) { y = 1; enemy->Enemy_Orientation = OrientationEnemy::down_enemy; } if (y <= -1) { y = -1; enemy->Enemy_Orientation = OrientationEnemy::up_enemy; } enemy->pos.x += x; enemy->pos.y += y; if (enemy->tile_pos == enemy->green_enemy_path[enemy->green_enemy_path.size()-i]) { i++; } if (i == enemy->green_enemy_path.size() || enemy->tile_pos == player->tilepos) { i = 0; enemy->green_enemy_path.clear(); } } }
9,084
3,821
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "ngraph/node.hpp" #include "ngraph/op/op.hpp" #include "openvino/op/mvn.hpp" namespace ngraph { namespace op { namespace v0 { using ov::op::v0::MVN; } // namespace v0 using v0::MVN; using ov::op::MVNEpsMode; namespace v6 { using ov::op::v6::MVN; } // namespace v6 } // namespace op } // namespace ngraph
422
180
#include "AdapterStats.h" using reseq::AdapterStats; #include <algorithm> using std::max; using std::max_element; using std::min; using std::sort; #include <array> using std::array; #include <cmath> using std::ceil; #include <fstream> using std::ifstream; using std::ofstream; #include <iterator> using std::distance; #include <list> using std::list; //include <string> using std::string; //include <vector> using std::vector; #include <utility> using std::pair; #include "reportingUtils.hpp" //include <seqan/bam_io.h> using seqan::BamAlignmentRecord; using seqan::CharString; using seqan::Dna; using seqan::Dna5; using seqan::DnaString; using seqan::Exception; using seqan::reverseComplement; using seqan::StringSet; #include <seqan/seq_io.h> using seqan::readRecords; using seqan::SeqFileIn; #include "skewer/src/matrix.h" //include "utilities.hpp" using reseq::utilities::at; using reseq::utilities::SetToMax; inline reseq::uintSeqLen AdapterStats::GetStartPosOnReference(const BamAlignmentRecord &record){ uintSeqLen start_pos = record.beginPos; if('S' == at(record.cigar, 0).operation){ if(at(record.cigar, 0).count < start_pos){ start_pos -= at(record.cigar, 0).count; } else{ start_pos = 0; } } else if('H' == at(record.cigar, 0).operation){ if( 2 <= length(record.cigar) && 'S' == at(record.cigar, 1).operation){ if(at(record.cigar, 1).count < start_pos){ start_pos -= at(record.cigar, 1).count; } else{ start_pos = 0; } } } return start_pos; } reseq::uintReadLen AdapterStats::CountErrors(uintReadLen &last_error_pos, const BamAlignmentRecord &record, const Reference &reference){ uintReadLen num_errors(0), read_pos(0); auto ref_pos = GetStartPosOnReference(record); auto &ref_seq = reference.ReferenceSequence(record.rID); for( const auto &cigar_element : record.cigar ){ switch( cigar_element.operation ){ case 'M': case '=': case 'X': case 'S': // Treat soft-clipping as match, so that bwa and bowtie2 behave the same for(auto i=cigar_element.count; i--; ){ if( ref_pos >= length(ref_seq) || at(ref_seq, ref_pos++) != at(record.seq, read_pos++) ){ if( !hasFlagRC(record) || !num_errors ){ // In case of a normal read always overwrite errors to get the last; in case of a reversed read stop after the first last_error_pos = read_pos - 1; } ++num_errors; } } break; case 'N': case 'D': // Deletions can be attributed to the base before or after the deletion, choose the one resulting in the lowest last_error_pos in the end (so shortest adapter required length) if( hasFlagRC(record) ){ if( !num_errors ){ last_error_pos = read_pos; } } else{ last_error_pos = read_pos-1; } num_errors += cigar_element.count; ref_pos += cigar_element.count; break; case 'I': // Insertions can be attributed to the first or last base of the insertion, choose the one resulting in the lowest last_error_pos in the end (so shortest adapter required length) if( hasFlagRC(record) ){ if( !num_errors ){ last_error_pos = read_pos; } } else{ last_error_pos = read_pos+cigar_element.count-1; } num_errors += cigar_element.count; read_pos += cigar_element.count; break; default: printErr << "Unknown cigar operation: " << cigar_element.operation << std::endl; } } // Reverse position for normal reads to get them counted from the end of the read if( !hasFlagRC(record) ){ last_error_pos = length(record.seq) - 1 - last_error_pos; } return num_errors; } bool AdapterStats::VerifyInsert(const CharString &read1, const CharString &read2, intSeqShift pos1, intSeqShift pos2){ if( 1 > pos1 || 1 > pos2){ return true; } if( pos1 == pos2 ){ uintReadLen matches(0), i2(0); for(uintReadLen i1=pos1; i1--; ){ switch(at(read1, i1)){ case 'A': if( 'T' == at(read2, i2) ){ ++matches; } break; case 'C': if( 'G' == at(read2, i2) ){ ++matches; } break; case 'G': if( 'C' == at(read2, i2) ){ ++matches; } break; case 'T': if( 'A' == at(read2, i2) ){ ++matches; } break; } ++i2; } if(matches > pos1*95/100){ return true; } } return false; } bool AdapterStats::AdaptersAmbigous(const seqan::DnaString &adaper1, const seqan::DnaString &adaper2, uintReadLen max_length){ auto compare_until = max( static_cast<uintReadLen>(max(length(adaper1), length(adaper2))), max_length ); uintReadLen num_diff = 0; for( auto pos=compare_until; pos--; ){ if(at(adaper1, pos) != at(adaper2, pos)){ ++num_diff; } } return num_diff < 2+compare_until/10; } AdapterStats::AdapterStats(){ // Clear adapter_overrun_bases_ for( auto i = tmp_overrun_bases_.size(); i--; ){ tmp_overrun_bases_.at(i) = 0; } } bool AdapterStats::LoadAdapters(const char *adapter_file, const char *adapter_matrix){ StringSet<CharString> ids; StringSet<DnaString> seqs; printInfo << "Loading adapters from: " << adapter_file << std::endl; printInfo << "Loading adapter combination matrix from: " << adapter_matrix << std::endl; try{ SeqFileIn seq_file_in(adapter_file); readRecords(ids, seqs, seq_file_in); } catch(const Exception &e){ printErr << "Could not load adapter sequences: " << e.what() << std::endl; return false; } vector<string> matrix; matrix.resize(length(seqs)); ifstream matrix_file; matrix_file.open(adapter_matrix); uintAdapterId nline=0; while( length(seqs) > nline && matrix_file.good() ){ getline(matrix_file, matrix.at(nline++)); } matrix_file.close(); // Check if matrix fits to adapter file bool error = false; if(length(seqs) != nline ){ printErr << "Matrix has less rows than adapters loaded from file." << std::endl; error = true; } matrix_file.get(); // Test if file is at the end if( !matrix_file.eof() ){ printErr << "Matrix has more rows than adapters loaded from file." << std::endl; error = true; } for( ; nline--; ){ if( length(seqs) > matrix.at(nline).size() ){ printErr << "Matrix row " << nline << " has less columns than adapters loaded from file." << std::endl; error = true; } else if( length(seqs) < matrix.at(nline).size() ){ printErr << "Matrix row " << nline << " has more columns than adapters loaded from file." << std::endl; error = true; } for(auto nchar = matrix.at(nline).size(); nchar--; ){ if( '0' != matrix.at(nline).at(nchar) && '1' != matrix.at(nline).at(nchar)){ printErr << "Not allowed character '" << matrix.at(nline).at(nchar) << "' in matrix at line " << nline << ", position " << nchar << std::endl; error = true; } } } if(error){ return false; } // Get adapters that are allowed for first or second array<vector<pair<DnaString, uintAdapterId>>, 2> adapter_list; for(uintTempSeq seg=2; seg--; ){ adapter_list.at(seg).reserve(length(seqs)); } for( nline = length(seqs); nline--; ){ for(auto nchar = length(seqs); nchar--; ){ if( '1' == matrix.at(nline).at(nchar) ){ // If one adapter pair has this adaptor as first, add it to first and continue with the next adapter adapter_list.at(0).push_back({at(seqs, nline),nline}); break; } } } for(auto nchar = length(seqs); nchar--; ){ for( nline = length(seqs); nline--; ){ if( '1' == matrix.at(nline).at(nchar) ){ adapter_list.at(1).push_back({at(seqs, nchar),nchar}); break; } } } for(uintTempSeq seg=2; seg--; ){ // Also add reverse complement of adapters (as the direction is different depending on the sequencing machine Hiseq2000 vs. 4000) adapter_list.at(seg).reserve(adapter_list.at(seg).size()*2); for( uintAdapterId i=adapter_list.at(seg).size(); i--;){ adapter_list.at(seg).push_back(adapter_list.at(seg).at(i)); reverseComplement(adapter_list.at(seg).back().first); adapter_list.at(seg).back().second += length(ids); } // Sort adapters by sequence (necessary for SolveAmbiguities function later) and fill the class variables sort(adapter_list.at(seg)); seqs_.at(seg).reserve(adapter_list.at(seg).size()); names_.at(seg).reserve(adapter_list.at(seg).size()); for( auto &adapter : adapter_list.at(seg) ){ seqs_.at(seg).push_back(adapter.first); if(adapter.second < length(ids)){ names_.at(seg).push_back((string(toCString(at(ids, adapter.second)))+"_f").c_str()); } else{ names_.at(seg).push_back((string(toCString(at(ids, adapter.second-length(ids))))+"_r").c_str()); } } } // Fill adapter_combinations_ with the valid combinations of both adapters combinations_.clear(); combinations_.resize(adapter_list.at(0).size(), vector<bool>(adapter_list.at(1).size(), true) ); // Set all combinations by default to valid for( auto adapter1 = adapter_list.at(0).size(); adapter1--; ){ for( auto adapter2 = adapter_list.at(1).size(); adapter2--; ){ if('0' == matrix.at( adapter_list.at(0).at(adapter1).second%length(ids) ).at( adapter_list.at(1).at(adapter2).second%length(ids) )){ // Combination not valid combinations_.at(adapter1).at(adapter2) = false; } } } return true; } void AdapterStats::PrepareAdapterPrediction(){ if(0 == combinations_.size()){ for(uintTempSeq template_segment=2; template_segment--; ){ adapter_kmers_.at(template_segment).Prepare(); adapter_start_kmers_.at(template_segment).resize(adapter_kmers_.at(template_segment).counts_.size(), 0); } } } void AdapterStats::ExtractAdapterPart(const seqan::BamAlignmentRecord &record){ if(0 == combinations_.size()){ if( hasFlagUnmapped(record) || hasFlagNextUnmapped(record) ){ auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceForward(record.seq, 0); if( adapter_start >= 0 ){ ++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start); } } else if( hasFlagRC(record) ){ if(record.beginPos <= record.pNext && record.beginPos+length(record.seq) > record.pNext){ uintReadLen clipped(0); if('S' == at(record.cigar, 0).operation){ clipped = at(record.cigar, 0).count; } else if('H' == at(record.cigar, 0).operation){ clipped = at(record.cigar, 0).count; if('S' == at(record.cigar, 1).operation){ clipped += at(record.cigar, 1).count; } } auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceReverse(record.seq, clipped + record.pNext-record.beginPos); if( adapter_start >= 0 ){ ++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start); } } } else{ if(record.beginPos >= record.pNext && record.beginPos < record.pNext+length(record.seq)){ uintReadLen clipped(0); if('S' == at(record.cigar, length(record.cigar)-1).operation){ clipped = at(record.cigar, length(record.cigar)-1).count; } else if('H' == at(record.cigar, length(record.cigar)-1).operation){ clipped = at(record.cigar, length(record.cigar)-1).count; if('S' == at(record.cigar, length(record.cigar)-2).operation){ clipped += at(record.cigar, length(record.cigar)-2).count; } } auto adapter_start = adapter_kmers_.at(hasFlagLast(record)).CountSequenceForward(record.seq, length(record.seq) - max(clipped, static_cast<uintReadLen>(record.beginPos - record.pNext))); if( adapter_start >= 0 ){ ++adapter_start_kmers_.at(hasFlagLast(record)).at(adapter_start); } } } } } bool AdapterStats::PredictAdapters(){ if(0 == combinations_.size()){ std::vector<bool> use_kmer; uintBaseCall max_extension, second_highest; auto base = adapter_kmers_.at(0).counts_.size() >> 2; uintReadLen adapter_ext_pos(0); ofstream myfile; if(kAdapterSearchInfoFile){ myfile.open(kAdapterSearchInfoFile); myfile << "template_segment, tries_left, position, kmer, counts" << std::endl; } for(uintTempSeq template_segment=2; template_segment--; ){ // Find start of adapter use_kmer.clear(); use_kmer.resize(adapter_kmers_.at(template_segment).counts_.size(), true); use_kmer.at(0) = false; // Ignore all A's as possible adapter Kmer<kKmerLength>::intType excluded_kmer; for(uintBaseCall nuc=3; --nuc; ){ excluded_kmer = nuc; for(auto i=kKmerLength-1; i--; ){ excluded_kmer <<= 2; excluded_kmer += nuc; } use_kmer.at(excluded_kmer) = false; // Ignore all C's/G's as possible adapter } use_kmer.at( adapter_kmers_.at(template_segment).counts_.size()-1 ) = false; // Ignore all T's as possible adapter DnaString adapter; reserve(adapter, 50); bool found_adapter = false; uintNumFits tries = 100; while(!found_adapter && tries--){ Kmer<kKmerLength>::intType max_kmer = 1; while(!use_kmer.at(max_kmer)){ ++max_kmer; } for(Kmer<kKmerLength>::intType kmer = max_kmer+1; kmer < adapter_start_kmers_.at(template_segment).size(); ++kmer ){ if( use_kmer.at(kmer) && adapter_start_kmers_.at(template_segment).at(kmer) > adapter_start_kmers_.at(template_segment).at(max_kmer) ){ max_kmer = kmer; } } use_kmer.at(max_kmer) = false; // Prevent endless circle auto kmer = max_kmer; resize(adapter, kKmerLength); for(uintReadLen pos=kKmerLength; pos--; ){ at(adapter, pos) = kmer%4; kmer >>= 2; } if(kAdapterSearchInfoFile){ // Sort kmers to get top 100 std::vector<std::pair<uintNucCount, Kmer<kKmerLength>::intType>> sorted_kmers; sorted_kmers.reserve(adapter_start_kmers_.size()); for(Kmer<kKmerLength>::intType kmer = 0; kmer < adapter_start_kmers_.at(template_segment).size(); ++kmer ){ sorted_kmers.emplace_back(adapter_start_kmers_.at(template_segment).at(kmer), kmer); } sort(sorted_kmers.begin(),sorted_kmers.end()); string kmer_nucs; kmer_nucs.resize(kKmerLength); for(auto sk = sorted_kmers.size(); sk-- > sorted_kmers.size()-100; ){ myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Start, "; kmer = sorted_kmers.at(sk).second; for(uintReadLen pos=kKmerLength; pos--; ){ kmer_nucs.at(pos) = static_cast<Dna>(kmer%4); kmer >>= 2; } myfile << kmer_nucs << ", " << sorted_kmers.at(sk).first << std::endl; } } // Restore start cut kmer = max_kmer; if(kAdapterSearchInfoFile){ adapter_ext_pos = 0; } while(true){ kmer >>= 2; if(kAdapterSearchInfoFile){ myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << ++adapter_ext_pos << ", A"; for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){ myfile << at(adapter, pos); } myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", C"; for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){ myfile << at(adapter, pos); } myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+base) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", G"; for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){ myfile << at(adapter, pos); } myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+2*base) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Left" << adapter_ext_pos << ", T"; for(uintReadLen pos=0; pos < kKmerLength-1; ++pos){ myfile << at(adapter, pos); } myfile << ", " << adapter_kmers_.at(template_segment).counts_.at(kmer+3*base) << std::endl; } if( adapter_kmers_.at(template_segment).counts_.at(kmer+3*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+2*base) ){ max_extension = 3; second_highest = 2; } else{ max_extension = 2; second_highest = 3; } for(uintBaseCall ext=2; ext--; ){ if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+max_extension*base) ){ second_highest = max_extension; max_extension = ext; } else if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext*base) > adapter_kmers_.at(template_segment).counts_.at(kmer+second_highest*base) ){ second_highest = ext; } } kmer += base*max_extension; if( use_kmer.at(kmer) && adapter_kmers_.at(template_segment).counts_.at(kmer) > 100 && adapter_kmers_.at(template_segment).counts_.at(kmer) > 5*adapter_kmers_.at(template_segment).counts_.at(kmer-max_extension*base+second_highest*base) ){ insertValue(adapter, 0, static_cast<Dna>(max_extension) ); use_kmer.at(kmer) = false; // Prevent endless circle } else{ break; } } // Extend adapter kmer = max_kmer; if(kAdapterSearchInfoFile){ adapter_ext_pos = 0; } while(true){ kmer <<= 2; kmer %= adapter_kmers_.at(template_segment).counts_.size(); if(kAdapterSearchInfoFile){ myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << ++adapter_ext_pos << ", "; for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){ myfile << at(adapter, pos); } myfile << "A, " << adapter_kmers_.at(template_segment).counts_.at(kmer) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", "; for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){ myfile << at(adapter, pos); } myfile << "C, " << adapter_kmers_.at(template_segment).counts_.at(kmer+1) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", "; for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){ myfile << at(adapter, pos); } myfile << "G, " << adapter_kmers_.at(template_segment).counts_.at(kmer+2) << std::endl; myfile << static_cast<uintTempSeqPrint>(template_segment) << ", " << tries << ", Right" << adapter_ext_pos << ", "; for(uintReadLen pos=length(adapter)-kKmerLength+1; pos < length(adapter); ++pos){ myfile << at(adapter, pos); } myfile << "T, " << adapter_kmers_.at(template_segment).counts_.at(kmer+3) << std::endl; } if( adapter_kmers_.at(template_segment).counts_.at(kmer+3) > adapter_kmers_.at(template_segment).counts_.at(kmer+2) ){ max_extension = 3; second_highest = 2; } else{ max_extension = 2; second_highest = 3; } for(uintBaseCall ext=2; ext--; ){ if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext) > adapter_kmers_.at(template_segment).counts_.at(kmer+max_extension) ){ second_highest = max_extension; max_extension = ext; } else if( adapter_kmers_.at(template_segment).counts_.at(kmer+ext) > adapter_kmers_.at(template_segment).counts_.at(kmer+second_highest) ){ second_highest = ext; } } kmer += max_extension; if( use_kmer.at(kmer) && adapter_kmers_.at(template_segment).counts_.at(kmer) > 100 && adapter_kmers_.at(template_segment).counts_.at(kmer) > 5*adapter_kmers_.at(template_segment).counts_.at(kmer-max_extension+second_highest) ){ adapter += static_cast<Dna>(max_extension); use_kmer.at(kmer) = false; // Prevent endless circle } else{ break; } } // Remove A's at end while(length(adapter) && 0 == back(adapter)){ eraseBack(adapter); } if( 30 > length(adapter) ){ printInfo << "Detected non-extendible sequence '" << adapter << "' as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << std::endl; } else if( 120 < length(adapter) ){ printErr << "Detected very long sequence '" << adapter << "' as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << ", which is likely part of the genome." << std::endl; if(kAdapterSearchInfoFile){ myfile.close(); } return false; } else{ printInfo << "Detected adapter " << static_cast<uintTempSeqPrint>(template_segment+1) << ": " << adapter << std::endl; found_adapter = true; } } if(!found_adapter){ printErr << "Only non-extendible sequences were found as adapter for read " << static_cast<uintTempSeqPrint>(template_segment+1) << std::endl; if(kAdapterSearchInfoFile){ myfile.close(); } return false; } seqs_.at(template_segment).push_back(adapter); names_.at(template_segment).emplace_back(toCString(CharString(adapter))); // Free memory adapter_kmers_.at(template_segment).Clear(); adapter_start_kmers_.at(template_segment).clear(); adapter_start_kmers_.at(template_segment).shrink_to_fit(); } if(kAdapterSearchInfoFile){ myfile.close(); } combinations_.resize( 1, vector<bool>(1, true) ); // Set the single combinations to valid } return true; } void AdapterStats::PrepareAdapters(uintReadLen size_read_length, uintQual phred_quality_offset){ // Resize adapter vectors tmp_counts_.resize(seqs_.at(0).size()); for( auto &dim1 : tmp_counts_ ){ dim1.resize(seqs_.at(1).size()); for( auto &dim2 : dim1 ){ dim2.resize(size_read_length); for( auto &dim3 : dim2 ){ dim3.resize(size_read_length); } } } for(uintTempSeq seg=2; seg--; ){ tmp_start_cut_.at(seg).resize(seqs_.at(seg).size()); for( auto &dim1 : tmp_start_cut_.at(seg) ){ dim1.resize(size_read_length); } } tmp_polya_tail_length_.resize(size_read_length); // Prepare skewer matrix for adapter identification skewer::cMatrix::InitParameters(skewer::TRIM_PE, 0.1, 0.03, phred_quality_offset, false); // 0.1 and 0.03 are the default values from the skewer software for( auto &adapter : seqs_.at(0) ){ skewer::cMatrix::AddAdapter(skewer::cMatrix::firstAdapters, toCString(static_cast<CharString>(adapter)), length(adapter), skewer::TRIM_TAIL); } for( auto &adapter : seqs_.at(1) ){ skewer::cMatrix::AddAdapter(skewer::cMatrix::secondAdapters, toCString(static_cast<CharString>(adapter)), length(adapter), skewer::TRIM_TAIL); } skewer::cMatrix::CalculateIndices(combinations_, seqs_.at(0).size(), seqs_.at(1).size()); } bool AdapterStats::Detect(uintReadLen &adapter_position_first, uintReadLen &adapter_position_second, const BamAlignmentRecord &record_first, const BamAlignmentRecord &record_second, const Reference &reference, bool properly_mapped){ bool search_adapters(true); // Determine minimum adapter length int i_min_overlap(0); if( hasFlagUnmapped(record_first) || hasFlagUnmapped(record_second) ){ uintReadLen last_error_pos(kMinimumAdapterLengthUnmapped-1); // Case of both reads unmapped if( (hasFlagUnmapped(record_first) || CountErrors(last_error_pos, record_first, reference)) && (hasFlagUnmapped(record_second) || CountErrors(last_error_pos, record_second, reference)) ){ i_min_overlap = last_error_pos+1; // +1 because it is a position starting at 0 and we need a length } else{ // In case one of the reads is a perfect match don't look for adapters search_adapters = false; } } else{ uintReadLen last_error_pos1, last_error_pos2; if( CountErrors(last_error_pos1, record_first, reference) && CountErrors(last_error_pos2, record_second, reference) ){ i_min_overlap = max(last_error_pos1, last_error_pos2)+1; // A perfect matching piece cannot be an adapter, so adapter must be at least reach last error in both reads } else{ search_adapters = false; } } if(search_adapters){ // Fill read1, read2 with first/second measured in sequencer(by fastq file) not by position in bam file and convert to measurement/fastq direction (not reference/bam direction) const CharString *qual1, *qual2; CharString read1, read2, reversed_qual; if( hasFlagLast(record_second) ){ read1 = record_first.seq; if( hasFlagRC(record_first) ){ reverseComplement(read1); // Reverses in place, so don't let it act on the record sequence itself reversed_qual = record_first.qual; reverse(reversed_qual); qual1 = &reversed_qual; } else{ qual1 = &record_first.qual; } read2 = record_second.seq; if( hasFlagRC(record_second) ){ reverseComplement(read2); // Reverses in place, so don't let it act on the record sequence itself reversed_qual = record_second.qual; reverse(reversed_qual); qual2 = &reversed_qual; } else{ qual2 = &record_second.qual; } } else{ read1 = record_second.seq; if( hasFlagRC(record_second) ){ reverseComplement(read1); // Reverses in place, so don't let it act on the record sequence itself reversed_qual = record_second.qual; reverse(reversed_qual); qual1 = &reversed_qual; } else{ qual1 = &record_second.qual; } read2 = record_first.seq; if( hasFlagRC(record_first) ){ reverseComplement(read2); // Reverses in place, so don't let it act on the record sequence itself reversed_qual = record_first.qual; reverse(reversed_qual); qual2 = &reversed_qual; } else{ qual2 = &record_first.qual; } } auto index1 = skewer::cMatrix::findAdapter(toCString(read1), length(read1), reinterpret_cast<unsigned char *>(toCString(*qual1)), length(*qual1), i_min_overlap); if( index1.bc-- ){ // Adapter has been detected for first read (bc is now index of adapter) auto index2 = skewer::cMatrix::findAdapter2(toCString(read2), length(read2), reinterpret_cast<unsigned char *>(toCString(*qual2)), length(*qual2), i_min_overlap); if( index2.bc-- && combinations_.at(index1.bc).at(index2.bc)){ // Adapter has been detected also for second read and it is a valid pair with the first if( 2 > max(index1.pos,index2.pos) - min(index1.pos,index2.pos) ){ // Allow a single one-base indel in the insert between the adapters if( properly_mapped || VerifyInsert(read1, read2, index1.pos, index2.pos) ){ // Stats that need to be aware of cut length bool poly_a_tail = true; uintReadLen poly_a_tail_length = 0; for(uintReadLen pos=index1.pos + length(seqs_.at(0).at(index1.bc)); pos < length(read1); ++pos){ if(poly_a_tail){ if('A' == at(read1, pos)){ ++poly_a_tail_length; } else{ poly_a_tail=false; ++tmp_polya_tail_length_.at(poly_a_tail_length); } } if(!poly_a_tail){ ++tmp_overrun_bases_.at(Dna5(at(read1, pos))); } } poly_a_tail = true; poly_a_tail_length = 0; for(uintReadLen pos=index2.pos + length(seqs_.at(1).at(index2.bc)); pos < length(read2); ++pos){ if(poly_a_tail){ if('A' == at(read2, pos)){ ++poly_a_tail_length; } else{ poly_a_tail=false; ++tmp_polya_tail_length_.at(poly_a_tail_length); } } if(!poly_a_tail){ ++tmp_overrun_bases_.at(Dna5(at(read2, pos))); } } // If the read starts with an adapter note down if and how much it has been cut of at the beginning (position below 0) and set position to 0 for the further stats if(1>index1.pos){ ++tmp_start_cut_.at(0).at(index1.bc).at(-index1.pos); index1.pos = 0; } if(1>index2.pos){ ++tmp_start_cut_.at(1).at(index2.bc).at(-index2.pos); index2.pos = 0; } // Set return values if( hasFlagLast(record_first) ){ adapter_position_first = index2.pos; adapter_position_second = index1.pos; } else{ adapter_position_first = index1.pos; adapter_position_second = index2.pos; } // Fill in stats ++tmp_counts_.at(index1.bc).at(index2.bc).at(length(read1)-index1.pos).at(length(read2)-index2.pos); return true; } } } } } // If no adapter where found fill in read length adapter_position_first = length(record_first.seq); adapter_position_second = length(record_second.seq); return false; } void AdapterStats::Finalize(){ // Copy to final vectors counts_.resize(tmp_counts_.size()); for( auto i = tmp_counts_.size(); i--; ){ counts_.at(i).resize(tmp_counts_.at(i).size()); for( auto j = tmp_counts_.at(i).size(); j--; ){ counts_.at(i).at(j).Acquire(tmp_counts_.at(i).at(j)); } } for(uintTempSeq seg=2; seg--; ){ start_cut_.at(seg).resize(tmp_start_cut_.at(seg).size()); for( auto i = tmp_start_cut_.at(seg).size(); i--; ){ start_cut_.at(seg).at(i).Acquire(tmp_start_cut_.at(seg).at(i)); } } polya_tail_length_.Acquire(tmp_polya_tail_length_); for( auto i = tmp_overrun_bases_.size(); i--; ){ overrun_bases_.at(i) = tmp_overrun_bases_.at(i); } } void AdapterStats::SumCounts(){ for(uintTempSeq seg=2; seg--; ){ count_sum_.at(seg).clear(); count_sum_.at(seg).resize(start_cut_.at(seg).size(), 0); } // Sum adapters starting from length where adapters are unambiguous (sorted by content: so simply first position that differs from adapter before and after) uintFragCount sum; uintReadLen first_diff_before_a1(0), first_diff_after_a1, first_diff_before_a2, first_diff_after_a2; for( auto a1=counts_.size(); a1--; ){ first_diff_after_a1 = 0; if(a1){ // Not last in loop while(first_diff_after_a1 < min(length(seqs_.at(0).at(a1)), length(seqs_.at(0).at(a1-1))) && at(seqs_.at(0).at(a1), first_diff_after_a1) == at(seqs_.at(0).at(a1-1), first_diff_after_a1) ){ ++first_diff_after_a1; } } first_diff_before_a2 = 0; for( auto a2=counts_.at(0).size(); a2--; ){ // All vectors i are the same length so we can simply take the length of 0 first_diff_after_a2 = 0; if(a2){ // Not last in loop while(first_diff_after_a2 < min(length(seqs_.at(1).at(a2)), length(seqs_.at(1).at(a2-1))) && at(seqs_.at(1).at(a2), first_diff_after_a2) == at(seqs_.at(1).at(a2-1), first_diff_after_a2) ){ ++first_diff_after_a2; } } sum = 0; for( auto pos1 = max(max(first_diff_before_a1,first_diff_after_a1), static_cast<uintReadLen>(counts_.at(a1).at(a2).from())); pos1 < counts_.at(a1).at(a2).to(); ++pos1){ for( auto pos2 = max(max(first_diff_before_a2,first_diff_after_a2), static_cast<uintReadLen>(counts_.at(a1).at(a2).at(pos1).from())); pos2 < counts_.at(a1).at(a2).at(pos1).to(); ++pos2){ sum += counts_.at(a1).at(a2).at(pos1).at(pos2); } } count_sum_.at(0).at(a1) += sum; count_sum_.at(1).at(a2) += sum; first_diff_before_a2 = first_diff_after_a2; } first_diff_before_a1 = first_diff_after_a1; } } void AdapterStats::Shrink(){ for( auto &dim1 : counts_){ for( auto &adapter_pair : dim1){ ShrinkVect(adapter_pair); } } } void AdapterStats::PrepareSimulation(){ for(uintTempSeq seg=2; seg--; ){ significant_count_.at(seg).clear(); significant_count_.at(seg).resize(count_sum_.at(seg).size(), 0); uintFragCount threshold = ceil(*max_element(count_sum_.at(seg).begin(), count_sum_.at(seg).end()) * kMinFractionOfMaximumForSimulation); for(auto i=significant_count_.at(seg).size(); i--; ){ if(count_sum_.at(seg).at(i) < threshold){ significant_count_.at(seg).at(i) = 0; } else{ significant_count_.at(seg).at(i) = count_sum_.at(seg).at(i); } } } }
32,165
13,684
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <gtest/gtest.h> #include "laser_geometry/laser_geometry.h" #include "sensor_msgs/PointCloud.h" #include <math.h> #include <angles/angles.h> #include "rostest/permuter.h" #define PROJECTION_TEST_RANGE_MIN (0.23) #define PROJECTION_TEST_RANGE_MAX (40.0) class BuildScanException { }; sensor_msgs::LaserScan build_constant_scan(double range, double intensity, double ang_min, double ang_max, double ang_increment, ros::Duration scan_time) { if (((ang_max - ang_min) / ang_increment) < 0) throw (BuildScanException()); sensor_msgs::LaserScan scan; scan.header.stamp = ros::Time::now(); scan.header.frame_id = "laser_frame"; scan.angle_min = ang_min; scan.angle_max = ang_max; scan.angle_increment = ang_increment; scan.scan_time = scan_time.toSec(); scan.range_min = PROJECTION_TEST_RANGE_MIN; scan.range_max = PROJECTION_TEST_RANGE_MAX; uint32_t i = 0; for(; ang_min + i * ang_increment < ang_max; i++) { scan.ranges.push_back(range); scan.intensities.push_back(intensity); } scan.time_increment = scan_time.toSec()/(double)i; return scan; }; class TestProjection : public laser_geometry::LaserProjection { public: const boost::numeric::ublas::matrix<double>& getUnitVectors(double angle_min, double angle_max, double angle_increment, unsigned int length) { return getUnitVectors_(angle_min, angle_max, angle_increment, length); } }; void test_getUnitVectors(double angle_min, double angle_max, double angle_increment, unsigned int length) { double tolerance = 1e-12; TestProjection projector; const boost::numeric::ublas::matrix<double> & mat = projector.getUnitVectors(angle_min, angle_max, angle_increment, length); for (unsigned int i = 0; i < mat.size2(); i++) { EXPECT_NEAR(angles::shortest_angular_distance(atan2(mat(1,i), mat(0,i)), angle_min + i * angle_increment), 0, tolerance); // check expected angle EXPECT_NEAR(1.0, mat(1,i)*mat(1,i) + mat(0,i)*mat(0,i), tolerance); //make sure normalized } } #if 0 TEST(laser_geometry, getUnitVectors) { double min_angle = -M_PI/2; double max_angle = M_PI/2; double angle_increment = M_PI/180; std::vector<double> min_angles, max_angles, angle_increments; rostest::Permuter permuter; min_angles.push_back(-M_PI); min_angles.push_back(-M_PI/1.5); min_angles.push_back(-M_PI/2); min_angles.push_back(-M_PI/4); min_angles.push_back(-M_PI/8); min_angles.push_back(M_PI); min_angles.push_back(M_PI/1.5); min_angles.push_back(M_PI/2); min_angles.push_back(M_PI/4); min_angles.push_back(M_PI/8); permuter.addOptionSet(min_angles, &min_angle); max_angles.push_back(M_PI); max_angles.push_back(M_PI/1.5); max_angles.push_back(M_PI/2); max_angles.push_back(M_PI/4); max_angles.push_back(M_PI/8); max_angles.push_back(-M_PI); max_angles.push_back(-M_PI/1.5); max_angles.push_back(-M_PI/2); max_angles.push_back(-M_PI/4); max_angles.push_back(-M_PI/8); permuter.addOptionSet(max_angles, &max_angle); angle_increments.push_back(M_PI/180); // one degree angle_increments.push_back(M_PI/360); // half degree angle_increments.push_back(M_PI/720); // quarter degree angle_increments.push_back(-M_PI/180); // -one degree angle_increments.push_back(-M_PI/360); // -half degree angle_increments.push_back(-M_PI/720); // -quarter degree permuter.addOptionSet(angle_increments, &angle_increment); while (permuter.step()) { if ((max_angle - min_angle) / angle_increment > 0.0) { unsigned int length = round((max_angle - min_angle)/ angle_increment); try { test_getUnitVectors(min_angle, max_angle, angle_increment, length); test_getUnitVectors(min_angle, max_angle, angle_increment, (max_angle - min_angle)/ angle_increment); test_getUnitVectors(min_angle, max_angle, angle_increment, (max_angle - min_angle)/ angle_increment + 1); } catch (BuildScanException &ex) { if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception FAIL(); } } //else //printf("%f\n", (max_angle - min_angle) / angle_increment); } } TEST(laser_geometry, projectLaser) { double tolerance = 1e-12; laser_geometry::LaserProjection projector; double min_angle = -M_PI/2; double max_angle = M_PI/2; double angle_increment = M_PI/180; double range = 1.0; double intensity = 1.0; ros::Duration scan_time = ros::Duration(1/40); ros::Duration increment_time = ros::Duration(1/400); std::vector<double> ranges, intensities, min_angles, max_angles, angle_increments; std::vector<ros::Duration> increment_times, scan_times; rostest::Permuter permuter; ranges.push_back(-1.0); ranges.push_back(1.0); ranges.push_back(2.0); ranges.push_back(3.0); ranges.push_back(4.0); ranges.push_back(5.0); ranges.push_back(100.0); permuter.addOptionSet(ranges, &range); intensities.push_back(1.0); intensities.push_back(2.0); intensities.push_back(3.0); intensities.push_back(4.0); intensities.push_back(5.0); permuter.addOptionSet(intensities, &intensity); min_angles.push_back(-M_PI); min_angles.push_back(-M_PI/1.5); min_angles.push_back(-M_PI/2); min_angles.push_back(-M_PI/4); min_angles.push_back(-M_PI/8); permuter.addOptionSet(min_angles, &min_angle); max_angles.push_back(M_PI); max_angles.push_back(M_PI/1.5); max_angles.push_back(M_PI/2); max_angles.push_back(M_PI/4); max_angles.push_back(M_PI/8); permuter.addOptionSet(max_angles, &max_angle); // angle_increments.push_back(-M_PI/180); // -one degree angle_increments.push_back(M_PI/180); // one degree angle_increments.push_back(M_PI/360); // half degree angle_increments.push_back(M_PI/720); // quarter degree permuter.addOptionSet(angle_increments, &angle_increment); scan_times.push_back(ros::Duration(1/40)); scan_times.push_back(ros::Duration(1/20)); permuter.addOptionSet(scan_times, &scan_time); while (permuter.step()) { try { // printf("%f %f %f %f %f %f\n", range, intensity, min_angle, max_angle, angle_increment, scan_time.toSec()); sensor_msgs::LaserScan scan = build_constant_scan(range, intensity, min_angle, max_angle, angle_increment, scan_time); sensor_msgs::PointCloud cloud_out; projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)1); projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)1); projector.projectLaser(scan, cloud_out, -1.0); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)2); projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)2); projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)3); projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)4); unsigned int valid_points = 0; for (unsigned int i = 0; i < scan.ranges.size(); i++) if (scan.ranges[i] <= PROJECTION_TEST_RANGE_MAX && scan.ranges[i] >= PROJECTION_TEST_RANGE_MIN) valid_points ++; EXPECT_EQ(valid_points, cloud_out.points.size()); for (unsigned int i = 0; i < cloud_out.points.size(); i++) { EXPECT_NEAR(cloud_out.points[i].x , (float)((double)(scan.ranges[i]) * cos((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance); EXPECT_NEAR(cloud_out.points[i].y , (float)((double)(scan.ranges[i]) * sin((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance); EXPECT_NEAR(cloud_out.points[i].z, 0, tolerance); EXPECT_NEAR(cloud_out.channels[0].values[i], scan.intensities[i], tolerance);//intensity \todo determine this by lookup not hard coded order EXPECT_NEAR(cloud_out.channels[1].values[i], i, tolerance);//index EXPECT_NEAR(cloud_out.channels[2].values[i], scan.ranges[i], tolerance);//ranges EXPECT_NEAR(cloud_out.channels[3].values[i], (float)i * scan.time_increment, tolerance);//timestamps }; } catch (BuildScanException &ex) { if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception FAIL(); } } } #endif TEST(laser_geometry, projectLaser2) { double tolerance = 1e-12; laser_geometry::LaserProjection projector; double min_angle = -M_PI/2; double max_angle = M_PI/2; double angle_increment = M_PI/180; double range = 1.0; double intensity = 1.0; ros::Duration scan_time = ros::Duration(1/40); ros::Duration increment_time = ros::Duration(1/400); std::vector<double> ranges, intensities, min_angles, max_angles, angle_increments; std::vector<ros::Duration> increment_times, scan_times; rostest::Permuter permuter; ranges.push_back(-1.0); ranges.push_back(1.0); ranges.push_back(2.0); ranges.push_back(3.0); ranges.push_back(4.0); ranges.push_back(5.0); ranges.push_back(100.0); permuter.addOptionSet(ranges, &range); intensities.push_back(1.0); intensities.push_back(2.0); intensities.push_back(3.0); intensities.push_back(4.0); intensities.push_back(5.0); permuter.addOptionSet(intensities, &intensity); min_angles.push_back(-M_PI); min_angles.push_back(-M_PI/1.5); min_angles.push_back(-M_PI/2); min_angles.push_back(-M_PI/4); min_angles.push_back(-M_PI/8); permuter.addOptionSet(min_angles, &min_angle); max_angles.push_back(M_PI); max_angles.push_back(M_PI/1.5); max_angles.push_back(M_PI/2); max_angles.push_back(M_PI/4); max_angles.push_back(M_PI/8); permuter.addOptionSet(max_angles, &max_angle); // angle_increments.push_back(-M_PI/180); // -one degree angle_increments.push_back(M_PI/180); // one degree angle_increments.push_back(M_PI/360); // half degree angle_increments.push_back(M_PI/720); // quarter degree permuter.addOptionSet(angle_increments, &angle_increment); scan_times.push_back(ros::Duration(1/40)); scan_times.push_back(ros::Duration(1/20)); permuter.addOptionSet(scan_times, &scan_time); while (permuter.step()) { try { // printf("%f %f %f %f %f %f\n", range, intensity, min_angle, max_angle, angle_increment, scan_time.toSec()); sensor_msgs::LaserScan scan = build_constant_scan(range, intensity, min_angle, max_angle, angle_increment, scan_time); sensor_msgs::PointCloud2 cloud_out; projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4); projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4); projector.projectLaser(scan, cloud_out, -1.0); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5); projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5); projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)6); projector.projectLaser(scan, cloud_out, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)7); unsigned int valid_points = 0; for (unsigned int i = 0; i < scan.ranges.size(); i++) if (scan.ranges[i] <= PROJECTION_TEST_RANGE_MAX && scan.ranges[i] >= PROJECTION_TEST_RANGE_MIN) valid_points ++; EXPECT_EQ(valid_points, cloud_out.width); uint32_t x_offset = 0; uint32_t y_offset = 0; uint32_t z_offset = 0; uint32_t intensity_offset = 0; uint32_t index_offset = 0; uint32_t distance_offset = 0; uint32_t stamps_offset = 0; for (std::vector<sensor_msgs::PointField>::iterator f = cloud_out.fields.begin(); f != cloud_out.fields.end(); f++) { if (f->name == "x") x_offset = f->offset; if (f->name == "y") y_offset = f->offset; if (f->name == "z") z_offset = f->offset; if (f->name == "intensity") intensity_offset = f->offset; if (f->name == "index") index_offset = f->offset; if (f->name == "distances") distance_offset = f->offset; if (f->name == "stamps") stamps_offset = f->offset; } for (unsigned int i = 0; i < cloud_out.width; i++) { EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + x_offset] , (float)((double)(scan.ranges[i]) * cos((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance); EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + y_offset] , (float)((double)(scan.ranges[i]) * sin((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance); EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + z_offset] , 0, tolerance); EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + intensity_offset] , scan.intensities[i], tolerance);//intensity \todo determine this by lookup not hard coded order EXPECT_NEAR(*(uint32_t*)&cloud_out.data[i*cloud_out.point_step + index_offset], i, tolerance);//index EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + distance_offset], scan.ranges[i], tolerance);//ranges EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + stamps_offset], (float)i * scan.time_increment, tolerance);//timestamps }; } catch (BuildScanException &ex) { if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception FAIL(); } } } TEST(laser_geometry, transformLaserScanToPointCloud) { tf::Transformer tf; double tolerance = 1e-12; laser_geometry::LaserProjection projector; double min_angle = -M_PI/2; double max_angle = M_PI/2; double angle_increment = M_PI/180; double range = 1.0; double intensity = 1.0; ros::Duration scan_time = ros::Duration(1/40); ros::Duration increment_time = ros::Duration(1/400); std::vector<double> ranges, intensities, min_angles, max_angles, angle_increments; std::vector<ros::Duration> increment_times, scan_times; rostest::Permuter permuter; ranges.push_back(-1.0); ranges.push_back(1.0); ranges.push_back(2.0); ranges.push_back(3.0); ranges.push_back(4.0); ranges.push_back(5.0); ranges.push_back(100.0); permuter.addOptionSet(ranges, &range); intensities.push_back(1.0); intensities.push_back(2.0); intensities.push_back(3.0); intensities.push_back(4.0); intensities.push_back(5.0); permuter.addOptionSet(intensities, &intensity); min_angles.push_back(-M_PI); min_angles.push_back(-M_PI/1.5); min_angles.push_back(-M_PI/2); min_angles.push_back(-M_PI/4); min_angles.push_back(-M_PI/8); max_angles.push_back(M_PI); max_angles.push_back(M_PI/1.5); max_angles.push_back(M_PI/2); max_angles.push_back(M_PI/4); max_angles.push_back(M_PI/8); permuter.addOptionSet(min_angles, &min_angle); permuter.addOptionSet(max_angles, &max_angle); angle_increments.push_back(-M_PI/180); // -one degree angle_increments.push_back(M_PI/180); // one degree angle_increments.push_back(M_PI/360); // half degree angle_increments.push_back(M_PI/720); // quarter degree permuter.addOptionSet(angle_increments, &angle_increment); scan_times.push_back(ros::Duration(1/40)); scan_times.push_back(ros::Duration(1/20)); permuter.addOptionSet(scan_times, &scan_time); while (permuter.step()) { try { //printf("%f %f %f %f %f %f\n", range, intensity, min_angle, max_angle, angle_increment, scan_time.toSec()); sensor_msgs::LaserScan scan = build_constant_scan(range, intensity, min_angle, max_angle, angle_increment, scan_time); scan.header.frame_id = "laser_frame"; sensor_msgs::PointCloud cloud_out; projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)1); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Intensity); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)1); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)2); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)2); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)3); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp); EXPECT_EQ(cloud_out.channels.size(), (unsigned int)4); unsigned int valid_points = 0; for (unsigned int i = 0; i < scan.ranges.size(); i++) if (scan.ranges[i] <= PROJECTION_TEST_RANGE_MAX && scan.ranges[i] >= PROJECTION_TEST_RANGE_MIN) valid_points ++; EXPECT_EQ(valid_points, cloud_out.points.size()); for (unsigned int i = 0; i < cloud_out.points.size(); i++) { EXPECT_NEAR(cloud_out.points[i].x , (float)((double)(scan.ranges[i]) * cos((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance); EXPECT_NEAR(cloud_out.points[i].y , (float)((double)(scan.ranges[i]) * sin((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance); EXPECT_NEAR(cloud_out.points[i].z, 0, tolerance); EXPECT_NEAR(cloud_out.channels[0].values[i], scan.intensities[i], tolerance);//intensity \todo determine this by lookup not hard coded order EXPECT_NEAR(cloud_out.channels[1].values[i], i, tolerance);//index EXPECT_NEAR(cloud_out.channels[2].values[i], scan.ranges[i], tolerance);//ranges EXPECT_NEAR(cloud_out.channels[3].values[i], (float)i * scan.time_increment, tolerance);//timestamps }; } catch (BuildScanException &ex) { if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception FAIL(); } } } TEST(laser_geometry, transformLaserScanToPointCloud2) { tf::Transformer tf; tf2::BufferCore tf2; double tolerance = 1e-12; laser_geometry::LaserProjection projector; double min_angle = -M_PI/2; double max_angle = M_PI/2; double angle_increment = M_PI/180; double range = 1.0; double intensity = 1.0; ros::Duration scan_time = ros::Duration(1/40); ros::Duration increment_time = ros::Duration(1/400); std::vector<double> ranges, intensities, min_angles, max_angles, angle_increments; std::vector<ros::Duration> increment_times, scan_times; rostest::Permuter permuter; ranges.push_back(-1.0); ranges.push_back(1.0); ranges.push_back(2.0); ranges.push_back(3.0); ranges.push_back(4.0); ranges.push_back(5.0); ranges.push_back(100.0); permuter.addOptionSet(ranges, &range); intensities.push_back(1.0); intensities.push_back(2.0); intensities.push_back(3.0); intensities.push_back(4.0); intensities.push_back(5.0); permuter.addOptionSet(intensities, &intensity); min_angles.push_back(-M_PI); min_angles.push_back(-M_PI/1.5); min_angles.push_back(-M_PI/2); min_angles.push_back(-M_PI/4); min_angles.push_back(-M_PI/8); max_angles.push_back(M_PI); max_angles.push_back(M_PI/1.5); max_angles.push_back(M_PI/2); max_angles.push_back(M_PI/4); max_angles.push_back(M_PI/8); permuter.addOptionSet(min_angles, &min_angle); permuter.addOptionSet(max_angles, &max_angle); angle_increments.push_back(-M_PI/180); // -one degree angle_increments.push_back(M_PI/180); // one degree angle_increments.push_back(M_PI/360); // half degree angle_increments.push_back(M_PI/720); // quarter degree permuter.addOptionSet(angle_increments, &angle_increment); scan_times.push_back(ros::Duration(1/40)); scan_times.push_back(ros::Duration(1/20)); permuter.addOptionSet(scan_times, &scan_time); while (permuter.step()) { try { //printf("%f %f %f %f %f %f\n", range, intensity, min_angle, max_angle, angle_increment, scan_time.toSec()); sensor_msgs::LaserScan scan = build_constant_scan(range, intensity, min_angle, max_angle, angle_increment, scan_time); scan.header.frame_id = "laser_frame"; sensor_msgs::PointCloud2 cloud_out; projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::None); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)3); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::None); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)3); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Intensity); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Intensity); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)4); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)5); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)6); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)6); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)7); projector.transformLaserScanToPointCloud(scan.header.frame_id, scan, cloud_out, tf2, -1.0, laser_geometry::channel_option::Intensity | laser_geometry::channel_option::Index | laser_geometry::channel_option::Distance | laser_geometry::channel_option::Timestamp); EXPECT_EQ(cloud_out.fields.size(), (unsigned int)7); EXPECT_EQ(cloud_out.is_dense, false); unsigned int valid_points = 0; for (unsigned int i = 0; i < scan.ranges.size(); i++) if (scan.ranges[i] <= PROJECTION_TEST_RANGE_MAX && scan.ranges[i] >= PROJECTION_TEST_RANGE_MIN) valid_points ++; EXPECT_EQ(valid_points, cloud_out.width); uint32_t x_offset = 0; uint32_t y_offset = 0; uint32_t z_offset = 0; uint32_t intensity_offset = 0; uint32_t index_offset = 0; uint32_t distance_offset = 0; uint32_t stamps_offset = 0; for (std::vector<sensor_msgs::PointField>::iterator f = cloud_out.fields.begin(); f != cloud_out.fields.end(); f++) { if (f->name == "x") x_offset = f->offset; if (f->name == "y") y_offset = f->offset; if (f->name == "z") z_offset = f->offset; if (f->name == "intensity") intensity_offset = f->offset; if (f->name == "index") index_offset = f->offset; if (f->name == "distances") distance_offset = f->offset; if (f->name == "stamps") stamps_offset = f->offset; } for (unsigned int i = 0; i < cloud_out.width; i++) { EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + x_offset] , (float)((double)(scan.ranges[i]) * cos((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance); EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + y_offset] , (float)((double)(scan.ranges[i]) * sin((double)(scan.angle_min) + i * (double)(scan.angle_increment))), tolerance); EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + z_offset] , 0, tolerance); EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + intensity_offset] , scan.intensities[i], tolerance);//intensity \todo determine this by lookup not hard coded order EXPECT_NEAR(*(uint32_t*)&cloud_out.data[i*cloud_out.point_step + index_offset], i, tolerance);//index EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + distance_offset], scan.ranges[i], tolerance);//ranges EXPECT_NEAR(*(float*)&cloud_out.data[i*cloud_out.point_step + stamps_offset], (float)i * scan.time_increment, tolerance);//timestamps }; } catch (BuildScanException &ex) { if ((max_angle - min_angle) / angle_increment > 0.0)//make sure it is not a false exception FAIL(); } } } int main(int argc, char **argv){ ros::Time::init(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
28,688
10,865
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chat.h" #include "base58.h" #include "clientversion.h" #include "net.h" #include "pubkey.h" #include "timedata.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include "rpcpog.h" #include <stdint.h> #include <algorithm> #include <map> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <boost/thread.hpp> #include <boost/algorithm/string.hpp> using namespace std; map<uint256, CChat> mapChats; CCriticalSection cs_mapChats; void CChat::SetNull() { nVersion = 1; nTime = 0; nID = 0; bPrivate = false; nPriority = 0; sPayload.clear(); sFromNickName.clear(); sToNickName.clear(); sDestination.clear(); } std::string CChat::ToString() const { return strprintf( "CChat(\n" " nVersion = %d\n" " nTime = %d\n" " nID = %d\n" " bPrivate = %d\n" " nPriority = %d\n" " sDestination = %s\n" " sPayload = \"%s\"\n" " sFromNickName= \"%s\"\n" " sToNickName = \"%s\"\n" ")\n", nVersion, nTime, nID, bPrivate, nPriority, sDestination, sPayload, sFromNickName, sToNickName); } std::string CChat::Serialized() const { return strprintf( "%d<COL>%d<COL>%d<COL>%d<COL>%d<COL>%s<COL>%s<COL>%s<COL>%s", nVersion, nTime, nID, bPrivate, nPriority, sDestination, sPayload, sFromNickName, sToNickName); } void CChat::Deserialize(std::string sData) { std::vector<std::string> vInput = Split(sData.c_str(),"<COL>"); if (vInput.size() > 7) { this->nVersion = cdbl(vInput[0], 0); this->nTime = cdbl(vInput[1], 0); this->nID = cdbl(vInput[2], 0); this->bPrivate = (bool)(cdbl(vInput[3], 0)); this->nPriority = cdbl(vInput[4], 0); this->sDestination = vInput[5]; this->sPayload = vInput[6]; this->sFromNickName = vInput[7]; this->sToNickName = vInput[8]; } } bool CChat::IsNull() const { return (nTime == 0); } uint256 CChat::GetHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << nTime; ss << nPriority; ss << sPayload; ss << sFromNickName; ss << sToNickName; ss << sDestination; return ss.GetHash(); } bool CChat::RelayTo(CNode* pnode) const { if (pnode->nVersion == 0) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { pnode->PushMessage(NetMsgType::CHAT, *this); return true; } return false; } CChat CChat::getChatByHash(const uint256 &hash) { CChat retval; { LOCK(cs_mapChats); map<uint256, CChat>::iterator mi = mapChats.find(hash); if(mi != mapChats.end()) retval = mi->second; } return retval; } bool CChat::ProcessChat() { map<uint256, CChat>::iterator mi = mapChats.find(GetHash()); if(mi != mapChats.end()) return false; // Never seen this chat record mapChats.insert(make_pair(GetHash(), *this)); // Notify UI std::string sNickName = GetArg("-nickname", ""); if (boost::iequals(sNickName, sToNickName) && sPayload == "<RING>" && bPrivate == true) { msPagedFrom = sFromNickName; mlPaged++; } uiInterface.NotifyChatEvent(Serialized()); return true; }
3,633
1,486
#include "SteppingRight.h" void SteppingRight::entry(void) { spdlog::info(" Stepping RIGHT"); trajectoryGenerator->initialiseTrajectory(robot->getCurrentMotion(), Foot::Left, robot->getJointStates()); robot->startNewTraj(); robot->setCurrentState(AlexState::StepR); } void SteppingRight::during(void) { robot->moveThroughTraj(); } void SteppingRight::exit(void) { spdlog::debug("EXITING STEPPING RIGHT"); }
432
149
// Copyright (c) 2013, Ford Motor Company // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following // disclaimer in the documentation and/or other materials provided with the // distribution. // // Neither the name of the Ford Motor Company 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. #ifdef MODIFY_FUNCTION_SIGN #include <global_first.h> #endif #include "smart_objects/smart_object.h" #include "smart_objects/string_schema_item.h" #ifdef MODIFY_FUNCTION_SIGN #ifdef OS_WIN32 #include "utils/global.h" #endif #endif namespace NsSmartDeviceLink { namespace NsSmartObjects { utils::SharedPtr<CStringSchemaItem> CStringSchemaItem::create( const TSchemaItemParameter<size_t>& MinLength, const TSchemaItemParameter<size_t>& MaxLength, const TSchemaItemParameter<std::string>& DefaultValue) { return new CStringSchemaItem(MinLength, MaxLength, DefaultValue); } Errors::eType CStringSchemaItem::validate(const SmartObject& Object) { Errors::eType result = Errors::ERROR; if (SmartType_String == Object.getType()) { result = Errors::OK; size_t minLength; size_t maxLength; #ifdef MODIFY_FUNCTION_SIGN #ifdef OS_WIN32 std::string strIn = Object.asString(); wchar_string value; Global::toUnicode(strIn, CP_UTF8, value); #else std::string value = Object.asString(); #endif #else std::string value = Object.asString(); #endif if (true == mMinLength.getValue(minLength)) { if (value.size() < minLength) { result = Errors::INVALID_VALUE; } } if (true == mMaxLength.getValue(maxLength)) { if (value.size() > maxLength) { result = Errors::OUT_OF_RANGE; } } } else { result = Errors::INVALID_VALUE; } return result; } bool CStringSchemaItem::setDefaultValue(SmartObject& Object) { bool result = false; std::string value; if (true == mDefaultValue.getValue(value)) { Object = value; result = true; } return result; } void CStringSchemaItem::BuildObjectBySchema(const SmartObject& pattern_object, SmartObject& result_object) { if (SmartType_String == pattern_object.getType()) { result_object = pattern_object; } else { bool result = setDefaultValue(result_object); if (false == result) { result_object = std::string(""); } } } CStringSchemaItem::CStringSchemaItem( const TSchemaItemParameter<size_t>& MinLength, const TSchemaItemParameter<size_t>& MaxLength, const TSchemaItemParameter<std::string>& DefaultValue) : mMinLength(MinLength), mMaxLength(MaxLength), mDefaultValue(DefaultValue) { } } // namespace NsSmartObjects } // namespace NsSmartDeviceLink
4,085
1,379
// CClientUse.cpp // Copyright Menace Software (www.menasoft.com). // #include "graysvr.h" // predef header. #include "cclient.h" bool CClient::Cmd_Use_Item( CItem * pItem, bool fTestTouch ) { // Assume we can see the target. // called from Event_DoubleClick if ( pItem == NULL ) return false; if ( fTestTouch ) { // CanTouch handles priv level compares for chars if ( ! m_pChar->CanUse( pItem, false )) { if ( ! m_pChar->CanTouch( pItem )) { SysMessage(( m_pChar->IsStatFlag( STATF_DEAD )) ? "Your ghostly hand passes through the object." : "You can't reach that." ); return false; } SysMessage( "You can't use this where it is." ); return false; } } CItemBase * pItemDef = pItem->Item_GetDef(); // Must equip the item ? if ( pItemDef->IsTypeEquippable() && pItem->GetParent() != m_pChar ) { DEBUG_CHECK( pItemDef->GetEquipLayer()); switch ( pItem->GetType()) { case IT_LIGHT_LIT: case IT_SPELLBOOK: // can be equipped, but don't need to be break; case IT_LIGHT_OUT: if ( ! pItem->IsItemInContainer()) break; default: if ( ! m_pChar->CanMove( pItem ) || ! m_pChar->ItemEquip( pItem )) { SysMessage( "The item should be equipped to use." ); return false; } break; } } SetTargMode(); m_Targ_UID = pItem->GetUID(); // probably already set anyhow. m_tmUseItem.m_pParent = pItem->GetParent(); // Cheat Verify. if ( pItem->OnTrigger( ITRIG_DCLICK, m_pChar ) == TRIGRET_RET_TRUE ) { return true; } // Use types of items. (specific to client) switch ( pItem->GetType() ) { case IT_TRACKER: { DIR_TYPE dir = (DIR_TYPE) ( DIR_QTY + 1 ); // invalid value. if ( ! m_pChar->Skill_Tracking( pItem->m_uidLink, dir )) { if ( pItem->m_uidLink.IsValidUID()) { SysMessage( "You cannot locate your target" ); } m_Targ_UID = pItem->GetUID(); addTarget( CLIMODE_TARG_LINK, "Who do you want to attune to ?" ); } } return true; case IT_TRACK_ITEM: // 109 - track a id or type of item. case IT_TRACK_CHAR: // 110 = track a char or range of char id's // Track a type of item or creature. { // Look in the local area for this item or char. } break; case IT_SHAFT: case IT_FEATHER: Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_bolts" )); return true; case IT_FISH_POLE: // Just be near water ? addTarget( CLIMODE_TARG_USE_ITEM, "Where would you like to fish?", true ); return true; case IT_DEED: addTargetDeed( pItem ); return true; case IT_METRONOME: pItem->OnTick(); return true; case IT_EQ_BANK_BOX: case IT_EQ_VENDOR_BOX: g_Log.Event( LOGL_WARN|LOGM_CHEAT, "%x:Cheater '%s' is using 3rd party tools to open bank box\n", m_Socket.GetSocket(), (LPCTSTR) GetAccount()->GetName()); return false; case IT_CONTAINER_LOCKED: case IT_SHIP_HOLD_LOCK: if ( ! m_pChar->GetPackSafe()->ContentFindKeyFor( pItem )) { SysMessage( "This item is locked."); if ( ! IsPriv( PRIV_GM )) return false; } case IT_CORPSE: case IT_SHIP_HOLD: case IT_CONTAINER: case IT_TRASH_CAN: { CItemContainer * pPack = dynamic_cast <CItemContainer *>(pItem); if ( ! m_pChar->Skill_Snoop_Check( pPack )) { if ( ! addContainerSetup( pPack )) return false; } } return true; case IT_GAME_BOARD: if ( ! pItem->IsTopLevel()) { SysMessage( "Can't open game board in a container" ); return false; } { CItemContainer* pBoard = dynamic_cast <CItemContainer *>(pItem); ASSERT(pBoard); pBoard->Game_Create(); addContainerSetup( pBoard ); } return true; case IT_BBOARD: addBulletinBoard( dynamic_cast<CItemContainer *>(pItem)); return true; case IT_SIGN_GUMP: // Things like grave stones and sign plaques. // Need custom gumps. { GUMP_TYPE gumpid = pItemDef->m_ttContainer.m_gumpid; if ( ! gumpid ) { return false; } addGumpTextDisp( pItem, gumpid, pItem->GetName(), ( pItem->IsIndividualName()) ? pItem->GetName() : NULL ); } return true; case IT_BOOK: case IT_MESSAGE: case IT_EQ_NPC_SCRIPT: case IT_EQ_MESSAGE: if ( ! addBookOpen( pItem )) { SysMessage( "The book apears to be ruined!" ); } return true; case IT_STONE_GUILD: case IT_STONE_TOWN: case IT_STONE_ROOM: // Guild and town stones. { CItemStone * pStone = dynamic_cast<CItemStone*>(pItem); if ( pStone == NULL ) break; pStone->Use_Item( this ); } return true; case IT_ADVANCE_GATE: // Upgrade the player to the skills of the selected NPC script. m_pChar->Use_AdvanceGate( pItem ); return true; case IT_POTION: if ( ! m_pChar->CanMove( pItem )) // locked down decoration. { SysMessage( "You can't move the item." ); return false; } if ( RES_GET_INDEX(pItem->m_itPotion.m_Type) == SPELL_Poison ) { // ask them what they want to use the poison on ? // Poisoning or poison self ? addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, true ); return true; } else if ( RES_GET_INDEX(pItem->m_itPotion.m_Type) == SPELL_Explosion ) { // Throw explode potion. if ( ! m_pChar->ItemPickup( pItem, 1 )) return true; m_tmUseItem.m_pParent = pItem->GetParent(); // Cheat Verify FIX. addTarget( CLIMODE_TARG_USE_ITEM, "Where do you want to throw the potion?", true, true ); // Put the potion in our hand as well. (and set it's timer) pItem->m_itPotion.m_tick = 4; // countdown to explode purple. pItem->SetTimeout( TICK_PER_SEC ); pItem->m_uidLink = m_pChar->GetUID(); return true; } if ( m_pChar->Use_Drink( pItem )) return true; break; case IT_ANIM_ACTIVE: SysMessage( "The item is in use" ); return false; case IT_CLOCK: addObjMessage( m_pChar->GetTopSector()->GetLocalGameTime(), pItem ); return true; case IT_SPAWN_CHAR: SysMessage( "You negate the spawn" ); pItem->Spawn_KillChildren(); return true; case IT_SPAWN_ITEM: SysMessage( "You trigger the spawn." ); pItem->Spawn_OnTick( true ); return true; case IT_SHRINE: if ( m_pChar->OnSpellEffect( SPELL_Resurrection, m_pChar, 1000, pItem )) return true; SysMessage( "You have a feeling of holiness" ); return true; case IT_SHIP_TILLER: // dclick on tiller man. pItem->Speak( "Arrg stop that.", 0, TALKMODE_SAY, FONT_NORMAL ); return true; // A menu or such other action ( not instantanious) case IT_WAND: case IT_SCROLL: // activate the scroll. return Cmd_Skill_Magery( (SPELL_TYPE)RES_GET_INDEX(pItem->m_itWeapon.m_spell), pItem ); case IT_RUNE: // name the rune. if ( ! m_pChar->CanMove( pItem, true )) { return false; } addPromptConsole( CLIMODE_PROMPT_NAME_RUNE, "What is the new name of the rune ?" ); return true; case IT_CARPENTRY: // Carpentry type tool Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_carpentry" )); return true; // Solve for the combination of this item with another. case IT_FORGE: addTarget( CLIMODE_TARG_USE_ITEM, "Select ore to smelt." ); return true; case IT_ORE: // just use the nearest forge. return m_pChar->Skill_Mining_Smelt( pItem, NULL ); case IT_INGOT: return Cmd_Skill_Smith( pItem ); case IT_KEY: case IT_KEYRING: if ( pItem->GetTopLevelObj() != m_pChar && ! m_pChar->IsPriv(PRIV_GM)) { SysMessage( "The key must be on your person" ); return false; } addTarget( CLIMODE_TARG_USE_ITEM, "Select item to use the key on.", false, true ); return true; case IT_BANDAGE: // SKILL_HEALING, or SKILL_VETERINARY addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, false ); return true; case IT_BANDAGE_BLOOD: // Clean the bandages. case IT_COTTON: // use on a spinning wheel. case IT_WOOL: // use on a spinning wheel. case IT_YARN: // Use this on a loom. case IT_THREAD: // Use this on a loom. case IT_COMM_CRYSTAL: case IT_SCISSORS: case IT_LOCKPICK: // Use on a locked thing. case IT_CARPENTRY_CHOP: case IT_WEAPON_MACE_STAFF: case IT_WEAPON_MACE_SMITH: // Can be used for smithing ? case IT_WEAPON_MACE_SHARP: // war axe can be used to cut/chop trees. case IT_WEAPON_SWORD: // 23 = case IT_WEAPON_FENCE: // 24 = can't be used to chop trees. case IT_WEAPON_AXE: addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to use this on?", false, true ); return true; case IT_MEAT_RAW: case IT_FOOD_RAW: addTarget( CLIMODE_TARG_USE_ITEM, "What do you want to cook this on?" ); return true; case IT_FISH: SysMessage( "Use a knife to cut this up" ); return true; case IT_TELESCOPE: // Big telescope. SysMessage( "Wow you can see the sky!" ); return true; case IT_MAP: case IT_MAP_BLANK: if ( ! pItem->m_itMap.m_right && ! pItem->m_itMap.m_bottom ) { Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_cartography" )); } else if ( ! IsPriv(PRIV_GM) && pItem->GetTopLevelObj() != m_pChar ) // must be on your person. { SysMessage( "You must possess the map to get a good look at it." ); } else { addMap( dynamic_cast <CItemMap*>( pItem )); } return true; case IT_CANNON_BALL: { CGString sTmp; sTmp.Format( "What do you want to use the %s on?", (LPCTSTR) pItem->GetName()); addTarget( CLIMODE_TARG_USE_ITEM, sTmp ); } return true; case IT_CANNON_MUZZLE: // Make sure the cannon is loaded. if ( ! m_pChar->CanUse( pItem, false )) return( false ); if ( ! ( pItem->m_itCannon.m_Load & 1 )) { addTarget( CLIMODE_TARG_USE_ITEM, "The cannon needs powder" ); return true; } if ( ! ( pItem->m_itCannon.m_Load & 2 )) { addTarget( CLIMODE_TARG_USE_ITEM, "The cannon needs shot" ); return true; } addTarget( CLIMODE_TARG_USE_ITEM, "Armed and ready. What is the target?", false, true ); return true; case IT_CRYSTAL_BALL: // Gaze into the crystal ball. return true; case IT_WEAPON_MACE_CROOK: addTarget( CLIMODE_TARG_USE_ITEM, "What would you like to herd?", false, true ); return true; case IT_SEED: case IT_PITCHER_EMPTY: { // not a crime. CGString sTmp; sTmp.Format( "Where do you want to use the %s?", (LPCTSTR) pItem->GetName()); addTarget( CLIMODE_TARG_USE_ITEM, sTmp, true ); } return true; case IT_WEAPON_MACE_PICK: { // Mine at the location. (possible crime?) CGString sTmp; sTmp.Format( "Where do you want to use the %s?", (LPCTSTR) pItem->GetName()); addTarget( CLIMODE_TARG_USE_ITEM, sTmp, true, true ); } return true; case IT_SPELLBOOK: addSpellbookOpen( pItem ); return true; case IT_HAIR_DYE: if (!m_pChar->LayerFind( LAYER_BEARD ) && !m_pChar->LayerFind( LAYER_HAIR )) { SysMessage("You have no hair to dye!"); return true; } Dialog_Setup( CLIMODE_DIALOG_HAIR_DYE, g_Cfg.ResourceGetIDType( RES_DIALOG, "d_HAIR_DYE" ), m_pChar ); return true; case IT_DYE: addTarget( CLIMODE_TARG_USE_ITEM, "Which dye vat will you use this on?" ); return true; case IT_DYE_VAT: addTarget( CLIMODE_TARG_USE_ITEM, "Select the object to use this on.", false, true ); return true; case IT_MORTAR: // If we have a mortar then do alchemy. addTarget( CLIMODE_TARG_USE_ITEM, "What reagent you like to make a potion out of?" ); return true; case IT_POTION_EMPTY: if ( ! m_pChar->ContentFind(RESOURCE_ID(RES_TYPEDEF,IT_MORTAR))) { SysMessage( "You have no mortar and pestle." ); return( false ); } addTarget( CLIMODE_TARG_USE_ITEM, "What reagent you like to make a potion out of?" ); return true; case IT_REAGENT: // Make a potion with this. (The best type we can) if ( ! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_MORTAR))) { SysMessage( "You have no mortar and pestle." ); return false; } Cmd_Skill_Alchemy( pItem ); return true; // Put up menus to better decide what to do. case IT_TINKER_TOOLS: // Tinker tools. Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_tinker" )); return true; case IT_SEWING_KIT: // IT_SEWING_KIT Sew with materials we have on hand. { CGString sTmp; sTmp.Format( "What do you want to use the %s on?", (LPCTSTR) pItem->GetName()); addTarget( CLIMODE_TARG_USE_ITEM, sTmp ); } return true; case IT_SCROLL_BLANK: Cmd_Skill_Inscription(); return true; default: // An NPC could use it this way. if ( m_pChar->Use_Item( pItem )) return( true ); break; } SysMessage( "You can't think of a way to use that item."); return( false ); } void CClient::Cmd_EditItem( CObjBase * pObj, int iSelect ) { // ARGS: // iSelect == -1 = setup. // m_Targ_Text = what are we doing to it ? // if ( pObj == NULL ) return; CContainer * pContainer = dynamic_cast <CContainer *> (pObj); if ( pContainer == NULL ) { addGumpDialogProps( pObj->GetUID()); return; } if ( iSelect == 0 ) return; // cancelled. if ( iSelect > 0 ) { // We selected an item. if ( iSelect >= COUNTOF(m_tmMenu.m_Item)) return; if ( m_Targ_Text.IsEmpty()) { addGumpDialogProps( m_tmMenu.m_Item ); } else { OnTarg_Obj_Set( CGrayUID( m_tmMenu.m_Item ).ObjFind() ); } return; } CMenuItem item; // Most as we want to display at one time. item.m_sText.Format( "Contents of %s", (LPCTSTR) pObj->GetName()); int count=0; for ( CItem * pItem = pContainer->GetContentHead(); pItem != NULL; pItem = pItem->GetNext()) { if ( count >= COUNTOF( item )) break; m_tmMenu.m_Item = pItem->GetUID(); item.m_sText = pItem->GetName(); ITEMID_TYPE idi = pItem->GetDispID(); item.m_id = idi; } addItemMenu( CLIMODE_MENU_EDIT, item, count, pObj ); } bool CClient::Cmd_CreateItem( ITEMID_TYPE id, bool fStatic ) { // make an item near by. m_tmAdd.m_id = id; m_tmAdd.m_fStatic = fStatic; return addTargetItems( CLIMODE_TARG_ADDITEM, m_tmAdd.m_id ); } bool CClient::Cmd_CreateChar( CREID_TYPE id, SPELL_TYPE iSpell, bool fPet ) { // make a creature near by. (GM or script used only) // "ADDNPC" // spell = SPELL_Summon ASSERT(m_pChar); m_tmSkillMagery.m_Spell = iSpell; // m_atMagery.m_Spell m_tmSkillMagery.m_SummonID = id; // m_atMagery.m_SummonID m_tmSkillMagery.m_fSummonPet = fPet; if ( ! m_Targ_PrvUID.IsValidUID()) { m_Targ_PrvUID = m_pChar->GetUID(); // what id this was already a scroll. } const CSpellDef * pSpellDef = g_Cfg.GetSpellDef( iSpell ); ASSERT( pSpellDef ); return addTargetChars( CLIMODE_TARG_SKILL_MAGERY, id, pSpellDef->IsSpellType( SPELLFLAG_HARM )); } bool CClient::Cmd_Skill_Menu( RESOURCE_ID_BASE rid, int iSelect ) { // Build the skill menu for the curent active skill. // Only list the things we have skill and ingrediants to make. // // ARGS: // m_Targ_UID = the object used to get us here. // rid = which menu ? // iSelect = -2 = Just a test of the whole menu., // iSelect = -1 = 1st setup. // iSelect = 0 = cancel // iSelect = x = execute the selection. // // RETURN: false = fail/cancel the skill. // m_tmMenu.m_Item = the menu entries. ASSERT(m_pChar); if ( iSelect == 0 || rid.GetResType() != RES_SKILLMENU ) return( false ); int iDifficulty = 0; // Find section. CResourceLock s; if ( ! g_Cfg.ResourceLock( s, rid )) { return false; } // Get title line if ( ! s.ReadKey()) return( false ); CMenuItem item; if ( iSelect < 0 ) { item.m_sText = s.GetKey(); if ( iSelect == -1 ) { m_tmMenu.m_ResourceID = rid; } } bool fSkip = false; // skip this if we lack resources or skill. bool fSuccess = false; int iOnCount = 0; int iShowCount = 0; bool fShowMenu = false; // are we showing a menu? while ( s.ReadKeyParse()) { if ( s.IsKeyHead( "ON", 2 )) { // a new option to look at. fSkip = false; iOnCount ++; if ( iSelect < 0 ) // building up the list. { if ( iSelect < -1 && iShowCount >= 1 ) // just a test. so we are done. { return( true ); } iShowCount ++; if ( ! item.ParseLine( s.GetArgRaw(), NULL, m_pChar )) { // remove if the item is invalid. iShowCount --; fSkip = true; continue; } if ( iSelect == -1 ) { m_tmMenu.m_Item = iOnCount; } if ( iShowCount >= COUNTOF( item )-1 ) break; } else { if ( iOnCount > iSelect ) // we are done. break; } continue; } if ( fSkip ) // we have decided we cant do this option. continue; if ( iSelect > 0 && iOnCount != iSelect ) // only interested in the selected option continue; // Check for a skill / non-consumables required. if ( s.IsKey("TEST")) { CResourceQtyArray skills( s.GetArgStr()); if ( ! skills.IsResourceMatchAll(m_pChar)) { iShowCount--; fSkip = true; } continue; } if ( s.IsKey("TESTIF")) { m_pChar->ParseText( s.GetArgRaw(), m_pChar ); if ( ! s.GetArgVal()) { iShowCount--; fSkip = true; } continue; } // select to execute any entries here ? if ( iOnCount == iSelect ) { m_pChar->m_Act_Targ = m_Targ_UID; // Execute command from script TRIGRET_TYPE tRet = m_pChar->OnTriggerRun( s, TRIGRUN_SINGLE_EXEC, m_pChar ); if ( tRet == TRIGRET_RET_TRUE ) { return( false ); } fSuccess = true; // we are good. but continue til the end } else { ASSERT( iSelect < 0 ); if ( s.IsKey("SKILLMENU")) { // Test if there is anything in this skillmenu we can do. if ( ! Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, s.GetArgStr()), iSelect-1 )) { iShowCount--; fSkip = true; } else { fShowMenu = true; ASSERT( ! fSkip ); } continue; } if ( s.IsKey("MAKEITEM")) { // test if i can make this item using m_Targ_UID. // There should ALWAYS be a valid id here. if ( ! m_pChar->Skill_MakeItem( (ITEMID_TYPE) g_Cfg.ResourceGetIndexType( RES_ITEMDEF, s.GetArgS tr()), m_Targ_UID, SKTRIG_SELECT )) { iShowCount--; fSkip = true; } continue; } } } if ( iSelect < -1 ) // just a test. { return( iShowCount ? true : false ); } if ( iSelect > 0 ) // seems our resources disappeared. { if ( ! fSuccess ) { SysMessage( "You can't make that." ); } return( fSuccess ); } if ( ! iShowCount ) { SysMessage( "You can't make anything with what you have." ); return( false ); } if ( iShowCount == 1 && fShowMenu ) { // If there is just one menu then select it. return( Cmd_Skill_Menu( rid, m_tmMenu.m_Item )); } addItemMenu( CLIMODE_MENU_SKILL, item, iShowCount ); return( true ); } bool CClient::Cmd_Skill_Magery( SPELL_TYPE iSpell, CObjBase * pSrc ) { // start casting a spell. prompt for target. // pSrc = you the char. // pSrc = magic object is source ? static const TCHAR sm_Txt_Summon = "Where would you like to summon the creature ?"; // Do we have the regs ? etc. ASSERT(m_pChar); if ( ! m_pChar->Spell_CanCast( iSpell, true, pSrc, true )) return false; const CSpellDef * pSpellDef = g_Cfg.GetSpellDef( iSpell ); ASSERT(pSpellDef); if ( g_Log.IsLogged( LOGL_TRACE )) { DEBUG_MSG(( "%x:Cast Spell %d='%s'\n", m_Socket.GetSocket(), iSpell, pSpellDef->GetName())); } SetTargMode(); m_tmSkillMagery.m_Spell = iSpell; // m_atMagery.m_Spell m_Targ_UID = m_pChar->GetUID(); // default target. m_Targ_PrvUID = pSrc->GetUID(); // source of the spell. LPCTSTR pPrompt = "Select Target"; switch ( iSpell ) { case SPELL_Recall: pPrompt = "Select rune to recall from."; break; case SPELL_Blade_Spirit: pPrompt = sm_Txt_Summon; break; case SPELL_Summon: return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_summon" )); case SPELL_Mark: pPrompt = "Select rune to mark."; break; case SPELL_Gate_Travel: // gate travel pPrompt = "Select rune to gate from."; break; case SPELL_Polymorph: // polymorph creature menu. if ( IsPriv(PRIV_GM)) { pPrompt = "Select creature to polymorph."; break; } return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_polymorph" )); case SPELL_Earthquake: // cast immediately with no targetting. m_pChar->m_atMagery.m_Spell = SPELL_Earthquake; m_pChar->m_Act_Targ = m_Targ_UID; m_pChar->m_Act_TargPrv = m_Targ_PrvUID; m_pChar->m_Act_p = m_pChar->GetTopPoint(); return( m_pChar->Skill_Start( SKILL_MAGERY )); case SPELL_Resurrection: pPrompt = "Select ghost to resurrect."; break; case SPELL_Vortex: case SPELL_Air_Elem: case SPELL_Daemon: case SPELL_Earth_Elem: case SPELL_Fire_Elem: case SPELL_Water_Elem: pPrompt = sm_Txt_Summon; break; // Necro spells case SPELL_Summon_Undead: // Summon an undead pPrompt = sm_Txt_Summon; break; case SPELL_Animate_Dead: // Corpse to zombie pPrompt = "Choose a corpse"; break; case SPELL_Bone_Armor: // Skeleton corpse to bone armor pPrompt = "Chose a skeleton"; break; } addTarget( CLIMODE_TARG_SKILL_MAGERY, pPrompt, ! pSpellDef->IsSpellType( SPELLFLAG_TARG_OBJ | SPELLFLAG_TARG_CHAR ), pSpellDef->IsSpellType( SPELLFLAG_HARM )); return( true ); } bool CClient::Cmd_Skill_Tracking( int track_sel, bool fExec ) { // look around for stuff. ASSERT(m_pChar); if ( track_sel < 0 ) { // Initial pre-track setup. if ( m_pChar->m_pArea->IsFlag( REGION_FLAG_SHIP ) && ! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_SPY_GLASS)) ) { SysMessage( "You need a Spyglass to use tracking here." ); return( false ); } // Tacking (unlike other skills) is used during menu setup. m_pChar->Skill_Fail( true ); // Kill previous skill. CMenuItem item; item.m_sText = "Tracking"; item.m_id = ITEMID_TRACK_HORSE; item.m_sText = "Animals"; item.m_id = ITEMID_TRACK_OGRE; item.m_sText = "Monsters"; item.m_id = ITEMID_TRACK_MAN; item.m_sText = "Humans"; item.m_id = ITEMID_TRACK_MAN_NAKED; item.m_sText = "Players"; item.m_id = ITEMID_TRACK_WISP; item.m_sText = "Anything that moves"; m_tmMenu.m_Item = 0; addItemMenu( CLIMODE_MENU_SKILL_TRACK_SETUP, item, 5 ); return( true ); } if ( track_sel ) // Not Cancelled { ASSERT( ((WORD)track_sel) < COUNTOF( m_tmMenu.m_Item )); if ( fExec ) { // Tracking menu got us here. Start tracking the selected creature. m_pChar->SetTimeout( 1*TICK_PER_SEC ); m_pChar->m_Act_Targ = m_tmMenu.m_Item; // selected UID m_pChar->Skill_Start( SKILL_TRACKING ); return true; } bool fGM = IsPriv(PRIV_GM); static const NPCBRAIN_TYPE sm_Track_Brain = { NPCBRAIN_QTY, // not used here. NPCBRAIN_ANIMAL, NPCBRAIN_MONSTER, NPCBRAIN_HUMAN, NPCBRAIN_NONE, // players NPCBRAIN_QTY, // anything. }; if ( track_sel >= COUNTOF(sm_Track_Brain)) track_sel = COUNTOF(sm_Track_Brain)-1; NPCBRAIN_TYPE track_type = sm_Track_Brain; CMenuItem item; int count = 0; item.m_sText = "Tracking"; m_tmMenu.m_Item = track_sel; CWorldSearch AreaChars( m_pChar->GetTopPoint(), m_pChar->Skill_GetBase(SKILL_TRACKING)/20 + 10 ); while (true) { CChar * pChar = AreaChars.GetChar(); if ( pChar == NULL ) break; if ( m_pChar == pChar ) continue; if ( ! m_pChar->CanDisturb( pChar )) continue; CCharBase * pCharDef = pChar->Char_GetDef(); NPCBRAIN_TYPE basic_type = pChar->GetCreatureType(); if ( track_type != basic_type && track_type != NPCBRAIN_QTY ) { if ( track_type != NPCBRAIN_NONE ) // no match. { continue; } // players if ( ! pChar->m_pPlayer ) continue; if ( ! fGM && basic_type != NPCBRAIN_HUMAN ) // can't track polymorphed person. continue; } if ( ! fGM && ! pCharDef->Can( CAN_C_WALK )) // never moves or just swims. continue; count ++; item.m_id = pCharDef->m_trackID; item.m_sText = pChar->GetName(); m_tmMenu.m_Item = pChar->GetUID(); if ( count >= COUNTOF( item )-1 ) break; } if ( count ) { // Some credit for trying. m_pChar->Skill_UseQuick( SKILL_TRACKING, 20 + Calc_GetRandVal( 30 )); addItemMenu( CLIMODE_MENU_SKILL_TRACK, item, count ); return( true ); } else { // Some credit for trying. m_pChar->Skill_UseQuick( SKILL_TRACKING, 10 + Calc_GetRandVal( 30 )); } } // Tracking failed or was cancelled . static LPCTSTR const sm_Track_FailMsg = { "Tracking Cancelled", "You see no signs of animals to track.", "You see no signs of monsters to track.", "You see no signs of humans to track.", "You see no signs of players to track.", "You see no signs to track." }; SysMessage( sm_Track_FailMsg ); return( false ); } bool CClient::Cmd_Skill_Smith( CItem * pIngots ) { ASSERT(m_pChar); if ( pIngots == NULL || ! pIngots->IsType(IT_INGOT)) { SysMessage( "You need ingots for smithing." ); return( false ); } ASSERT( m_Targ_UID == pIngots->GetUID()); if ( pIngots->GetTopLevelObj() != m_pChar ) { SysMessage( "The ingots must be on your person" ); return( false ); } // must have hammer equipped. CItem * pHammer = m_pChar->LayerFind( LAYER_HAND1 ); if ( pHammer == NULL || ! pHammer->IsType(IT_WEAPON_MACE_SMITH)) { SysMessage( "You must weild a smith hammer of some sort." ); return( false ); } // Select the blacksmith item type. // repair items or make type of items. if ( ! g_World.IsItemTypeNear( m_pChar->GetTopPoint(), IT_FORGE, 3 )) { SysMessage( "You must be near a forge to smith ingots" ); return( false ); } // Select the blacksmith item type. // repair items or make type of items. return( Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU,"sm_blacksmith" ))); } bool CClient::Cmd_Skill_Inscription() { // Select the scroll type to make. // iSelect = -1 = 1st setup. // iSelect = 0 = cancel // iSelect = x = execute the selection. // we should already be in inscription skill mode. ASSERT(m_pChar); CItem * pBlank = m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_SCROLL_BLANK)); if ( pBlank == NULL ) { SysMessage( "You have no blank scrolls" ); return( false ); } return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_inscription" ) ); } bool CClient::Cmd_Skill_Alchemy( CItem * pReag ) { // SKILL_ALCHEMY if ( pReag == NULL ) return( false ); ASSERT(m_pChar); if ( ! m_pChar->CanUse( pReag, true )) return( false ); if ( ! pReag->IsType(IT_REAGENT)) { // That is not a reagent. SysMessage( "That is not a reagent." ); return( false ); } // Find bottles to put potions in. if ( ! m_pChar->ContentFind(RESOURCE_ID(RES_TYPEDEF,IT_POTION_EMPTY))) { SysMessage( "You have no bottles for your potion." ); return( false ); } m_Targ_UID = pReag->GetUID(); // Put up a menu to decide formula ? return Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_alchemy" )); } bool CClient::Cmd_Skill_Cartography( int iLevel ) { // select the map type. ASSERT(m_pChar); if ( m_pChar->Skill_Wait(SKILL_CARTOGRAPHY)) return( false ); if ( ! m_pChar->ContentFind( RESOURCE_ID(RES_TYPEDEF,IT_MAP_BLANK))) { SysMessage( "You have no blank parchment to draw on" ); return( false ); } return( Cmd_Skill_Menu( g_Cfg.ResourceGetIDType( RES_SKILLMENU, "sm_cartography" ))); } bool CClient::Cmd_SecureTrade( CChar * pChar, CItem * pItem ) { // Begin secure trading with a char. (Make the initial offer) ASSERT(m_pChar); // Trade window only if another PC. if ( ! pChar->IsClient()) { return( pChar->NPC_OnItemGive( m_pChar, pItem )); } // Is there already a trade window open for this client ? CItem * pItemCont = m_pChar->GetContentHead(); for ( ; pItemCont != NULL; pItemCont = pItemCont->GetNext()) { if ( ! pItemCont->IsType(IT_EQ_TRADE_WINDOW)) continue; // found it CItem * pItemPartner = pItemCont->m_uidLink.ItemFind(); // counterpart trade window. if ( pItemPartner == NULL ) continue; CChar * pCharPartner = dynamic_cast <CChar*>( pItemPartner->GetParent()); if ( pCharPartner != pChar ) continue; CItemContainer * pCont = dynamic_cast <CItemContainer *>( pItemCont ); ASSERT(pCont); pCont->ContentAdd( pItem ); return( true ); } // Open a new one. CItemContainer* pCont1 = dynamic_cast <CItemContainer*> (CItem::CreateBase( ITEMID_Bulletin1 )); ASSERT(pCont1); pCont1->SetType( IT_EQ_TRADE_WINDOW ); CItemContainer* pCont2 = dynamic_cast <CItemContainer*> (CItem::CreateBase( ITEMID_Bulletin1 )); ASSERT(pCont2); pCont2->SetType( IT_EQ_TRADE_WINDOW ); pCont1->m_itEqTradeWindow.m_fCheck = false; pCont1->m_uidLink = pCont2->GetUID(); pCont2->m_itEqTradeWindow.m_fCheck = false; pCont2->m_uidLink = pCont1->GetUID(); m_pChar->LayerAdd( pCont1, LAYER_SPECIAL ); pChar->LayerAdd( pCont2, LAYER_SPECIAL ); CCommand cmd; int len = sizeof(cmd.SecureTrade); cmd.SecureTrade.m_Cmd = XCMD_SecureTrade; cmd.SecureTrade.m_len = len; cmd.SecureTrade.m_action = SECURE_TRADE_OPEN; // init cmd.SecureTrade.m_UID = pChar->GetUID(); cmd.SecureTrade.m_UID1 = pCont1->GetUID(); cmd.SecureTrade.m_UID2 = pCont2->GetUID(); cmd.SecureTrade.m_fname = 1; strcpy( cmd.SecureTrade.m_charname, pChar->GetName()); xSendPkt( &cmd, len ); cmd.SecureTrade.m_UID = m_pChar->GetUID(); cmd.SecureTrade.m_UID1 = pCont2->GetUID(); cmd.SecureTrade.m_UID2 = pCont1->GetUID(); strcpy( cmd.SecureTrade.m_charname, m_pChar->GetName()); pChar->GetClient()->xSendPkt( &cmd, len ); CPointMap pt( 30, 30, 9 ); pCont1->ContentAdd( pItem, pt ); return( true ); }
43,621
12,711
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Viacheslav G. Rybalov */ #include <string.h> #include "ArrayType.h" #include "PacketParser.h" #include "ClassManager.h" using namespace jdwp; using namespace ArrayType; void ArrayType::NewInstanceHandler::Execute(JNIEnv *jni) throw(AgentException) { jclass cls = m_cmdParser->command.ReadReferenceTypeID(jni); jint length = m_cmdParser->command.ReadInt(); JDWP_ASSERT(cls != 0); char* signature = 0; jvmtiError err; JVMTI_TRACE(err, GetJvmtiEnv()->GetClassSignature(cls, &signature, 0)); JvmtiAutoFree afv1(signature); if (err != JVMTI_ERROR_NONE) { throw AgentException(err); } JDWP_TRACE_DATA("NewInstance: received: refTypeID=" << cls << ", length=" << length << ", signature=" << JDWP_CHECK_NULL(signature)); if ((signature == 0) || (strlen(signature) < 2)) { throw AgentException(JDWP_ERROR_INVALID_OBJECT); } if(signature[0] != '[') { throw AgentException(JDWP_ERROR_INVALID_ARRAY); } jarray arr = 0; switch (signature[1]) { case 'Z': { JDWP_TRACE_DATA("NewInstance: new boolean array"); arr = jni->NewBooleanArray(length); break; } case 'B': { JDWP_TRACE_DATA("NewInstance: new byte array"); arr = jni->NewByteArray(length); break; } case 'C': { JDWP_TRACE_DATA("NewInstance: new char array"); arr = jni->NewCharArray(length); break; } case 'S': { JDWP_TRACE_DATA("NewInstance: new short array"); arr = jni->NewShortArray(length); break; } case 'I': { JDWP_TRACE_DATA("NewInstance: new int array"); arr = jni->NewIntArray(length); break; } case 'J': { JDWP_TRACE_DATA("NewInstance: new long array"); arr = jni->NewLongArray(length); break; } case 'F': { arr = jni->NewFloatArray(length); JDWP_TRACE_DATA("NewInstance: new float array"); break; } case 'D': { JDWP_TRACE_DATA("NewInstance: new double array"); arr = jni->NewDoubleArray(length); break; } case 'L': case '[': { char* name = GetClassManager().GetClassName(&signature[1]); JvmtiAutoFree jafn(name); jobject loader; JVMTI_TRACE(err, GetJvmtiEnv()->GetClassLoader(cls, &loader)); if (err != JVMTI_ERROR_NONE) { throw AgentException(err); } jclass elementClass = GetClassManager().GetClassForName(jni, name, loader); JDWP_TRACE_DATA("NewInstance: new object array: " "class=" << JDWP_CHECK_NULL(name)); arr = jni->NewObjectArray(length, elementClass, 0); break; } default: JDWP_TRACE_DATA("NewInstance: bad type signature: " << JDWP_CHECK_NULL(signature)); throw AgentException(JDWP_ERROR_INVALID_ARRAY); } GetClassManager().CheckOnException(jni); if (arr == 0) { throw AgentException(JDWP_ERROR_OUT_OF_MEMORY); } JDWP_TRACE_DATA("NewInstance: send: tag=" << JDWP_TAG_ARRAY << ", newArray=" << arr); m_cmdParser->reply.WriteByte(JDWP_TAG_ARRAY); m_cmdParser->reply.WriteArrayID(jni, arr); }
4,302
1,336
#include "logger.h" //Mutex for cout //Prevent interleaving of output pthread_mutex_t coutMutex = PTHREAD_MUTEX_INITIALIZER;
131
55
/*****************************************************************************/ // Copyright 2006 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in // accordance with the terms of the Adobe license agreement accompanying it. /*****************************************************************************/ /* $Id: //mondo/dng_sdk_1_4/dng_sdk/source/dng_memory.cpp#1 $ */ /* $DateTime: 2012/05/30 13:28:51 $ */ /* $Change: 832332 $ */ /* $Author: tknoll $ */ /*****************************************************************************/ #include "dng_memory.h" #include "dng_bottlenecks.h" #include "dng_exceptions.h" /*****************************************************************************/ dng_memory_data::dng_memory_data () : fBuffer (NULL) { } /*****************************************************************************/ dng_memory_data::dng_memory_data (uint32 size) : fBuffer (NULL) { Allocate (size); } /*****************************************************************************/ dng_memory_data::~dng_memory_data () { Clear (); } /*****************************************************************************/ void dng_memory_data::Allocate (uint32 size) { Clear (); if (size) { fBuffer = (char*)malloc (size); if (!fBuffer) { ThrowMemoryFull (); } } } /*****************************************************************************/ void dng_memory_data::Clear () { if (fBuffer) { free (fBuffer); fBuffer = NULL; } } /*****************************************************************************/ dng_memory_block * dng_memory_block::Clone (dng_memory_allocator &allocator) const { uint32 size = LogicalSize (); dng_memory_block * result = allocator.Allocate (size); DoCopyBytes (Buffer (), result->Buffer (), size); return result; } /*****************************************************************************/ class dng_malloc_block : public dng_memory_block { private: void *fMalloc; public: dng_malloc_block (uint32 logicalSize); virtual ~dng_malloc_block (); private: // Hidden copy constructor and assignment operator. dng_malloc_block (const dng_malloc_block &block); dng_malloc_block & operator= (const dng_malloc_block &block); }; /*****************************************************************************/ dng_malloc_block::dng_malloc_block (uint32 logicalSize) : dng_memory_block (logicalSize) , fMalloc (NULL) { #if qLinux int err = ::posix_memalign( (void **) &fMalloc, 16, (size_t) PhysicalSize() ); if (err) { ThrowMemoryFull (); } #else fMalloc = (char*)malloc (PhysicalSize ()); if (!fMalloc) { ThrowMemoryFull (); } #endif SetBuffer (fMalloc); } /*****************************************************************************/ dng_malloc_block::~dng_malloc_block () { if (fMalloc) { free (fMalloc); } } /*****************************************************************************/ dng_memory_block * dng_memory_allocator::Allocate (uint32 size) { dng_memory_block *result = new dng_malloc_block (size); if (!result) { ThrowMemoryFull (); } return result; } /*****************************************************************************/ dng_memory_allocator gDefaultDNGMemoryAllocator; /*****************************************************************************/
3,793
1,397
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/foas/model/CommitJobRequest.h> using AlibabaCloud::Foas::Model::CommitJobRequest; CommitJobRequest::CommitJobRequest() : RoaServiceRequest("foas", "2018-11-11") { setResourcePath("/api/v2/projects/[projectName]/jobs/[jobName]/commit"); setMethod(HttpRequest::Method::Put); } CommitJobRequest::~CommitJobRequest() {} std::string CommitJobRequest::getProjectName()const { return projectName_; } void CommitJobRequest::setProjectName(const std::string& projectName) { projectName_ = projectName; setParameter("ProjectName", projectName); } std::string CommitJobRequest::getRegionId()const { return regionId_; } void CommitJobRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setHeader("RegionId", regionId); } float CommitJobRequest::getMaxCU()const { return maxCU_; } void CommitJobRequest::setMaxCU(float maxCU) { maxCU_ = maxCU; setBodyParameter("MaxCU", std::to_string(maxCU)); } std::string CommitJobRequest::getConfigure()const { return configure_; } void CommitJobRequest::setConfigure(const std::string& configure) { configure_ = configure; setBodyParameter("Configure", configure); } bool CommitJobRequest::getIsOnOff()const { return isOnOff_; } void CommitJobRequest::setIsOnOff(bool isOnOff) { isOnOff_ = isOnOff; setBodyParameter("IsOnOff", isOnOff ? "true" : "false"); } std::string CommitJobRequest::getJobName()const { return jobName_; } void CommitJobRequest::setJobName(const std::string& jobName) { jobName_ = jobName; setParameter("JobName", jobName); }
2,251
774
/*++ Copyright (c) Microsoft Corporation Module Name: FxPkgPdoUM.cpp Abstract: This module implements the Pnp package for Pdo devices. Author: Environment: User mode only Revision History: --*/ #include "pnppriv.hpp" #include <wdmguid.h> // Tracing support #if defined(EVENT_TRACING) extern "C" { #include "FxPkgPdoUM.tmh" } #endif _Must_inspect_result_ NTSTATUS FxPkgPdo::_PnpQueryResources( __inout FxPkgPnp* This, __inout FxIrp *Irp ) { return ((FxPkgPdo*) This)->PnpQueryResources(Irp); } _Must_inspect_result_ NTSTATUS FxPkgPdo::PnpQueryResources( __inout FxIrp *Irp ) /*++ Routine Description: This method is invoked in response to a Pnp QueryResources IRP. We return the resources that the device is currently consuming. Arguments: Irp - a pointer to the FxIrp Returns: NTSTATUS --*/ { UNREFERENCED_PARAMETER(Irp); ASSERTMSG("Not implemented for UMDF\n", FALSE); return STATUS_NOT_IMPLEMENTED; } _Must_inspect_result_ NTSTATUS FxPkgPdo::_PnpQueryResourceRequirements( __inout FxPkgPnp* This, __inout FxIrp *Irp ) { return ((FxPkgPdo*) This)->PnpQueryResourceRequirements(Irp); } _Must_inspect_result_ NTSTATUS FxPkgPdo::PnpQueryResourceRequirements( __inout FxIrp *Irp ) /*++ Routine Description: This method is invoked in response to a Pnp QueryResourceRequirements IRP. We return the set (of sets) of possible resources that we could accept which would allow our device to work. Arguments: Irp - a pointer to the FxIrp Returns: NTSTATUS --*/ { UNREFERENCED_PARAMETER(Irp); ASSERTMSG("Not implemented for UMDF\n", FALSE); return STATUS_NOT_IMPLEMENTED; } _Must_inspect_result_ NTSTATUS FxPkgPdo::_PnpFilterResourceRequirements( __inout FxPkgPnp* This, __inout FxIrp *Irp ) /*++ Routine Description: Filter resource requirements for the PDO. A chance to further muck with the resources assigned to the device. Arguments: This - the package Irp - the request Return Value: NTSTATUS --*/ { UNREFERENCED_PARAMETER(This); UNREFERENCED_PARAMETER(Irp); ASSERTMSG("Not implemented for UMDF\n", FALSE); return STATUS_NOT_IMPLEMENTED; }
2,269
880
// ******************************************************************************************************************************* // ******************************************************************************************************************************* // // Name: sys_processor.cpp // Purpose: Processor Emulation. // Created: 26th October 2015 // Author: Paul Robson (paul@robsons.org.uk) // // ******************************************************************************************************************************* // ******************************************************************************************************************************* #ifdef WINDOWS #include <stdio.h> #endif #ifdef ARDUINO #include <avr/pgmspace.h> #endif #include "sys_processor.h" // ******************************************************************************************************************************* // Main Memory/CPU // ******************************************************************************************************************************* static BYTE8 A,B,C,D,E,H,L,pszValue,carry,HaltFlag; static BYTE8 interruptEnabled,MB,PCIX,interruptRequest; static WORD16 temp16,MA,PCR[8],Cycles; static BYTE8 ramMemory[RAMSIZE]; // RAM memory // ******************************************************************************************************************************* // Memory read and write macros. // ******************************************************************************************************************************* #define READ() if (MA < RAMSIZE) MB = ramMemory[MA] #define WRITE() if (MA < RAMSIZE) ramMemory[MA] = MB // ******************************************************************************************************************************* // I/O Port connections // ******************************************************************************************************************************* #define INPORT00() { if (A & 0x02) interruptEnabled = A & 0x01;MB = 0x1; } // Port 00 : if bit 1 set enable int, return 1 #define INPORT01() MB = HWIReadKeyboard() // Port 01 : Keyboard in. #define OUTPORT08() HWIWriteDisplay(MB) // Port 08 : Video Display // ******************************************************************************************************************************* // Support Macros and Functions // ******************************************************************************************************************************* #define CYCLES(n) Cycles += (n) #define FETCH() { MA = PCTR;READ();PCTR = (PCTR + 1) & 07777; } #define FETCHWORD() { MA = PCTR;READ();temp16 = MB;MA++;READ();MA = (MB << 8) | temp16; PCTR = (PCTR + 2) & 07777; } #define JUMP() PCTR = MA & 0x3FFF #define CALL() { PCIX = (PCIX + 1) & 7;PCTR = MA & 0x3FFF; } #define RETURN() PCIX = (PCIX - 1) & 7; static void _BinaryAdd(void) { temp16 = A + MB + carry; // Calc result carry = temp16 >> 8; // Get new carry MB = temp16 & 0xFF; // Result in MB } static void _BinarySubtract(void){ temp16 = A - MB - carry; // Calc result carry = (temp16 >> 8) & 1; // Get new borrow MB = temp16 & 0xFF; // Result in MB } static BYTE8 _IsParityEven(BYTE8 n) { BYTE8 isEven = -1; // 0 is even parity while (n != 0) { // until all bits test if (n & 1) isEven = !isEven; // each set bit toggles it n = n >> 1; } return isEven; } // ******************************************************************************************************************************* // Built in image // ******************************************************************************************************************************* #ifdef WINDOWS static const BYTE8 __image[] = { #include "__binary.h" }; #endif #ifdef ARDUINO static const PROGMEM uint16_t __image[] = { #include "__binary.h" }; #endif #include "__binary_size.h" static BYTE8 isCLILoad = 0; // ******************************************************************************************************************************* // Port interfaces // ******************************************************************************************************************************* void CPUReset(void) { A = B = C = D = E = H = L = pszValue = carry = HaltFlag = 0; PCIX = 0;PCR[PCIX] = 0;Cycles = 0;interruptRequest = 0;interruptEnabled = 0; HWIReset(); if (isCLILoad == 0) { isCLILoad = 1; for (WORD16 n = 0;n < BINARY_SIZE;n++) { #ifdef WINDOWS ramMemory[n] = __image[n]; #endif #ifdef ARDUINO ramMemory[n] = pgm_read_byte_far(__image+n); #endif } } } // ******************************************************************************************************************************* // Request an interrupt // ******************************************************************************************************************************* #include <stdio.h> void CPUInterruptRequest(void) { interruptRequest = 1; } // ******************************************************************************************************************************* // Execute a single phase. // ******************************************************************************************************************************* #include "__8008_ports.h" // Hoover up any undefined ports. BYTE8 CPUExecuteInstruction(void) { if (interruptRequest != 0) { // Interrupted. interruptRequest = 0; // Clear IRQ flag if (interruptEnabled != 0) { // Is interrupt enabled. HaltFlag = 0; // Clear Halt flag. MA = 0;CALL(); // Do a RST 0. return 0; } } if (HaltFlag == 0) { // CPU is running (not halt) FETCH(); // Fetch and execute switch(MB) { // Do the selected opcode and phase. #include "__8008_opcodes.h" } } if (HaltFlag == 0 && Cycles < CYCLES_PER_FRAME) return 0; // Frame in progress, return 0. if (HaltFlag != 0) Cycles = 0; // Fix up for HALT. Cycles -= CYCLES_PER_FRAME; // Adjust cycle counter HWIEndFrame(); // Hardware stuff. return FRAME_RATE; // Return the frame rate for sync speed. } #ifdef INCLUDE_DEBUGGING_SUPPORT // ******************************************************************************************************************************* // Get the step over breakpoint value // ******************************************************************************************************************************* WORD16 CPUGetStepOverBreakpoint(void) { BYTE8 opcode = CPURead(PCTR); // Read opcode. if ((opcode & 0xC7) == 0x07) return ((PCTR+1) & 0x3FFF); // RST xx if ((opcode & 0xC3) == 0x42) return ((PCTR+3) & 0x3FFF); // CALL xxxx (various calls) return 0xFFFF; } // ******************************************************************************************************************************* // Run continuously till breakpoints / Halt. // ******************************************************************************************************************************* BYTE8 CPUExecute(WORD16 break1,WORD16 break2) { BYTE8 rate = 0; while(1) { rate = CPUExecuteInstruction(); // Execute one instruction phase. if (rate != 0) { // If end of frame, return rate. return rate; } if (PCTR == break1 || PCTR == break2) return 0; } // Until hit a breakpoint or HLT. } // ******************************************************************************************************************************* // Load a binary file into RAM // ******************************************************************************************************************************* void CPULoadBinary(char *fileName) { FILE *f = fopen(fileName,"rb"); fread(ramMemory,RAMSIZE,1,f); fclose(f); isCLILoad = 1; // stop reset loading memory } // ******************************************************************************************************************************* // Gets a pointer to RAM memory // ******************************************************************************************************************************* BYTE8 CPURead(WORD16 address) { WORD16 _MA = MA;BYTE8 _MB = MB;BYTE8 result; MA = address;READ();result = MB; MA = _MA;MB = _MB; return result; } // ******************************************************************************************************************************* // Retrieve a snapshot of the processor // ******************************************************************************************************************************* static CPUSTATUS s; // Status area CPUSTATUS *CPUGetStatus(void) { int i; s.a = A;s.b = B;s.c = C;s.d = D;s.e = E;s.h = H;s.l = L; // 8 bit registers s.zFlag = (pszValue == 0);s.cFlag = (carry != 0);s.hFlag = (HaltFlag != 0); // Flags s.pFlag = (_IsParityEven(pszValue) != 0);s.sFlag = ((pszValue & 0x80) != 0); s.interruptEnabled = interruptEnabled; s.cycles = Cycles; // Number of cycles. for (i = 0;i < 8;i++) s.stack[i] = 0; // Clear stack. s.pc = PCTR; // Save PC. i = PCIX-1;s.stackDepth = 0; // Copy stack. while (i >= 0) s.stack[s.stackDepth++] = PCR[i--]; s.hl = (s.h << 8) | s.l;s.m = CPURead(s.hl & 0x3FFF); // Helpers return &s; } #endif
9,821
3,461
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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. ********************************************************************************/ #ifndef RWSIM_UTIL_TARGETCONFIGGRASPPOLICY_HPP_ #define RWSIM_UTIL_TARGETCONFIGGRASPPOLICY_HPP_ #include "GraspPolicy.hpp" #include <rw/core/PropertyMap.hpp> #include <rw/core/Ptr.hpp> #include <rwlibs/simulation/SimulatedController.hpp> namespace rwsim { namespace dynamics { class DynamicDevice; }} // namespace rwsim::dynamics namespace rwsim { namespace util { /** * @brief This grasp policy will close the fingers of a device to a * randomly choosen target position which is generated either from a * predefined set of target configurations or from one of the * selected hueristics. */ class TargetConfigGraspPolicy : public GraspPolicy { public: typedef rw::core::Ptr< TargetConfigGraspPolicy > Ptr; /** * @brief constructor * @param dev * @return */ TargetConfigGraspPolicy (rwsim::dynamics::DynamicDevice* dev); virtual ~TargetConfigGraspPolicy (); void setDefaultSettings (); static std::string getID () { return "TargetConfigGraspPolicy"; }; // inherited from GraspPolicy virtual void reset (const rw::kinematics::State& state); virtual rwlibs::simulation::SimulatedController::Ptr getController (); virtual std::string getIdentifier () { return TargetConfigGraspPolicy::getID (); } virtual rw::core::PropertyMap getSettings () { return _settings; }; virtual void applySettings (); private: rw::core::PropertyMap _settings; rwsim::dynamics::DynamicDevice* _dev; rwlibs::simulation::SimulatedController::Ptr _controller; }; }} // namespace rwsim::util #endif /* GRASPPOLICY_HPP_ */
2,587
718
#include "UI/UISprite.h" #include "TextureFileManager.h" #include "Texture.h" #include "AlphaMask.h" //IMPLEMENT_AND_REGISTER_CLASS_INFO(UISprite, UISprite, 2DLayers); IMPLEMENT_CLASS_INFO(UISprite) UISprite::UISprite(const kstl::string& name, CLASS_NAME_TREE_ARG) : UITexturedItem(name, PASS_CLASS_NAME_TREE_ARG) , mTexture(*this, false, LABEL_AND_ID(Texture), "") , mSprite(*this, false, LABEL_AND_ID(Sprite), "") { mSpriteSheet = 0; mHasSprite = false; } UISprite::~UISprite() { } //----------------------------------------------------------------------------------------------------- //ReloadTexture void UISprite::NotifyUpdate(const unsigned int labelid) { if (labelid == mIsEnabled.getLabelID()) { if (!GetSons().empty()) { kstl::set<Node2D*, Node2D::PriorityCompare> sons = GetSons(); kstl::set<Node2D*, Node2D::PriorityCompare>::iterator it = sons.begin(); kstl::set<Node2D*, Node2D::PriorityCompare>::iterator end = sons.end(); while (it != end) { (*it)->setValue(LABEL_TO_ID(IsEnabled), mIsEnabled); it++; } } } else if (labelid == mTexture.getLabelID() && _isInit) { ChangeTexture(); } else if (labelid == mSprite.getLabelID() && _isInit) { ChangeTexture(); } UITexturedItem::NotifyUpdate(labelid); } void UISprite::InitModifiable() { if (_isInit) return; UITexturedItem::InitModifiable(); if (_isInit) { ChangeTexture(); mIsEnabled.changeNotificationLevel(Owner); mTexture.changeNotificationLevel(Owner); mSprite.changeNotificationLevel(Owner); } } void UISprite::ChangeTexture() { mHasSprite = false; const kstl::string& lTexName = mTexture.const_ref(); if (lTexName == "") return; auto& textureManager = KigsCore::Singleton<TextureFileManager>(); mSpriteSheet = textureManager->GetSpriteSheetTexture(lTexName); SetTexture(mSpriteSheet->Get_Texture()); if (!mTexturePointer) return; mTexturePointer->Init(); const SpriteSheetFrame * f = mSpriteSheet->Get_Frame(mSprite); if (f == nullptr) return; mHasSprite = true; Point2D s, r; mTexturePointer->GetSize(s.x, s.y); mTexturePointer->GetRatio(r.x, r.y); s /= r; mUVMin.Set((kfloat)f->FramePos_X+0.5f, (kfloat)f->FramePos_Y+0.5f); mUVMin /= s; mUVMax.Set((kfloat)(f->FramePos_X+f->FrameSize_X-0.5f), (kfloat)(f->FramePos_Y+f->FrameSize_Y-0.5f)); mUVMax /= s; //mUVMax = mUVMin + mUVMax; // auto size if ((((unsigned int)mSizeX) == 0) && (((unsigned int)mSizeY) == 0)) { mSizeX = f->FrameSize_X; mSizeY = f->FrameSize_Y; } } bool UISprite::isAlpha(float X, float Y) { //Try to get mask if (!mAlphaMask) { kstl::vector<ModifiableItemStruct> sons = getItems(); for (unsigned int i = 0; i < sons.size(); i++) { if (sons[i].mItem->isSubType("AlphaMask")) { mAlphaMask = sons[i].mItem; break; } } } if (mAlphaMask) { return !mAlphaMask->CheckTo(X, Y); } return false; } void UISprite::SetTexUV(UIVerticesInfo * aQI) { if (mHasSprite) { kfloat ratioX, ratioY, sx, sy; mTexturePointer->GetSize(sx, sy); mTexturePointer->GetRatio(ratioX, ratioY); kfloat dx = 0.5f / sx; kfloat dy = 0.5f / sy; VInfo2D::Data* buf = reinterpret_cast<VInfo2D::Data*>(aQI->Buffer()); aQI->Flag |= UIVerticesInfo_Texture; // triangle strip order buf[0].setTexUV(mUVMin.x + dx, mUVMin.y + dy); buf[1].setTexUV(mUVMin.x + dx, mUVMax.y - dy); buf[3].setTexUV(mUVMax.x - dx, mUVMax.y - dy); buf[2].setTexUV(mUVMax.x - dx, mUVMin.y + dy); } }
3,458
1,565
#include <iostream> using namespace std; int main() { string s; cout << "Other Successfully initiated." << endl; while (cin >> s) cout << "Success " << s << endl; }
185
58
#include <stdio.h> #include <stdlib.h> #include <time.h> int getRandomNum( void ); void correctAnswer(); void wrongAnswer(); int answerTheQuestion( int, int ); void askQuestions( int ); int main() { srand( (time(NULL)) ); askQuestions(10); return 0; } int getRandomNum() { int res = 1 + rand()%12; return res; } void correctAnswer() { int response = getRandomNum(); switch(response) { case 1: case 2: case 3: printf("Very good!\n"); break; case 4: case 5: case 6: printf("Excellent!\n"); break; case 7: case 8: case 9: printf("Nice Work!\n"); break; case 10: case 11: case 12: printf("Keep up the good work!\n"); break; default: printf("Congrats!\n"); } } void wrongAnswer() { int response = getRandomNum(); switch(response) { case 1: case 2: case 3: printf("No. Please try again!\n"); break; case 4: case 5: case 6: printf("Wrong. Try once more!\n"); break; case 7: case 8: case 9: printf("Don't give up!\n"); break; case 10: case 11: case 12: printf("No. Keep trying!\n"); break; default: printf("So wrong, dude!\n"); } } int answerTheQuestion(int a, int b) { int guess; int wrongGuesses = 0; int correct=0; int result = a*b; do { printf("What is %d x %d? ",a, b); scanf("%d", &guess); if(guess==result) { correct = 1; correctAnswer(); } else { wrongAnswer(); wrongGuesses++; } } while(!correct); return wrongGuesses; } void askQuestions(int n) { int i, a, b; int wrong=0; for(i=0; i<n; i++) { a = getRandomNum(); b = getRandomNum(); wrong += answerTheQuestion(a, b); } float percentage = (10.0/(10.0 + wrong)) * 100.0; if(percentage < 75.0) { printf("\nOnly %.2f%% of your guesses were correct\n", percentage); printf("Please ask your instructor for extra help\n"); } else { printf("\nCongratulations %.2f%% of your guesses were correct\n", percentage); } }
2,489
842
/* * AutoPublicAddress.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project authors * * 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 "flow/Platform.h" #include <algorithm> #define BOOST_SYSTEM_NO_LIB #define BOOST_DATE_TIME_NO_LIB #define BOOST_REGEX_NO_LIB #include "boost/asio.hpp" #include "fdbclient/CoordinationInterface.h" // Determine public IP address by calling the first coordinator. IPAddress determinePublicIPAutomatically(ClusterConnectionString& ccs) { try { using namespace boost::asio; io_service ioService; ip::udp::socket socket(ioService); ccs.resolveHostnamesBlocking(); const auto& coordAddr = ccs.coordinators()[0]; const auto boostIp = coordAddr.ip.isV6() ? ip::address(ip::address_v6(coordAddr.ip.toV6())) : ip::address(ip::address_v4(coordAddr.ip.toV4())); ip::udp::endpoint endpoint(boostIp, coordAddr.port); socket.connect(endpoint); IPAddress ip = coordAddr.ip.isV6() ? IPAddress(socket.local_endpoint().address().to_v6().to_bytes()) : IPAddress(socket.local_endpoint().address().to_v4().to_ulong()); socket.close(); return ip; } catch (boost::system::system_error e) { fprintf(stderr, "Error determining public address: %s\n", e.what()); throw bind_failed(); } }
1,920
635
/* ************************************************************************ * Copyright 2016-2019 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "handle.h" #include "logging.h" #include "rocblas.h" #include "utility.h" template <typename T, typename U, typename V> __global__ void copy_kernel(rocblas_int n, const U xa, ptrdiff_t shiftx, rocblas_int incx, rocblas_stride stridex, V ya, ptrdiff_t shifty, rocblas_int incy, rocblas_stride stridey) { ptrdiff_t tid = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; // bound if(tid < n) { const T* x = load_ptr_batch(xa, hipBlockIdx_y, shiftx, stridex); T* y = load_ptr_batch(ya, hipBlockIdx_y, shifty, stridey); y[tid * incy] = x[tid * incx]; } } template <rocblas_int NB, typename T, typename U, typename V> rocblas_status rocblas_copy_template(rocblas_handle handle, rocblas_int n, U x, rocblas_int offsetx, rocblas_int incx, rocblas_stride stridex, V y, rocblas_int offsety, rocblas_int incy, rocblas_stride stridey, rocblas_int batch_count) { // Quick return if possible. if(n <= 0 || !batch_count) return rocblas_status_success; if(!x || !y) return rocblas_status_invalid_pointer; if(batch_count < 0) return rocblas_status_invalid_size; // in case of negative inc shift pointer to end of data for negative indexing tid*inc ptrdiff_t shiftx = offsetx - ((incx < 0) ? ptrdiff_t(incx) * (n - 1) : 0); ptrdiff_t shifty = offsety - ((incy < 0) ? ptrdiff_t(incy) * (n - 1) : 0); int blocks = (n - 1) / NB + 1; dim3 grid(blocks, batch_count); dim3 threads(NB); hipLaunchKernelGGL((copy_kernel<T>), grid, threads, 0, handle->rocblas_stream, n, x, shiftx, incx, stridex, y, shifty, incy, stridey); return rocblas_status_success; }
2,853
839
// // Branched off piLibs (Copyright © 2015 Inigo Quilez, The MIT License), in 2015. See THIRD_PARTY_LICENSES.txt // #include <malloc.h> #include "../../libBasics/piTypes.h" #include "piBitInterlacer.h" namespace ImmCore { namespace piBitInterlacer { BitStream::BitStream() { mBits = 0; mState = 0; } bool BitStream::output(int bit, uint8_t *res) { mState |= (bit << mBits); mBits++; if (mBits == 8) { *res = mState; mBits = 0; mState = 0; return true; } return false; } bool BitStream::flush(uint8_t *val) { if (mBits != 0) { *val = mState; return true; } return false; } uint64_t interlace8(uint8_t *dst, const uint8_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits) { if (numPoints == 0) return 0; // interlace all bits, sort bits from lower to higher bits across channels uint64_t num = 0; BitStream bit; for (int b = 0; b < numBits; b++) for (int j = 0; j < numChannels; j++) for (int i = 0; i < numPoints; i++) { uint8_t res; if (bit.output((data[numChannels*i + j] >> b) & 1, &res)) dst[num++] = res; } uint8_t res; if (bit.flush(&res)) dst[num++] = res; // remove trailing zeroes uint64_t len = 0; for (int64_t i = num - 1; i >= 0; i--) { if (dst[i] != 0) { len = i + 1; break; } } return len; } uint64_t interlace16(uint8_t *dst, const uint16_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits) { if (numPoints == 0) return 0; // interlace all bits, sort bits from lower to higher bits across channels uint64_t num = 0; BitStream bit; for (int b = 0; b < numBits; b++) for (int j = 0; j < numChannels; j++) for (int i = 0; i < numPoints; i++) { uint8_t res; if (bit.output((data[numChannels*i + j] >> b) & 1, &res)) dst[num++] = res; } uint8_t res; if (bit.flush(&res)) dst[num++] = res; // remove trailing zeroes uint64_t len = 0; for (int64_t i = num - 1; i >= 0; i--) { if (dst[i] != 0) { len = i + 1; break; } } return len; } uint64_t interlace32(uint8_t *dst, const uint32_t *data, uint64_t numPoints, uint64_t numChannels, uint64_t numBits) { if (numPoints == 0) return 0; // interlace all bits, sort bits from lower to higher bits across channels uint64_t num = 0; BitStream bit; for (int b = 0; b < numBits; b++) for (int j = 0; j < numChannels; j++) for (int i = 0; i < numPoints; i++) { uint8_t res; if (bit.output((data[numChannels*i + j] >> b) & 1, &res)) dst[num++] = res; } uint8_t res; if (bit.flush(&res)) dst[num++] = res; // remove trailing zeroes uint64_t len = 0; for (int64_t i = num - 1; i >= 0; i--) { if (dst[i] != 0) { len = i + 1; break; } } return len; } void deinterlace8(const uint8_t *src, uint8_t *data, uint64_t numBytes, uint64_t numPoints, unsigned int numChannels, unsigned int numBits) { for (uint64_t i = 0, num = numPoints*numChannels; i < num; i++) { data[i] = 0; } unsigned int bit = 0; unsigned int channel = 0; uint64_t point = 0; for (uint64_t i = 0; i < numBytes; i++) { const uint8_t byte = src[i]; for (int j = 0; j < 8; j++) { const int b = (byte >> j) & 1; data[numChannels*point + channel] |= (b << bit); point++; if (point >= numPoints) { point = 0; channel++; if (channel >= numChannels) { channel = 0; bit++; if (bit >= numBits) { bit = 0; return; } } } } } } void deinterlace16(const uint8_t *src, uint16_t *data, uint64_t numBytes, uint64_t numPoints, unsigned int numChannels, unsigned int numBits) { for (uint64_t i = 0, num = numPoints*numChannels; i < num; i++) { data[i] = 0; } unsigned int bit = 0; unsigned int channel = 0; uint64_t point = 0; for (uint64_t i = 0; i < numBytes; i++) { const uint8_t byte = src[i]; for (int j = 0; j < 8; j++) { const unsigned int b = (byte >> j) & 1; data[numChannels*point + channel] |= (b << bit); point++; if (point >= numPoints) { point = 0; channel++; if (channel >= numChannels) { channel = 0; bit++; if (bit >= numBits) { bit = 0; return; } } } } } } } }
4,523
2,430
/* * 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 "window_option_impl_test.h" namespace OHOS { void WindowOptionImplTest::SetUp() { } void WindowOptionImplTest::TearDown() { } void WindowOptionImplTest::SetUpTestCase() { } void WindowOptionImplTest::TearDownTestCase() { } namespace { /* * Feature: WindowOptionImpl Getter, Setter * Function: WindowOptionImpl * SubFunction: Getter, Setter * FunctionPoints: WindowOptionImpl Getter, Setter * EnvConditions: N/A * CaseDescription: 1. Check Set and Get WindowType * 2. Check Set and Get WindowMode * 3. Check Set and Get Display * 4. Check Set and Get ConsumerSurface */ HWTEST_F(WindowOptionImplTest, Create, testing::ext::TestSize.Level0) { WindowOptionImpl woi; // 1. Check Set and Get WindowType constexpr WindowType type1 = static_cast<WindowType>(0); constexpr WindowType type2 = static_cast<WindowType>(1); woi.SetWindowType(type1); ASSERT_EQ(woi.GetWindowType(), type1) << "CaseDescription: " << "1. Check Set and Get WindowType (woi.GetWindowType() == type1)"; woi.SetWindowType(type2); ASSERT_EQ(woi.GetWindowType(), type2) << "CaseDescription: " << "1. Check Set and Get WindowType (woi.GetWindowType() == type2)"; // 2. Check Set and Get WindowMode constexpr WindowMode mode1 = static_cast<WindowMode>(0); constexpr WindowMode mode2 = static_cast<WindowMode>(1); woi.SetWindowMode(mode1); ASSERT_EQ(woi.GetWindowMode(), mode1) << "CaseDescription: " << "2. Check Set and Get WindowMode (woi.GetWindowMode() == mode1)"; woi.SetWindowMode(mode2); ASSERT_EQ(woi.GetWindowMode(), mode2) << "CaseDescription: " << "2. Check Set and Get WindowMode (woi.GetWindowMode() == mode2)"; // 3. Check Set and Get Display constexpr int32_t display1 = 1; constexpr int32_t display2 = 2; woi.SetDisplay(display1); ASSERT_EQ(woi.GetDisplay(), display1) << "CaseDescription: " << "3. Check Set and Get Display (woi.GetDisplay() == display1)"; woi.SetDisplay(display2); ASSERT_EQ(woi.GetDisplay(), display2) << "CaseDescription: " << "3. Check Set and Get Display (woi.GetY() == display2)"; // 4. Check Set and Get ConsumerSurface auto csurface1 = Surface::CreateSurfaceAsConsumer(); auto csurface2 = Surface::CreateSurfaceAsConsumer(); woi.SetConsumerSurface(csurface1); ASSERT_EQ(woi.GetConsumerSurface(), csurface1) << "CaseDescription: " << "4. Check Set and Get ConsumerSurface (woi.GetConsumerSurface() == csurface1)"; woi.SetConsumerSurface(csurface2); ASSERT_EQ(woi.GetConsumerSurface(), csurface2) << "CaseDescription: " << "4. Check Set and Get ConsumerSurface (woi.GetConsumerSurface() == csurface2)"; } /* * Feature: WindowOptionImpl Invalid Set * Function: WindowOptionImpl * SubFunction: Invalid Set * FunctionPoints: WindowOptionImpl Invalid Set * EnvConditions: N/A * CaseDescription: 1. set invalid WindowType, check * 2. set invalid WindowMode, check * 3. set invalid Display, check * 4. set invalid ConsumerSurface, check */ HWTEST_F(WindowOptionImplTest, InvalidSet, testing::ext::TestSize.Level0) { WindowOptionImpl woi; // 1. set invalid WindowType, check constexpr auto invalidWindowType = static_cast<WindowType>(-1); ASSERT_EQ(woi.SetWindowType(invalidWindowType), WM_ERROR_INVALID_PARAM) << "CaseDescription: " << "1. set invalid WindowType, check (woi.SetWindowType() == WM_ERROR_INVALID_PARAM)"; // 2. set invalid WindowMode, check constexpr auto invalidWindowMode = static_cast<WindowMode>(-1); ASSERT_EQ(woi.SetWindowMode(invalidWindowMode), WM_ERROR_INVALID_PARAM) << "CaseDescription: " << "2. set invalid WindowMode, check (woi.SetWindowMode() == WM_ERROR_INVALID_PARAM)"; // 3. set invalid display, check constexpr auto invalidDisplay = -1; ASSERT_EQ(woi.SetDisplay(invalidDisplay), WM_ERROR_INVALID_PARAM) << "CaseDescription: " << "3. set invalid display, check (woi.SetDisplay() == WM_ERROR_INVALID_PARAM)"; // 4. set invalid consumerSurface, check auto csurface = Surface::CreateSurfaceAsConsumer(); auto producer = csurface->GetProducer(); auto invalidConsumerSurface = Surface::CreateSurfaceAsProducer(producer); ASSERT_EQ(woi.SetConsumerSurface(invalidConsumerSurface), WM_ERROR_INVALID_PARAM) << "CaseDescription: " << "4. set invalid consumerSurface, check (woi.SetConsumerSurface() == WM_ERROR_INVALID_PARAM)"; } } // namespace } // namespace OHOS
5,208
1,684
#ifndef NEXMARK_FILTER_EVALUATOR_HPP #define NEXMARK_FILTER_EVALUATOR_HPP #include "core/SingleInputTransformEvaluator.h" #include "Nexmark/NexmarkFilter.hpp" /* convert a stream of records to a stream of <NexmarkRecord> records */ template <typename InputT, typename OutputT, template<class> class BundleT_> class NexmarkFilterEvaluator : public SingleInputTransformEvaluator<NexmarkFilter<InputT, OutputT>, BundleT_<InputT>, BundleT_<OutputT> > { using TransformT = NexmarkFilter<InputT, OutputT>; using InputBundleT = BundleT_<InputT>; using OutputBundleT = BundleT_<OutputT>; public: bool evaluateSingleInput (TransformT* trans, shared_ptr<InputBundleT> input_bundle, shared_ptr<OutputBundleT> output_bundle) override { for (auto && it = input_bundle->begin(); it != input_bundle->end(); ++it) { if(trans->do_map(*it)) { output_bundle->add_record(*it); } } trans->record_counter_.fetch_add(input_bundle->size(), std::memory_order_relaxed); return true; // return false; } NexmarkFilterEvaluator(int node) : SingleInputTransformEvaluator<TransformT, InputBundleT, OutputBundleT>(node) {} }; #endif //NEXMARK_FILTER_EVALUATOR_HPP
1,462
438